@ny4n/tui 0.0.0-stage → 1.0.0

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