@linxiraos/pi-tui 1.4.4 → 1.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +29 -27
  2. package/dist/types/app-keybindings.d.ts +5 -0
  3. package/dist/types/chrome/context-map.d.ts +15 -0
  4. package/dist/types/chrome/context-presentation.d.ts +48 -0
  5. package/dist/types/chrome/context-view-model.d.ts +77 -0
  6. package/dist/types/components/image.d.ts +20 -0
  7. package/dist/types/components/loader.d.ts +1 -1
  8. package/dist/types/native/blobs.d.ts +9 -0
  9. package/dist/types/overlays/advisor-config.d.ts +6 -0
  10. package/dist/types/overlays/agent-hub-projection.d.ts +3 -1
  11. package/dist/types/overlays/ask-dialog.d.ts +12 -3
  12. package/dist/types/overlays/btw-history-panel.d.ts +16 -2
  13. package/dist/types/overlays/btw-history.d.ts +7 -0
  14. package/dist/types/overlays/btw-panel.d.ts +2 -0
  15. package/dist/types/overlays/context-viewer-format.d.ts +42 -0
  16. package/dist/types/overlays/context-viewer-overview.d.ts +70 -0
  17. package/dist/types/overlays/context-viewer.d.ts +25 -0
  18. package/dist/types/overlays/hook-input.d.ts +1 -0
  19. package/dist/types/overlays/mcp-add-wizard.d.ts +2 -0
  20. package/dist/types/overlays/pause-screen.d.ts +13 -3
  21. package/dist/types/overlays/running-subagent-badge.d.ts +7 -1
  22. package/dist/types/prompt/macos-spelling.d.ts +2 -2
  23. package/dist/types/render/hyperlink.d.ts +15 -2
  24. package/dist/types/render/output-pane.d.ts +1 -1
  25. package/dist/types/render/render-utils.d.ts +7 -1
  26. package/dist/types/status-line/component.d.ts +2 -2
  27. package/dist/types/status-line/context-usage.d.ts +15 -30
  28. package/dist/types/terminal-capabilities.d.ts +7 -0
  29. package/dist/types/theme/symbols.d.ts +1 -1
  30. package/dist/types/tools/ask.d.ts +4 -0
  31. package/dist/types/tools/edit.d.ts +3 -1
  32. package/dist/types/tools/fetch.d.ts +1 -0
  33. package/dist/types/tools/github.d.ts +3 -0
  34. package/dist/types/tools/grouped-file-output.d.ts +2 -0
  35. package/dist/types/tools/mcp.d.ts +3 -3
  36. package/dist/types/tools/read.d.ts +3 -0
  37. package/dist/types/tools/wait.d.ts +16 -2
  38. package/dist/types/tui.d.ts +2 -0
  39. package/dist/types/vim.d.ts +39 -0
  40. package/package.json +9 -9
  41. package/src/app-keybindings.d.ts +5 -0
  42. package/src/app-keybindings.ts +5 -0
  43. package/src/chat/bash-execution.ts +7 -1
  44. package/src/chat/read-tool-group.ts +1 -2
  45. package/src/chat/skill-message.ts +2 -6
  46. package/src/chrome/context-map.ts +62 -0
  47. package/src/chrome/context-presentation.ts +26 -0
  48. package/src/chrome/context-view-model.ts +73 -0
  49. package/src/chrome/transcript-container.ts +89 -59
  50. package/src/components/editor.ts +455 -13
  51. package/src/components/image.d.ts +20 -0
  52. package/src/components/image.ts +83 -18
  53. package/src/components/loader.d.ts +1 -1
  54. package/src/components/loader.ts +1 -1
  55. package/src/components/markdown.ts +109 -7
  56. package/src/hotkeys-markdown.ts +1 -0
  57. package/src/native/blobs.d.ts +9 -0
  58. package/src/native/blobs.ts +3 -2
  59. package/src/overlays/advisor-config.ts +9 -2
  60. package/src/overlays/agent-hub-projection.d.ts +3 -1
  61. package/src/overlays/agent-hub-projection.ts +6 -5
  62. package/src/overlays/agent-hub.ts +51 -42
  63. package/src/overlays/ask-dialog.ts +125 -35
  64. package/src/overlays/btw-history-panel.ts +124 -12
  65. package/src/overlays/btw-history.ts +11 -0
  66. package/src/overlays/btw-panel.ts +8 -4
  67. package/src/overlays/context-viewer-format.ts +145 -0
  68. package/src/overlays/context-viewer-overview.ts +381 -0
  69. package/src/overlays/context-viewer.ts +728 -0
  70. package/src/overlays/hook-input.ts +2 -0
  71. package/src/overlays/mcp-add-wizard.ts +5 -0
  72. package/src/overlays/pause-screen.ts +166 -33
  73. package/src/overlays/running-subagent-badge.ts +12 -1
  74. package/src/overlays/settings-defs.ts +1 -0
  75. package/src/overlays/usage-dashboard.ts +15 -2
  76. package/src/prompt/macos-spelling.ts +24 -15
  77. package/src/render/hyperlink.d.ts +15 -2
  78. package/src/render/hyperlink.ts +41 -18
  79. package/src/render/output-pane.d.ts +1 -1
  80. package/src/render/output-pane.ts +60 -17
  81. package/src/render/render-utils.d.ts +7 -1
  82. package/src/render/render-utils.ts +11 -2
  83. package/src/setup/scenes/sign-in.ts +6 -0
  84. package/src/status-line/component.ts +6 -4
  85. package/src/status-line/context-usage.ts +56 -582
  86. package/src/terminal-capabilities.d.ts +7 -0
  87. package/src/terminal-capabilities.ts +10 -0
  88. package/src/theme/symbols.d.ts +1 -1
  89. package/src/theme/symbols.ts +16 -0
  90. package/src/tools/ask.d.ts +4 -0
  91. package/src/tools/ask.ts +4 -0
  92. package/src/tools/ast-grep.ts +3 -2
  93. package/src/tools/bash.ts +5 -23
  94. package/src/tools/edit.d.ts +3 -1
  95. package/src/tools/edit.ts +8 -4
  96. package/src/tools/fetch.d.ts +1 -0
  97. package/src/tools/fetch.ts +1 -0
  98. package/src/tools/find.ts +3 -10
  99. package/src/tools/github.d.ts +3 -0
  100. package/src/tools/github.ts +23 -3
  101. package/src/tools/glob.ts +4 -3
  102. package/src/tools/grep.ts +3 -4
  103. package/src/tools/grouped-file-output.d.ts +2 -0
  104. package/src/tools/grouped-file-output.ts +8 -2
  105. package/src/tools/mcp.d.ts +3 -3
  106. package/src/tools/mcp.ts +27 -9
  107. package/src/tools/native-view.ts +2 -2
  108. package/src/tools/read.d.ts +3 -0
  109. package/src/tools/read.ts +3 -1
  110. package/src/tools/vibe.ts +14 -3
  111. package/src/tools/wait.d.ts +16 -2
  112. package/src/tools/wait.ts +16 -2
  113. package/src/tui.d.ts +2 -0
  114. package/src/tui.ts +59 -19
  115. package/src/vim.d.ts +39 -0
  116. package/src/vim.ts +313 -22
