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