-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvim.ts
More file actions
750 lines (680 loc) · 25.5 KB
/
Copy pathvim.ts
File metadata and controls
750 lines (680 loc) · 25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
/*
* vim.ts - mode state machine + key dispatcher.
*/
import { afterRender, afterSelectionSync, deleteRange, extendSelection, getCaret, getLines, getText, insertLineBreak, insertText, lineColToOffset, redo, replaceRange, setCaret, undo } from "./editor";
import {
applyVisualOperator,
changeLines,
deleteCharBackward,
deleteCharForward,
handleOperatorKey,
Op,
OpPending,
opResult,
paste,
toLineEnd,
} from "./operators";
import {
findChar,
FindCmd,
moveDown,
moveFirstLine,
moveFirstNonBlank,
moveLastLine,
moveLeft,
moveLineEnd,
moveLineStart,
moveRight,
moveUp,
moveWordBackward,
moveWordEnd,
moveWordForward,
moveWORDBackward,
moveWORDEnd,
moveWORDForward,
repeatFind,
} from "./motions";
import { settings } from "./settings";
import { updateIndicator } from "./statusline";
export const enum Mode {
Normal = "NORMAL",
Insert = "INSERT",
Visual = "VISUAL",
Replace = "REPLACE",
}
export interface EditorState {
mode: Mode;
/** goal column for j/k, null when invalidated by horizontal movement */
goalCol: number | null;
/** timestamp of last Escape consumed in NORMAL mode (for double-Escape) */
lastEscape: number;
/** accumulated numeric count prefix (0 = none) */
count: number;
/** pending multi-key state: awaiting second key of gg, r's char, or operator */
pending: null | { kind: "g"; } | { kind: "r"; count: number; }
| { kind: "f"; cmd: FindCmd; count: number; } | OpPending;
/** visual mode: fixed end of the selection (absolute offset) */
visualAnchor: number;
/** visual mode: moving end of the selection (absolute offset) */
visualHead: number;
/** replace mode: original chars overwritten (null = appended past EOL) */
replaceStack: (string | null)[];
}
const DOUBLE_ESCAPE_MS = 500;
/* ------------------------------------------------------------------ */
/* `.` repeat: record the key sequence of the last buffer-changing */
/* command and replay it. */
/* ------------------------------------------------------------------ */
/** Keys in recording order for the change currently being typed. */
let recordBuffer: string[] = [];
/** Key sequence of the last completed change, for `.`. */
let lastChange: string[] | null = null;
/** True while `.` is replaying keys (suppress re-recording). */
let replaying = false;
/** True while recording insert-mode text after a change/insert command
* (vim replays the typed text on `.`). Committed on Escape. */
let recordingInsert = false;
/** recordBuffer index where the insert-mode segment starts (for
* Backspace handling while recording). */
let recordInsertStart = 0;
/** Simple normal-mode commands that count as repeatable changes. */
const CHANGE_KEYS = new Set(["x", "X", "D", "p", "P", "~", "J"]);
/** Normal-mode commands that enter INSERT mode; the typed text is part
* of the repeatable change. */
const INSERT_KEYS = new Set(["i", "a", "I", "A", "o", "O", "s", "C", "S"]);
function startInsertRecording(): void {
if (replaying) return;
recordingInsert = true;
recordInsertStart = recordBuffer.length;
}
function commitChange(): void {
if (!replaying) lastChange = recordBuffer.slice();
}
const states = new WeakMap<HTMLElement, EditorState>();
export function getState(editor: HTMLElement): EditorState {
let s = states.get(editor);
if (!s) {
s = {
mode: Mode.Insert, goalCol: null, lastEscape: 0,
count: 0, pending: null,
visualAnchor: 0, visualHead: 0,
replaceStack: [],
};
states.set(editor, s);
}
return s;
}
function setMode(editor: HTMLElement, mode: Mode): void {
const s = getState(editor);
s.mode = mode;
s.goalCol = null;
s.count = 0;
s.pending = null;
updateIndicator(editor, mode);
}
/**
* Bindings receive `count`: the numeric prefix, or undefined when none was
* typed (some commands like G distinguish "no count" from "count 1").
*/
const normalBindings: Record<string, (editor: HTMLElement, count?: number) => void> = {
h: (e, c) => moveLeft(e, c ?? 1),
l: (e, c) => moveRight(e, c ?? 1),
j: (e, c) => moveDown(e, c ?? 1),
k: (e, c) => moveUp(e, c ?? 1),
ArrowLeft: (e, c) => moveLeft(e, c ?? 1),
ArrowRight: (e, c) => moveRight(e, c ?? 1),
ArrowDown: (e, c) => moveDown(e, c ?? 1),
ArrowUp: (e, c) => moveUp(e, c ?? 1),
w: (e, c) => moveWordForward(e, c ?? 1),
b: (e, c) => moveWordBackward(e, c ?? 1),
e: (e, c) => moveWordEnd(e, c ?? 1),
W: (e, c) => moveWORDForward(e, c ?? 1),
B: (e, c) => moveWORDBackward(e, c ?? 1),
E: (e, c) => moveWORDEnd(e, c ?? 1),
0: moveLineStart,
"^": moveFirstNonBlank,
$: (e, c) => moveLineEnd(e, c ?? 1),
G: moveLastLine,
";": (e, c) => repeatFind(e, c ?? 1, false),
",": (e, c) => repeatFind(e, c ?? 1, true),
i: editor => setMode(editor, Mode.Insert),
a: appendAfter,
I: insertLineStart,
A: appendLineEnd,
o: openBelow,
O: openAbove,
x: (e, c) => deleteCharForward(e, c ?? 1, () => { }),
X: (e, c) => deleteCharBackward(e, c ?? 1),
s: (e, c) => deleteCharForward(e, c ?? 1, () => setMode(e, Mode.Insert), true),
D: e => toLineEnd(e, "d", () => { }),
C: e => toLineEnd(e, "c", () => setMode(e, Mode.Insert)),
S: (e, c) => changeLines(e, c ?? 1, () => setMode(e, Mode.Insert)),
p: (e, c) => paste(e, true, c ?? 1),
P: (e, c) => paste(e, false, c ?? 1),
v: enterVisual,
u: e => undo(e),
"~": (e, c) => toggleCase(e, c ?? 1),
J: (e, c) => joinLines(e, c ?? 1),
R: enterReplace,
};
/** True when `editor` is waiting for r's replacement char (for the
* underline cursor overlay). */
export function isReplacePending(editor: HTMLElement): boolean {
return states.get(editor)?.pending?.kind === "r";
}
/** R - enter replace (overtype) mode. */
function enterReplace(editor: HTMLElement): void {
getState(editor).replaceStack = [];
setMode(editor, Mode.Replace);
}
/** Overtype one character in REPLACE mode; caret advances. */
function replaceModeChar(editor: HTMLElement, state: EditorState, ch: string): void {
const pos = getCaret(editor);
if (!pos) return;
const lines = getLines(editor);
if (pos.col < lines[pos.line].length) {
state.replaceStack.push(lines[pos.line][pos.col]);
replaceRange(editor, pos.offset, pos.offset + 1, ch);
} else {
// past end of line: append (vim behavior)
state.replaceStack.push(null);
insertText(editor, ch, pos.offset);
}
}
/** Handle a key in REPLACE mode. Consumes everything except modifiers. */
function handleReplaceKey(editor: HTMLElement, state: EditorState, key: string): boolean {
if (key === "Shift" || key === "CapsLock") return false;
if (!replaying) recordBuffer.push(key);
if (key === "Escape") {
commitChange();
setMode(editor, Mode.Normal);
moveLeft(editor, 1);
return true;
}
if (key === "Backspace") {
const pos = getCaret(editor);
if (!pos) return true;
if (state.replaceStack.length === 0) {
// before the replace start: just move left, nothing to restore
moveLeft(editor, 1);
return true;
}
if (pos.col === 0) return true; // don't cross line boundaries
const orig = state.replaceStack.pop()!;
if (orig === null) {
// char was appended past EOL: remove it (caret lands before it)
deleteRange(editor, pos.offset - 1, pos.offset);
} else {
replaceRange(editor, pos.offset - 1, pos.offset, orig);
const target = pos.offset - 1;
afterRender(editor, () => setCaret(editor, target));
}
return true;
}
if (key.length === 1) {
replaceModeChar(editor, state, key);
return true;
}
// swallow everything else (arrows, Enter, Delete, ...) to keep the
// replace stack consistent
return true;
}
/** Motions available in visual mode (they move the selection head). */
const visualMotions: Record<string, (editor: HTMLElement, count?: number) => void> = {
h: (e, c) => moveLeft(e, c ?? 1),
l: (e, c) => moveRight(e, c ?? 1),
j: (e, c) => moveDown(e, c ?? 1),
k: (e, c) => moveUp(e, c ?? 1),
ArrowLeft: (e, c) => moveLeft(e, c ?? 1),
ArrowRight: (e, c) => moveRight(e, c ?? 1),
ArrowDown: (e, c) => moveDown(e, c ?? 1),
ArrowUp: (e, c) => moveUp(e, c ?? 1),
w: (e, c) => moveWordForward(e, c ?? 1),
b: (e, c) => moveWordBackward(e, c ?? 1),
e: (e, c) => moveWordEnd(e, c ?? 1),
W: (e, c) => moveWORDForward(e, c ?? 1),
B: (e, c) => moveWORDBackward(e, c ?? 1),
E: (e, c) => moveWORDEnd(e, c ?? 1),
0: moveLineStart,
"^": moveFirstNonBlank,
$: (e, c) => moveLineEnd(e, c ?? 1),
G: moveLastLine,
";": (e, c) => repeatFind(e, c ?? 1, false),
",": (e, c) => repeatFind(e, c ?? 1, true),
};
/** v - enter charwise visual mode, anchored at the caret. */
function enterVisual(editor: HTMLElement): void {
const pos = getCaret(editor);
if (!pos) return;
setMode(editor, Mode.Visual);
const s = getState(editor);
s.visualAnchor = pos.offset;
s.visualHead = pos.offset;
renderVisualSelection(editor, s);
}
/** Re-extend the DOM selection to cover [anchor, head] inclusively. */
function renderVisualSelection(editor: HTMLElement, s: EditorState): void {
const len = getText(editor).length;
const a = Math.min(s.visualAnchor, len);
const h = Math.min(s.visualHead, len);
if (h >= a) extendSelection(editor, a, Math.min(h + 1, len));
else extendSelection(editor, Math.min(a + 1, len), h);
}
/** Leave visual mode, collapsing the caret to the selection head. */
function exitVisual(editor: HTMLElement, s: EditorState): void {
setCaret(editor, Math.min(s.visualHead, Math.max(getText(editor).length - 1, 0)));
setMode(editor, Mode.Normal);
}
/** Handle a key in VISUAL mode. Always consumes unless stated otherwise. */
function handleVisualKey(editor: HTMLElement, state: EditorState, e: KeyboardEvent): boolean {
const key = e.key;
if (key === "Escape" || key === "v") {
exitVisual(editor, state);
return true;
}
// numeric count prefix
if (/^[0-9]$/.test(key) && !(key === "0" && state.count === 0)) {
state.count = Math.min(state.count * 10 + Number(key), 999999);
return true;
}
// pending f/F/t/T: next key is the target char
if (state.pending?.kind === "f") {
const { cmd, count } = state.pending;
state.pending = null;
state.count = 0;
if (key.length === 1) {
setCaret(editor, Math.min(state.visualHead, Math.max(getText(editor).length - 1, 0)));
findChar(editor, cmd, key, count);
const pos = getCaret(editor);
if (pos) state.visualHead = pos.offset;
renderVisualSelection(editor, state);
}
return true;
}
if (key === "f" || key === "F" || key === "t" || key === "T") {
state.pending = { kind: "f", cmd: key, count: state.count || 1 };
state.count = 0;
return true;
}
// pending g -> gg
if (state.pending?.kind === "g") {
state.pending = null;
if (key === "g") {
const count = state.count || undefined;
state.count = 0;
setCaret(editor, Math.min(state.visualHead, Math.max(getText(editor).length - 1, 0)));
moveFirstLine(editor, count);
const pos = getCaret(editor);
if (pos) state.visualHead = pos.offset;
renderVisualSelection(editor, state);
}
state.count = 0;
return true;
}
if (key === "g") {
state.pending = { kind: "g" };
return true;
}
// o - swap anchor and head
if (key === "o") {
state.count = 0;
[state.visualAnchor, state.visualHead] = [state.visualHead, state.visualAnchor];
renderVisualSelection(editor, state);
return true;
}
// operators on the selection
if (key === "d" || key === "x" || key === "c" || key === "s" || key === "y") {
const op: Op = key === "x" ? "d" : key === "s" ? "c" : key as Op;
const len = getText(editor).length;
const a = Math.min(state.visualAnchor, len);
const h = Math.min(state.visualHead, len);
const start = Math.min(a, h);
const end = Math.min(Math.max(a, h) + 1, len);
setMode(editor, Mode.Normal);
applyVisualOperator(editor, op, start, end, () => setMode(editor, Mode.Insert));
return true;
}
const motion = visualMotions[key];
if (motion) {
const count = state.count || undefined;
state.count = 0;
// collapse to the head so motions read the right caret position,
// move, then re-extend the selection from the anchor
setCaret(editor, Math.min(state.visualHead, Math.max(getText(editor).length - 1, 0)));
motion(editor, count);
const pos = getCaret(editor);
if (pos) state.visualHead = pos.offset;
renderVisualSelection(editor, state);
return true;
}
state.count = 0;
// block printable/editing keys from modifying the box
if (key.length === 1) return true;
if (key === "Backspace" || key === "Delete") return true;
if (key === "Enter") return e.shiftKey;
return false;
}
/** r<char> - replace count characters under the caret with `ch`. */
function replaceChars(editor: HTMLElement, ch: string, count: number): void {
const pos = getCaret(editor);
if (!pos) return;
const lines = getLines(editor);
// vim: r fails when there aren't enough characters on the line
if (pos.col + count > lines[pos.line].length) return;
replaceRange(editor, pos.offset, pos.offset + count, ch.repeat(count));
const target = pos.offset + count - 1;
afterRender(editor, () => setCaret(editor, target));
}
/** ~ - toggle case of count characters, moving the caret right. */
function toggleCase(editor: HTMLElement, count: number): void {
const pos = getCaret(editor);
if (!pos) return;
const lines = getLines(editor);
const lineEnd = pos.offset - pos.col + lines[pos.line].length;
const end = Math.min(pos.offset + count, lineEnd);
if (end <= pos.offset) return;
const text = getText(editor).slice(pos.offset, end);
const toggled = Array.from(text, c => {
const lower = c.toLowerCase();
return c === lower ? c.toUpperCase() : lower;
}).join("");
replaceRange(editor, pos.offset, end, toggled);
const target = Math.min(end, Math.max(lineEnd - 1, pos.offset - pos.col));
afterRender(editor, () => setCaret(editor, target));
}
/** J - join count lines (min 2) with a single space, vim-style. */
function joinLines(editor: HTMLElement, count: number): void {
const pos = getCaret(editor);
if (!pos) return;
const lines = getLines(editor);
const last = Math.min(pos.line + Math.max(count, 2) - 1, lines.length - 1);
if (last === pos.line) return;
let joined = lines[pos.line];
const caretCol = joined.length; // caret lands at the first join point
for (let i = pos.line + 1; i <= last; i++) {
const next = lines[i].replace(/^\s+/, "");
joined = joined.replace(/\s+$/, "");
joined = next ? joined + " " + next : joined;
}
const lineStart = pos.offset - pos.col;
replaceRange(editor, lineStart, lineColToOffset(lines, last, lines[last].length), joined);
const target = lineStart + Math.min(caretCol, Math.max(joined.length - 1, 0));
afterRender(editor, () => setCaret(editor, target));
}
/** a - enter insert mode one character to the right. */
function appendAfter(editor: HTMLElement): void {
const pos = getCaret(editor);
if (pos) {
const lines = getLines(editor);
if (pos.col < lines[pos.line].length) setCaret(editor, pos.offset + 1);
}
setMode(editor, Mode.Insert);
}
/** I - enter insert mode at the first non-blank character of the line. */
function insertLineStart(editor: HTMLElement): void {
moveFirstNonBlank(editor);
setMode(editor, Mode.Insert);
}
/** A - enter insert mode at the end of the line. */
function appendLineEnd(editor: HTMLElement): void {
const pos = getCaret(editor);
if (pos) {
const lines = getLines(editor);
setCaret(editor, lineColToOffset(lines, pos.line, lines[pos.line].length));
}
setMode(editor, Mode.Insert);
}
/** o - open a new line below the current one and enter insert mode. */
function openBelow(editor: HTMLElement): void {
const pos = getCaret(editor);
if (!pos) {
setMode(editor, Mode.Insert);
return;
}
const lines = getLines(editor);
setCaret(editor, lineColToOffset(lines, pos.line, lines[pos.line].length));
afterSelectionSync(() => {
insertLineBreak(editor);
// caret ends up on the new (empty) line after the break
setMode(editor, Mode.Insert);
});
}
/** O - open a new line above the current one and enter insert mode. */
function openAbove(editor: HTMLElement): void {
const pos = getCaret(editor);
if (!pos) {
setMode(editor, Mode.Insert);
return;
}
setCaret(editor, lineColToOffset(getLines(editor), pos.line, 0));
afterSelectionSync(() => {
insertLineBreak(editor);
// caret is now at the start of the pushed-down original line;
// move it up onto the new empty line above.
setCaret(editor, lineColToOffset(getLines(editor), pos.line, 0));
setMode(editor, Mode.Insert);
});
}
/**
* Handle a keydown aimed at a slate editor.
* Returns true if the event was consumed (caller should preventDefault +
* stopImmediatePropagation).
*/
export function handleKey(editor: HTMLElement, e: KeyboardEvent): boolean {
const state = getState(editor);
updateIndicator(editor, state.mode);
if (state.mode === Mode.Insert) {
if (e.key === "Escape" && !e.ctrlKey && !e.altKey && !e.metaKey) {
if (!replaying && recordingInsert) {
recordBuffer.push("Escape");
commitChange();
}
recordingInsert = false;
setMode(editor, Mode.Normal);
// vim moves the caret one left when leaving insert mode
moveLeft(editor, 1);
return true; // swallow so Discord doesn't clear reply state
}
// record typed text so `.` can replay the whole change
if (!replaying && recordingInsert && !e.ctrlKey && !e.altKey && !e.metaKey) {
if (e.key.length === 1) recordBuffer.push(e.key);
else if (e.key === "Backspace" && recordBuffer.length > recordInsertStart) {
recordBuffer.pop();
}
}
return false;
}
if (state.mode === Mode.Replace) {
if (e.ctrlKey || e.altKey || e.metaKey) return false;
return handleReplaceKey(editor, state, e.key);
}
// Ctrl-R -> redo in NORMAL mode (consumed so Discord doesn't refresh)
if (state.mode === Mode.Normal && e.ctrlKey && !e.altKey && !e.metaKey && e.key === "r") {
redo(editor);
return true;
}
if (e.ctrlKey || e.altKey || e.metaKey) return false;
// ignore bare modifier presses so they don't clear pending state
if (e.key === "Shift" || e.key === "CapsLock") return false;
if (state.mode === Mode.Visual) return handleVisualKey(editor, state, e);
// NORMAL mode
if (e.key === "Escape") {
if (state.pending || state.count) {
state.pending = null;
state.count = 0;
return true;
}
switch (settings.store.escapeInNormal) {
case "passthrough":
return false;
case "double": {
const now = Date.now();
if (now - state.lastEscape <= DOUBLE_ESCAPE_MS) {
state.lastEscape = 0;
return false; // second escape passes through
}
state.lastEscape = now;
return true;
}
default: // "swallow"
return true;
}
}
return handleNormalKey(editor, state, e.key, e.shiftKey);
}
/** Handle a single NORMAL-mode key (also used by `.` replay). */
function handleNormalKey(editor: HTMLElement, state: EditorState, key: string, shiftKey: boolean): boolean {
// record keys for `.`: a fresh command starts when nothing is pending
if (!replaying) {
if (!state.pending && state.count === 0) {
recordBuffer = [key];
recordingInsert = false;
} else {
recordBuffer.push(key);
}
}
// r-pending: the next printable key replaces characters
if (state.pending?.kind === "r") {
const rCount = state.pending.count;
state.pending = null;
if (key.length === 1) {
replaceChars(editor, key, rCount);
commitChange();
}
return true;
}
// f/F/t/T-pending: the next printable key is the search char
if (state.pending?.kind === "f") {
const { cmd, count } = state.pending;
state.pending = null;
if (key.length === 1) findChar(editor, cmd, key, count);
return true;
}
// operator-pending: feed everything to the operator handler
if (state.pending?.kind === "op") {
const wasChange = state.pending.op === "c";
opResult.applied = false;
state.pending = handleOperatorKey(
editor, state.pending, key,
() => setMode(editor, Mode.Insert)
);
if (!state.pending && opResult.applied) {
// c enters insert mode: keep recording the typed text and
// commit on Escape instead
if (wasChange) startInsertRecording();
else commitChange();
}
return true;
}
// pending multi-key sequences (gg)
if (state.pending) {
state.pending = null;
if (key === "g") {
const count = state.count || undefined;
state.count = 0;
moveFirstLine(editor, count);
}
return true; // swallow unknown g-sequences too
}
// numeric count prefix (0 is a motion unless a count is in progress)
if (/^[0-9]$/.test(key) && !(key === "0" && state.count === 0)) {
state.count = Math.min(state.count * 10 + Number(key), 999999);
return true;
}
const count = state.count || undefined;
if (key === "g") {
state.pending = { kind: "g" };
return true;
}
if (key === "f" || key === "F" || key === "t" || key === "T") {
state.pending = { kind: "f", cmd: key, count: state.count || 1 };
state.count = 0;
return true;
}
if (key === "r") {
state.pending = { kind: "r", count: state.count || 1 };
state.count = 0;
// show the REPLACE indicator while waiting for the char; the next
// keydown re-syncs the badge to the real mode (top of handleKey)
updateIndicator(editor, Mode.Replace);
return true;
}
if (key === ".") {
state.count = 0;
if (!replaying && lastChange) {
replaying = true;
replayKeys(editor, state, lastChange, 0);
}
return true;
}
if (key === "d" || key === "c" || key === "y") {
state.pending = {
kind: "op", op: key as Op,
count: state.count, motionCount: 0,
};
state.count = 0;
return true;
}
const binding = normalBindings[key];
if (binding) {
state.count = 0;
binding(editor, count);
if (INSERT_KEYS.has(key)) startInsertRecording();
else if (CHANGE_KEYS.has(key)) commitChange();
return true;
}
state.count = 0;
// Block printable keys and editing keys from modifying the box.
if (key.length === 1) return true;
if (key === "Backspace" || key === "Delete") return true;
// Enter sends the message (allowed); Shift+Enter would insert a newline.
if (key === "Enter") return shiftKey;
// Let non-printable keys (Enter, Tab, Escape, ...) through.
return false;
}
/**
* Replay recorded keys for `.`, one per macrotask: mode changes triggered
* by operators (c entering insert) happen in afterSelectionSync/afterRender
* callbacks, so each replayed key must wait for the previous one's async
* effects to settle.
*/
function replayKeys(editor: HTMLElement, state: EditorState, keys: string[], i: number): void {
if (i >= keys.length) {
replaying = false;
return;
}
const k = keys[i];
if (state.mode === Mode.Replace) {
handleReplaceKey(editor, state, k);
} else if (state.mode === Mode.Insert) {
if (k === "Escape") {
setMode(editor, Mode.Normal);
moveLeft(editor, 1);
} else if (k.length === 1) {
insertText(editor, k);
}
} else {
handleNormalKey(editor, state, k, false);
}
setTimeout(() => replayKeys(editor, state, keys, i + 1), 0);
}
export function resetOnFocus(editor: HTMLElement): void {
const s = getState(editor);
switch (settings.store.defaultMode) {
case "normal":
setMode(editor, Mode.Normal);
return;
case "remember":
// keep whatever mode the editor was left in, but never resume
// visual/replace (their transient state is gone)
if (s.mode === Mode.Visual || s.mode === Mode.Replace) {
setMode(editor, Mode.Normal);
return;
}
break;
default: // "insert"
setMode(editor, Mode.Insert);
return;
}
updateIndicator(editor, s.mode);
}