@lenylvt/pi-tui 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +767 -0
  2. package/dist/autocomplete.d.ts +50 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +623 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/components/box.d.ts +22 -0
  7. package/dist/components/box.d.ts.map +1 -0
  8. package/dist/components/box.js +104 -0
  9. package/dist/components/box.js.map +1 -0
  10. package/dist/components/cancellable-loader.d.ts +22 -0
  11. package/dist/components/cancellable-loader.d.ts.map +1 -0
  12. package/dist/components/cancellable-loader.js +35 -0
  13. package/dist/components/cancellable-loader.js.map +1 -0
  14. package/dist/components/editor.d.ts +244 -0
  15. package/dist/components/editor.d.ts.map +1 -0
  16. package/dist/components/editor.js +1861 -0
  17. package/dist/components/editor.js.map +1 -0
  18. package/dist/components/image.d.ts +28 -0
  19. package/dist/components/image.d.ts.map +1 -0
  20. package/dist/components/image.js +69 -0
  21. package/dist/components/image.js.map +1 -0
  22. package/dist/components/input.d.ts +37 -0
  23. package/dist/components/input.d.ts.map +1 -0
  24. package/dist/components/input.js +426 -0
  25. package/dist/components/input.js.map +1 -0
  26. package/dist/components/loader.d.ts +21 -0
  27. package/dist/components/loader.d.ts.map +1 -0
  28. package/dist/components/loader.js +49 -0
  29. package/dist/components/loader.js.map +1 -0
  30. package/dist/components/markdown.d.ts +95 -0
  31. package/dist/components/markdown.d.ts.map +1 -0
  32. package/dist/components/markdown.js +660 -0
  33. package/dist/components/markdown.js.map +1 -0
  34. package/dist/components/select-list.d.ts +50 -0
  35. package/dist/components/select-list.d.ts.map +1 -0
  36. package/dist/components/select-list.js +159 -0
  37. package/dist/components/select-list.js.map +1 -0
  38. package/dist/components/settings-list.d.ts +50 -0
  39. package/dist/components/settings-list.d.ts.map +1 -0
  40. package/dist/components/settings-list.js +185 -0
  41. package/dist/components/settings-list.js.map +1 -0
  42. package/dist/components/spacer.d.ts +12 -0
  43. package/dist/components/spacer.d.ts.map +1 -0
  44. package/dist/components/spacer.js +23 -0
  45. package/dist/components/spacer.js.map +1 -0
  46. package/dist/components/text.d.ts +19 -0
  47. package/dist/components/text.d.ts.map +1 -0
  48. package/dist/components/text.js +89 -0
  49. package/dist/components/text.js.map +1 -0
  50. package/dist/components/truncated-text.d.ts +13 -0
  51. package/dist/components/truncated-text.d.ts.map +1 -0
  52. package/dist/components/truncated-text.js +51 -0
  53. package/dist/components/truncated-text.js.map +1 -0
  54. package/dist/editor-component.d.ts +39 -0
  55. package/dist/editor-component.d.ts.map +1 -0
  56. package/dist/editor-component.js +2 -0
  57. package/dist/editor-component.js.map +1 -0
  58. package/dist/fuzzy.d.ts +16 -0
  59. package/dist/fuzzy.d.ts.map +1 -0
  60. package/dist/fuzzy.js +107 -0
  61. package/dist/fuzzy.js.map +1 -0
  62. package/dist/index.d.ts +23 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +32 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/keybindings.d.ts +193 -0
  67. package/dist/keybindings.d.ts.map +1 -0
  68. package/dist/keybindings.js +174 -0
  69. package/dist/keybindings.js.map +1 -0
  70. package/dist/keys.d.ts +170 -0
  71. package/dist/keys.d.ts.map +1 -0
  72. package/dist/keys.js +1124 -0
  73. package/dist/keys.js.map +1 -0
  74. package/dist/kill-ring.d.ts +28 -0
  75. package/dist/kill-ring.d.ts.map +1 -0
  76. package/dist/kill-ring.js +44 -0
  77. package/dist/kill-ring.js.map +1 -0
  78. package/dist/stdin-buffer.d.ts +48 -0
  79. package/dist/stdin-buffer.d.ts.map +1 -0
  80. package/dist/stdin-buffer.js +317 -0
  81. package/dist/stdin-buffer.js.map +1 -0
  82. package/dist/terminal-image.d.ts +68 -0
  83. package/dist/terminal-image.d.ts.map +1 -0
  84. package/dist/terminal-image.js +288 -0
  85. package/dist/terminal-image.js.map +1 -0
  86. package/dist/terminal.d.ts +84 -0
  87. package/dist/terminal.d.ts.map +1 -0
  88. package/dist/terminal.js +285 -0
  89. package/dist/terminal.js.map +1 -0
  90. package/dist/tui.d.ts +218 -0
  91. package/dist/tui.d.ts.map +1 -0
  92. package/dist/tui.js +966 -0
  93. package/dist/tui.js.map +1 -0
  94. package/dist/undo-stack.d.ts +17 -0
  95. package/dist/undo-stack.d.ts.map +1 -0
  96. package/dist/undo-stack.js +25 -0
  97. package/dist/undo-stack.js.map +1 -0
  98. package/dist/utils.d.ts +78 -0
  99. package/dist/utils.d.ts.map +1 -0
  100. package/dist/utils.js +960 -0
  101. package/dist/utils.js.map +1 -0
  102. package/package.json +55 -0
  103. package/src/autocomplete.ts +771 -0
  104. package/src/components/box.ts +137 -0
  105. package/src/components/cancellable-loader.ts +40 -0
  106. package/src/components/editor.ts +2230 -0
  107. package/src/components/image.ts +104 -0
  108. package/src/components/input.ts +503 -0
  109. package/src/components/loader.ts +55 -0
  110. package/src/components/markdown.ts +820 -0
  111. package/src/components/select-list.ts +229 -0
  112. package/src/components/settings-list.ts +250 -0
  113. package/src/components/spacer.ts +28 -0
  114. package/src/components/text.ts +106 -0
  115. package/src/components/truncated-text.ts +65 -0
  116. package/src/editor-component.ts +74 -0
  117. package/src/fuzzy.ts +133 -0
  118. package/src/index.ts +104 -0
  119. package/src/keybindings.ts +244 -0
  120. package/src/keys.ts +1356 -0
  121. package/src/kill-ring.ts +46 -0
  122. package/src/stdin-buffer.ts +386 -0
  123. package/src/terminal-image.ts +381 -0
  124. package/src/terminal.ts +360 -0
  125. package/src/tui.ts +1200 -0
  126. package/src/undo-stack.ts +28 -0
  127. package/src/utils.ts +1068 -0
