lonny-agent 0.1.2 → 0.1.8

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