@oh-my-pi/pi-tui 18.11.0 → 18.11.2

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 (82) hide show
  1. package/CHANGELOG.md +52 -146
  2. package/dist/types/apps/git/git-tui.d.ts +16 -2
  3. package/dist/types/autocomplete.d.ts +2 -0
  4. package/dist/types/charts/chart-svg.d.ts +7 -13
  5. package/dist/types/chat/table-chart.d.ts +11 -15
  6. package/dist/types/chrome/transcript-container.d.ts +2 -0
  7. package/dist/types/components/image.d.ts +2 -0
  8. package/dist/types/components/markdown.d.ts +37 -0
  9. package/dist/types/native/blobs.d.ts +11 -11
  10. package/dist/types/overlays/agent-hub-projection.d.ts +10 -5
  11. package/dist/types/overlays/job-tree.d.ts +50 -0
  12. package/dist/types/overlays/jobs-panel.d.ts +24 -11
  13. package/dist/types/prompt/composer.d.ts +20 -0
  14. package/dist/types/prompt/custom-editor.d.ts +2 -0
  15. package/dist/types/prompt/image-references.d.ts +22 -0
  16. package/dist/types/prompt/macos-spelling.d.ts +2 -1
  17. package/dist/types/prompt/prose-gate.d.ts +3 -0
  18. package/dist/types/prompt/queued-messages.d.ts +1 -1
  19. package/dist/types/prompt/typing-word.d.ts +25 -0
  20. package/dist/types/render/hyperlink.d.ts +2 -0
  21. package/dist/types/render/utils.d.ts +1 -1
  22. package/dist/types/status-line/context-usage.d.ts +3 -0
  23. package/dist/types/status-line/host.d.ts +6 -4
  24. package/dist/types/status-line/startup.d.ts +6 -6
  25. package/dist/types/stdin-buffer.d.ts +7 -0
  26. package/dist/types/terminal.d.ts +8 -4
  27. package/dist/types/tools/eval.d.ts +5 -0
  28. package/dist/types/tools/grouped-file-output.d.ts +2 -0
  29. package/dist/types/tools/read.d.ts +5 -4
  30. package/dist/types/tui.d.ts +10 -0
  31. package/package.json +9 -9
  32. package/src/apps/git/git-tui.ts +27 -10
  33. package/src/apps/git/sidebar.ts +5 -1
  34. package/src/autocomplete.ts +21 -19
  35. package/src/bracketed-paste.ts +9 -2
  36. package/src/charts/chart-svg.ts +19 -22
  37. package/src/chat/assistant-message.ts +37 -12
  38. package/src/chat/bash-execution.ts +7 -2
  39. package/src/chat/image-loading.ts +4 -6
  40. package/src/chat/read-tool-group.ts +1 -0
  41. package/src/chat/table-chart.ts +24 -57
  42. package/src/chat/tool-execution.ts +11 -4
  43. package/src/chat/user-message.ts +22 -15
  44. package/src/chrome/transcript-container.ts +10 -0
  45. package/src/components/editor.ts +12 -12
  46. package/src/components/image.ts +23 -6
  47. package/src/components/markdown.ts +375 -6
  48. package/src/components/settings-list.ts +2 -4
  49. package/src/native/blobs.ts +22 -6
  50. package/src/native/reconcile.ts +19 -15
  51. package/src/overlays/agent-hub-projection.ts +63 -12
  52. package/src/overlays/btw-history-panel.ts +30 -23
  53. package/src/overlays/extensions/extension-list.ts +4 -6
  54. package/src/overlays/job-tree.ts +177 -0
  55. package/src/overlays/jobs-panel.ts +107 -49
  56. package/src/overlays/settings-selector.ts +3 -0
  57. package/src/prompt/composer.ts +180 -23
  58. package/src/prompt/custom-editor.ts +19 -1
  59. package/src/prompt/image-references.ts +79 -2
  60. package/src/prompt/macos-spelling.ts +28 -5
  61. package/src/prompt/prose-gate.ts +3 -0
  62. package/src/prompt/queued-messages.ts +9 -2
  63. package/src/prompt/typing-word.ts +59 -0
  64. package/src/render/code-cell.ts +8 -1
  65. package/src/render/hyperlink.ts +5 -0
  66. package/src/render/utils.ts +1 -1
  67. package/src/render/width-aware-text.ts +6 -5
  68. package/src/status-line/component.ts +22 -10
  69. package/src/status-line/context-usage.ts +22 -16
  70. package/src/status-line/footer.ts +18 -35
  71. package/src/status-line/host.ts +6 -1
  72. package/src/status-line/startup.ts +6 -6
  73. package/src/stdin-buffer.ts +11 -1
  74. package/src/terminal.ts +136 -42
  75. package/src/tools/ast-grep.ts +2 -2
  76. package/src/tools/edit.ts +16 -1
  77. package/src/tools/eval.ts +51 -11
  78. package/src/tools/grouped-file-output.ts +6 -1
  79. package/src/tools/read.ts +6 -5
  80. package/src/tools/write.ts +1 -1
  81. package/src/tui.ts +61 -30
  82. package/src/utils.ts +5 -3