@@ -42,9 +42,16 @@ import {
42
42
  visibleWidth,
43
43
  } from "../utils";
44
44
  import {
45
+ countGraphemes,
46
+ diffInsertSession,
47
+ flatten,
45
48
  lastGraphemeStart,
46
49
  nextGraphemeStart,
50
+ offsetToPos,
51
+ prevGraphemeStart,
52
+ stepGraphemes,
47
53
  type VimCommand,
54
+ type VimInsertRecord,
48
55
  type VimMode,
49
56
  type VimPosition,
50
57
  VimState,
@@ -460,6 +467,154 @@ const DEFAULT_PAGE_SCROLL_LINES = 10;
460
467
 
461
468
  const MAX_UNDO_STACK = 100;
462
469
 
470
+ /** Undo-stack position to fold later snapshots back to; `shifts` tracks MAX_UNDO_STACK eviction. */
471
+ interface UndoMark {
472
+ depth: number;
473
+ shifts: number;
474
+ }
475
+
476
+ /**
477
+ * Tracked Insert/Replace session: `[0, leftEnd)` is surviving pre-session text on the left and
478
+ * `[rightStart, len)` on the right (flat-buffer offsets), so the gap is what the session typed.
479
+ * `delBefore`/`delAfter` count pre-session graphemes deleted around the anchor — tracked
480
+ * incrementally because a final-text diff cannot see a delete that was retyped identically.
481
+ */
482
+ interface VimSessionState {
483
+ mark: UndoMark;
484
+ replace: boolean;
485
+ /** Flat text at segment start (diff fallback and arrowed-split baseline). */
486
+ text: string;
487
+ /** Flat cursor at segment start. */
488
+ cursor: number;
489
+ arrowed: boolean;
490
+ leftEnd: number;
491
+ rightStart: number;
492
+ delBefore: number;
493
+ delAfter: number;
494
+ /** False after an edit path we cannot classify (native host edits); falls back to a final diff. */
495
+ tracked: boolean;
496
+ }
497
+
498
+ /** Length of `lines.join("\n")` without building it. */
499
+ function flatLength(lines: readonly string[]): number {
500
+ let length = lines.length - 1;
501
+ for (const line of lines) length += line.length;
502
+ return length;
503
+ }
504
+
505
+ /** `lines.join("\n").slice(start, end)` without joining the whole buffer. */
506
+ function sliceFlat(lines: readonly string[], start: number, end: number): string {
507
+ let out = "";
508
+ let offset = 0;
509
+ for (let i = 0; i < lines.length && offset < end; i++) {
510
+ const line = lines[i]!;
511
+ const lineEnd = offset + line.length;
512
+ if (lineEnd >= start) {
513
+ out += line.slice(Math.max(0, start - offset), end - offset);
514
+ if (i < lines.length - 1 && lineEnd < end) out += "\n";
515
+ }
516
+ offset = lineEnd + 1;
517
+ }
518
+ return out;
519
+ }
520
+
521
+ /**
522
+ * Common prefix and non-overlapping common suffix of `before.join("\n")` and `after.join("\n")` —
523
+ * the split a flat char scan gives — without joining either buffer. Lines an edit left alone keep
524
+ * their string identity, so they are skipped whole and a keystroke costs O(lines), not O(chars).
525
+ */
526
+ function diffFlatLines(
527
+ before: readonly string[],
528
+ after: readonly string[],
529
+ beforeLength: number,
530
+ afterLength: number,
531
+ ): { prefix: number; suffix: number } {
532
+ const prefixMax = Math.min(beforeLength, afterLength);
533
+ let prefix = 0;
534
+ let bl = 0;
535
+ let bc = 0;
536
+ let al = 0;
537
+ let ac = 0;
538
+ // `prefix < prefixMax` guarantees both sides still have a character; past a line's end it is "\n".
539
+ while (prefix < prefixMax) {
540
+ const bLine = before[bl]!;
541
+ const aLine = after[al]!;
542
+ if (
543
+ bc === 0 &&
544
+ ac === 0 &&
545
+ bl < before.length - 1 &&
546
+ al < after.length - 1 &&
547
+ prefix + bLine.length + 1 <= prefixMax &&
548
+ bLine === aLine
549
+ ) {
550
+ prefix += bLine.length + 1;
551
+ bl++;
552
+ al++;
553
+ continue;
554
+ }
555
+ const b = bc < bLine.length ? bLine.charCodeAt(bc) : 10;
556
+ const a = ac < aLine.length ? aLine.charCodeAt(ac) : 10;
557
+ if (a !== b) break;
558
+ prefix++;
559
+ if (bc < bLine.length) {
560
+ bc++;
561
+ } else {
562
+ bl++;
563
+ bc = 0;
564
+ }
565
+ if (ac < aLine.length) {
566
+ ac++;
567
+ } else {
568
+ al++;
569
+ ac = 0;
570
+ }
571
+ }
572
+
573
+ const suffixMax = Math.min(beforeLength - prefix, afterLength - prefix);
574
+ let suffix = 0;
575
+ bl = before.length - 1;
576
+ al = after.length - 1;
577
+ bc = before[bl]!.length;
578
+ ac = after[al]!.length;
579
+ // Positions sit just past the next character to compare; before a line's start it is "\n".
580
+ while (suffix < suffixMax) {
581
+ const bLine = before[bl]!;
582
+ const aLine = after[al]!;
583
+ if (
584
+ bc === bLine.length &&
585
+ ac === aLine.length &&
586
+ bl > 0 &&
587
+ al > 0 &&
588
+ suffix + bLine.length + 1 <= suffixMax &&
589
+ bLine === aLine
590
+ ) {
591
+ suffix += bLine.length + 1;
592
+ bl--;
593
+ al--;
594
+ bc = before[bl]!.length;
595
+ ac = after[al]!.length;
596
+ continue;
597
+ }
598
+ const b = bc > 0 ? bLine.charCodeAt(bc - 1) : 10;
599
+ const a = ac > 0 ? aLine.charCodeAt(ac - 1) : 10;
600
+ if (a !== b) break;
601
+ suffix++;
602
+ if (bc > 0) {
603
+ bc--;
604
+ } else {
605
+ bl--;
606
+ bc = before[bl]!.length;
607
+ }
608
+ if (ac > 0) {
609
+ ac--;
610
+ } else {
611
+ al--;
612
+ ac = after[al]!.length;
613
+ }
614
+ }
615
+ return { prefix, suffix };
616
+ }
617
+
463
618
  /**
464
619
  * Typed characters that replace the provisional space a Tab word accept adds, so
465
620
  * they attach to the accepted word: closing punctuation, and `-` for compounds
@@ -676,6 +831,8 @@ export class Editor implements Component, Focusable {
676
831
  #lastAction: "kill" | "yank" | "type-word" | "accept-word" | "replace" | null = null;
677
832
  /** Graphemes overwritten in the current `R` session, so Backspace can restore them. */
678
833
  #replaceLog: { line: number; col: number; removed: string; text: string }[] = [];
834
+ /** Insert/Replace session a Vim command opened; Escape hands its text to `.` and folds its undo steps into one. */
835
+ #vimSession: VimSessionState | null = null;
679
836
 
680
837
  // Character jump mode
681
838
  #jumpMode: "forward" | "backward" | null = null;
@@ -748,6 +905,13 @@ export class Editor implements Component, Focusable {
748
905
  // Undo stack for editor state changes
749
906
  #undoStack: EditorState[] = [];
750
907
  #suspendUndo = false;
908
+ /** Snapshots evicted from the front of {@link #undoStack}, so {@link UndoMark}s stay aligned. */
909
+ #undoShifts = 0;
910
+ /**
911
+ * Undo mark whose first snapshot `u` must still reach: the open Insert/Replace segment, or the
912
+ * Normal-mode key being applied (so a counted `.` stays one undo step past the stack cap).
913
+ */
914
+ #pinnedUndo: UndoMark | null = null;
751
915
 
752
916
  onSubmit?: (text: string) => void | Promise<void>;
753
917
  onAltEnter?: (text: string) => void;
@@ -917,8 +1081,15 @@ export class Editor implements Component, Focusable {
917
1081
  * never left in a state where ordinary typing does nothing. */
918
1082
  setVimMode(enabled: boolean): void {
919
1083
  if (enabled === (this.#vim !== null)) return;
1084
+ this.#vimSession = null;
1085
+ this.#pinnedUndo = null;
920
1086
  this.#vim = enabled ? new VimState() : null;
921
- if (this.#vim) this.#vim.mode = "insert";
1087
+ if (this.#vim) {
1088
+ this.#vim.mode = "insert";
1089
+ const mark = this.#undoMark();
1090
+ this.#pinnedUndo = mark;
1091
+ this.#startVimSession(mark, false);
1092
+ }
922
1093
  this.invalidate();
923
1094
  }
924
1095
 
@@ -1096,6 +1267,7 @@ export class Editor implements Component, Focusable {
1096
1267
  }
1097
1268
  /** Internal setText that doesn't reset history state - used by navigateHistory */
1098
1269
  #setTextInternal(text: string, cursorAnchor: HistoryCursorAnchor = "end"): void {
1270
+ this.#endVimSession();
1099
1271
  this.#undoStack.length = 0;
1100
1272
  const lines = sanitizeLoadedText(text).split("\n");
1101
1273
  this.#state.lines = lines.length === 0 ? [""] : lines;
@@ -1112,6 +1284,11 @@ export class Editor implements Component, Focusable {
1112
1284
  this.#state.cursorLine = this.#state.lines.length - 1;
1113
1285
  this.#setCursorCol(this.#state.lines[this.#state.cursorLine]?.length || 0);
1114
1286
  }
1287
+ if (this.#vim !== null && (this.#vim.mode === "insert" || this.#vim.mode === "replace")) {
1288
+ const mark = this.#undoMark();
1289
+ this.#pinnedUndo = mark;
1290
+ this.#startVimSession(mark, this.#vim.mode === "replace");
1291
+ }
1115
1292
  this.#notifyChange();
1116
1293
  }
1117
1294
 
@@ -1783,8 +1960,62 @@ export class Editor implements Component, Focusable {
1783
1960
  // so a fragmented paste stream can never grow the call stack.
1784
1961
  let next: string | undefined = data;
1785
1962
  while (next !== undefined && next.length > 0) {
1963
+ const session = this.#vimSession;
1964
+ const revision = this.#textRevision;
1965
+ const line = this.#state.cursorLine;
1966
+ const col = this.#state.cursorCol;
1967
+ // A line-array copy is pointer-sized per line; the edit diff below skips unchanged lines whole.
1968
+ const linesBefore =
1969
+ session !== null && session.tracked && !session.replace ? this.#state.lines.slice() : undefined;
1786
1970
  next = this.#handleInputChunk(next);
1971
+ // A bare cursor move inside one Insert/Replace session splits it, like Vim's arrow keys.
1972
+ if (
1973
+ session !== null &&
1974
+ session === this.#vimSession &&
1975
+ this.#textRevision === revision &&
1976
+ (line !== this.#state.cursorLine || col !== this.#state.cursorCol)
1977
+ ) {
1978
+ this.#breakVimSession();
1979
+ } else if (
1980
+ session !== null &&
1981
+ session === this.#vimSession &&
1982
+ session.tracked &&
1983
+ !session.replace &&
1984
+ linesBefore !== undefined &&
1985
+ this.#textRevision !== revision
1986
+ ) {
1987
+ this.#trackVimSessionEdit(session, linesBefore);
1988
+ }
1989
+ }
1990
+ }
1991
+
1992
+ /**
1993
+ * Fold one chunk's buffer change into the session window. Counting original deletions here keeps
1994
+ * `deleteBefore`/`deleteAfter` exact even when typed text coincides with what was deleted
1995
+ * (Backspace then retyping the same grapheme), which a final-text diff cannot recover.
1996
+ */
1997
+ #trackVimSessionEdit(session: VimSessionState, linesBefore: readonly string[]): void {
1998
+ const linesAfter = this.#state.lines;
1999
+ const beforeLength = flatLength(linesBefore);
2000
+ const afterLength = flatLength(linesAfter);
2001
+ const { prefix: p, suffix: q } = diffFlatLines(linesBefore, linesAfter, beforeLength, afterLength);
2002
+ const removedEnd = beforeLength - q;
2003
+ const insLen = afterLength - p - q;
2004
+ const leftCut = Math.max(0, Math.min(removedEnd, session.leftEnd) - p);
2005
+ const rightCut = Math.max(0, removedEnd - Math.max(p, session.rightStart));
2006
+ const typedCut = removedEnd - p - leftCut - rightCut;
2007
+ if (insLen > 0 && p < session.leftEnd - leftCut) {
2008
+ // Insertion inside surviving original text can't be told apart from typed text; the
2009
+ // finalize diff still produces a bounded record.
2010
+ session.tracked = false;
2011
+ return;
2012
+ }
2013
+ if (leftCut > 0) session.delBefore += countGraphemes(sliceFlat(linesBefore, p, p + leftCut));
2014
+ if (rightCut > 0) {
2015
+ session.delAfter += countGraphemes(sliceFlat(linesBefore, removedEnd - rightCut, removedEnd));
1787
2016
  }
2017
+ session.leftEnd -= leftCut;
2018
+ session.rightStart = session.rightStart - leftCut - typedCut + insLen;
1788
2019
  }
1789
2020
 
1790
2021
  /** Process one input chunk. Returns the unconsumed tail of a completed paste, if any. */
@@ -2205,10 +2436,12 @@ export class Editor implements Component, Focusable {
2205
2436
  // Word left
2206
2437
  this.#resetKillSequence();
2207
2438
  this.#moveWordBackwards();
2439
+ this.#dismissAutocomplete();
2208
2440
  } else if (kb.matchesCanonical(canonical, "tui.editor.cursorWordRight")) {
2209
2441
  // Word right
2210
2442
  this.#resetKillSequence();
2211
2443
  this.#moveWordForwards();
2444
+ this.#dismissAutocomplete();
2212
2445
  }
2213
2446
  // Arrow keys
2214
2447
  else if (kb.matchesCanonical(canonical, "tui.editor.cursorUp")) {
@@ -2326,9 +2559,31 @@ export class Editor implements Component, Focusable {
2326
2559
  const before = vim.mode;
2327
2560
  const pendingBefore = vim.pendingText;
2328
2561
  const selectedLinesBefore = this.vimSelectedLines;
2562
+ const mark = this.#undoMark();
2563
+ const pinHere = this.#vimSession === null;
2564
+ if (pinHere) this.#pinnedUndo = mark;
2565
+ const revisionBefore = this.#textRevision;
2329
2566
  const commands = vim.handleKey(key, this.#state);
2330
- if (commands === null) return false;
2567
+ if (commands === null) {
2568
+ if (pinHere) this.#pinnedUndo = null;
2569
+ return false;
2570
+ }
2571
+ const editing = (mode: VimMode) => mode === "insert" || mode === "replace";
2572
+ // Before applying: Escape's commands would otherwise clear the replace log this reads.
2573
+ if (editing(before) && !editing(vim.mode)) this.#endVimSession();
2331
2574
  this.#applyVimCommands(commands);
2575
+ if (this.#textRevision !== revisionBefore) {
2576
+ vim.commitChange();
2577
+ } else {
2578
+ vim.discardChange();
2579
+ }
2580
+ // The session baseline follows `cw`'s delete or `o`'s new line, but its undo mark precedes them,
2581
+ // so one `u` restores the whole change. Every other key (`.` too) is a single undo step.
2582
+ if (!editing(before) && editing(vim.mode)) this.#startVimSession(mark, vim.mode === "replace");
2583
+ else if (this.#vimSession === null) {
2584
+ this.#collapseUndoSince(mark);
2585
+ this.#pinnedUndo = null;
2586
+ }
2332
2587
  // Pending and selection size are mode chrome too: hosts echo `2d` and the Visual line count
2333
2588
  // beside the mode name, and extending a selection changes neither the mode nor the pending
2334
2589
  // command — so all three have to be compared or the indicator goes stale mid-selection.
@@ -2340,6 +2595,89 @@ export class Editor implements Component, Focusable {
2340
2595
  return true;
2341
2596
  }
2342
2597
 
2598
+ #undoMark(): UndoMark {
2599
+ return { depth: this.#undoStack.length, shifts: this.#undoShifts };
2600
+ }
2601
+
2602
+ /** Keep only the first snapshot pushed since `mark`, folding everything after it into one undo step. */
2603
+ #collapseUndoSince(mark: UndoMark): void {
2604
+ const keep = Math.max(0, mark.depth - (this.#undoShifts - mark.shifts)) + 1;
2605
+ if (this.#undoStack.length > keep) this.#undoStack.length = keep;
2606
+ }
2607
+
2608
+ #startVimSession(mark: UndoMark, replace: boolean): void {
2609
+ // A stale "type-word" would coalesce the session's first keystroke into the pre-session
2610
+ // undo step, so `u` would swallow text the session never touched.
2611
+ this.#resetKillSequence();
2612
+ const { text, cursor } = flatten(this.#state);
2613
+ this.#vimSession = {
2614
+ mark,
2615
+ replace,
2616
+ text,
2617
+ cursor,
2618
+ arrowed: false,
2619
+ leftEnd: cursor,
2620
+ rightStart: cursor,
2621
+ delBefore: 0,
2622
+ delAfter: 0,
2623
+ tracked: true,
2624
+ };
2625
+ }
2626
+
2627
+ /** Hand the current session segment's text to `.` and fold its undo steps. */
2628
+ #finalizeVimSegment(): void {
2629
+ const session = this.#vimSession;
2630
+ const vim = this.#vim;
2631
+ if (session === null || vim === null) return;
2632
+ const record: VimInsertRecord = session.replace
2633
+ ? { deleteBefore: 0, deleteAfter: 0, text: this.#replaceLog.map(entry => entry.text).join("") }
2634
+ : session.tracked
2635
+ ? {
2636
+ deleteBefore: session.delBefore,
2637
+ deleteAfter: session.delAfter,
2638
+ text: this.#state.lines.join("\n").slice(session.leftEnd, session.rightStart),
2639
+ }
2640
+ : diffInsertSession(session.text, session.cursor, this.#state.lines.join("\n"));
2641
+ if (!session.arrowed) vim.recordInsert(record, false);
2642
+ // An empty segment after an arrow keeps the earlier change, as Vim does.
2643
+ else if (record.text !== "" || record.deleteBefore > 0 || record.deleteAfter > 0) vim.recordInsert(record, true);
2644
+ this.#collapseUndoSince(session.mark);
2645
+ }
2646
+
2647
+ #endVimSession(): void {
2648
+ this.#finalizeVimSegment();
2649
+ this.#vimSession = null;
2650
+ this.#pinnedUndo = null;
2651
+ // A spent log would otherwise leak into the next Replace session's record.
2652
+ this.#replaceLog.length = 0;
2653
+ }
2654
+
2655
+ /** An arrow key inside Insert/Replace: close the segment and start a fresh one at the new cursor. */
2656
+ #breakVimSession(): void {
2657
+ const session = this.#vimSession;
2658
+ if (session === null) return;
2659
+ this.#finalizeVimSegment();
2660
+ this.#resetKillSequence();
2661
+ // Replace-mode Backspace cannot restore across a cursor move, and old overwrites must not leak
2662
+ // into the next segment's record.
2663
+ this.#replaceLog.length = 0;
2664
+ const { text, cursor } = flatten(this.#state);
2665
+ const mark = this.#undoMark();
2666
+ this.#vimSession = {
2667
+ ...session,
2668
+ mark,
2669
+ text,
2670
+ cursor,
2671
+ arrowed: true,
2672
+ leftEnd: cursor,
2673
+ rightStart: cursor,
2674
+ delBefore: 0,
2675
+ delAfter: 0,
2676
+ tracked: true,
2677
+ };
2678
+ this.#pinnedUndo = mark;
2679
+ }
2680
+
2343
2681
  #applyVimCommands(commands: readonly VimCommand[]): void {
2344
2682
  for (const command of commands) {
2345
2683
  // A delete or other edit in replace mode invalidates Backspace restores. Motions do not.
@@ -2391,6 +2729,9 @@ export class Editor implements Component, Focusable {
2391
2729
  case "indent":
2392
2730
  this.#indentVimLines(command.fromLine, command.toLine, command.out);
2393
2731
  break;
2732
+ case "retype":
2733
+ this.#retypeVimInsert(command);
2734
+ break;
2394
2735
  }
2395
2736
  }
2396
2737
  this.#clampVimCursor();
@@ -2419,7 +2760,7 @@ export class Editor implements Component, Focusable {
2419
2760
  // makes the logged columns meaningless; start a fresh undo step and a fresh log.
2420
2761
  if (this.#lastAction !== "replace") {
2421
2762
  this.#recordUndoState();
2422
- this.#replaceLog.length = 0;
2763
+ if (!this.#vimSession?.replace) this.#replaceLog.length = 0;
2423
2764
  }
2424
2765
  this.#lastAction = "replace";
2425
2766
  // Editing a recalled prompt makes it a draft, so Up/Down at an edge move the cursor again
@@ -2557,6 +2898,23 @@ export class Editor implements Component, Focusable {
2557
2898
 
2558
2899
  // A range that cuts through an atomic placeholder (`[Image #1, 800x600]`) swallows the whole
2559
2900
  // token instead of leaving a corrupt fragment — the same rule backspace follows.
2901
+ const { start, end } = this.#expandVimRange(from, to);
2902
+
2903
+ const removed = this.#sliceRange(start, end, false);
2904
+ if (!removed) return;
2905
+ this.#recordUndoState();
2906
+ this.#killRing.push(removed, { prepend: false });
2907
+ const head = (lines[start.line] ?? "").slice(0, start.col);
2908
+ const tail = (lines[Math.min(end.line, lines.length - 1)] ?? "").slice(end.col);
2909
+ lines.splice(start.line, Math.min(end.line, lines.length - 1) - start.line + 1, head + tail);
2910
+ this.#state.cursorLine = start.line;
2911
+ this.#setCursorCol(start.col);
2912
+ this.#afterVimEdit();
2913
+ }
2914
+
2915
+ /** Widen a charwise range so it never cuts through an atomic placeholder token. */
2916
+ #expandVimRange(from: VimPosition, to: VimPosition): { start: VimPosition; end: VimPosition } {
2917
+ const lines = this.#state.lines;
2560
2918
  let start = from;
2561
2919
  let end = to;
2562
2920
  if (start.line === end.line) {
@@ -2574,16 +2932,54 @@ export class Editor implements Component, Focusable {
2574
2932
  if (endToken !== undefined && endToken.end > end.col) end = { line: end.line, col: endToken.end };
2575
2933
  }
2576
2934
  }
2935
+ return { start, end };
2936
+ }
2577
2937
 
2578
- const removed = this.#sliceRange(start, end, false);
2579
- if (!removed) return;
2938
+ /** `.` after an Insert/Replace session: type its text again, `times` copies, then Escape's step back. */
2939
+ #retypeVimInsert(command: Extract<VimCommand, { kind: "retype" }>): void {
2940
+ for (let n = 0; n < command.times; n++) {
2941
+ // `3.` after `ofoo`: one new line per copy, stacking downward (Vim's `3Ofoo` does too).
2942
+ if (n > 0 && command.newline) this.#openVimLine(true);
2943
+ if (command.overwrite) {
2944
+ for (const seg of segmenter.segment(command.record.text)) {
2945
+ if (seg.segment === "\n" || seg.segment === "\r\n") this.#addNewLine();
2946
+ else this.#overwriteReplaceGrapheme(seg.segment);
2947
+ }
2948
+ } else {
2949
+ this.#spliceVimInsert(command.record);
2950
+ }
2951
+ }
2952
+ if (command.overwrite) {
2953
+ this.#replaceLog.length = 0;
2954
+ this.#resetKillSequence();
2955
+ }
2956
+ const line = this.#state.lines[this.#state.cursorLine] ?? "";
2957
+ this.#setCursorCol(prevGraphemeStart(line, this.#state.cursorCol));
2958
+ }
2959
+
2960
+ /**
2961
+ * Replay one Insert session at the cursor. Built directly rather than through the typing path,
2962
+ * which would pop autocomplete from Normal mode and feed the kill ring.
2963
+ */
2964
+ #spliceVimInsert(record: VimInsertRecord): void {
2965
+ const lines = this.#state.lines;
2966
+ const { text: flat, cursor } = flatten(this.#state);
2967
+ const { start, end } = this.#expandVimRange(
2968
+ offsetToPos(lines, stepGraphemes(flat, cursor, record.deleteBefore, false)),
2969
+ offsetToPos(lines, stepGraphemes(flat, cursor, record.deleteAfter, true)),
2970
+ );
2971
+ if (record.text === "" && start.line === end.line && start.col === end.col) return;
2580
2972
  this.#recordUndoState();
2581
- this.#killRing.push(removed, { prepend: false });
2582
2973
  const head = (lines[start.line] ?? "").slice(0, start.col);
2583
- const tail = (lines[Math.min(end.line, lines.length - 1)] ?? "").slice(end.col);
2584
- lines.splice(start.line, Math.min(end.line, lines.length - 1) - start.line + 1, head + tail);
2585
- this.#state.cursorLine = start.line;
2586
- this.#setCursorCol(start.col);
2974
+ const tail = (lines[end.line] ?? "").slice(end.col);
2975
+ const parts = record.text.split("\n");
2976
+ const rows = parts.slice();
2977
+ rows[0] = head + rows[0];
2978
+ rows[rows.length - 1] += tail;
2979
+ lines.splice(start.line, end.line - start.line + 1, ...rows);
2980
+ this.#state.cursorLine = start.line + parts.length - 1;
2981
+ this.#setCursorCol((parts.length === 1 ? head.length : 0) + (parts.at(-1) ?? "").length);
2982
+ this.#lastAction = null;
2587
2983
  this.#afterVimEdit();
2588
2984
  }
2589
2985
 
@@ -3092,17 +3488,25 @@ export class Editor implements Component, Focusable {
3092
3488
  if (!resolved) return;
3093
3489
  this.#resetKillSequence();
3094
3490
  if (resolved.changed) {
3491
+ if (this.#vimSession) this.#vimSession.tracked = false;
3095
3492
  this.#historyIndex = -1;
3096
3493
  this.#recordUndoState();
3097
3494
  this.#state.lines = resolved.text.split("\n");
3098
3495
  }
3099
3496
  const lines = this.#state.lines;
3497
+ const priorLine = this.#state.cursorLine;
3498
+ const priorCol = this.#state.cursorCol;
3100
3499
  let line = 0;
3101
3500
  let col = resolved.cursor;
3102
3501
  while (line < lines.length - 1 && col > lines[line]!.length) col -= lines[line++]!.length + 1;
3103
3502
  this.#state.cursorLine = line;
3104
3503
  this.#setCursorCol(col);
3105
- if (!resolved.changed) return;
3504
+ if (!resolved.changed) {
3505
+ if (this.#vimSession !== null && (priorLine !== line || priorCol !== col)) {
3506
+ this.#breakVimSession();
3507
+ }
3508
+ return;
3509
+ }
3106
3510
  this.#notifyChange(resolved.text);
3107
3511
  this.#retriggerAutocompleteAtCursor();
3108
3512
  }
@@ -3503,6 +3907,9 @@ export class Editor implements Component, Focusable {
3503
3907
  const dropSpace = this.#hasProvisionalSpace();
3504
3908
  this.#historyIndex = -1; // Exit history browsing mode
3505
3909
  this.#resetKillSequence();
3910
+ // The cursor leaves the trigger token's line, so any open popup is stale:
3911
+ // keeping it would float on the new line and Enter would submit past it.
3912
+ this.#dismissAutocomplete();
3506
3913
  this.#recordUndoState();
3507
3914
 
3508
3915
  const currentLine = this.#state.lines[this.#state.cursorLine] || "";
@@ -3518,6 +3925,9 @@ export class Editor implements Component, Focusable {
3518
3925
  // Move cursor to start of new line
3519
3926
  this.#state.cursorLine++;
3520
3927
  this.#setCursorCol(0);
3928
+ if (this.#vimSession?.replace) {
3929
+ this.#replaceLog.push({ line: this.#state.cursorLine - 1, col: splitCol, removed: "", text: "\n" });
3930
+ }
3521
3931
 
3522
3932
  this.#notifyChange();
3523
3933
  }
@@ -3540,6 +3950,7 @@ export class Editor implements Component, Focusable {
3540
3950
  }
3541
3951
 
3542
3952
  #submitValue(): void {
3953
+ this.#endVimSession();
3543
3954
  this.#resetKillSequence();
3544
3955
 
3545
3956
  const result = this.#expandPasteMarkers(this.#state.lines.join("\n")).trim();
@@ -3550,6 +3961,11 @@ export class Editor implements Component, Focusable {
3550
3961
  this.#scrollOffset = 0;
3551
3962
  this.#undoStack.length = 0;
3552
3963
 
3964
+ if (this.#vim !== null && (this.#vim.mode === "insert" || this.#vim.mode === "replace")) {
3965
+ const mark = this.#undoMark();
3966
+ this.#pinnedUndo = mark;
3967
+ this.#startVimSession(mark, this.#vim.mode === "replace");
3968
+ }
3553
3969
  this.#notifyChange("");
3554
3970
  if (this.onSubmit) this.onSubmit(result);
3555
3971
  }
@@ -3795,23 +4211,27 @@ export class Editor implements Component, Focusable {
3795
4211
 
3796
4212
  #moveToLineStart(): void {
3797
4213
  this.#resetKillSequence();
4214
+ this.#dismissAutocomplete();
3798
4215
  this.#setCursorCol(0);
3799
4216
  }
3800
4217
 
3801
4218
  #moveToLineEnd(): void {
3802
4219
  this.#resetKillSequence();
4220
+ this.#dismissAutocomplete();
3803
4221
  const currentLine = this.#state.lines[this.#state.cursorLine] || "";
3804
4222
  this.#setCursorCol(currentLine.length);
3805
4223
  }
3806
4224
 
3807
4225
  #moveToMessageStart(): void {
3808
4226
  this.#resetKillSequence();
4227
+ this.#dismissAutocomplete();
3809
4228
  this.#state.cursorLine = 0;
3810
4229
  this.#setCursorCol(0);
3811
4230
  }
3812
4231
 
3813
4232
  #moveToMessageEnd(): void {
3814
4233
  this.#resetKillSequence();
4234
+ this.#dismissAutocomplete();
3815
4235
  this.#state.cursorLine = this.#state.lines.length - 1;
3816
4236
  const currentLine = this.#state.lines[this.#state.cursorLine] || "";
3817
4237
  this.#setCursorCol(currentLine.length);
@@ -3841,9 +4261,17 @@ export class Editor implements Component, Focusable {
3841
4261
  cursorLine: this.#state.cursorLine,
3842
4262
  cursorCol: this.#state.cursorCol,
3843
4263
  });
3844
- if (this.#undoStack.length > MAX_UNDO_STACK) {
3845
- this.#undoStack.shift();
4264
+ if (this.#undoStack.length <= MAX_UNDO_STACK) return;
4265
+ const pin = this.#pinnedUndo;
4266
+ const anchorIndex = pin === null ? -1 : pin.depth - (this.#undoShifts - pin.shifts);
4267
+ if (anchorIndex === 0 && this.#undoStack.length > 1) {
4268
+ // Front entry is the open change's restore point. Drop the snapshot after it, and don't
4269
+ // bump #undoShifts: index 0 did not move, so the mark still points at it.
4270
+ this.#undoStack.splice(1, 1);
4271
+ return;
3846
4272
  }
4273
+ this.#undoStack.shift();
4274
+ this.#undoShifts++;
3847
4275
  }
3848
4276
 
3849
4277
  #applyUndo(): void {
@@ -4283,6 +4711,7 @@ export class Editor implements Component, Focusable {
4283
4711
 
4284
4712
  #moveCursor(deltaLine: number, deltaCol: number): void {
4285
4713
  this.#resetKillSequence();
4714
+ this.#dismissAutocomplete();
4286
4715
  const visualLines = this.#buildVisualLineMap(this.#caretRowWidth);
4287
4716
  const currentVisualLine = this.#findCurrentVisualLine(visualLines);
4288
4717
 
@@ -4335,6 +4764,7 @@ export class Editor implements Component, Focusable {
4335
4764
 
4336
4765
  #pageScroll(direction: -1 | 1): void {
4337
4766
  this.#resetKillSequence();
4767
+ this.#dismissAutocomplete();
4338
4768
  const visualLines = this.#buildVisualLineMap(this.#caretRowWidth);
4339
4769
  const currentVisualLine = this.#findCurrentVisualLine(visualLines);
4340
4770
  const step = this.#getPageScrollStep(visualLines.length);
@@ -4365,6 +4795,7 @@ export class Editor implements Component, Focusable {
4365
4795
  */
4366
4796
  #jumpToChar(char: string, direction: "forward" | "backward"): void {
4367
4797
  this.#resetKillSequence();
4798
+ this.#dismissAutocomplete();
4368
4799
  const isForward = direction === "forward";
4369
4800
  const lines = this.#state.lines;
4370
4801
 
@@ -4781,6 +5212,17 @@ export class Editor implements Component, Focusable {
4781
5212
  }
4782
5213
  }
4783
5214
 
5215
+ /**
5216
+ * Close the popup when the cursor leaves the token it was opened for (newline,
5217
+ * pure cursor motion). Its prefix no longer matches the text before the cursor,
5218
+ * so it could neither accept nor refresh and would linger stale.
5219
+ */
5220
+ #dismissAutocomplete(): void {
5221
+ if (this.#autocompleteState === null) return;
5222
+ this.#cancelAutocomplete();
5223
+ this.onAutocompleteUpdate?.();
5224
+ }
5225
+
4784
5226
  /**
4785
5227
  * Whether an autocomplete popup is on screen. An `@` list narrowed to no match
4786
5228
  * while its refresh is pending stays open internally but is hidden, so it does