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