@jadelclemens/pi-vim 0.0.0-stage → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1141 @@
1
+ /**
2
+ * Normal mode handler.
3
+ * Implements vim motions, operators, text objects, mode switching, count prefixes, and pending key states.
4
+ */
5
+
6
+ import type { VimState } from "../state.js";
7
+ import { resetOperatorState } from "../state.js";
8
+ import { isDigit, ESCAPE_SEQS } from "../keys.js";
9
+ import {
10
+ wordForward,
11
+ wordBackward,
12
+ wordEnd,
13
+ WORDForward,
14
+ WORDBackward,
15
+ WORDEnd,
16
+ goToFirstLine,
17
+ goToLastLine,
18
+ firstNonBlank,
19
+ lineStart,
20
+ lineEnd,
21
+ findCharForward,
22
+ findCharBackward,
23
+ tillCharForward,
24
+ tillCharBackward,
25
+ repeatCharSearch,
26
+ reverseCharSearch,
27
+ paragraphBackward,
28
+ paragraphForward,
29
+ matchingBracket,
30
+ type MotionFn,
31
+ type MotionResult,
32
+ } from "../motions.js";
33
+ import {
34
+ motionToRange,
35
+ textObjectToRange,
36
+ applyOperator,
37
+ type OperatorRange,
38
+ } from "../operators.js";
39
+ import { resolveTextObject } from "../text-objects.js";
40
+ import { getRegister, isValidRegister } from "../registers.js";
41
+ import {
42
+ startRecording,
43
+ recordKey,
44
+ markInsertEntry,
45
+ finalizeRecording,
46
+ getLastChange,
47
+ isCurrentlyRecording,
48
+ } from "../repeat.js";
49
+ import { resetReplaceState } from "./replace.js";
50
+ import {
51
+ beginSearch,
52
+ searchNext,
53
+ searchPrev,
54
+ searchWordUnderCursor,
55
+ } from "../search.js";
56
+
57
+ export interface NormalModeContext {
58
+ state: VimState;
59
+ superHandleInput: (data: string) => void;
60
+ getText: () => string;
61
+ getCursor: () => { line: number; col: number };
62
+ setText: (text: string) => void;
63
+ moveCursorTo: (line: number, col: number) => void;
64
+ undo: () => void;
65
+ redo: () => void;
66
+ }
67
+
68
+ /**
69
+ * Execute a motion and move the cursor to the result.
70
+ * If an operator is pending, apply the operator to the motion range instead.
71
+ */
72
+ function executeMotion(
73
+ motion: MotionFn,
74
+ ctx: NormalModeContext,
75
+ count: number,
76
+ ): void {
77
+ const lines = ctx.getText().split("\n");
78
+ const cursor = ctx.getCursor();
79
+ const result = motion(lines, cursor, count);
80
+
81
+ if (ctx.state.pendingOperator) {
82
+ applyOperatorWithMotion(ctx, lines, cursor, result);
83
+ } else {
84
+ ctx.moveCursorTo(result.position.line, result.position.col);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Apply a pending operator using a motion result.
90
+ */
91
+ function applyOperatorWithMotion(
92
+ ctx: NormalModeContext,
93
+ lines: string[],
94
+ cursor: { line: number; col: number },
95
+ motionResult: MotionResult,
96
+ ): void {
97
+ const range = motionToRange(cursor, motionResult);
98
+ applyOperatorToRange(ctx, lines, range);
99
+ }
100
+
101
+ /** Execute w/W, including Vim's operator-specific word-motion rules. */
102
+ function executeWordForward(
103
+ motion: MotionFn,
104
+ endMotion: MotionFn,
105
+ ctx: NormalModeContext,
106
+ count: number,
107
+ ): void {
108
+ const lines = ctx.getText().split("\n");
109
+ const cursor = ctx.getCursor();
110
+ const operator = ctx.state.pendingOperator;
111
+ const currentChar = (lines[cursor.line] || "")[cursor.col] || "";
112
+
113
+ // `cw`/`cW` behave like `ce`/`cE` when not started in whitespace.
114
+ let result = operator === "c" && !/[ \t]/.test(currentChar)
115
+ ? endMotion(lines, cursor, count)
116
+ : motion(lines, cursor, count);
117
+
118
+ // A single `dw`/`dW` on the last word of a line does not consume the
119
+ // newline. Larger counts really do cross the line boundary.
120
+ if (
121
+ operator === "d" &&
122
+ count === 1 &&
123
+ result.position.line > cursor.line &&
124
+ /\S/.test((lines[cursor.line] || "").slice(cursor.col))
125
+ ) {
126
+ result = {
127
+ position: {
128
+ line: cursor.line,
129
+ col: Math.max(0, (lines[cursor.line] || "").length - 1),
130
+ },
131
+ linewise: false,
132
+ inclusive: true,
133
+ };
134
+ }
135
+
136
+ if (operator) applyOperatorWithMotion(ctx, lines, cursor, result);
137
+ else ctx.moveCursorTo(result.position.line, result.position.col);
138
+ }
139
+
140
+ /**
141
+ * Apply a pending operator to a given range.
142
+ */
143
+ function applyOperatorToRange(
144
+ ctx: NormalModeContext,
145
+ lines: string[],
146
+ range: OperatorRange,
147
+ ): void {
148
+ const operator = ctx.state.pendingOperator!;
149
+ const register = ctx.state.register;
150
+
151
+ const result = applyOperator(operator, lines, range, register);
152
+
153
+ ctx.setText(result.newLines.join("\n"));
154
+ ctx.moveCursorTo(result.cursor.line, result.cursor.col);
155
+
156
+ if (result.enterInsert) {
157
+ ctx.state.mode = "insert";
158
+ // Mark insert entry for dot-repeat (e.g., `cw` enters insert)
159
+ if (isCurrentlyRecording()) {
160
+ markInsertEntry();
161
+ }
162
+ } else {
163
+ // Operator completed without entering insert — finalize recording
164
+ finalizeChangeRecording(ctx.state);
165
+ }
166
+
167
+ resetOperatorState(ctx.state);
168
+ }
169
+
170
+ /**
171
+ * Apply a linewise operator for doubled operators (dd, cc, yy, >>, <<).
172
+ */
173
+ function applyLinewiseOperator(
174
+ ctx: NormalModeContext,
175
+ operator: string,
176
+ count: number,
177
+ ): void {
178
+ const lines = ctx.getText().split("\n");
179
+ const cursor = ctx.getCursor();
180
+ const endLine = Math.min(cursor.line + count - 1, lines.length - 1);
181
+
182
+ const range: OperatorRange = {
183
+ start: { line: cursor.line, col: 0 },
184
+ end: { line: endLine, col: (lines[endLine] || "").length },
185
+ linewise: true,
186
+ inclusive: true,
187
+ };
188
+
189
+ const register = ctx.state.register;
190
+ const result = applyOperator(operator, lines, range, register);
191
+
192
+ ctx.setText(result.newLines.join("\n"));
193
+ ctx.moveCursorTo(result.cursor.line, result.cursor.col);
194
+
195
+ if (result.enterInsert) {
196
+ ctx.state.mode = "insert";
197
+ if (isCurrentlyRecording()) {
198
+ markInsertEntry();
199
+ }
200
+ } else {
201
+ finalizeChangeRecording(ctx.state);
202
+ }
203
+
204
+ resetOperatorState(ctx.state);
205
+ }
206
+
207
+ /**
208
+ * Handle input in normal mode.
209
+ * Returns true if the key was handled.
210
+ */
211
+ export function handleNormalMode(data: string, ctx: NormalModeContext): boolean {
212
+ const { state } = ctx;
213
+
214
+ // --- Pending register selection (after `"`) ---
215
+ if (state.pendingRegister) {
216
+ state.pendingRegister = false;
217
+ if (data.length === 1 && isValidRegister(data)) {
218
+ state.register = data;
219
+ // Record for dot-repeat
220
+ if (isCurrentlyRecording()) {
221
+ recordKey('"');
222
+ recordKey(data);
223
+ }
224
+ } else {
225
+ // Invalid register, cancel
226
+ resetOperatorState(state);
227
+ state.register = '"';
228
+ }
229
+ return true;
230
+ }
231
+
232
+ // --- Pending text object key (after 'i' or 'a' in operator-pending mode) ---
233
+ if (state.pendingTextObjectPrefix) {
234
+ const prefix = state.pendingTextObjectPrefix;
235
+ state.pendingTextObjectPrefix = null;
236
+
237
+ const textObjFn = resolveTextObject(prefix, data);
238
+ if (textObjFn) {
239
+ const lines = ctx.getText().split("\n");
240
+ const cursor = ctx.getCursor();
241
+ const range = textObjFn(lines, cursor);
242
+
243
+ if (range) {
244
+ if (state.pendingOperator) {
245
+ // Record the text object key for dot-repeat
246
+ if (isCurrentlyRecording()) {
247
+ recordKey(prefix);
248
+ recordKey(data);
249
+ }
250
+ applyOperatorToRange(ctx, lines, textObjectToRange(range));
251
+ } else {
252
+ // Text objects without operator don't do anything in normal mode
253
+ resetOperatorState(state);
254
+ }
255
+ } else {
256
+ resetOperatorState(state);
257
+ }
258
+ } else {
259
+ resetOperatorState(state);
260
+ }
261
+ return true;
262
+ }
263
+
264
+ // --- Pending character input for f/F/t/T/r ---
265
+ if (state.pendingCharMotion) {
266
+ const pending = state.pendingCharMotion;
267
+ state.pendingCharMotion = null;
268
+
269
+ // Only accept single printable characters
270
+ if (data.length === 1 && data.charCodeAt(0) >= 32) {
271
+ const count = state.count || 1;
272
+ let motionFn: MotionFn;
273
+
274
+ switch (pending) {
275
+ case "f":
276
+ motionFn = findCharForward(data);
277
+ break;
278
+ case "F":
279
+ motionFn = findCharBackward(data);
280
+ break;
281
+ case "t":
282
+ motionFn = tillCharForward(data);
283
+ break;
284
+ case "T":
285
+ motionFn = tillCharBackward(data);
286
+ break;
287
+ case "r":
288
+ // Replace character under cursor (only without pending operator)
289
+ if (!state.pendingOperator) {
290
+ beginChangeRecording(state, `r${data}`, count);
291
+ replaceChar(data, ctx, count);
292
+ finalizeChangeRecording(state);
293
+ }
294
+ resetOperatorState(state);
295
+ return true;
296
+ default:
297
+ resetOperatorState(state);
298
+ return true;
299
+ }
300
+
301
+ // Record char motion key for dot-repeat
302
+ if (isCurrentlyRecording()) {
303
+ recordKey(pending);
304
+ recordKey(data);
305
+ }
306
+ executeMotion(motionFn, ctx, count);
307
+ if (!state.pendingOperator) {
308
+ resetOperatorState(state);
309
+ }
310
+ return true;
311
+ }
312
+
313
+ // Non-printable cancels the pending motion
314
+ resetOperatorState(state);
315
+ return true;
316
+ }
317
+
318
+ // --- Pending `g` prefix ---
319
+ if (state.pendingG) {
320
+ state.pendingG = false;
321
+
322
+ if (data === "g") {
323
+ // `gg` - go to first line (or line N)
324
+ const count = state.count || 1;
325
+ const countExplicit = state.countStarted;
326
+ if (isCurrentlyRecording()) {
327
+ recordKey("g");
328
+ recordKey("g");
329
+ }
330
+ executeMotion(goToFirstLine, ctx, countExplicit ? count : 1);
331
+ if (!state.pendingOperator) {
332
+ resetOperatorState(state);
333
+ }
334
+ return true;
335
+ }
336
+
337
+ // Unrecognized g-command, cancel
338
+ resetOperatorState(state);
339
+ return true;
340
+ }
341
+
342
+ // Count prefix handling: 1-9 start a count, 0 continues if already started
343
+ if (isDigit(data) && (data !== "0" || state.countStarted)) {
344
+ state.count = Math.min(state.count * 10 + parseInt(data, 10), 99999);
345
+ state.countStarted = true;
346
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
347
+ return true;
348
+ }
349
+
350
+ const count = state.count || 1;
351
+ const countExplicit = state.countStarted;
352
+
353
+ // --- Register selection prefix (`"`) ---
354
+ if (data === '"') {
355
+ state.pendingRegister = true;
356
+ return true;
357
+ }
358
+
359
+ // --- Dot-repeat (`.`) ---
360
+ if (data === ".") {
361
+ replayLastChange(ctx, countExplicit ? count : 0);
362
+ resetOperatorState(state);
363
+ return true;
364
+ }
365
+
366
+ // --- Operators ---
367
+ if (data === "d" || data === "c" || data === "y" || data === ">" || data === "<") {
368
+ if (state.pendingOperator === data) {
369
+ // Doubled operator (dd, cc, yy, >>, <<) → linewise on current line(s)
370
+ // Recording was already started when the first operator key was pressed
371
+ if (isCurrentlyRecording()) {
372
+ recordKey(data);
373
+ }
374
+ applyLinewiseOperator(ctx, data, state.pendingOperatorCount * count);
375
+ return true;
376
+ }
377
+ if (state.pendingOperator) {
378
+ // Different operator while one is pending → cancel
379
+ resetOperatorState(state);
380
+ return true;
381
+ }
382
+ // Set pending operator — recording starts but we wait for the motion key
383
+ // Don't record yank (y) — it's not a change
384
+ if (data !== "y" && !state.isReplaying && !isCurrentlyRecording()) {
385
+ startRecording();
386
+ // Record count digits if any
387
+ if (countExplicit) {
388
+ for (const digit of String(count)) recordKey(digit);
389
+ }
390
+ recordKey(data);
391
+ }
392
+ state.pendingOperator = data;
393
+ state.pendingOperatorCount = count;
394
+ // The motion has its own count. Vim multiplies it by the operator count:
395
+ // `2d3w` is six words, not twenty-three.
396
+ state.count = 0;
397
+ state.countStarted = false;
398
+ return true;
399
+ }
400
+
401
+ // --- Shortcut operators (D, C, Y) ---
402
+ if (data === "D") {
403
+ // D = d$ (delete to end of line)
404
+ beginChangeRecording(state, "D", count);
405
+ state.pendingOperator = "d";
406
+ executeMotion(lineEnd, ctx, 1);
407
+ finalizeChangeRecording(state);
408
+ return true;
409
+ }
410
+
411
+ if (data === "C") {
412
+ // C = c$ (change to end of line)
413
+ beginChangeRecording(state, "C", count);
414
+ state.pendingOperator = "c";
415
+ executeMotion(lineEnd, ctx, 1);
416
+ // Don't finalize — enters insert mode, finalized on Escape
417
+ return true;
418
+ }
419
+
420
+ if (data === "Y") {
421
+ // Y = yy (yank whole line) — yank is not a "change" (no dot-repeat)
422
+ applyLinewiseOperator(ctx, "y", count);
423
+ return true;
424
+ }
425
+
426
+ // --- Paste commands ---
427
+ if (data === "p" || data === "P") {
428
+ beginChangeRecording(state, data, count);
429
+ const reg = getRegister(state.register);
430
+ if (reg) {
431
+ paste(ctx, reg.text, reg.linewise, data === "P");
432
+ }
433
+ finalizeChangeRecording(state);
434
+ resetOperatorState(state);
435
+ return true;
436
+ }
437
+
438
+ // --- Text object prefixes (only valid in operator-pending mode) ---
439
+ if ((data === "i" || data === "a") && state.pendingOperator) {
440
+ state.pendingTextObjectPrefix = data;
441
+ return true;
442
+ }
443
+
444
+ const motionCount = state.pendingOperator
445
+ ? state.pendingOperatorCount * count
446
+ : count;
447
+
448
+ switch (data) {
449
+ // === Basic directional motions ===
450
+ case "h":
451
+ if (state.pendingOperator) {
452
+ if (isCurrentlyRecording()) recordKey(data);
453
+ executeMotionForOperator("h", ctx, motionCount);
454
+ } else {
455
+ for (let i = 0; i < count && ctx.getCursor().col > 0; i++) {
456
+ ctx.superHandleInput(ESCAPE_SEQS.left);
457
+ }
458
+ resetOperatorState(state);
459
+ }
460
+ return true;
461
+
462
+ case "j":
463
+ if (state.pendingOperator) {
464
+ if (isCurrentlyRecording()) recordKey(data);
465
+ // j with operator is linewise
466
+ const lines = ctx.getText().split("\n");
467
+ const cursor = ctx.getCursor();
468
+ const endLine = Math.min(cursor.line + motionCount, lines.length - 1);
469
+ const range: OperatorRange = {
470
+ start: { line: cursor.line, col: 0 },
471
+ end: { line: endLine, col: (lines[endLine] || "").length },
472
+ linewise: true,
473
+ inclusive: true,
474
+ };
475
+ applyOperatorToRange(ctx, lines, range);
476
+ } else {
477
+ for (let i = 0; i < count; i++) ctx.superHandleInput(ESCAPE_SEQS.down);
478
+ resetOperatorState(state);
479
+ }
480
+ return true;
481
+
482
+ case "k":
483
+ if (state.pendingOperator) {
484
+ if (isCurrentlyRecording()) recordKey(data);
485
+ // k with operator is linewise
486
+ const lines = ctx.getText().split("\n");
487
+ const cursor = ctx.getCursor();
488
+ const startLine = Math.max(cursor.line - motionCount, 0);
489
+ const range: OperatorRange = {
490
+ start: { line: startLine, col: 0 },
491
+ end: { line: cursor.line, col: (lines[cursor.line] || "").length },
492
+ linewise: true,
493
+ inclusive: true,
494
+ };
495
+ applyOperatorToRange(ctx, lines, range);
496
+ } else {
497
+ for (let i = 0; i < count; i++) ctx.superHandleInput(ESCAPE_SEQS.up);
498
+ resetOperatorState(state);
499
+ }
500
+ return true;
501
+
502
+ case "l":
503
+ if (state.pendingOperator) {
504
+ if (isCurrentlyRecording()) recordKey(data);
505
+ executeMotionForOperator("l", ctx, count);
506
+ } else {
507
+ for (let i = 0; i < count; i++) {
508
+ const cursor = ctx.getCursor();
509
+ const line = ctx.getText().split("\n")[cursor.line] || "";
510
+ const segments = [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(line)];
511
+ if (cursor.col >= (segments.at(-1)?.index ?? 0)) break;
512
+ ctx.superHandleInput(ESCAPE_SEQS.right);
513
+ }
514
+ resetOperatorState(state);
515
+ }
516
+ return true;
517
+
518
+ // === Line motions ===
519
+ case "0":
520
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
521
+ executeMotion(lineStart, ctx, 1);
522
+ if (!state.pendingOperator) resetOperatorState(state);
523
+ return true;
524
+
525
+ case "$":
526
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
527
+ executeMotion(lineEnd, ctx, count);
528
+ if (!state.pendingOperator) resetOperatorState(state);
529
+ return true;
530
+
531
+ case "^":
532
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
533
+ executeMotion(firstNonBlank, ctx, 1);
534
+ if (!state.pendingOperator) resetOperatorState(state);
535
+ return true;
536
+
537
+ // === Word motions ===
538
+ case "w":
539
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
540
+ executeWordForward(wordForward, wordEnd, ctx, motionCount);
541
+ if (!state.pendingOperator) resetOperatorState(state);
542
+ return true;
543
+
544
+ case "b":
545
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
546
+ executeMotion(wordBackward, ctx, motionCount);
547
+ if (!state.pendingOperator) resetOperatorState(state);
548
+ return true;
549
+
550
+ case "e":
551
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
552
+ executeMotion(wordEnd, ctx, motionCount);
553
+ if (!state.pendingOperator) resetOperatorState(state);
554
+ return true;
555
+
556
+ case "W":
557
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
558
+ executeWordForward(WORDForward, WORDEnd, ctx, motionCount);
559
+ if (!state.pendingOperator) resetOperatorState(state);
560
+ return true;
561
+
562
+ case "B":
563
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
564
+ executeMotion(WORDBackward, ctx, motionCount);
565
+ if (!state.pendingOperator) resetOperatorState(state);
566
+ return true;
567
+
568
+ case "E":
569
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
570
+ executeMotion(WORDEnd, ctx, motionCount);
571
+ if (!state.pendingOperator) resetOperatorState(state);
572
+ return true;
573
+
574
+ // === Find/Till character motions ===
575
+ case "f":
576
+ case "F":
577
+ case "t":
578
+ case "T":
579
+ state.pendingCharMotion = data;
580
+ return true;
581
+
582
+ // === Repeat char search ===
583
+ case ";":
584
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
585
+ executeMotion(repeatCharSearch, ctx, count);
586
+ if (!state.pendingOperator) resetOperatorState(state);
587
+ return true;
588
+
589
+ case ",":
590
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
591
+ executeMotion(reverseCharSearch, ctx, count);
592
+ if (!state.pendingOperator) resetOperatorState(state);
593
+ return true;
594
+
595
+ // === Line-level motions ===
596
+ case "g":
597
+ state.pendingG = true;
598
+ return true;
599
+
600
+ case "G":
601
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
602
+ // G without count → last line, G with count → line N
603
+ if (countExplicit) {
604
+ executeMotion(goToLastLine, ctx, count);
605
+ } else {
606
+ const lines = ctx.getText().split("\n");
607
+ executeMotion(goToLastLine, ctx, lines.length);
608
+ }
609
+ if (!state.pendingOperator) resetOperatorState(state);
610
+ return true;
611
+
612
+ // === Paragraph motions ===
613
+ case "{":
614
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
615
+ executeMotion(paragraphBackward, ctx, count);
616
+ if (!state.pendingOperator) resetOperatorState(state);
617
+ return true;
618
+
619
+ case "}":
620
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
621
+ executeMotion(paragraphForward, ctx, count);
622
+ if (!state.pendingOperator) resetOperatorState(state);
623
+ return true;
624
+
625
+ // === Matching bracket ===
626
+ case "%":
627
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
628
+ executeMotion(matchingBracket, ctx, 1);
629
+ if (!state.pendingOperator) resetOperatorState(state);
630
+ return true;
631
+
632
+ // === Search motions ===
633
+ case "n":
634
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
635
+ executeMotion(searchNext, ctx, count);
636
+ if (!state.pendingOperator) resetOperatorState(state);
637
+ return true;
638
+
639
+ case "N":
640
+ if (state.pendingOperator && isCurrentlyRecording()) recordKey(data);
641
+ executeMotion(searchPrev, ctx, count);
642
+ if (!state.pendingOperator) resetOperatorState(state);
643
+ return true;
644
+
645
+ case "*": {
646
+ const lines = ctx.getText().split("\n");
647
+ const cursor = ctx.getCursor();
648
+ const result = searchWordUnderCursor(lines, cursor, "forward");
649
+ if (state.pendingOperator) {
650
+ if (isCurrentlyRecording()) recordKey(data);
651
+ applyOperatorWithMotion(ctx, lines, cursor, result);
652
+ } else {
653
+ ctx.moveCursorTo(result.position.line, result.position.col);
654
+ }
655
+ resetOperatorState(state);
656
+ return true;
657
+ }
658
+
659
+ case "#": {
660
+ const lines = ctx.getText().split("\n");
661
+ const cursor = ctx.getCursor();
662
+ const result = searchWordUnderCursor(lines, cursor, "backward");
663
+ if (state.pendingOperator) {
664
+ if (isCurrentlyRecording()) recordKey(data);
665
+ applyOperatorWithMotion(ctx, lines, cursor, result);
666
+ } else {
667
+ ctx.moveCursorTo(result.position.line, result.position.col);
668
+ }
669
+ resetOperatorState(state);
670
+ return true;
671
+ }
672
+
673
+ // === Search command-line entry ===
674
+ case "/":
675
+ beginSearch("forward", "normal");
676
+ state.mode = "command-line";
677
+ resetOperatorState(state);
678
+ return true;
679
+
680
+ case "?":
681
+ beginSearch("backward", "normal");
682
+ state.mode = "command-line";
683
+ resetOperatorState(state);
684
+ return true;
685
+
686
+ // === Insert mode entry ===
687
+ case "i":
688
+ beginChangeRecording(state, "i", count);
689
+ markInsertEntry();
690
+ state.mode = "insert";
691
+ resetOperatorState(state);
692
+ return true;
693
+
694
+ case "a":
695
+ beginChangeRecording(state, "a", count);
696
+ markInsertEntry();
697
+ state.mode = "insert";
698
+ {
699
+ const cursor = ctx.getCursor();
700
+ const line = ctx.getText().split("\n")[cursor.line] || "";
701
+ if (cursor.col < line.length) ctx.superHandleInput(ESCAPE_SEQS.right);
702
+ }
703
+ resetOperatorState(state);
704
+ return true;
705
+
706
+ case "I": {
707
+ beginChangeRecording(state, "I", count);
708
+ markInsertEntry();
709
+ // Insert at first non-whitespace
710
+ const lines = ctx.getText().split("\n");
711
+ const cursor = ctx.getCursor();
712
+ const line = lines[cursor.line] || "";
713
+ const match = line.match(/^\s*/);
714
+ const targetCol = match ? match[0].length : 0;
715
+ ctx.moveCursorTo(cursor.line, targetCol);
716
+ state.mode = "insert";
717
+ resetOperatorState(state);
718
+ return true;
719
+ }
720
+
721
+ case "A":
722
+ beginChangeRecording(state, "A", count);
723
+ markInsertEntry();
724
+ ctx.superHandleInput(ESCAPE_SEQS.end);
725
+ state.mode = "insert";
726
+ resetOperatorState(state);
727
+ return true;
728
+
729
+ case "o": {
730
+ beginChangeRecording(state, "o", count);
731
+ markInsertEntry();
732
+ // Open line below
733
+ const lines = ctx.getText().split("\n");
734
+ const cursor = ctx.getCursor();
735
+ lines.splice(cursor.line + 1, 0, "");
736
+ ctx.setText(lines.join("\n"));
737
+ ctx.moveCursorTo(cursor.line + 1, 0);
738
+ state.mode = "insert";
739
+ resetOperatorState(state);
740
+ return true;
741
+ }
742
+
743
+ case "O": {
744
+ beginChangeRecording(state, "O", count);
745
+ markInsertEntry();
746
+ // Split at the start of the current line instead of replacing the whole
747
+ // buffer and walking back from EOF. The latter fails when wrapped screen
748
+ // rows do not correspond one-to-one with logical lines.
749
+ const lines = ctx.getText().split("\n");
750
+ const cursor = ctx.getCursor();
751
+ const indent = (lines[cursor.line] || "").match(/^[ \t]*/)?.[0] || "";
752
+ ctx.superHandleInput(ESCAPE_SEQS.home);
753
+ ctx.superHandleInput(ESCAPE_SEQS.newline);
754
+ ctx.superHandleInput(ESCAPE_SEQS.up);
755
+ if (indent) ctx.superHandleInput(indent);
756
+ state.openLineRepeatCount = count;
757
+ state.mode = "insert";
758
+ resetOperatorState(state);
759
+ return true;
760
+ }
761
+
762
+ // === Visual mode entry ===
763
+ case "v": {
764
+ state.mode = "visual";
765
+ const cursor = ctx.getCursor();
766
+ state.visualAnchor = { line: cursor.line, col: cursor.col };
767
+ resetOperatorState(state);
768
+ return true;
769
+ }
770
+
771
+ case "V": {
772
+ state.mode = "visual-line";
773
+ const cursor = ctx.getCursor();
774
+ state.visualAnchor = { line: cursor.line, col: cursor.col };
775
+ resetOperatorState(state);
776
+ return true;
777
+ }
778
+
779
+ // === Basic editing ===
780
+ case "x": {
781
+ beginChangeRecording(state, "x", count);
782
+ // x = dl (delete char under cursor)
783
+ for (let i = 0; i < count; i++) {
784
+ ctx.superHandleInput(ESCAPE_SEQS.delete);
785
+ }
786
+ finalizeChangeRecording(state);
787
+ resetOperatorState(state);
788
+ return true;
789
+ }
790
+
791
+ case "X": {
792
+ beginChangeRecording(state, "X", count);
793
+ for (let i = 0; i < count; i++) {
794
+ ctx.superHandleInput(ESCAPE_SEQS.backspace);
795
+ }
796
+ finalizeChangeRecording(state);
797
+ resetOperatorState(state);
798
+ return true;
799
+ }
800
+
801
+ case "r":
802
+ // Replace character - wait for next char
803
+ state.pendingCharMotion = "r";
804
+ return true;
805
+
806
+ case "R":
807
+ // Enter replace mode (overtype)
808
+ beginChangeRecording(state, "R", count);
809
+ markInsertEntry();
810
+ resetReplaceState();
811
+ state.mode = "replace";
812
+ resetOperatorState(state);
813
+ return true;
814
+
815
+ // === Undo / Redo ===
816
+ case "u":
817
+ // Undo
818
+ ctx.undo();
819
+ resetOperatorState(state);
820
+ return true;
821
+
822
+ case "\x12":
823
+ // Ctrl+r (redo)
824
+ ctx.redo();
825
+ resetOperatorState(state);
826
+ return true;
827
+
828
+ // === Join lines ===
829
+ case "J": {
830
+ beginChangeRecording(state, "J", count);
831
+ const lines = ctx.getText().split("\n");
832
+ const cursor = ctx.getCursor();
833
+ const joinCount = Math.min(count, lines.length - cursor.line - 1);
834
+
835
+ if (joinCount > 0) {
836
+ for (let i = 0; i < joinCount; i++) {
837
+ const lineIdx = cursor.line;
838
+ if (lineIdx + 1 < lines.length) {
839
+ const currentLine = lines[lineIdx]!;
840
+ const nextLine = (lines[lineIdx + 1] || "").replace(/^\s+/, "");
841
+ const joinCol = currentLine.length;
842
+ lines[lineIdx] = currentLine + (nextLine.length > 0 ? " " + nextLine : "");
843
+ lines.splice(lineIdx + 1, 1);
844
+ }
845
+ }
846
+ const joinCol = (lines[cursor.line] || "").length;
847
+ ctx.setText(lines.join("\n"));
848
+ // Place cursor at the join point
849
+ const finalLine = lines[cursor.line] || "";
850
+ ctx.moveCursorTo(cursor.line, Math.min(joinCol, Math.max(0, finalLine.length - 1)));
851
+ }
852
+ finalizeChangeRecording(state);
853
+ resetOperatorState(state);
854
+ return true;
855
+ }
856
+
857
+ // === Toggle case ===
858
+ case "~": {
859
+ beginChangeRecording(state, "~", count);
860
+ const lines = ctx.getText().split("\n");
861
+ const cursor = ctx.getCursor();
862
+ const line = lines[cursor.line] || "";
863
+
864
+ if (cursor.col < line.length) {
865
+ const end = Math.min(cursor.col + count, line.length);
866
+ let toggled = "";
867
+ for (let i = cursor.col; i < end; i++) {
868
+ const ch = line[i]!;
869
+ toggled += ch === ch.toLowerCase() ? ch.toUpperCase() : ch.toLowerCase();
870
+ }
871
+ lines[cursor.line] = line.substring(0, cursor.col) + toggled + line.substring(end);
872
+ ctx.setText(lines.join("\n"));
873
+ ctx.moveCursorTo(cursor.line, Math.min(end, Math.max(0, (lines[cursor.line] || "").length - 1)));
874
+ }
875
+ finalizeChangeRecording(state);
876
+ resetOperatorState(state);
877
+ return true;
878
+ }
879
+
880
+ default:
881
+ break;
882
+ }
883
+
884
+ // If we have a pending operator and got an unrecognized key, cancel
885
+ if (state.pendingOperator) {
886
+ resetOperatorState(state);
887
+ return true;
888
+ }
889
+
890
+ // If we have an unrecognized key, reset count and pass control sequences through
891
+ resetOperatorState(state);
892
+
893
+ // Pass control sequences to super for app keybindings (ctrl+d, etc.)
894
+ if (data.length === 1 && data.charCodeAt(0) < 32) {
895
+ ctx.superHandleInput(data);
896
+ return true;
897
+ }
898
+
899
+ // Pass escape sequences through
900
+ if (data.length > 1 && data.startsWith("\x1b")) {
901
+ ctx.superHandleInput(data);
902
+ return true;
903
+ }
904
+
905
+ // Ignore unrecognized printable characters in normal mode
906
+ return true;
907
+ }
908
+
909
+ /**
910
+ * Execute a simple h/l motion for operator-pending mode.
911
+ */
912
+ function executeMotionForOperator(
913
+ key: string,
914
+ ctx: NormalModeContext,
915
+ count: number,
916
+ ): void {
917
+ const lines = ctx.getText().split("\n");
918
+ const cursor = ctx.getCursor();
919
+ const line = lines[cursor.line] || "";
920
+
921
+ let targetCol: number;
922
+ if (key === "h") {
923
+ targetCol = Math.max(0, cursor.col - count);
924
+ } else {
925
+ // l
926
+ targetCol = Math.min(line.length - 1, cursor.col + count);
927
+ }
928
+
929
+ const motionResult: MotionResult = {
930
+ position: { line: cursor.line, col: targetCol },
931
+ linewise: false,
932
+ inclusive: key === "l",
933
+ };
934
+
935
+ applyOperatorWithMotion(ctx, lines, cursor, motionResult);
936
+ }
937
+
938
+ /**
939
+ * Begin recording a change for dot-repeat, unless already recording or replaying.
940
+ */
941
+ function beginChangeRecording(state: VimState, key: string, count: number): void {
942
+ if (state.isReplaying) return;
943
+ if (isCurrentlyRecording()) return;
944
+ startRecording();
945
+ if (count > 1) {
946
+ recordKey(String(count));
947
+ }
948
+ // For compound keys like "r{char}", record all chars
949
+ for (const ch of key) {
950
+ recordKey(ch);
951
+ }
952
+ }
953
+
954
+ /**
955
+ * Finalize recording if we're recording and not replaying.
956
+ */
957
+ function finalizeChangeRecording(state: VimState): void {
958
+ if (state.isReplaying) return;
959
+ if (isCurrentlyRecording()) {
960
+ finalizeRecording();
961
+ }
962
+ }
963
+
964
+ /**
965
+ * Replay the last recorded change (dot-repeat).
966
+ * If countOverride > 0, use it instead of the recorded count.
967
+ */
968
+ function replayLastChange(ctx: NormalModeContext, countOverride: number): void {
969
+ const change = getLastChange();
970
+ if (!change) return;
971
+
972
+ const { state } = ctx;
973
+ state.isReplaying = true;
974
+
975
+ try {
976
+ // Replay the normal-mode keys
977
+ for (const key of change.keys) {
978
+ // If this is a count and we have an override, skip the recorded count
979
+ // (The count is embedded in the keys as a string number)
980
+ handleNormalMode(key, ctx);
981
+ }
982
+
983
+ // If the change entered insert or replace mode, type the recorded text then escape
984
+ if (change.enteredInsert && (state.mode === "insert" || state.mode === "replace")) {
985
+ const wasReplace = state.mode === "replace";
986
+ if (wasReplace) {
987
+ // In replace mode, we need to overtype characters
988
+ const lines = ctx.getText().split("\n");
989
+ const cursor = ctx.getCursor();
990
+ let line = lines[cursor.line] || "";
991
+ let col = cursor.col;
992
+
993
+ for (const ch of change.insertedText) {
994
+ if (ch === "\n") {
995
+ // Split line at cursor for newline
996
+ const before = line.substring(0, col);
997
+ const after = line.substring(col);
998
+ lines[cursor.line] = before;
999
+ lines.splice(cursor.line + 1, 0, after);
1000
+ cursor.line++;
1001
+ col = 0;
1002
+ line = lines[cursor.line] || "";
1003
+ } else if (col < line.length) {
1004
+ // Overtype
1005
+ line = line.substring(0, col) + ch + line.substring(col + 1);
1006
+ lines[cursor.line] = line;
1007
+ col++;
1008
+ } else {
1009
+ // Append at end
1010
+ line = line + ch;
1011
+ lines[cursor.line] = line;
1012
+ col++;
1013
+ }
1014
+ }
1015
+ ctx.setText(lines.join("\n"));
1016
+ ctx.moveCursorTo(cursor.line, Math.max(0, col - 1));
1017
+ } else {
1018
+ for (const ch of change.insertedText) {
1019
+ if (ch === "\n") {
1020
+ ctx.superHandleInput("\n");
1021
+ } else {
1022
+ ctx.superHandleInput(ch);
1023
+ }
1024
+ }
1025
+ }
1026
+ // Exit insert/replace mode
1027
+ state.mode = "normal";
1028
+ if (!wasReplace && ctx.getCursor().col > 0) {
1029
+ ctx.superHandleInput("\x1b[D"); // left
1030
+ }
1031
+ }
1032
+ } finally {
1033
+ state.isReplaying = false;
1034
+ }
1035
+ }
1036
+
1037
+ /**
1038
+ * Replace character under cursor with given char, repeated `count` times.
1039
+ */
1040
+ function replaceChar(
1041
+ char: string,
1042
+ ctx: NormalModeContext,
1043
+ count: number,
1044
+ ): void {
1045
+ const lines = ctx.getText().split("\n");
1046
+ const cursor = ctx.getCursor();
1047
+ const line = lines[cursor.line] || "";
1048
+
1049
+ // Replace `count` characters starting at cursor
1050
+ const end = Math.min(cursor.col + count, line.length);
1051
+ if (cursor.col >= line.length) return;
1052
+
1053
+ const newLine =
1054
+ line.substring(0, cursor.col) +
1055
+ char.repeat(end - cursor.col) +
1056
+ line.substring(end);
1057
+ lines[cursor.line] = newLine;
1058
+ ctx.setText(lines.join("\n"));
1059
+ // Cursor stays at the last replaced character (or cursor.col if count=1)
1060
+ ctx.moveCursorTo(cursor.line, end - 1);
1061
+ }
1062
+
1063
+ /**
1064
+ * Paste text from register.
1065
+ */
1066
+ function paste(
1067
+ ctx: NormalModeContext,
1068
+ text: string,
1069
+ linewise: boolean,
1070
+ before: boolean,
1071
+ ): void {
1072
+ const lines = ctx.getText().split("\n");
1073
+ const cursor = ctx.getCursor();
1074
+
1075
+ if (linewise) {
1076
+ const pasteLines = text.split("\n");
1077
+ if (before) {
1078
+ // P: paste above current line
1079
+ lines.splice(cursor.line, 0, ...pasteLines);
1080
+ ctx.setText(lines.join("\n"));
1081
+ const targetLineText = lines[cursor.line] || "";
1082
+ const match = targetLineText.match(/^\s*/);
1083
+ ctx.moveCursorTo(cursor.line, match ? match[0].length : 0);
1084
+ } else {
1085
+ // p: paste below current line
1086
+ lines.splice(cursor.line + 1, 0, ...pasteLines);
1087
+ ctx.setText(lines.join("\n"));
1088
+ const targetLine = cursor.line + 1;
1089
+ const targetLineText = lines[targetLine] || "";
1090
+ const match = targetLineText.match(/^\s*/);
1091
+ ctx.moveCursorTo(targetLine, match ? match[0].length : 0);
1092
+ }
1093
+ } else {
1094
+ // Character-wise paste
1095
+ const line = lines[cursor.line] || "";
1096
+ if (before) {
1097
+ // P: paste before cursor
1098
+ const newLine = line.substring(0, cursor.col) + text + line.substring(cursor.col);
1099
+ lines[cursor.line] = newLine;
1100
+ ctx.setText(lines.join("\n"));
1101
+
1102
+ if (text.includes("\n")) {
1103
+ // Multi-line paste: cursor goes to start of pasted text
1104
+ ctx.moveCursorTo(cursor.line, cursor.col);
1105
+ } else {
1106
+ // Single line: cursor goes to last pasted character
1107
+ ctx.moveCursorTo(cursor.line, cursor.col + text.length - 1);
1108
+ }
1109
+ } else {
1110
+ // p: paste after cursor
1111
+ const insertCol = Math.min(cursor.col + 1, line.length);
1112
+ const pasteLines = text.split("\n");
1113
+
1114
+ if (pasteLines.length === 1) {
1115
+ const newLine = line.substring(0, insertCol) + text + line.substring(insertCol);
1116
+ lines[cursor.line] = newLine;
1117
+ ctx.setText(lines.join("\n"));
1118
+ ctx.moveCursorTo(cursor.line, insertCol + text.length - 1);
1119
+ } else {
1120
+ // Multi-line character-wise paste
1121
+ const before = line.substring(0, insertCol);
1122
+ const after = line.substring(insertCol);
1123
+ const firstPasteLine = before + pasteLines[0];
1124
+ const lastPasteLine = pasteLines[pasteLines.length - 1] + after;
1125
+
1126
+ const newLines = [
1127
+ firstPasteLine,
1128
+ ...pasteLines.slice(1, -1),
1129
+ lastPasteLine,
1130
+ ];
1131
+ lines.splice(cursor.line, 1, ...newLines);
1132
+ ctx.setText(lines.join("\n"));
1133
+
1134
+ // Cursor at end of pasted text
1135
+ const lastPasteLineIdx = cursor.line + pasteLines.length - 1;
1136
+ const lastPasteCol = (pasteLines[pasteLines.length - 1] || "").length - 1;
1137
+ ctx.moveCursorTo(lastPasteLineIdx, Math.max(0, lastPasteCol));
1138
+ }
1139
+ }
1140
+ }
1141
+ }