open-pi-tui 0.57.1

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