forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCursor.ts
More file actions
1530 lines (1306 loc) · 45.6 KB
/
Cursor.ts
File metadata and controls
1530 lines (1306 loc) · 45.6 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 { stringWidth } from '../ink/stringWidth.js'
import { wrapAnsi } from '../ink/wrapAnsi.js'
import {
firstGrapheme,
getGraphemeSegmenter,
getWordSegmenter,
} from './intl.js'
/**
* Kill ring for storing killed (cut) text that can be yanked (pasted) with Ctrl+Y.
* This is global state that shares one kill ring across all input fields.
*
* Consecutive kills accumulate in the kill ring until the user types some
* other key. Alt+Y cycles through previous kills after a yank.
*/
const KILL_RING_MAX_SIZE = 10
let killRing: string[] = []
let killRingIndex = 0
let lastActionWasKill = false
// Track yank state for yank-pop (alt-y)
let lastYankStart = 0
let lastYankLength = 0
let lastActionWasYank = false
export function pushToKillRing(
text: string,
direction: 'prepend' | 'append' = 'append',
): void {
if (text.length > 0) {
if (lastActionWasKill && killRing.length > 0) {
// Accumulate with the most recent kill
if (direction === 'prepend') {
killRing[0] = text + killRing[0]
} else {
killRing[0] = killRing[0] + text
}
} else {
// Add new entry to front of ring
killRing.unshift(text)
if (killRing.length > KILL_RING_MAX_SIZE) {
killRing.pop()
}
}
lastActionWasKill = true
// Reset yank state when killing new text
lastActionWasYank = false
}
}
export function getLastKill(): string {
return killRing[0] ?? ''
}
export function getKillRingItem(index: number): string {
if (killRing.length === 0) return ''
const normalizedIndex =
((index % killRing.length) + killRing.length) % killRing.length
return killRing[normalizedIndex] ?? ''
}
export function getKillRingSize(): number {
return killRing.length
}
export function clearKillRing(): void {
killRing = []
killRingIndex = 0
lastActionWasKill = false
lastActionWasYank = false
lastYankStart = 0
lastYankLength = 0
}
export function resetKillAccumulation(): void {
lastActionWasKill = false
}
// Yank tracking for yank-pop
export function recordYank(start: number, length: number): void {
lastYankStart = start
lastYankLength = length
lastActionWasYank = true
killRingIndex = 0
}
export function canYankPop(): boolean {
return lastActionWasYank && killRing.length > 1
}
export function yankPop(): {
text: string
start: number
length: number
} | null {
if (!lastActionWasYank || killRing.length <= 1) {
return null
}
// Cycle to next item in kill ring
killRingIndex = (killRingIndex + 1) % killRing.length
const text = killRing[killRingIndex] ?? ''
return { text, start: lastYankStart, length: lastYankLength }
}
export function updateYankLength(length: number): void {
lastYankLength = length
}
export function resetYankState(): void {
lastActionWasYank = false
}
/**
* Text Processing Flow for Unicode Normalization:
*
* User Input (raw text, potentially mixed NFD/NFC)
* ↓
* MeasuredText (normalizes to NFC + builds grapheme info)
* ↓
* All cursor operations use normalized text/offsets
* ↓
* Display uses normalized text from wrappedLines
*
* This flow ensures consistent Unicode handling:
* - NFD/NFC normalization differences don't break cursor movement
* - Grapheme clusters (like 👨👩👧👦) are treated as single units
* - Display width calculations are accurate for CJK characters
*
* RULE: Once text enters MeasuredText, all operations
* work on the normalized version.
*/
// Pre-compiled regex patterns for Vim word detection (avoid creating in hot loops)
export const VIM_WORD_CHAR_REGEX = /^[\p{L}\p{N}\p{M}_]$/u
export const WHITESPACE_REGEX = /\s/
// Exported helper functions for Vim character classification
export const isVimWordChar = (ch: string): boolean =>
VIM_WORD_CHAR_REGEX.test(ch)
export const isVimWhitespace = (ch: string): boolean =>
WHITESPACE_REGEX.test(ch)
export const isVimPunctuation = (ch: string): boolean =>
ch.length > 0 && !isVimWhitespace(ch) && !isVimWordChar(ch)
type WrappedText = string[]
type Position = {
line: number
column: number
}
export class Cursor {
readonly offset: number
constructor(
readonly measuredText: MeasuredText,
offset: number = 0,
readonly selection: number = 0,
) {
// it's ok for the cursor to be 1 char beyond the end of the string
this.offset = Math.max(0, Math.min(this.text.length, offset))
}
static fromText(
text: string,
columns: number,
offset: number = 0,
selection: number = 0,
): Cursor {
// make MeasuredText on less than columns width, to account for cursor
return new Cursor(new MeasuredText(text, columns - 1), offset, selection)
}
getViewportStartLine(maxVisibleLines?: number): number {
if (maxVisibleLines === undefined || maxVisibleLines <= 0) return 0
const { line } = this.getPosition()
const allLines = this.measuredText.getWrappedText()
if (allLines.length <= maxVisibleLines) return 0
const half = Math.floor(maxVisibleLines / 2)
let startLine = Math.max(0, line - half)
const endLine = Math.min(allLines.length, startLine + maxVisibleLines)
if (endLine - startLine < maxVisibleLines) {
startLine = Math.max(0, endLine - maxVisibleLines)
}
return startLine
}
getViewportCharOffset(maxVisibleLines?: number): number {
const startLine = this.getViewportStartLine(maxVisibleLines)
if (startLine === 0) return 0
const wrappedLines = this.measuredText.getWrappedLines()
return wrappedLines[startLine]?.startOffset ?? 0
}
getViewportCharEnd(maxVisibleLines?: number): number {
const startLine = this.getViewportStartLine(maxVisibleLines)
const allLines = this.measuredText.getWrappedLines()
if (maxVisibleLines === undefined || maxVisibleLines <= 0)
return this.text.length
const endLine = Math.min(allLines.length, startLine + maxVisibleLines)
if (endLine >= allLines.length) return this.text.length
return allLines[endLine]?.startOffset ?? this.text.length
}
render(
cursorChar: string,
mask: string,
invert: (text: string) => string,
ghostText?: { text: string; dim: (text: string) => string },
maxVisibleLines?: number,
) {
const { line, column } = this.getPosition()
const allLines = this.measuredText.getWrappedText()
const startLine = this.getViewportStartLine(maxVisibleLines)
const endLine =
maxVisibleLines !== undefined && maxVisibleLines > 0
? Math.min(allLines.length, startLine + maxVisibleLines)
: allLines.length
return allLines
.slice(startLine, endLine)
.map((text, i) => {
const currentLine = i + startLine
let displayText = text
if (mask) {
const graphemes = Array.from(getGraphemeSegmenter().segment(text))
if (currentLine === allLines.length - 1) {
// Last line: mask all but the trailing 6 chars so the user can
// confirm they pasted the right thing without exposing the full token
const visibleCount = Math.min(6, graphemes.length)
const maskCount = graphemes.length - visibleCount
const splitOffset =
graphemes.length > visibleCount ? graphemes[maskCount]!.index : 0
displayText = mask.repeat(maskCount) + text.slice(splitOffset)
} else {
// Earlier wrapped lines: fully mask. Previously only the last line
// was masked, leaking the start of the token on narrow terminals
// where the pasted OAuth code wraps across multiple lines.
displayText = mask.repeat(graphemes.length)
}
}
// looking for the line with the cursor
if (line !== currentLine) return displayText.trimEnd()
// Split the line into before/at/after cursor in a single pass over the
// graphemes, accumulating display width until we reach the cursor column.
// This replaces a two-pass approach (displayWidthToStringIndex + a second
// segmenter pass) — the intermediate stringIndex from that approach is
// always a grapheme boundary, so the "cursor in the middle of a
// multi-codepoint character" branch was unreachable.
let beforeCursor = ''
let atCursor = cursorChar
let afterCursor = ''
let currentWidth = 0
let cursorFound = false
for (const { segment } of getGraphemeSegmenter().segment(displayText)) {
if (cursorFound) {
afterCursor += segment
continue
}
const nextWidth = currentWidth + stringWidth(segment)
if (nextWidth > column) {
atCursor = segment
cursorFound = true
} else {
currentWidth = nextWidth
beforeCursor += segment
}
}
// Only invert the cursor if we have a cursor character to show
// When ghost text is present and cursor is at end, show first ghost char in cursor
let renderedCursor: string
let ghostSuffix = ''
if (
ghostText &&
currentLine === allLines.length - 1 &&
this.isAtEnd() &&
ghostText.text.length > 0
) {
// First ghost character goes in the inverted cursor (grapheme-safe)
const firstGhostChar =
firstGrapheme(ghostText.text) || ghostText.text[0]!
renderedCursor = cursorChar ? invert(firstGhostChar) : firstGhostChar
// Rest of ghost text is dimmed after cursor
const ghostRest = ghostText.text.slice(firstGhostChar.length)
if (ghostRest.length > 0) {
ghostSuffix = ghostText.dim(ghostRest)
}
} else {
renderedCursor = cursorChar ? invert(atCursor) : atCursor
}
return (
beforeCursor + renderedCursor + ghostSuffix + afterCursor.trimEnd()
)
})
.join('\n')
}
left(): Cursor {
if (this.offset === 0) return this
const chip = this.imageRefEndingAt(this.offset)
if (chip) return new Cursor(this.measuredText, chip.start)
const prevOffset = this.measuredText.prevOffset(this.offset)
return new Cursor(this.measuredText, prevOffset)
}
right(): Cursor {
if (this.offset >= this.text.length) return this
const chip = this.imageRefStartingAt(this.offset)
if (chip) return new Cursor(this.measuredText, chip.end)
const nextOffset = this.measuredText.nextOffset(this.offset)
return new Cursor(this.measuredText, Math.min(nextOffset, this.text.length))
}
/**
* If an [Image #N] chip ends at `offset`, return its bounds. Used by left()
* to hop the cursor over the chip instead of stepping into it.
*/
imageRefEndingAt(offset: number): { start: number; end: number } | null {
const m = this.text.slice(0, offset).match(/\[Image #\d+\]$/)
return m ? { start: offset - m[0].length, end: offset } : null
}
imageRefStartingAt(offset: number): { start: number; end: number } | null {
const m = this.text.slice(offset).match(/^\[Image #\d+\]/)
return m ? { start: offset, end: offset + m[0].length } : null
}
/**
* If offset lands strictly inside an [Image #N] chip, snap it to the given
* boundary. Used by word-movement methods so Ctrl+W / Alt+D never leave a
* partial chip.
*/
snapOutOfImageRef(offset: number, toward: 'start' | 'end'): number {
const re = /\[Image #\d+\]/g
let m
while ((m = re.exec(this.text)) !== null) {
const start = m.index
const end = start + m[0].length
if (offset > start && offset < end) {
return toward === 'start' ? start : end
}
}
return offset
}
up(): Cursor {
const { line, column } = this.getPosition()
if (line === 0) {
return this
}
const prevLine = this.measuredText.getWrappedText()[line - 1]
if (prevLine === undefined) {
return this
}
const prevLineDisplayWidth = stringWidth(prevLine)
if (column > prevLineDisplayWidth) {
const newOffset = this.getOffset({
line: line - 1,
column: prevLineDisplayWidth,
})
return new Cursor(this.measuredText, newOffset, 0)
}
const newOffset = this.getOffset({ line: line - 1, column })
return new Cursor(this.measuredText, newOffset, 0)
}
down(): Cursor {
const { line, column } = this.getPosition()
if (line >= this.measuredText.lineCount - 1) {
return this
}
// If there is no next line, stay on the current line,
// and let the caller handle it (e.g. for prompt input,
// we move to the next history entry)
const nextLine = this.measuredText.getWrappedText()[line + 1]
if (nextLine === undefined) {
return this
}
// If the current column is past the end of the next line,
// move to the end of the next line
const nextLineDisplayWidth = stringWidth(nextLine)
if (column > nextLineDisplayWidth) {
const newOffset = this.getOffset({
line: line + 1,
column: nextLineDisplayWidth,
})
return new Cursor(this.measuredText, newOffset, 0)
}
// Otherwise, move to the same column on the next line
const newOffset = this.getOffset({
line: line + 1,
column,
})
return new Cursor(this.measuredText, newOffset, 0)
}
/**
* Move to the start of the current line (column 0).
* This is the raw version used internally by startOfLine.
*/
private startOfCurrentLine(): Cursor {
const { line } = this.getPosition()
return new Cursor(
this.measuredText,
this.getOffset({
line,
column: 0,
}),
0,
)
}
startOfLine(): Cursor {
const { line, column } = this.getPosition()
// If already at start of line and not at first line, move to previous line
if (column === 0 && line > 0) {
return new Cursor(
this.measuredText,
this.getOffset({
line: line - 1,
column: 0,
}),
0,
)
}
return this.startOfCurrentLine()
}
firstNonBlankInLine(): Cursor {
const { line } = this.getPosition()
const lineText = this.measuredText.getWrappedText()[line] || ''
const match = lineText.match(/^\s*\S/)
const column = match?.index ? match.index + match[0].length - 1 : 0
const offset = this.getOffset({ line, column })
return new Cursor(this.measuredText, offset, 0)
}
endOfLine(): Cursor {
const { line } = this.getPosition()
const column = this.measuredText.getLineLength(line)
const offset = this.getOffset({ line, column })
return new Cursor(this.measuredText, offset, 0)
}
// Helper methods for finding logical line boundaries
private findLogicalLineStart(fromOffset: number = this.offset): number {
const prevNewline = this.text.lastIndexOf('\n', fromOffset - 1)
return prevNewline === -1 ? 0 : prevNewline + 1
}
private findLogicalLineEnd(fromOffset: number = this.offset): number {
const nextNewline = this.text.indexOf('\n', fromOffset)
return nextNewline === -1 ? this.text.length : nextNewline
}
// Helper to get logical line bounds for current position
private getLogicalLineBounds(): { start: number; end: number } {
return {
start: this.findLogicalLineStart(),
end: this.findLogicalLineEnd(),
}
}
// Helper to create cursor with preserved column, clamped to line length
// Snaps to grapheme boundary to avoid landing mid-grapheme
private createCursorWithColumn(
lineStart: number,
lineEnd: number,
targetColumn: number,
): Cursor {
const lineLength = lineEnd - lineStart
const clampedColumn = Math.min(targetColumn, lineLength)
const rawOffset = lineStart + clampedColumn
const offset = this.measuredText.snapToGraphemeBoundary(rawOffset)
return new Cursor(this.measuredText, offset, 0)
}
endOfLogicalLine(): Cursor {
return new Cursor(this.measuredText, this.findLogicalLineEnd(), 0)
}
startOfLogicalLine(): Cursor {
return new Cursor(this.measuredText, this.findLogicalLineStart(), 0)
}
firstNonBlankInLogicalLine(): Cursor {
const { start, end } = this.getLogicalLineBounds()
const lineText = this.text.slice(start, end)
const match = lineText.match(/\S/)
const offset = start + (match?.index ?? 0)
return new Cursor(this.measuredText, offset, 0)
}
upLogicalLine(): Cursor {
const { start: currentStart } = this.getLogicalLineBounds()
// At first line - stay at beginning
if (currentStart === 0) {
return new Cursor(this.measuredText, 0, 0)
}
// Calculate target column position
const currentColumn = this.offset - currentStart
// Find previous line bounds
const prevLineEnd = currentStart - 1
const prevLineStart = this.findLogicalLineStart(prevLineEnd)
return this.createCursorWithColumn(
prevLineStart,
prevLineEnd,
currentColumn,
)
}
downLogicalLine(): Cursor {
const { start: currentStart, end: currentEnd } = this.getLogicalLineBounds()
// At last line - stay at end
if (currentEnd >= this.text.length) {
return new Cursor(this.measuredText, this.text.length, 0)
}
// Calculate target column position
const currentColumn = this.offset - currentStart
// Find next line bounds
const nextLineStart = currentEnd + 1
const nextLineEnd = this.findLogicalLineEnd(nextLineStart)
return this.createCursorWithColumn(
nextLineStart,
nextLineEnd,
currentColumn,
)
}
// Vim word vs WORD movements:
// - word (lowercase w/b/e): sequences of letters, digits, and underscores
// - WORD (uppercase W/B/E): sequences of non-whitespace characters
// For example, in "hello-world!", word movements see 3 words: "hello", "world", and nothing
// But WORD movements see 1 WORD: "hello-world!"
nextWord(): Cursor {
if (this.isAtEnd()) {
return this
}
// Use Intl.Segmenter for proper word boundary detection (including CJK)
const wordBoundaries = this.measuredText.getWordBoundaries()
// Find the next word start boundary after current position
for (const boundary of wordBoundaries) {
if (boundary.isWordLike && boundary.start > this.offset) {
return new Cursor(this.measuredText, boundary.start)
}
}
// If no next word found, go to end
return new Cursor(this.measuredText, this.text.length)
}
endOfWord(): Cursor {
if (this.isAtEnd()) {
return this
}
// Use Intl.Segmenter for proper word boundary detection (including CJK)
const wordBoundaries = this.measuredText.getWordBoundaries()
// Find the current word boundary we're in
for (const boundary of wordBoundaries) {
if (!boundary.isWordLike) continue
// If we're inside this word but NOT at the last character
if (this.offset >= boundary.start && this.offset < boundary.end - 1) {
// Move to end of this word (last character position)
return new Cursor(this.measuredText, boundary.end - 1)
}
// If we're at the last character of a word (end - 1), find the next word's end
if (this.offset === boundary.end - 1) {
// Find next word
for (const nextBoundary of wordBoundaries) {
if (nextBoundary.isWordLike && nextBoundary.start > this.offset) {
return new Cursor(this.measuredText, nextBoundary.end - 1)
}
}
return this
}
}
// If not in a word, find the next word and go to its end
for (const boundary of wordBoundaries) {
if (boundary.isWordLike && boundary.start > this.offset) {
return new Cursor(this.measuredText, boundary.end - 1)
}
}
return this
}
prevWord(): Cursor {
if (this.isAtStart()) {
return this
}
// Use Intl.Segmenter for proper word boundary detection (including CJK)
const wordBoundaries = this.measuredText.getWordBoundaries()
// Find the previous word start boundary before current position
// We need to iterate in reverse to find the previous word
let prevWordStart: number | null = null
for (const boundary of wordBoundaries) {
if (!boundary.isWordLike) continue
// If we're at or after the start of this word, but this word starts before us
if (boundary.start < this.offset) {
// If we're inside this word (not at the start), go to its start
if (this.offset > boundary.start && this.offset <= boundary.end) {
return new Cursor(this.measuredText, boundary.start)
}
// Otherwise, remember this as a candidate for previous word
prevWordStart = boundary.start
}
}
if (prevWordStart !== null) {
return new Cursor(this.measuredText, prevWordStart)
}
return new Cursor(this.measuredText, 0)
}
// Vim-specific word methods
// In Vim, a "word" is either:
// 1. A sequence of word characters (letters, digits, underscore) - including Unicode
// 2. A sequence of non-blank, non-word characters (punctuation/symbols)
nextVimWord(): Cursor {
if (this.isAtEnd()) {
return this
}
let pos = this.offset
const advance = (p: number): number => this.measuredText.nextOffset(p)
const currentGrapheme = this.graphemeAt(pos)
if (!currentGrapheme) {
return this
}
if (isVimWordChar(currentGrapheme)) {
while (pos < this.text.length && isVimWordChar(this.graphemeAt(pos))) {
pos = advance(pos)
}
} else if (isVimPunctuation(currentGrapheme)) {
while (pos < this.text.length && isVimPunctuation(this.graphemeAt(pos))) {
pos = advance(pos)
}
}
while (
pos < this.text.length &&
WHITESPACE_REGEX.test(this.graphemeAt(pos))
) {
pos = advance(pos)
}
return new Cursor(this.measuredText, pos)
}
endOfVimWord(): Cursor {
if (this.isAtEnd()) {
return this
}
const text = this.text
let pos = this.offset
const advance = (p: number): number => this.measuredText.nextOffset(p)
if (this.graphemeAt(pos) === '') {
return this
}
pos = advance(pos)
while (pos < text.length && WHITESPACE_REGEX.test(this.graphemeAt(pos))) {
pos = advance(pos)
}
if (pos >= text.length) {
return new Cursor(this.measuredText, text.length)
}
const charAtPos = this.graphemeAt(pos)
if (isVimWordChar(charAtPos)) {
while (pos < text.length) {
const nextPos = advance(pos)
if (nextPos >= text.length || !isVimWordChar(this.graphemeAt(nextPos)))
break
pos = nextPos
}
} else if (isVimPunctuation(charAtPos)) {
while (pos < text.length) {
const nextPos = advance(pos)
if (
nextPos >= text.length ||
!isVimPunctuation(this.graphemeAt(nextPos))
)
break
pos = nextPos
}
}
return new Cursor(this.measuredText, pos)
}
prevVimWord(): Cursor {
if (this.isAtStart()) {
return this
}
let pos = this.offset
const retreat = (p: number): number => this.measuredText.prevOffset(p)
pos = retreat(pos)
while (pos > 0 && WHITESPACE_REGEX.test(this.graphemeAt(pos))) {
pos = retreat(pos)
}
// At position 0 with whitespace means no previous word exists, go to start
if (pos === 0 && WHITESPACE_REGEX.test(this.graphemeAt(0))) {
return new Cursor(this.measuredText, 0)
}
const charAtPos = this.graphemeAt(pos)
if (isVimWordChar(charAtPos)) {
while (pos > 0) {
const prevPos = retreat(pos)
if (!isVimWordChar(this.graphemeAt(prevPos))) break
pos = prevPos
}
} else if (isVimPunctuation(charAtPos)) {
while (pos > 0) {
const prevPos = retreat(pos)
if (!isVimPunctuation(this.graphemeAt(prevPos))) break
pos = prevPos
}
}
return new Cursor(this.measuredText, pos)
}
nextWORD(): Cursor {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let nextCursor: Cursor = this
// If we're on a non-whitespace character, move to the next whitespace
while (!nextCursor.isOverWhitespace() && !nextCursor.isAtEnd()) {
nextCursor = nextCursor.right()
}
// now move to the next non-whitespace character
while (nextCursor.isOverWhitespace() && !nextCursor.isAtEnd()) {
nextCursor = nextCursor.right()
}
return nextCursor
}
endOfWORD(): Cursor {
if (this.isAtEnd()) {
return this
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
let cursor: Cursor = this
// Check if we're already at the end of a WORD
// (current character is non-whitespace, but next character is whitespace or we're at the end)
const atEndOfWORD =
!cursor.isOverWhitespace() &&
(cursor.right().isOverWhitespace() || cursor.right().isAtEnd())
if (atEndOfWORD) {
// We're already at the end of a WORD, move to the next WORD
cursor = cursor.right()
return cursor.endOfWORD()
}
// If we're on a whitespace character, find the next WORD
if (cursor.isOverWhitespace()) {
cursor = cursor.nextWORD()
}
// Now move to the end of the current WORD
while (!cursor.right().isOverWhitespace() && !cursor.isAtEnd()) {
cursor = cursor.right()
}
return cursor
}
prevWORD(): Cursor {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let cursor: Cursor = this
// if we are already at the beginning of a WORD, step off it
if (cursor.left().isOverWhitespace()) {
cursor = cursor.left()
}
// Move left over any whitespace characters
while (cursor.isOverWhitespace() && !cursor.isAtStart()) {
cursor = cursor.left()
}
// If we're over a non-whitespace character, move to the start of this WORD
if (!cursor.isOverWhitespace()) {
while (!cursor.left().isOverWhitespace() && !cursor.isAtStart()) {
cursor = cursor.left()
}
}
return cursor
}
modifyText(end: Cursor, insertString: string = ''): Cursor {
const startOffset = this.offset
const endOffset = end.offset
const newText =
this.text.slice(0, startOffset) +
insertString +
this.text.slice(endOffset)
return Cursor.fromText(
newText,
this.columns,
startOffset + insertString.normalize('NFC').length,
)
}
insert(insertString: string): Cursor {
const newCursor = this.modifyText(this, insertString)
return newCursor
}
del(): Cursor {
if (this.isAtEnd()) {
return this
}
return this.modifyText(this.right())
}
backspace(): Cursor {
if (this.isAtStart()) {
return this
}
return this.left().modifyText(this)
}
deleteToLineStart(): { cursor: Cursor; killed: string } {
// If cursor is right after a newline (at start of line), delete just that
// newline — symmetric with deleteToLineEnd's newline handling. This lets
// repeated ctrl+u clear across lines.
if (this.offset > 0 && this.text[this.offset - 1] === '\n') {
return { cursor: this.left().modifyText(this), killed: '\n' }
}
// Use startOfLine() so that at column 0 of a wrapped visual line,
// the cursor moves to the previous visual line's start instead of
// getting stuck.
const startCursor = this.startOfLine()
const killed = this.text.slice(startCursor.offset, this.offset)
return { cursor: startCursor.modifyText(this), killed }
}
deleteToLineEnd(): { cursor: Cursor; killed: string } {
// If cursor is on a newline character, delete just that character
if (this.text[this.offset] === '\n') {
return { cursor: this.modifyText(this.right()), killed: '\n' }
}
const endCursor = this.endOfLine()
const killed = this.text.slice(this.offset, endCursor.offset)
return { cursor: this.modifyText(endCursor), killed }
}
deleteToLogicalLineEnd(): Cursor {
// If cursor is on a newline character, delete just that character
if (this.text[this.offset] === '\n') {
return this.modifyText(this.right())
}
return this.modifyText(this.endOfLogicalLine())
}
deleteWordBefore(): { cursor: Cursor; killed: string } {
if (this.isAtStart()) {
return { cursor: this, killed: '' }
}
const target = this.snapOutOfImageRef(this.prevWord().offset, 'start')
const prevWordCursor = new Cursor(this.measuredText, target)
const killed = this.text.slice(prevWordCursor.offset, this.offset)
return { cursor: prevWordCursor.modifyText(this), killed }
}
/**
* Deletes a token before the cursor if one exists.
* Supports pasted text refs: [Pasted text #1], [Pasted text #1 +10 lines],
* [...Truncated text #1 +10 lines...]
*
* Note: @mentions are NOT tokenized since users may want to correct typos
* in file paths. Use Ctrl/Cmd+backspace for word-deletion on mentions.
*
* Returns null if no token found at cursor position.
* Only triggers when cursor is at end of token (followed by whitespace or EOL).
*/
deleteTokenBefore(): Cursor | null {
// Cursor at chip.start is the "selected" state — backspace deletes the
// chip forward, not the char before it.
const chipAfter = this.imageRefStartingAt(this.offset)
if (chipAfter) {
const end =
this.text[chipAfter.end] === ' ' ? chipAfter.end + 1 : chipAfter.end
return this.modifyText(new Cursor(this.measuredText, end))
}
if (this.isAtStart()) {
return null
}
// Only trigger if cursor is at a word boundary (whitespace or end of string after cursor)
const charAfter = this.text[this.offset]
if (charAfter !== undefined && !/\s/.test(charAfter)) {
return null
}
const textBefore = this.text.slice(0, this.offset)
// Check for pasted/truncated text refs: [Pasted text #1] or [...Truncated text #1 +50 lines...]
const pasteMatch = textBefore.match(
/(^|\s)\[(Pasted text #\d+(?: \+\d+ lines)?|Image #\d+|\.\.\.Truncated text #\d+ \+\d+ lines\.\.\.)\]$/,
)
if (pasteMatch) {
const matchStart = pasteMatch.index! + pasteMatch[1]!.length
return new Cursor(this.measuredText, matchStart).modifyText(this)
}
return null
}
deleteWordAfter(): Cursor {
if (this.isAtEnd()) {
return this
}
const target = this.snapOutOfImageRef(this.nextWord().offset, 'end')
return this.modifyText(new Cursor(this.measuredText, target))
}
private graphemeAt(pos: number): string {
if (pos >= this.text.length) return ''
const nextOff = this.measuredText.nextOffset(pos)
return this.text.slice(pos, nextOff)
}
private isOverWhitespace(): boolean {
const currentChar = this.text[this.offset] ?? ''
return /\s/.test(currentChar)
}
equals(other: Cursor): boolean {
return (
this.offset === other.offset && this.measuredText === other.measuredText
)
}
isAtStart(): boolean {
return this.offset === 0
}
isAtEnd(): boolean {