-
Notifications
You must be signed in to change notification settings - Fork 14.2k
Expand file tree
/
Copy pathtext-buffer.ts
More file actions
3603 lines (3211 loc) · 108 KB
/
Copy pathtext-buffer.ts
File metadata and controls
3603 lines (3211 loc) · 108 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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import pathMod from 'node:path';
import * as path from 'node:path';
import { useState, useCallback, useEffect, useMemo, useReducer } from 'react';
import { LRUCache } from 'mnemonist';
import {
coreEvents,
CoreEvent,
debugLogger,
unescapePath,
type EditorType,
getEditorCommand,
isGuiEditor,
} from '@google/gemini-cli-core';
import {
toCodePoints,
cpLen,
cpSlice,
stripUnsafeCharacters,
getCachedStringWidth,
} from '../../utils/textUtils.js';
import { parsePastedPaths } from '../../utils/clipboardUtils.js';
import type { Key } from '../../contexts/KeypressContext.js';
import { keyMatchers, Command } from '../../keyMatchers.js';
import type { VimAction } from './vim-buffer-actions.js';
import { handleVimAction } from './vim-buffer-actions.js';
import { LRU_BUFFER_PERF_CACHE_LIMIT } from '../../constants.js';
const LARGE_PASTE_LINE_THRESHOLD = 5;
const LARGE_PASTE_CHAR_THRESHOLD = 500;
// Regex to match paste placeholders like [Pasted Text: 6 lines] or [Pasted Text: 501 chars #2]
export const PASTED_TEXT_PLACEHOLDER_REGEX =
/\[Pasted Text: \d+ (?:lines|chars)(?: #\d+)?\]/g;
export type Direction =
| 'left'
| 'right'
| 'up'
| 'down'
| 'wordLeft'
| 'wordRight'
| 'home'
| 'end';
// Helper functions for line-based word navigation
export const isWordCharStrict = (char: string): boolean =>
/[\w\p{L}\p{N}]/u.test(char); // Matches a single character that is any Unicode letter, any Unicode number, or an underscore
export const isWhitespace = (char: string): boolean => /\s/.test(char);
// Check if a character is a combining mark (only diacritics for now)
export const isCombiningMark = (char: string): boolean => /\p{M}/u.test(char);
// Check if a character should be considered part of a word (including combining marks)
export const isWordCharWithCombining = (char: string): boolean =>
isWordCharStrict(char) || isCombiningMark(char);
// Get the script of a character (simplified for common scripts)
export const getCharScript = (char: string): string => {
if (/[\p{Script=Latin}]/u.test(char)) return 'latin'; // All Latin script chars including diacritics
if (/[\p{Script=Han}]/u.test(char)) return 'han'; // Chinese
if (/[\p{Script=Arabic}]/u.test(char)) return 'arabic';
if (/[\p{Script=Hiragana}]/u.test(char)) return 'hiragana';
if (/[\p{Script=Katakana}]/u.test(char)) return 'katakana';
if (/[\p{Script=Cyrillic}]/u.test(char)) return 'cyrillic';
return 'other';
};
// Check if two characters are from different scripts (indicating word boundary)
export const isDifferentScript = (char1: string, char2: string): boolean => {
if (!isWordCharStrict(char1) || !isWordCharStrict(char2)) return false;
return getCharScript(char1) !== getCharScript(char2);
};
// Find next word start within a line, starting from col
export const findNextWordStartInLine = (
line: string,
col: number,
): number | null => {
const chars = toCodePoints(line);
let i = col;
if (i >= chars.length) return null;
const currentChar = chars[i];
// Skip current word/sequence based on character type
if (isWordCharStrict(currentChar)) {
while (i < chars.length && isWordCharWithCombining(chars[i])) {
// Check for script boundary - if next character is from different script, stop here
if (
i + 1 < chars.length &&
isWordCharStrict(chars[i + 1]) &&
isDifferentScript(chars[i], chars[i + 1])
) {
i++; // Include current character
break; // Stop at script boundary
}
i++;
}
} else if (!isWhitespace(currentChar)) {
while (
i < chars.length &&
!isWordCharStrict(chars[i]) &&
!isWhitespace(chars[i])
) {
i++;
}
}
// Skip whitespace
while (i < chars.length && isWhitespace(chars[i])) {
i++;
}
return i < chars.length ? i : null;
};
// Find previous word start within a line
export const findPrevWordStartInLine = (
line: string,
col: number,
): number | null => {
const chars = toCodePoints(line);
let i = col;
if (i <= 0) return null;
i--;
// Skip whitespace moving backwards
while (i >= 0 && isWhitespace(chars[i])) {
i--;
}
if (i < 0) return null;
if (isWordCharStrict(chars[i])) {
// We're in a word, move to its beginning
while (i >= 0 && isWordCharStrict(chars[i])) {
// Check for script boundary - if previous character is from different script, stop here
if (
i - 1 >= 0 &&
isWordCharStrict(chars[i - 1]) &&
isDifferentScript(chars[i], chars[i - 1])
) {
return i; // Return current position at script boundary
}
i--;
}
return i + 1;
} else {
// We're in punctuation, move to its beginning
while (i >= 0 && !isWordCharStrict(chars[i]) && !isWhitespace(chars[i])) {
i--;
}
return i + 1;
}
};
// Find word end within a line
export const findWordEndInLine = (line: string, col: number): number | null => {
const chars = toCodePoints(line);
let i = col;
// If we're already at the end of a word (including punctuation sequences), advance to next word
// This includes both regular word endings and script boundaries
const atEndOfWordChar =
i < chars.length &&
isWordCharWithCombining(chars[i]) &&
(i + 1 >= chars.length ||
!isWordCharWithCombining(chars[i + 1]) ||
(isWordCharStrict(chars[i]) &&
i + 1 < chars.length &&
isWordCharStrict(chars[i + 1]) &&
isDifferentScript(chars[i], chars[i + 1])));
const atEndOfPunctuation =
i < chars.length &&
!isWordCharWithCombining(chars[i]) &&
!isWhitespace(chars[i]) &&
(i + 1 >= chars.length ||
isWhitespace(chars[i + 1]) ||
isWordCharWithCombining(chars[i + 1]));
if (atEndOfWordChar || atEndOfPunctuation) {
// We're at the end of a word or punctuation sequence, move forward to find next word
i++;
// Skip whitespace to find next word or punctuation
while (i < chars.length && isWhitespace(chars[i])) {
i++;
}
}
// If we're not on a word character, find the next word or punctuation sequence
if (i < chars.length && !isWordCharWithCombining(chars[i])) {
// Skip whitespace to find next word or punctuation
while (i < chars.length && isWhitespace(chars[i])) {
i++;
}
}
// Move to end of current word (including combining marks, but stop at script boundaries)
let foundWord = false;
let lastBaseCharPos = -1;
if (i < chars.length && isWordCharWithCombining(chars[i])) {
// Handle word characters
while (i < chars.length && isWordCharWithCombining(chars[i])) {
foundWord = true;
// Track the position of the last base character (not combining mark)
if (isWordCharStrict(chars[i])) {
lastBaseCharPos = i;
}
// Check if next character is from a different script (word boundary)
if (
i + 1 < chars.length &&
isWordCharStrict(chars[i + 1]) &&
isDifferentScript(chars[i], chars[i + 1])
) {
i++; // Include current character
if (isWordCharStrict(chars[i - 1])) {
lastBaseCharPos = i - 1;
}
break; // Stop at script boundary
}
i++;
}
} else if (i < chars.length && !isWhitespace(chars[i])) {
// Handle punctuation sequences (like ████)
while (
i < chars.length &&
!isWordCharStrict(chars[i]) &&
!isWhitespace(chars[i])
) {
foundWord = true;
lastBaseCharPos = i;
i++;
}
}
// Only return a position if we actually found a word
// Return the position of the last base character, not combining marks
if (foundWord && lastBaseCharPos >= col) {
return lastBaseCharPos;
}
return null;
};
// Initialize segmenter for word boundary detection
const segmenter = new Intl.Segmenter(undefined, { granularity: 'word' });
function findPrevWordBoundary(line: string, cursorCol: number): number {
const codePoints = toCodePoints(line);
// Convert cursorCol (CP index) to string index
const prefix = codePoints.slice(0, cursorCol).join('');
const cursorIdx = prefix.length;
let targetIdx = 0;
for (const seg of segmenter.segment(line)) {
// We want the last word start strictly before the cursor.
// If we've reached or passed the cursor, we stop.
if (seg.index >= cursorIdx) break;
if (seg.isWordLike) {
targetIdx = seg.index;
}
}
return toCodePoints(line.slice(0, targetIdx)).length;
}
function findNextWordBoundary(line: string, cursorCol: number): number {
const codePoints = toCodePoints(line);
const prefix = codePoints.slice(0, cursorCol).join('');
const cursorIdx = prefix.length;
let targetIdx = line.length;
for (const seg of segmenter.segment(line)) {
const segEnd = seg.index + seg.segment.length;
if (segEnd > cursorIdx) {
if (seg.isWordLike) {
targetIdx = segEnd;
break;
}
}
}
return toCodePoints(line.slice(0, targetIdx)).length;
}
// Find next word across lines
export const findNextWordAcrossLines = (
lines: string[],
cursorRow: number,
cursorCol: number,
searchForWordStart: boolean,
): { row: number; col: number } | null => {
// First try current line
const currentLine = lines[cursorRow] || '';
const colInCurrentLine = searchForWordStart
? findNextWordStartInLine(currentLine, cursorCol)
: findWordEndInLine(currentLine, cursorCol);
if (colInCurrentLine !== null) {
return { row: cursorRow, col: colInCurrentLine };
}
// Search subsequent lines
for (let row = cursorRow + 1; row < lines.length; row++) {
const line = lines[row] || '';
const chars = toCodePoints(line);
// For empty lines, if we haven't found any words yet, return the empty line
if (chars.length === 0) {
// Check if there are any words in remaining lines
let hasWordsInLaterLines = false;
for (let laterRow = row + 1; laterRow < lines.length; laterRow++) {
const laterLine = lines[laterRow] || '';
const laterChars = toCodePoints(laterLine);
let firstNonWhitespace = 0;
while (
firstNonWhitespace < laterChars.length &&
isWhitespace(laterChars[firstNonWhitespace])
) {
firstNonWhitespace++;
}
if (firstNonWhitespace < laterChars.length) {
hasWordsInLaterLines = true;
break;
}
}
// If no words in later lines, return the empty line
if (!hasWordsInLaterLines) {
return { row, col: 0 };
}
continue;
}
// Find first non-whitespace
let firstNonWhitespace = 0;
while (
firstNonWhitespace < chars.length &&
isWhitespace(chars[firstNonWhitespace])
) {
firstNonWhitespace++;
}
if (firstNonWhitespace < chars.length) {
if (searchForWordStart) {
return { row, col: firstNonWhitespace };
} else {
// For word end, find the end of the first word
const endCol = findWordEndInLine(line, firstNonWhitespace);
if (endCol !== null) {
return { row, col: endCol };
}
}
}
}
return null;
};
// Find previous word across lines
export const findPrevWordAcrossLines = (
lines: string[],
cursorRow: number,
cursorCol: number,
): { row: number; col: number } | null => {
// First try current line
const currentLine = lines[cursorRow] || '';
const colInCurrentLine = findPrevWordStartInLine(currentLine, cursorCol);
if (colInCurrentLine !== null) {
return { row: cursorRow, col: colInCurrentLine };
}
// Search previous lines
for (let row = cursorRow - 1; row >= 0; row--) {
const line = lines[row] || '';
const chars = toCodePoints(line);
if (chars.length === 0) continue;
// Find last word start
let lastWordStart = chars.length;
while (lastWordStart > 0 && isWhitespace(chars[lastWordStart - 1])) {
lastWordStart--;
}
if (lastWordStart > 0) {
// Find start of this word
const wordStart = findPrevWordStartInLine(line, lastWordStart);
if (wordStart !== null) {
return { row, col: wordStart };
}
}
}
return null;
};
// Helper functions for vim line operations
export const getPositionFromOffsets = (
startOffset: number,
endOffset: number,
lines: string[],
) => {
let offset = 0;
let startRow = 0;
let startCol = 0;
let endRow = 0;
let endCol = 0;
// Find start position
for (let i = 0; i < lines.length; i++) {
const lineLength = lines[i].length + 1; // +1 for newline
if (offset + lineLength > startOffset) {
startRow = i;
startCol = startOffset - offset;
break;
}
offset += lineLength;
}
// Find end position
offset = 0;
for (let i = 0; i < lines.length; i++) {
const lineLength = lines[i].length + (i < lines.length - 1 ? 1 : 0); // +1 for newline except last line
if (offset + lineLength >= endOffset) {
endRow = i;
endCol = endOffset - offset;
break;
}
offset += lineLength;
}
return { startRow, startCol, endRow, endCol };
};
export const getLineRangeOffsets = (
startRow: number,
lineCount: number,
lines: string[],
) => {
let startOffset = 0;
// Calculate start offset
for (let i = 0; i < startRow; i++) {
startOffset += lines[i].length + 1; // +1 for newline
}
// Calculate end offset
let endOffset = startOffset;
for (let i = 0; i < lineCount; i++) {
const lineIndex = startRow + i;
if (lineIndex < lines.length) {
endOffset += lines[lineIndex].length;
if (lineIndex < lines.length - 1) {
endOffset += 1; // +1 for newline
}
}
}
return { startOffset, endOffset };
};
export const replaceRangeInternal = (
state: TextBufferState,
startRow: number,
startCol: number,
endRow: number,
endCol: number,
text: string,
): TextBufferState => {
const currentLine = (row: number) => state.lines[row] || '';
const currentLineLen = (row: number) => cpLen(currentLine(row));
const clamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max);
if (
startRow > endRow ||
(startRow === endRow && startCol > endCol) ||
startRow < 0 ||
startCol < 0 ||
endRow >= state.lines.length ||
(endRow < state.lines.length && endCol > currentLineLen(endRow))
) {
return state; // Invalid range
}
const newLines = [...state.lines];
const sCol = clamp(startCol, 0, currentLineLen(startRow));
const eCol = clamp(endCol, 0, currentLineLen(endRow));
const prefix = cpSlice(currentLine(startRow), 0, sCol);
const suffix = cpSlice(currentLine(endRow), eCol);
const normalisedReplacement = text
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n');
const replacementParts = normalisedReplacement.split('\n');
// The combined first line of the new text
const firstLine = prefix + replacementParts[0];
if (replacementParts.length === 1) {
// No newlines in replacement: combine prefix, replacement, and suffix on one line.
newLines.splice(startRow, endRow - startRow + 1, firstLine + suffix);
} else {
// Newlines in replacement: create new lines.
const lastLine = replacementParts[replacementParts.length - 1] + suffix;
const middleLines = replacementParts.slice(1, -1);
newLines.splice(
startRow,
endRow - startRow + 1,
firstLine,
...middleLines,
lastLine,
);
}
const finalCursorRow = startRow + replacementParts.length - 1;
const finalCursorCol =
(replacementParts.length > 1 ? 0 : sCol) +
cpLen(replacementParts[replacementParts.length - 1]);
return {
...state,
lines: newLines,
cursorRow: Math.min(Math.max(finalCursorRow, 0), newLines.length - 1),
cursorCol: Math.max(
0,
Math.min(finalCursorCol, cpLen(newLines[finalCursorRow] || '')),
),
preferredCol: null,
};
};
export interface Viewport {
height: number;
width: number;
}
function clamp(v: number, min: number, max: number): number {
return v < min ? min : v > max ? max : v;
}
/* ────────────────────────────────────────────────────────────────────────── */
interface UseTextBufferProps {
initialText?: string;
initialCursorOffset?: number;
viewport: Viewport; // Viewport dimensions needed for scrolling
stdin?: NodeJS.ReadStream | null; // For external editor
setRawMode?: (mode: boolean) => void; // For external editor
onChange?: (text: string) => void; // Callback for when text changes
isValidPath: (path: string) => boolean;
shellModeActive?: boolean; // Whether the text buffer is in shell mode
inputFilter?: (text: string) => string; // Optional filter for input text
singleLine?: boolean;
getPreferredEditor?: () => EditorType | undefined;
}
interface UndoHistoryEntry {
lines: string[];
cursorRow: number;
cursorCol: number;
pastedContent: Record<string, string>;
expandedPaste: ExpandedPasteInfo | null;
}
function calculateInitialCursorPosition(
initialLines: string[],
offset: number,
): [number, number] {
let remainingChars = offset;
let row = 0;
while (row < initialLines.length) {
const lineLength = cpLen(initialLines[row]);
// Add 1 for the newline character (except for the last line)
const totalCharsInLineAndNewline =
lineLength + (row < initialLines.length - 1 ? 1 : 0);
if (remainingChars <= lineLength) {
// Cursor is on this line
return [row, remainingChars];
}
remainingChars -= totalCharsInLineAndNewline;
row++;
}
// Offset is beyond the text, place cursor at the end of the last line
if (initialLines.length > 0) {
const lastRow = initialLines.length - 1;
return [lastRow, cpLen(initialLines[lastRow])];
}
return [0, 0]; // Default for empty text
}
export function offsetToLogicalPos(
text: string,
offset: number,
): [number, number] {
let row = 0;
let col = 0;
let currentOffset = 0;
if (offset === 0) return [0, 0];
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineLength = cpLen(line);
const lineLengthWithNewline = lineLength + (i < lines.length - 1 ? 1 : 0);
if (offset <= currentOffset + lineLength) {
// Check against lineLength first
row = i;
col = offset - currentOffset;
return [row, col];
} else if (offset <= currentOffset + lineLengthWithNewline) {
// Check if offset is the newline itself
row = i;
col = lineLength; // Position cursor at the end of the current line content
// If the offset IS the newline, and it's not the last line, advance to next line, col 0
if (
offset === currentOffset + lineLengthWithNewline &&
i < lines.length - 1
) {
return [i + 1, 0];
}
return [row, col]; // Otherwise, it's at the end of the current line content
}
currentOffset += lineLengthWithNewline;
}
// If offset is beyond the text length, place cursor at the end of the last line
// or [0,0] if text is empty
if (lines.length > 0) {
row = lines.length - 1;
col = cpLen(lines[row]);
} else {
row = 0;
col = 0;
}
return [row, col];
}
/**
* Converts logical row/col position to absolute text offset
* Inverse operation of offsetToLogicalPos
*/
export function logicalPosToOffset(
lines: string[],
row: number,
col: number,
): number {
let offset = 0;
// Clamp row to valid range
const actualRow = Math.min(row, lines.length - 1);
// Add lengths of all lines before the target row
for (let i = 0; i < actualRow; i++) {
offset += cpLen(lines[i]) + 1; // +1 for newline
}
// Add column offset within the target row
if (actualRow >= 0 && actualRow < lines.length) {
offset += Math.min(col, cpLen(lines[actualRow]));
}
return offset;
}
/**
* Transformations allow for the CLI to render terse representations of things like file paths
* (e.g., "@some/path/to/an/image.png" to "[Image image.png]")
* When the cursor enters a transformed representation, it expands to reveal the logical representation.
* (e.g., "[Image image.png]" to "@some/path/to/an/image.png")
*/
export interface Transformation {
logStart: number;
logEnd: number;
logicalText: string;
collapsedText: string;
type: 'image' | 'paste';
id?: string; // For paste placeholders
}
export const imagePathRegex =
/@((?:\\.|[^\s\r\n\\])+?\.(?:png|jpg|jpeg|gif|webp|svg|bmp))\b/gi;
export function getTransformedImagePath(filePath: string): string {
const raw = filePath;
// Ignore leading @ when stripping directories, but keep it for simple '@file.png'
const withoutAt = raw.startsWith('@') ? raw.slice(1) : raw;
// Unescape the path to handle escaped spaces and other characters
const unescaped = unescapePath(withoutAt);
// Find last directory separator, supporting both POSIX and Windows styles
const lastSepIndex = Math.max(
unescaped.lastIndexOf('/'),
unescaped.lastIndexOf('\\'),
);
// If we saw a separator, take the segment after it; otherwise fall back to the unescaped string
const fileName =
lastSepIndex >= 0 ? unescaped.slice(lastSepIndex + 1) : unescaped;
const extension = path.extname(fileName);
const baseName = path.basename(fileName, extension);
const maxBaseLength = 10;
const truncatedBase =
baseName.length > maxBaseLength
? `...${baseName.slice(-maxBaseLength)}`
: baseName;
return `[Image ${truncatedBase}${extension}]`;
}
const transformationsCache = new LRUCache<string, Transformation[]>(
LRU_BUFFER_PERF_CACHE_LIMIT,
);
export function calculateTransformationsForLine(
line: string,
): Transformation[] {
const cached = transformationsCache.get(line);
if (cached) {
return cached;
}
const transformations: Transformation[] = [];
// 1. Detect image paths
imagePathRegex.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = imagePathRegex.exec(line)) !== null) {
const logicalText = match[0];
const logStart = cpLen(line.substring(0, match.index));
const logEnd = logStart + cpLen(logicalText);
transformations.push({
logStart,
logEnd,
logicalText,
collapsedText: getTransformedImagePath(logicalText),
type: 'image',
});
}
// 2. Detect paste placeholders
const pasteRegex = new RegExp(PASTED_TEXT_PLACEHOLDER_REGEX.source, 'g');
while ((match = pasteRegex.exec(line)) !== null) {
const logicalText = match[0];
const logStart = cpLen(line.substring(0, match.index));
const logEnd = logStart + cpLen(logicalText);
transformations.push({
logStart,
logEnd,
logicalText,
collapsedText: logicalText,
type: 'paste',
id: logicalText,
});
}
// Sort transformations by logStart to maintain consistency
transformations.sort((a, b) => a.logStart - b.logStart);
transformationsCache.set(line, transformations);
return transformations;
}
export function calculateTransformations(lines: string[]): Transformation[][] {
return lines.map((ln) => calculateTransformationsForLine(ln));
}
export function getTransformUnderCursor(
row: number,
col: number,
spansByLine: Transformation[][],
): Transformation | null {
const spans = spansByLine[row];
if (!spans || spans.length === 0) return null;
for (const span of spans) {
if (col >= span.logStart && col < span.logEnd) {
return span;
}
if (col < span.logStart) break;
}
return null;
}
export interface ExpandedPasteInfo {
id: string;
startLine: number;
lineCount: number;
prefix: string;
suffix: string;
}
/**
* Check if a line index falls within an expanded paste region.
* Returns the paste placeholder ID if found, null otherwise.
*/
export function getExpandedPasteAtLine(
lineIndex: number,
expandedPaste: ExpandedPasteInfo | null,
): string | null {
if (
expandedPaste &&
lineIndex >= expandedPaste.startLine &&
lineIndex < expandedPaste.startLine + expandedPaste.lineCount
) {
return expandedPaste.id;
}
return null;
}
/**
* Surgery for expanded paste regions when lines are added or removed.
* Adjusts startLine indices and detaches any region that is partially or fully deleted.
*/
export function shiftExpandedRegions(
expandedPaste: ExpandedPasteInfo | null,
changeStartLine: number,
lineDelta: number,
changeEndLine?: number, // Inclusive
): {
newInfo: ExpandedPasteInfo | null;
isDetached: boolean;
} {
if (!expandedPaste) return { newInfo: null, isDetached: false };
const effectiveEndLine = changeEndLine ?? changeStartLine;
const infoEndLine = expandedPaste.startLine + expandedPaste.lineCount - 1;
// 1. Check for overlap/intersection with the changed range
const isOverlapping =
changeStartLine <= infoEndLine &&
effectiveEndLine >= expandedPaste.startLine;
if (isOverlapping) {
// If the change is a deletion (lineDelta < 0) that touches this region, we detach.
// If it's an insertion, we only detach if it's a multi-line insertion (lineDelta > 0)
// that isn't at the very start of the region (which would shift it).
// Regular character typing (lineDelta === 0) does NOT detach.
if (
lineDelta < 0 ||
(lineDelta > 0 &&
changeStartLine > expandedPaste.startLine &&
changeStartLine <= infoEndLine)
) {
return { newInfo: null, isDetached: true };
}
}
// 2. Shift regions that start at or after the change point
if (expandedPaste.startLine >= changeStartLine) {
return {
newInfo: {
...expandedPaste,
startLine: expandedPaste.startLine + lineDelta,
},
isDetached: false,
};
}
return { newInfo: expandedPaste, isDetached: false };
}
/**
* Detach any expanded paste region if the cursor is within it.
* This converts the expanded content to regular text that can no longer be collapsed.
* Returns the state unchanged if cursor is not in an expanded region.
*/
export function detachExpandedPaste(state: TextBufferState): TextBufferState {
const expandedId = getExpandedPasteAtLine(
state.cursorRow,
state.expandedPaste,
);
if (!expandedId) return state;
const { [expandedId]: _, ...newPastedContent } = state.pastedContent;
return {
...state,
expandedPaste: null,
pastedContent: newPastedContent,
};
}
/**
* Represents an atomic placeholder that should be deleted as a unit.
* Extensible to support future placeholder types.
*/
interface AtomicPlaceholder {
start: number; // Start position in logical text
end: number; // End position in logical text
type: 'paste' | 'image'; // Type for cleanup logic
id?: string; // For paste placeholders: the pastedContent key
}
/**
* Find atomic placeholder at cursor for backspace (cursor at end).
* Checks all placeholder types in priority order.
*/
function findAtomicPlaceholderForBackspace(
line: string,
cursorCol: number,
transformations: Transformation[],
): AtomicPlaceholder | null {
for (const transform of transformations) {
if (cursorCol === transform.logEnd) {
return {
start: transform.logStart,
end: transform.logEnd,
type: transform.type,
id: transform.id,
};
}
}
return null;
}
/**
* Find atomic placeholder at cursor for delete (cursor at start).
*/
function findAtomicPlaceholderForDelete(
line: string,
cursorCol: number,
transformations: Transformation[],
): AtomicPlaceholder | null {
for (const transform of transformations) {
if (cursorCol === transform.logStart) {
return {
start: transform.logStart,
end: transform.logEnd,
type: transform.type,
id: transform.id,
};
}
}
return null;
}
export function calculateTransformedLine(
logLine: string,
logIndex: number,
logicalCursor: [number, number],
transformations: Transformation[],
): { transformedLine: string; transformedToLogMap: number[] } {
let transformedLine = '';
const transformedToLogMap: number[] = [];
let lastLogPos = 0;
const cursorIsOnThisLine = logIndex === logicalCursor[0];
const cursorCol = logicalCursor[1];
for (const transform of transformations) {
const textBeforeTransformation = cpSlice(
logLine,
lastLogPos,
transform.logStart,
);
transformedLine += textBeforeTransformation;
for (let i = 0; i < cpLen(textBeforeTransformation); i++) {
transformedToLogMap.push(lastLogPos + i);
}
const isExpanded =
transform.type === 'image' &&
cursorIsOnThisLine &&
cursorCol >= transform.logStart &&
cursorCol <= transform.logEnd;