@@ -4,6 +4,7 @@ import {
4
4
  type AutocompleteItem,
5
5
  type AutocompleteProvider,
6
6
  atCompletionMatches,
7
+ extractAtFilePrefix,
7
8
  findLeadingSlashCommandStart,
8
9
  findTrailingSlashCommandStart,
9
10
  isDirectoryCompletionValue,
@@ -99,7 +100,6 @@ function sameDecorations(a: readonly TspEditorDecoration[], b: readonly TspEdito
99
100
  return true;
100
101
  }
101
102
  const MENTION_CONTEXT_RE = /(?:^|\s)\^[^\s]*$/;
102
- const AT_TOKEN_RE = /(?:^|\s)(@[^\s]*)$/;
103
103
 
104
104
  const AUTOCOMPLETE_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
105
105
  overflowSearch: false,
@@ -1764,7 +1764,7 @@ export class Editor implements Component, Focusable {
1764
1764
  let typed = this.#autocompletePrefix;
1765
1765
  if (typed.startsWith("@")) {
1766
1766
  const line = this.#state.lines[this.#state.cursorLine] ?? "";
1767
- typed = AT_TOKEN_RE.exec(line.slice(0, this.#state.cursorCol))?.[1] ?? typed;
1767
+ typed = extractAtFilePrefix(line.slice(0, this.#state.cursorCol)) ?? typed;
1768
1768
  }
1769
1769
  typed = typed.replace(/^[/@:#$^]"?/, "");
1770
1770
  return typed.slice(typed.lastIndexOf("/") + 1);
@@ -3348,7 +3348,7 @@ export class Editor implements Component, Focusable {
3348
3348
  this.#tryTriggerAutocomplete();
3349
3349
  }
3350
3350
  // Check if we're in an @ file reference context
3351
- else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
3351
+ else if (extractAtFilePrefix(textBeforeCursor)) {
3352
3352
  this.#tryTriggerAutocomplete();
3353
3353
  }
3354
3354
  // Check if we're in a model mention context
@@ -3472,7 +3472,7 @@ export class Editor implements Component, Focusable {
3472
3472
  const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
3473
3473
  if (this.#isInSlashAutocompleteContext()) {
3474
3474
  this.#tryTriggerAutocomplete();
3475
- } else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
3475
+ } else if (extractAtFilePrefix(textBeforeCursor)) {
3476
3476
  this.#tryTriggerAutocomplete();
3477
3477
  } else if (MENTION_CONTEXT_RE.test(textBeforeCursor)) {
3478
3478
  this.#tryTriggerAutocomplete();
@@ -3675,7 +3675,7 @@ export class Editor implements Component, Focusable {
3675
3675
  this.#tryTriggerAutocomplete();
3676
3676
  }
3677
3677
  // @ file reference context
3678
- else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
3678
+ else if (extractAtFilePrefix(textBeforeCursor)) {
3679
3679
  this.#tryTriggerAutocomplete();
3680
3680
  }
3681
3681
  // model mention context
@@ -3850,7 +3850,7 @@ export class Editor implements Component, Focusable {
3850
3850
  const textBeforeCursor = currentLine.slice(0, this.#state.cursorCol);
3851
3851
  if (this.#isInSlashAutocompleteContext()) {
3852
3852
  this.#tryTriggerAutocomplete();
3853
- } else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
3853
+ } else if (extractAtFilePrefix(textBeforeCursor)) {
3854
3854
  this.#tryTriggerAutocomplete();
3855
3855
  } else if (MENTION_CONTEXT_RE.test(textBeforeCursor)) {
3856
3856
  this.#tryTriggerAutocomplete();
@@ -4187,7 +4187,7 @@ export class Editor implements Component, Focusable {
4187
4187
  this.#tryTriggerAutocomplete();
4188
4188
  }
4189
4189
  // @ file reference context
4190
- else if (textBeforeCursor.match(/(?:^|[\s])@[^\s]*$/)) {
4190
+ else if (extractAtFilePrefix(textBeforeCursor)) {
4191
4191
  this.#tryTriggerAutocomplete();
4192
4192
  }
4193
4193
  // model mention context
@@ -4448,8 +4448,8 @@ export class Editor implements Component, Focusable {
4448
4448
  * - Mid-prompt skill branch re-anchors when the popup item is a skill and the
4449
4449
  * current text still ends in a matching trailing slash token, preventing a
4450
4450
  * stale selection from replacing a newer skill prefix.
4451
- * - `@`-file branch re-anchors via `#extractAtPrefix`; safe when the current text
4452
- * still ends in a whitespace-anchored `@<token>`.
4451
+ * - `@`-file branch re-anchors via `extractAtFilePrefix`; safe when the current text
4452
+ * still ends in a whitespace-anchored or double-quoted `@` token.
4453
4453
  * - Everything else is stale — accepting it would corrupt the buffer (issue #4295).
4454
4454
  */
4455
4455
  #autocompletePrefixMatchesCursorText(currentTextBeforeCursor: string, item?: SelectItem | null): boolean {
@@ -4484,7 +4484,7 @@ export class Editor implements Component, Focusable {
4484
4484
  }
4485
4485
 
4486
4486
  if (this.#autocompletePrefix.startsWith("@")) {
4487
- return /(?:^|\s)@[^\s]*$/.test(currentTextBeforeCursor);
4487
+ return extractAtFilePrefix(currentTextBeforeCursor) !== null;
4488
4488
  }
4489
4489
 
4490
4490
  if (this.#autocompletePrefix.startsWith("^")) {
@@ -4879,8 +4879,8 @@ export class Editor implements Component, Focusable {
4879
4879
  #narrowAtFileList(): void {
4880
4880
  if (!this.#autocompleteList || !this.#autocompletePrefix.startsWith("@")) return;
4881
4881
  const currentLine = this.#state.lines[this.#state.cursorLine] ?? "";
4882
- const token = AT_TOKEN_RE.exec(currentLine.slice(0, this.#state.cursorCol))?.[1];
4883
- if (token !== undefined) this.#autocompleteList.setFilter(token);
4882
+ const token = extractAtFilePrefix(currentLine.slice(0, this.#state.cursorCol));
4883
+ if (token !== null) this.#autocompleteList.setFilter(token);
4884
4884
  }
4885
4885
 
4886
4886
  #invalidateAutocompleteRequests(): void {
@@ -10,7 +10,8 @@ import {
10
10
  renderImage,
11
11
  TERMINAL,
12
12
  } from "../terminal-capabilities";
13
- import { nativeImageNode } from "../native/blobs";
13
+ import { nativeImageNode, openableImageProps } from "../native/blobs";
14
+ import { imageLinksEnabled, linkedImageText, transcriptImageLink } from "../prompt/image-references";
14
15
  import type { DescribeContext, NativeNode } from "../native/node";
15
16
  import type { Component } from "../tui";
16
17
 
@@ -22,6 +23,8 @@ export interface ImageOptions {
22
23
  maxWidthCells?: number;
23
24
  maxHeightCells?: number;
24
25
  filename?: string;
26
+ /** File the image was read from; its link target. Images without one link to a blob copy of their bytes. */
27
+ sourcePath?: string;
25
28
  /** Shared budget that caps how many inline images render as live graphics. */
26
29
  budget?: ImageBudget;
27
30
  /**
@@ -653,11 +656,13 @@ export class Image implements Component {
653
656
  #cachedCellWidthPx = 0;
654
657
  #cachedCellHeightPx = 0;
655
658
  #cachedKittyUnicodePlaceholders = false;
659
+ #cachedLinked = false;
656
660
  // Tallest graphic placement this image has rendered. The text fallback
657
661
  // pads itself to this height so a budget demotion never shrinks the block
658
662
  // (its rows may already be committed to native scrollback).
659
663
  #renderedGraphicRows = 0;
660
- #native?: NativeNode;
664
+ /** Described node and the link policy it was built under (an `off` switch drops its `href`). */
665
+ #native?: { linked: boolean; node: NativeNode };
661
666
  /** Newest SIXEL encode: its target size and, once settled, the sequence (`null` on failure). */
662
667
  #sixel?: { widthPx: number; heightPx: number; sequence?: string | null };
663
668
 
@@ -736,10 +741,12 @@ export class Image implements Component {
736
741
  * graphics protocols do not apply.
737
742
  */
738
743
  describe(_cx: DescribeContext): NativeNode {
739
- if (this.#native) return this.#native;
744
+ const linked = imageLinksEnabled();
745
+ if (this.#native?.linked === linked) return this.#native.node;
740
746
  const maxW = this.#options.maxWidthCells;
741
747
  const maxH = this.#options.maxHeightCells;
742
- this.#native = nativeImageNode(Buffer.from(this.#base64Data, "base64"), this.#mimeType, {
748
+ const href = transcriptImageLink({ data: this.#base64Data, mimeType: this.#mimeType }, this.#options.sourcePath);
749
+ const node = nativeImageNode(Buffer.from(this.#base64Data, "base64"), this.#mimeType, {
743
750
  alt: imageFallback(this.#mimeType, this.#dimensions, this.#options.filename),
744
751
  w: this.#dimensions.widthPx,
745
752
  h: this.#dimensions.heightPx,
@@ -750,8 +757,10 @@ export class Image implements Component {
750
757
  h: maxH && maxH > 0 ? `${maxH}lines` : undefined,
751
758
  }
752
759
  : undefined,
760
+ ...openableImageProps(href),
753
761
  });
754
- return this.#native;
762
+ this.#native = { linked, node };
763
+ return node;
755
764
  }
756
765
 
757
766
  render(width: number): readonly string[] {
@@ -771,6 +780,7 @@ export class Image implements Component {
771
780
  // re-encode the full image on every render pass.
772
781
  const imageId = this.#imageId;
773
782
  const transmitsSeparately = imageProtocol === ImageProtocol.Kitty && imageId != null;
783
+ const linked = imageLinksEnabled();
774
784
 
775
785
  if (
776
786
  this.#cachedLines &&
@@ -780,6 +790,8 @@ export class Image implements Component {
780
790
  this.#cachedCellWidthPx === cellDimensions.widthPx &&
781
791
  this.#cachedCellHeightPx === cellDimensions.heightPx &&
782
792
  this.#cachedKittyUnicodePlaceholders === kittyUnicodePlaceholders &&
793
+ // The text fallback embeds a link only under an enabled hyperlink policy.
794
+ this.#cachedLinked === linked &&
783
795
  (!transmitsSeparately || this.#budget?.shouldTransmit(imageId) !== true) &&
784
796
  // Cached rows reserved for a pending SIXEL encode must not reach scrollback.
785
797
  !(scrollbackRenderDepth > 0 && this.#sixel !== undefined && this.#sixel.sequence === undefined)
@@ -850,6 +862,7 @@ export class Image implements Component {
850
862
  this.#cachedCellWidthPx = cellDimensions.widthPx;
851
863
  this.#cachedCellHeightPx = cellDimensions.heightPx;
852
864
  this.#cachedKittyUnicodePlaceholders = kittyUnicodePlaceholders;
865
+ this.#cachedLinked = linked;
853
866
 
854
867
  return lines;
855
868
  }
@@ -864,7 +877,11 @@ export class Image implements Component {
864
877
  */
865
878
  #fallbackLines(): string[] {
866
879
  const fallback = this.#theme.fallbackColor(
867
- imageFallback(this.#mimeType, this.#dimensions, this.#options.filename),
880
+ linkedImageText(
881
+ imageFallback(this.#mimeType, this.#dimensions, this.#options.filename),
882
+ { data: this.#base64Data, mimeType: this.#mimeType },
883
+ this.#options.sourcePath,
884
+ ),
868
885
  );
869
886
  if (this.#renderedGraphicRows <= 1) return [fallback];
870
887
  const lines: string[] = [];
@@ -10,10 +10,13 @@ import {
10
10
  } from "@oh-my-pi/pi-utils/marked";
11
11
  import {
12
12
  type MathBlockOpener,
13
+ type MathOpener,
13
14
  mathBlockCloserIndex,
14
15
  mathBlockInContext,
15
16
  mathBlockMayCloseAt,
16
17
  mathBlockOpenerAt,
18
+ mathOpenerAt,
19
+ mathSpanAt,
17
20
  mathSpanInContext,
18
21
  mathStartIndex,
19
22
  } from "@oh-my-pi/pi-utils/math-delimiters";
@@ -64,6 +67,349 @@ export function streamingMarkdownSource(text: string): string {
64
67
  return replaceTabs(normalizeOsc8Terminators(text));
65
68
  }
66
69
 
70
+ // A leading-pipe table line: optional indent / blockquote markers, then `|`.
71
+ const TABLE_LINE_AT = /[ \t>]*\|/y;
72
+ // A line holding an unescaped `|`: a GFM table line needs no outer pipes.
73
+ const PIPE_IN_LINE_AT = /[^\n]*?(?<!\\)\|/y;
74
+ // A whole GFM delimiter row (`| --- | :-: |`, `--- | ---`). Without a leading pipe it needs an inner one; a lone
75
+ // `---` is a rule or setext underline.
76
+ const DELIMITER_ROW_AT =
77
+ /[ \t>]*(?:\|[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?|[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)+\|?)[ \t]*\r?(?=\n|$)/y;
78
+ const UNESCAPED_PIPE = /(?<!\\)\|/g;
79
+ const UNESCAPED_PIPE_END = /(?<!\\)\|$/;
80
+ // A fence line (opener or closer) after any blockquote markers: indentation, marker, info string.
81
+ const FENCE_LINE = /^(?:[ \t]*>)*([ \t]*)(`{3,}|~{3,})([^\n]*)$/gm;
82
+ // A list item's marker line after any blockquote markers: indentation, marker, spacing.
83
+ const LIST_ITEM_LINE = /^(?:[ \t]*>)*([ \t]*)([-*+]|\d{1,9}[.)])([ \t]+)\S/;
84
+
85
+ function matchesAt(pattern: RegExp, text: string, lineStart: number): boolean {
86
+ pattern.lastIndex = lineStart;
87
+ return pattern.test(text);
88
+ }
89
+
90
+ /** Column width of leading whitespace, tabs to the next multiple of four. */
91
+ function indentWidth(whitespace: string): number {
92
+ let width = 0;
93
+ for (const ch of whitespace) width = ch === "\t" ? width + 4 - (width % 4) : width + 1;
94
+ return width;
95
+ }
96
+
97
+ /**
98
+ * Whether the fence line at `lineStart`, indented `indent` columns, is a real
99
+ * fence: at most three columns in, or inside a list item whose content column
100
+ * it sits within three columns of. Deeper lines elsewhere are indented code.
101
+ */
102
+ function fenceIndentValid(text: string, lineStart: number, indent: number): boolean {
103
+ if (indent <= 3) return true;
104
+ for (let end = lineStart - 1; end > 0;) {
105
+ const start = text.lastIndexOf("\n", end - 1) + 1;
106
+ const line = text.slice(start, end);
107
+ end = start - 1;
108
+ if (!line.trim()) continue;
109
+ const lineIndent = indentWidth(/^(?:[ \t]*>)*([ \t]*)/.exec(line)![1]);
110
+ if (lineIndent >= indent) continue;
111
+ const item = LIST_ITEM_LINE.exec(line);
112
+ if (item) {
113
+ const content = indentWidth(item[1]) + item[2].length + indentWidth(item[3]);
114
+ return indent >= content && indent <= content + 3;
115
+ }
116
+ // A less indented line that is no list item: only a list item's continuation text keeps looking.
117
+ if (lineIndent === 0) return false;
118
+ }
119
+ return false;
120
+ }
121
+
122
+ /** Whether a code fence is still open at `end` of `text`. */
123
+ function fenceOpenAt(text: string, end: number): boolean {
124
+ let open: string | undefined;
125
+ FENCE_LINE.lastIndex = 0;
126
+ for (let match = FENCE_LINE.exec(text); match !== null && match.index < end; match = FENCE_LINE.exec(text)) {
127
+ const [, indent, marker, rest] = match;
128
+ if (!fenceIndentValid(text, match.index, indentWidth(indent))) continue;
129
+ if (open === undefined) {
130
+ // A backtick fence's info string cannot hold a backtick (that line is inline code).
131
+ if (marker[0] !== "`" || !rest.includes("`")) open = marker;
132
+ } else if (marker[0] === open[0] && marker.length >= open.length && !rest.trim()) {
133
+ open = undefined;
134
+ }
135
+ }
136
+ return open !== undefined;
137
+ }
138
+
139
+ /**
140
+ * Streaming `md` source for a native terminal, minus a still-growing table row:
141
+ * the unterminated last line when a GFM table (a run of pipe lines holding a
142
+ * header and its delimiter row, outer pipes optional) sits right above it,
143
+ * outside any open code fence. GFM continues a table on any non-blank line, so
144
+ * that line is a row whatever it holds so far. The terminal sizes columns by
145
+ * every row it gets, so a half-streamed row (an unclosed link shows its whole
146
+ * URL) would rewrap the table each frame, and TSP cannot ask it to skip one.
147
+ * The result keeps the newline before the held line, so it is a prefix of
148
+ * `text` and of the result for every append to it: streaming stays
149
+ * append-only. Pass untrimmed source: trimming first drops the newline that
150
+ * marks the last row finished, so that row would be held too.
151
+ */
152
+ export function holdPartialTableRow(text: string): string {
153
+ const lastBreak = text.lastIndexOf("\n");
154
+ if (lastBreak <= 0 || lastBreak === text.length - 1) return text;
155
+ // Walk up the run of pipe lines above the growing row to a delimiter row with a header above it.
156
+ let lineStart = text.lastIndexOf("\n", lastBreak - 1) + 1;
157
+ let table = false;
158
+ while (matchesAt(PIPE_IN_LINE_AT, text, lineStart)) {
159
+ const above = lineStart > 0 ? text.lastIndexOf("\n", lineStart - 2) + 1 : -1;
160
+ if (matchesAt(DELIMITER_ROW_AT, text, lineStart)) {
161
+ table = above >= 0 && matchesAt(PIPE_IN_LINE_AT, text, above);
162
+ lineStart = above;
163
+ break;
164
+ }
165
+ if (above < 0) break;
166
+ lineStart = above;
167
+ }
168
+ if (!table || fenceOpenAt(text, lineStart)) return text;
169
+ return text.slice(0, lastBreak + 1);
170
+ }
171
+
172
+ /**
173
+ * Index of the cell a streaming table's last row is still writing: the cell
174
+ * after its last `|`, or -1 when a newline or trailing `|` closed the row.
175
+ * `raw` is the table token's source; GFM splits cells on every unescaped pipe.
176
+ */
177
+ function growingTableCell(raw: string): number {
178
+ if (raw.endsWith("\n")) return -1;
179
+ const line = raw.slice(raw.lastIndexOf("\n") + 1).trimEnd();
180
+ if (UNESCAPED_PIPE_END.test(line)) return -1;
181
+ const pipes = line.match(UNESCAPED_PIPE)?.length ?? 0;
182
+ return matchesAt(TABLE_LINE_AT, line, 0) ? pipes - 1 : pipes;
183
+ }
184
+
185
+ const MATH_CLOSERS: Record<MathOpener, string> = { $: "$", $$: "$$", "\\(": "\\)", "\\[": "\\]" };
186
+ // The end of a math body that is not yet valid LaTeX: a half-typed command, a lone `\`, or a dangling `^`/`_`.
187
+ const PARTIAL_LATEX_TAIL = /(?:\\[A-Za-z]*|[\^_])$/;
188
+ // A body opened by anything but `$$` needs one of these: `$5` is a price and `\[docs]` an escaped bracket until
189
+ // LaTeX shows up, so they stay literal until they close.
190
+ const LATEX_HINT = /[\\^_{}]/;
191
+ // Math openers tried from the end of the run; the one being written is almost always the last.
192
+ const MATH_OPENER_TRIES = 3;
193
+
194
+ /** Whether the character at `at` follows an odd run of backslashes. */
195
+ function escapedAt(text: string, at: number): boolean {
196
+ let slashes = 0;
197
+ while (at - slashes - 1 >= 0 && text[at - slashes - 1] === "\\") slashes++;
198
+ return slashes % 2 === 1;
199
+ }
200
+
201
+ /**
202
+ * Where `text` is inline prose rather than code: the closed code spans, and
203
+ * the start of a backtick run no later run closes. While streaming, that run
204
+ * is a code span still being written, so nothing after it is prose.
205
+ */
206
+ class InlineCode {
207
+ readonly #spans: number[] = [];
208
+ readonly #openFrom: number;
209
+
210
+ constructor(text: string) {
211
+ let at = text.indexOf("`");
212
+ let openFrom = text.length;
213
+ while (at >= 0) {
214
+ let runEnd = at;
215
+ while (text[runEnd] === "`") runEnd++;
216
+ if (escapedAt(text, at) && runEnd - at === 1) {
217
+ at = text.indexOf("`", runEnd);
218
+ continue;
219
+ }
220
+ const length = runEnd - at;
221
+ let close = text.indexOf("`", runEnd);
222
+ let closeEnd = close;
223
+ while (close >= 0) {
224
+ closeEnd = close;
225
+ while (text[closeEnd] === "`") closeEnd++;
226
+ if (closeEnd - close === length) break;
227
+ close = text.indexOf("`", closeEnd);
228
+ }
229
+ if (close < 0) {
230
+ openFrom = at;
231
+ break;
232
+ }
233
+ this.#spans.push(at, closeEnd);
234
+ at = text.indexOf("`", closeEnd);
235
+ }
236
+ this.#openFrom = openFrom;
237
+ }
238
+
239
+ /** Whether `at` is prose: outside every code span, and before any span still open. */
240
+ prose(at: number): boolean {
241
+ if (at >= this.#openFrom) return false;
242
+ for (let i = 0; i < this.#spans.length; i += 2) {
243
+ if (at >= this.#spans[i]! && at < this.#spans[i + 1]!) return false;
244
+ }
245
+ return true;
246
+ }
247
+ }
248
+
249
+ /** `text` with its trailing open link closed, or `undefined` when its end is not inside a link destination. */
250
+ function closeOpenLink(text: string, code: () => InlineCode): string | undefined {
251
+ const destination = text.lastIndexOf("](");
252
+ if (destination < 0 || escapedAt(text, destination)) return undefined;
253
+ // A destination may hold balanced parentheses; `<…>` destinations and titles are not guessed.
254
+ if (text[destination + 2] === "<") return undefined;
255
+ let depth = 1;
256
+ for (let i = destination + 2; i < text.length; i++) {
257
+ const ch = text[i];
258
+ if (ch === "\\") i++;
259
+ else if (ch === "(") depth++;
260
+ else if (ch === ")" && --depth === 0) return undefined;
261
+ else if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") return undefined;
262
+ }
263
+ let nested = 0;
264
+ let label = -1;
265
+ for (let i = destination - 1; i >= 0; i--) {
266
+ const ch = text[i];
267
+ if ((ch !== "[" && ch !== "]") || escapedAt(text, i)) continue;
268
+ if (ch === "]") nested++;
269
+ else if (nested > 0) nested--;
270
+ else {
271
+ label = i;
272
+ break;
273
+ }
274
+ }
275
+ // An image keeps its literal form: its alt text and source are not a link.
276
+ if (label < 0 || (text[label - 1] === "!" && !escapedAt(text, label - 1))) return undefined;
277
+ const spans = code();
278
+ if (!spans.prose(label) || !spans.prose(destination)) return undefined;
279
+ return text + ")".repeat(depth);
280
+ }
281
+
282
+ /** `text` with its trailing open math span closed in its last valid form, or `undefined`. */
283
+ function closeOpenMath(text: string, code: () => InlineCode): string | undefined {
284
+ let from = text.length;
285
+ for (let tries = 0; tries < MATH_OPENER_TRIES && from > 0;) {
286
+ const at = Math.max(
287
+ text.lastIndexOf("$", from - 1),
288
+ text.lastIndexOf("\\(", from - 1),
289
+ text.lastIndexOf("\\[", from - 1),
290
+ );
291
+ if (at < 0) return undefined;
292
+ from = at;
293
+ const opener = mathOpenerAt(text, at);
294
+ // The second `$` of a `$$` opener is not an opener of its own.
295
+ if (opener === undefined || (opener === "$" && text[at - 1] === "$")) continue;
296
+ tries++;
297
+ if (!code().prose(at)) continue;
298
+ const bodyStart = at + opener.length;
299
+ let written = text.slice(bodyStart);
300
+ // A `$$` span whose closer is half written ends in that closer's first `$`.
301
+ if (opener === "$$" && written.endsWith("$") && !escapedAt(text, text.length - 1)) written = written.slice(0, -1);
302
+ const body = written.replace(PARTIAL_LATEX_TAIL, "");
303
+ if (!body.trim() || (opener !== "$$" && !LATEX_HINT.test(written))) continue;
304
+ let depth = 0;
305
+ for (let i = 0; i < body.length; i++) {
306
+ if (body[i] === "\\") i++;
307
+ else if (body[i] === "{") depth++;
308
+ else if (body[i] === "}" && depth > 0) depth--;
309
+ }
310
+ const closed = `${text.slice(0, bodyStart)}${body}${"}".repeat(depth)}${MATH_CLOSERS[opener]}`;
311
+ // The grammar decides: escaped, currency-like, or space-padded openers stay literal.
312
+ if (mathSpanAt(closed, at)?.end === closed.length) return closed;
313
+ }
314
+ return undefined;
315
+ }
316
+
317
+ /**
318
+ * `text`, one inline run whose end is still streaming, with a trailing open
319
+ * link or math span closed the way the finished text most likely closes it,
320
+ * or `undefined` when nothing at its end is open. A link gains its missing
321
+ * `)` (one per open parenthesis in its destination), so it renders as the
322
+ * link it becomes instead of literal brackets and URL. A math body is cut back
323
+ * to its last valid form (a half-typed command, dangling `^`/`_`, or the first
324
+ * `$` of a `$$` closer dropped, open braces closed) and closed, so the
325
+ * rendered math grows in place instead of raw LaTeX turning into symbols at
326
+ * the closer. A `$` body needs a LaTeX character, so a price (`$5 per`) is
327
+ * never speculated. Only prose is: escaped openers and anything inside a code
328
+ * span, closed or still being written, stay literal.
329
+ */
330
+ export function speculativeInlineClose(text: string): string | undefined {
331
+ let spans: InlineCode | undefined;
332
+ const code = () => (spans ??= new InlineCode(text));
333
+ return closeOpenLink(text, code) ?? closeOpenMath(text, code);
334
+ }
335
+
336
+ /**
337
+ * Streaming `md` source for a native terminal with the open link or math span
338
+ * at its end speculatively closed ({@link speculativeInlineClose}), as the TUI
339
+ * renders it. Only the last block is read (a span cannot cross a blank line),
340
+ * and source inside an open code fence is left as it is. Each frame rewrites
341
+ * only the guessed closers at the end, which the reconciler sends as a small
342
+ * `splice`.
343
+ */
344
+ export function speculativeStreamingSource(text: string): string {
345
+ const blockBreak = text.lastIndexOf("\n\n");
346
+ const blockStart = blockBreak < 0 ? 0 : blockBreak + 2;
347
+ const closed = speculativeInlineClose(text.slice(blockStart));
348
+ if (closed === undefined || fenceOpenAt(text, text.length)) return text;
349
+ return text.slice(0, blockStart) + closed;
350
+ }
351
+
352
+ /** `raw` with its last `from` replaced by `to`, or `undefined` when `from` is not in it. */
353
+ function replaceLast(raw: string, from: string, to: string): string | undefined {
354
+ const at = raw.lastIndexOf(from);
355
+ return at < 0 ? undefined : raw.slice(0, at) + to + raw.slice(at + from.length);
356
+ }
357
+
358
+ /**
359
+ * A copy of `token`, the last block of a streaming render, whose still-written
360
+ * inline run is speculatively closed ({@link speculativeInlineClose}), or
361
+ * `undefined` when nothing in it is open. Follows the run into the last list
362
+ * item, blockquote child, or the open cell of a table's last row. `raw` is
363
+ * rewritten to match, so row caches keyed on it never mistake the copy for
364
+ * the source as it stands.
365
+ */
366
+ function speculateStreamingToken(token: Token): Token | undefined {
367
+ switch (token.type) {
368
+ case "paragraph":
369
+ case "heading":
370
+ case "text": {
371
+ const closed = speculativeInlineClose(token.text);
372
+ const raw = closed === undefined ? undefined : replaceLast(token.raw, token.text, closed);
373
+ if (closed === undefined || raw === undefined) return undefined;
374
+ return { ...token, raw, text: closed, tokens: lexInlineTokens(closed) };
375
+ }
376
+ case "blockquote": {
377
+ const children: Token[] = token.tokens ?? [];
378
+ const inner = children.at(-1);
379
+ const patched = inner && speculateStreamingToken(inner);
380
+ const raw = inner && patched && replaceLast(token.raw, inner.raw, patched.raw);
381
+ if (!patched || raw === undefined) return undefined;
382
+ return { ...token, raw, tokens: [...children.slice(0, -1), patched] };
383
+ }
384
+ case "list": {
385
+ const items: Tokens.ListItem[] = token.items;
386
+ const item = items.at(-1);
387
+ const inner = item?.tokens.at(-1);
388
+ if (!item || !inner) return undefined;
389
+ const patched = speculateStreamingToken(inner);
390
+ const itemRaw = patched && replaceLast(item.raw, inner.raw, patched.raw);
391
+ const raw = itemRaw === undefined ? undefined : replaceLast(token.raw, item.raw, itemRaw);
392
+ if (!patched || itemRaw === undefined || raw === undefined) return undefined;
393
+ const grown = { ...item, raw: itemRaw, tokens: [...item.tokens.slice(0, -1), patched] };
394
+ return { ...token, raw, items: [...items.slice(0, -1), grown] };
395
+ }
396
+ case "table": {
397
+ const rows: Tokens.TableCell[][] = token.rows;
398
+ const open = growingTableCell(token.raw);
399
+ const row = rows.at(-1);
400
+ const cell = open >= 0 ? row?.[open] : undefined;
401
+ if (!row || !cell) return undefined;
402
+ const closed = speculativeInlineClose(cell.text);
403
+ const raw = closed === undefined ? undefined : replaceLast(token.raw, cell.text, closed);
404
+ if (closed === undefined || raw === undefined) return undefined;
405
+ const cells = row.map((c, i) => (i === open ? { ...c, text: closed, tokens: lexInlineTokens(closed) } : c));
406
+ return { ...token, raw, rows: [...rows.slice(0, -1), cells] };
407
+ }
408
+ default:
409
+ return undefined;
410
+ }
411
+ }
412
+
67
413
  /** The longest suffix of `text` a future append could still complete into a
68
414
  * full `\x1b]8;[^\x07\x1b]*\x1b\\` match: the last `\x1b]8;` plus clean
69
415
  * body (or that plus the pending ST-ESC `\x1b`), or a strict prefix of the
@@ -2056,8 +2402,10 @@ export class Markdown implements Component {
2056
2402
  const cached = this.#native;
2057
2403
  if (cached?.text === this.#text && cached.stream === stream) return cached.node;
2058
2404
  // Sources are model text; OSC 8 / SGR bytes a caller spliced in are the terminal's to style, not ours.
2059
- const source = this.#text.includes("\x1b") ? plainText(this.#text) : this.#text;
2060
- const described = md(source, stream ? { stream: true } : undefined);
2405
+ const plain = this.#text.includes("\x1b") ? plainText(this.#text) : this.#text;
2406
+ const described = stream
2407
+ ? md(speculativeStreamingSource(holdPartialTableRow(plain)), { stream: true })
2408
+ : md(plain);
2061
2409
  this.#native = { text: this.#text, stream, node: described };
2062
2410
  return described;
2063
2411
  }
@@ -2532,7 +2880,9 @@ export class Markdown implements Component {
2532
2880
  // into a table on a marker-free delta (`| --` + `--- | -`).
2533
2881
  !FAST_TABLE_DELIM_ROW_RE.test(grownLastLine) &&
2534
2882
  (!markerDelta || (!this.#lastTailCapture?.open && !pairSeamHazard && !inlineHasOpen(deltaTokens!))) &&
2535
- !FAST_URL_ANYWHERE_RE.test(seamWindow)
2883
+ !FAST_URL_ANYWHERE_RE.test(seamWindow) &&
2884
+ // A link or math span the grown row leaves open renders speculatively closed: re-lex.
2885
+ speculativeInlineClose(grownLastLine) === undefined
2536
2886
  ) {
2537
2887
  // Same text paths a full re-lex applies: real pipeline for marker
2538
2888
  // deltas, plain swatch/entity render for inert deltas.
@@ -2636,8 +2986,12 @@ export class Markdown implements Component {
2636
2986
  }
2637
2987
  }
2638
2988
 
2639
- // Parse markdown to HTML-like tokens
2640
- const tokens = this.#lexTokens(normalizedText);
2989
+ // Parse markdown to HTML-like tokens. While streaming, the block still
2990
+ // being written renders its open link or math span as already closed.
2991
+ const lexed = this.#lexTokens(normalizedText);
2992
+ const tail = lexed.at(-1);
2993
+ const speculated = this.transientRenderCache && tail ? speculateStreamingToken(tail) : undefined;
2994
+ const tokens = speculated ? [...lexed.slice(0, -1), speculated] : lexed;
2641
2995
  let contentLines: string[];
2642
2996
  this.#activeRenderSignature = signature;
2643
2997
  try {
@@ -2664,6 +3018,8 @@ export class Markdown implements Component {
2664
3018
 
2665
3019
  const fastEligible =
2666
3020
  this.transientRenderCache &&
3021
+ // A speculated frame's rows come from source the stream does not hold yet.
3022
+ speculated === undefined &&
2667
3023
  contentLines.length > 0 &&
2668
3024
  // B+ invariant: only the FINAL #renderContentLines call captures;
2669
3025
  // the all-cache-hit prefix path clears #lastTailCapture at its top.
@@ -4054,8 +4410,21 @@ export class Markdown implements Component {
4054
4410
  naturalWidths[i] = Math.max(...headerLineWidths, 0);
4055
4411
  minWordWidths[i] = Math.max(1, this.#getLongestWordWidth(headerText, maxUnbrokenWordWidth));
4056
4412
  }
4057
- for (const row of token.rows) {
4413
+ // While streaming, the last row's open cell is still growing (an unclosed
4414
+ // link even shows its whole URL): sizing columns by it would rewrap every
4415
+ // row above it on each frame. Lay that cell out in the measured widths
4416
+ // instead; it counts once a `|` or newline closes it. The row's closed
4417
+ // cells are final and count already. The first data row has no finished
4418
+ // rows to borrow from, so it counts whole.
4419
+ const openCell =
4420
+ this.#transientRenderCache && !this.#renderingStablePrefix && token.rows.length > 1
4421
+ ? growingTableCell(token.raw)
4422
+ : -1;
4423
+ const lastRow = token.rows.length - 1;
4424
+ for (let rowIndex = 0; rowIndex <= lastRow; rowIndex++) {
4425
+ const row = token.rows[rowIndex];
4058
4426
  for (let i = 0; i < row.length; i++) {
4427
+ if (rowIndex === lastRow && i === openCell) continue;
4059
4428
  const cellText = this.#renderInlineTokens(row[i].tokens || [], styleContext);
4060
4429
  const cellLineWidths = this.#terminalLineWidths(cellText);
4061
4430
  naturalWidths[i] = Math.max(naturalWidths[i] || 0, ...cellLineWidths);
@@ -4,6 +4,7 @@ import { fuzzyFilter } from "../fuzzy";
4
4
  import { getKeybindings } from "../keybindings";
5
5
  import { extractPrintableText } from "../keys";
6
6
  import type { MouseRoutable, SgrMouseEvent } from "../mouse";
7
+ import { slugify } from "@oh-my-pi/pi-utils";
7
8
  import type { TspPrefsControl, TspPrefsRow, TspPrefsSection, TspProps, TspSpan } from "@oh-my-pi/pi-wire";
8
9
  import { col, node, span } from "../native/describe";
9
10
  import { sameItems, sameProps } from "../native/memo";
@@ -78,10 +79,7 @@ export interface PrefsSectionRef {
78
79
 
79
80
  /** The section id for a section title (`"Status Line"` → `"status-line"`). */
80
81
  export function prefsSectionId(title: string): string {
81
- return title
82
- .toLowerCase()
83
- .replace(/[^a-z0-9]+/g, "-")
84
- .replace(/^-|-$/g, "");
82
+ return slugify(title);
85
83
  }
86
84
 
87
85
  /** A setting as a native settings row, given its typed control; `undefined` for headings. */