@@ -0,0 +1,2230 @@
1
+ import type { AutocompleteProvider, AutocompleteSuggestions, CombinedAutocompleteProvider } from "../autocomplete.js";
2
+ import { getKeybindings } from "../keybindings.js";
3
+ import { decodeKittyPrintable, matchesKey } from "../keys.js";
4
+ import { KillRing } from "../kill-ring.js";
5
+ import { type Component, CURSOR_MARKER, type Focusable, type TUI } from "../tui.js";
6
+ import { UndoStack } from "../undo-stack.js";
7
+ import { getSegmenter, isPunctuationChar, isWhitespaceChar, truncateToWidth, visibleWidth } from "../utils.js";
8
+ import { SelectList, type SelectListLayoutOptions, type SelectListTheme } from "./select-list.js";
9
+
10
+ const baseSegmenter = getSegmenter();
11
+
12
+ /** Regex matching paste markers like `[paste #1 +123 lines]` or `[paste #2 1234 chars]`. */
13
+ const PASTE_MARKER_REGEX = /\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g;
14
+
15
+ /** Non-global version for single-segment testing. */
16
+ const PASTE_MARKER_SINGLE = /^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;
17
+
18
+ /** Check if a segment is a paste marker (i.e. was merged by segmentWithMarkers). */
19
+ function isPasteMarker(segment: string): boolean {
20
+ return segment.length >= 10 && PASTE_MARKER_SINGLE.test(segment);
21
+ }
22
+
23
+ /**
24
+ * A segmenter that wraps Intl.Segmenter and merges graphemes that fall
25
+ * within paste markers into single atomic segments. This makes cursor
26
+ * movement, deletion, word-wrap, etc. treat paste markers as single units.
27
+ *
28
+ * Only markers whose numeric ID exists in `validIds` are merged.
29
+ */
30
+ function segmentWithMarkers(text: string, validIds: Set<number>): Iterable<Intl.SegmentData> {
31
+ // Fast path: no paste markers in the text or no valid IDs.
32
+ if (validIds.size === 0 || !text.includes("[paste #")) {
33
+ return baseSegmenter.segment(text);
34
+ }
35
+
36
+ // Find all marker spans with valid IDs.
37
+ const markers: Array<{ start: number; end: number }> = [];
38
+ for (const m of text.matchAll(PASTE_MARKER_REGEX)) {
39
+ const id = Number.parseInt(m[1]!, 10);
40
+ if (!validIds.has(id)) continue;
41
+ markers.push({ start: m.index, end: m.index + m[0].length });
42
+ }
43
+ if (markers.length === 0) {
44
+ return baseSegmenter.segment(text);
45
+ }
46
+
47
+ // Build merged segment list.
48
+ const baseSegments = baseSegmenter.segment(text);
49
+ const result: Intl.SegmentData[] = [];
50
+ let markerIdx = 0;
51
+
52
+ for (const seg of baseSegments) {
53
+ // Skip past markers that are entirely before this segment.
54
+ while (markerIdx < markers.length && markers[markerIdx]!.end <= seg.index) {
55
+ markerIdx++;
56
+ }
57
+
58
+ const marker = markerIdx < markers.length ? markers[markerIdx]! : null;
59
+
60
+ if (marker && seg.index >= marker.start && seg.index < marker.end) {
61
+ // This segment falls inside a marker.
62
+ // If this is the first segment of the marker, emit a merged segment.
63
+ if (seg.index === marker.start) {
64
+ const markerText = text.slice(marker.start, marker.end);
65
+ result.push({
66
+ segment: markerText,
67
+ index: marker.start,
68
+ input: text,
69
+ });
70
+ }
71
+ // Otherwise skip (already merged into the first segment).
72
+ } else {
73
+ result.push(seg);
74
+ }
75
+ }
76
+
77
+ return result;
78
+ }
79
+
80
+ /**
81
+ * Represents a chunk of text for word-wrap layout.
82
+ * Tracks both the text content and its position in the original line.
83
+ */
84
+ export interface TextChunk {
85
+ text: string;
86
+ startIndex: number;
87
+ endIndex: number;
88
+ }
89
+
90
+ /**
91
+ * Split a line into word-wrapped chunks.
92
+ * Wraps at word boundaries when possible, falling back to character-level
93
+ * wrapping for words longer than the available width.
94
+ *
95
+ * @param line - The text line to wrap
96
+ * @param maxWidth - Maximum visible width per chunk
97
+ * @param preSegmented - Optional pre-segmented graphemes (e.g. with paste-marker awareness).
98
+ * When omitted the default Intl.Segmenter is used.
99
+ * @returns Array of chunks with text and position information
100
+ */
101
+ export function wordWrapLine(line: string, maxWidth: number, preSegmented?: Intl.SegmentData[]): TextChunk[] {
102
+ if (!line || maxWidth <= 0) {
103
+ return [{ text: "", startIndex: 0, endIndex: 0 }];
104
+ }
105
+
106
+ const lineWidth = visibleWidth(line);
107
+ if (lineWidth <= maxWidth) {
108
+ return [{ text: line, startIndex: 0, endIndex: line.length }];
109
+ }
110
+
111
+ const chunks: TextChunk[] = [];
112
+ const segments = preSegmented ?? [...baseSegmenter.segment(line)];
113
+
114
+ let currentWidth = 0;
115
+ let chunkStart = 0;
116
+
117
+ // Wrap opportunity: the position after the last whitespace before a non-whitespace
118
+ // grapheme, i.e. where a line break is allowed.
119
+ let wrapOppIndex = -1;
120
+ let wrapOppWidth = 0;
121
+
122
+ for (let i = 0; i < segments.length; i++) {
123
+ const seg = segments[i]!;
124
+ const grapheme = seg.segment;
125
+ const gWidth = visibleWidth(grapheme);
126
+ const charIndex = seg.index;
127
+ const isWs = !isPasteMarker(grapheme) && isWhitespaceChar(grapheme);
128
+
129
+ // Overflow check before advancing.
130
+ if (currentWidth + gWidth > maxWidth) {
131
+ if (wrapOppIndex >= 0 && currentWidth - wrapOppWidth + gWidth <= maxWidth) {
132
+ // Backtrack to last wrap opportunity (the remaining content
133
+ // plus the current grapheme still fits within maxWidth).
134
+ chunks.push({ text: line.slice(chunkStart, wrapOppIndex), startIndex: chunkStart, endIndex: wrapOppIndex });
135
+ chunkStart = wrapOppIndex;
136
+ currentWidth -= wrapOppWidth;
137
+ } else if (chunkStart < charIndex) {
138
+ // No viable wrap opportunity: force-break at current position.
139
+ // This also handles the case where backtracking to a word
140
+ // boundary wouldn't help because the remaining content plus
141
+ // the current grapheme (e.g. a wide character) still exceeds
142
+ // maxWidth.
143
+ chunks.push({ text: line.slice(chunkStart, charIndex), startIndex: chunkStart, endIndex: charIndex });
144
+ chunkStart = charIndex;
145
+ currentWidth = 0;
146
+ }
147
+ wrapOppIndex = -1;
148
+ }
149
+
150
+ if (gWidth > maxWidth) {
151
+ // Single atomic segment wider than maxWidth (e.g. paste marker
152
+ // in a narrow terminal). Re-wrap it at grapheme granularity.
153
+
154
+ // The segment remains logically atomic for cursor
155
+ // movement / editing — the split is purely visual for word-wrap layout.
156
+ const subChunks = wordWrapLine(grapheme, maxWidth);
157
+ for (let j = 0; j < subChunks.length - 1; j++) {
158
+ const sc = subChunks[j]!;
159
+ chunks.push({ text: sc.text, startIndex: charIndex + sc.startIndex, endIndex: charIndex + sc.endIndex });
160
+ }
161
+ const last = subChunks[subChunks.length - 1]!;
162
+ chunkStart = charIndex + last.startIndex;
163
+ currentWidth = visibleWidth(last.text);
164
+ wrapOppIndex = -1;
165
+ continue;
166
+ }
167
+
168
+ // Advance.
169
+ currentWidth += gWidth;
170
+
171
+ // Record wrap opportunity: whitespace followed by non-whitespace.
172
+ // Multiple spaces join (no break between them); the break point is
173
+ // after the last space before the next word.
174
+ const next = segments[i + 1];
175
+ if (isWs && next && (isPasteMarker(next.segment) || !isWhitespaceChar(next.segment))) {
176
+ wrapOppIndex = next.index;
177
+ wrapOppWidth = currentWidth;
178
+ }
179
+ }
180
+
181
+ // Push final chunk.
182
+ chunks.push({ text: line.slice(chunkStart), startIndex: chunkStart, endIndex: line.length });
183
+
184
+ return chunks;
185
+ }
186
+
187
+ // Kitty CSI-u sequences for printable keys, including optional shifted/base codepoints.
188
+ interface EditorState {
189
+ lines: string[];
190
+ cursorLine: number;
191
+ cursorCol: number;
192
+ }
193
+
194
+ interface LayoutLine {
195
+ text: string;
196
+ hasCursor: boolean;
197
+ cursorPos?: number;
198
+ }
199
+
200
+ export interface EditorTheme {
201
+ borderColor: (str: string) => string;
202
+ selectList: SelectListTheme;
203
+ }
204
+
205
+ export interface EditorOptions {
206
+ paddingX?: number;
207
+ autocompleteMaxVisible?: number;
208
+ }
209
+
210
+ const SLASH_COMMAND_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
211
+ minPrimaryColumnWidth: 12,
212
+ maxPrimaryColumnWidth: 32,
213
+ };
214
+
215
+ const ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS = 20;
216
+
217
+ export class Editor implements Component, Focusable {
218
+ private state: EditorState = {
219
+ lines: [""],
220
+ cursorLine: 0,
221
+ cursorCol: 0,
222
+ };
223
+
224
+ /** Focusable interface - set by TUI when focus changes */
225
+ focused: boolean = false;
226
+
227
+ protected tui: TUI;
228
+ private theme: EditorTheme;
229
+ private paddingX: number = 0;
230
+
231
+ // Store last render width for cursor navigation
232
+ private lastWidth: number = 80;
233
+
234
+ // Vertical scrolling support
235
+ private scrollOffset: number = 0;
236
+
237
+ // Border color (can be changed dynamically)
238
+ public borderColor: (str: string) => string;
239
+
240
+ // Autocomplete support
241
+ private autocompleteProvider?: AutocompleteProvider;
242
+ private autocompleteList?: SelectList;
243
+ private autocompleteState: "regular" | "force" | null = null;
244
+ private autocompletePrefix: string = "";
245
+ private autocompleteMaxVisible: number = 5;
246
+ private autocompleteAbort?: AbortController;
247
+ private autocompleteDebounceTimer?: ReturnType<typeof setTimeout>;
248
+ private autocompleteRequestTask: Promise<void> = Promise.resolve();
249
+ private autocompleteStartToken: number = 0;
250
+ private autocompleteRequestId: number = 0;
251
+
252
+ // Paste tracking for large pastes
253
+ private pastes: Map<number, string> = new Map();
254
+ private pasteCounter: number = 0;
255
+
256
+ // Bracketed paste mode buffering
257
+ private pasteBuffer: string = "";
258
+ private isInPaste: boolean = false;
259
+
260
+ // Prompt history for up/down navigation
261
+ private history: string[] = [];
262
+ private historyIndex: number = -1; // -1 = not browsing, 0 = most recent, 1 = older, etc.
263
+
264
+ // Kill ring for Emacs-style kill/yank operations
265
+ private killRing = new KillRing();
266
+ private lastAction: "kill" | "yank" | "type-word" | null = null;
267
+
268
+ // Character jump mode
269
+ private jumpMode: "forward" | "backward" | null = null;
270
+
271
+ // Preferred visual column for vertical cursor movement (sticky column)
272
+ private preferredVisualCol: number | null = null;
273
+
274
+ // Undo support
275
+ private undoStack = new UndoStack<EditorState>();
276
+
277
+ public onSubmit?: (text: string) => void;
278
+ public onChange?: (text: string) => void;
279
+ public disableSubmit: boolean = false;
280
+
281
+ constructor(tui: TUI, theme: EditorTheme, options: EditorOptions = {}) {
282
+ this.tui = tui;
283
+ this.theme = theme;
284
+ this.borderColor = theme.borderColor;
285
+ const paddingX = options.paddingX ?? 0;
286
+ this.paddingX = Number.isFinite(paddingX) ? Math.max(0, Math.floor(paddingX)) : 0;
287
+ const maxVisible = options.autocompleteMaxVisible ?? 5;
288
+ this.autocompleteMaxVisible = Number.isFinite(maxVisible) ? Math.max(3, Math.min(20, Math.floor(maxVisible))) : 5;
289
+ }
290
+
291
+ /** Set of currently valid paste IDs, for marker-aware segmentation. */
292
+ private validPasteIds(): Set<number> {
293
+ return new Set(this.pastes.keys());
294
+ }
295
+
296
+ /** Segment text with paste-marker awareness, only merging markers with valid IDs. */
297
+ private segment(text: string): Iterable<Intl.SegmentData> {
298
+ return segmentWithMarkers(text, this.validPasteIds());
299
+ }
300
+
301
+ getPaddingX(): number {
302
+ return this.paddingX;
303
+ }
304
+
305
+ setPaddingX(padding: number): void {
306
+ const newPadding = Number.isFinite(padding) ? Math.max(0, Math.floor(padding)) : 0;
307
+ if (this.paddingX !== newPadding) {
308
+ this.paddingX = newPadding;
309
+ this.tui.requestRender();
310
+ }
311
+ }
312
+
313
+ getAutocompleteMaxVisible(): number {
314
+ return this.autocompleteMaxVisible;
315
+ }
316
+
317
+ setAutocompleteMaxVisible(maxVisible: number): void {
318
+ const newMaxVisible = Number.isFinite(maxVisible) ? Math.max(3, Math.min(20, Math.floor(maxVisible))) : 5;
319
+ if (this.autocompleteMaxVisible !== newMaxVisible) {
320
+ this.autocompleteMaxVisible = newMaxVisible;
321
+ this.tui.requestRender();
322
+ }
323
+ }
324
+
325
+ setAutocompleteProvider(provider: AutocompleteProvider): void {
326
+ this.cancelAutocomplete();
327
+ this.autocompleteProvider = provider;
328
+ }
329
+
330
+ /**
331
+ * Add a prompt to history for up/down arrow navigation.
332
+ * Called after successful submission.
333
+ */
334
+ addToHistory(text: string): void {
335
+ const trimmed = text.trim();
336
+ if (!trimmed) return;
337
+ // Don't add consecutive duplicates
338
+ if (this.history.length > 0 && this.history[0] === trimmed) return;
339
+ this.history.unshift(trimmed);
340
+ // Limit history size
341
+ if (this.history.length > 100) {
342
+ this.history.pop();
343
+ }
344
+ }
345
+
346
+ private isEditorEmpty(): boolean {
347
+ return this.state.lines.length === 1 && this.state.lines[0] === "";
348
+ }
349
+
350
+ private isOnFirstVisualLine(): boolean {
351
+ const visualLines = this.buildVisualLineMap(this.lastWidth);
352
+ const currentVisualLine = this.findCurrentVisualLine(visualLines);
353
+ return currentVisualLine === 0;
354
+ }
355
+
356
+ private isOnLastVisualLine(): boolean {
357
+ const visualLines = this.buildVisualLineMap(this.lastWidth);
358
+ const currentVisualLine = this.findCurrentVisualLine(visualLines);
359
+ return currentVisualLine === visualLines.length - 1;
360
+ }
361
+
362
+ private navigateHistory(direction: 1 | -1): void {
363
+ this.lastAction = null;
364
+ if (this.history.length === 0) return;
365
+
366
+ const newIndex = this.historyIndex - direction; // Up(-1) increases index, Down(1) decreases
367
+ if (newIndex < -1 || newIndex >= this.history.length) return;
368
+
369
+ // Capture state when first entering history browsing mode
370
+ if (this.historyIndex === -1 && newIndex >= 0) {
371
+ this.pushUndoSnapshot();
372
+ }
373
+
374
+ this.historyIndex = newIndex;
375
+
376
+ if (this.historyIndex === -1) {
377
+ // Returned to "current" state - clear editor
378
+ this.setTextInternal("");
379
+ } else {
380
+ this.setTextInternal(this.history[this.historyIndex] || "");
381
+ }
382
+ }
383
+
384
+ /** Internal setText that doesn't reset history state - used by navigateHistory */
385
+ private setTextInternal(text: string): void {
386
+ const lines = text.split("\n");
387
+ this.state.lines = lines.length === 0 ? [""] : lines;
388
+ this.state.cursorLine = this.state.lines.length - 1;
389
+ this.setCursorCol(this.state.lines[this.state.cursorLine]?.length || 0);
390
+ // Reset scroll - render() will adjust to show cursor
391
+ this.scrollOffset = 0;
392
+
393
+ if (this.onChange) {
394
+ this.onChange(this.getText());
395
+ }
396
+ }
397
+
398
+ invalidate(): void {
399
+ // No cached state to invalidate currently
400
+ }
401
+
402
+ render(width: number): string[] {
403
+ const maxPadding = Math.max(0, Math.floor((width - 1) / 2));
404
+ const paddingX = Math.min(this.paddingX, maxPadding);
405
+ const contentWidth = Math.max(1, width - paddingX * 2);
406
+
407
+ // Layout width: with padding the cursor can overflow into it,
408
+ // without padding we reserve 1 column for the cursor.
409
+ const layoutWidth = Math.max(1, contentWidth - (paddingX ? 0 : 1));
410
+
411
+ // Store for cursor navigation (must match wrapping width)
412
+ this.lastWidth = layoutWidth;
413
+
414
+ const horizontal = this.borderColor("─");
415
+
416
+ // Layout the text
417
+ const layoutLines = this.layoutText(layoutWidth);
418
+
419
+ // Calculate max visible lines: 30% of terminal height, minimum 5 lines
420
+ const terminalRows = this.tui.terminal.rows;
421
+ const maxVisibleLines = Math.max(5, Math.floor(terminalRows * 0.3));
422
+
423
+ // Find the cursor line index in layoutLines
424
+ let cursorLineIndex = layoutLines.findIndex((line) => line.hasCursor);
425
+ if (cursorLineIndex === -1) cursorLineIndex = 0;
426
+
427
+ // Adjust scroll offset to keep cursor visible
428
+ if (cursorLineIndex < this.scrollOffset) {
429
+ this.scrollOffset = cursorLineIndex;
430
+ } else if (cursorLineIndex >= this.scrollOffset + maxVisibleLines) {
431
+ this.scrollOffset = cursorLineIndex - maxVisibleLines + 1;
432
+ }
433
+
434
+ // Clamp scroll offset to valid range
435
+ const maxScrollOffset = Math.max(0, layoutLines.length - maxVisibleLines);
436
+ this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxScrollOffset));
437
+
438
+ // Get visible lines slice
439
+ const visibleLines = layoutLines.slice(this.scrollOffset, this.scrollOffset + maxVisibleLines);
440
+
441
+ const result: string[] = [];
442
+ const leftPadding = " ".repeat(paddingX);
443
+ const rightPadding = leftPadding;
444
+
445
+ // Render top border (with scroll indicator if scrolled down)
446
+ if (this.scrollOffset > 0) {
447
+ const indicator = `─── ↑ ${this.scrollOffset} more `;
448
+ const remaining = width - visibleWidth(indicator);
449
+ if (remaining >= 0) {
450
+ result.push(this.borderColor(indicator + "─".repeat(remaining)));
451
+ } else {
452
+ result.push(this.borderColor(truncateToWidth(indicator, width)));
453
+ }
454
+ } else {
455
+ result.push(horizontal.repeat(width));
456
+ }
457
+
458
+ // Render each visible layout line
459
+ // Emit hardware cursor marker only when focused and not showing autocomplete
460
+ const emitCursorMarker = this.focused && !this.autocompleteState;
461
+
462
+ for (const layoutLine of visibleLines) {
463
+ let displayText = layoutLine.text;
464
+ let lineVisibleWidth = visibleWidth(layoutLine.text);
465
+ let cursorInPadding = false;
466
+
467
+ // Add cursor if this line has it
468
+ if (layoutLine.hasCursor && layoutLine.cursorPos !== undefined) {
469
+ const before = displayText.slice(0, layoutLine.cursorPos);
470
+ const after = displayText.slice(layoutLine.cursorPos);
471
+
472
+ // Hardware cursor marker (zero-width, emitted before fake cursor for IME positioning)
473
+ const marker = emitCursorMarker ? CURSOR_MARKER : "";
474
+
475
+ if (after.length > 0) {
476
+ // Cursor is on a character (grapheme) - replace it with highlighted version
477
+ // Get the first grapheme from 'after'
478
+ const afterGraphemes = [...this.segment(after)];
479
+ const firstGrapheme = afterGraphemes[0]?.segment || "";
480
+ const restAfter = after.slice(firstGrapheme.length);
481
+ const cursor = `\x1b[7m${firstGrapheme}\x1b[0m`;
482
+ displayText = before + marker + cursor + restAfter;
483
+ // lineVisibleWidth stays the same - we're replacing, not adding
484
+ } else {
485
+ // Cursor is at the end - add highlighted space
486
+ const cursor = "\x1b[7m \x1b[0m";
487
+ displayText = before + marker + cursor;
488
+ lineVisibleWidth = lineVisibleWidth + 1;
489
+ // If cursor overflows content width into the padding, flag it
490
+ if (lineVisibleWidth > contentWidth && paddingX > 0) {
491
+ cursorInPadding = true;
492
+ }
493
+ }
494
+ }
495
+
496
+ // Calculate padding based on actual visible width
497
+ const padding = " ".repeat(Math.max(0, contentWidth - lineVisibleWidth));
498
+ const lineRightPadding = cursorInPadding ? rightPadding.slice(1) : rightPadding;
499
+
500
+ // Render the line (no side borders, just horizontal lines above and below)
501
+ result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`);
502
+ }
503
+
504
+ // Render bottom border (with scroll indicator if more content below)
505
+ const linesBelow = layoutLines.length - (this.scrollOffset + visibleLines.length);
506
+ if (linesBelow > 0) {
507
+ const indicator = `─── ↓ ${linesBelow} more `;
508
+ const remaining = width - visibleWidth(indicator);
509
+ result.push(this.borderColor(indicator + "─".repeat(Math.max(0, remaining))));
510
+ } else {
511
+ result.push(horizontal.repeat(width));
512
+ }
513
+
514
+ // Add autocomplete list if active
515
+ if (this.autocompleteState && this.autocompleteList) {
516
+ const autocompleteResult = this.autocompleteList.render(contentWidth);
517
+ for (const line of autocompleteResult) {
518
+ const lineWidth = visibleWidth(line);
519
+ const linePadding = " ".repeat(Math.max(0, contentWidth - lineWidth));
520
+ result.push(`${leftPadding}${line}${linePadding}${rightPadding}`);
521
+ }
522
+ }
523
+
524
+ return result;
525
+ }
526
+
527
+ handleInput(data: string): void {
528
+ const kb = getKeybindings();
529
+
530
+ // Handle character jump mode (awaiting next character to jump to)
531
+ if (this.jumpMode !== null) {
532
+ // Cancel if the hotkey is pressed again
533
+ if (kb.matches(data, "tui.editor.jumpForward") || kb.matches(data, "tui.editor.jumpBackward")) {
534
+ this.jumpMode = null;
535
+ return;
536
+ }
537
+
538
+ if (data.charCodeAt(0) >= 32) {
539
+ // Printable character - perform the jump
540
+ const direction = this.jumpMode;
541
+ this.jumpMode = null;
542
+ this.jumpToChar(data, direction);
543
+ return;
544
+ }
545
+
546
+ // Control character - cancel and fall through to normal handling
547
+ this.jumpMode = null;
548
+ }
549
+
550
+ // Handle bracketed paste mode
551
+ if (data.includes("\x1b[200~")) {
552
+ this.isInPaste = true;
553
+ this.pasteBuffer = "";
554
+ data = data.replace("\x1b[200~", "");
555
+ }
556
+
557
+ if (this.isInPaste) {
558
+ this.pasteBuffer += data;
559
+ const endIndex = this.pasteBuffer.indexOf("\x1b[201~");
560
+ if (endIndex !== -1) {
561
+ const pasteContent = this.pasteBuffer.substring(0, endIndex);
562
+ if (pasteContent.length > 0) {
563
+ this.handlePaste(pasteContent);
564
+ }
565
+ this.isInPaste = false;
566
+ const remaining = this.pasteBuffer.substring(endIndex + 6);
567
+ this.pasteBuffer = "";
568
+ if (remaining.length > 0) {
569
+ this.handleInput(remaining);
570
+ }
571
+ return;
572
+ }
573
+ return;
574
+ }
575
+
576
+ // Ctrl+C - let parent handle (exit/clear)
577
+ if (kb.matches(data, "tui.input.copy")) {
578
+ return;
579
+ }
580
+
581
+ // Undo
582
+ if (kb.matches(data, "tui.editor.undo")) {
583
+ this.undo();
584
+ return;
585
+ }
586
+
587
+ // Handle autocomplete mode
588
+ if (this.autocompleteState && this.autocompleteList) {
589
+ if (kb.matches(data, "tui.select.cancel")) {
590
+ this.cancelAutocomplete();
591
+ return;
592
+ }
593
+
594
+ if (kb.matches(data, "tui.select.up") || kb.matches(data, "tui.select.down")) {
595
+ this.autocompleteList.handleInput(data);
596
+ return;
597
+ }
598
+
599
+ if (kb.matches(data, "tui.input.tab")) {
600
+ const selected = this.autocompleteList.getSelectedItem();
601
+ if (selected && this.autocompleteProvider) {
602
+ this.pushUndoSnapshot();
603
+ this.lastAction = null;
604
+ const result = this.autocompleteProvider.applyCompletion(
605
+ this.state.lines,
606
+ this.state.cursorLine,
607
+ this.state.cursorCol,
608
+ selected,
609
+ this.autocompletePrefix,
610
+ );
611
+ this.state.lines = result.lines;
612
+ this.state.cursorLine = result.cursorLine;
613
+ this.setCursorCol(result.cursorCol);
614
+ this.cancelAutocomplete();
615
+ if (this.onChange) this.onChange(this.getText());
616
+ }
617
+ return;
618
+ }
619
+
620
+ if (kb.matches(data, "tui.select.confirm")) {
621
+ const selected = this.autocompleteList.getSelectedItem();
622
+ if (selected && this.autocompleteProvider) {
623
+ this.pushUndoSnapshot();
624
+ this.lastAction = null;
625
+ const result = this.autocompleteProvider.applyCompletion(
626
+ this.state.lines,
627
+ this.state.cursorLine,
628
+ this.state.cursorCol,
629
+ selected,
630
+ this.autocompletePrefix,
631
+ );
632
+ this.state.lines = result.lines;
633
+ this.state.cursorLine = result.cursorLine;
634
+ this.setCursorCol(result.cursorCol);
635
+
636
+ if (this.autocompletePrefix.startsWith("/")) {
637
+ this.cancelAutocomplete();
638
+ // Fall through to submit
639
+ } else {
640
+ this.cancelAutocomplete();
641
+ if (this.onChange) this.onChange(this.getText());
642
+ return;
643
+ }
644
+ }
645
+ }
646
+ }
647
+
648
+ // Tab - trigger completion
649
+ if (kb.matches(data, "tui.input.tab") && !this.autocompleteState) {
650
+ this.handleTabCompletion();
651
+ return;
652
+ }
653
+
654
+ // Deletion actions
655
+ if (kb.matches(data, "tui.editor.deleteToLineEnd")) {
656
+ this.deleteToEndOfLine();
657
+ return;
658
+ }
659
+ if (kb.matches(data, "tui.editor.deleteToLineStart")) {
660
+ this.deleteToStartOfLine();
661
+ return;
662
+ }
663
+ if (kb.matches(data, "tui.editor.deleteWordBackward")) {
664
+ this.deleteWordBackwards();
665
+ return;
666
+ }
667
+ if (kb.matches(data, "tui.editor.deleteWordForward")) {
668
+ this.deleteWordForward();
669
+ return;
670
+ }
671
+ if (kb.matches(data, "tui.editor.deleteCharBackward") || matchesKey(data, "shift+backspace")) {
672
+ this.handleBackspace();
673
+ return;
674
+ }
675
+ if (kb.matches(data, "tui.editor.deleteCharForward") || matchesKey(data, "shift+delete")) {
676
+ this.handleForwardDelete();
677
+ return;
678
+ }
679
+
680
+ // Kill ring actions
681
+ if (kb.matches(data, "tui.editor.yank")) {
682
+ this.yank();
683
+ return;
684
+ }
685
+ if (kb.matches(data, "tui.editor.yankPop")) {
686
+ this.yankPop();
687
+ return;
688
+ }
689
+
690
+ // Cursor movement actions
691
+ if (kb.matches(data, "tui.editor.cursorLineStart")) {
692
+ this.moveToLineStart();
693
+ return;
694
+ }
695
+ if (kb.matches(data, "tui.editor.cursorLineEnd")) {
696
+ this.moveToLineEnd();
697
+ return;
698
+ }
699
+ if (kb.matches(data, "tui.editor.cursorWordLeft")) {
700
+ this.moveWordBackwards();
701
+ return;
702
+ }
703
+ if (kb.matches(data, "tui.editor.cursorWordRight")) {
704
+ this.moveWordForwards();
705
+ return;
706
+ }
707
+
708
+ // New line
709
+ if (
710
+ kb.matches(data, "tui.input.newLine") ||
711
+ (data.charCodeAt(0) === 10 && data.length > 1) ||
712
+ data === "\x1b\r" ||
713
+ data === "\x1b[13;2~" ||
714
+ (data.length > 1 && data.includes("\x1b") && data.includes("\r")) ||
715
+ (data === "\n" && data.length === 1)
716
+ ) {
717
+ if (this.shouldSubmitOnBackslashEnter(data, kb)) {
718
+ this.handleBackspace();
719
+ this.submitValue();
720
+ return;
721
+ }
722
+ this.addNewLine();
723
+ return;
724
+ }
725
+
726
+ // Submit (Enter)
727
+ if (kb.matches(data, "tui.input.submit")) {
728
+ if (this.disableSubmit) return;
729
+
730
+ // Workaround for terminals without Shift+Enter support:
731
+ // If char before cursor is \, delete it and insert newline instead of submitting.
732
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
733
+ if (this.state.cursorCol > 0 && currentLine[this.state.cursorCol - 1] === "\\") {
734
+ this.handleBackspace();
735
+ this.addNewLine();
736
+ return;
737
+ }
738
+
739
+ this.submitValue();
740
+ return;
741
+ }
742
+
743
+ // Arrow key navigation (with history support)
744
+ if (kb.matches(data, "tui.editor.cursorUp")) {
745
+ if (this.isEditorEmpty()) {
746
+ this.navigateHistory(-1);
747
+ } else if (this.historyIndex > -1 && this.isOnFirstVisualLine()) {
748
+ this.navigateHistory(-1);
749
+ } else if (this.isOnFirstVisualLine()) {
750
+ // Already at top - jump to start of line
751
+ this.moveToLineStart();
752
+ } else {
753
+ this.moveCursor(-1, 0);
754
+ }
755
+ return;
756
+ }
757
+ if (kb.matches(data, "tui.editor.cursorDown")) {
758
+ if (this.historyIndex > -1 && this.isOnLastVisualLine()) {
759
+ this.navigateHistory(1);
760
+ } else if (this.isOnLastVisualLine()) {
761
+ // Already at bottom - jump to end of line
762
+ this.moveToLineEnd();
763
+ } else {
764
+ this.moveCursor(1, 0);
765
+ }
766
+ return;
767
+ }
768
+ if (kb.matches(data, "tui.editor.cursorRight")) {
769
+ this.moveCursor(0, 1);
770
+ return;
771
+ }
772
+ if (kb.matches(data, "tui.editor.cursorLeft")) {
773
+ this.moveCursor(0, -1);
774
+ return;
775
+ }
776
+
777
+ // Page up/down - scroll by page and move cursor
778
+ if (kb.matches(data, "tui.editor.pageUp")) {
779
+ this.pageScroll(-1);
780
+ return;
781
+ }
782
+ if (kb.matches(data, "tui.editor.pageDown")) {
783
+ this.pageScroll(1);
784
+ return;
785
+ }
786
+
787
+ // Character jump mode triggers
788
+ if (kb.matches(data, "tui.editor.jumpForward")) {
789
+ this.jumpMode = "forward";
790
+ return;
791
+ }
792
+ if (kb.matches(data, "tui.editor.jumpBackward")) {
793
+ this.jumpMode = "backward";
794
+ return;
795
+ }
796
+
797
+ // Shift+Space - insert regular space
798
+ if (matchesKey(data, "shift+space")) {
799
+ this.insertCharacter(" ");
800
+ return;
801
+ }
802
+
803
+ const kittyPrintable = decodeKittyPrintable(data);
804
+ if (kittyPrintable !== undefined) {
805
+ this.insertCharacter(kittyPrintable);
806
+ return;
807
+ }
808
+
809
+ // Regular characters
810
+ if (data.charCodeAt(0) >= 32) {
811
+ this.insertCharacter(data);
812
+ }
813
+ }
814
+
815
+ private layoutText(contentWidth: number): LayoutLine[] {
816
+ const layoutLines: LayoutLine[] = [];
817
+
818
+ if (this.state.lines.length === 0 || (this.state.lines.length === 1 && this.state.lines[0] === "")) {
819
+ // Empty editor
820
+ layoutLines.push({
821
+ text: "",
822
+ hasCursor: true,
823
+ cursorPos: 0,
824
+ });
825
+ return layoutLines;
826
+ }
827
+
828
+ // Process each logical line
829
+ for (let i = 0; i < this.state.lines.length; i++) {
830
+ const line = this.state.lines[i] || "";
831
+ const isCurrentLine = i === this.state.cursorLine;
832
+ const lineVisibleWidth = visibleWidth(line);
833
+
834
+ if (lineVisibleWidth <= contentWidth) {
835
+ // Line fits in one layout line
836
+ if (isCurrentLine) {
837
+ layoutLines.push({
838
+ text: line,
839
+ hasCursor: true,
840
+ cursorPos: this.state.cursorCol,
841
+ });
842
+ } else {
843
+ layoutLines.push({
844
+ text: line,
845
+ hasCursor: false,
846
+ });
847
+ }
848
+ } else {
849
+ // Line needs wrapping - use word-aware wrapping
850
+ const chunks = wordWrapLine(line, contentWidth, [...this.segment(line)]);
851
+
852
+ for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
853
+ const chunk = chunks[chunkIndex];
854
+ if (!chunk) continue;
855
+
856
+ const cursorPos = this.state.cursorCol;
857
+ const isLastChunk = chunkIndex === chunks.length - 1;
858
+
859
+ // Determine if cursor is in this chunk
860
+ // For word-wrapped chunks, we need to handle the case where
861
+ // cursor might be in trimmed whitespace at end of chunk
862
+ let hasCursorInChunk = false;
863
+ let adjustedCursorPos = 0;
864
+
865
+ if (isCurrentLine) {
866
+ if (isLastChunk) {
867
+ // Last chunk: cursor belongs here if >= startIndex
868
+ hasCursorInChunk = cursorPos >= chunk.startIndex;
869
+ adjustedCursorPos = cursorPos - chunk.startIndex;
870
+ } else {
871
+ // Non-last chunk: cursor belongs here if in range [startIndex, endIndex)
872
+ // But we need to handle the visual position in the trimmed text
873
+ hasCursorInChunk = cursorPos >= chunk.startIndex && cursorPos < chunk.endIndex;
874
+ if (hasCursorInChunk) {
875
+ adjustedCursorPos = cursorPos - chunk.startIndex;
876
+ // Clamp to text length (in case cursor was in trimmed whitespace)
877
+ if (adjustedCursorPos > chunk.text.length) {
878
+ adjustedCursorPos = chunk.text.length;
879
+ }
880
+ }
881
+ }
882
+ }
883
+
884
+ if (hasCursorInChunk) {
885
+ layoutLines.push({
886
+ text: chunk.text,
887
+ hasCursor: true,
888
+ cursorPos: adjustedCursorPos,
889
+ });
890
+ } else {
891
+ layoutLines.push({
892
+ text: chunk.text,
893
+ hasCursor: false,
894
+ });
895
+ }
896
+ }
897
+ }
898
+ }
899
+
900
+ return layoutLines;
901
+ }
902
+
903
+ getText(): string {
904
+ return this.state.lines.join("\n");
905
+ }
906
+
907
+ private expandPasteMarkers(text: string): string {
908
+ let result = text;
909
+ for (const [pasteId, pasteContent] of this.pastes) {
910
+ const markerRegex = new RegExp(`\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`, "g");
911
+ result = result.replace(markerRegex, () => pasteContent);
912
+ }
913
+ return result;
914
+ }
915
+
916
+ /**
917
+ * Get text with paste markers expanded to their actual content.
918
+ * Use this when you need the full content (e.g., for external editor).
919
+ */
920
+ getExpandedText(): string {
921
+ return this.expandPasteMarkers(this.state.lines.join("\n"));
922
+ }
923
+
924
+ getLines(): string[] {
925
+ return [...this.state.lines];
926
+ }
927
+
928
+ getCursor(): { line: number; col: number } {
929
+ return { line: this.state.cursorLine, col: this.state.cursorCol };
930
+ }
931
+
932
+ setText(text: string): void {
933
+ this.cancelAutocomplete();
934
+ this.lastAction = null;
935
+ this.historyIndex = -1; // Exit history browsing mode
936
+ const normalized = this.normalizeText(text);
937
+ // Push undo snapshot if content differs (makes programmatic changes undoable)
938
+ if (this.getText() !== normalized) {
939
+ this.pushUndoSnapshot();
940
+ }
941
+ this.setTextInternal(normalized);
942
+ }
943
+
944
+ /**
945
+ * Insert text at the current cursor position.
946
+ * Used for programmatic insertion (e.g., clipboard image markers).
947
+ * This is atomic for undo - single undo restores entire pre-insert state.
948
+ */
949
+ insertTextAtCursor(text: string): void {
950
+ if (!text) return;
951
+ this.cancelAutocomplete();
952
+ this.pushUndoSnapshot();
953
+ this.lastAction = null;
954
+ this.historyIndex = -1;
955
+ this.insertTextAtCursorInternal(text);
956
+ }
957
+
958
+ /**
959
+ * Normalize text for editor storage:
960
+ * - Normalize line endings (\r\n and \r -> \n)
961
+ * - Expand tabs to 4 spaces
962
+ */
963
+ private normalizeText(text: string): string {
964
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\t/g, " ");
965
+ }
966
+
967
+ /**
968
+ * Internal text insertion at cursor. Handles single and multi-line text.
969
+ * Does not push undo snapshots or trigger autocomplete - caller is responsible.
970
+ * Normalizes line endings and calls onChange once at the end.
971
+ */
972
+ private insertTextAtCursorInternal(text: string): void {
973
+ if (!text) return;
974
+
975
+ // Normalize line endings and tabs
976
+ const normalized = this.normalizeText(text);
977
+ const insertedLines = normalized.split("\n");
978
+
979
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
980
+ const beforeCursor = currentLine.slice(0, this.state.cursorCol);
981
+ const afterCursor = currentLine.slice(this.state.cursorCol);
982
+
983
+ if (insertedLines.length === 1) {
984
+ // Single line - insert at cursor position
985
+ this.state.lines[this.state.cursorLine] = beforeCursor + normalized + afterCursor;
986
+ this.setCursorCol(this.state.cursorCol + normalized.length);
987
+ } else {
988
+ // Multi-line insertion
989
+ this.state.lines = [
990
+ // All lines before current line
991
+ ...this.state.lines.slice(0, this.state.cursorLine),
992
+
993
+ // The first inserted line merged with text before cursor
994
+ beforeCursor + insertedLines[0],
995
+
996
+ // All middle inserted lines
997
+ ...insertedLines.slice(1, -1),
998
+
999
+ // The last inserted line with text after cursor
1000
+ insertedLines[insertedLines.length - 1] + afterCursor,
1001
+
1002
+ // All lines after current line
1003
+ ...this.state.lines.slice(this.state.cursorLine + 1),
1004
+ ];
1005
+
1006
+ this.state.cursorLine += insertedLines.length - 1;
1007
+ this.setCursorCol((insertedLines[insertedLines.length - 1] || "").length);
1008
+ }
1009
+
1010
+ if (this.onChange) {
1011
+ this.onChange(this.getText());
1012
+ }
1013
+ }
1014
+
1015
+ // All the editor methods from before...
1016
+ private insertCharacter(char: string, skipUndoCoalescing?: boolean): void {
1017
+ this.historyIndex = -1; // Exit history browsing mode
1018
+
1019
+ // Undo coalescing (fish-style):
1020
+ // - Consecutive word chars coalesce into one undo unit
1021
+ // - Space captures state before itself (so undo removes space+following word together)
1022
+ // - Each space is separately undoable
1023
+ // Skip coalescing when called from atomic operations (e.g., handlePaste)
1024
+ if (!skipUndoCoalescing) {
1025
+ if (isWhitespaceChar(char) || this.lastAction !== "type-word") {
1026
+ this.pushUndoSnapshot();
1027
+ }
1028
+ this.lastAction = "type-word";
1029
+ }
1030
+
1031
+ const line = this.state.lines[this.state.cursorLine] || "";
1032
+
1033
+ const before = line.slice(0, this.state.cursorCol);
1034
+ const after = line.slice(this.state.cursorCol);
1035
+
1036
+ this.state.lines[this.state.cursorLine] = before + char + after;
1037
+ this.setCursorCol(this.state.cursorCol + char.length);
1038
+
1039
+ if (this.onChange) {
1040
+ this.onChange(this.getText());
1041
+ }
1042
+
1043
+ // Check if we should trigger or update autocomplete
1044
+ if (!this.autocompleteState) {
1045
+ // Auto-trigger for "/" at the start of a line (slash commands)
1046
+ if (char === "/" && this.isAtStartOfMessage()) {
1047
+ this.tryTriggerAutocomplete();
1048
+ }
1049
+ // Auto-trigger for "@" file reference (fuzzy search)
1050
+ else if (char === "@") {
1051
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1052
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
1053
+ // Only trigger if @ is after whitespace or at start of line
1054
+ const charBeforeAt = textBeforeCursor[textBeforeCursor.length - 2];
1055
+ if (textBeforeCursor.length === 1 || charBeforeAt === " " || charBeforeAt === "\t") {
1056
+ this.tryTriggerAutocomplete();
1057
+ }
1058
+ }
1059
+ // Also auto-trigger when typing letters in a slash command context
1060
+ else if (/[a-zA-Z0-9.\-_]/.test(char)) {
1061
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1062
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
1063
+ // Check if we're in a slash command (with or without space for arguments)
1064
+ if (this.isInSlashCommandContext(textBeforeCursor)) {
1065
+ this.tryTriggerAutocomplete();
1066
+ }
1067
+ // Check if we're in an @ file reference context
1068
+ else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
1069
+ this.tryTriggerAutocomplete();
1070
+ }
1071
+ }
1072
+ } else {
1073
+ this.updateAutocomplete();
1074
+ }
1075
+ }
1076
+
1077
+ private handlePaste(pastedText: string): void {
1078
+ this.cancelAutocomplete();
1079
+ this.historyIndex = -1; // Exit history browsing mode
1080
+ this.lastAction = null;
1081
+
1082
+ this.pushUndoSnapshot();
1083
+
1084
+ // Clean the pasted text: normalize line endings, expand tabs
1085
+ const cleanText = this.normalizeText(pastedText);
1086
+
1087
+ // Filter out non-printable characters except newlines
1088
+ let filteredText = cleanText
1089
+ .split("")
1090
+ .filter((char) => char === "\n" || char.charCodeAt(0) >= 32)
1091
+ .join("");
1092
+
1093
+ // If pasting a file path (starts with /, ~, or .) and the character before
1094
+ // the cursor is a word character, prepend a space for better readability
1095
+ if (/^[/~.]/.test(filteredText)) {
1096
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1097
+ const charBeforeCursor = this.state.cursorCol > 0 ? currentLine[this.state.cursorCol - 1] : "";
1098
+ if (charBeforeCursor && /\w/.test(charBeforeCursor)) {
1099
+ filteredText = ` ${filteredText}`;
1100
+ }
1101
+ }
1102
+
1103
+ // Split into lines to check for large paste
1104
+ const pastedLines = filteredText.split("\n");
1105
+
1106
+ // Check if this is a large paste (> 10 lines or > 1000 characters)
1107
+ const totalChars = filteredText.length;
1108
+ if (pastedLines.length > 10 || totalChars > 1000) {
1109
+ // Store the paste and insert a marker
1110
+ this.pasteCounter++;
1111
+ const pasteId = this.pasteCounter;
1112
+ this.pastes.set(pasteId, filteredText);
1113
+
1114
+ // Insert marker like "[paste #1 +123 lines]" or "[paste #1 1234 chars]"
1115
+ const marker =
1116
+ pastedLines.length > 10
1117
+ ? `[paste #${pasteId} +${pastedLines.length} lines]`
1118
+ : `[paste #${pasteId} ${totalChars} chars]`;
1119
+ this.insertTextAtCursorInternal(marker);
1120
+ return;
1121
+ }
1122
+
1123
+ if (pastedLines.length === 1) {
1124
+ // Single line - insert atomically (do not trigger autocomplete during paste)
1125
+ this.insertTextAtCursorInternal(filteredText);
1126
+ return;
1127
+ }
1128
+
1129
+ // Multi-line paste - use direct state manipulation
1130
+ this.insertTextAtCursorInternal(filteredText);
1131
+ }
1132
+
1133
+ private addNewLine(): void {
1134
+ this.cancelAutocomplete();
1135
+ this.historyIndex = -1; // Exit history browsing mode
1136
+ this.lastAction = null;
1137
+
1138
+ this.pushUndoSnapshot();
1139
+
1140
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1141
+
1142
+ const before = currentLine.slice(0, this.state.cursorCol);
1143
+ const after = currentLine.slice(this.state.cursorCol);
1144
+
1145
+ // Split current line
1146
+ this.state.lines[this.state.cursorLine] = before;
1147
+ this.state.lines.splice(this.state.cursorLine + 1, 0, after);
1148
+
1149
+ // Move cursor to start of new line
1150
+ this.state.cursorLine++;
1151
+ this.setCursorCol(0);
1152
+
1153
+ if (this.onChange) {
1154
+ this.onChange(this.getText());
1155
+ }
1156
+ }
1157
+
1158
+ private shouldSubmitOnBackslashEnter(data: string, kb: ReturnType<typeof getKeybindings>): boolean {
1159
+ if (this.disableSubmit) return false;
1160
+ if (!matchesKey(data, "enter")) return false;
1161
+ const submitKeys = kb.getKeys("tui.input.submit");
1162
+ const hasShiftEnter = submitKeys.includes("shift+enter") || submitKeys.includes("shift+return");
1163
+ if (!hasShiftEnter) return false;
1164
+
1165
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1166
+ return this.state.cursorCol > 0 && currentLine[this.state.cursorCol - 1] === "\\";
1167
+ }
1168
+
1169
+ private submitValue(): void {
1170
+ this.cancelAutocomplete();
1171
+ const result = this.expandPasteMarkers(this.state.lines.join("\n")).trim();
1172
+
1173
+ this.state = { lines: [""], cursorLine: 0, cursorCol: 0 };
1174
+ this.pastes.clear();
1175
+ this.pasteCounter = 0;
1176
+ this.historyIndex = -1;
1177
+ this.scrollOffset = 0;
1178
+ this.undoStack.clear();
1179
+ this.lastAction = null;
1180
+
1181
+ if (this.onChange) this.onChange("");
1182
+ if (this.onSubmit) this.onSubmit(result);
1183
+ }
1184
+
1185
+ private handleBackspace(): void {
1186
+ this.historyIndex = -1; // Exit history browsing mode
1187
+ this.lastAction = null;
1188
+
1189
+ if (this.state.cursorCol > 0) {
1190
+ this.pushUndoSnapshot();
1191
+
1192
+ // Delete grapheme before cursor (handles emojis, combining characters, etc.)
1193
+ const line = this.state.lines[this.state.cursorLine] || "";
1194
+ const beforeCursor = line.slice(0, this.state.cursorCol);
1195
+
1196
+ // Find the last grapheme in the text before cursor
1197
+ const graphemes = [...this.segment(beforeCursor)];
1198
+ const lastGrapheme = graphemes[graphemes.length - 1];
1199
+ const graphemeLength = lastGrapheme ? lastGrapheme.segment.length : 1;
1200
+
1201
+ const before = line.slice(0, this.state.cursorCol - graphemeLength);
1202
+ const after = line.slice(this.state.cursorCol);
1203
+
1204
+ this.state.lines[this.state.cursorLine] = before + after;
1205
+ this.setCursorCol(this.state.cursorCol - graphemeLength);
1206
+ } else if (this.state.cursorLine > 0) {
1207
+ this.pushUndoSnapshot();
1208
+
1209
+ // Merge with previous line
1210
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1211
+ const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
1212
+
1213
+ this.state.lines[this.state.cursorLine - 1] = previousLine + currentLine;
1214
+ this.state.lines.splice(this.state.cursorLine, 1);
1215
+
1216
+ this.state.cursorLine--;
1217
+ this.setCursorCol(previousLine.length);
1218
+ }
1219
+
1220
+ if (this.onChange) {
1221
+ this.onChange(this.getText());
1222
+ }
1223
+
1224
+ // Update or re-trigger autocomplete after backspace
1225
+ if (this.autocompleteState) {
1226
+ this.updateAutocomplete();
1227
+ } else {
1228
+ // If autocomplete was cancelled (no matches), re-trigger if we're in a completable context
1229
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1230
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
1231
+ // Slash command context
1232
+ if (this.isInSlashCommandContext(textBeforeCursor)) {
1233
+ this.tryTriggerAutocomplete();
1234
+ }
1235
+ // @ file reference context
1236
+ else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
1237
+ this.tryTriggerAutocomplete();
1238
+ }
1239
+ }
1240
+ }
1241
+
1242
+ /**
1243
+ * Set cursor column and clear preferredVisualCol.
1244
+ * Use this for all non-vertical cursor movements to reset sticky column behavior.
1245
+ */
1246
+ private setCursorCol(col: number): void {
1247
+ this.state.cursorCol = col;
1248
+ this.preferredVisualCol = null;
1249
+ }
1250
+
1251
+ /**
1252
+ * Move cursor to a target visual line, applying sticky column logic.
1253
+ * Shared by moveCursor() and pageScroll().
1254
+ */
1255
+ private moveToVisualLine(
1256
+ visualLines: Array<{ logicalLine: number; startCol: number; length: number }>,
1257
+ currentVisualLine: number,
1258
+ targetVisualLine: number,
1259
+ ): void {
1260
+ const currentVL = visualLines[currentVisualLine];
1261
+ const targetVL = visualLines[targetVisualLine];
1262
+
1263
+ if (currentVL && targetVL) {
1264
+ const currentVisualCol = this.state.cursorCol - currentVL.startCol;
1265
+
1266
+ // For non-last segments, clamp to length-1 to stay within the segment
1267
+ const isLastSourceSegment =
1268
+ currentVisualLine === visualLines.length - 1 ||
1269
+ visualLines[currentVisualLine + 1]?.logicalLine !== currentVL.logicalLine;
1270
+ const sourceMaxVisualCol = isLastSourceSegment ? currentVL.length : Math.max(0, currentVL.length - 1);
1271
+
1272
+ const isLastTargetSegment =
1273
+ targetVisualLine === visualLines.length - 1 ||
1274
+ visualLines[targetVisualLine + 1]?.logicalLine !== targetVL.logicalLine;
1275
+ const targetMaxVisualCol = isLastTargetSegment ? targetVL.length : Math.max(0, targetVL.length - 1);
1276
+
1277
+ const moveToVisualCol = this.computeVerticalMoveColumn(
1278
+ currentVisualCol,
1279
+ sourceMaxVisualCol,
1280
+ targetMaxVisualCol,
1281
+ );
1282
+
1283
+ // Set cursor position
1284
+ this.state.cursorLine = targetVL.logicalLine;
1285
+ const targetCol = targetVL.startCol + moveToVisualCol;
1286
+ const logicalLine = this.state.lines[targetVL.logicalLine] || "";
1287
+ this.state.cursorCol = Math.min(targetCol, logicalLine.length);
1288
+
1289
+ // Snap cursor to atomic segment boundary (e.g. paste markers)
1290
+ // so the cursor never lands in the middle of a multi-grapheme unit.
1291
+ // Single-grapheme segments don't need snapping.
1292
+ const segments = [...this.segment(logicalLine)];
1293
+ for (const seg of segments) {
1294
+ if (seg.index > this.state.cursorCol) break;
1295
+ if (seg.segment.length <= 1) continue;
1296
+ if (this.state.cursorCol < seg.index + seg.segment.length) {
1297
+ // jump to the start of the segment when moving up, to the end when moving down.
1298
+ this.state.cursorCol = currentVisualLine > targetVisualLine ? seg.index : seg.index + seg.segment.length;
1299
+ break;
1300
+ }
1301
+ }
1302
+ }
1303
+ }
1304
+
1305
+ /**
1306
+ * Compute the target visual column for vertical cursor movement.
1307
+ * Implements the sticky column decision table:
1308
+ *
1309
+ * | P | S | T | U | Scenario | Set Preferred | Move To |
1310
+ * |---|---|---|---| ---------------------------------------------------- |---------------|-------------|
1311
+ * | 0 | * | 0 | - | Start nav, target fits | null | current |
1312
+ * | 0 | * | 1 | - | Start nav, target shorter | current | target end |
1313
+ * | 1 | 0 | 0 | 0 | Clamped, target fits preferred | null | preferred |
1314
+ * | 1 | 0 | 0 | 1 | Clamped, target longer but still can't fit preferred | keep | target end |
1315
+ * | 1 | 0 | 1 | - | Clamped, target even shorter | keep | target end |
1316
+ * | 1 | 1 | 0 | - | Rewrapped, target fits current | null | current |
1317
+ * | 1 | 1 | 1 | - | Rewrapped, target shorter than current | current | target end |
1318
+ *
1319
+ * Where:
1320
+ * - P = preferred col is set
1321
+ * - S = cursor in middle of source line (not clamped to end)
1322
+ * - T = target line shorter than current visual col
1323
+ * - U = target line shorter than preferred col
1324
+ */
1325
+ private computeVerticalMoveColumn(
1326
+ currentVisualCol: number,
1327
+ sourceMaxVisualCol: number,
1328
+ targetMaxVisualCol: number,
1329
+ ): number {
1330
+ const hasPreferred = this.preferredVisualCol !== null; // P
1331
+ const cursorInMiddle = currentVisualCol < sourceMaxVisualCol; // S
1332
+ const targetTooShort = targetMaxVisualCol < currentVisualCol; // T
1333
+
1334
+ if (!hasPreferred || cursorInMiddle) {
1335
+ if (targetTooShort) {
1336
+ // Cases 2 and 7
1337
+ this.preferredVisualCol = currentVisualCol;
1338
+ return targetMaxVisualCol;
1339
+ }
1340
+
1341
+ // Cases 1 and 6
1342
+ this.preferredVisualCol = null;
1343
+ return currentVisualCol;
1344
+ }
1345
+
1346
+ const targetCantFitPreferred = targetMaxVisualCol < this.preferredVisualCol!; // U
1347
+ if (targetTooShort || targetCantFitPreferred) {
1348
+ // Cases 4 and 5
1349
+ return targetMaxVisualCol;
1350
+ }
1351
+
1352
+ // Case 3
1353
+ const result = this.preferredVisualCol!;
1354
+ this.preferredVisualCol = null;
1355
+ return result;
1356
+ }
1357
+
1358
+ private moveToLineStart(): void {
1359
+ this.lastAction = null;
1360
+ this.setCursorCol(0);
1361
+ }
1362
+
1363
+ private moveToLineEnd(): void {
1364
+ this.lastAction = null;
1365
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1366
+ this.setCursorCol(currentLine.length);
1367
+ }
1368
+
1369
+ private deleteToStartOfLine(): void {
1370
+ this.historyIndex = -1; // Exit history browsing mode
1371
+
1372
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1373
+
1374
+ if (this.state.cursorCol > 0) {
1375
+ this.pushUndoSnapshot();
1376
+
1377
+ // Calculate text to be deleted and save to kill ring (backward deletion = prepend)
1378
+ const deletedText = currentLine.slice(0, this.state.cursorCol);
1379
+ this.killRing.push(deletedText, { prepend: true, accumulate: this.lastAction === "kill" });
1380
+ this.lastAction = "kill";
1381
+
1382
+ // Delete from start of line up to cursor
1383
+ this.state.lines[this.state.cursorLine] = currentLine.slice(this.state.cursorCol);
1384
+ this.setCursorCol(0);
1385
+ } else if (this.state.cursorLine > 0) {
1386
+ this.pushUndoSnapshot();
1387
+
1388
+ // At start of line - merge with previous line, treating newline as deleted text
1389
+ this.killRing.push("\n", { prepend: true, accumulate: this.lastAction === "kill" });
1390
+ this.lastAction = "kill";
1391
+
1392
+ const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
1393
+ this.state.lines[this.state.cursorLine - 1] = previousLine + currentLine;
1394
+ this.state.lines.splice(this.state.cursorLine, 1);
1395
+ this.state.cursorLine--;
1396
+ this.setCursorCol(previousLine.length);
1397
+ }
1398
+
1399
+ if (this.onChange) {
1400
+ this.onChange(this.getText());
1401
+ }
1402
+ }
1403
+
1404
+ private deleteToEndOfLine(): void {
1405
+ this.historyIndex = -1; // Exit history browsing mode
1406
+
1407
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1408
+
1409
+ if (this.state.cursorCol < currentLine.length) {
1410
+ this.pushUndoSnapshot();
1411
+
1412
+ // Calculate text to be deleted and save to kill ring (forward deletion = append)
1413
+ const deletedText = currentLine.slice(this.state.cursorCol);
1414
+ this.killRing.push(deletedText, { prepend: false, accumulate: this.lastAction === "kill" });
1415
+ this.lastAction = "kill";
1416
+
1417
+ // Delete from cursor to end of line
1418
+ this.state.lines[this.state.cursorLine] = currentLine.slice(0, this.state.cursorCol);
1419
+ } else if (this.state.cursorLine < this.state.lines.length - 1) {
1420
+ this.pushUndoSnapshot();
1421
+
1422
+ // At end of line - merge with next line, treating newline as deleted text
1423
+ this.killRing.push("\n", { prepend: false, accumulate: this.lastAction === "kill" });
1424
+ this.lastAction = "kill";
1425
+
1426
+ const nextLine = this.state.lines[this.state.cursorLine + 1] || "";
1427
+ this.state.lines[this.state.cursorLine] = currentLine + nextLine;
1428
+ this.state.lines.splice(this.state.cursorLine + 1, 1);
1429
+ }
1430
+
1431
+ if (this.onChange) {
1432
+ this.onChange(this.getText());
1433
+ }
1434
+ }
1435
+
1436
+ private deleteWordBackwards(): void {
1437
+ this.historyIndex = -1; // Exit history browsing mode
1438
+
1439
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1440
+
1441
+ // If at start of line, behave like backspace at column 0 (merge with previous line)
1442
+ if (this.state.cursorCol === 0) {
1443
+ if (this.state.cursorLine > 0) {
1444
+ this.pushUndoSnapshot();
1445
+
1446
+ // Treat newline as deleted text (backward deletion = prepend)
1447
+ this.killRing.push("\n", { prepend: true, accumulate: this.lastAction === "kill" });
1448
+ this.lastAction = "kill";
1449
+
1450
+ const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
1451
+ this.state.lines[this.state.cursorLine - 1] = previousLine + currentLine;
1452
+ this.state.lines.splice(this.state.cursorLine, 1);
1453
+ this.state.cursorLine--;
1454
+ this.setCursorCol(previousLine.length);
1455
+ }
1456
+ } else {
1457
+ this.pushUndoSnapshot();
1458
+
1459
+ // Save lastAction before cursor movement (moveWordBackwards resets it)
1460
+ const wasKill = this.lastAction === "kill";
1461
+
1462
+ const oldCursorCol = this.state.cursorCol;
1463
+ this.moveWordBackwards();
1464
+ const deleteFrom = this.state.cursorCol;
1465
+ this.setCursorCol(oldCursorCol);
1466
+
1467
+ const deletedText = currentLine.slice(deleteFrom, this.state.cursorCol);
1468
+ this.killRing.push(deletedText, { prepend: true, accumulate: wasKill });
1469
+ this.lastAction = "kill";
1470
+
1471
+ this.state.lines[this.state.cursorLine] =
1472
+ currentLine.slice(0, deleteFrom) + currentLine.slice(this.state.cursorCol);
1473
+ this.setCursorCol(deleteFrom);
1474
+ }
1475
+
1476
+ if (this.onChange) {
1477
+ this.onChange(this.getText());
1478
+ }
1479
+ }
1480
+
1481
+ private deleteWordForward(): void {
1482
+ this.historyIndex = -1; // Exit history browsing mode
1483
+
1484
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1485
+
1486
+ // If at end of line, merge with next line (delete the newline)
1487
+ if (this.state.cursorCol >= currentLine.length) {
1488
+ if (this.state.cursorLine < this.state.lines.length - 1) {
1489
+ this.pushUndoSnapshot();
1490
+
1491
+ // Treat newline as deleted text (forward deletion = append)
1492
+ this.killRing.push("\n", { prepend: false, accumulate: this.lastAction === "kill" });
1493
+ this.lastAction = "kill";
1494
+
1495
+ const nextLine = this.state.lines[this.state.cursorLine + 1] || "";
1496
+ this.state.lines[this.state.cursorLine] = currentLine + nextLine;
1497
+ this.state.lines.splice(this.state.cursorLine + 1, 1);
1498
+ }
1499
+ } else {
1500
+ this.pushUndoSnapshot();
1501
+
1502
+ // Save lastAction before cursor movement (moveWordForwards resets it)
1503
+ const wasKill = this.lastAction === "kill";
1504
+
1505
+ const oldCursorCol = this.state.cursorCol;
1506
+ this.moveWordForwards();
1507
+ const deleteTo = this.state.cursorCol;
1508
+ this.setCursorCol(oldCursorCol);
1509
+
1510
+ const deletedText = currentLine.slice(this.state.cursorCol, deleteTo);
1511
+ this.killRing.push(deletedText, { prepend: false, accumulate: wasKill });
1512
+ this.lastAction = "kill";
1513
+
1514
+ this.state.lines[this.state.cursorLine] =
1515
+ currentLine.slice(0, this.state.cursorCol) + currentLine.slice(deleteTo);
1516
+ }
1517
+
1518
+ if (this.onChange) {
1519
+ this.onChange(this.getText());
1520
+ }
1521
+ }
1522
+
1523
+ private handleForwardDelete(): void {
1524
+ this.historyIndex = -1; // Exit history browsing mode
1525
+ this.lastAction = null;
1526
+
1527
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1528
+
1529
+ if (this.state.cursorCol < currentLine.length) {
1530
+ this.pushUndoSnapshot();
1531
+
1532
+ // Delete grapheme at cursor position (handles emojis, combining characters, etc.)
1533
+ const afterCursor = currentLine.slice(this.state.cursorCol);
1534
+
1535
+ // Find the first grapheme at cursor
1536
+ const graphemes = [...this.segment(afterCursor)];
1537
+ const firstGrapheme = graphemes[0];
1538
+ const graphemeLength = firstGrapheme ? firstGrapheme.segment.length : 1;
1539
+
1540
+ const before = currentLine.slice(0, this.state.cursorCol);
1541
+ const after = currentLine.slice(this.state.cursorCol + graphemeLength);
1542
+ this.state.lines[this.state.cursorLine] = before + after;
1543
+ } else if (this.state.cursorLine < this.state.lines.length - 1) {
1544
+ this.pushUndoSnapshot();
1545
+
1546
+ // At end of line - merge with next line
1547
+ const nextLine = this.state.lines[this.state.cursorLine + 1] || "";
1548
+ this.state.lines[this.state.cursorLine] = currentLine + nextLine;
1549
+ this.state.lines.splice(this.state.cursorLine + 1, 1);
1550
+ }
1551
+
1552
+ if (this.onChange) {
1553
+ this.onChange(this.getText());
1554
+ }
1555
+
1556
+ // Update or re-trigger autocomplete after forward delete
1557
+ if (this.autocompleteState) {
1558
+ this.updateAutocomplete();
1559
+ } else {
1560
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1561
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
1562
+ // Slash command context
1563
+ if (this.isInSlashCommandContext(textBeforeCursor)) {
1564
+ this.tryTriggerAutocomplete();
1565
+ }
1566
+ // @ file reference context
1567
+ else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
1568
+ this.tryTriggerAutocomplete();
1569
+ }
1570
+ }
1571
+ }
1572
+
1573
+ /**
1574
+ * Build a mapping from visual lines to logical positions.
1575
+ * Returns an array where each element represents a visual line with:
1576
+ * - logicalLine: index into this.state.lines
1577
+ * - startCol: starting column in the logical line
1578
+ * - length: length of this visual line segment
1579
+ */
1580
+ private buildVisualLineMap(width: number): Array<{ logicalLine: number; startCol: number; length: number }> {
1581
+ const visualLines: Array<{ logicalLine: number; startCol: number; length: number }> = [];
1582
+
1583
+ for (let i = 0; i < this.state.lines.length; i++) {
1584
+ const line = this.state.lines[i] || "";
1585
+ const lineVisWidth = visibleWidth(line);
1586
+ if (line.length === 0) {
1587
+ // Empty line still takes one visual line
1588
+ visualLines.push({ logicalLine: i, startCol: 0, length: 0 });
1589
+ } else if (lineVisWidth <= width) {
1590
+ visualLines.push({ logicalLine: i, startCol: 0, length: line.length });
1591
+ } else {
1592
+ // Line needs wrapping - use word-aware wrapping
1593
+ const chunks = wordWrapLine(line, width, [...this.segment(line)]);
1594
+ for (const chunk of chunks) {
1595
+ visualLines.push({
1596
+ logicalLine: i,
1597
+ startCol: chunk.startIndex,
1598
+ length: chunk.endIndex - chunk.startIndex,
1599
+ });
1600
+ }
1601
+ }
1602
+ }
1603
+
1604
+ return visualLines;
1605
+ }
1606
+
1607
+ /**
1608
+ * Find the visual line index for the current cursor position.
1609
+ */
1610
+ private findCurrentVisualLine(
1611
+ visualLines: Array<{ logicalLine: number; startCol: number; length: number }>,
1612
+ ): number {
1613
+ for (let i = 0; i < visualLines.length; i++) {
1614
+ const vl = visualLines[i];
1615
+ if (!vl) continue;
1616
+ if (vl.logicalLine === this.state.cursorLine) {
1617
+ const colInSegment = this.state.cursorCol - vl.startCol;
1618
+ // Cursor is in this segment if it's within range
1619
+ // For the last segment of a logical line, cursor can be at length (end position)
1620
+ const isLastSegmentOfLine =
1621
+ i === visualLines.length - 1 || visualLines[i + 1]?.logicalLine !== vl.logicalLine;
1622
+ if (colInSegment >= 0 && (colInSegment < vl.length || (isLastSegmentOfLine && colInSegment <= vl.length))) {
1623
+ return i;
1624
+ }
1625
+ }
1626
+ }
1627
+ // Fallback: return last visual line
1628
+ return visualLines.length - 1;
1629
+ }
1630
+
1631
+ private moveCursor(deltaLine: number, deltaCol: number): void {
1632
+ this.lastAction = null;
1633
+ const visualLines = this.buildVisualLineMap(this.lastWidth);
1634
+ const currentVisualLine = this.findCurrentVisualLine(visualLines);
1635
+
1636
+ if (deltaLine !== 0) {
1637
+ const targetVisualLine = currentVisualLine + deltaLine;
1638
+
1639
+ if (targetVisualLine >= 0 && targetVisualLine < visualLines.length) {
1640
+ this.moveToVisualLine(visualLines, currentVisualLine, targetVisualLine);
1641
+ }
1642
+ }
1643
+
1644
+ if (deltaCol !== 0) {
1645
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1646
+
1647
+ if (deltaCol > 0) {
1648
+ // Moving right - move by one grapheme (handles emojis, combining characters, etc.)
1649
+ if (this.state.cursorCol < currentLine.length) {
1650
+ const afterCursor = currentLine.slice(this.state.cursorCol);
1651
+ const graphemes = [...this.segment(afterCursor)];
1652
+ const firstGrapheme = graphemes[0];
1653
+ this.setCursorCol(this.state.cursorCol + (firstGrapheme ? firstGrapheme.segment.length : 1));
1654
+ } else if (this.state.cursorLine < this.state.lines.length - 1) {
1655
+ // Wrap to start of next logical line
1656
+ this.state.cursorLine++;
1657
+ this.setCursorCol(0);
1658
+ } else {
1659
+ // At end of last line - can't move, but set preferredVisualCol for up/down navigation
1660
+ const currentVL = visualLines[currentVisualLine];
1661
+ if (currentVL) {
1662
+ this.preferredVisualCol = this.state.cursorCol - currentVL.startCol;
1663
+ }
1664
+ }
1665
+ } else {
1666
+ // Moving left - move by one grapheme (handles emojis, combining characters, etc.)
1667
+ if (this.state.cursorCol > 0) {
1668
+ const beforeCursor = currentLine.slice(0, this.state.cursorCol);
1669
+ const graphemes = [...this.segment(beforeCursor)];
1670
+ const lastGrapheme = graphemes[graphemes.length - 1];
1671
+ this.setCursorCol(this.state.cursorCol - (lastGrapheme ? lastGrapheme.segment.length : 1));
1672
+ } else if (this.state.cursorLine > 0) {
1673
+ // Wrap to end of previous logical line
1674
+ this.state.cursorLine--;
1675
+ const prevLine = this.state.lines[this.state.cursorLine] || "";
1676
+ this.setCursorCol(prevLine.length);
1677
+ }
1678
+ }
1679
+ }
1680
+ }
1681
+
1682
+ /**
1683
+ * Scroll by a page (direction: -1 for up, 1 for down).
1684
+ * Moves cursor by the page size while keeping it in bounds.
1685
+ */
1686
+ private pageScroll(direction: -1 | 1): void {
1687
+ this.lastAction = null;
1688
+ const terminalRows = this.tui.terminal.rows;
1689
+ const pageSize = Math.max(5, Math.floor(terminalRows * 0.3));
1690
+
1691
+ const visualLines = this.buildVisualLineMap(this.lastWidth);
1692
+ const currentVisualLine = this.findCurrentVisualLine(visualLines);
1693
+ const targetVisualLine = Math.max(0, Math.min(visualLines.length - 1, currentVisualLine + direction * pageSize));
1694
+
1695
+ this.moveToVisualLine(visualLines, currentVisualLine, targetVisualLine);
1696
+ }
1697
+
1698
+ private moveWordBackwards(): void {
1699
+ this.lastAction = null;
1700
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1701
+
1702
+ // If at start of line, move to end of previous line
1703
+ if (this.state.cursorCol === 0) {
1704
+ if (this.state.cursorLine > 0) {
1705
+ this.state.cursorLine--;
1706
+ const prevLine = this.state.lines[this.state.cursorLine] || "";
1707
+ this.setCursorCol(prevLine.length);
1708
+ }
1709
+ return;
1710
+ }
1711
+
1712
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
1713
+ const graphemes = [...this.segment(textBeforeCursor)];
1714
+ let newCol = this.state.cursorCol;
1715
+
1716
+ // Skip trailing whitespace
1717
+ while (
1718
+ graphemes.length > 0 &&
1719
+ !isPasteMarker(graphemes[graphemes.length - 1]?.segment || "") &&
1720
+ isWhitespaceChar(graphemes[graphemes.length - 1]?.segment || "")
1721
+ ) {
1722
+ newCol -= graphemes.pop()?.segment.length || 0;
1723
+ }
1724
+
1725
+ if (graphemes.length > 0) {
1726
+ const lastGrapheme = graphemes[graphemes.length - 1]?.segment || "";
1727
+ if (isPasteMarker(lastGrapheme)) {
1728
+ // Paste marker is a single atomic word
1729
+ newCol -= graphemes.pop()?.segment.length || 0;
1730
+ } else if (isPunctuationChar(lastGrapheme)) {
1731
+ // Skip punctuation run
1732
+ while (
1733
+ graphemes.length > 0 &&
1734
+ isPunctuationChar(graphemes[graphemes.length - 1]?.segment || "") &&
1735
+ !isPasteMarker(graphemes[graphemes.length - 1]?.segment || "")
1736
+ ) {
1737
+ newCol -= graphemes.pop()?.segment.length || 0;
1738
+ }
1739
+ } else {
1740
+ // Skip word run
1741
+ while (
1742
+ graphemes.length > 0 &&
1743
+ !isWhitespaceChar(graphemes[graphemes.length - 1]?.segment || "") &&
1744
+ !isPunctuationChar(graphemes[graphemes.length - 1]?.segment || "") &&
1745
+ !isPasteMarker(graphemes[graphemes.length - 1]?.segment || "")
1746
+ ) {
1747
+ newCol -= graphemes.pop()?.segment.length || 0;
1748
+ }
1749
+ }
1750
+ }
1751
+
1752
+ this.setCursorCol(newCol);
1753
+ }
1754
+
1755
+ /**
1756
+ * Yank (paste) the most recent kill ring entry at cursor position.
1757
+ */
1758
+ private yank(): void {
1759
+ if (this.killRing.length === 0) return;
1760
+
1761
+ this.pushUndoSnapshot();
1762
+
1763
+ const text = this.killRing.peek()!;
1764
+ this.insertYankedText(text);
1765
+
1766
+ this.lastAction = "yank";
1767
+ }
1768
+
1769
+ /**
1770
+ * Cycle through kill ring (only works immediately after yank or yank-pop).
1771
+ * Replaces the last yanked text with the previous entry in the ring.
1772
+ */
1773
+ private yankPop(): void {
1774
+ // Only works if we just yanked and have more than one entry
1775
+ if (this.lastAction !== "yank" || this.killRing.length <= 1) return;
1776
+
1777
+ this.pushUndoSnapshot();
1778
+
1779
+ // Delete the previously yanked text (still at end of ring before rotation)
1780
+ this.deleteYankedText();
1781
+
1782
+ // Rotate the ring: move end to front
1783
+ this.killRing.rotate();
1784
+
1785
+ // Insert the new most recent entry (now at end after rotation)
1786
+ const text = this.killRing.peek()!;
1787
+ this.insertYankedText(text);
1788
+
1789
+ this.lastAction = "yank";
1790
+ }
1791
+
1792
+ /**
1793
+ * Insert text at cursor position (used by yank operations).
1794
+ */
1795
+ private insertYankedText(text: string): void {
1796
+ this.historyIndex = -1; // Exit history browsing mode
1797
+ const lines = text.split("\n");
1798
+
1799
+ if (lines.length === 1) {
1800
+ // Single line - insert at cursor
1801
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1802
+ const before = currentLine.slice(0, this.state.cursorCol);
1803
+ const after = currentLine.slice(this.state.cursorCol);
1804
+ this.state.lines[this.state.cursorLine] = before + text + after;
1805
+ this.setCursorCol(this.state.cursorCol + text.length);
1806
+ } else {
1807
+ // Multi-line insert
1808
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1809
+ const before = currentLine.slice(0, this.state.cursorCol);
1810
+ const after = currentLine.slice(this.state.cursorCol);
1811
+
1812
+ // First line merges with text before cursor
1813
+ this.state.lines[this.state.cursorLine] = before + (lines[0] || "");
1814
+
1815
+ // Insert middle lines
1816
+ for (let i = 1; i < lines.length - 1; i++) {
1817
+ this.state.lines.splice(this.state.cursorLine + i, 0, lines[i] || "");
1818
+ }
1819
+
1820
+ // Last line merges with text after cursor
1821
+ const lastLineIndex = this.state.cursorLine + lines.length - 1;
1822
+ this.state.lines.splice(lastLineIndex, 0, (lines[lines.length - 1] || "") + after);
1823
+
1824
+ // Update cursor position
1825
+ this.state.cursorLine = lastLineIndex;
1826
+ this.setCursorCol((lines[lines.length - 1] || "").length);
1827
+ }
1828
+
1829
+ if (this.onChange) {
1830
+ this.onChange(this.getText());
1831
+ }
1832
+ }
1833
+
1834
+ /**
1835
+ * Delete the previously yanked text (used by yank-pop).
1836
+ * The yanked text is derived from killRing[end] since it hasn't been rotated yet.
1837
+ */
1838
+ private deleteYankedText(): void {
1839
+ const yankedText = this.killRing.peek();
1840
+ if (!yankedText) return;
1841
+
1842
+ const yankLines = yankedText.split("\n");
1843
+
1844
+ if (yankLines.length === 1) {
1845
+ // Single line - delete backward from cursor
1846
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1847
+ const deleteLen = yankedText.length;
1848
+ const before = currentLine.slice(0, this.state.cursorCol - deleteLen);
1849
+ const after = currentLine.slice(this.state.cursorCol);
1850
+ this.state.lines[this.state.cursorLine] = before + after;
1851
+ this.setCursorCol(this.state.cursorCol - deleteLen);
1852
+ } else {
1853
+ // Multi-line delete - cursor is at end of last yanked line
1854
+ const startLine = this.state.cursorLine - (yankLines.length - 1);
1855
+ const startCol = (this.state.lines[startLine] || "").length - (yankLines[0] || "").length;
1856
+
1857
+ // Get text after cursor on current line
1858
+ const afterCursor = (this.state.lines[this.state.cursorLine] || "").slice(this.state.cursorCol);
1859
+
1860
+ // Get text before yank start position
1861
+ const beforeYank = (this.state.lines[startLine] || "").slice(0, startCol);
1862
+
1863
+ // Remove all lines from startLine to cursorLine and replace with merged line
1864
+ this.state.lines.splice(startLine, yankLines.length, beforeYank + afterCursor);
1865
+
1866
+ // Update cursor
1867
+ this.state.cursorLine = startLine;
1868
+ this.setCursorCol(startCol);
1869
+ }
1870
+
1871
+ if (this.onChange) {
1872
+ this.onChange(this.getText());
1873
+ }
1874
+ }
1875
+
1876
+ private pushUndoSnapshot(): void {
1877
+ this.undoStack.push(this.state);
1878
+ }
1879
+
1880
+ private undo(): void {
1881
+ this.historyIndex = -1; // Exit history browsing mode
1882
+ const snapshot = this.undoStack.pop();
1883
+ if (!snapshot) return;
1884
+ Object.assign(this.state, snapshot);
1885
+ this.lastAction = null;
1886
+ this.preferredVisualCol = null;
1887
+ if (this.onChange) {
1888
+ this.onChange(this.getText());
1889
+ }
1890
+ }
1891
+
1892
+ /**
1893
+ * Jump to the first occurrence of a character in the specified direction.
1894
+ * Multi-line search. Case-sensitive. Skips the current cursor position.
1895
+ */
1896
+ private jumpToChar(char: string, direction: "forward" | "backward"): void {
1897
+ this.lastAction = null;
1898
+ const isForward = direction === "forward";
1899
+ const lines = this.state.lines;
1900
+
1901
+ const end = isForward ? lines.length : -1;
1902
+ const step = isForward ? 1 : -1;
1903
+
1904
+ for (let lineIdx = this.state.cursorLine; lineIdx !== end; lineIdx += step) {
1905
+ const line = lines[lineIdx] || "";
1906
+ const isCurrentLine = lineIdx === this.state.cursorLine;
1907
+
1908
+ // Current line: start after/before cursor; other lines: search full line
1909
+ const searchFrom = isCurrentLine
1910
+ ? isForward
1911
+ ? this.state.cursorCol + 1
1912
+ : this.state.cursorCol - 1
1913
+ : undefined;
1914
+
1915
+ const idx = isForward ? line.indexOf(char, searchFrom) : line.lastIndexOf(char, searchFrom);
1916
+
1917
+ if (idx !== -1) {
1918
+ this.state.cursorLine = lineIdx;
1919
+ this.setCursorCol(idx);
1920
+ return;
1921
+ }
1922
+ }
1923
+ // No match found - cursor stays in place
1924
+ }
1925
+
1926
+ private moveWordForwards(): void {
1927
+ this.lastAction = null;
1928
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1929
+
1930
+ // If at end of line, move to start of next line
1931
+ if (this.state.cursorCol >= currentLine.length) {
1932
+ if (this.state.cursorLine < this.state.lines.length - 1) {
1933
+ this.state.cursorLine++;
1934
+ this.setCursorCol(0);
1935
+ }
1936
+ return;
1937
+ }
1938
+
1939
+ const textAfterCursor = currentLine.slice(this.state.cursorCol);
1940
+ const segments = this.segment(textAfterCursor);
1941
+ const iterator = segments[Symbol.iterator]();
1942
+ let next = iterator.next();
1943
+ let newCol = this.state.cursorCol;
1944
+
1945
+ // Skip leading whitespace
1946
+ while (!next.done && !isPasteMarker(next.value.segment) && isWhitespaceChar(next.value.segment)) {
1947
+ newCol += next.value.segment.length;
1948
+ next = iterator.next();
1949
+ }
1950
+
1951
+ if (!next.done) {
1952
+ const firstGrapheme = next.value.segment;
1953
+ if (isPasteMarker(firstGrapheme)) {
1954
+ // Paste marker is a single atomic word
1955
+ newCol += firstGrapheme.length;
1956
+ } else if (isPunctuationChar(firstGrapheme)) {
1957
+ // Skip punctuation run
1958
+ while (!next.done && isPunctuationChar(next.value.segment) && !isPasteMarker(next.value.segment)) {
1959
+ newCol += next.value.segment.length;
1960
+ next = iterator.next();
1961
+ }
1962
+ } else {
1963
+ // Skip word run
1964
+ while (
1965
+ !next.done &&
1966
+ !isWhitespaceChar(next.value.segment) &&
1967
+ !isPunctuationChar(next.value.segment) &&
1968
+ !isPasteMarker(next.value.segment)
1969
+ ) {
1970
+ newCol += next.value.segment.length;
1971
+ next = iterator.next();
1972
+ }
1973
+ }
1974
+ }
1975
+
1976
+ this.setCursorCol(newCol);
1977
+ }
1978
+
1979
+ // Slash menu only allowed on the first line of the editor
1980
+ private isSlashMenuAllowed(): boolean {
1981
+ return this.state.cursorLine === 0;
1982
+ }
1983
+
1984
+ // Helper method to check if cursor is at start of message (for slash command detection)
1985
+ private isAtStartOfMessage(): boolean {
1986
+ if (!this.isSlashMenuAllowed()) return false;
1987
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
1988
+ const beforeCursor = currentLine.slice(0, this.state.cursorCol);
1989
+ return beforeCursor.trim() === "" || beforeCursor.trim() === "/";
1990
+ }
1991
+
1992
+ private isInSlashCommandContext(textBeforeCursor: string): boolean {
1993
+ return this.isSlashMenuAllowed() && textBeforeCursor.trimStart().startsWith("/");
1994
+ }
1995
+
1996
+ // Autocomplete methods
1997
+ /**
1998
+ * Find the best autocomplete item index for the given prefix.
1999
+ * Returns -1 if no match is found.
2000
+ *
2001
+ * Match priority:
2002
+ * 1. Exact match (prefix === item.value) -> always selected
2003
+ * 2. Prefix match -> first item whose value starts with prefix
2004
+ * 3. No match -> -1 (keep default highlight)
2005
+ *
2006
+ * Matching is case-sensitive and checks item.value only.
2007
+ */
2008
+ private getBestAutocompleteMatchIndex(items: Array<{ value: string; label: string }>, prefix: string): number {
2009
+ if (!prefix) return -1;
2010
+
2011
+ let firstPrefixIndex = -1;
2012
+
2013
+ for (let i = 0; i < items.length; i++) {
2014
+ const value = items[i]!.value;
2015
+ if (value === prefix) {
2016
+ return i; // Exact match always wins
2017
+ }
2018
+ if (firstPrefixIndex === -1 && value.startsWith(prefix)) {
2019
+ firstPrefixIndex = i;
2020
+ }
2021
+ }
2022
+
2023
+ return firstPrefixIndex;
2024
+ }
2025
+
2026
+ private createAutocompleteList(
2027
+ prefix: string,
2028
+ items: Array<{ value: string; label: string; description?: string }>,
2029
+ ): SelectList {
2030
+ const layout = prefix.startsWith("/") ? SLASH_COMMAND_SELECT_LIST_LAYOUT : undefined;
2031
+ return new SelectList(items, this.autocompleteMaxVisible, this.theme.selectList, layout);
2032
+ }
2033
+
2034
+ private tryTriggerAutocomplete(explicitTab: boolean = false): void {
2035
+ this.requestAutocomplete({ force: false, explicitTab });
2036
+ }
2037
+
2038
+ private handleTabCompletion(): void {
2039
+ if (!this.autocompleteProvider) return;
2040
+
2041
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
2042
+ const beforeCursor = currentLine.slice(0, this.state.cursorCol);
2043
+
2044
+ if (this.isInSlashCommandContext(beforeCursor) && !beforeCursor.trimStart().includes(" ")) {
2045
+ this.handleSlashCommandCompletion();
2046
+ } else {
2047
+ this.forceFileAutocomplete(true);
2048
+ }
2049
+ }
2050
+
2051
+ private handleSlashCommandCompletion(): void {
2052
+ this.requestAutocomplete({ force: false, explicitTab: true });
2053
+ }
2054
+
2055
+ private forceFileAutocomplete(explicitTab: boolean = false): void {
2056
+ this.requestAutocomplete({ force: true, explicitTab });
2057
+ }
2058
+
2059
+ private requestAutocomplete(options: { force: boolean; explicitTab: boolean }): void {
2060
+ if (!this.autocompleteProvider) return;
2061
+
2062
+ if (options.force) {
2063
+ const provider = this.autocompleteProvider as CombinedAutocompleteProvider;
2064
+ const shouldTrigger =
2065
+ !provider.shouldTriggerFileCompletion ||
2066
+ provider.shouldTriggerFileCompletion(this.state.lines, this.state.cursorLine, this.state.cursorCol);
2067
+ if (!shouldTrigger) {
2068
+ return;
2069
+ }
2070
+ }
2071
+
2072
+ this.cancelAutocompleteRequest();
2073
+ const startToken = ++this.autocompleteStartToken;
2074
+
2075
+ const debounceMs = this.getAutocompleteDebounceMs(options);
2076
+ if (debounceMs > 0) {
2077
+ this.autocompleteDebounceTimer = setTimeout(() => {
2078
+ this.autocompleteDebounceTimer = undefined;
2079
+ void this.startAutocompleteRequest(startToken, options);
2080
+ }, debounceMs);
2081
+ return;
2082
+ }
2083
+
2084
+ void this.startAutocompleteRequest(startToken, options);
2085
+ }
2086
+
2087
+ private async startAutocompleteRequest(
2088
+ startToken: number,
2089
+ options: { force: boolean; explicitTab: boolean },
2090
+ ): Promise<void> {
2091
+ const previousTask = this.autocompleteRequestTask;
2092
+ this.autocompleteRequestTask = (async () => {
2093
+ await previousTask;
2094
+ if (startToken !== this.autocompleteStartToken || !this.autocompleteProvider) {
2095
+ return;
2096
+ }
2097
+
2098
+ const controller = new AbortController();
2099
+ this.autocompleteAbort = controller;
2100
+ const requestId = ++this.autocompleteRequestId;
2101
+ const snapshotText = this.getText();
2102
+ const snapshotLine = this.state.cursorLine;
2103
+ const snapshotCol = this.state.cursorCol;
2104
+
2105
+ await this.runAutocompleteRequest(requestId, controller, snapshotText, snapshotLine, snapshotCol, options);
2106
+ })();
2107
+ await this.autocompleteRequestTask;
2108
+ }
2109
+
2110
+ private getAutocompleteDebounceMs(options: { force: boolean; explicitTab: boolean }): number {
2111
+ if (options.explicitTab || options.force) {
2112
+ return 0;
2113
+ }
2114
+
2115
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
2116
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
2117
+ const isAttachmentContext = /(?:^|[ \t])@(?:"[^"]*|[^\s]*)$/.test(textBeforeCursor);
2118
+ return isAttachmentContext ? ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS : 0;
2119
+ }
2120
+
2121
+ private async runAutocompleteRequest(
2122
+ requestId: number,
2123
+ controller: AbortController,
2124
+ snapshotText: string,
2125
+ snapshotLine: number,
2126
+ snapshotCol: number,
2127
+ options: { force: boolean; explicitTab: boolean },
2128
+ ): Promise<void> {
2129
+ if (!this.autocompleteProvider) return;
2130
+
2131
+ const suggestions = await this.autocompleteProvider.getSuggestions(
2132
+ this.state.lines,
2133
+ this.state.cursorLine,
2134
+ this.state.cursorCol,
2135
+ { signal: controller.signal, force: options.force },
2136
+ );
2137
+
2138
+ if (!this.isAutocompleteRequestCurrent(requestId, controller, snapshotText, snapshotLine, snapshotCol)) {
2139
+ return;
2140
+ }
2141
+
2142
+ this.autocompleteAbort = undefined;
2143
+
2144
+ if (!suggestions || suggestions.items.length === 0) {
2145
+ this.cancelAutocomplete();
2146
+ this.tui.requestRender();
2147
+ return;
2148
+ }
2149
+
2150
+ if (options.force && options.explicitTab && suggestions.items.length === 1) {
2151
+ const item = suggestions.items[0]!;
2152
+ this.pushUndoSnapshot();
2153
+ this.lastAction = null;
2154
+ const result = this.autocompleteProvider.applyCompletion(
2155
+ this.state.lines,
2156
+ this.state.cursorLine,
2157
+ this.state.cursorCol,
2158
+ item,
2159
+ suggestions.prefix,
2160
+ );
2161
+ this.state.lines = result.lines;
2162
+ this.state.cursorLine = result.cursorLine;
2163
+ this.setCursorCol(result.cursorCol);
2164
+ if (this.onChange) this.onChange(this.getText());
2165
+ this.tui.requestRender();
2166
+ return;
2167
+ }
2168
+
2169
+ this.applyAutocompleteSuggestions(suggestions, options.force ? "force" : "regular");
2170
+ this.tui.requestRender();
2171
+ }
2172
+
2173
+ private isAutocompleteRequestCurrent(
2174
+ requestId: number,
2175
+ controller: AbortController,
2176
+ snapshotText: string,
2177
+ snapshotLine: number,
2178
+ snapshotCol: number,
2179
+ ): boolean {
2180
+ return (
2181
+ !controller.signal.aborted &&
2182
+ requestId === this.autocompleteRequestId &&
2183
+ this.getText() === snapshotText &&
2184
+ this.state.cursorLine === snapshotLine &&
2185
+ this.state.cursorCol === snapshotCol
2186
+ );
2187
+ }
2188
+
2189
+ private applyAutocompleteSuggestions(suggestions: AutocompleteSuggestions, state: "regular" | "force"): void {
2190
+ this.autocompletePrefix = suggestions.prefix;
2191
+ this.autocompleteList = this.createAutocompleteList(suggestions.prefix, suggestions.items);
2192
+
2193
+ const bestMatchIndex = this.getBestAutocompleteMatchIndex(suggestions.items, suggestions.prefix);
2194
+ if (bestMatchIndex >= 0) {
2195
+ this.autocompleteList.setSelectedIndex(bestMatchIndex);
2196
+ }
2197
+
2198
+ this.autocompleteState = state;
2199
+ }
2200
+
2201
+ private cancelAutocompleteRequest(): void {
2202
+ this.autocompleteStartToken += 1;
2203
+ if (this.autocompleteDebounceTimer) {
2204
+ clearTimeout(this.autocompleteDebounceTimer);
2205
+ this.autocompleteDebounceTimer = undefined;
2206
+ }
2207
+ this.autocompleteAbort?.abort();
2208
+ this.autocompleteAbort = undefined;
2209
+ }
2210
+
2211
+ private clearAutocompleteUi(): void {
2212
+ this.autocompleteState = null;
2213
+ this.autocompleteList = undefined;
2214
+ this.autocompletePrefix = "";
2215
+ }
2216
+
2217
+ private cancelAutocomplete(): void {
2218
+ this.cancelAutocompleteRequest();
2219
+ this.clearAutocompleteUi();
2220
+ }
2221
+
2222
+ public isShowingAutocomplete(): boolean {
2223
+ return this.autocompleteState !== null;
2224
+ }
2225
+
2226
+ private updateAutocomplete(): void {
2227
+ if (!this.autocompleteState || !this.autocompleteProvider) return;
2228
+ this.requestAutocomplete({ force: this.autocompleteState === "force", explicitTab: false });
2229
+ }
2230
+ }