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