@caupulican/pi-tui 0.78.2

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