-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
1829 lines (1659 loc) · 56.9 KB
/
index.ts
File metadata and controls
1829 lines (1659 loc) · 56.9 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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { execFileSync } from "node:child_process";
import { copyToClipboard, CustomEditor, type ExtensionAPI, type ExtensionContext } from "@mariozechner/pi-coding-agent";
import { Key, matchesKey, truncateToWidth, visibleWidth } from "@mariozechner/pi-tui";
type Mode = "normal" | "insert" | "replace" | "visual" | "visual-line";
type Pending = "d" | "c" | "y" | "f" | "F" | "t" | "T" | "r" | undefined;
type LastFind = { char: string; forward: boolean; till: boolean } | undefined;
type Cursor = { line: number; col: number };
type CustomEditorArgs = ConstructorParameters<typeof CustomEditor>;
type InternalEditor = {
state: {
cursorLine: number;
lines?: string[];
cursorCol?: number;
};
setCursorCol(col: number): void;
onChange?: (text: string) => void;
preferredVisualCol?: number | null;
historyIndex?: number;
lastAction?: string | null;
paddingX?: number;
scrollOffset?: number;
borderColor?: (text: string) => string;
layoutText?: (contentWidth: number) => Array<{ text: string; hasCursor: boolean; cursorPos?: number }>;
};
type EditorSnapshot = {
text: string;
cursor: Cursor;
};
type ReplaceSessionEdit = {
start: number;
inserted: string;
original: string;
};
const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
function sanitizeStatusText(text: string): string {
return text
.replace(/[\r\n\t]/g, " ")
.replace(/ +/g, " ")
.trim();
}
function formatTokens(count: number): string {
if (count < 1000) return count.toString();
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
if (count < 1000000) return `${Math.round(count / 1000)}k`;
if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;
return `${Math.round(count / 1000000)}M`;
}
function isWord(char: string | undefined): boolean {
return !!char && /[A-Za-z0-9_]/.test(char);
}
function runClipboardCommand(command: string, args: readonly string[]): string | undefined {
try {
return execFileSync(command, args, {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
timeout: 2000,
}).replace(/\r\n/g, "\n");
} catch {
return undefined;
}
}
function readSystemClipboardText(): string | undefined {
if (process.platform === "darwin") return runClipboardCommand("pbpaste", []);
if (process.platform === "win32") {
return runClipboardCommand("powershell", ["-NoProfile", "-Command", "Get-Clipboard -Raw"]);
}
if (process.env.TERMUX_VERSION) {
const text = runClipboardCommand("termux-clipboard-get", []);
if (text !== undefined) return text;
}
for (const [command, args] of [
["wl-paste", ["-n"]],
["xclip", ["-selection", "clipboard", "-o"]],
["xsel", ["--clipboard", "--output"]],
] as const) {
const text = runClipboardCommand(command, args);
if (text !== undefined) return text;
}
return undefined;
}
function isBigWord(char: string | undefined): boolean {
return !!char && !/\s/.test(char);
}
function lineStart(text: string, offset: number): number {
if (offset <= 0) return 0;
const bounded = Math.min(offset, text.length);
const index = text.lastIndexOf("\n", bounded - 1);
return index === -1 ? 0 : index + 1;
}
function lineEnd(text: string, offset: number): number {
const bounded = Math.min(Math.max(offset, 0), text.length);
const index = text.indexOf("\n", bounded);
return index === -1 ? text.length : index;
}
function lineLast(text: string, offset: number): number {
const start = lineStart(text, offset);
const end = lineEnd(text, offset);
return end > start ? end - 1 : start;
}
function prevLineStart(text: string, offset: number): number | undefined {
const start = lineStart(text, offset);
if (start === 0) return undefined;
return lineStart(text, start - 1);
}
function nextLineStart(text: string, offset: number): number | undefined {
const end = lineEnd(text, offset);
if (end >= text.length) return undefined;
return end + 1;
}
function moveUp(text: string, offset: number): number {
const currentStart = lineStart(text, offset);
const targetStart = prevLineStart(text, offset);
if (targetStart === undefined) return offset;
const targetLast = lineLast(text, targetStart);
const col = offset - currentStart;
return Math.min(targetStart + col, targetLast);
}
function moveDown(text: string, offset: number): number {
const currentStart = lineStart(text, offset);
const targetStart = nextLineStart(text, offset);
if (targetStart === undefined) return offset;
const targetLast = lineLast(text, targetStart);
const col = offset - currentStart;
return Math.min(targetStart + col, targetLast);
}
function nextWordStart(text: string, offset: number, big: boolean): number {
const match = big ? isBigWord : isWord;
let pos = offset;
if (pos < text.length && match(text[pos])) {
while (pos < text.length && match(text[pos])) pos++;
}
while (pos < text.length && !match(text[pos])) pos++;
return pos;
}
function prevWordStart(text: string, offset: number, big: boolean): number {
const match = big ? isBigWord : isWord;
let pos = offset;
while (pos > 0 && !match(text[pos - 1])) pos--;
while (pos > 0 && match(text[pos - 1])) pos--;
return pos;
}
function wordEnd(text: string, offset: number, big: boolean): number {
if (text.length === 0) return 0;
const match = big ? isBigWord : isWord;
let pos = offset;
if (pos >= text.length) pos = text.length - 1;
if (match(text[pos]) && (pos + 1 >= text.length || !match(text[pos + 1]))) {
pos++;
}
while (pos < text.length && !match(text[pos])) pos++;
if (pos >= text.length) return text.length - 1;
while (pos + 1 < text.length && match(text[pos + 1])) pos++;
return pos;
}
function firstNonWhitespace(text: string, offset: number): number {
const start = lineStart(text, offset);
const end = lineEnd(text, offset);
let pos = start;
while (pos < end && /\s/.test(text[pos] ?? "")) pos++;
return pos;
}
function isBlankLine(text: string, offset: number): boolean {
const start = lineStart(text, offset);
const end = lineEnd(text, offset);
return /^\s*$/.test(text.slice(start, end));
}
function paragraphForward(text: string, offset: number): number {
let pos = lineEnd(text, offset);
while (pos < text.length) {
pos += 1;
if (pos >= text.length) return lineStart(text, text.length);
if (!isBlankLine(text, pos) && (pos === 0 || isBlankLine(text, pos - 1))) return pos;
pos = lineEnd(text, pos);
}
return offset;
}
function paragraphBackward(text: string, offset: number): number {
let pos = lineStart(text, offset);
while (pos > 0) {
pos = lineStart(text, pos - 1);
if (!isBlankLine(text, pos) && (pos === 0 || isBlankLine(text, pos - 1))) return pos;
}
return 0;
}
function totalLength(lines: string[]): number {
if (lines.length === 0) return 0;
return lines.reduce((sum, line) => sum + line.length, 0) + lines.length - 1;
}
function cursorToOffset(lines: string[], cursor: Cursor): number {
let offset = 0;
for (let i = 0; i < cursor.line; i++) {
offset += (lines[i] ?? "").length + 1;
}
return offset + cursor.col;
}
function offsetToCursor(lines: string[], offset: number): Cursor {
const boundedOffset = clamp(offset, 0, totalLength(lines));
let remaining = boundedOffset;
for (let line = 0; line < lines.length; line++) {
const current = lines[line] ?? "";
if (remaining <= current.length) {
return { line, col: remaining };
}
remaining -= current.length;
if (line < lines.length - 1) remaining -= 1;
}
const lastLine = Math.max(0, lines.length - 1);
return { line: lastLine, col: (lines[lastLine] ?? "").length };
}
function nextGraphemeOffset(text: string, offset: number): number {
if (offset >= text.length) return offset;
for (const segment of graphemeSegmenter.segment(text.slice(offset))) {
return offset + segment.segment.length;
}
return Math.min(offset + 1, text.length);
}
function prevGraphemeOffset(text: string, offset: number): number {
if (offset <= 0) return 0;
let previous = 0;
for (const segment of graphemeSegmenter.segment(text.slice(0, offset))) {
previous = segment.index;
}
return previous;
}
function replaceRange(text: string, start: number, end: number, replacement = ""): string {
return text.slice(0, start) + replacement + text.slice(end);
}
class VimModeEditor extends CustomEditor {
private mode: Mode = "insert";
private pending: Pending;
private pendingTextObject?: "i" | "a";
private pendingFindOp?: { op: "d" | "c" | "y"; motion: "f" | "F" | "t" | "T"; count: number };
private visualAnchor?: number;
private flashRange?: { start: number; end: number; linewise: boolean };
private flashTimer?: ReturnType<typeof setTimeout>;
private count = "";
private pendingG = false;
private lastFind: LastFind;
private readonly redoStack: EditorSnapshot[] = [];
private readonly replaceSessionEdits: ReplaceSessionEdit[] = [];
private unnamedRegister = "";
private unnamedRegisterType: "char" | "line" = "char";
constructor(
tui: CustomEditorArgs[0],
theme: CustomEditorArgs[1],
keybindings: CustomEditorArgs[2],
private onStatusChange: (mode: Mode, pending: string) => void,
private onYank: (text: string) => void,
private getClipboardText: () => string | undefined,
) {
super(tui, theme, keybindings);
this.emitStatus();
setTimeout(() => this.updateCursorStyle(), 0);
}
private get editor(): InternalEditor {
return this as unknown as InternalEditor;
}
private getPendingDisplay(): string {
const count = this.count;
if (this.pendingFindOp) return `${this.pendingFindOp.op}${count}${this.pendingFindOp.motion}`;
if (this.pendingTextObject && this.pending) return `${this.pending}${count}${this.pendingTextObject}`;
if (this.pending) return `${this.pending}${count}`;
if (this.pendingG) return `g${count}`;
if (count) return count;
return "";
}
private matchesAction(data: string, action: string): boolean {
return (this as unknown as { keybindings: { matches(data: string, action: string): boolean } }).keybindings.matches(data, action);
}
private writeCursorShape(sequence: string): void {
try {
process.stdout.write(sequence);
} catch {}
try {
this.tui.terminal.write(sequence);
} catch {}
}
private resetTerminalCursor(): void {
(this.tui as unknown as { setShowHardwareCursor(enabled: boolean): void }).setShowHardwareCursor(false);
this.writeCursorShape("\x1b[2 q");
}
private updateCursorStyle(): void {
const textEntry = this.mode === "insert" || this.mode === "replace";
const sequence = this.mode === "replace" ? "\x1b[3 q" : textEntry ? "\x1b[5 q" : "\x1b[2 q";
(this.tui as unknown as { setShowHardwareCursor(enabled: boolean): void }).setShowHardwareCursor(textEntry);
this.writeCursorShape(sequence);
setTimeout(() => this.writeCursorShape(sequence), 0);
}
private emitStatus(): void {
this.onStatusChange(this.mode, this.getPendingDisplay());
this.updateCursorStyle();
this.tui.requestRender();
}
private clearPending(): void {
this.pending = undefined;
this.pendingTextObject = undefined;
this.pendingFindOp = undefined;
this.pendingG = false;
this.count = "";
this.emitStatus();
}
private getVisualRange(): { start: number; end: number; linewise: boolean } | undefined {
if (this.visualAnchor === undefined) return undefined;
const current = this.getCurrentOffset();
if (this.mode === "visual-line") {
const start = Math.min(lineStart(this.getCurrentText(), this.visualAnchor), lineStart(this.getCurrentText(), current));
const end = Math.max(lineEnd(this.getCurrentText(), this.visualAnchor), lineEnd(this.getCurrentText(), current));
return { start, end: Math.min(end + 1, this.getCurrentText().length), linewise: true };
}
return {
start: Math.min(this.visualAnchor, current),
end: Math.max(this.visualAnchor, current) + 1,
linewise: false,
};
}
private takeCount(defaultCount = 1): number {
const value = this.count ? Number.parseInt(this.count, 10) : defaultCount;
this.count = "";
return Number.isFinite(value) && value > 0 ? value : defaultCount;
}
private captureSnapshot(): EditorSnapshot {
const cursor = this.getCursor();
return {
text: this.getText(),
cursor: { line: cursor.line, col: cursor.col },
};
}
private restoreSnapshot(snapshot: EditorSnapshot): void {
this.editor.state.lines = snapshot.text.split("\n");
this.editor.state.cursorLine = snapshot.cursor.line;
this.editor.setCursorCol(snapshot.cursor.col);
this.editor.preferredVisualCol = null;
this.editor.historyIndex = -1;
this.editor.lastAction = null;
this.editor.onChange?.(snapshot.text);
this.tui.requestRender();
}
private clearRedoStack(): void {
this.redoStack.length = 0;
}
private flashSelection(start: number, end: number, linewise = false): void {
if (this.flashTimer) clearTimeout(this.flashTimer);
this.flashRange = { start: Math.min(start, end), end: Math.max(start, end), linewise };
this.tui.requestRender();
this.flashTimer = setTimeout(() => {
this.flashRange = undefined;
this.flashTimer = undefined;
this.tui.requestRender();
}, 120);
}
private writeRegister(text: string, type: "char" | "line" = "char"): void {
this.unnamedRegister = text;
this.unnamedRegisterType = type;
}
private writeYank(text: string, type: "char" | "line" = "char"): void {
this.writeRegister(text, type);
this.onYank(text);
}
private readClipboardRegister(): { text: string; type: "char" | "line" } | undefined {
const text = this.getClipboardText();
if (!text) return undefined;
return {
text,
type: text === this.unnamedRegister ? this.unnamedRegisterType : "char",
};
}
private wordObjectRange(around: boolean): { start: number; end: number } | undefined {
const text = this.getCurrentText();
let start = this.getCurrentOffset();
if (!isWord(text[start])) {
if (isWord(text[start - 1])) start -= 1;
else return undefined;
}
while (start > 0 && isWord(text[start - 1])) start--;
let end = start;
while (end < text.length && isWord(text[end])) end++;
if (around) {
while (end < text.length && (text[end] === " " || text[end] === "\t")) end++;
}
return { start, end };
}
private delimitedObjectRange(char: string, around: boolean): { start: number; end: number } | undefined {
const pairs: Record<string, [string, string]> = {
'"': ['"', '"'],
"'": ["'", "'"],
"`": ["`", "`"],
"(": ["(", ")"],
")": ["(", ")"],
"[": ["[", "]"],
"]": ["[", "]"],
"{": ["{", "}"],
"}": ["{", "}"],
};
const pair = pairs[char];
if (!pair) return undefined;
const [open, close] = pair;
const text = this.getCurrentText();
if (text.length === 0) return undefined;
let offset = Math.min(this.getCurrentOffset(), text.length - 1);
if (open === close) {
const startOfLine = lineStart(text, offset);
const endOfLine = lineEnd(text, offset);
const pairs: Array<{ start: number; end: number }> = [];
let pendingQuote: number | undefined;
for (let i = startOfLine; i < endOfLine; i++) {
if (text[i] !== open || text[i - 1] === "\\") continue;
if (pendingQuote === undefined) pendingQuote = i;
else {
pairs.push({ start: pendingQuote, end: i });
pendingQuote = undefined;
}
}
if (pairs.length === 0) return undefined;
const candidates = pairs.filter((pair) => offset >= pair.start && offset <= pair.end);
if (candidates.length > 0) {
const pair = candidates.reduce((best, candidate) =>
candidate.end - candidate.start < best.end - best.start ? candidate : best,
);
return around ? { start: pair.start, end: pair.end + 1 } : { start: pair.start + 1, end: pair.end };
}
let best: { start: number; end: number; distance: number } | undefined;
for (const pair of pairs) {
const innerStart = pair.start + 1;
const innerEnd = pair.end;
const distance = offset < innerStart ? innerStart - offset : offset > innerEnd ? offset - innerEnd : 0;
if (!best || distance < best.distance || (distance === best.distance && pair.start > best.start)) {
best = { start: pair.start, end: pair.end, distance };
}
}
if (!best) return undefined;
return around ? { start: best.start, end: best.end + 1 } : { start: best.start + 1, end: best.end };
}
const candidates: Array<{ start: number; end: number }> = [];
for (let start = 0; start < text.length; start++) {
if (text[start] !== open) continue;
let depth = 0;
for (let end = start + 1; end < text.length; end++) {
if (text[end] === open) depth++;
else if (text[end] === close) {
if (depth === 0) {
if (offset >= start && offset <= end) candidates.push({ start, end });
break;
}
depth--;
}
}
}
if (candidates.length === 0) return undefined;
const match = candidates.reduce((best, candidate) => {
if (!best) return candidate;
return candidate.end - candidate.start < best.end - best.start ? candidate : best;
}, undefined as { start: number; end: number } | undefined);
if (!match) return undefined;
return around ? { start: match.start, end: match.end + 1 } : { start: match.start + 1, end: match.end };
}
private setMode(mode: Mode): void {
if (this.mode === mode) return;
this.mode = mode;
if (mode !== "replace") this.replaceSessionEdits.length = 0;
if (mode !== "visual" && mode !== "visual-line") this.visualAnchor = undefined;
this.emitStatus();
this.tui.requestRender();
}
private getCurrentText(): string {
return this.getText();
}
private getCurrentOffset(): number {
return cursorToOffset(this.getLines(), this.getCursor());
}
private setCursor(line: number, col: number): void {
this.editor.state.cursorLine = line;
this.editor.setCursorCol(col);
this.tui.requestRender();
}
private moveToOffset(offset: number): void {
const cursor = offsetToCursor(this.getLines(), offset);
this.setCursor(cursor.line, cursor.col);
}
private enterVisual(linewise: boolean): void {
this.clearPending();
this.visualAnchor = this.getCurrentOffset();
this.setMode(linewise ? "visual-line" : "visual");
}
private exitVisual(): void {
const range = this.getVisualRange();
this.setMode("normal");
if (range) this.moveToOffset(range.start);
}
private applyVisual(action: "delete" | "change" | "yank" | "put"): void {
const range = this.getVisualRange();
if (!range) {
this.setMode("normal");
return;
}
const text = this.getCurrentText();
const selected = text.slice(range.start, range.end);
if (action === "yank") {
this.writeYank(selected, range.linewise ? "line" : "char");
this.setMode("normal");
this.moveToOffset(range.start);
return;
}
if (action === "put") {
const register = this.readClipboardRegister();
if (!register) {
this.setMode("normal");
return;
}
this.edit(() => ({
text: replaceRange(text, range.start, range.end, register.text),
cursorOffset: Math.max(range.start, range.start + register.text.length - 1),
}));
this.setMode("normal");
return;
}
this.edit(() => ({
text: replaceRange(text, range.start, range.end),
cursorOffset: range.start,
}));
this.setMode(action === "change" ? "insert" : "normal");
}
private normalizeCursorForNormalMode(): void {
const cursor = this.getCursor();
const line = this.getLines()[cursor.line] ?? "";
if (line.length === 0) {
this.setCursor(cursor.line, 0);
return;
}
if (cursor.col > 0) {
this.setCursor(cursor.line, Math.min(cursor.col - 1, line.length - 1));
return;
}
this.setCursor(cursor.line, 0);
}
private edit(transform: (text: string, offset: number) => { text: string; cursorOffset: number } | undefined): boolean {
const text = this.getCurrentText();
const offset = this.getCurrentOffset();
const next = transform(text, offset);
if (!next) return false;
if (next.text === text && next.cursorOffset === offset) return false;
this.clearRedoStack();
this.setText(next.text);
const cursor = offsetToCursor(this.getLines(), next.cursorOffset);
this.setCursor(cursor.line, cursor.col);
return true;
}
private enterInsert(): void {
this.clearPending();
this.setMode("insert");
}
private enterReplace(): void {
this.clearPending();
this.replaceSessionEdits.length = 0;
this.setMode("replace");
}
private appendAfterCursor(): void {
const text = this.getCurrentText();
const offset = this.getCurrentOffset();
this.moveToOffset(Math.min(offset + 1, lineEnd(text, offset)));
this.enterInsert();
}
private insertLineStart(): void {
const text = this.getCurrentText();
const offset = this.getCurrentOffset();
this.moveToOffset(firstNonWhitespace(text, offset));
this.enterInsert();
}
private appendLineEnd(): void {
const text = this.getCurrentText();
const offset = this.getCurrentOffset();
this.moveToOffset(lineEnd(text, offset));
this.enterInsert();
}
private openLineBelow(): void {
this.clearPending();
this.edit((text, offset) => {
const at = lineEnd(text, offset);
return {
text: `${text.slice(0, at)}\n${text.slice(at)}`,
cursorOffset: at + 1,
};
});
this.setMode("insert");
}
private openLineAbove(): void {
this.clearPending();
this.edit((text, offset) => {
const at = lineStart(text, offset);
return {
text: `${text.slice(0, at)}\n${text.slice(at)}`,
cursorOffset: at,
};
});
this.setMode("insert");
}
private moveWord(direction: "next" | "prev" | "end", big: boolean, count = 1): void {
this.moveToOffset(this.wordMotionTarget(direction, big, count));
}
private moveLeft(count = 1): void {
let offset = this.getCurrentOffset();
const text = this.getCurrentText();
for (let i = 0; i < count; i++) {
offset = Math.max(lineStart(text, offset), prevGraphemeOffset(text, offset));
}
this.moveToOffset(offset);
}
private moveRight(count = 1): void {
let offset = this.getCurrentOffset();
const text = this.getCurrentText();
for (let i = 0; i < count; i++) {
offset = Math.min(lineLast(text, offset), nextGraphemeOffset(text, offset));
}
this.moveToOffset(offset);
}
private moveUp(count = 1): void {
let offset = this.getCurrentOffset();
for (let i = 0; i < count; i++) {
offset = moveUp(this.getCurrentText(), offset);
}
this.moveToOffset(offset);
}
private moveDown(count = 1): void {
let offset = this.getCurrentOffset();
for (let i = 0; i < count; i++) {
offset = moveDown(this.getCurrentText(), offset);
}
this.moveToOffset(offset);
}
private moveLineStart(): void {
this.moveToOffset(lineStart(this.getCurrentText(), this.getCurrentOffset()));
}
private moveLineFirstNonWhitespace(count = 1): void {
if (count > 1) this.moveDown(count - 1);
this.moveToOffset(firstNonWhitespace(this.getCurrentText(), this.getCurrentOffset()));
}
private moveToLine(lineNumber: number): void {
const lines = this.getLines();
const lineIndex = clamp(lineNumber - 1, 0, Math.max(0, lines.length - 1));
const col = Math.min(this.getCursor().col, Math.max(0, (lines[lineIndex] ?? "").length - 1));
this.setCursor(lineIndex, Math.max(0, col));
}
private moveParagraph(forward: boolean, count = 1): void {
let offset = this.getCurrentOffset();
for (let i = 0; i < count; i++) {
offset = forward ? paragraphForward(this.getCurrentText(), offset) : paragraphBackward(this.getCurrentText(), offset);
}
this.moveToOffset(offset);
}
private moveLineEnd(): void {
this.moveToOffset(lineLast(this.getCurrentText(), this.getCurrentOffset()));
}
private replaceUnderCursor(char: string, count = 1): void {
this.clearPending();
this.edit((text, offset) => {
if (offset >= lineEnd(text, offset)) return undefined;
let end = offset;
for (let i = 0; i < count; i++) {
end = nextGraphemeOffset(text, end);
if (end > lineEnd(text, offset)) {
end = lineEnd(text, offset);
break;
}
}
return {
text: replaceRange(text, offset, end, char.repeat(Math.max(1, count))),
cursorOffset: offset,
};
});
}
private deleteBackwardChar(): boolean {
const lastReplace = this.replaceSessionEdits[this.replaceSessionEdits.length - 1];
if (this.mode === "replace" && lastReplace) {
const restored = this.edit((text, offset) => {
const end = lastReplace.start + lastReplace.inserted.length;
if (offset !== end) return undefined;
this.replaceSessionEdits.pop();
return {
text: replaceRange(text, lastReplace.start, end, lastReplace.original),
cursorOffset: lastReplace.start,
};
});
if (restored) return true;
}
return this.edit((text, offset) => {
if (offset <= 0) return undefined;
const start = prevGraphemeOffset(text, offset);
return {
text: replaceRange(text, start, offset),
cursorOffset: start,
};
});
}
private replaceModeInput(data: string): void {
if (data === "\r") {
super.handleInput(data);
return;
}
if (this.matchesAction(data, "tui.editor.deleteCharBackward") || matchesKey(data, "shift+backspace")) {
this.deleteBackwardChar();
return;
}
if (!(data.length === 1 && data.charCodeAt(0) >= 32)) {
super.handleInput(data);
return;
}
this.edit((text, offset) => {
if (offset < text.length && text[offset] !== "\n") {
const end = nextGraphemeOffset(text, offset);
this.replaceSessionEdits.push({
start: offset,
inserted: data,
original: text.slice(offset, end),
});
return {
text: replaceRange(text, offset, end, data),
cursorOffset: offset + data.length,
};
}
this.replaceSessionEdits.push({ start: offset, inserted: data, original: "" });
return {
text: replaceRange(text, offset, offset, data),
cursorOffset: offset + data.length,
};
});
}
private deleteToLineEnd(change: boolean): void {
this.clearPending();
this.edit((text, offset) => {
const end = lineEnd(text, offset);
if (offset > end) return undefined;
const deleteEnd = offset === end && end < text.length ? end + 1 : end;
if (deleteEnd <= offset) return undefined;
return {
text: replaceRange(text, offset, deleteEnd),
cursorOffset: offset,
};
});
if (change) this.setMode("insert");
}
private substituteChar(): void {
this.clearPending();
this.edit((text, offset) => {
if (offset >= lineEnd(text, offset)) return undefined;
const end = nextGraphemeOffset(text, offset);
return {
text: replaceRange(text, offset, end),
cursorOffset: offset,
};
});
this.setMode("insert");
}
private toggleCase(count = 1): void {
this.clearPending();
this.edit((text, offset) => {
if (offset >= lineEnd(text, offset)) return undefined;
let current = offset;
let result = text;
for (let i = 0; i < count; i++) {
if (current >= lineEnd(result, offset)) break;
const end = nextGraphemeOffset(result, current);
const segment = result.slice(current, end);
const toggled = segment === segment.toUpperCase() ? segment.toLowerCase() : segment.toUpperCase();
result = replaceRange(result, current, end, toggled);
current = current + toggled.length;
}
return {
text: result,
cursorOffset: Math.max(offset, current - 1),
};
});
}
private deleteUnderCursor(count = 1): void {
this.clearPending();
this.edit((text, offset) => {
if (offset >= lineEnd(text, offset)) return undefined;
let end = offset;
for (let i = 0; i < count; i++) {
end = nextGraphemeOffset(text, end);
if (end > lineEnd(text, offset)) {
end = lineEnd(text, offset);
break;
}
}
return {
text: replaceRange(text, offset, end),
cursorOffset: offset,
};
});
}
private applyRange(start: number, end: number, change = false, yank = false): void {
this.clearPending();
const from = Math.min(start, end);
const to = Math.max(start, end);
if (to <= from) return;
const text = this.getCurrentText();
const selected = text.slice(from, to);
if (yank) this.writeYank(selected, "char");
if (yank) {
this.flashSelection(from, to, false);
this.moveToOffset(start <= end ? from : Math.max(from, to - 1));
return;
}
this.edit(() => ({
text: replaceRange(text, from, to),
cursorOffset: from,
}));
if (change) this.setMode("insert");
}
private wordMotionTarget(direction: "next" | "prev" | "end", big: boolean, count: number, from = this.getCurrentOffset()): number {
let target = from;
for (let i = 0; i < count; i++) {
const text = this.getCurrentText();
target =
direction === "next"
? nextWordStart(text, target, big)
: direction === "prev"
? prevWordStart(text, target, big)
: wordEnd(text, target, big);
}
return target;
}
private deleteWord(change: boolean): void {
const offset = this.getCurrentOffset();
const endOffset = this.wordMotionTarget("next", false, this.takeCount(1), offset);
this.applyRange(offset, endOffset, change);
}
private deleteLine(count = 1, direction: -1 | 1 | 0 = 0): void {
this.clearPending();
this.edit((text, offset) => {
if (text.length === 0) return undefined;
const { start, end } = this.lineBlockRange(count, direction);
const nextText = replaceRange(text, start, end);
return {
text: nextText,
cursorOffset: Math.min(start, nextText.length),
};
});
}
private substituteLine(count = 1): void {
this.deleteLine(count);
this.setMode("insert");
}
private lineBlockRange(count: number, direction: -1 | 1 | 0): { start: number; end: number } {
const text = this.getCurrentText();
const offset = this.getCurrentOffset();
let start = lineStart(text, offset);
let end = lineEnd(text, offset);
if (direction >= 0) {
for (let i = 1; i < count; i++) {
if (end >= text.length) break;
end = lineEnd(text, end + 1);
}
end = Math.min(end + 1, text.length);
} else {
for (let i = 1; i < count; i++) {
if (start === 0) break;
start = lineStart(text, start - 1);
}
end = Math.min(lineEnd(text, offset) + 1, text.length);
}
return { start, end };
}
private yankLine(count = 1): void {
this.clearPending();
const { start, end } = this.lineBlockRange(count, 0);
this.writeYank(this.getCurrentText().slice(start, end), "line");
this.flashSelection(start, end, true);
}
private put(after: boolean, count = 1): void {
this.clearPending();
const register = this.readClipboardRegister();
if (!register) return;
const text = register.text.repeat(Math.max(1, count));
const linewise = register.type === "line";
this.edit((currentText, offset) => {
if (linewise) {
const currentLineEnd = lineEnd(currentText, offset);
const insertAt = after ? currentLineEnd + (currentLineEnd < currentText.length ? 1 : 0) : lineStart(currentText, offset);
const needsLeadingNewline = after && insertAt === currentText.length && currentText.length > 0 && currentText[currentText.length - 1] !== "\n";
const insertion = needsLeadingNewline ? `\n${text}` : text;
const nextText = replaceRange(currentText, insertAt, insertAt, insertion);
return { text: nextText, cursorOffset: insertAt + (needsLeadingNewline ? 1 : 0) };
}
const insertAt = after ? Math.min(nextGraphemeOffset(currentText, offset), currentText.length) : offset;
const nextText = replaceRange(currentText, insertAt, insertAt, text);
return {
text: nextText,
cursorOffset: Math.max(insertAt, insertAt + text.length - 1),
};
});