@jadelclemens/pi-vim 0.0.0-stage → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/vim-editor.ts ADDED
@@ -0,0 +1,662 @@
1
+ /**
2
+ * VimEditor - Modal vim editor extending CustomEditor.
3
+ * Routes input to mode-specific handlers and renders mode indicator.
4
+ */
5
+
6
+ import { CustomEditor } from "@mariozechner/pi-coding-agent";
7
+ import {
8
+ CURSOR_MARKER,
9
+ matchesKey,
10
+ truncateToWidth,
11
+ visibleWidth,
12
+ } from "@mariozechner/pi-tui";
13
+ import type { TUI, EditorOptions, EditorTheme, AutocompleteProvider } from "@mariozechner/pi-tui";
14
+ import { watch, type FSWatcher } from "node:fs";
15
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { spawn } from "node:child_process";
19
+ import { createInitialState, modeDisplayName, type VimState } from "./state.js";
20
+ import type { VimConfig } from "./config.js";
21
+ import { handleNormalMode, type NormalModeContext } from "./modes/normal.js";
22
+ import { handleInsertMode, type InsertModeContext } from "./modes/insert.js";
23
+ import { handleReplaceMode, resetReplaceState, type ReplaceModeContext } from "./modes/replace.js";
24
+ import { handleVisualMode, getVisualRange, type VisualModeContext } from "./modes/visual.js";
25
+ import {
26
+ handleSearchInput,
27
+ getSearchPrompt,
28
+ getSearchState,
29
+ executeSearchMotion,
30
+ } from "./search.js";
31
+
32
+ const TMUX_HOOK_ID = `${process.pid}`;
33
+ const TMUX_STATE_DIR = join(tmpdir(), "pi-vim-focus");
34
+
35
+ function tmuxStateFile(pane: string): string {
36
+ return join(TMUX_STATE_DIR, `pane-${pane.replace(/[^a-zA-Z0-9_.-]/g, "_")}-${TMUX_HOOK_ID}.state`);
37
+ }
38
+
39
+ function shellQuote(value: string): string {
40
+ return `'${value.replace(/'/g, `'\\''`)}'`;
41
+ }
42
+
43
+ async function runTmux(args: string[]): Promise<void> {
44
+ await new Promise<void>((resolve) => {
45
+ const child = spawn("tmux", args, { stdio: "ignore", timeout: 2000 });
46
+ child.once("close", () => resolve());
47
+ child.once("error", () => resolve());
48
+ });
49
+ }
50
+
51
+ export class VimEditor extends CustomEditor {
52
+ public vimState: VimState;
53
+ private redoStack: Array<{ lines: string[]; cursorLine: number; cursorCol: number }> = [];
54
+ private wrapAutocomplete: ((provider: AutocompleteProvider) => AutocompleteProvider) | undefined;
55
+ private terminalFocused = true;
56
+ private tmuxFocusWatcher: FSWatcher | undefined;
57
+ private tmuxPane: string | undefined;
58
+
59
+ /**
60
+ * DECSCUSR cursor styles:
61
+ * 2 => steady block
62
+ * 6 => steady bar (thin)
63
+ */
64
+ private static readonly CURSOR_BLOCK = "\x1b[2 q";
65
+ private static readonly CURSOR_BAR = "\x1b[6 q";
66
+ // OSC 12 sets the terminal cursor color; OSC 112 restores its configured color.
67
+ private static readonly CURSOR_COLOR_RESET = "\x1b]112\x07";
68
+ private static readonly CURSOR_COLORS: Record<VimState["mode"], string> = {
69
+ normal: "#e5a50a", // yellow-orange
70
+ insert: "#57e389", // green
71
+ replace: "#ff7800",
72
+ visual: "#c061cb", // light purple
73
+ "visual-line": "#c061cb",
74
+ "command-line": "#c061cb",
75
+ "operator-pending": "#e5a50a",
76
+ };
77
+
78
+ private cursorFallbackStyle(mode: VimState["mode"]): string {
79
+ const hex = VimEditor.CURSOR_COLORS[mode].slice(1);
80
+ const [red, green, blue] = [0, 2, 4].map((offset) => Number.parseInt(hex.slice(offset, offset + 2), 16));
81
+ return `\x1b[2;4;38;2;${red};${green};${blue}m`;
82
+ }
83
+
84
+ constructor(
85
+ tui: TUI,
86
+ theme: EditorTheme,
87
+ keybindings: any,
88
+ options?: EditorOptions,
89
+ wrapAutocomplete?: (provider: AutocompleteProvider) => AutocompleteProvider,
90
+ private readonly config: VimConfig = { disableModeIndicator: false },
91
+ ) {
92
+ super(tui, theme, keybindings, options);
93
+ this.vimState = createInitialState();
94
+ this.wrapAutocomplete = wrapAutocomplete;
95
+ this.applyCursorShapeForMode(this.vimState.mode);
96
+ void this.startTmuxFocusTracking();
97
+ }
98
+
99
+ public isInNormalMode(): boolean {
100
+ return this.vimState.mode === "normal";
101
+ }
102
+
103
+ /**
104
+ * Apply a hardware cursor shape for the current vim mode.
105
+ * Insert mode uses a thin bar; all other modes use a block.
106
+ */
107
+ private applyCursorShapeForMode(mode: VimState["mode"]): void {
108
+ const isInsert = mode === "insert";
109
+ const seq = isInsert ? VimEditor.CURSOR_BAR : VimEditor.CURSOR_BLOCK;
110
+
111
+ // Let the terminal draw the focused cursor, but use a software fallback
112
+ // while unfocused: many terminals hide their hardware cursor entirely.
113
+ try {
114
+ this.tui.setShowHardwareCursor(this.terminalFocused);
115
+ } catch {
116
+ // Older pi-tui without hardware-cursor toggle; ignore.
117
+ }
118
+
119
+ try {
120
+ // Sakura/VTE supports OSC 12, and tmux forwards it to the outer terminal.
121
+ // Unsupported terminals simply ignore the sequence.
122
+ this.tui.terminal.write(`\x1b]12;${VimEditor.CURSOR_COLORS[mode]}\x07${seq}`);
123
+ } catch {
124
+ // Ignore terminals that don't support cursor style or cursor color.
125
+ }
126
+ }
127
+
128
+ /** Track focus through tmux hooks; Pi consumes terminal CSI focus events. */
129
+ private async startTmuxFocusTracking(): Promise<void> {
130
+ const pane = process.env.TMUX_PANE;
131
+ if (!pane) return;
132
+ this.tmuxPane = pane;
133
+ const file = tmuxStateFile(pane);
134
+ try {
135
+ await mkdir(TMUX_STATE_DIR, { recursive: true });
136
+ await writeFile(file, "1", "utf8");
137
+ await runTmux(["set-hook", "-p", "-t", pane, `pane-focus-in[${TMUX_HOOK_ID}]`, `run-shell -b "printf %s 1 > ${shellQuote(file)}"`]);
138
+ await runTmux(["set-hook", "-p", "-t", pane, `pane-focus-out[${TMUX_HOOK_ID}]`, `run-shell -b "printf %s 0 > ${shellQuote(file)}"`]);
139
+ this.tmuxFocusWatcher = watch(file, { persistent: false }, () => void this.readTmuxFocusState(file));
140
+ } catch {
141
+ // Tmux focus hooks are optional; retain hardware-only behavior.
142
+ }
143
+ }
144
+
145
+ private async readTmuxFocusState(file: string): Promise<void> {
146
+ try {
147
+ this.setTerminalFocus((await readFile(file, "utf8")).trim() !== "0");
148
+ } catch {
149
+ // Ignore transient reads while tmux updates the state file.
150
+ }
151
+ }
152
+
153
+ private setTerminalFocus(focused: boolean): void {
154
+ if (focused === this.terminalFocused) return;
155
+ this.terminalFocused = focused;
156
+ try {
157
+ this.tui.setShowHardwareCursor(focused);
158
+ } catch {
159
+ // Older pi-tui without hardware-cursor toggle; ignore.
160
+ }
161
+ this.tui.requestRender();
162
+ if (focused) {
163
+ // TUI may emit DECTCEM after the focus hook fires; reapply the Vim shape
164
+ // afterward so insert mode remains a bar instead of its default block.
165
+ const timer = setTimeout(() => this.applyCursorShapeForMode(this.vimState.mode), 25);
166
+ timer.unref?.();
167
+ }
168
+ }
169
+
170
+ dispose(): void {
171
+ try {
172
+ // The unfocused fallback turns Pi's hardware cursor off. Restore it before
173
+ // exiting, then request the terminal's default cursor state explicitly.
174
+ this.tui.setShowHardwareCursor(true);
175
+ this.tui.terminal.write("\x1b[?25h\x1b[0 q" + VimEditor.CURSOR_COLOR_RESET);
176
+ } catch {
177
+ // Best effort: the terminal may already be shutting down.
178
+ }
179
+ this.tmuxFocusWatcher?.close();
180
+ this.tmuxFocusWatcher = undefined;
181
+ const pane = this.tmuxPane;
182
+ this.tmuxPane = undefined;
183
+ if (!pane) return;
184
+ void Promise.all([
185
+ runTmux(["set-hook", "-up", "-t", pane, `pane-focus-in[${TMUX_HOOK_ID}]`]),
186
+ runTmux(["set-hook", "-up", "-t", pane, `pane-focus-out[${TMUX_HOOK_ID}]`]),
187
+ rm(tmuxStateFile(pane), { force: true }),
188
+ ]);
189
+ }
190
+
191
+ /**
192
+ * Wrap the autocomplete provider with fuzzy file matching for @ queries.
193
+ * This integrates pi-fzfp's weighted dual-key scoring into the vim editor.
194
+ */
195
+ override setAutocompleteProvider(provider: AutocompleteProvider): void {
196
+ super.setAutocompleteProvider(this.wrapAutocomplete ? this.wrapAutocomplete(provider) : provider);
197
+ }
198
+
199
+ /**
200
+ * Undo: snapshot current state to redo stack, then perform base editor undo.
201
+ * Works at the same level as the base editor's internal state.
202
+ */
203
+ vimUndo(): void {
204
+ const editor = this as any;
205
+ if (!editor.undoStack || editor.undoStack.length === 0) return;
206
+
207
+ // Save current internal state to redo stack before undoing
208
+ const state = editor.state;
209
+ this.redoStack.push(structuredClone(state));
210
+
211
+ // Perform base editor undo
212
+ editor.undo();
213
+ }
214
+
215
+ /**
216
+ * Redo: restore state from redo stack, push current state to undo stack.
217
+ * Mirrors the base editor's undo mechanism in reverse.
218
+ */
219
+ vimRedo(): void {
220
+ if (this.redoStack.length === 0) return;
221
+ const editor = this as any;
222
+ const snapshot = this.redoStack.pop()!;
223
+
224
+ // Push current state to undo stack
225
+ editor.undoStack.push(structuredClone(editor.state));
226
+
227
+ // Restore the redo snapshot directly into internal state
228
+ Object.assign(editor.state, snapshot);
229
+ editor.lastAction = null;
230
+ editor.preferredVisualCol = null;
231
+ if (editor.onChange) {
232
+ editor.onChange(this.getText());
233
+ }
234
+ }
235
+
236
+ handleInput(data: string): void {
237
+ const { vimState } = this;
238
+ const modeBefore = vimState.mode;
239
+ const textBefore = this.getText();
240
+ const redoStackBefore = this.redoStack.length;
241
+
242
+ switch (vimState.mode) {
243
+ case "insert":
244
+ this.handleInsert(data);
245
+ break;
246
+
247
+ case "replace":
248
+ this.handleReplace(data);
249
+ break;
250
+
251
+ case "normal":
252
+ this.handleNormal(data);
253
+ break;
254
+
255
+ case "visual":
256
+ case "visual-line":
257
+ this.handleVisual(data);
258
+ break;
259
+
260
+ case "command-line":
261
+ this.handleCommandLine(data);
262
+ break;
263
+
264
+ default:
265
+ // For unimplemented modes, pass through to super
266
+ super.handleInput(data);
267
+ break;
268
+ }
269
+
270
+ // Clear redo stack when text changes from a non-undo/redo action.
271
+ // If the redo stack changed size, it was an undo/redo operation — don't clear.
272
+ if (this.redoStack.length === redoStackBefore && this.getText() !== textBefore) {
273
+ this.redoStack.length = 0;
274
+ }
275
+
276
+ if (this.vimState.mode === "normal") {
277
+ const cursor = this.getCursor();
278
+ const line = this.getText().split("\n")[cursor.line] || "";
279
+ if (line.length > 0 && cursor.col >= line.length) {
280
+ const segments = [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(line)];
281
+ this.moveCursorTo(cursor.line, segments.at(-1)?.index ?? 0);
282
+ }
283
+ }
284
+
285
+ if (this.vimState.mode !== modeBefore) {
286
+ this.applyCursorShapeForMode(this.vimState.mode);
287
+ }
288
+ }
289
+
290
+ private handleInsert(data: string): void {
291
+ const ctx: InsertModeContext = {
292
+ state: this.vimState,
293
+ getCursor: () => this.getCursor(),
294
+ getText: () => this.getText(),
295
+ setText: (text) => this.setText(text),
296
+ moveCursorTo: (line, col) => this.moveCursorTo(line, col),
297
+ superHandleInput: (d) => super.handleInput(d),
298
+ };
299
+ handleInsertMode(data, ctx);
300
+ }
301
+
302
+ private handleReplace(data: string): void {
303
+ const ctx: ReplaceModeContext = {
304
+ state: this.vimState,
305
+ getCursor: () => this.getCursor(),
306
+ getText: () => this.getText(),
307
+ setText: (text) => this.setText(text),
308
+ moveCursorTo: (line, col) => this.moveCursorTo(line, col),
309
+ superHandleInput: (d) => super.handleInput(d),
310
+ };
311
+ handleReplaceMode(data, ctx);
312
+ }
313
+
314
+ private handleNormal(data: string): void {
315
+ // Escape in normal mode → pass to super (abort agent, etc.)
316
+ if (matchesKey(data, "escape")) {
317
+ super.handleInput(data);
318
+ return;
319
+ }
320
+
321
+ const ctx: NormalModeContext = {
322
+ state: this.vimState,
323
+ superHandleInput: (d) => super.handleInput(d),
324
+ getText: () => this.getText(),
325
+ getCursor: () => this.getCursor(),
326
+ setText: (text) => this.setText(text),
327
+ moveCursorTo: (line, col) => this.moveCursorTo(line, col),
328
+ undo: () => this.vimUndo(),
329
+ redo: () => this.vimRedo(),
330
+ };
331
+ handleNormalMode(data, ctx);
332
+ }
333
+
334
+ private handleCommandLine(data: string): void {
335
+ const state = getSearchState();
336
+ const returnMode = state.returnMode;
337
+ const result = handleSearchInput(data);
338
+
339
+ if (result === "confirm") {
340
+ // Execute the search and move cursor to the match
341
+ const lines = this.getText().split("\n");
342
+ const cursor = this.getCursor();
343
+ const motionResult = executeSearchMotion(lines, cursor);
344
+ this.moveCursorTo(motionResult.position.line, motionResult.position.col);
345
+ this.vimState.mode = returnMode;
346
+ } else if (result === "cancel") {
347
+ this.vimState.mode = "normal";
348
+ this.vimState.visualAnchor = null;
349
+ }
350
+ // "continue" → stay in command-line mode, render will show the prompt
351
+ }
352
+
353
+ private handleVisual(data: string): void {
354
+ const ctx: VisualModeContext = {
355
+ state: this.vimState,
356
+ superHandleInput: (d) => super.handleInput(d),
357
+ getText: () => this.getText(),
358
+ getCursor: () => this.getCursor(),
359
+ setText: (text) => this.setText(text),
360
+ moveCursorTo: (line, col) => this.moveCursorTo(line, col),
361
+ };
362
+ handleVisualMode(data, ctx);
363
+ }
364
+
365
+ /** Set a logical position without navigating through wrapped screen rows. */
366
+ moveCursorTo(targetLine: number, targetCol: number): void {
367
+ // Pi exposes the cursor getter but not a setter; redo uses the same state.
368
+ const editor = this as any;
369
+ const lines: string[] = editor.state.lines;
370
+ const line = Math.max(0, Math.min(targetLine, lines.length - 1));
371
+ editor.state.cursorLine = line;
372
+ editor.state.cursorCol = Math.max(0, Math.min(targetCol, (lines[line] || "").length));
373
+ editor.preferredVisualCol = null;
374
+ editor.snappedFromCursorCol = null;
375
+ }
376
+
377
+ /**
378
+ * Remove the software reverse-video cursor cell that the base editor draws,
379
+ * so the terminal hardware cursor is the only cursor in every Vim mode.
380
+ *
381
+ * The hardware cursor marker remains in place for IME/cursor positioning.
382
+ */
383
+ private stripSoftCursorHighlight(line: string): string {
384
+ const markerIndex = line.indexOf(CURSOR_MARKER);
385
+ if (markerIndex === -1) return line;
386
+
387
+ const markerEnd = markerIndex + CURSOR_MARKER.length;
388
+ const before = line.slice(0, markerEnd);
389
+ const after = line.slice(markerEnd);
390
+
391
+ // Base editor emits cursor as: \x1b[7m<grapheme>\x1b[0m immediately after marker.
392
+ const strippedAfter = after.replace(/^\x1b\[7m([\s\S]*?)\x1b\[0m/, "$1");
393
+ return before + strippedAfter;
394
+ }
395
+
396
+ render(width: number): string[] {
397
+ const lines = super.render(width);
398
+ if (lines.length === 0) return lines;
399
+
400
+ // Focused: terminal hardware cursor only. Unfocused: retain a software
401
+ // fallback because many terminals hide their hardware cursor entirely.
402
+ if (this.terminalFocused) {
403
+ for (let i = 0; i < lines.length; i++) {
404
+ lines[i] = this.stripSoftCursorHighlight(lines[i]!);
405
+ }
406
+ } else {
407
+ const style = this.cursorFallbackStyle(this.vimState.mode);
408
+ const fallback = `${style}$1\x1b[0m`; // dim, mode-colored underline
409
+ for (let i = 0; i < lines.length; i++) {
410
+ lines[i] = lines[i]!.replace(/\x1b\[7m([\s\S]*?)\x1b\[0m/g, fallback);
411
+ }
412
+ }
413
+
414
+ // Apply visual selection highlighting if in visual mode
415
+ // Also keep highlighting when in command-line mode initiated from visual
416
+ const isVisual = this.vimState.mode === "visual" || this.vimState.mode === "visual-line";
417
+ const isSearchFromVisual =
418
+ this.vimState.mode === "command-line" &&
419
+ (getSearchState().returnMode === "visual" || getSearchState().returnMode === "visual-line");
420
+ if ((isVisual || isSearchFromVisual) && this.vimState.visualAnchor) {
421
+ this.applyVisualHighlight(lines, width);
422
+ }
423
+
424
+ // Add mode indicator to the bottom border (right side)
425
+ const last = lines.length - 1;
426
+
427
+ if (this.vimState.mode === "command-line" && getSearchState().active) {
428
+ // Show search prompt on the bottom border
429
+ const prompt = getSearchPrompt();
430
+ const cursorChar = "█";
431
+ const promptWithCursor = ` ${prompt}${cursorChar} `;
432
+ if (visibleWidth(lines[last]!) >= promptWithCursor.length) {
433
+ lines[last] =
434
+ truncateToWidth(lines[last]!, width - promptWithCursor.length, "") +
435
+ promptWithCursor;
436
+ }
437
+ } else if (!this.config.disableModeIndicator) {
438
+ const modeName = modeDisplayName(this.vimState.mode);
439
+ const label = ` ${modeName} `;
440
+ if (visibleWidth(lines[last]!) >= label.length) {
441
+ lines[last] =
442
+ truncateToWidth(lines[last]!, width - label.length, "") + label;
443
+ }
444
+ }
445
+
446
+ return lines;
447
+ }
448
+
449
+ /**
450
+ * Apply reverse-video highlighting to the visual selection range in rendered output.
451
+ *
452
+ * The rendered output from super.render() is structured as:
453
+ * [top border, ...content lines (with padding), bottom border, ...autocomplete]
454
+ *
455
+ * Content lines have format: `${leftPadding}${displayText}${rightPadding}`
456
+ * where padding is `paddingX` spaces on each side (default 0).
457
+ * The editor also inserts CURSOR_MARKER (APC sequence) and cursor highlighting.
458
+ *
459
+ * We use pi-tui's extractAnsiCode to properly skip ALL escape sequences
460
+ * (CSI, OSC, APC) when counting visible positions.
461
+ */
462
+ private applyVisualHighlight(renderedLines: string[], width: number): void {
463
+ const text = this.getText();
464
+ const textLines = text.split("\n");
465
+ const cursor = this.getCursor();
466
+ const range = getVisualRange(this.vimState, cursor, textLines);
467
+
468
+ // The editor uses paddingX (default 0) for left/right content padding.
469
+ // With paddingX=0: contentWidth = width, layoutWidth = width - 1
470
+ // Content lines start at renderedLines[1] through renderedLines[length-2].
471
+ // The padding property is accessed via getPadding().
472
+ const paddingX = this.getPaddingX();
473
+ const contentWidth = Math.max(1, width - paddingX * 2);
474
+ const layoutWidth = Math.max(1, contentWidth - (paddingX ? 0 : 1));
475
+
476
+ // Map text line index → first rendered line index (1-based, after top border)
477
+ const textLineToRenderedStart: number[] = [];
478
+ let renderedIdx = 1; // skip top border
479
+ for (let i = 0; i < textLines.length; i++) {
480
+ textLineToRenderedStart.push(renderedIdx);
481
+ const lineLen = Math.max(1, visibleWidth(textLines[i] || ""));
482
+ const wrappedCount = Math.ceil(lineLen / layoutWidth);
483
+ renderedIdx += wrappedCount;
484
+ }
485
+
486
+ // Highlight the selected ranges
487
+ for (let textLine = range.start.line; textLine <= range.end.line; textLine++) {
488
+ const lineText = textLines[textLine] || "";
489
+ const renderedStart = textLineToRenderedStart[textLine];
490
+ if (renderedStart === undefined) continue;
491
+
492
+ let selStartCol: number;
493
+ let selEndCol: number;
494
+
495
+ if (range.linewise) {
496
+ selStartCol = 0;
497
+ selEndCol = lineText.length;
498
+ } else {
499
+ selStartCol = textLine === range.start.line ? range.start.col : 0;
500
+ selEndCol =
501
+ textLine === range.end.line ? range.end.col + 1 : lineText.length;
502
+ }
503
+
504
+ // Apply highlighting across wrapped lines
505
+ const lineLen = Math.max(1, lineText.length);
506
+ const wrappedCount = Math.ceil(lineLen / layoutWidth);
507
+
508
+ for (let wrap = 0; wrap < wrappedCount; wrap++) {
509
+ const rIdx = renderedStart + wrap;
510
+ if (rIdx >= renderedLines.length - 1) break; // don't touch bottom border
511
+
512
+ const wrapStartCol = wrap * layoutWidth;
513
+ const wrapEndCol = wrapStartCol + layoutWidth;
514
+
515
+ // Intersection of selection with this wrapped segment
516
+ const hlStart = Math.max(selStartCol, wrapStartCol) - wrapStartCol;
517
+ const hlEnd = Math.min(selEndCol, wrapEndCol) - wrapStartCol;
518
+
519
+ if (hlStart < hlEnd) {
520
+ // Offset by paddingX for left padding
521
+ renderedLines[rIdx] = highlightRenderedLine(
522
+ renderedLines[rIdx]!,
523
+ hlStart + paddingX,
524
+ hlEnd + paddingX,
525
+ );
526
+ }
527
+ }
528
+ }
529
+ }
530
+ }
531
+
532
+ /**
533
+ * Detect an escape sequence at position `pos` in `str`.
534
+ * Returns the length of the escape sequence, or 0 if none found.
535
+ *
536
+ * Handles:
537
+ * - CSI sequences: \x1b[ ... m/G/K/H/J
538
+ * - OSC sequences: \x1b] ... BEL or \x1b] ... ST(\x1b\\)
539
+ * - APC sequences: \x1b_ ... BEL or \x1b_ ... ST(\x1b\\)
540
+ */
541
+ function escapeSeqLength(str: string, pos: number): number {
542
+ if (pos >= str.length || str[pos] !== "\x1b") return 0;
543
+ const next = str[pos + 1];
544
+
545
+ // CSI: \x1b[ ... terminator
546
+ if (next === "[") {
547
+ let j = pos + 2;
548
+ while (j < str.length && !/[mGKHJ]/.test(str[j]!)) j++;
549
+ if (j < str.length) return j + 1 - pos;
550
+ return 0;
551
+ }
552
+
553
+ // OSC: \x1b] ... BEL or ST
554
+ if (next === "]") {
555
+ let j = pos + 2;
556
+ while (j < str.length) {
557
+ if (str[j] === "\x07") return j + 1 - pos;
558
+ if (str[j] === "\x1b" && str[j + 1] === "\\") return j + 2 - pos;
559
+ j++;
560
+ }
561
+ return 0;
562
+ }
563
+
564
+ // APC: \x1b_ ... BEL or ST
565
+ if (next === "_") {
566
+ let j = pos + 2;
567
+ while (j < str.length) {
568
+ if (str[j] === "\x07") return j + 1 - pos;
569
+ if (str[j] === "\x1b" && str[j + 1] === "\\") return j + 2 - pos;
570
+ j++;
571
+ }
572
+ return 0;
573
+ }
574
+
575
+ return 0;
576
+ }
577
+
578
+ /**
579
+ * Insert reverse-video ANSI codes into a rendered line at specific visible column positions.
580
+ * Properly handles CSI, OSC, and APC escape sequences (including CURSOR_MARKER).
581
+ *
582
+ * When the cursor falls inside the highlighted range, the editor's cursor rendering
583
+ * inserts `\x1b[0m` (full reset) after the cursor character, which would kill the
584
+ * reverse video for the rest of the selection. We detect this and re-inject `\x1b[7m`
585
+ * after any SGR reset that falls within the highlighted range.
586
+ *
587
+ * `startVisCol` and `endVisCol` are 0-indexed visible column positions to highlight.
588
+ */
589
+ function highlightRenderedLine(
590
+ line: string,
591
+ startVisCol: number,
592
+ endVisCol: number,
593
+ ): string {
594
+ let result = "";
595
+ let visCol = 0;
596
+ let i = 0;
597
+ let started = false;
598
+ let ended = false;
599
+
600
+ while (i < line.length) {
601
+ // Check for any escape sequence (CSI, OSC, APC)
602
+ const seqLen = escapeSeqLength(line, i);
603
+ if (seqLen > 0) {
604
+ // Insert highlight markers before this escape sequence if needed
605
+ if (!started && visCol >= startVisCol) {
606
+ result += "\x1b[7m";
607
+ started = true;
608
+ }
609
+ if (started && !ended && visCol >= endVisCol) {
610
+ result += "\x1b[27m";
611
+ ended = true;
612
+ }
613
+
614
+ const seq = line.substring(i, i + seqLen);
615
+ result += seq;
616
+
617
+ // If we're inside the highlight range and this is a SGR reset (\x1b[0m),
618
+ // re-inject reverse video to keep the selection highlighted.
619
+ // The editor's cursor rendering uses \x1b[0m after the cursor character,
620
+ // which would otherwise kill our reverse video.
621
+ if (started && !ended && isResetSequence(seq)) {
622
+ result += "\x1b[7m";
623
+ }
624
+
625
+ i += seqLen;
626
+ continue;
627
+ }
628
+
629
+ // Insert highlight markers at the right visible positions
630
+ if (!started && visCol === startVisCol) {
631
+ result += "\x1b[7m";
632
+ started = true;
633
+ }
634
+ if (started && !ended && visCol === endVisCol) {
635
+ result += "\x1b[27m";
636
+ ended = true;
637
+ }
638
+
639
+ result += line[i];
640
+ // Only count printable characters as visible
641
+ const code = line.charCodeAt(i);
642
+ if (code >= 0x20) {
643
+ visCol++;
644
+ }
645
+ i++;
646
+ }
647
+
648
+ // Close highlight if we reached end of line before endVisCol
649
+ if (started && !ended) {
650
+ result += "\x1b[27m";
651
+ }
652
+
653
+ return result;
654
+ }
655
+
656
+ /**
657
+ * Check if an ANSI sequence is an SGR reset that would clear reverse video.
658
+ * Matches \x1b[0m and \x1b[m (both are full SGR resets).
659
+ */
660
+ function isResetSequence(seq: string): boolean {
661
+ return seq === "\x1b[0m" || seq === "\x1b[m";
662
+ }