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