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