@bramburn/qi-tui 0.0.0-stage → 0.85.1

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