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