jeopi-tui 16.2.13
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.
- package/CHANGELOG.md +1861 -0
- package/README.md +705 -0
- package/dist/types/autocomplete.d.ts +99 -0
- package/dist/types/bracketed-paste.d.ts +51 -0
- package/dist/types/components/box.d.ts +31 -0
- package/dist/types/components/cancellable-loader.d.ts +21 -0
- package/dist/types/components/editor.d.ts +155 -0
- package/dist/types/components/image.d.ts +112 -0
- package/dist/types/components/input.d.ts +23 -0
- package/dist/types/components/loader.d.ts +20 -0
- package/dist/types/components/markdown.d.ts +64 -0
- package/dist/types/components/scroll-view.d.ts +62 -0
- package/dist/types/components/select-list.d.ts +68 -0
- package/dist/types/components/settings-list.d.ts +123 -0
- package/dist/types/components/spacer.d.ts +11 -0
- package/dist/types/components/tab-bar.d.ts +89 -0
- package/dist/types/components/text.d.ts +14 -0
- package/dist/types/components/truncated-text.d.ts +10 -0
- package/dist/types/deccara.d.ts +49 -0
- package/dist/types/desktop-notify.d.ts +51 -0
- package/dist/types/editor-component.d.ts +38 -0
- package/dist/types/fuzzy.d.ts +32 -0
- package/dist/types/index.d.ts +32 -0
- package/dist/types/keybindings.d.ts +191 -0
- package/dist/types/keys.d.ts +208 -0
- package/dist/types/kill-ring.d.ts +20 -0
- package/dist/types/kitty-graphics.d.ts +79 -0
- package/dist/types/latex-block.d.ts +7 -0
- package/dist/types/latex-to-unicode.d.ts +33 -0
- package/dist/types/loop-watchdog.d.ts +39 -0
- package/dist/types/mouse.d.ts +67 -0
- package/dist/types/stdin-buffer.d.ts +60 -0
- package/dist/types/symbols.d.ts +25 -0
- package/dist/types/terminal-capabilities.d.ts +284 -0
- package/dist/types/terminal.d.ts +107 -0
- package/dist/types/ttyid.d.ts +9 -0
- package/dist/types/tui.d.ts +423 -0
- package/dist/types/utils.d.ts +95 -0
- package/package.json +73 -0
- package/src/autocomplete.ts +1026 -0
- package/src/bracketed-paste.ts +123 -0
- package/src/components/box.ts +194 -0
- package/src/components/cancellable-loader.ts +40 -0
- package/src/components/editor.ts +3092 -0
- package/src/components/image.ts +444 -0
- package/src/components/input.ts +474 -0
- package/src/components/loader.ts +103 -0
- package/src/components/markdown.ts +2068 -0
- package/src/components/scroll-view.ts +227 -0
- package/src/components/select-list.ts +531 -0
- package/src/components/settings-list.ts +793 -0
- package/src/components/spacer.ts +32 -0
- package/src/components/tab-bar.ts +300 -0
- package/src/components/text.ts +122 -0
- package/src/components/truncated-text.ts +69 -0
- package/src/deccara.ts +314 -0
- package/src/desktop-notify.ts +186 -0
- package/src/editor-component.ts +74 -0
- package/src/fuzzy.ts +356 -0
- package/src/index.ts +51 -0
- package/src/keybindings.ts +337 -0
- package/src/keys.ts +561 -0
- package/src/kill-ring.ts +51 -0
- package/src/kitty-graphics.ts +171 -0
- package/src/latex-block.ts +461 -0
- package/src/latex-to-unicode.ts +1994 -0
- package/src/loop-watchdog.ts +106 -0
- package/src/mouse.ts +105 -0
- package/src/stdin-buffer.ts +669 -0
- package/src/symbols.ts +26 -0
- package/src/terminal-capabilities.ts +1152 -0
- package/src/terminal.ts +1463 -0
- package/src/ttyid.ts +84 -0
- package/src/tui.ts +3901 -0
- package/src/utils.ts +570 -0
|
@@ -0,0 +1,3092 @@
|
|
|
1
|
+
import { getProjectDir, logger } from "jeopi-utils";
|
|
2
|
+
import {
|
|
3
|
+
type AutocompleteProvider,
|
|
4
|
+
findLeadingSlashCommandStart,
|
|
5
|
+
findTrailingSlashCommandStart,
|
|
6
|
+
} from "../autocomplete";
|
|
7
|
+
import { BracketedPasteHandler, decodeReencodedPasteControls } from "../bracketed-paste";
|
|
8
|
+
import { getKeybindings, type KeybindingsManager } from "../keybindings";
|
|
9
|
+
import { extractPrintableText, matchesKey } from "../keys";
|
|
10
|
+
import { KillRing } from "../kill-ring";
|
|
11
|
+
import type { SymbolTheme } from "../symbols";
|
|
12
|
+
import { type Component, CURSOR_MARKER, type Focusable } from "../tui";
|
|
13
|
+
import {
|
|
14
|
+
getSegmenter,
|
|
15
|
+
getWordNavKind,
|
|
16
|
+
moveWordLeft,
|
|
17
|
+
moveWordRight,
|
|
18
|
+
padding,
|
|
19
|
+
replaceTabs,
|
|
20
|
+
sliceByColumn,
|
|
21
|
+
truncateToWidth,
|
|
22
|
+
visibleWidth,
|
|
23
|
+
} from "../utils";
|
|
24
|
+
import { SelectList, type SelectListLayoutOptions, type SelectListTheme } from "./select-list";
|
|
25
|
+
|
|
26
|
+
const AUTOCOMPLETE_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
|
|
27
|
+
overflowSearch: false,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const SLASH_COMMAND_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
|
|
31
|
+
minPrimaryColumnWidth: 12,
|
|
32
|
+
maxPrimaryColumnWidth: 32,
|
|
33
|
+
overflowSearch: false,
|
|
34
|
+
wrapDescription: true,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function sanitizeLoadedText(text: string): string {
|
|
38
|
+
// Normalize CRLF/CR → LF, then strip C0 control chars except \n.
|
|
39
|
+
return replaceTabs(text.replace(/\r\n?/g, "\n")).replace(/[\x00-\x09\x0b-\x1f]/g, "");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const segmenter = getSegmenter();
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Represents a chunk of text for word-wrap layout.
|
|
46
|
+
* Tracks both the text content and its position in the original line.
|
|
47
|
+
*/
|
|
48
|
+
interface TextChunk {
|
|
49
|
+
text: string;
|
|
50
|
+
startIndex: number;
|
|
51
|
+
endIndex: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Split a line into word-wrapped chunks.
|
|
56
|
+
* Wraps at word boundaries when possible, falling back to character-level
|
|
57
|
+
* wrapping for words longer than the available width.
|
|
58
|
+
*
|
|
59
|
+
* @param line - The text line to wrap
|
|
60
|
+
* @param maxWidth - Maximum visible width per chunk
|
|
61
|
+
* @returns Array of chunks with text and position information
|
|
62
|
+
*/
|
|
63
|
+
function wordWrapLine(line: string, maxWidth: number): TextChunk[] {
|
|
64
|
+
if (!line || maxWidth <= 0) {
|
|
65
|
+
return [{ text: "", startIndex: 0, endIndex: 0 }];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const lineWidth = visibleWidth(line);
|
|
69
|
+
if (lineWidth <= maxWidth) {
|
|
70
|
+
return [{ text: line, startIndex: 0, endIndex: line.length }];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const chunks: TextChunk[] = [];
|
|
74
|
+
|
|
75
|
+
// Split into tokens (words and whitespace runs)
|
|
76
|
+
const tokens: { text: string; startIndex: number; endIndex: number; isWhitespace: boolean }[] = [];
|
|
77
|
+
let currentToken = "";
|
|
78
|
+
let tokenStart = 0;
|
|
79
|
+
let inWhitespace = false;
|
|
80
|
+
let charIndex = 0;
|
|
81
|
+
|
|
82
|
+
for (const seg of segmenter.segment(line)) {
|
|
83
|
+
const grapheme = seg.segment;
|
|
84
|
+
const graphemeIsWhitespace = getWordNavKind(grapheme) === "whitespace";
|
|
85
|
+
|
|
86
|
+
if (currentToken === "") {
|
|
87
|
+
inWhitespace = graphemeIsWhitespace;
|
|
88
|
+
tokenStart = charIndex;
|
|
89
|
+
} else if (graphemeIsWhitespace !== inWhitespace) {
|
|
90
|
+
// Token type changed - save current token
|
|
91
|
+
tokens.push({
|
|
92
|
+
text: currentToken,
|
|
93
|
+
startIndex: tokenStart,
|
|
94
|
+
endIndex: charIndex,
|
|
95
|
+
isWhitespace: inWhitespace,
|
|
96
|
+
});
|
|
97
|
+
currentToken = "";
|
|
98
|
+
tokenStart = charIndex;
|
|
99
|
+
inWhitespace = graphemeIsWhitespace;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
currentToken += grapheme;
|
|
103
|
+
charIndex += grapheme.length;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Push final token
|
|
107
|
+
if (currentToken) {
|
|
108
|
+
tokens.push({
|
|
109
|
+
text: currentToken,
|
|
110
|
+
startIndex: tokenStart,
|
|
111
|
+
endIndex: charIndex,
|
|
112
|
+
isWhitespace: inWhitespace,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Build chunks using word wrapping
|
|
117
|
+
let currentChunk = "";
|
|
118
|
+
let currentWidth = 0;
|
|
119
|
+
let chunkStartIndex = 0;
|
|
120
|
+
let atLineStart = true; // Track if we're at the start of a line (for skipping whitespace)
|
|
121
|
+
|
|
122
|
+
function consumePrefixToWidth(text: string, availableWidth: number): { text: string; len: number } {
|
|
123
|
+
let prefix = "";
|
|
124
|
+
let prefixWidth = 0;
|
|
125
|
+
let len = 0;
|
|
126
|
+
for (const seg of segmenter.segment(text)) {
|
|
127
|
+
const grapheme = seg.segment;
|
|
128
|
+
const graphemeWidth = visibleWidth(grapheme);
|
|
129
|
+
if (prefixWidth + graphemeWidth > availableWidth) break;
|
|
130
|
+
prefix += grapheme;
|
|
131
|
+
prefixWidth += graphemeWidth;
|
|
132
|
+
len += grapheme.length;
|
|
133
|
+
if (prefixWidth === availableWidth) break;
|
|
134
|
+
}
|
|
135
|
+
return { text: prefix, len };
|
|
136
|
+
}
|
|
137
|
+
function hasWideGrapheme(text: string): boolean {
|
|
138
|
+
for (const seg of segmenter.segment(text)) {
|
|
139
|
+
if (visibleWidth(seg.segment) > 1) return true;
|
|
140
|
+
}
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
for (const token of tokens) {
|
|
144
|
+
const tokenWidth = visibleWidth(token.text);
|
|
145
|
+
|
|
146
|
+
// Skip leading whitespace at line start. Keep the skipped run mapped onto the
|
|
147
|
+
// preceding chunk (when one exists) so every cursor position resolves to a
|
|
148
|
+
// layout line instead of falling through to the buffer's last visual line.
|
|
149
|
+
if (atLineStart && token.isWhitespace) {
|
|
150
|
+
const prev = chunks[chunks.length - 1];
|
|
151
|
+
if (prev) prev.endIndex = token.endIndex;
|
|
152
|
+
chunkStartIndex = token.endIndex;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
atLineStart = false;
|
|
156
|
+
|
|
157
|
+
// If this single token is wider than maxWidth, we need to break it
|
|
158
|
+
if (tokenWidth > maxWidth) {
|
|
159
|
+
// If we're mid-line, try to use the remaining width by consuming a prefix of this long token.
|
|
160
|
+
let consumedPrefix = "";
|
|
161
|
+
let consumedPrefixLen = 0; // JS string index (code units) consumed from token.text
|
|
162
|
+
if (currentChunk && currentWidth < maxWidth) {
|
|
163
|
+
const remainingWidth = maxWidth - currentWidth;
|
|
164
|
+
const consumed = consumePrefixToWidth(token.text, remainingWidth);
|
|
165
|
+
consumedPrefix = consumed.text;
|
|
166
|
+
consumedPrefixLen = consumed.len;
|
|
167
|
+
}
|
|
168
|
+
// First, push any accumulated chunk (optionally filled with the prefix).
|
|
169
|
+
if (currentChunk) {
|
|
170
|
+
if (consumedPrefix) {
|
|
171
|
+
chunks.push({
|
|
172
|
+
text: currentChunk + consumedPrefix,
|
|
173
|
+
startIndex: chunkStartIndex,
|
|
174
|
+
endIndex: token.startIndex + consumedPrefixLen,
|
|
175
|
+
});
|
|
176
|
+
currentChunk = "";
|
|
177
|
+
currentWidth = 0;
|
|
178
|
+
chunkStartIndex = token.startIndex + consumedPrefixLen;
|
|
179
|
+
} else {
|
|
180
|
+
chunks.push({
|
|
181
|
+
text: currentChunk,
|
|
182
|
+
startIndex: chunkStartIndex,
|
|
183
|
+
endIndex: token.startIndex,
|
|
184
|
+
});
|
|
185
|
+
currentChunk = "";
|
|
186
|
+
currentWidth = 0;
|
|
187
|
+
chunkStartIndex = token.startIndex;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
// Break the remaining long token by grapheme
|
|
191
|
+
const remainingText = consumedPrefixLen > 0 ? token.text.slice(consumedPrefixLen) : token.text;
|
|
192
|
+
let tokenChunk = "";
|
|
193
|
+
let tokenChunkWidth = 0;
|
|
194
|
+
let tokenChunkStart = token.startIndex + consumedPrefixLen;
|
|
195
|
+
let tokenCharIndex = token.startIndex + consumedPrefixLen;
|
|
196
|
+
for (const seg of segmenter.segment(remainingText)) {
|
|
197
|
+
const grapheme = seg.segment;
|
|
198
|
+
const graphemeWidth = visibleWidth(grapheme);
|
|
199
|
+
if (tokenChunkWidth + graphemeWidth > maxWidth && tokenChunk) {
|
|
200
|
+
chunks.push({
|
|
201
|
+
text: tokenChunk,
|
|
202
|
+
startIndex: tokenChunkStart,
|
|
203
|
+
endIndex: tokenCharIndex,
|
|
204
|
+
});
|
|
205
|
+
tokenChunk = grapheme;
|
|
206
|
+
tokenChunkWidth = graphemeWidth;
|
|
207
|
+
tokenChunkStart = tokenCharIndex;
|
|
208
|
+
} else {
|
|
209
|
+
tokenChunk += grapheme;
|
|
210
|
+
tokenChunkWidth += graphemeWidth;
|
|
211
|
+
}
|
|
212
|
+
tokenCharIndex += grapheme.length;
|
|
213
|
+
}
|
|
214
|
+
// Keep remainder as start of next chunk
|
|
215
|
+
if (tokenChunk) {
|
|
216
|
+
currentChunk = tokenChunk;
|
|
217
|
+
currentWidth = tokenChunkWidth;
|
|
218
|
+
chunkStartIndex = tokenChunkStart;
|
|
219
|
+
}
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Check if adding this token would exceed width
|
|
224
|
+
if (currentWidth + tokenWidth > maxWidth) {
|
|
225
|
+
// For wide-character tokens (e.g., CJK runs), prefer using remaining width before wrapping
|
|
226
|
+
// the whole token to the next line. This avoids leaving a short ASCII word alone.
|
|
227
|
+
if (currentChunk && !token.isWhitespace && currentWidth < maxWidth && hasWideGrapheme(token.text)) {
|
|
228
|
+
const remainingWidth = maxWidth - currentWidth;
|
|
229
|
+
const consumed = consumePrefixToWidth(token.text, remainingWidth);
|
|
230
|
+
if (consumed.text) {
|
|
231
|
+
chunks.push({
|
|
232
|
+
text: currentChunk + consumed.text,
|
|
233
|
+
startIndex: chunkStartIndex,
|
|
234
|
+
endIndex: token.startIndex + consumed.len,
|
|
235
|
+
});
|
|
236
|
+
const remainder = token.text.slice(consumed.len);
|
|
237
|
+
currentChunk = remainder;
|
|
238
|
+
currentWidth = visibleWidth(remainder);
|
|
239
|
+
chunkStartIndex = token.startIndex + consumed.len;
|
|
240
|
+
atLineStart = false;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
// Push current chunk (trimming trailing whitespace for display)
|
|
245
|
+
const trimmedChunk = currentChunk.trimEnd();
|
|
246
|
+
if (trimmedChunk || chunks.length === 0) {
|
|
247
|
+
chunks.push({
|
|
248
|
+
text: trimmedChunk,
|
|
249
|
+
startIndex: chunkStartIndex,
|
|
250
|
+
endIndex: chunkStartIndex + currentChunk.length,
|
|
251
|
+
});
|
|
252
|
+
} else {
|
|
253
|
+
// All-whitespace chunk collapsed away: keep its span mapped on the
|
|
254
|
+
// previous chunk so cursor positions inside it stay addressable.
|
|
255
|
+
const prev = chunks[chunks.length - 1];
|
|
256
|
+
if (prev) prev.endIndex = chunkStartIndex + currentChunk.length;
|
|
257
|
+
}
|
|
258
|
+
// Start new line - skip leading whitespace
|
|
259
|
+
atLineStart = true;
|
|
260
|
+
if (token.isWhitespace) {
|
|
261
|
+
// Extend the preceding chunk over the whitespace run skipped at the wrap
|
|
262
|
+
// point; otherwise cursor positions inside it map to no layout line.
|
|
263
|
+
const prev = chunks[chunks.length - 1];
|
|
264
|
+
if (prev) prev.endIndex = token.endIndex;
|
|
265
|
+
currentChunk = "";
|
|
266
|
+
currentWidth = 0;
|
|
267
|
+
chunkStartIndex = token.endIndex;
|
|
268
|
+
} else {
|
|
269
|
+
currentChunk = token.text;
|
|
270
|
+
currentWidth = tokenWidth;
|
|
271
|
+
chunkStartIndex = token.startIndex;
|
|
272
|
+
atLineStart = false;
|
|
273
|
+
}
|
|
274
|
+
} else {
|
|
275
|
+
// Add token to current chunk
|
|
276
|
+
currentChunk += token.text;
|
|
277
|
+
currentWidth += tokenWidth;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Push final chunk
|
|
282
|
+
if (currentChunk) {
|
|
283
|
+
chunks.push({
|
|
284
|
+
text: currentChunk,
|
|
285
|
+
startIndex: chunkStartIndex,
|
|
286
|
+
endIndex: line.length,
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
return chunks.length > 0 ? chunks : [{ text: "", startIndex: 0, endIndex: 0 }];
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Visual cell column of code-unit `offset` within `text`, counted by grapheme walk. */
|
|
294
|
+
function visualColAtOffset(text: string, offset: number): number {
|
|
295
|
+
if (offset <= 0) return 0;
|
|
296
|
+
let col = 0;
|
|
297
|
+
for (const seg of segmenter.segment(text)) {
|
|
298
|
+
if (seg.index >= offset) break;
|
|
299
|
+
col += visibleWidth(seg.segment);
|
|
300
|
+
}
|
|
301
|
+
return col;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Code-unit offset of visual cell `col` within `text`, snapped to a grapheme
|
|
305
|
+
* boundary so the result never splits a surrogate pair or cluster. */
|
|
306
|
+
function offsetAtVisualCol(text: string, col: number): number {
|
|
307
|
+
if (col <= 0) return 0;
|
|
308
|
+
let current = 0;
|
|
309
|
+
for (const seg of segmenter.segment(text)) {
|
|
310
|
+
const width = visibleWidth(seg.segment);
|
|
311
|
+
if (current + width > col) return seg.index;
|
|
312
|
+
current += width;
|
|
313
|
+
}
|
|
314
|
+
return text.length;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Highest visual column the cursor may occupy on a wrap segment: the full width
|
|
318
|
+
* on a logical line's last segment, otherwise just before the final grapheme
|
|
319
|
+
* (the segment end is the next segment's start). */
|
|
320
|
+
function maxSegmentVisualCol(text: string, isLastSegment: boolean): number {
|
|
321
|
+
let total = 0;
|
|
322
|
+
let lastWidth = 0;
|
|
323
|
+
for (const seg of segmenter.segment(text)) {
|
|
324
|
+
lastWidth = visibleWidth(seg.segment);
|
|
325
|
+
total += lastWidth;
|
|
326
|
+
}
|
|
327
|
+
return isLastSegment ? total : Math.max(0, total - lastWidth);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const DEFAULT_PAGE_SCROLL_LINES = 10;
|
|
331
|
+
|
|
332
|
+
const MAX_UNDO_STACK = 100;
|
|
333
|
+
|
|
334
|
+
interface EditorState {
|
|
335
|
+
lines: string[];
|
|
336
|
+
cursorLine: number;
|
|
337
|
+
cursorCol: number;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
interface LayoutLine {
|
|
341
|
+
text: string;
|
|
342
|
+
hasCursor: boolean;
|
|
343
|
+
cursorPos?: number;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export interface EditorTheme {
|
|
347
|
+
borderColor: (str: string) => string;
|
|
348
|
+
selectList: SelectListTheme;
|
|
349
|
+
symbols: SymbolTheme;
|
|
350
|
+
editorPaddingX?: number;
|
|
351
|
+
/** Style function for inline hint/ghost text (dim text after cursor) */
|
|
352
|
+
hintStyle?: (text: string) => string;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export interface EditorTopBorder {
|
|
356
|
+
/** The status content (already styled) */
|
|
357
|
+
content: string;
|
|
358
|
+
/** Visible width of the content */
|
|
359
|
+
width: number;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
interface HistoryEntry {
|
|
363
|
+
prompt: string;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
interface HistoryStorage {
|
|
367
|
+
add(prompt: string, cwd?: string): Promise<void>;
|
|
368
|
+
getRecent(limit: number): HistoryEntry[];
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
type HistoryCursorAnchor = "start" | "end";
|
|
372
|
+
|
|
373
|
+
export class Editor implements Component, Focusable {
|
|
374
|
+
#state: EditorState = {
|
|
375
|
+
lines: [""],
|
|
376
|
+
cursorLine: 0,
|
|
377
|
+
cursorCol: 0,
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
/** Focusable interface - set by TUI when focus changes */
|
|
381
|
+
focused: boolean = false;
|
|
382
|
+
|
|
383
|
+
#theme: EditorTheme;
|
|
384
|
+
#useTerminalCursor = false;
|
|
385
|
+
|
|
386
|
+
/** When set, replaces the normal cursor glyph at end-of-text with this ANSI-styled string. */
|
|
387
|
+
cursorOverride: string | undefined;
|
|
388
|
+
/** Display width of the cursorOverride glyph (needed because override may contain ANSI escapes). */
|
|
389
|
+
cursorOverrideWidth: number | undefined;
|
|
390
|
+
/** Optional hook that styles displayed input text with zero-width ANSI escapes.
|
|
391
|
+
* MUST preserve visible width (may only add SGR codes, never glyphs). Applied per
|
|
392
|
+
* layout line to the user-text segments — never to the cursor glyph or inline hint. */
|
|
393
|
+
decorateText: ((text: string) => string) | undefined;
|
|
394
|
+
#promptGutter: string | undefined;
|
|
395
|
+
|
|
396
|
+
// Store last layout width for cursor navigation
|
|
397
|
+
#lastLayoutWidth: number = 80;
|
|
398
|
+
// Word-wrap result cache shared by #layoutText, #buildVisualLineMap, and key
|
|
399
|
+
// handlers within a frame. Line text is a sound key (strings are immutable);
|
|
400
|
+
// cleared on width change and size-bounded so stale lines don't accumulate.
|
|
401
|
+
#wrapCache = new Map<string, TextChunk[]>();
|
|
402
|
+
#wrapCacheWidth = -1;
|
|
403
|
+
#paddingXOverride: number | undefined;
|
|
404
|
+
#maxHeight?: number;
|
|
405
|
+
#scrollOffset: number = 0;
|
|
406
|
+
|
|
407
|
+
// Emacs-style kill ring
|
|
408
|
+
#killRing = new KillRing();
|
|
409
|
+
#lastAction: "kill" | "yank" | "type-word" | null = null;
|
|
410
|
+
|
|
411
|
+
// Character jump mode
|
|
412
|
+
#jumpMode: "forward" | "backward" | null = null;
|
|
413
|
+
|
|
414
|
+
// Preferred visual column for vertical cursor movement (sticky column)
|
|
415
|
+
#preferredVisualCol: number | null = null;
|
|
416
|
+
|
|
417
|
+
// Border color (can be changed dynamically)
|
|
418
|
+
borderColor: (str: string) => string;
|
|
419
|
+
|
|
420
|
+
// Autocomplete support
|
|
421
|
+
#autocompleteProvider?: AutocompleteProvider;
|
|
422
|
+
#autocompleteList?: SelectList;
|
|
423
|
+
#autocompleteState: "regular" | "force" | null = null;
|
|
424
|
+
#autocompletePrefix: string = "";
|
|
425
|
+
#autocompleteRequestId: number = 0;
|
|
426
|
+
#autocompleteMaxVisible: number = 5;
|
|
427
|
+
onAutocompleteUpdate?: () => void;
|
|
428
|
+
|
|
429
|
+
// Paste tracking for large pastes
|
|
430
|
+
#pastes: Map<number, string> = new Map();
|
|
431
|
+
#pasteCounter: number = 0;
|
|
432
|
+
|
|
433
|
+
/** Optional pattern matching atomic placeholder tokens (e.g. `[Image #1, 800x600]` or
|
|
434
|
+
* `[Paste #2, +30 lines]`) that the editor treats as indivisible: a backspace or forward-delete
|
|
435
|
+
* landing on any character of a token removes the whole token instead of corrupting it into
|
|
436
|
+
* stray text. MUST be a global regex; the editor recompiles a private copy so its `lastIndex`
|
|
437
|
+
* is never shared with the caller. */
|
|
438
|
+
atomicTokenPattern: RegExp | undefined;
|
|
439
|
+
#atomicTokenSource: string | undefined;
|
|
440
|
+
#atomicTokenRe: RegExp | undefined;
|
|
441
|
+
|
|
442
|
+
// Bracketed paste mode buffering
|
|
443
|
+
#pasteHandler = new BracketedPasteHandler();
|
|
444
|
+
|
|
445
|
+
// Prompt history for up/down navigation
|
|
446
|
+
#history: string[] = [];
|
|
447
|
+
#historyIndex: number = -1; // -1 = not browsing, 0 = most recent, 1 = older, etc.
|
|
448
|
+
#historyStorage?: HistoryStorage;
|
|
449
|
+
|
|
450
|
+
// Undo stack for editor state changes
|
|
451
|
+
#undoStack: EditorState[] = [];
|
|
452
|
+
#suspendUndo = false;
|
|
453
|
+
|
|
454
|
+
// Debounce timer for autocomplete updates
|
|
455
|
+
#autocompleteTimeout?: NodeJS.Timeout;
|
|
456
|
+
|
|
457
|
+
onSubmit?: (text: string) => void | Promise<void>;
|
|
458
|
+
onAltEnter?: (text: string) => void;
|
|
459
|
+
onChange?: (text: string) => void;
|
|
460
|
+
/** Called for a "marker-sized" paste — the point where the editor would otherwise collapse it
|
|
461
|
+
* into a `[Paste #N]` token (> 10 lines or > 1000 characters). Return `true` to intercept:
|
|
462
|
+
* the editor inserts nothing and records no undo state, leaving insertion to the host (e.g. a
|
|
463
|
+
* "wrap in a code block / XML / attach as file" menu for very large pastes), which re-inserts
|
|
464
|
+
* via {@link insertPaste} or {@link insertText}. Return `false` (or leave unset) for the
|
|
465
|
+
* default collapse-to-marker behavior. `lineCount` is the sanitized paste's line count. */
|
|
466
|
+
onLargePaste?: (text: string, lineCount: number) => boolean;
|
|
467
|
+
onAutocompleteCancel?: () => void;
|
|
468
|
+
disableSubmit: boolean = false;
|
|
469
|
+
|
|
470
|
+
// Custom top border (for status line integration). Either an eager `content`
|
|
471
|
+
// (set once, reused every frame) or a `provider` that recomputes lazily just
|
|
472
|
+
// before the editor paints — the second form lets the host coalesce
|
|
473
|
+
// per-event rebuilds down to one per rendered frame (see #4145).
|
|
474
|
+
#topBorderContent?: EditorTopBorder;
|
|
475
|
+
#topBorderProvider?: (availableWidth: number) => EditorTopBorder | undefined;
|
|
476
|
+
#borderVisible = true;
|
|
477
|
+
|
|
478
|
+
constructor(theme: EditorTheme) {
|
|
479
|
+
this.#theme = theme;
|
|
480
|
+
this.borderColor = theme.borderColor;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
setAutocompleteProvider(provider: AutocompleteProvider): void {
|
|
484
|
+
this.#autocompleteProvider = provider;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* Set custom content for the top border (e.g., status line).
|
|
489
|
+
* Pass undefined to use the default plain border.
|
|
490
|
+
*
|
|
491
|
+
* Eager: the passed value is cached and reused every frame. Callers that
|
|
492
|
+
* mutate status upstream must recompute and call this again. Prefer
|
|
493
|
+
* {@link setTopBorderProvider} for high-frequency updates — it collapses
|
|
494
|
+
* per-event rebuilds to one per painted frame.
|
|
495
|
+
*/
|
|
496
|
+
setTopBorder(content: EditorTopBorder | undefined): void {
|
|
497
|
+
this.#topBorderContent = content;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* Install a lazy provider invoked once per editor render with the current
|
|
502
|
+
* `availableWidth`. Overrides any eager content set via {@link setTopBorder}
|
|
503
|
+
* — pass `undefined` to detach and fall back to the eager slot.
|
|
504
|
+
*
|
|
505
|
+
* Use this when the top border derives from state that mutates far faster
|
|
506
|
+
* than the render cadence (session events, streaming, subagent updates).
|
|
507
|
+
* The TUI already throttles renders, so a provider is invoked at most once
|
|
508
|
+
* per frame and never does wasted work between paints.
|
|
509
|
+
*/
|
|
510
|
+
setTopBorderProvider(provider: ((availableWidth: number) => EditorTopBorder | undefined) | undefined): void {
|
|
511
|
+
this.#topBorderProvider = provider;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Show or hide the editor border chrome.
|
|
516
|
+
*/
|
|
517
|
+
setBorderVisible(borderVisible: boolean): void {
|
|
518
|
+
this.#borderVisible = borderVisible;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
setPromptGutter(promptGutter: string | undefined): void {
|
|
522
|
+
this.#promptGutter = promptGutter;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Get the available width for top border content given a total terminal width.
|
|
527
|
+
* Accounts for the border characters and horizontal padding when visible.
|
|
528
|
+
*/
|
|
529
|
+
getTopBorderAvailableWidth(terminalWidth: number): number {
|
|
530
|
+
const paddingX = this.#getEditorPaddingX();
|
|
531
|
+
const borderWidth = this.#getHorizontalChromeWidth(paddingX);
|
|
532
|
+
return Math.max(0, terminalWidth - borderWidth * 2);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Use the real terminal cursor instead of rendering a cursor glyph.
|
|
537
|
+
*/
|
|
538
|
+
setUseTerminalCursor(useTerminalCursor: boolean): void {
|
|
539
|
+
this.#useTerminalCursor = useTerminalCursor;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
getUseTerminalCursor(): boolean {
|
|
543
|
+
return this.#useTerminalCursor;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
setMaxHeight(maxHeight: number | undefined): void {
|
|
547
|
+
if (this.#maxHeight === maxHeight) return;
|
|
548
|
+
this.#maxHeight = maxHeight;
|
|
549
|
+
// Don't reset scrollOffset — #updateScrollOffset will clamp it on next render
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
setPaddingX(paddingX: number): void {
|
|
553
|
+
this.#paddingXOverride = Math.max(0, paddingX);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
getAutocompleteMaxVisible(): number {
|
|
557
|
+
return this.#autocompleteMaxVisible;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
setAutocompleteMaxVisible(maxVisible: number): void {
|
|
561
|
+
const newMaxVisible = Number.isFinite(maxVisible) ? Math.max(3, Math.min(20, Math.floor(maxVisible))) : 5;
|
|
562
|
+
if (this.#autocompleteMaxVisible !== newMaxVisible) {
|
|
563
|
+
this.#autocompleteMaxVisible = newMaxVisible;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
setHistoryStorage(storage: HistoryStorage): void {
|
|
568
|
+
this.#historyStorage = storage;
|
|
569
|
+
const recent = storage.getRecent(100);
|
|
570
|
+
this.#history = recent.map(entry => entry.prompt);
|
|
571
|
+
this.#historyIndex = -1;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Add a prompt to history for up/down arrow navigation.
|
|
576
|
+
* Called after successful submission.
|
|
577
|
+
*/
|
|
578
|
+
addToHistory(text: string): void {
|
|
579
|
+
const trimmed = text.trim();
|
|
580
|
+
if (!trimmed) return;
|
|
581
|
+
// Don't add consecutive duplicates
|
|
582
|
+
if (this.#history.length > 0 && this.#history[0] === trimmed) return;
|
|
583
|
+
this.#history.unshift(trimmed);
|
|
584
|
+
// Limit history size
|
|
585
|
+
if (this.#history.length > 100) {
|
|
586
|
+
this.#history.pop();
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
const stor = this.#historyStorage;
|
|
590
|
+
if (stor) {
|
|
591
|
+
stor.add(trimmed, getProjectDir()).catch(error => {
|
|
592
|
+
logger.error("HistoryStorage add failed", { error: String(error) });
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
#isEditorEmpty(): boolean {
|
|
598
|
+
return this.#state.lines.length === 1 && this.#state.lines[0] === "";
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
#isOnFirstVisualLine(): boolean {
|
|
602
|
+
const visualLines = this.#buildVisualLineMap(this.#lastLayoutWidth);
|
|
603
|
+
const currentVisualLine = this.#findCurrentVisualLine(visualLines);
|
|
604
|
+
return currentVisualLine === 0;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
#isOnLastVisualLine(): boolean {
|
|
608
|
+
const visualLines = this.#buildVisualLineMap(this.#lastLayoutWidth);
|
|
609
|
+
const currentVisualLine = this.#findCurrentVisualLine(visualLines);
|
|
610
|
+
return currentVisualLine === visualLines.length - 1;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
#navigateHistory(direction: 1 | -1): void {
|
|
614
|
+
this.#resetKillSequence();
|
|
615
|
+
if (this.#history.length === 0) return;
|
|
616
|
+
const newIndex = this.#historyIndex - direction; // Up(-1) increases index, Down(1) decreases
|
|
617
|
+
if (newIndex < -1 || newIndex >= this.#history.length) return;
|
|
618
|
+
this.#historyIndex = newIndex;
|
|
619
|
+
if (this.#historyIndex === -1) {
|
|
620
|
+
// Returned to "current" state - clear editor
|
|
621
|
+
this.#setTextInternal("", "end");
|
|
622
|
+
} else {
|
|
623
|
+
const cursorAnchor: HistoryCursorAnchor = direction === -1 ? "start" : "end";
|
|
624
|
+
this.#setTextInternal(this.#history[this.#historyIndex] || "", cursorAnchor);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
/** Internal setText that doesn't reset history state - used by navigateHistory */
|
|
628
|
+
#setTextInternal(text: string, cursorAnchor: HistoryCursorAnchor = "end"): void {
|
|
629
|
+
this.#undoStack.length = 0;
|
|
630
|
+
const lines = sanitizeLoadedText(text).split("\n");
|
|
631
|
+
this.#state.lines = lines.length === 0 ? [""] : lines;
|
|
632
|
+
if (cursorAnchor === "start") {
|
|
633
|
+
this.#state.cursorLine = 0;
|
|
634
|
+
this.#setCursorCol(0);
|
|
635
|
+
} else {
|
|
636
|
+
this.#state.cursorLine = this.#state.lines.length - 1;
|
|
637
|
+
this.#setCursorCol(this.#state.lines[this.#state.cursorLine]?.length || 0);
|
|
638
|
+
}
|
|
639
|
+
if (this.onChange) {
|
|
640
|
+
this.onChange(this.getText());
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
invalidate(): void {
|
|
645
|
+
// No cached state to invalidate currently
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
#getEditorPaddingX(): number {
|
|
649
|
+
const padding = this.#paddingXOverride ?? this.#theme.editorPaddingX ?? 2;
|
|
650
|
+
return Math.max(0, padding);
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
#getHorizontalChromeWidth(paddingX: number): number {
|
|
654
|
+
return this.#borderVisible ? paddingX + 1 : 0;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
#getPromptGutterWidth(width: number, paddingX: number): number {
|
|
658
|
+
if (this.#borderVisible || !this.#promptGutter) return 0;
|
|
659
|
+
const chromeWidth = 2 * this.#getHorizontalChromeWidth(paddingX);
|
|
660
|
+
const availableWidth = Math.max(0, width - chromeWidth);
|
|
661
|
+
return Math.min(visibleWidth(this.#promptGutter), availableWidth);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
#getPromptGutter(
|
|
665
|
+
width: number,
|
|
666
|
+
paddingX: number,
|
|
667
|
+
): { firstLine: string; continuation: string; width: number } | undefined {
|
|
668
|
+
if (this.#borderVisible || !this.#promptGutter) return undefined;
|
|
669
|
+
const gutterWidth = this.#getPromptGutterWidth(width, paddingX);
|
|
670
|
+
if (gutterWidth === 0) return undefined;
|
|
671
|
+
return {
|
|
672
|
+
firstLine: sliceByColumn(this.#promptGutter, 0, gutterWidth, true),
|
|
673
|
+
continuation: padding(gutterWidth),
|
|
674
|
+
width: gutterWidth,
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
#getContentWidth(width: number, paddingX: number): number {
|
|
679
|
+
const chromeWidth = 2 * this.#getHorizontalChromeWidth(paddingX);
|
|
680
|
+
return Math.max(0, width - chromeWidth - this.#getPromptGutterWidth(width, paddingX));
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
#getLayoutWidth(width: number, paddingX: number): number {
|
|
684
|
+
const contentWidth = this.#getContentWidth(width, paddingX);
|
|
685
|
+
const cursorReserve = this.#borderVisible && paddingX === 0 ? 1 : 0;
|
|
686
|
+
// Keep cursor/scroll layout addressable even when a borderless prompt gutter consumes every visible column.
|
|
687
|
+
return Math.max(1, contentWidth - cursorReserve);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
#getVisibleContentHeight(contentLines: number): number {
|
|
691
|
+
if (this.#maxHeight === undefined) return contentLines;
|
|
692
|
+
const verticalChrome = this.#borderVisible ? 2 : 0;
|
|
693
|
+
return Math.max(1, this.#maxHeight - verticalChrome);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/** Apply the optional input decorator to a plain (ANSI-free) text segment.
|
|
697
|
+
* Decoration only adds zero-width SGR codes, so visible width is unchanged.
|
|
698
|
+
* Splits around CURSOR_MARKER so each user-text segment is decorated in
|
|
699
|
+
* isolation: the marker begins with ESC, and a keyword regex that pins
|
|
700
|
+
* the right boundary with `(?!\S)` would otherwise reject an otherwise-
|
|
701
|
+
* valid match at the cursor seam (e.g. `ultrathink` immediately followed
|
|
702
|
+
* by the marker stops glowing until a trailing character is typed). */
|
|
703
|
+
#decorate(text: string): string {
|
|
704
|
+
const decorate = this.decorateText;
|
|
705
|
+
if (decorate === undefined || text.length === 0) return text;
|
|
706
|
+
const idx = text.indexOf(CURSOR_MARKER);
|
|
707
|
+
if (idx === -1) return decorate(text);
|
|
708
|
+
const before = text.slice(0, idx);
|
|
709
|
+
const after = text.slice(idx + CURSOR_MARKER.length);
|
|
710
|
+
return (before.length > 0 ? decorate(before) : "") + CURSOR_MARKER + (after.length > 0 ? decorate(after) : "");
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
#getStyledInputCursor(): { text: string; width: number } {
|
|
714
|
+
const cursorChar = this.#theme.symbols.inputCursor;
|
|
715
|
+
// Keep the software cursor steady. Ghostty/cmux can leave visual
|
|
716
|
+
// afterimages for SGR blink cells during rapid input-row repaints.
|
|
717
|
+
return { text: cursorChar, width: visibleWidth(cursorChar) };
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
#renderEndOfLineCursorAtWidthLimit(
|
|
721
|
+
before: string,
|
|
722
|
+
marker: string,
|
|
723
|
+
maxWidth: number,
|
|
724
|
+
replacement?: { text: string; width: number },
|
|
725
|
+
): { text: string; width: number } {
|
|
726
|
+
const beforeGraphemes = [...segmenter.segment(before)];
|
|
727
|
+
const lastGrapheme = beforeGraphemes[beforeGraphemes.length - 1]?.segment;
|
|
728
|
+
const lastGraphemeWidth = lastGrapheme ? visibleWidth(lastGrapheme) : 0;
|
|
729
|
+
const builtInCursor = this.#getStyledInputCursor();
|
|
730
|
+
const fallbackReplacement = lastGrapheme
|
|
731
|
+
? { text: `\x1b[7m${lastGrapheme}\x1b[0m`, width: lastGraphemeWidth }
|
|
732
|
+
: builtInCursor;
|
|
733
|
+
const clampReplacement = (candidate: { text: string; width: number }): { text: string; width: number } => {
|
|
734
|
+
let text = sliceByColumn(candidate.text, 0, maxWidth, true);
|
|
735
|
+
let width = visibleWidth(text);
|
|
736
|
+
if (width > maxWidth) {
|
|
737
|
+
text = "";
|
|
738
|
+
width = 0;
|
|
739
|
+
}
|
|
740
|
+
return { text, width };
|
|
741
|
+
};
|
|
742
|
+
|
|
743
|
+
let clampedReplacement = clampReplacement(replacement ?? fallbackReplacement);
|
|
744
|
+
if (replacement && clampedReplacement.width === 0) {
|
|
745
|
+
// A custom override that cannot fit at all should first fall back to the highlighted tail.
|
|
746
|
+
clampedReplacement = clampReplacement(fallbackReplacement);
|
|
747
|
+
}
|
|
748
|
+
if (lastGrapheme && clampedReplacement.width === 0) {
|
|
749
|
+
// If even the highlighted trailing grapheme cannot fit, show the built-in single-column cursor.
|
|
750
|
+
clampedReplacement = clampReplacement(builtInCursor);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
const replacedSpanWidth = Math.min(maxWidth, Math.max(lastGraphemeWidth, clampedReplacement.width));
|
|
754
|
+
const prefixWidth = Math.max(0, maxWidth - replacedSpanWidth);
|
|
755
|
+
const beforePrefix = sliceByColumn(before, 0, prefixWidth, true);
|
|
756
|
+
const replacementPad = padding(Math.max(0, replacedSpanWidth - clampedReplacement.width));
|
|
757
|
+
return {
|
|
758
|
+
text: `${beforePrefix}${replacementPad}${clampedReplacement.text}${marker}`,
|
|
759
|
+
width: visibleWidth(beforePrefix) + replacedSpanWidth,
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
#renderTerminalCursorMarker(text: string, marker: string, maxWidth: number): string {
|
|
764
|
+
if (!marker) return text;
|
|
765
|
+
if (visibleWidth(text) < maxWidth) {
|
|
766
|
+
return text + marker;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
let insertAt = text.length;
|
|
770
|
+
let offset = 0;
|
|
771
|
+
for (const seg of segmenter.segment(text)) {
|
|
772
|
+
if (visibleWidth(seg.segment) > 0) {
|
|
773
|
+
insertAt = offset;
|
|
774
|
+
}
|
|
775
|
+
offset += seg.segment.length;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
return `${text.slice(0, insertAt)}${marker}${text.slice(insertAt)}`;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
#getPageScrollStep(totalVisualLines: number): number {
|
|
782
|
+
const visibleHeight =
|
|
783
|
+
this.#maxHeight === undefined ? DEFAULT_PAGE_SCROLL_LINES : this.#getVisibleContentHeight(totalVisualLines);
|
|
784
|
+
return Math.max(1, visibleHeight - 1);
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
#updateScrollOffset(layoutWidth: number, layoutLines: LayoutLine[], visibleHeight: number): void {
|
|
788
|
+
if (layoutLines.length <= visibleHeight) {
|
|
789
|
+
this.#scrollOffset = 0;
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const visualLines = this.#buildVisualLineMap(layoutWidth);
|
|
794
|
+
const cursorLine = this.#findCurrentVisualLine(visualLines);
|
|
795
|
+
if (cursorLine < this.#scrollOffset) {
|
|
796
|
+
this.#scrollOffset = cursorLine;
|
|
797
|
+
} else if (cursorLine >= this.#scrollOffset + visibleHeight) {
|
|
798
|
+
this.#scrollOffset = cursorLine - visibleHeight + 1;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
const maxOffset = Math.max(0, layoutLines.length - visibleHeight);
|
|
802
|
+
this.#scrollOffset = Math.min(this.#scrollOffset, maxOffset);
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
render(width: number): readonly string[] {
|
|
806
|
+
const paddingX = this.#getEditorPaddingX();
|
|
807
|
+
const borderVisible = this.#borderVisible;
|
|
808
|
+
const promptGutter = this.#getPromptGutter(width, paddingX);
|
|
809
|
+
const contentAreaWidth = this.#getContentWidth(width, paddingX);
|
|
810
|
+
const layoutWidth = this.#getLayoutWidth(width, paddingX);
|
|
811
|
+
this.#lastLayoutWidth = layoutWidth;
|
|
812
|
+
|
|
813
|
+
// Box-drawing characters for rounded corners
|
|
814
|
+
const box = this.#theme.symbols.boxRound;
|
|
815
|
+
const borderWidth = this.#getHorizontalChromeWidth(paddingX);
|
|
816
|
+
const topLeft = this.borderColor(`${box.topLeft}${box.horizontal.repeat(paddingX)}`);
|
|
817
|
+
const topRight = this.borderColor(`${box.horizontal.repeat(paddingX)}${box.topRight}`);
|
|
818
|
+
const bottomLeft = this.borderColor(`${box.bottomLeft}${box.horizontal}${padding(Math.max(0, paddingX - 1))}`);
|
|
819
|
+
const horizontal = this.borderColor(box.horizontal);
|
|
820
|
+
|
|
821
|
+
// Layout the text
|
|
822
|
+
const layoutLines = this.#layoutText(layoutWidth);
|
|
823
|
+
const visibleContentHeight = this.#getVisibleContentHeight(layoutLines.length);
|
|
824
|
+
this.#updateScrollOffset(layoutWidth, layoutLines, visibleContentHeight);
|
|
825
|
+
const visibleLayoutLines = layoutLines.slice(this.#scrollOffset, this.#scrollOffset + visibleContentHeight);
|
|
826
|
+
|
|
827
|
+
const result: string[] = [];
|
|
828
|
+
|
|
829
|
+
if (borderVisible) {
|
|
830
|
+
// Render top border: ╭─ [status content] ────────────────╮
|
|
831
|
+
const topFillWidth = Math.max(0, width - borderWidth * 2);
|
|
832
|
+
// Provider (lazy) wins over eager content — a host that installs both
|
|
833
|
+
// wants the coalesced path; falling back to eager keeps existing
|
|
834
|
+
// setTopBorder callers working unchanged.
|
|
835
|
+
const topBorder = this.#topBorderProvider ? this.#topBorderProvider(topFillWidth) : this.#topBorderContent;
|
|
836
|
+
if (topBorder) {
|
|
837
|
+
const { content, width: statusWidth } = topBorder;
|
|
838
|
+
if (statusWidth <= topFillWidth) {
|
|
839
|
+
// Status fits - add fill after it
|
|
840
|
+
const fillWidth = topFillWidth - statusWidth;
|
|
841
|
+
result.push(topLeft + content + this.borderColor(box.horizontal.repeat(fillWidth)) + topRight);
|
|
842
|
+
} else {
|
|
843
|
+
// Status too long - truncate it
|
|
844
|
+
const truncated = truncateToWidth(content, Math.max(0, topFillWidth - 1));
|
|
845
|
+
const truncatedWidth = visibleWidth(truncated);
|
|
846
|
+
const fillWidth = Math.max(0, topFillWidth - truncatedWidth);
|
|
847
|
+
result.push(topLeft + truncated + this.borderColor(box.horizontal.repeat(fillWidth)) + topRight);
|
|
848
|
+
}
|
|
849
|
+
} else {
|
|
850
|
+
result.push(topLeft + horizontal.repeat(topFillWidth) + topRight);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// Render each layout line
|
|
855
|
+
// Emit hardware cursor marker only when focused and not showing autocomplete
|
|
856
|
+
const emitCursorMarker = this.focused && !this.#autocompleteState;
|
|
857
|
+
const lineContentWidth = contentAreaWidth;
|
|
858
|
+
|
|
859
|
+
// Compute inline hint text (dim ghost text after cursor)
|
|
860
|
+
const inlineHint = this.#getInlineHint();
|
|
861
|
+
const hintStyle = this.#theme.hintStyle ?? ((t: string) => `\x1b[2m${t}\x1b[0m`);
|
|
862
|
+
|
|
863
|
+
for (let visibleIndex = 0; visibleIndex < visibleLayoutLines.length; visibleIndex++) {
|
|
864
|
+
const layoutLine = visibleLayoutLines[visibleIndex]!;
|
|
865
|
+
let displayText = layoutLine.text;
|
|
866
|
+
let displayWidth = visibleWidth(layoutLine.text);
|
|
867
|
+
let cursorPaddingOverflow = 0;
|
|
868
|
+
let decorated = false;
|
|
869
|
+
const showPromptGutter = promptGutter !== undefined && visibleIndex === 0;
|
|
870
|
+
const gutterText =
|
|
871
|
+
promptGutter === undefined ? "" : showPromptGutter ? promptGutter.firstLine : promptGutter.continuation;
|
|
872
|
+
|
|
873
|
+
// Add cursor if this line has it
|
|
874
|
+
const hasCursor = layoutLine.hasCursor && layoutLine.cursorPos !== undefined;
|
|
875
|
+
const marker = emitCursorMarker ? CURSOR_MARKER : "";
|
|
876
|
+
|
|
877
|
+
if (!borderVisible && displayWidth > lineContentWidth) {
|
|
878
|
+
displayText = sliceByColumn(displayText, 0, lineContentWidth, true);
|
|
879
|
+
displayWidth = visibleWidth(displayText);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
if (!borderVisible && lineContentWidth === 0) {
|
|
883
|
+
if (hasCursor && !this.#useTerminalCursor) {
|
|
884
|
+
const zeroWidthCursorBudget = visibleWidth(gutterText);
|
|
885
|
+
const zeroWidthCursorReplacement = this.cursorOverride
|
|
886
|
+
? { text: this.cursorOverride, width: this.cursorOverrideWidth ?? 1 }
|
|
887
|
+
: this.#getStyledInputCursor();
|
|
888
|
+
if (showPromptGutter && zeroWidthCursorBudget > 0) {
|
|
889
|
+
// Keep the leading prompt glyph visible when the gutter consumes the whole row.
|
|
890
|
+
const promptGlyph = [...segmenter.segment(gutterText)][0]?.segment ?? "";
|
|
891
|
+
const promptGlyphWidth = visibleWidth(promptGlyph);
|
|
892
|
+
const remainingCursorWidth = Math.max(0, zeroWidthCursorBudget - promptGlyphWidth);
|
|
893
|
+
if (remainingCursorWidth === 0) {
|
|
894
|
+
result.push(`\x1b[7m${promptGlyph}\x1b[0m${marker}`);
|
|
895
|
+
} else {
|
|
896
|
+
const widthLimitedCursor = this.#renderEndOfLineCursorAtWidthLimit(
|
|
897
|
+
"",
|
|
898
|
+
marker,
|
|
899
|
+
remainingCursorWidth,
|
|
900
|
+
zeroWidthCursorReplacement,
|
|
901
|
+
);
|
|
902
|
+
result.push(`${promptGlyph}${widthLimitedCursor.text}`);
|
|
903
|
+
}
|
|
904
|
+
} else {
|
|
905
|
+
const widthLimitedCursor = this.#renderEndOfLineCursorAtWidthLimit(
|
|
906
|
+
gutterText,
|
|
907
|
+
marker,
|
|
908
|
+
zeroWidthCursorBudget,
|
|
909
|
+
zeroWidthCursorReplacement,
|
|
910
|
+
);
|
|
911
|
+
result.push(widthLimitedCursor.text);
|
|
912
|
+
}
|
|
913
|
+
} else if (hasCursor && this.#useTerminalCursor) {
|
|
914
|
+
result.push(this.#renderTerminalCursorMarker(gutterText, marker, visibleWidth(gutterText)));
|
|
915
|
+
} else {
|
|
916
|
+
result.push(gutterText + (hasCursor ? marker : ""));
|
|
917
|
+
}
|
|
918
|
+
continue;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
if (hasCursor && this.#useTerminalCursor) {
|
|
922
|
+
if (marker) {
|
|
923
|
+
const before = displayText.slice(0, layoutLine.cursorPos);
|
|
924
|
+
const after = displayText.slice(layoutLine.cursorPos);
|
|
925
|
+
if (after.length === 0 && inlineHint) {
|
|
926
|
+
const availWidth = Math.max(0, lineContentWidth - displayWidth);
|
|
927
|
+
const hintText = hintStyle(truncateToWidth(inlineHint, availWidth));
|
|
928
|
+
displayText = before + marker + hintText;
|
|
929
|
+
displayWidth += Math.min(visibleWidth(inlineHint), availWidth);
|
|
930
|
+
} else if (after.length === 0 && !borderVisible && displayWidth >= lineContentWidth) {
|
|
931
|
+
displayText = this.#renderTerminalCursorMarker(before, marker, lineContentWidth);
|
|
932
|
+
} else {
|
|
933
|
+
displayText = before + marker + after;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
} else if (hasCursor && !this.#useTerminalCursor) {
|
|
937
|
+
const before = displayText.slice(0, layoutLine.cursorPos);
|
|
938
|
+
const after = displayText.slice(layoutLine.cursorPos);
|
|
939
|
+
|
|
940
|
+
if (after.length > 0) {
|
|
941
|
+
// Cursor is on a character (grapheme) - replace it with highlighted version
|
|
942
|
+
// Get the first grapheme from 'after'
|
|
943
|
+
const afterGraphemes = [...segmenter.segment(after)];
|
|
944
|
+
const firstGrapheme = afterGraphemes[0]?.segment || "";
|
|
945
|
+
const restAfter = after.slice(firstGrapheme.length);
|
|
946
|
+
const cursor = `\x1b[7m${firstGrapheme}\x1b[0m`;
|
|
947
|
+
// Decorate the plain text on each side of the cursor glyph. The reverse-video
|
|
948
|
+
// reset (\x1b[0m) ends in "m" (a word char), so a boundary match on restAfter
|
|
949
|
+
// would fail in the whole-line fallback below — decorate the segments here.
|
|
950
|
+
displayText = this.#decorate(before) + marker + cursor + this.#decorate(restAfter);
|
|
951
|
+
decorated = true;
|
|
952
|
+
// displayWidth stays the same - we're replacing, not adding
|
|
953
|
+
} else if (this.cursorOverride) {
|
|
954
|
+
// Cursor override replaces the normal end-of-text cursor glyph
|
|
955
|
+
const overrideWidth = this.cursorOverrideWidth ?? 1;
|
|
956
|
+
if (!borderVisible && displayWidth + overrideWidth > lineContentWidth) {
|
|
957
|
+
// Borderless editors have no spare padding cell for an end-of-line cursor glyph.
|
|
958
|
+
// Preserve cursorOverride by replacing the tail of the line with it.
|
|
959
|
+
const widthLimitedCursor = this.#renderEndOfLineCursorAtWidthLimit(before, marker, lineContentWidth, {
|
|
960
|
+
text: this.cursorOverride,
|
|
961
|
+
width: overrideWidth,
|
|
962
|
+
});
|
|
963
|
+
displayText = widthLimitedCursor.text;
|
|
964
|
+
displayWidth = widthLimitedCursor.width;
|
|
965
|
+
} else if (inlineHint) {
|
|
966
|
+
const availWidth = Math.max(0, lineContentWidth - displayWidth - overrideWidth);
|
|
967
|
+
const hintText = hintStyle(truncateToWidth(inlineHint, availWidth));
|
|
968
|
+
displayText = before + marker + this.cursorOverride + hintText;
|
|
969
|
+
displayWidth += overrideWidth + Math.min(visibleWidth(inlineHint), availWidth);
|
|
970
|
+
} else {
|
|
971
|
+
displayText = before + marker + this.cursorOverride;
|
|
972
|
+
displayWidth += overrideWidth;
|
|
973
|
+
}
|
|
974
|
+
} else {
|
|
975
|
+
// Cursor is at the end - add thin cursor glyph
|
|
976
|
+
const { text: cursor, width: cursorWidth } = this.#getStyledInputCursor();
|
|
977
|
+
if (!borderVisible && displayWidth + cursorWidth > lineContentWidth) {
|
|
978
|
+
// Borderless editors have no spare padding cell for an end-of-line cursor glyph.
|
|
979
|
+
// Highlight the last grapheme so the cursor stays visible without consuming width.
|
|
980
|
+
const widthLimitedCursor = this.#renderEndOfLineCursorAtWidthLimit(before, marker, lineContentWidth);
|
|
981
|
+
displayText = widthLimitedCursor.text;
|
|
982
|
+
displayWidth = widthLimitedCursor.width;
|
|
983
|
+
} else if (inlineHint) {
|
|
984
|
+
const availWidth = Math.max(0, lineContentWidth - displayWidth - cursorWidth);
|
|
985
|
+
const hintText = hintStyle(truncateToWidth(inlineHint, availWidth));
|
|
986
|
+
displayText = before + marker + cursor + hintText;
|
|
987
|
+
displayWidth += cursorWidth + Math.min(visibleWidth(inlineHint), availWidth);
|
|
988
|
+
} else {
|
|
989
|
+
displayText = before + marker + cursor;
|
|
990
|
+
displayWidth += cursorWidth;
|
|
991
|
+
}
|
|
992
|
+
if (displayWidth > lineContentWidth && paddingX > 0) {
|
|
993
|
+
cursorPaddingOverflow = displayWidth - lineContentWidth;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// No cursor on this line, or a branch that left the user text intact: decorate
|
|
999
|
+
// the whole line. `#decorate` splits around CURSOR_MARKER so a keyword glued to
|
|
1000
|
+
// the cursor still satisfies its right-boundary lookahead.
|
|
1001
|
+
if (!decorated) {
|
|
1002
|
+
displayText = this.#decorate(displayText);
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
const linePad = padding(Math.max(0, lineContentWidth - displayWidth));
|
|
1006
|
+
|
|
1007
|
+
if (!borderVisible) {
|
|
1008
|
+
result.push(gutterText + displayText + linePad);
|
|
1009
|
+
continue;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// All lines have consistent borders based on padding. When the end-of-line cursor
|
|
1013
|
+
// glyph (or a wide trailing grapheme) extends past `lineContentWidth`, shrink the
|
|
1014
|
+
// right chrome by the exact overflow count: drop padding spaces first, then the
|
|
1015
|
+
// trailing `─`, but never the corner/vertical bar itself.
|
|
1016
|
+
const isLastLine = visibleIndex === visibleLayoutLines.length - 1;
|
|
1017
|
+
const rightChromeCells = Math.max(1, paddingX + 1 - cursorPaddingOverflow);
|
|
1018
|
+
if (isLastLine) {
|
|
1019
|
+
const rightPad = Math.max(0, rightChromeCells - 2);
|
|
1020
|
+
const includeHorizontal = rightChromeCells >= 2;
|
|
1021
|
+
const bottomRightAdjusted = this.borderColor(
|
|
1022
|
+
`${padding(rightPad)}${includeHorizontal ? box.horizontal : ""}${box.bottomRight}`,
|
|
1023
|
+
);
|
|
1024
|
+
result.push(`${bottomLeft}${displayText}${linePad}${bottomRightAdjusted}`);
|
|
1025
|
+
} else {
|
|
1026
|
+
const leftBorder = this.borderColor(`${box.vertical}${padding(paddingX)}`);
|
|
1027
|
+
const rightBorder = this.borderColor(`${padding(Math.max(0, rightChromeCells - 1))}${box.vertical}`);
|
|
1028
|
+
result.push(leftBorder + displayText + linePad + rightBorder);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
// Add autocomplete list if active
|
|
1033
|
+
if (this.#autocompleteState && this.#autocompleteList) {
|
|
1034
|
+
const autocompleteResult = this.#autocompleteList.render(width);
|
|
1035
|
+
result.push(...autocompleteResult);
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
return result;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
handleInput(data: string): void {
|
|
1042
|
+
const kb = getKeybindings();
|
|
1043
|
+
|
|
1044
|
+
// Handle character jump mode (awaiting next character to jump to)
|
|
1045
|
+
if (this.#jumpMode !== null) {
|
|
1046
|
+
// Cancel if the hotkey is pressed again
|
|
1047
|
+
if (kb.matches(data, "tui.editor.jumpForward") || kb.matches(data, "tui.editor.jumpBackward")) {
|
|
1048
|
+
this.#jumpMode = null;
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
const printableText = extractPrintableText(data);
|
|
1053
|
+
if (printableText) {
|
|
1054
|
+
const direction = this.#jumpMode;
|
|
1055
|
+
this.#jumpMode = null;
|
|
1056
|
+
this.#jumpToChar(printableText, direction);
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
// Control character - cancel and fall through to normal handling
|
|
1061
|
+
this.#jumpMode = null;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// Handle bracketed paste mode
|
|
1065
|
+
const paste = this.#pasteHandler.process(data);
|
|
1066
|
+
if (paste.handled) {
|
|
1067
|
+
if (paste.pasteContent !== undefined) {
|
|
1068
|
+
this.#handlePaste(paste.pasteContent);
|
|
1069
|
+
if (paste.remaining.length > 0) {
|
|
1070
|
+
this.handleInput(paste.remaining);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
// Handle special key combinations first
|
|
1077
|
+
|
|
1078
|
+
// Ctrl+C is reserved by parent components for app-level handling.
|
|
1079
|
+
// Do not consume arbitrary user-bound "copy" keys here, since the editor
|
|
1080
|
+
// has no copy implementation and would make those keys disappear.
|
|
1081
|
+
if (matchesKey(data, "ctrl+c")) {
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
// Undo
|
|
1086
|
+
if (kb.matches(data, "tui.editor.undo")) {
|
|
1087
|
+
this.#applyUndo();
|
|
1088
|
+
return;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// Handle autocomplete special keys first (but don't block other input)
|
|
1092
|
+
if (this.#autocompleteState && this.#autocompleteList) {
|
|
1093
|
+
// Escape - cancel autocomplete
|
|
1094
|
+
if (kb.matches(data, "tui.select.cancel")) {
|
|
1095
|
+
this.#cancelAutocomplete(true);
|
|
1096
|
+
return;
|
|
1097
|
+
}
|
|
1098
|
+
// Let the autocomplete list handle navigation and selection
|
|
1099
|
+
else if (
|
|
1100
|
+
kb.matches(data, "tui.select.up") ||
|
|
1101
|
+
kb.matches(data, "tui.select.down") ||
|
|
1102
|
+
kb.matches(data, "tui.select.pageUp") ||
|
|
1103
|
+
kb.matches(data, "tui.select.pageDown") ||
|
|
1104
|
+
kb.matches(data, "tui.input.submit") ||
|
|
1105
|
+
data === "\n" ||
|
|
1106
|
+
kb.matches(data, "tui.input.tab")
|
|
1107
|
+
) {
|
|
1108
|
+
// Only pass navigation keys to the list, not Enter/Tab (we handle those directly)
|
|
1109
|
+
if (
|
|
1110
|
+
kb.matches(data, "tui.select.up") ||
|
|
1111
|
+
kb.matches(data, "tui.select.down") ||
|
|
1112
|
+
kb.matches(data, "tui.select.pageUp") ||
|
|
1113
|
+
kb.matches(data, "tui.select.pageDown")
|
|
1114
|
+
) {
|
|
1115
|
+
this.#autocompleteList.handleInput(data);
|
|
1116
|
+
this.onAutocompleteUpdate?.();
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
// If Tab was pressed, always apply the selection
|
|
1121
|
+
if (kb.matches(data, "tui.input.tab")) {
|
|
1122
|
+
const selected = this.#autocompleteList.getSelectedItem();
|
|
1123
|
+
if (selected && this.#autocompleteProvider) {
|
|
1124
|
+
const shouldChainSlashCommandAutocomplete = this.#isSlashCommandNameAutocompleteSelection();
|
|
1125
|
+
const result = this.#autocompleteProvider.applyCompletion(
|
|
1126
|
+
this.#state.lines,
|
|
1127
|
+
this.#state.cursorLine,
|
|
1128
|
+
this.#state.cursorCol,
|
|
1129
|
+
selected,
|
|
1130
|
+
this.#autocompletePrefix,
|
|
1131
|
+
);
|
|
1132
|
+
|
|
1133
|
+
this.#state.lines = result.lines;
|
|
1134
|
+
this.#state.cursorLine = result.cursorLine;
|
|
1135
|
+
this.#setCursorCol(result.cursorCol);
|
|
1136
|
+
|
|
1137
|
+
this.#cancelAutocomplete();
|
|
1138
|
+
this.onAutocompleteUpdate?.();
|
|
1139
|
+
|
|
1140
|
+
if (this.onChange) {
|
|
1141
|
+
this.onChange(this.getText());
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
result.onApplied?.();
|
|
1145
|
+
|
|
1146
|
+
if (shouldChainSlashCommandAutocomplete && this.#isCompletedSlashCommandAtCursor()) {
|
|
1147
|
+
void this.#tryTriggerAutocomplete();
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// If Enter was pressed on a slash command, apply completion and submit
|
|
1154
|
+
if (
|
|
1155
|
+
(kb.matches(data, "tui.input.submit") || data === "\n") &&
|
|
1156
|
+
findLeadingSlashCommandStart(this.#autocompletePrefix) !== null
|
|
1157
|
+
) {
|
|
1158
|
+
// Check for stale autocomplete state due to debounce
|
|
1159
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] ?? "";
|
|
1160
|
+
const currentTextBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
1161
|
+
if (!this.#autocompletePrefixMatchesCursorText(currentTextBeforeCursor)) {
|
|
1162
|
+
// Autocomplete is stale - cancel and fall through to normal submission
|
|
1163
|
+
this.#cancelAutocomplete();
|
|
1164
|
+
} else {
|
|
1165
|
+
const selected = this.#autocompleteList.getSelectedItem();
|
|
1166
|
+
if (selected && this.#autocompleteProvider) {
|
|
1167
|
+
const result = this.#autocompleteProvider.applyCompletion(
|
|
1168
|
+
this.#state.lines,
|
|
1169
|
+
this.#state.cursorLine,
|
|
1170
|
+
this.#state.cursorCol,
|
|
1171
|
+
selected,
|
|
1172
|
+
this.#autocompletePrefix,
|
|
1173
|
+
);
|
|
1174
|
+
|
|
1175
|
+
this.#state.lines = result.lines;
|
|
1176
|
+
this.#state.cursorLine = result.cursorLine;
|
|
1177
|
+
this.#setCursorCol(result.cursorCol);
|
|
1178
|
+
result.onApplied?.();
|
|
1179
|
+
}
|
|
1180
|
+
this.#cancelAutocomplete();
|
|
1181
|
+
}
|
|
1182
|
+
// Don't return - fall through to submission logic
|
|
1183
|
+
}
|
|
1184
|
+
// If Enter was pressed on a file path, apply completion
|
|
1185
|
+
else if (kb.matches(data, "tui.input.submit") || data === "\n") {
|
|
1186
|
+
const selected = this.#autocompleteList.getSelectedItem();
|
|
1187
|
+
if (selected && this.#autocompleteProvider) {
|
|
1188
|
+
const result = this.#autocompleteProvider.applyCompletion(
|
|
1189
|
+
this.#state.lines,
|
|
1190
|
+
this.#state.cursorLine,
|
|
1191
|
+
this.#state.cursorCol,
|
|
1192
|
+
selected,
|
|
1193
|
+
this.#autocompletePrefix,
|
|
1194
|
+
);
|
|
1195
|
+
|
|
1196
|
+
this.#state.lines = result.lines;
|
|
1197
|
+
this.#state.cursorLine = result.cursorLine;
|
|
1198
|
+
this.#setCursorCol(result.cursorCol);
|
|
1199
|
+
|
|
1200
|
+
this.#cancelAutocomplete();
|
|
1201
|
+
this.onAutocompleteUpdate?.();
|
|
1202
|
+
|
|
1203
|
+
if (this.onChange) {
|
|
1204
|
+
this.onChange(this.getText());
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
result.onApplied?.();
|
|
1208
|
+
}
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
// For other keys (like regular typing), DON'T return here
|
|
1213
|
+
// Let them fall through to normal character handling
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
// Tab key - context-aware completion (but not when already autocompleting)
|
|
1217
|
+
if (kb.matches(data, "tui.input.tab") && !this.#autocompleteState) {
|
|
1218
|
+
this.#handleTabCompletion();
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// Continue with rest of input handling
|
|
1223
|
+
// Ctrl+K - Delete to end of line
|
|
1224
|
+
if (matchesKey(data, "ctrl+k")) {
|
|
1225
|
+
this.#deleteToEndOfLine();
|
|
1226
|
+
}
|
|
1227
|
+
// Ctrl+U - Delete to start of line
|
|
1228
|
+
else if (matchesKey(data, "ctrl+u")) {
|
|
1229
|
+
this.#deleteToStartOfLine();
|
|
1230
|
+
}
|
|
1231
|
+
// Ctrl+W - Delete word backwards
|
|
1232
|
+
else if (matchesKey(data, "ctrl+w")) {
|
|
1233
|
+
this.#deleteWordBackwards();
|
|
1234
|
+
}
|
|
1235
|
+
// Option/Alt+Backspace - Delete word backwards.
|
|
1236
|
+
// Ghostty on macOS reports Option+Backspace as super+alt (kitty mod 11) — see #2064.
|
|
1237
|
+
else if (matchesKey(data, "alt+backspace") || matchesKey(data, "super+alt+backspace")) {
|
|
1238
|
+
this.#deleteWordBackwards();
|
|
1239
|
+
}
|
|
1240
|
+
// Option/Alt+D and Option+Delete - Delete word forwards. Same Ghostty quirk applies.
|
|
1241
|
+
else if (
|
|
1242
|
+
matchesKey(data, "alt+d") ||
|
|
1243
|
+
matchesKey(data, "alt+delete") ||
|
|
1244
|
+
matchesKey(data, "super+alt+d") ||
|
|
1245
|
+
matchesKey(data, "super+alt+delete")
|
|
1246
|
+
) {
|
|
1247
|
+
this.#deleteWordForwards();
|
|
1248
|
+
}
|
|
1249
|
+
// Ctrl+Y - Yank from kill ring
|
|
1250
|
+
else if (matchesKey(data, "ctrl+y")) {
|
|
1251
|
+
this.#yankFromKillRing();
|
|
1252
|
+
}
|
|
1253
|
+
// Alt+Y - Yank-pop (cycle kill ring)
|
|
1254
|
+
else if (matchesKey(data, "alt+y")) {
|
|
1255
|
+
this.#yankPop();
|
|
1256
|
+
}
|
|
1257
|
+
// Ctrl+A - Move to start of line
|
|
1258
|
+
else if (matchesKey(data, "ctrl+a")) {
|
|
1259
|
+
this.#moveToLineStart();
|
|
1260
|
+
}
|
|
1261
|
+
// Ctrl+E - Move to end of line
|
|
1262
|
+
else if (matchesKey(data, "ctrl+e")) {
|
|
1263
|
+
this.#moveToLineEnd();
|
|
1264
|
+
}
|
|
1265
|
+
// Alt+Enter - special handler if callback exists, otherwise new line
|
|
1266
|
+
else if (matchesKey(data, "alt+enter")) {
|
|
1267
|
+
if (this.onAltEnter) {
|
|
1268
|
+
this.onAltEnter(this.getText());
|
|
1269
|
+
} else {
|
|
1270
|
+
this.#addNewLine();
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
// New line
|
|
1274
|
+
else if (
|
|
1275
|
+
(data.charCodeAt(0) === 10 && data.length > 1) || // Ctrl+Enter with modifiers
|
|
1276
|
+
matchesKey(data, "ctrl+enter") || // Ctrl+Enter (Kitty/modifyOtherKeys, including lock bits/keypad Enter)
|
|
1277
|
+
data === "\x1b\r" || // Option+Enter in some terminals (legacy)
|
|
1278
|
+
data === "\x1b[13;2~" || // Shift+Enter in some terminals (legacy format)
|
|
1279
|
+
kb.matches(data, "tui.input.newLine") || // Shift+Enter (Kitty protocol, handles lock bits)
|
|
1280
|
+
(data.length > 1 && data.includes("\x1b") && data.includes("\r")) ||
|
|
1281
|
+
(data === "\n" && data.length === 1) // Shift+Enter from iTerm2 mapping
|
|
1282
|
+
) {
|
|
1283
|
+
if (this.#shouldSubmitOnBackslashEnter(data, kb)) {
|
|
1284
|
+
this.#handleBackspace();
|
|
1285
|
+
this.#submitValue();
|
|
1286
|
+
return;
|
|
1287
|
+
}
|
|
1288
|
+
this.#addNewLine();
|
|
1289
|
+
}
|
|
1290
|
+
// Plain Enter - submit (handles both legacy \r and Kitty protocol with lock bits)
|
|
1291
|
+
else if (kb.matches(data, "tui.input.submit") || data === "\n") {
|
|
1292
|
+
// If submit is disabled, do nothing
|
|
1293
|
+
if (this.disableSubmit) {
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
// Synchronous slash command completion for the race condition where
|
|
1298
|
+
// async autocomplete hasn't resolved yet (user types /q quickly + Enter).
|
|
1299
|
+
// Match the existing selected-item behavior when autocomplete IS showing.
|
|
1300
|
+
if (!this.#autocompleteState) {
|
|
1301
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] ?? "";
|
|
1302
|
+
const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
1303
|
+
if (
|
|
1304
|
+
findLeadingSlashCommandStart(textBeforeCursor) !== null &&
|
|
1305
|
+
this.#isInSubmittedSlashCommandContext() &&
|
|
1306
|
+
this.#autocompleteProvider?.trySyncSlashCompletion
|
|
1307
|
+
) {
|
|
1308
|
+
const syncResult = this.#autocompleteProvider.trySyncSlashCompletion(textBeforeCursor);
|
|
1309
|
+
if (syncResult && syncResult.items.length > 0) {
|
|
1310
|
+
// Invalidate any pending async autocomplete so its stale results are discarded
|
|
1311
|
+
this.#autocompleteRequestId += 1;
|
|
1312
|
+
// Apply the best match and submit the completed command
|
|
1313
|
+
const selected = syncResult.items[0]!;
|
|
1314
|
+
const result = this.#autocompleteProvider.applyCompletion(
|
|
1315
|
+
this.#state.lines,
|
|
1316
|
+
this.#state.cursorLine,
|
|
1317
|
+
this.#state.cursorCol,
|
|
1318
|
+
selected,
|
|
1319
|
+
syncResult.prefix,
|
|
1320
|
+
);
|
|
1321
|
+
this.#state.lines = result.lines;
|
|
1322
|
+
this.#state.cursorLine = result.cursorLine;
|
|
1323
|
+
this.#setCursorCol(result.cursorCol);
|
|
1324
|
+
result.onApplied?.();
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
this.#submitValue();
|
|
1330
|
+
}
|
|
1331
|
+
// Backspace (including Shift+Backspace)
|
|
1332
|
+
else if (kb.matches(data, "tui.editor.deleteCharBackward") || matchesKey(data, "shift+backspace")) {
|
|
1333
|
+
this.#handleBackspace();
|
|
1334
|
+
}
|
|
1335
|
+
// Line navigation shortcuts (Home/End keys)
|
|
1336
|
+
else if (kb.matches(data, "tui.editor.cursorLineStart")) {
|
|
1337
|
+
this.#moveToLineStart();
|
|
1338
|
+
} else if (kb.matches(data, "tui.editor.cursorLineEnd")) {
|
|
1339
|
+
this.#moveToLineEnd();
|
|
1340
|
+
}
|
|
1341
|
+
// Page navigation (PageUp/PageDown)
|
|
1342
|
+
else if (kb.matches(data, "tui.editor.pageUp")) {
|
|
1343
|
+
if (this.#isEditorEmpty()) {
|
|
1344
|
+
this.#navigateHistory(-1);
|
|
1345
|
+
} else if (this.#historyIndex > -1 && this.#isOnFirstVisualLine()) {
|
|
1346
|
+
this.#navigateHistory(-1);
|
|
1347
|
+
} else {
|
|
1348
|
+
this.#pageScroll(-1);
|
|
1349
|
+
}
|
|
1350
|
+
} else if (kb.matches(data, "tui.editor.pageDown")) {
|
|
1351
|
+
if (this.#historyIndex > -1 && this.#isOnLastVisualLine()) {
|
|
1352
|
+
this.#navigateHistory(1);
|
|
1353
|
+
} else {
|
|
1354
|
+
this.#pageScroll(1);
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
// Forward delete (Fn+Backspace or Delete key, including Shift+Delete)
|
|
1358
|
+
else if (kb.matches(data, "tui.editor.deleteCharForward") || matchesKey(data, "shift+delete")) {
|
|
1359
|
+
this.#handleForwardDelete();
|
|
1360
|
+
}
|
|
1361
|
+
// Word navigation (Option/Alt + Arrow or Ctrl + Arrow)
|
|
1362
|
+
else if (kb.matches(data, "tui.editor.cursorWordLeft")) {
|
|
1363
|
+
// Word left
|
|
1364
|
+
this.#resetKillSequence();
|
|
1365
|
+
this.#moveWordBackwards();
|
|
1366
|
+
} else if (kb.matches(data, "tui.editor.cursorWordRight")) {
|
|
1367
|
+
// Word right
|
|
1368
|
+
this.#resetKillSequence();
|
|
1369
|
+
this.#moveWordForwards();
|
|
1370
|
+
}
|
|
1371
|
+
// Arrow keys
|
|
1372
|
+
else if (kb.matches(data, "tui.editor.cursorUp")) {
|
|
1373
|
+
// Up - history navigation or cursor movement
|
|
1374
|
+
if (this.#isEditorEmpty()) {
|
|
1375
|
+
this.#navigateHistory(-1); // Start browsing history
|
|
1376
|
+
} else if (this.#historyIndex > -1 && this.#isOnFirstVisualLine()) {
|
|
1377
|
+
this.#navigateHistory(-1); // Navigate to older history entry
|
|
1378
|
+
} else if (this.#isOnFirstVisualLine()) {
|
|
1379
|
+
// Already at top - jump to start of line
|
|
1380
|
+
this.#moveToLineStart();
|
|
1381
|
+
} else {
|
|
1382
|
+
this.#moveCursor(-1, 0); // Cursor movement (within text or history entry)
|
|
1383
|
+
}
|
|
1384
|
+
} else if (kb.matches(data, "tui.editor.cursorDown")) {
|
|
1385
|
+
// Down - history navigation or cursor movement
|
|
1386
|
+
if (this.#historyIndex > -1 && this.#isOnLastVisualLine()) {
|
|
1387
|
+
this.#navigateHistory(1); // Navigate to newer history entry or clear
|
|
1388
|
+
} else if (this.#isOnLastVisualLine()) {
|
|
1389
|
+
// Already at bottom - jump to end of line
|
|
1390
|
+
this.#moveToLineEnd();
|
|
1391
|
+
} else {
|
|
1392
|
+
this.#moveCursor(1, 0); // Cursor movement (within text or history entry)
|
|
1393
|
+
}
|
|
1394
|
+
} else if (kb.matches(data, "tui.editor.cursorRight")) {
|
|
1395
|
+
// Right
|
|
1396
|
+
this.#moveCursor(0, 1);
|
|
1397
|
+
} else if (kb.matches(data, "tui.editor.cursorLeft")) {
|
|
1398
|
+
// Left
|
|
1399
|
+
this.#moveCursor(0, -1);
|
|
1400
|
+
}
|
|
1401
|
+
// Shift+Space - insert regular space (Kitty protocol sends escape sequence)
|
|
1402
|
+
else if (matchesKey(data, "shift+space")) {
|
|
1403
|
+
this.#insertCharacter(" ");
|
|
1404
|
+
}
|
|
1405
|
+
// Character jump mode triggers
|
|
1406
|
+
else if (kb.matches(data, "tui.editor.jumpForward")) {
|
|
1407
|
+
this.#jumpMode = "forward";
|
|
1408
|
+
} else if (kb.matches(data, "tui.editor.jumpBackward")) {
|
|
1409
|
+
this.#jumpMode = "backward";
|
|
1410
|
+
}
|
|
1411
|
+
// Printable keystrokes, including Kitty CSI-u text-producing sequences.
|
|
1412
|
+
else {
|
|
1413
|
+
const printableText = extractPrintableText(data);
|
|
1414
|
+
if (printableText) {
|
|
1415
|
+
this.#insertCharacter(printableText);
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
#wrapLine(line: string, width: number): TextChunk[] {
|
|
1421
|
+
if (width !== this.#wrapCacheWidth) {
|
|
1422
|
+
this.#wrapCache.clear();
|
|
1423
|
+
this.#wrapCacheWidth = width;
|
|
1424
|
+
}
|
|
1425
|
+
let chunks = this.#wrapCache.get(line);
|
|
1426
|
+
if (chunks === undefined) {
|
|
1427
|
+
if (this.#wrapCache.size >= 256) {
|
|
1428
|
+
this.#wrapCache.clear();
|
|
1429
|
+
}
|
|
1430
|
+
chunks = wordWrapLine(line, width);
|
|
1431
|
+
this.#wrapCache.set(line, chunks);
|
|
1432
|
+
}
|
|
1433
|
+
return chunks;
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
#layoutText(contentWidth: number): LayoutLine[] {
|
|
1437
|
+
const layoutLines: LayoutLine[] = [];
|
|
1438
|
+
|
|
1439
|
+
if (this.#state.lines.length === 0 || (this.#state.lines.length === 1 && this.#state.lines[0] === "")) {
|
|
1440
|
+
// Empty editor
|
|
1441
|
+
layoutLines.push({
|
|
1442
|
+
text: "",
|
|
1443
|
+
hasCursor: true,
|
|
1444
|
+
cursorPos: 0,
|
|
1445
|
+
});
|
|
1446
|
+
return layoutLines;
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
// Process each logical line
|
|
1450
|
+
for (let i = 0; i < this.#state.lines.length; i++) {
|
|
1451
|
+
const line = this.#state.lines[i] || "";
|
|
1452
|
+
const isCurrentLine = i === this.#state.cursorLine;
|
|
1453
|
+
const lineVisibleWidth = visibleWidth(line);
|
|
1454
|
+
|
|
1455
|
+
if (lineVisibleWidth <= contentWidth) {
|
|
1456
|
+
// Line fits in one layout line
|
|
1457
|
+
if (isCurrentLine) {
|
|
1458
|
+
layoutLines.push({
|
|
1459
|
+
text: line,
|
|
1460
|
+
hasCursor: true,
|
|
1461
|
+
cursorPos: this.#state.cursorCol,
|
|
1462
|
+
});
|
|
1463
|
+
} else {
|
|
1464
|
+
layoutLines.push({
|
|
1465
|
+
text: line,
|
|
1466
|
+
hasCursor: false,
|
|
1467
|
+
});
|
|
1468
|
+
}
|
|
1469
|
+
} else {
|
|
1470
|
+
// Line needs wrapping - use word-aware wrapping
|
|
1471
|
+
const chunks = this.#wrapLine(line, contentWidth);
|
|
1472
|
+
|
|
1473
|
+
for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
|
|
1474
|
+
const chunk = chunks[chunkIndex];
|
|
1475
|
+
if (!chunk) continue;
|
|
1476
|
+
|
|
1477
|
+
const cursorPos = this.#state.cursorCol;
|
|
1478
|
+
const isLastChunk = chunkIndex === chunks.length - 1;
|
|
1479
|
+
|
|
1480
|
+
// Determine if cursor is in this chunk
|
|
1481
|
+
// For word-wrapped chunks, we need to handle the case where
|
|
1482
|
+
// cursor might be in trimmed whitespace at end of chunk
|
|
1483
|
+
let hasCursorInChunk = false;
|
|
1484
|
+
let adjustedCursorPos = 0;
|
|
1485
|
+
|
|
1486
|
+
if (isCurrentLine) {
|
|
1487
|
+
// The first chunk owns any leading whitespace the wrapper skipped,
|
|
1488
|
+
// so a cursor inside it still maps to a layout line.
|
|
1489
|
+
const chunkStart = chunkIndex === 0 ? 0 : chunk.startIndex;
|
|
1490
|
+
if (isLastChunk) {
|
|
1491
|
+
// Last chunk: cursor belongs here if >= startIndex
|
|
1492
|
+
hasCursorInChunk = cursorPos >= chunkStart;
|
|
1493
|
+
} else {
|
|
1494
|
+
// Non-last chunk: cursor belongs here if in range [startIndex, endIndex)
|
|
1495
|
+
hasCursorInChunk = cursorPos >= chunkStart && cursorPos < chunk.endIndex;
|
|
1496
|
+
}
|
|
1497
|
+
if (hasCursorInChunk) {
|
|
1498
|
+
// Clamp into the displayed text (cursor may sit in trimmed/skipped whitespace)
|
|
1499
|
+
adjustedCursorPos = Math.max(0, Math.min(cursorPos - chunk.startIndex, chunk.text.length));
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
if (hasCursorInChunk) {
|
|
1504
|
+
layoutLines.push({
|
|
1505
|
+
text: chunk.text,
|
|
1506
|
+
hasCursor: true,
|
|
1507
|
+
cursorPos: adjustedCursorPos,
|
|
1508
|
+
});
|
|
1509
|
+
} else {
|
|
1510
|
+
layoutLines.push({
|
|
1511
|
+
text: chunk.text,
|
|
1512
|
+
hasCursor: false,
|
|
1513
|
+
});
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
return layoutLines;
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
getText(): string {
|
|
1523
|
+
return this.#state.lines.join("\n");
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
#expandPasteMarkers(text: string): string {
|
|
1527
|
+
let result = text;
|
|
1528
|
+
for (const [pasteId, pasteContent] of this.#pastes) {
|
|
1529
|
+
const markerRegex = new RegExp(`\\[Paste #${pasteId}(?:, (?:\\+\\d+ lines|\\d+ chars))?\\]`, "g");
|
|
1530
|
+
result = result.replace(markerRegex, () => pasteContent);
|
|
1531
|
+
}
|
|
1532
|
+
return result;
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
/**
|
|
1536
|
+
* Get text with paste markers expanded to their actual content.
|
|
1537
|
+
* Use this when you need the full content (e.g., for external editor).
|
|
1538
|
+
*/
|
|
1539
|
+
getExpandedText(): string {
|
|
1540
|
+
return this.#expandPasteMarkers(this.#state.lines.join("\n"));
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
getLines(): string[] {
|
|
1544
|
+
return [...this.#state.lines];
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
getCursor(): { line: number; col: number } {
|
|
1548
|
+
return { line: this.#state.cursorLine, col: this.#state.cursorCol };
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
moveToLineStart(): void {
|
|
1552
|
+
this.#moveToLineStart();
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
moveToLineEnd(): void {
|
|
1556
|
+
this.#moveToLineEnd();
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
moveToMessageStart(): void {
|
|
1560
|
+
this.#moveToMessageStart();
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
moveToMessageEnd(): void {
|
|
1564
|
+
this.#moveToMessageEnd();
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
/**
|
|
1568
|
+
* Undo the last meaningful edit while ignoring transient text that is still present at the cursor.
|
|
1569
|
+
* Used for command-like autocomplete actions whose typed trigger should not count as the edit being undone.
|
|
1570
|
+
*/
|
|
1571
|
+
undoPastTransientText(transientText: string): void {
|
|
1572
|
+
if (transientText.length === 0) {
|
|
1573
|
+
this.#applyUndo();
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
1578
|
+
const transientStartCol = this.#state.cursorCol - transientText.length;
|
|
1579
|
+
if (transientStartCol < 0 || currentLine.slice(transientStartCol, this.#state.cursorCol) !== transientText) {
|
|
1580
|
+
this.#applyUndo();
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
const beforeTransient = currentLine.slice(0, transientStartCol);
|
|
1585
|
+
const afterTransient = currentLine.slice(this.#state.cursorCol);
|
|
1586
|
+
this.#historyIndex = -1;
|
|
1587
|
+
this.#resetKillSequence();
|
|
1588
|
+
this.#preferredVisualCol = null;
|
|
1589
|
+
this.#state.lines[this.#state.cursorLine] = beforeTransient + afterTransient;
|
|
1590
|
+
this.#setCursorCol(transientStartCol);
|
|
1591
|
+
|
|
1592
|
+
while (true) {
|
|
1593
|
+
const snapshot = this.#undoStack.at(-1);
|
|
1594
|
+
if (
|
|
1595
|
+
!snapshot ||
|
|
1596
|
+
!this.#matchesTransientUndoSnapshot(
|
|
1597
|
+
snapshot,
|
|
1598
|
+
transientText,
|
|
1599
|
+
transientStartCol,
|
|
1600
|
+
beforeTransient,
|
|
1601
|
+
afterTransient,
|
|
1602
|
+
)
|
|
1603
|
+
) {
|
|
1604
|
+
break;
|
|
1605
|
+
}
|
|
1606
|
+
this.#undoStack.pop();
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
if (this.#undoStack.length === 0) {
|
|
1610
|
+
if (this.onChange) {
|
|
1611
|
+
this.onChange(this.getText());
|
|
1612
|
+
}
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
this.#applyUndo();
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
setText(text: string): void {
|
|
1620
|
+
this.#historyIndex = -1; // Exit history browsing mode
|
|
1621
|
+
this.#resetKillSequence();
|
|
1622
|
+
this.#setTextInternal(text);
|
|
1623
|
+
}
|
|
1624
|
+
submit(): void {
|
|
1625
|
+
if (this.disableSubmit) return;
|
|
1626
|
+
this.#submitValue();
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
#exitHistoryForEditing(): void {
|
|
1630
|
+
if (this.#historyIndex === -1) return;
|
|
1631
|
+
if (this.#state.cursorLine === 0 && this.#state.cursorCol === 0) {
|
|
1632
|
+
this.#state.cursorLine = this.#state.lines.length - 1;
|
|
1633
|
+
const line = this.#state.lines[this.#state.cursorLine] || "";
|
|
1634
|
+
this.#setCursorCol(line.length);
|
|
1635
|
+
}
|
|
1636
|
+
this.#historyIndex = -1;
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
/** Insert text at the current cursor position */
|
|
1640
|
+
insertText(text: string): void {
|
|
1641
|
+
this.#exitHistoryForEditing();
|
|
1642
|
+
this.#insertTextAtCursor(text);
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
/** Delete up to `count` characters immediately before the cursor on the current line.
|
|
1646
|
+
* Used to "track back" the auto-repeat spaces that the space-hold push-to-talk gesture
|
|
1647
|
+
* optimistically inserts before it recognizes the hold. Capped at the cursor column so it
|
|
1648
|
+
* never crosses a line boundary or under-runs the line. */
|
|
1649
|
+
deleteBeforeCursor(count: number): void {
|
|
1650
|
+
const removable = Math.min(count, this.#state.cursorCol);
|
|
1651
|
+
if (removable <= 0) return;
|
|
1652
|
+
this.#exitHistoryForEditing();
|
|
1653
|
+
this.#recordUndoState();
|
|
1654
|
+
const line = this.#state.lines[this.#state.cursorLine] ?? "";
|
|
1655
|
+
this.#state.lines[this.#state.cursorLine] =
|
|
1656
|
+
line.slice(0, this.#state.cursorCol - removable) + line.slice(this.#state.cursorCol);
|
|
1657
|
+
this.#setCursorCol(this.#state.cursorCol - removable);
|
|
1658
|
+
this.#lastAction = null;
|
|
1659
|
+
if (this.onChange) {
|
|
1660
|
+
this.onChange(this.getText());
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
/** Code units of the current volatile speech-to-text preview (see {@link setVolatileText}). */
|
|
1665
|
+
#volatileTextLen = 0;
|
|
1666
|
+
|
|
1667
|
+
/** Show or replace a volatile speech-to-text preview at the cursor. The text is
|
|
1668
|
+
* inserted with undo suspended so a long live dictation never floods the undo
|
|
1669
|
+
* stack; finalize it with {@link commitVolatileText} or drop it with
|
|
1670
|
+
* {@link clearVolatileText}. Newlines are allowed. */
|
|
1671
|
+
setVolatileText(text: string): void {
|
|
1672
|
+
this.#exitHistoryForEditing();
|
|
1673
|
+
this.#withUndoSuspended(() => {
|
|
1674
|
+
this.#deleteCharsBeforeCursor(this.#volatileTextLen);
|
|
1675
|
+
if (text) this.#insertTextAtCursor(text);
|
|
1676
|
+
});
|
|
1677
|
+
this.#volatileTextLen = text.length;
|
|
1678
|
+
if (!text && this.onChange) this.onChange(this.getText());
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
/** Remove the current volatile preview without committing it. */
|
|
1682
|
+
clearVolatileText(): void {
|
|
1683
|
+
if (this.#volatileTextLen === 0) return;
|
|
1684
|
+
this.#withUndoSuspended(() => this.#deleteCharsBeforeCursor(this.#volatileTextLen));
|
|
1685
|
+
this.#volatileTextLen = 0;
|
|
1686
|
+
if (this.onChange) this.onChange(this.getText());
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
/** Drop any volatile preview, then insert `text` as a single undoable edit. */
|
|
1690
|
+
commitVolatileText(text: string): void {
|
|
1691
|
+
this.#exitHistoryForEditing();
|
|
1692
|
+
this.#withUndoSuspended(() => this.#deleteCharsBeforeCursor(this.#volatileTextLen));
|
|
1693
|
+
this.#volatileTextLen = 0;
|
|
1694
|
+
if (text) this.#insertTextAtCursor(text);
|
|
1695
|
+
else if (this.onChange) this.onChange(this.getText());
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
/** Delete `count` UTF-16 code units immediately before the cursor, crossing line
|
|
1699
|
+
* boundaries (each consumed newline counts as one). Undo is the caller's concern. */
|
|
1700
|
+
#deleteCharsBeforeCursor(count: number): void {
|
|
1701
|
+
let remaining = count;
|
|
1702
|
+
while (remaining > 0) {
|
|
1703
|
+
if (this.#state.cursorCol > 0) {
|
|
1704
|
+
const removable = Math.min(remaining, this.#state.cursorCol);
|
|
1705
|
+
const line = this.#state.lines[this.#state.cursorLine] ?? "";
|
|
1706
|
+
this.#state.lines[this.#state.cursorLine] =
|
|
1707
|
+
line.slice(0, this.#state.cursorCol - removable) + line.slice(this.#state.cursorCol);
|
|
1708
|
+
this.#setCursorCol(this.#state.cursorCol - removable);
|
|
1709
|
+
remaining -= removable;
|
|
1710
|
+
} else if (this.#state.cursorLine > 0) {
|
|
1711
|
+
const prev = this.#state.lines[this.#state.cursorLine - 1] ?? "";
|
|
1712
|
+
const cur = this.#state.lines[this.#state.cursorLine] ?? "";
|
|
1713
|
+
this.#state.lines[this.#state.cursorLine - 1] = prev + cur;
|
|
1714
|
+
this.#state.lines.splice(this.#state.cursorLine, 1);
|
|
1715
|
+
this.#state.cursorLine -= 1;
|
|
1716
|
+
this.#setCursorCol(prev.length);
|
|
1717
|
+
remaining -= 1;
|
|
1718
|
+
} else {
|
|
1719
|
+
break;
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/** Apply terminal paste semantics to text from non-bracketed paste transports. */
|
|
1725
|
+
pasteText(text: string): void {
|
|
1726
|
+
this.#handlePaste(text);
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
/** Insert `content` as a collapsed `[Paste #N]` marker (stored for expansion on submit via
|
|
1730
|
+
* {@link getExpandedText}). Hosts that intercept large pastes through {@link onLargePaste} use
|
|
1731
|
+
* this to re-insert a (possibly transformed) paste without re-triggering the interception hook. */
|
|
1732
|
+
insertPaste(content: string): void {
|
|
1733
|
+
this.#historyIndex = -1;
|
|
1734
|
+
this.#resetKillSequence();
|
|
1735
|
+
this.#recordUndoState();
|
|
1736
|
+
this.#withUndoSuspended(() => {
|
|
1737
|
+
this.#storePasteMarker(content, content.split("\n").length);
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
// All the editor methods from before...
|
|
1742
|
+
#insertCharacter(char: string): void {
|
|
1743
|
+
this.#exitHistoryForEditing();
|
|
1744
|
+
// Undo coalescing: consecutive word typing collapses into one undo unit
|
|
1745
|
+
// (mirrors Input); any other action resets the run via #lastAction.
|
|
1746
|
+
const isWordChunk = [...segmenter.segment(char)].every(seg => getWordNavKind(seg.segment) !== "whitespace");
|
|
1747
|
+
if (!isWordChunk || this.#lastAction !== "type-word") {
|
|
1748
|
+
this.#recordUndoState();
|
|
1749
|
+
}
|
|
1750
|
+
this.#lastAction = isWordChunk ? "type-word" : null;
|
|
1751
|
+
|
|
1752
|
+
const line = this.#state.lines[this.#state.cursorLine] || "";
|
|
1753
|
+
|
|
1754
|
+
const before = line.slice(0, this.#state.cursorCol);
|
|
1755
|
+
const after = line.slice(this.#state.cursorCol);
|
|
1756
|
+
|
|
1757
|
+
this.#state.lines[this.#state.cursorLine] = before + char + after;
|
|
1758
|
+
this.#setCursorCol(this.#state.cursorCol + char.length);
|
|
1759
|
+
|
|
1760
|
+
if (this.onChange) {
|
|
1761
|
+
this.onChange(this.getText());
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
// Synchronous inline replacement (e.g. emoji shortcodes `:joy:` → 😂).
|
|
1765
|
+
// Runs before autocomplete trigger so the popup doesn't briefly chase a
|
|
1766
|
+
// prefix that's about to be rewritten.
|
|
1767
|
+
if (char.length === 1 && this.#autocompleteProvider?.trySyncInlineReplace) {
|
|
1768
|
+
const replaceLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
1769
|
+
const textBeforeCursor = replaceLine.slice(0, this.#state.cursorCol);
|
|
1770
|
+
const replacement = this.#autocompleteProvider.trySyncInlineReplace(textBeforeCursor);
|
|
1771
|
+
if (replacement) {
|
|
1772
|
+
const before = replaceLine.slice(0, this.#state.cursorCol - replacement.replaceLen);
|
|
1773
|
+
const after = replaceLine.slice(this.#state.cursorCol);
|
|
1774
|
+
this.#state.lines[this.#state.cursorLine] = before + replacement.insert + after;
|
|
1775
|
+
this.#setCursorCol(before.length + replacement.insert.length);
|
|
1776
|
+
if (this.onChange) {
|
|
1777
|
+
this.onChange(this.getText());
|
|
1778
|
+
}
|
|
1779
|
+
if (this.#autocompleteState) {
|
|
1780
|
+
this.#cancelAutocomplete();
|
|
1781
|
+
this.onAutocompleteUpdate?.();
|
|
1782
|
+
}
|
|
1783
|
+
return;
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
// Check if we should trigger or update autocomplete
|
|
1788
|
+
if (!this.#autocompleteState) {
|
|
1789
|
+
// Auto-trigger for "/" at the start of a submitted command or a mid-prompt skill lookup.
|
|
1790
|
+
if (char === "/" && (this.#isAtStartOfSubmittedMessage() || this.#isInMidPromptSkillSlashContext())) {
|
|
1791
|
+
this.#tryTriggerAutocomplete();
|
|
1792
|
+
}
|
|
1793
|
+
// Auto-trigger for "@" file reference (fuzzy search)
|
|
1794
|
+
else if (char === "@") {
|
|
1795
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
1796
|
+
const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
1797
|
+
// Only trigger if @ is after whitespace or at start of line
|
|
1798
|
+
const charBeforeAt = textBeforeCursor[textBeforeCursor.length - 2];
|
|
1799
|
+
if (textBeforeCursor.length === 1 || charBeforeAt === " " || charBeforeAt === "\t") {
|
|
1800
|
+
this.#tryTriggerAutocomplete();
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
// Auto-trigger for "#" prompt actions anywhere in the current token
|
|
1804
|
+
else if (char === "#") {
|
|
1805
|
+
this.#tryTriggerAutocomplete();
|
|
1806
|
+
}
|
|
1807
|
+
// Also auto-trigger when typing letters/path chars in a completable context
|
|
1808
|
+
else if (/[a-zA-Z0-9.\-_/]/.test(char)) {
|
|
1809
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
1810
|
+
const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
1811
|
+
// Check if we're in a slash command or mid-prompt skill lookup.
|
|
1812
|
+
if (this.#isInSlashAutocompleteContext()) {
|
|
1813
|
+
this.#tryTriggerAutocomplete();
|
|
1814
|
+
}
|
|
1815
|
+
// Check if we're in an @ file reference context
|
|
1816
|
+
else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
|
|
1817
|
+
this.#tryTriggerAutocomplete();
|
|
1818
|
+
}
|
|
1819
|
+
// Check if we're in a # prompt action context
|
|
1820
|
+
else if (textBeforeCursor.match(/#[^\s#]*$/)) {
|
|
1821
|
+
this.#tryTriggerAutocomplete();
|
|
1822
|
+
}
|
|
1823
|
+
// Check if we're in a :emoji shortcode context
|
|
1824
|
+
else if (textBeforeCursor.match(/(?:^|[\s([{>]):[a-zA-Z0-9_+-]*$/)) {
|
|
1825
|
+
this.#tryTriggerAutocomplete();
|
|
1826
|
+
}
|
|
1827
|
+
// Check if we're typing an internal URL scheme (e.g. local://, skill://)
|
|
1828
|
+
else if (this.#textTriggersUrlAutocomplete(textBeforeCursor)) {
|
|
1829
|
+
this.#tryTriggerAutocomplete();
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
} else {
|
|
1833
|
+
this.#debouncedUpdateAutocomplete();
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
#handlePaste(pastedText: string): void {
|
|
1838
|
+
let filteredText = this.#sanitizePastedText(pastedText);
|
|
1839
|
+
|
|
1840
|
+
// If pasting a file path (starts with /, ~, or .) and the character before
|
|
1841
|
+
// the cursor is a word character, prepend a space for better readability.
|
|
1842
|
+
if (/^[/~.]/.test(filteredText)) {
|
|
1843
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
1844
|
+
const charBeforeCursor = this.#state.cursorCol > 0 ? currentLine[this.#state.cursorCol - 1] : "";
|
|
1845
|
+
if (charBeforeCursor && /\w/.test(charBeforeCursor)) {
|
|
1846
|
+
filteredText = ` ${filteredText}`;
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
const pastedLines = filteredText.split("\n");
|
|
1851
|
+
const totalChars = filteredText.length;
|
|
1852
|
+
// "Marker-sized": large enough to collapse into a `[Paste #N]` token (> 10 lines or
|
|
1853
|
+
// > 1000 characters) instead of flooding the buffer.
|
|
1854
|
+
const isMarkerSized = pastedLines.length > 10 || totalChars > 1000;
|
|
1855
|
+
|
|
1856
|
+
// Let the host intercept marker-sized pastes (e.g. the large-paste menu). When it takes
|
|
1857
|
+
// over, the editor inserts nothing and records no undo state — the host re-inserts via
|
|
1858
|
+
// `insertPaste`/`insertText` once the user chooses.
|
|
1859
|
+
if (isMarkerSized && this.onLargePaste?.(filteredText, pastedLines.length)) {
|
|
1860
|
+
return;
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
this.#historyIndex = -1; // Exit history browsing mode
|
|
1864
|
+
this.#resetKillSequence();
|
|
1865
|
+
this.#recordUndoState();
|
|
1866
|
+
|
|
1867
|
+
this.#withUndoSuspended(() => {
|
|
1868
|
+
if (isMarkerSized) {
|
|
1869
|
+
this.#storePasteMarker(filteredText, pastedLines.length);
|
|
1870
|
+
return;
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
if (pastedLines.length === 1) {
|
|
1874
|
+
// Single line - insert in one operation (per-char replay is O(paste × buffer)),
|
|
1875
|
+
// then evaluate autocomplete triggers once at the final cursor position.
|
|
1876
|
+
if (filteredText) {
|
|
1877
|
+
this.#insertTextAtCursor(filteredText);
|
|
1878
|
+
this.#retriggerAutocompleteAtCursor();
|
|
1879
|
+
}
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
// Multi-line paste - use insertTextAtCursor for proper handling
|
|
1884
|
+
this.#insertTextAtCursor(filteredText);
|
|
1885
|
+
});
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
/** Normalize raw pasted text: decode tmux re-encoded control bytes (both extended-keys formats),
|
|
1889
|
+
* normalize CRLF and
|
|
1890
|
+
* NFC (macOS NFD filename drag-drops), expand tabs, and strip control characters except newline. */
|
|
1891
|
+
#sanitizePastedText(pastedText: string): string {
|
|
1892
|
+
// Decode tmux's re-encoded control bytes (both extended-keys formats) back to
|
|
1893
|
+
// their literal byte so the per-char filter below preserves newlines instead of
|
|
1894
|
+
// stripping ESC and leaking the printable tail into the editor. See the decoder.
|
|
1895
|
+
const decodedText = decodeReencodedPasteControls(pastedText);
|
|
1896
|
+
|
|
1897
|
+
// Clean the pasted text. NFC-normalize so macOS Finder drag-drops of
|
|
1898
|
+
// Korean filenames (which arrive as NFD: e.g. `ᄒ`+`ᅪ` instead of `화`)
|
|
1899
|
+
// land in the buffer as the same precomposed syllables a terminal
|
|
1900
|
+
// renders — without this, cursor column accounting drifts by
|
|
1901
|
+
// `(NFD cells − NFC cells)` and the visible glyph desyncs from the
|
|
1902
|
+
// hardware cursor.
|
|
1903
|
+
const cleanText = decodedText.replace(/\r\n?/g, "\n").normalize("NFC");
|
|
1904
|
+
|
|
1905
|
+
// Convert tabs to spaces (4 spaces per tab).
|
|
1906
|
+
const tabExpandedText = cleanText.replace(/\t/g, " ");
|
|
1907
|
+
|
|
1908
|
+
// Strip control characters except newline (tabs already expanded above, CRs already
|
|
1909
|
+
// normalized). Single regex pass instead of split/filter/join to avoid allocating a
|
|
1910
|
+
// per-code-unit array for large pastes.
|
|
1911
|
+
return tabExpandedText.replace(/[\x00-\x09\x0B-\x1F]/g, "");
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
/** Store `content` in the paste buffer and insert a collapsed `[Paste #N]` marker that expands
|
|
1915
|
+
* back to `content` on submit. `lineCount` is the content's line count. */
|
|
1916
|
+
#storePasteMarker(content: string, lineCount: number): void {
|
|
1917
|
+
this.#pasteCounter++;
|
|
1918
|
+
const pasteId = this.#pasteCounter;
|
|
1919
|
+
this.#pastes.set(pasteId, content);
|
|
1920
|
+
|
|
1921
|
+
// Insert marker like "[Paste #1, +123 lines]" or "[Paste #1, 1234 chars]".
|
|
1922
|
+
const marker =
|
|
1923
|
+
lineCount > 10 ? `[Paste #${pasteId}, +${lineCount} lines]` : `[Paste #${pasteId}, ${content.length} chars]`;
|
|
1924
|
+
this.#insertTextAtCursor(marker);
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
/** Re-evaluate autocomplete triggers for the text ending at the cursor (used after bulk edits). */
|
|
1928
|
+
#retriggerAutocompleteAtCursor(): void {
|
|
1929
|
+
if (this.#autocompleteState) {
|
|
1930
|
+
this.#debouncedUpdateAutocomplete();
|
|
1931
|
+
return;
|
|
1932
|
+
}
|
|
1933
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
1934
|
+
const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
1935
|
+
if (this.#isInSlashAutocompleteContext()) {
|
|
1936
|
+
this.#tryTriggerAutocomplete();
|
|
1937
|
+
} else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
|
|
1938
|
+
this.#tryTriggerAutocomplete();
|
|
1939
|
+
} else if (textBeforeCursor.match(/#[^\s#]*$/)) {
|
|
1940
|
+
this.#tryTriggerAutocomplete();
|
|
1941
|
+
} else if (this.#textTriggersUrlAutocomplete(textBeforeCursor)) {
|
|
1942
|
+
this.#tryTriggerAutocomplete();
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
#addNewLine(): void {
|
|
1947
|
+
this.#historyIndex = -1; // Exit history browsing mode
|
|
1948
|
+
this.#resetKillSequence();
|
|
1949
|
+
this.#recordUndoState();
|
|
1950
|
+
|
|
1951
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
1952
|
+
|
|
1953
|
+
const before = currentLine.slice(0, this.#state.cursorCol);
|
|
1954
|
+
const after = currentLine.slice(this.#state.cursorCol);
|
|
1955
|
+
|
|
1956
|
+
// Split current line
|
|
1957
|
+
this.#state.lines[this.#state.cursorLine] = before;
|
|
1958
|
+
this.#state.lines.splice(this.#state.cursorLine + 1, 0, after);
|
|
1959
|
+
|
|
1960
|
+
// Move cursor to start of new line
|
|
1961
|
+
this.#state.cursorLine++;
|
|
1962
|
+
this.#setCursorCol(0);
|
|
1963
|
+
|
|
1964
|
+
if (this.onChange) {
|
|
1965
|
+
this.onChange(this.getText());
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
#shouldSubmitOnBackslashEnter(data: string, kb: KeybindingsManager): boolean {
|
|
1970
|
+
if (this.disableSubmit) return false;
|
|
1971
|
+
if (!matchesKey(data, "enter")) return false;
|
|
1972
|
+
const submitKeys = kb.getKeys("tui.input.submit");
|
|
1973
|
+
const hasShiftEnter = submitKeys.includes("shift+enter") || submitKeys.includes("shift+return");
|
|
1974
|
+
if (!hasShiftEnter) return false;
|
|
1975
|
+
|
|
1976
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
1977
|
+
return this.#state.cursorCol > 0 && currentLine[this.#state.cursorCol - 1] === "\\";
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1980
|
+
#submitValue(): void {
|
|
1981
|
+
this.#resetKillSequence();
|
|
1982
|
+
|
|
1983
|
+
const result = this.#expandPasteMarkers(this.#state.lines.join("\n")).trim();
|
|
1984
|
+
|
|
1985
|
+
this.#state = { lines: [""], cursorLine: 0, cursorCol: 0 };
|
|
1986
|
+
this.#pastes.clear();
|
|
1987
|
+
this.#pasteCounter = 0;
|
|
1988
|
+
this.#historyIndex = -1;
|
|
1989
|
+
this.#scrollOffset = 0;
|
|
1990
|
+
this.#undoStack.length = 0;
|
|
1991
|
+
|
|
1992
|
+
if (this.onChange) this.onChange("");
|
|
1993
|
+
if (this.onSubmit) this.onSubmit(result);
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
/** Resolve the compiled, global copy of `atomicTokenPattern`, rebuilt only when the source changes. */
|
|
1997
|
+
#getAtomicTokenRe(): RegExp | undefined {
|
|
1998
|
+
const pattern = this.atomicTokenPattern;
|
|
1999
|
+
if (pattern === undefined) {
|
|
2000
|
+
this.#atomicTokenSource = undefined;
|
|
2001
|
+
this.#atomicTokenRe = undefined;
|
|
2002
|
+
return undefined;
|
|
2003
|
+
}
|
|
2004
|
+
if (pattern.source !== this.#atomicTokenSource) {
|
|
2005
|
+
this.#atomicTokenSource = pattern.source;
|
|
2006
|
+
this.#atomicTokenRe = new RegExp(
|
|
2007
|
+
pattern.source,
|
|
2008
|
+
pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`,
|
|
2009
|
+
);
|
|
2010
|
+
}
|
|
2011
|
+
return this.#atomicTokenRe;
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
/** Find an atomic token on `line` whose span contains column `col` (`start <= col < end`). */
|
|
2015
|
+
#atomicTokenAt(line: string, col: number): { start: number; end: number } | undefined {
|
|
2016
|
+
const re = this.#getAtomicTokenRe();
|
|
2017
|
+
if (re === undefined) return undefined;
|
|
2018
|
+
re.lastIndex = 0;
|
|
2019
|
+
for (;;) {
|
|
2020
|
+
const match = re.exec(line);
|
|
2021
|
+
if (match === null) break;
|
|
2022
|
+
if (match[0].length === 0) {
|
|
2023
|
+
re.lastIndex = match.index + 1;
|
|
2024
|
+
continue;
|
|
2025
|
+
}
|
|
2026
|
+
const start = match.index;
|
|
2027
|
+
const end = start + match[0].length;
|
|
2028
|
+
if (col < start) break;
|
|
2029
|
+
if (col < end) return { start, end };
|
|
2030
|
+
}
|
|
2031
|
+
return undefined;
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
/** Expand the half-open range [start, end) so it never cuts through an atomic
|
|
2035
|
+
* placeholder token: a boundary landing inside a token pulls the whole token in. */
|
|
2036
|
+
#expandRangeOverAtomicTokens(line: string, start: number, end: number): { start: number; end: number } {
|
|
2037
|
+
const startToken = this.#atomicTokenAt(line, start);
|
|
2038
|
+
if (startToken !== undefined && startToken.start < start) {
|
|
2039
|
+
start = startToken.start;
|
|
2040
|
+
}
|
|
2041
|
+
if (end > start) {
|
|
2042
|
+
const endToken = this.#atomicTokenAt(line, end - 1);
|
|
2043
|
+
if (endToken !== undefined && endToken.end > end) {
|
|
2044
|
+
end = endToken.end;
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
return { start, end };
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
#handleBackspace(): void {
|
|
2051
|
+
this.#historyIndex = -1; // Exit history browsing mode
|
|
2052
|
+
this.#resetKillSequence();
|
|
2053
|
+
this.#recordUndoState();
|
|
2054
|
+
|
|
2055
|
+
if (this.#state.cursorCol > 0) {
|
|
2056
|
+
const line = this.#state.lines[this.#state.cursorLine] || "";
|
|
2057
|
+
// An atomic placeholder token (image/paste marker) deletes as a unit, so a single
|
|
2058
|
+
// backspace never leaves a half-eaten `[Paste #1, +30 lines` behind as stray text.
|
|
2059
|
+
const token = this.#atomicTokenAt(line, this.#state.cursorCol - 1);
|
|
2060
|
+
if (token !== undefined) {
|
|
2061
|
+
this.#state.lines[this.#state.cursorLine] = line.slice(0, token.start) + line.slice(token.end);
|
|
2062
|
+
this.#setCursorCol(token.start);
|
|
2063
|
+
} else {
|
|
2064
|
+
// Delete grapheme before cursor (handles emojis, combining characters, etc.)
|
|
2065
|
+
const beforeCursor = line.slice(0, this.#state.cursorCol);
|
|
2066
|
+
|
|
2067
|
+
// Find the last grapheme in the text before cursor
|
|
2068
|
+
const graphemes = [...segmenter.segment(beforeCursor)];
|
|
2069
|
+
const lastGrapheme = graphemes[graphemes.length - 1];
|
|
2070
|
+
const graphemeLength = lastGrapheme ? lastGrapheme.segment.length : 1;
|
|
2071
|
+
|
|
2072
|
+
const before = line.slice(0, this.#state.cursorCol - graphemeLength);
|
|
2073
|
+
const after = line.slice(this.#state.cursorCol);
|
|
2074
|
+
|
|
2075
|
+
this.#state.lines[this.#state.cursorLine] = before + after;
|
|
2076
|
+
this.#setCursorCol(this.#state.cursorCol - graphemeLength);
|
|
2077
|
+
}
|
|
2078
|
+
} else if (this.#state.cursorLine > 0) {
|
|
2079
|
+
// Merge with previous line
|
|
2080
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2081
|
+
const previousLine = this.#state.lines[this.#state.cursorLine - 1] || "";
|
|
2082
|
+
|
|
2083
|
+
this.#state.lines[this.#state.cursorLine - 1] = previousLine + currentLine;
|
|
2084
|
+
this.#state.lines.splice(this.#state.cursorLine, 1);
|
|
2085
|
+
|
|
2086
|
+
this.#state.cursorLine--;
|
|
2087
|
+
this.#setCursorCol(previousLine.length);
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
if (this.onChange) {
|
|
2091
|
+
this.onChange(this.getText());
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
// Update or re-trigger autocomplete after backspace
|
|
2095
|
+
if (this.#autocompleteState) {
|
|
2096
|
+
this.#debouncedUpdateAutocomplete();
|
|
2097
|
+
} else {
|
|
2098
|
+
// If autocomplete was cancelled (no matches), re-trigger if we're in a completable context
|
|
2099
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2100
|
+
const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
2101
|
+
// Slash command or mid-prompt skill lookup context
|
|
2102
|
+
if (this.#isInSlashAutocompleteContext()) {
|
|
2103
|
+
this.#tryTriggerAutocomplete();
|
|
2104
|
+
}
|
|
2105
|
+
// @ file reference context
|
|
2106
|
+
else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
|
|
2107
|
+
this.#tryTriggerAutocomplete();
|
|
2108
|
+
}
|
|
2109
|
+
// # prompt action context
|
|
2110
|
+
else if (textBeforeCursor.match(/#[^\s#]*$/)) {
|
|
2111
|
+
this.#tryTriggerAutocomplete();
|
|
2112
|
+
}
|
|
2113
|
+
// internal URL scheme context (e.g. local://, skill://)
|
|
2114
|
+
else if (this.#textTriggersUrlAutocomplete(textBeforeCursor)) {
|
|
2115
|
+
this.#tryTriggerAutocomplete();
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
/**
|
|
2121
|
+
* Set cursor column and clear preferredVisualCol.
|
|
2122
|
+
* Use this for all non-vertical cursor movements to reset sticky column behavior.
|
|
2123
|
+
*/
|
|
2124
|
+
#setCursorCol(col: number): void {
|
|
2125
|
+
this.#state.cursorCol = col;
|
|
2126
|
+
this.#preferredVisualCol = null;
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
/**
|
|
2130
|
+
* Move cursor to a target visual line, applying sticky column logic.
|
|
2131
|
+
* Shared by moveCursor() and pageScroll().
|
|
2132
|
+
*/
|
|
2133
|
+
#moveToVisualLine(
|
|
2134
|
+
visualLines: Array<{ logicalLine: number; startCol: number; length: number }>,
|
|
2135
|
+
currentVisualLine: number,
|
|
2136
|
+
targetVisualLine: number,
|
|
2137
|
+
): void {
|
|
2138
|
+
const currentVL = visualLines[currentVisualLine];
|
|
2139
|
+
const targetVL = visualLines[targetVisualLine];
|
|
2140
|
+
|
|
2141
|
+
if (currentVL && targetVL) {
|
|
2142
|
+
// Work in visual cells (grapheme-walked), not UTF-16 code units: code-unit
|
|
2143
|
+
// columns land mid-surrogate on emoji and drift on wide CJK glyphs.
|
|
2144
|
+
const sourceLine = this.#state.lines[currentVL.logicalLine] || "";
|
|
2145
|
+
const sourceText = sourceLine.slice(currentVL.startCol, currentVL.startCol + currentVL.length);
|
|
2146
|
+
const currentVisualCol = visualColAtOffset(sourceText, this.#state.cursorCol - currentVL.startCol);
|
|
2147
|
+
|
|
2148
|
+
// For non-last segments, clamp before the segment end to stay within the segment
|
|
2149
|
+
const isLastSourceSegment =
|
|
2150
|
+
currentVisualLine === visualLines.length - 1 ||
|
|
2151
|
+
visualLines[currentVisualLine + 1]?.logicalLine !== currentVL.logicalLine;
|
|
2152
|
+
const sourceMaxVisualCol = maxSegmentVisualCol(sourceText, isLastSourceSegment);
|
|
2153
|
+
|
|
2154
|
+
const isLastTargetSegment =
|
|
2155
|
+
targetVisualLine === visualLines.length - 1 ||
|
|
2156
|
+
visualLines[targetVisualLine + 1]?.logicalLine !== targetVL.logicalLine;
|
|
2157
|
+
const targetLine = this.#state.lines[targetVL.logicalLine] || "";
|
|
2158
|
+
const targetText = targetLine.slice(targetVL.startCol, targetVL.startCol + targetVL.length);
|
|
2159
|
+
const targetMaxVisualCol = maxSegmentVisualCol(targetText, isLastTargetSegment);
|
|
2160
|
+
|
|
2161
|
+
const moveToVisualCol = this.#computeVerticalMoveColumn(
|
|
2162
|
+
currentVisualCol,
|
|
2163
|
+
sourceMaxVisualCol,
|
|
2164
|
+
targetMaxVisualCol,
|
|
2165
|
+
);
|
|
2166
|
+
|
|
2167
|
+
// Set cursor position, snapping to a grapheme boundary in the target text
|
|
2168
|
+
this.#state.cursorLine = targetVL.logicalLine;
|
|
2169
|
+
const targetCol = targetVL.startCol + offsetAtVisualCol(targetText, moveToVisualCol);
|
|
2170
|
+
this.#state.cursorCol = Math.min(targetCol, targetLine.length);
|
|
2171
|
+
}
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
/**
|
|
2175
|
+
* Compute the target visual column for vertical cursor movement.
|
|
2176
|
+
* Implements the sticky column decision table.
|
|
2177
|
+
*/
|
|
2178
|
+
#computeVerticalMoveColumn(
|
|
2179
|
+
currentVisualCol: number,
|
|
2180
|
+
sourceMaxVisualCol: number,
|
|
2181
|
+
targetMaxVisualCol: number,
|
|
2182
|
+
): number {
|
|
2183
|
+
const hasPreferred = this.#preferredVisualCol !== null;
|
|
2184
|
+
const cursorInMiddle = currentVisualCol < sourceMaxVisualCol;
|
|
2185
|
+
const targetTooShort = targetMaxVisualCol < currentVisualCol;
|
|
2186
|
+
|
|
2187
|
+
if (!hasPreferred || cursorInMiddle) {
|
|
2188
|
+
if (targetTooShort) {
|
|
2189
|
+
this.#preferredVisualCol = currentVisualCol;
|
|
2190
|
+
return targetMaxVisualCol;
|
|
2191
|
+
}
|
|
2192
|
+
this.#preferredVisualCol = null;
|
|
2193
|
+
return currentVisualCol;
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
const targetCantFitPreferred = targetMaxVisualCol < this.#preferredVisualCol!;
|
|
2197
|
+
if (targetTooShort || targetCantFitPreferred) {
|
|
2198
|
+
return targetMaxVisualCol;
|
|
2199
|
+
}
|
|
2200
|
+
|
|
2201
|
+
const result = this.#preferredVisualCol!;
|
|
2202
|
+
this.#preferredVisualCol = null;
|
|
2203
|
+
return result;
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
#moveToLineStart(): void {
|
|
2207
|
+
this.#resetKillSequence();
|
|
2208
|
+
this.#setCursorCol(0);
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
#moveToLineEnd(): void {
|
|
2212
|
+
this.#resetKillSequence();
|
|
2213
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2214
|
+
this.#setCursorCol(currentLine.length);
|
|
2215
|
+
}
|
|
2216
|
+
|
|
2217
|
+
#moveToMessageStart(): void {
|
|
2218
|
+
this.#resetKillSequence();
|
|
2219
|
+
this.#state.cursorLine = 0;
|
|
2220
|
+
this.#setCursorCol(0);
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
#moveToMessageEnd(): void {
|
|
2224
|
+
this.#resetKillSequence();
|
|
2225
|
+
this.#state.cursorLine = this.#state.lines.length - 1;
|
|
2226
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2227
|
+
this.#setCursorCol(currentLine.length);
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
#resetKillSequence(): void {
|
|
2231
|
+
this.#lastAction = null;
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
#withUndoSuspended<T>(fn: () => T): T {
|
|
2235
|
+
const wasSuspended = this.#suspendUndo;
|
|
2236
|
+
this.#suspendUndo = true;
|
|
2237
|
+
try {
|
|
2238
|
+
return fn();
|
|
2239
|
+
} finally {
|
|
2240
|
+
this.#suspendUndo = wasSuspended;
|
|
2241
|
+
}
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
#recordUndoState(): void {
|
|
2245
|
+
if (this.#suspendUndo) return;
|
|
2246
|
+
this.#undoStack.push(structuredClone(this.#state));
|
|
2247
|
+
if (this.#undoStack.length > MAX_UNDO_STACK) {
|
|
2248
|
+
this.#undoStack.shift();
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
#applyUndo(): void {
|
|
2253
|
+
const snapshot = this.#undoStack.pop();
|
|
2254
|
+
if (!snapshot) return;
|
|
2255
|
+
|
|
2256
|
+
this.#historyIndex = -1;
|
|
2257
|
+
this.#resetKillSequence();
|
|
2258
|
+
this.#preferredVisualCol = null;
|
|
2259
|
+
Object.assign(this.#state, snapshot);
|
|
2260
|
+
|
|
2261
|
+
if (this.onChange) {
|
|
2262
|
+
this.onChange(this.getText());
|
|
2263
|
+
}
|
|
2264
|
+
|
|
2265
|
+
if (this.#autocompleteState) {
|
|
2266
|
+
this.#debouncedUpdateAutocomplete();
|
|
2267
|
+
} else {
|
|
2268
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2269
|
+
const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
2270
|
+
if (this.#isInSlashAutocompleteContext()) {
|
|
2271
|
+
this.#tryTriggerAutocomplete();
|
|
2272
|
+
} else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
|
|
2273
|
+
this.#tryTriggerAutocomplete();
|
|
2274
|
+
} else if (textBeforeCursor.match(/#[^\s#]*$/)) {
|
|
2275
|
+
this.#tryTriggerAutocomplete();
|
|
2276
|
+
} else if (this.#textTriggersUrlAutocomplete(textBeforeCursor)) {
|
|
2277
|
+
this.#tryTriggerAutocomplete();
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
|
|
2282
|
+
#matchesTransientUndoSnapshot(
|
|
2283
|
+
snapshot: EditorState,
|
|
2284
|
+
transientText: string,
|
|
2285
|
+
transientStartCol: number,
|
|
2286
|
+
beforeTransient: string,
|
|
2287
|
+
afterTransient: string,
|
|
2288
|
+
): boolean {
|
|
2289
|
+
if (snapshot.cursorLine !== this.#state.cursorLine) return false;
|
|
2290
|
+
if (snapshot.lines.length !== this.#state.lines.length) return false;
|
|
2291
|
+
|
|
2292
|
+
const transientLength = snapshot.cursorCol - transientStartCol;
|
|
2293
|
+
if (transientLength < 0 || transientLength >= transientText.length) return false;
|
|
2294
|
+
|
|
2295
|
+
for (let i = 0; i < snapshot.lines.length; i++) {
|
|
2296
|
+
if (i === this.#state.cursorLine) continue;
|
|
2297
|
+
if (snapshot.lines[i] !== this.#state.lines[i]) return false;
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
return (
|
|
2301
|
+
snapshot.lines[snapshot.cursorLine] ===
|
|
2302
|
+
beforeTransient + transientText.slice(0, transientLength) + afterTransient
|
|
2303
|
+
);
|
|
2304
|
+
}
|
|
2305
|
+
|
|
2306
|
+
#recordKill(text: string, direction: "forward" | "backward", accumulate = this.#lastAction === "kill"): void {
|
|
2307
|
+
if (!text) return;
|
|
2308
|
+
this.#killRing.push(text, { prepend: direction === "backward", accumulate });
|
|
2309
|
+
this.#lastAction = "kill";
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
#insertTextAtCursor(text: string): void {
|
|
2313
|
+
this.#historyIndex = -1;
|
|
2314
|
+
this.#resetKillSequence();
|
|
2315
|
+
this.#recordUndoState();
|
|
2316
|
+
|
|
2317
|
+
const normalized = text.replace(/\r\n?/g, "\n");
|
|
2318
|
+
const lines = normalized.split("\n");
|
|
2319
|
+
|
|
2320
|
+
if (lines.length === 1) {
|
|
2321
|
+
const line = this.#state.lines[this.#state.cursorLine] || "";
|
|
2322
|
+
const before = line.slice(0, this.#state.cursorCol);
|
|
2323
|
+
const after = line.slice(this.#state.cursorCol);
|
|
2324
|
+
this.#state.lines[this.#state.cursorLine] = before + normalized + after;
|
|
2325
|
+
this.#setCursorCol(this.#state.cursorCol + normalized.length);
|
|
2326
|
+
} else {
|
|
2327
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2328
|
+
const beforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
2329
|
+
const afterCursor = currentLine.slice(this.#state.cursorCol);
|
|
2330
|
+
|
|
2331
|
+
const newLines: string[] = [];
|
|
2332
|
+
for (let i = 0; i < this.#state.cursorLine; i++) {
|
|
2333
|
+
newLines.push(this.#state.lines[i] || "");
|
|
2334
|
+
}
|
|
2335
|
+
|
|
2336
|
+
newLines.push(beforeCursor + (lines[0] || ""));
|
|
2337
|
+
for (let i = 1; i < lines.length - 1; i++) {
|
|
2338
|
+
newLines.push(lines[i] || "");
|
|
2339
|
+
}
|
|
2340
|
+
newLines.push((lines[lines.length - 1] || "") + afterCursor);
|
|
2341
|
+
|
|
2342
|
+
for (let i = this.#state.cursorLine + 1; i < this.#state.lines.length; i++) {
|
|
2343
|
+
newLines.push(this.#state.lines[i] || "");
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
this.#state.lines = newLines;
|
|
2347
|
+
this.#state.cursorLine += lines.length - 1;
|
|
2348
|
+
this.#setCursorCol((lines[lines.length - 1] || "").length);
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
if (this.onChange) {
|
|
2352
|
+
this.onChange(this.getText());
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
#yankFromKillRing(): void {
|
|
2357
|
+
const text = this.#killRing.peek();
|
|
2358
|
+
if (!text) return;
|
|
2359
|
+
this.#insertTextAtCursor(text);
|
|
2360
|
+
this.#lastAction = "yank";
|
|
2361
|
+
}
|
|
2362
|
+
|
|
2363
|
+
#yankPop(): void {
|
|
2364
|
+
if (this.#lastAction !== "yank") return;
|
|
2365
|
+
if (this.#killRing.length <= 1) return;
|
|
2366
|
+
|
|
2367
|
+
this.#historyIndex = -1;
|
|
2368
|
+
this.#recordUndoState();
|
|
2369
|
+
|
|
2370
|
+
this.#withUndoSuspended(() => {
|
|
2371
|
+
if (!this.#deleteYankedText()) return;
|
|
2372
|
+
this.#killRing.rotate();
|
|
2373
|
+
const text = this.#killRing.peek();
|
|
2374
|
+
if (text) {
|
|
2375
|
+
this.#insertTextAtCursor(text);
|
|
2376
|
+
}
|
|
2377
|
+
});
|
|
2378
|
+
|
|
2379
|
+
this.#lastAction = "yank";
|
|
2380
|
+
}
|
|
2381
|
+
|
|
2382
|
+
/**
|
|
2383
|
+
* Delete the most recently yanked text from the buffer.
|
|
2384
|
+
*
|
|
2385
|
+
* This is a best-effort operation and assumes the cursor is still positioned
|
|
2386
|
+
* at the end of the yanked text.
|
|
2387
|
+
*/
|
|
2388
|
+
#deleteYankedText(): boolean {
|
|
2389
|
+
const yankedText = this.#killRing.peek();
|
|
2390
|
+
if (!yankedText) return false;
|
|
2391
|
+
|
|
2392
|
+
const yankLines = yankedText.split("\n");
|
|
2393
|
+
const endLine = this.#state.cursorLine;
|
|
2394
|
+
const endCol = this.#state.cursorCol;
|
|
2395
|
+
const startLine = endLine - (yankLines.length - 1);
|
|
2396
|
+
if (startLine < 0) return false;
|
|
2397
|
+
|
|
2398
|
+
if (yankLines.length === 1) {
|
|
2399
|
+
const line = this.#state.lines[endLine] ?? "";
|
|
2400
|
+
const startCol = endCol - yankedText.length;
|
|
2401
|
+
if (startCol < 0) return false;
|
|
2402
|
+
if (line.slice(startCol, endCol) !== yankedText) return false;
|
|
2403
|
+
|
|
2404
|
+
this.#state.lines[endLine] = line.slice(0, startCol) + line.slice(endCol);
|
|
2405
|
+
this.#state.cursorLine = endLine;
|
|
2406
|
+
this.#setCursorCol(startCol);
|
|
2407
|
+
return true;
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
const firstInserted = yankLines[0] ?? "";
|
|
2411
|
+
const lastInserted = yankLines[yankLines.length - 1] ?? "";
|
|
2412
|
+
const firstLineText = this.#state.lines[startLine] ?? "";
|
|
2413
|
+
const lastLineText = this.#state.lines[endLine] ?? "";
|
|
2414
|
+
|
|
2415
|
+
if (!firstLineText.endsWith(firstInserted)) return false;
|
|
2416
|
+
if (endCol !== lastInserted.length) return false;
|
|
2417
|
+
if (lastLineText.slice(0, endCol) !== lastInserted) return false;
|
|
2418
|
+
|
|
2419
|
+
const startCol = firstLineText.length - firstInserted.length;
|
|
2420
|
+
if (startCol < 0) return false;
|
|
2421
|
+
|
|
2422
|
+
const suffix = lastLineText.slice(endCol);
|
|
2423
|
+
const newLine = firstLineText.slice(0, startCol) + suffix;
|
|
2424
|
+
|
|
2425
|
+
this.#state.lines.splice(startLine, yankLines.length, newLine);
|
|
2426
|
+
this.#state.cursorLine = startLine;
|
|
2427
|
+
this.#setCursorCol(startCol);
|
|
2428
|
+
return true;
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
#deleteToStartOfLine(): void {
|
|
2432
|
+
this.#historyIndex = -1; // Exit history browsing mode
|
|
2433
|
+
this.#recordUndoState();
|
|
2434
|
+
|
|
2435
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2436
|
+
let deletedText = "";
|
|
2437
|
+
|
|
2438
|
+
if (this.#state.cursorCol > 0) {
|
|
2439
|
+
// Delete from start of line up to cursor, extending over any atomic token
|
|
2440
|
+
// the boundary would otherwise cut in half.
|
|
2441
|
+
const { end } = this.#expandRangeOverAtomicTokens(currentLine, 0, this.#state.cursorCol);
|
|
2442
|
+
deletedText = currentLine.slice(0, end);
|
|
2443
|
+
this.#state.lines[this.#state.cursorLine] = currentLine.slice(end);
|
|
2444
|
+
this.#setCursorCol(0);
|
|
2445
|
+
} else if (this.#state.cursorLine > 0) {
|
|
2446
|
+
// At start of line - merge with previous line
|
|
2447
|
+
deletedText = "\n";
|
|
2448
|
+
const previousLine = this.#state.lines[this.#state.cursorLine - 1] || "";
|
|
2449
|
+
this.#state.lines[this.#state.cursorLine - 1] = previousLine + currentLine;
|
|
2450
|
+
this.#state.lines.splice(this.#state.cursorLine, 1);
|
|
2451
|
+
this.#state.cursorLine--;
|
|
2452
|
+
this.#setCursorCol(previousLine.length);
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2455
|
+
this.#recordKill(deletedText, "backward");
|
|
2456
|
+
|
|
2457
|
+
if (this.onChange) {
|
|
2458
|
+
this.onChange(this.getText());
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
#deleteToEndOfLine(): void {
|
|
2463
|
+
this.#historyIndex = -1; // Exit history browsing mode
|
|
2464
|
+
this.#recordUndoState();
|
|
2465
|
+
|
|
2466
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2467
|
+
let deletedText = "";
|
|
2468
|
+
|
|
2469
|
+
if (this.#state.cursorCol < currentLine.length) {
|
|
2470
|
+
// Delete from cursor to end of line, extending backwards over an atomic
|
|
2471
|
+
// token the cursor sits inside so no half-eaten marker text remains.
|
|
2472
|
+
const { start } = this.#expandRangeOverAtomicTokens(currentLine, this.#state.cursorCol, currentLine.length);
|
|
2473
|
+
deletedText = currentLine.slice(start);
|
|
2474
|
+
this.#state.lines[this.#state.cursorLine] = currentLine.slice(0, start);
|
|
2475
|
+
if (start < this.#state.cursorCol) {
|
|
2476
|
+
this.#setCursorCol(start);
|
|
2477
|
+
}
|
|
2478
|
+
} else if (this.#state.cursorLine < this.#state.lines.length - 1) {
|
|
2479
|
+
// At end of line - merge with next line
|
|
2480
|
+
const nextLine = this.#state.lines[this.#state.cursorLine + 1] || "";
|
|
2481
|
+
deletedText = "\n";
|
|
2482
|
+
this.#state.lines[this.#state.cursorLine] = currentLine + nextLine;
|
|
2483
|
+
this.#state.lines.splice(this.#state.cursorLine + 1, 1);
|
|
2484
|
+
}
|
|
2485
|
+
|
|
2486
|
+
this.#recordKill(deletedText, "forward");
|
|
2487
|
+
|
|
2488
|
+
if (this.onChange) {
|
|
2489
|
+
this.onChange(this.getText());
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
#deleteWordBackwards(): void {
|
|
2494
|
+
this.#historyIndex = -1; // Exit history browsing mode
|
|
2495
|
+
this.#recordUndoState();
|
|
2496
|
+
|
|
2497
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2498
|
+
|
|
2499
|
+
// If at start of line, behave like backspace at column 0 (merge with previous line)
|
|
2500
|
+
if (this.#state.cursorCol === 0) {
|
|
2501
|
+
if (this.#state.cursorLine > 0) {
|
|
2502
|
+
this.#recordKill("\n", "backward");
|
|
2503
|
+
const previousLine = this.#state.lines[this.#state.cursorLine - 1] || "";
|
|
2504
|
+
this.#state.lines[this.#state.cursorLine - 1] = previousLine + currentLine;
|
|
2505
|
+
this.#state.lines.splice(this.#state.cursorLine, 1);
|
|
2506
|
+
this.#state.cursorLine--;
|
|
2507
|
+
this.#setCursorCol(previousLine.length);
|
|
2508
|
+
}
|
|
2509
|
+
} else {
|
|
2510
|
+
const oldCursorCol = this.#state.cursorCol;
|
|
2511
|
+
this.#moveWordBackwards();
|
|
2512
|
+
// Extend the range over any atomic token it intersects so a word delete
|
|
2513
|
+
// never leaves half-eaten marker text behind.
|
|
2514
|
+
const range = this.#expandRangeOverAtomicTokens(currentLine, this.#state.cursorCol, oldCursorCol);
|
|
2515
|
+
|
|
2516
|
+
const deletedText = currentLine.slice(range.start, range.end);
|
|
2517
|
+
this.#state.lines[this.#state.cursorLine] = currentLine.slice(0, range.start) + currentLine.slice(range.end);
|
|
2518
|
+
this.#setCursorCol(range.start);
|
|
2519
|
+
this.#recordKill(deletedText, "backward");
|
|
2520
|
+
}
|
|
2521
|
+
|
|
2522
|
+
if (this.onChange) {
|
|
2523
|
+
this.onChange(this.getText());
|
|
2524
|
+
}
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2527
|
+
#deleteWordForwards(): void {
|
|
2528
|
+
this.#historyIndex = -1; // Exit history browsing mode
|
|
2529
|
+
this.#recordUndoState();
|
|
2530
|
+
|
|
2531
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2532
|
+
|
|
2533
|
+
if (this.#state.cursorCol >= currentLine.length) {
|
|
2534
|
+
if (this.#state.cursorLine < this.#state.lines.length - 1) {
|
|
2535
|
+
this.#recordKill("\n", "forward");
|
|
2536
|
+
const nextLine = this.#state.lines[this.#state.cursorLine + 1] || "";
|
|
2537
|
+
this.#state.lines[this.#state.cursorLine] = currentLine + nextLine;
|
|
2538
|
+
this.#state.lines.splice(this.#state.cursorLine + 1, 1);
|
|
2539
|
+
}
|
|
2540
|
+
} else {
|
|
2541
|
+
const oldCursorCol = this.#state.cursorCol;
|
|
2542
|
+
this.#moveWordForwards();
|
|
2543
|
+
// Extend the range over any atomic token it intersects so a word delete
|
|
2544
|
+
// never leaves half-eaten marker text behind.
|
|
2545
|
+
const range = this.#expandRangeOverAtomicTokens(currentLine, oldCursorCol, this.#state.cursorCol);
|
|
2546
|
+
|
|
2547
|
+
const deletedText = currentLine.slice(range.start, range.end);
|
|
2548
|
+
this.#state.lines[this.#state.cursorLine] = currentLine.slice(0, range.start) + currentLine.slice(range.end);
|
|
2549
|
+
this.#setCursorCol(range.start);
|
|
2550
|
+
this.#recordKill(deletedText, "forward");
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
if (this.onChange) {
|
|
2554
|
+
this.onChange(this.getText());
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
|
|
2558
|
+
#handleForwardDelete(): void {
|
|
2559
|
+
this.#historyIndex = -1; // Exit history browsing mode
|
|
2560
|
+
this.#resetKillSequence();
|
|
2561
|
+
this.#recordUndoState();
|
|
2562
|
+
|
|
2563
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2564
|
+
|
|
2565
|
+
if (this.#state.cursorCol < currentLine.length) {
|
|
2566
|
+
// An atomic placeholder token (image/paste marker) deletes as a unit.
|
|
2567
|
+
const token = this.#atomicTokenAt(currentLine, this.#state.cursorCol);
|
|
2568
|
+
if (token !== undefined) {
|
|
2569
|
+
this.#state.lines[this.#state.cursorLine] =
|
|
2570
|
+
currentLine.slice(0, token.start) + currentLine.slice(token.end);
|
|
2571
|
+
this.#setCursorCol(token.start);
|
|
2572
|
+
} else {
|
|
2573
|
+
// Delete grapheme at cursor position (handles emojis, combining characters, etc.)
|
|
2574
|
+
const afterCursor = currentLine.slice(this.#state.cursorCol);
|
|
2575
|
+
|
|
2576
|
+
// Find the first grapheme at cursor
|
|
2577
|
+
const graphemes = [...segmenter.segment(afterCursor)];
|
|
2578
|
+
const firstGrapheme = graphemes[0];
|
|
2579
|
+
const graphemeLength = firstGrapheme ? firstGrapheme.segment.length : 1;
|
|
2580
|
+
|
|
2581
|
+
const before = currentLine.slice(0, this.#state.cursorCol);
|
|
2582
|
+
const after = currentLine.slice(this.#state.cursorCol + graphemeLength);
|
|
2583
|
+
this.#state.lines[this.#state.cursorLine] = before + after;
|
|
2584
|
+
}
|
|
2585
|
+
} else if (this.#state.cursorLine < this.#state.lines.length - 1) {
|
|
2586
|
+
// At end of line - merge with next line
|
|
2587
|
+
const nextLine = this.#state.lines[this.#state.cursorLine + 1] || "";
|
|
2588
|
+
this.#state.lines[this.#state.cursorLine] = currentLine + nextLine;
|
|
2589
|
+
this.#state.lines.splice(this.#state.cursorLine + 1, 1);
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
if (this.onChange) {
|
|
2593
|
+
this.onChange(this.getText());
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2596
|
+
// Update or re-trigger autocomplete after forward delete
|
|
2597
|
+
if (this.#autocompleteState) {
|
|
2598
|
+
this.#debouncedUpdateAutocomplete();
|
|
2599
|
+
} else {
|
|
2600
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2601
|
+
const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
2602
|
+
// Slash command or mid-prompt skill lookup context
|
|
2603
|
+
if (this.#isInSlashAutocompleteContext()) {
|
|
2604
|
+
this.#tryTriggerAutocomplete();
|
|
2605
|
+
}
|
|
2606
|
+
// @ file reference context
|
|
2607
|
+
else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
|
|
2608
|
+
this.#tryTriggerAutocomplete();
|
|
2609
|
+
}
|
|
2610
|
+
// # prompt action context
|
|
2611
|
+
else if (textBeforeCursor.match(/#[^\s#]*$/)) {
|
|
2612
|
+
this.#tryTriggerAutocomplete();
|
|
2613
|
+
}
|
|
2614
|
+
// internal URL scheme context (e.g. local://, skill://)
|
|
2615
|
+
else if (this.#textTriggersUrlAutocomplete(textBeforeCursor)) {
|
|
2616
|
+
this.#tryTriggerAutocomplete();
|
|
2617
|
+
}
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
|
|
2621
|
+
/**
|
|
2622
|
+
* Build a mapping from visual lines to logical positions.
|
|
2623
|
+
* Returns an array where each element represents a visual line with:
|
|
2624
|
+
* - logicalLine: index into this.#state.lines
|
|
2625
|
+
* - startCol: starting column in the logical line
|
|
2626
|
+
* - length: length of this visual line segment
|
|
2627
|
+
*/
|
|
2628
|
+
#buildVisualLineMap(width: number): Array<{ logicalLine: number; startCol: number; length: number }> {
|
|
2629
|
+
const visualLines: Array<{ logicalLine: number; startCol: number; length: number }> = [];
|
|
2630
|
+
|
|
2631
|
+
for (let i = 0; i < this.#state.lines.length; i++) {
|
|
2632
|
+
const line = this.#state.lines[i] || "";
|
|
2633
|
+
const lineVisWidth = visibleWidth(line);
|
|
2634
|
+
if (line.length === 0) {
|
|
2635
|
+
// Empty line still takes one visual line
|
|
2636
|
+
visualLines.push({ logicalLine: i, startCol: 0, length: 0 });
|
|
2637
|
+
} else if (lineVisWidth <= width) {
|
|
2638
|
+
visualLines.push({ logicalLine: i, startCol: 0, length: line.length });
|
|
2639
|
+
} else {
|
|
2640
|
+
// Line needs wrapping - use word-aware wrapping
|
|
2641
|
+
const chunks = this.#wrapLine(line, width);
|
|
2642
|
+
for (const chunk of chunks) {
|
|
2643
|
+
visualLines.push({
|
|
2644
|
+
logicalLine: i,
|
|
2645
|
+
startCol: chunk.startIndex,
|
|
2646
|
+
length: chunk.endIndex - chunk.startIndex,
|
|
2647
|
+
});
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
|
|
2652
|
+
return visualLines;
|
|
2653
|
+
}
|
|
2654
|
+
|
|
2655
|
+
/**
|
|
2656
|
+
* Find the visual line index for the current cursor position.
|
|
2657
|
+
*/
|
|
2658
|
+
#findCurrentVisualLine(visualLines: Array<{ logicalLine: number; startCol: number; length: number }>): number {
|
|
2659
|
+
for (let i = 0; i < visualLines.length; i++) {
|
|
2660
|
+
const vl = visualLines[i];
|
|
2661
|
+
if (!vl) continue;
|
|
2662
|
+
if (vl.logicalLine === this.#state.cursorLine) {
|
|
2663
|
+
const colInSegment = this.#state.cursorCol - vl.startCol;
|
|
2664
|
+
// Cursor is in this segment if it's within range
|
|
2665
|
+
// For the last segment of a logical line, cursor can be at length (end position)
|
|
2666
|
+
// The first segment also owns any leading whitespace the wrapper skipped
|
|
2667
|
+
// (its startCol can be > 0), so a negative colInSegment maps there.
|
|
2668
|
+
const isLastSegmentOfLine =
|
|
2669
|
+
i === visualLines.length - 1 || visualLines[i + 1]?.logicalLine !== vl.logicalLine;
|
|
2670
|
+
const isFirstSegmentOfLine = i === 0 || visualLines[i - 1]?.logicalLine !== vl.logicalLine;
|
|
2671
|
+
if (
|
|
2672
|
+
(colInSegment >= 0 || isFirstSegmentOfLine) &&
|
|
2673
|
+
(colInSegment < vl.length || (isLastSegmentOfLine && colInSegment <= vl.length))
|
|
2674
|
+
) {
|
|
2675
|
+
return i;
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
// Fallback: return last visual line
|
|
2680
|
+
return visualLines.length - 1;
|
|
2681
|
+
}
|
|
2682
|
+
|
|
2683
|
+
#moveCursor(deltaLine: number, deltaCol: number): void {
|
|
2684
|
+
this.#resetKillSequence();
|
|
2685
|
+
const visualLines = this.#buildVisualLineMap(this.#lastLayoutWidth);
|
|
2686
|
+
const currentVisualLine = this.#findCurrentVisualLine(visualLines);
|
|
2687
|
+
|
|
2688
|
+
if (deltaLine !== 0) {
|
|
2689
|
+
const targetVisualLine = currentVisualLine + deltaLine;
|
|
2690
|
+
|
|
2691
|
+
if (targetVisualLine >= 0 && targetVisualLine < visualLines.length) {
|
|
2692
|
+
this.#moveToVisualLine(visualLines, currentVisualLine, targetVisualLine);
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
|
|
2696
|
+
if (deltaCol !== 0) {
|
|
2697
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2698
|
+
|
|
2699
|
+
if (deltaCol > 0) {
|
|
2700
|
+
// Moving right - move by one grapheme (handles emojis, combining characters, etc.)
|
|
2701
|
+
if (this.#state.cursorCol < currentLine.length) {
|
|
2702
|
+
const afterCursor = currentLine.slice(this.#state.cursorCol);
|
|
2703
|
+
const graphemes = [...segmenter.segment(afterCursor)];
|
|
2704
|
+
const firstGrapheme = graphemes[0];
|
|
2705
|
+
this.#setCursorCol(this.#state.cursorCol + (firstGrapheme ? firstGrapheme.segment.length : 1));
|
|
2706
|
+
} else if (this.#state.cursorLine < this.#state.lines.length - 1) {
|
|
2707
|
+
// Wrap to start of next logical line
|
|
2708
|
+
this.#state.cursorLine++;
|
|
2709
|
+
this.#setCursorCol(0);
|
|
2710
|
+
} else {
|
|
2711
|
+
// At end of last line - can't move, but set preferredVisualCol for up/down navigation
|
|
2712
|
+
const currentVL = visualLines[currentVisualLine];
|
|
2713
|
+
if (currentVL) {
|
|
2714
|
+
const segmentText = currentLine.slice(currentVL.startCol, currentVL.startCol + currentVL.length);
|
|
2715
|
+
this.#preferredVisualCol = visualColAtOffset(segmentText, this.#state.cursorCol - currentVL.startCol);
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
} else {
|
|
2719
|
+
// Moving left - move by one grapheme (handles emojis, combining characters, etc.)
|
|
2720
|
+
if (this.#state.cursorCol > 0) {
|
|
2721
|
+
const beforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
2722
|
+
const graphemes = [...segmenter.segment(beforeCursor)];
|
|
2723
|
+
const lastGrapheme = graphemes[graphemes.length - 1];
|
|
2724
|
+
this.#setCursorCol(this.#state.cursorCol - (lastGrapheme ? lastGrapheme.segment.length : 1));
|
|
2725
|
+
} else if (this.#state.cursorLine > 0) {
|
|
2726
|
+
// Wrap to end of previous logical line
|
|
2727
|
+
this.#state.cursorLine--;
|
|
2728
|
+
const prevLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2729
|
+
this.#setCursorCol(prevLine.length);
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
|
|
2735
|
+
#pageScroll(direction: -1 | 1): void {
|
|
2736
|
+
this.#resetKillSequence();
|
|
2737
|
+
const visualLines = this.#buildVisualLineMap(this.#lastLayoutWidth);
|
|
2738
|
+
const currentVisualLine = this.#findCurrentVisualLine(visualLines);
|
|
2739
|
+
const step = this.#getPageScrollStep(visualLines.length);
|
|
2740
|
+
const targetVisualLine = Math.max(0, Math.min(visualLines.length - 1, currentVisualLine + direction * step));
|
|
2741
|
+
if (targetVisualLine === currentVisualLine) return;
|
|
2742
|
+
this.#moveToVisualLine(visualLines, currentVisualLine, targetVisualLine);
|
|
2743
|
+
}
|
|
2744
|
+
|
|
2745
|
+
#moveWordBackwards(): void {
|
|
2746
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2747
|
+
|
|
2748
|
+
// If at start of line, move to end of previous line
|
|
2749
|
+
if (this.#state.cursorCol === 0) {
|
|
2750
|
+
if (this.#state.cursorLine > 0) {
|
|
2751
|
+
this.#state.cursorLine--;
|
|
2752
|
+
const prevLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2753
|
+
this.#setCursorCol(prevLine.length);
|
|
2754
|
+
}
|
|
2755
|
+
return;
|
|
2756
|
+
}
|
|
2757
|
+
|
|
2758
|
+
this.#setCursorCol(moveWordLeft(currentLine, this.#state.cursorCol));
|
|
2759
|
+
}
|
|
2760
|
+
|
|
2761
|
+
/**
|
|
2762
|
+
* Jump to the first occurrence of a character in the specified direction.
|
|
2763
|
+
* Multi-line search. Case-sensitive. Skips the current cursor position.
|
|
2764
|
+
*/
|
|
2765
|
+
#jumpToChar(char: string, direction: "forward" | "backward"): void {
|
|
2766
|
+
this.#resetKillSequence();
|
|
2767
|
+
const isForward = direction === "forward";
|
|
2768
|
+
const lines = this.#state.lines;
|
|
2769
|
+
|
|
2770
|
+
const end = isForward ? lines.length : -1;
|
|
2771
|
+
const step = isForward ? 1 : -1;
|
|
2772
|
+
|
|
2773
|
+
for (let lineIdx = this.#state.cursorLine; lineIdx !== end; lineIdx += step) {
|
|
2774
|
+
const line = lines[lineIdx] || "";
|
|
2775
|
+
const isCurrentLine = lineIdx === this.#state.cursorLine;
|
|
2776
|
+
|
|
2777
|
+
// Current line: start after/before cursor; other lines: search full line
|
|
2778
|
+
const searchFrom = isCurrentLine
|
|
2779
|
+
? isForward
|
|
2780
|
+
? this.#state.cursorCol + 1
|
|
2781
|
+
: this.#state.cursorCol - 1
|
|
2782
|
+
: undefined;
|
|
2783
|
+
|
|
2784
|
+
const idx = isForward ? line.indexOf(char, searchFrom) : line.lastIndexOf(char, searchFrom);
|
|
2785
|
+
|
|
2786
|
+
if (idx !== -1) {
|
|
2787
|
+
this.#state.cursorLine = lineIdx;
|
|
2788
|
+
this.#setCursorCol(idx);
|
|
2789
|
+
return;
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
// No match found - cursor stays in place
|
|
2793
|
+
}
|
|
2794
|
+
|
|
2795
|
+
#moveWordForwards(): void {
|
|
2796
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2797
|
+
|
|
2798
|
+
// If at end of line, move to start of next line
|
|
2799
|
+
if (this.#state.cursorCol >= currentLine.length) {
|
|
2800
|
+
if (this.#state.cursorLine < this.#state.lines.length - 1) {
|
|
2801
|
+
this.#state.cursorLine++;
|
|
2802
|
+
this.#setCursorCol(0);
|
|
2803
|
+
}
|
|
2804
|
+
return;
|
|
2805
|
+
}
|
|
2806
|
+
|
|
2807
|
+
this.#setCursorCol(moveWordRight(currentLine, this.#state.cursorCol));
|
|
2808
|
+
}
|
|
2809
|
+
|
|
2810
|
+
#hasOnlyWhitespaceBeforeCursorLine(): boolean {
|
|
2811
|
+
for (let i = 0; i < this.#state.cursorLine; i++) {
|
|
2812
|
+
if ((this.#state.lines[i] || "").trim() !== "") {
|
|
2813
|
+
return false;
|
|
2814
|
+
}
|
|
2815
|
+
}
|
|
2816
|
+
return true;
|
|
2817
|
+
}
|
|
2818
|
+
|
|
2819
|
+
// Slash commands execute only when the submitted prompt starts with the command.
|
|
2820
|
+
#isAtStartOfSubmittedMessage(): boolean {
|
|
2821
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2822
|
+
const beforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
2823
|
+
|
|
2824
|
+
return this.#hasOnlyWhitespaceBeforeCursorLine() && (beforeCursor.trim() === "" || beforeCursor.trim() === "/");
|
|
2825
|
+
}
|
|
2826
|
+
|
|
2827
|
+
#isInSubmittedSlashCommandContext(): boolean {
|
|
2828
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2829
|
+
const beforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
2830
|
+
return this.#hasOnlyWhitespaceBeforeCursorLine() && beforeCursor.trimStart().startsWith("/");
|
|
2831
|
+
}
|
|
2832
|
+
|
|
2833
|
+
#isInMidPromptSkillSlashContext(): boolean {
|
|
2834
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2835
|
+
const beforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
2836
|
+
const slashStart = findTrailingSlashCommandStart(beforeCursor);
|
|
2837
|
+
if (slashStart === null) return false;
|
|
2838
|
+
if (this.#hasOnlyWhitespaceBeforeCursorLine() && findLeadingSlashCommandStart(beforeCursor) !== null)
|
|
2839
|
+
return false;
|
|
2840
|
+
return !this.#hasOnlyWhitespaceBeforeCursorLine() || beforeCursor.slice(0, slashStart).trim() !== "";
|
|
2841
|
+
}
|
|
2842
|
+
|
|
2843
|
+
#isInSlashAutocompleteContext(): boolean {
|
|
2844
|
+
return this.#isInSubmittedSlashCommandContext() || this.#isInMidPromptSkillSlashContext();
|
|
2845
|
+
}
|
|
2846
|
+
|
|
2847
|
+
#autocompletePrefixMatchesCursorText(currentTextBeforeCursor: string): boolean {
|
|
2848
|
+
if (currentTextBeforeCursor === this.#autocompletePrefix) return true;
|
|
2849
|
+
if (findTrailingSlashCommandStart(this.#autocompletePrefix) !== 0) return false;
|
|
2850
|
+
const slashStart = findTrailingSlashCommandStart(currentTextBeforeCursor);
|
|
2851
|
+
return slashStart !== null && currentTextBeforeCursor.slice(slashStart) === this.#autocompletePrefix;
|
|
2852
|
+
}
|
|
2853
|
+
|
|
2854
|
+
#isSlashCommandNameAutocompleteSelection(): boolean {
|
|
2855
|
+
if (this.#autocompleteState !== "regular") {
|
|
2856
|
+
return false;
|
|
2857
|
+
}
|
|
2858
|
+
|
|
2859
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2860
|
+
const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol).trimStart();
|
|
2861
|
+
return (
|
|
2862
|
+
this.#isInSubmittedSlashCommandContext() && textBeforeCursor.startsWith("/") && !textBeforeCursor.includes(" ")
|
|
2863
|
+
);
|
|
2864
|
+
}
|
|
2865
|
+
|
|
2866
|
+
#isCompletedSlashCommandAtCursor(): boolean {
|
|
2867
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2868
|
+
if (this.#state.cursorCol !== currentLine.length) {
|
|
2869
|
+
return false;
|
|
2870
|
+
}
|
|
2871
|
+
|
|
2872
|
+
const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol).trimStart();
|
|
2873
|
+
return this.#isInSubmittedSlashCommandContext() && /^\/\S+ $/.test(textBeforeCursor);
|
|
2874
|
+
}
|
|
2875
|
+
|
|
2876
|
+
// Autocomplete methods
|
|
2877
|
+
/**
|
|
2878
|
+
* Whether the text ending at the cursor looks like a `scheme://` URL token.
|
|
2879
|
+
* Generic by design: any scheme triggers a suggestion fetch and the active
|
|
2880
|
+
* provider decides whether it has candidates (returning none is a no-op).
|
|
2881
|
+
* MUST stay in sync with the token grammar in coding-agent's
|
|
2882
|
+
* `internal-url-autocomplete.ts`.
|
|
2883
|
+
*/
|
|
2884
|
+
#textTriggersUrlAutocomplete(textBeforeCursor: string): boolean {
|
|
2885
|
+
return /(?:^|[\s"'`(<=])[a-z][a-z0-9+.-]*:\/{1,2}[^\s"'`()<>]*$/i.test(textBeforeCursor);
|
|
2886
|
+
}
|
|
2887
|
+
|
|
2888
|
+
async #tryTriggerAutocomplete(explicitTab: boolean = false): Promise<void> {
|
|
2889
|
+
if (!this.#autocompleteProvider) return;
|
|
2890
|
+
// Check if we should trigger file completion on Tab
|
|
2891
|
+
if (explicitTab) {
|
|
2892
|
+
const shouldTrigger =
|
|
2893
|
+
!this.#autocompleteProvider.shouldTriggerFileCompletion ||
|
|
2894
|
+
this.#autocompleteProvider.shouldTriggerFileCompletion(
|
|
2895
|
+
this.#state.lines,
|
|
2896
|
+
this.#state.cursorLine,
|
|
2897
|
+
this.#state.cursorCol,
|
|
2898
|
+
);
|
|
2899
|
+
if (!shouldTrigger) {
|
|
2900
|
+
return;
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
|
|
2904
|
+
const requestId = ++this.#autocompleteRequestId;
|
|
2905
|
+
|
|
2906
|
+
const suggestions = await this.#autocompleteProvider.getSuggestions(
|
|
2907
|
+
this.#state.lines,
|
|
2908
|
+
this.#state.cursorLine,
|
|
2909
|
+
this.#state.cursorCol,
|
|
2910
|
+
);
|
|
2911
|
+
if (requestId !== this.#autocompleteRequestId) return;
|
|
2912
|
+
|
|
2913
|
+
if (suggestions && Array.isArray(suggestions.items) && suggestions.items.length > 0) {
|
|
2914
|
+
this.#autocompletePrefix = suggestions.prefix;
|
|
2915
|
+
this.#autocompleteList = this.#createAutocompleteList(suggestions.prefix, suggestions.items);
|
|
2916
|
+
this.#autocompleteState = "regular";
|
|
2917
|
+
this.onAutocompleteUpdate?.();
|
|
2918
|
+
} else {
|
|
2919
|
+
this.#cancelAutocomplete();
|
|
2920
|
+
this.onAutocompleteUpdate?.();
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
#createAutocompleteList(
|
|
2924
|
+
prefix: string,
|
|
2925
|
+
items: Array<{ value: string; label: string; description?: string }>,
|
|
2926
|
+
): SelectList {
|
|
2927
|
+
const layout = prefix.startsWith("/") ? SLASH_COMMAND_SELECT_LIST_LAYOUT : AUTOCOMPLETE_SELECT_LIST_LAYOUT;
|
|
2928
|
+
return new SelectList(items, this.#autocompleteMaxVisible, this.#theme.selectList, layout);
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
async #handleTabCompletion(): Promise<void> {
|
|
2932
|
+
if (!this.#autocompleteProvider) return;
|
|
2933
|
+
|
|
2934
|
+
const currentLine = this.#state.lines[this.#state.cursorLine] || "";
|
|
2935
|
+
const beforeCursor = currentLine.slice(0, this.#state.cursorCol);
|
|
2936
|
+
|
|
2937
|
+
if (this.#isInSubmittedSlashCommandContext() && !beforeCursor.trimStart().includes(" ")) {
|
|
2938
|
+
await this.#handleSlashCommandCompletion();
|
|
2939
|
+
} else if (this.#isInMidPromptSkillSlashContext()) {
|
|
2940
|
+
await this.#handleSlashCommandCompletion();
|
|
2941
|
+
if (!this.#autocompleteState) {
|
|
2942
|
+
await this.#forceFileAutocomplete(true);
|
|
2943
|
+
}
|
|
2944
|
+
} else {
|
|
2945
|
+
await this.#forceFileAutocomplete(true);
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
async #handleSlashCommandCompletion(): Promise<void> {
|
|
2949
|
+
await this.#tryTriggerAutocomplete();
|
|
2950
|
+
}
|
|
2951
|
+
|
|
2952
|
+
/*
|
|
2953
|
+
https://github.com/EsotericSoftware/spine-runtimes/actions/runs/19536643416/job/559322883
|
|
2954
|
+
17 this job fails with https://github.com/EsotericSoftware/spine-runtimes/actions/runs/19
|
|
2955
|
+
536643416/job/55932288317 havea look at .gi
|
|
2956
|
+
*/
|
|
2957
|
+
async #forceFileAutocomplete(explicitTab: boolean = false): Promise<void> {
|
|
2958
|
+
if (!this.#autocompleteProvider) return;
|
|
2959
|
+
|
|
2960
|
+
// File-aware providers expose getForceFileSuggestions; slash-only ones fall back to regular completion.
|
|
2961
|
+
const getForceFileSuggestions = this.#autocompleteProvider.getForceFileSuggestions;
|
|
2962
|
+
if (typeof getForceFileSuggestions !== "function") {
|
|
2963
|
+
await this.#tryTriggerAutocomplete(true);
|
|
2964
|
+
return;
|
|
2965
|
+
}
|
|
2966
|
+
|
|
2967
|
+
const requestId = ++this.#autocompleteRequestId;
|
|
2968
|
+
const suggestions = await getForceFileSuggestions.call(
|
|
2969
|
+
this.#autocompleteProvider,
|
|
2970
|
+
this.#state.lines,
|
|
2971
|
+
this.#state.cursorLine,
|
|
2972
|
+
this.#state.cursorCol,
|
|
2973
|
+
);
|
|
2974
|
+
if (requestId !== this.#autocompleteRequestId) return;
|
|
2975
|
+
|
|
2976
|
+
if (suggestions && Array.isArray(suggestions.items) && suggestions.items.length > 0) {
|
|
2977
|
+
// If there's exactly one suggestion and this was an explicit Tab press, apply it immediately
|
|
2978
|
+
if (explicitTab && suggestions.items.length === 1) {
|
|
2979
|
+
const item = suggestions.items[0]!;
|
|
2980
|
+
const result = this.#autocompleteProvider.applyCompletion(
|
|
2981
|
+
this.#state.lines,
|
|
2982
|
+
this.#state.cursorLine,
|
|
2983
|
+
this.#state.cursorCol,
|
|
2984
|
+
item,
|
|
2985
|
+
suggestions.prefix,
|
|
2986
|
+
);
|
|
2987
|
+
|
|
2988
|
+
this.#state.lines = result.lines;
|
|
2989
|
+
this.#state.cursorLine = result.cursorLine;
|
|
2990
|
+
this.#setCursorCol(result.cursorCol);
|
|
2991
|
+
|
|
2992
|
+
if (this.onChange) {
|
|
2993
|
+
this.onChange(this.getText());
|
|
2994
|
+
}
|
|
2995
|
+
return;
|
|
2996
|
+
}
|
|
2997
|
+
|
|
2998
|
+
this.#autocompletePrefix = suggestions.prefix;
|
|
2999
|
+
this.#autocompleteList = this.#createAutocompleteList(suggestions.prefix, suggestions.items);
|
|
3000
|
+
this.#autocompleteState = "force";
|
|
3001
|
+
this.onAutocompleteUpdate?.();
|
|
3002
|
+
} else {
|
|
3003
|
+
this.#cancelAutocomplete();
|
|
3004
|
+
this.onAutocompleteUpdate?.();
|
|
3005
|
+
}
|
|
3006
|
+
}
|
|
3007
|
+
|
|
3008
|
+
#cancelAutocomplete(notifyCancel: boolean = false): void {
|
|
3009
|
+
const wasAutocompleting = this.#autocompleteState !== null;
|
|
3010
|
+
this.#clearAutocompleteTimeout();
|
|
3011
|
+
this.#autocompleteRequestId += 1;
|
|
3012
|
+
this.#autocompleteState = null;
|
|
3013
|
+
this.#autocompleteList = undefined;
|
|
3014
|
+
this.#autocompletePrefix = "";
|
|
3015
|
+
if (notifyCancel && wasAutocompleting) {
|
|
3016
|
+
this.onAutocompleteCancel?.();
|
|
3017
|
+
}
|
|
3018
|
+
}
|
|
3019
|
+
|
|
3020
|
+
isShowingAutocomplete(): boolean {
|
|
3021
|
+
return this.#autocompleteState !== null;
|
|
3022
|
+
}
|
|
3023
|
+
|
|
3024
|
+
async #updateAutocomplete(): Promise<void> {
|
|
3025
|
+
if (!this.#autocompleteState || !this.#autocompleteProvider) return;
|
|
3026
|
+
|
|
3027
|
+
// In force mode, use forceFileAutocomplete to get suggestions
|
|
3028
|
+
if (this.#autocompleteState === "force") {
|
|
3029
|
+
this.#forceFileAutocomplete();
|
|
3030
|
+
return;
|
|
3031
|
+
}
|
|
3032
|
+
|
|
3033
|
+
const requestId = ++this.#autocompleteRequestId;
|
|
3034
|
+
|
|
3035
|
+
const suggestions = await this.#autocompleteProvider.getSuggestions(
|
|
3036
|
+
this.#state.lines,
|
|
3037
|
+
this.#state.cursorLine,
|
|
3038
|
+
this.#state.cursorCol,
|
|
3039
|
+
);
|
|
3040
|
+
if (requestId !== this.#autocompleteRequestId) return;
|
|
3041
|
+
|
|
3042
|
+
if (suggestions && Array.isArray(suggestions.items) && suggestions.items.length > 0) {
|
|
3043
|
+
this.#autocompletePrefix = suggestions.prefix;
|
|
3044
|
+
// Always create new SelectList to ensure update
|
|
3045
|
+
this.#autocompleteList = this.#createAutocompleteList(suggestions.prefix, suggestions.items);
|
|
3046
|
+
this.onAutocompleteUpdate?.();
|
|
3047
|
+
} else {
|
|
3048
|
+
this.#cancelAutocomplete();
|
|
3049
|
+
this.onAutocompleteUpdate?.();
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
|
|
3053
|
+
#debouncedUpdateAutocomplete(): void {
|
|
3054
|
+
if (this.#autocompleteTimeout) {
|
|
3055
|
+
clearTimeout(this.#autocompleteTimeout);
|
|
3056
|
+
}
|
|
3057
|
+
this.#autocompleteTimeout = setTimeout(() => {
|
|
3058
|
+
this.#updateAutocomplete();
|
|
3059
|
+
this.#autocompleteTimeout = undefined;
|
|
3060
|
+
}, 100);
|
|
3061
|
+
}
|
|
3062
|
+
|
|
3063
|
+
#clearAutocompleteTimeout(): void {
|
|
3064
|
+
if (this.#autocompleteTimeout) {
|
|
3065
|
+
clearTimeout(this.#autocompleteTimeout);
|
|
3066
|
+
this.#autocompleteTimeout = undefined;
|
|
3067
|
+
}
|
|
3068
|
+
}
|
|
3069
|
+
|
|
3070
|
+
/**
|
|
3071
|
+
* Get inline hint text to show as dim ghost text after the cursor.
|
|
3072
|
+
* Checks selected autocomplete item's hint first, then falls back to provider.
|
|
3073
|
+
*/
|
|
3074
|
+
#getInlineHint(): string | null {
|
|
3075
|
+
// Check selected autocomplete item for a hint
|
|
3076
|
+
if (this.#autocompleteState && this.#autocompleteList) {
|
|
3077
|
+
const selected = this.#autocompleteList.getSelectedItem();
|
|
3078
|
+
return selected?.hint ?? null;
|
|
3079
|
+
}
|
|
3080
|
+
|
|
3081
|
+
// Fall back to provider's getInlineHint
|
|
3082
|
+
if (this.#autocompleteProvider?.getInlineHint) {
|
|
3083
|
+
return this.#autocompleteProvider.getInlineHint(
|
|
3084
|
+
this.#state.lines,
|
|
3085
|
+
this.#state.cursorLine,
|
|
3086
|
+
this.#state.cursorCol,
|
|
3087
|
+
);
|
|
3088
|
+
}
|
|
3089
|
+
|
|
3090
|
+
return null;
|
|
3091
|
+
}
|
|
3092
|
+
}
|