@hncode/hncode 0.8.0 → 0.8.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.
package/src/markdown.js CHANGED
@@ -1,567 +1,619 @@
1
- // Markdown → ANSI rows.
2
- //
3
- // One block in, a list of painted rows out. Nothing here knows about a transcript, a session or a screen: a caller
4
- // hands over text and a width, which is what lets the same renderer serve a chat row, a tool result and a table cell.
5
- //
6
- // The incremental path exists because streaming rewrites only the LAST block of a growing reply. Splitting at blank
7
- // lines outside a fence makes every earlier block final, so only the tail is re-rendered — verified to produce the
8
- // same rows as a whole-document render, which is the property the cache depends on.
9
-
10
- import { C } from './colors.js';
11
- import { renderLatex } from './latex.js';
12
- import { measureTex, encodeTexImage, TEX_MAX_ROWS } from './tex/index.js';
13
- import { render as renderMermaid, sourceBox as mermaidSourceBox, toAnsi as mermaidAnsi } from './mermaid/index.js';
14
- import { encodeImageRow } from './image-row.js';
15
- import { terminalCaps } from './term-caps.js';
16
- import { col, visualCol, wrapWords } from './text.js';
17
-
18
- /**
19
- * Version of the markdown renderer, part of the incremental cache key.
20
- *
21
- * That cache is validated on the INPUT — text, width, colours — which cannot see that the renderer itself now produces
22
- * different rows for the same input. A session that cached a block before a fence type learned to draw kept showing
23
- * the old output, so the change looked like it had not shipped. Bump this whenever what `renderMdText` produces for
24
- * the same input changes.
25
- */
26
- export const MD_RENDER_VERSION = 7; // 7: an image row carries the TeX that produced it
27
-
28
- /**
29
- * Render a growing markdown text, re-rendering only the last block.
30
- *
31
- * @param {object} msg carries `_mdCache` between calls
32
- * @param {string} text
33
- * @param {number} width
34
- * @param {string} fg body colour
35
- * @param {string} codeFg inline-code colour
36
- * @returns {{headRows: string[], tailRows: string[], headCut: number}}
37
- */
38
- export function renderMdIncremental(msg, text, width, fg, codeFg) {
39
- const src = text.replace(/\r\n/g, '\n');
40
- let c = msg._mdCache;
41
- // Layout identity: same width/colours and the same text. Comparing the text (not just its length) is required — a
42
- // same-length replacement must re-render.
43
- if (c && c.v === MD_RENDER_VERSION && c.width === width && c.fg === fg && c.codeFg === codeFg && c.text === src) {
44
- return { headRows: c.headRows, tailRows: c.tailRows, headCut: c.headCut };
45
- }
46
- if (!c || c.v !== MD_RENDER_VERSION || c.width !== width || c.fg !== fg || c.codeFg !== codeFg) {
47
- c = msg._mdCache = { v: MD_RENDER_VERSION, width, fg, codeFg };
48
- }
49
-
50
- const parts = splitBlocks(src);
51
- // A block is final once a LATER block exists; the last one is still growing.
52
- const headCount = Math.max(0, parts.length - 1);
53
- // THE CACHED BLOCKS BELONG TO A VERSION OF THE RENDERER. Without that check a request for the same text, width and
54
- // colours reuses rows produced by an OLDER renderer: the fast path above rejects them on `c.v`, but it leaves `c`
55
- // untouched (its width and colours still match), and this reuse test then finds the block texts identical and hands
56
- // back the old rows.
57
- const canReuse = c.v === MD_RENDER_VERSION
58
- && Array.isArray(c.blocks)
59
- && Array.isArray(c.blockTexts)
60
- && c.blockTexts.length >= headCount
61
- && parts.length >= headCount
62
- && c.blockTexts.slice(0, headCount).every((t, i) => t === parts[i]);
63
-
64
- const blocks = canReuse ? c.blocks.slice(0, headCount) : parts.slice(0, headCount).map((b) => renderMdText(b, width, fg, codeFg));
65
- const headRows = [];
66
- for (const b of blocks) for (const r of b) headRows.push(r);
67
- const tailRows = renderMdText(parts.length ? parts[parts.length - 1] : '', width, fg, codeFg);
68
- const headCut = parts.length > 1 ? parts.slice(0, headCount).join('\n').length : 0;
69
-
70
- msg._mdCache = {
71
- v: MD_RENDER_VERSION,
72
- text: src, width, fg, codeFg,
73
- blocks, blockTexts: parts.slice(0, headCount),
74
- headRows, tailRows, headCut,
75
- };
76
- return { headRows, tailRows, headCut };
77
- }
78
-
79
- /**
80
- * Split at blank lines OUTSIDE a fence.
81
- *
82
- * The blank line(s) begin the NEXT block, so every block renders the same whether or not later blocks exist — that is
83
- * the property the incremental cache depends on.
84
- */
85
- export function splitBlocks(src) {
86
- if (src === '') return [''];
87
- const lines = src.split('\n');
88
- const out = [];
89
- let cur = [];
90
- let fence = false;
91
- for (const ln of lines) {
92
- const isFence = /^\s*(```+|~~~+)/.test(ln);
93
- const blank = ln.trim() === '';
94
- if (blank && !fence) {
95
- if (cur.length) { out.push(cur); cur = []; }
96
- cur.push(ln);
97
- continue;
98
- }
99
- if (isFence) fence = !fence;
100
- cur.push(ln);
101
- }
102
- if (cur.length) out.push(cur);
103
- return out.map((b) => b.join('\n'));
104
- }
105
-
106
- /** Render a whole markdown document to painted rows. */
107
- export function renderMdText(text, width, fg, codeFg) {
108
- const src = String(text).replace(/\r\n/g, '\n');
109
- const para = src.split('\n');
110
- const out = [];
111
- let i = 0;
112
- const isTableSep = (l) => /^\s*\|?\s*:?-{2,}.*\|/.test(l) || /^\s*\|[-: ]+\|/.test(l);
113
- const splitCells = (l) => {
114
- const s = l.trim().replace(/^\|/, '').replace(/\|$/, '');
115
- return s.split('|').map((c) => c.trim());
116
- };
117
-
118
- while (i < para.length) {
119
- const line = para[i];
120
- const t = line.replace(/\s+$/, '');
121
- // DISPLAY MATH: `$$ ... $$` and `\[ ... \]`.
122
- //
123
- // A fence is what a model writes when it wants a code block, but a formula usually arrives as `$$`. It is laid out
124
- // here as the formula it describes — stacked fractions, limits above a sum — and its source is what remains when
125
- // the subset cannot express it, exactly as a math fence behaves. The opener has to start the line and the closer
126
- // has to end one, so `cost is $$x$$ total` stays prose and is handled as inline math by the line renderer below.
127
- const mathOpen = /^\s*(\$\$|\\\[)/.exec(t);
128
- if (mathOpen) {
129
- const open = mathOpen[1];
130
- const close = open === '$$' ? '$$' : '\\]';
131
- const after = t.slice(mathOpen.index + mathOpen[0].length);
132
- let body = null;
133
- let used = 0;
134
- let closed = true;
135
- // One-line form: `$$x = 1$$` with nothing but whitespace after the closer.
136
- const oneLine = after.indexOf(close);
137
- if (oneLine >= 0 && after.slice(oneLine + close.length).trim() === '') {
138
- body = after.slice(0, oneLine);
139
- used = 1;
140
- } else if (after.trim() === '') {
141
- // Multi-line form: everything up to the line that ends with the closer.
142
- const collected = [];
143
- let k = i + 1;
144
- let found = false;
145
- while (k < para.length) {
146
- const cl = para[k].replace(/\s+$/, '');
147
- if (cl.trimEnd().endsWith(close)) {
148
- collected.push(cl.slice(0, cl.lastIndexOf(close)));
149
- k++;
150
- found = true;
151
- break;
152
- }
153
- collected.push(para[k]);
154
- k++;
155
- }
156
- body = collected.join('\n');
157
- used = k - i;
158
- // Still streaming: no closer yet, so the body is prose plus half a formula.
159
- closed = found;
160
- }
161
- if (body !== null && closed) {
162
- i += used;
163
- // Same three fallbacks as a math fence: bitmap, Unicode layout, then the source.
164
- const rows = mathBlockRows(body, width, true);
165
- if (rows) {
166
- out.push(...rows);
167
- } else {
168
- // Unsupported: show the TeX so the reader still gets the formula's meaning.
169
- for (const l of body.split('\n')) out.push(col(' ' + l.slice(0, Math.max(1, width - 2)), C.white));
170
- }
171
- continue;
172
- }
173
- }
174
- // Fenced code block. Rendered with a rule ABOVE (labelled with the language) and a matching full-width rule BELOW,
175
- // so the block is visibly delimited.
176
- const fm = /^\s*(`{3,}|~{3,})\s*(\S*)/.exec(t);
177
- if (fm) {
178
- const lang = fm[2] || '';
179
- i++;
180
- const buf = [];
181
- const fenceChar = fm[1][0];
182
- const fenceLen = fm[1].length;
183
- const isCloser = (s) => {
184
- const m = /^\s*(`{3,}|~{3,})\s*$/.exec(s);
185
- return !!m && m[1][0] === fenceChar && m[1].length >= fenceLen;
186
- };
187
- while (i < para.length && !isCloser(para[i])) { buf.push(para[i]); i++; }
188
- // Whether the closing fence was actually reached: an open fence means the text is still streaming.
189
- const fenceClosed = i < para.length;
190
- i++; // closing fence (no-op when the fence is still open)
191
- const rule = (s) => col(s, C.gray);
192
- // MATH FENCES ARE TYPESET. A `latex`/`tex`/`math` fence is TeX, not code: it is drawn as the formula it
193
- // describes, and when the terminal speaks an image protocol it is drawn as a TYPESET BITMAP rather than as
194
- // flattened Unicode.
195
- //
196
- // Three fallbacks, in order, and each one keeps the formula: the bitmap; the Unicode layout when the picture
197
- // cannot be placed (no protocol, no cell size, too wide, too tall); the SOURCE when the subset cannot express
198
- // the TeX at all.
199
- if (/^(latex|tex|math)$/i.test(lang)) {
200
- const tex = buf.join('\n').trim();
201
- const rendered = mathBlockRows(tex, width, fenceClosed);
202
- if (rendered) {
203
- out.push(...rendered);
204
- continue;
205
- }
206
- // Falls through to the plain code block: the source is all we have.
207
- }
208
- if (/^mermaid$/i.test(lang)) {
209
- const diagramSrc = buf.join('\n');
210
- let art = null;
211
- try { art = renderMermaid(diagramSrc); } catch { art = null; }
212
- // Wider than the panel: the frame is the honest answer, since truncating art would cut a box in half rather
213
- // than say the diagram does not fit.
214
- if (art && art.width <= width) {
215
- // `toAnsi` keeps the role of every span, so the frame stays dim and the connectors cyan instead of the
216
- // whole diagram arriving as plain white text.
217
- const coloured = mermaidAnsi(art);
218
- for (const l of coloured) out.push(l);
219
- continue;
220
- }
221
- try {
222
- for (const l of mermaidSourceBox(diagramSrc, width).plain) out.push(col(l, C.white));
223
- continue;
224
- } catch { /* fall through to the plain code block */ }
225
- }
226
- // Opening rule: `─ <lang> ` then `─` padding out to the FULL width.
227
- if (lang) {
228
- const head = `\u2500 ${lang} `;
229
- out.push(rule(head + '─'.repeat(Math.max(1, width - visualCol(head)))));
230
- } else {
231
- out.push(rule('─'.repeat(Math.max(1, width))));
232
- }
233
- // Fenced code block CONTENT is plain body text — the default terminal colour, not the theme's cyan. The cyan is
234
- // reserved for UI chrome and the language label; a large code block in cyan reads as "everything is the theme
235
- // colour".
236
- for (const cl of buf) out.push(col(cl.slice(0, width), C.white));
237
- // Closing rule, matching the opening one.
238
- out.push(rule('─'.repeat(Math.max(1, width))));
239
- continue;
240
- }
241
- // Table: a header line followed by a separator line
242
- if (t.includes('|') && i + 1 < para.length && isTableSep(para[i + 1])) {
243
- const header = splitCells(t);
244
- const sep = splitCells(para[i + 1]);
245
- const body = [];
246
- i += 2;
247
- while (i < para.length && para[i].trim().includes('|') && !isTableSep(para[i])) { body.push(splitCells(para[i])); i++; }
248
- renderTable(out, header, body, sep.length, width, fg);
249
- continue;
250
- }
251
- // Fall through to single-line renderer
252
- const rows = markdownLineToRows(t, width, fg, codeFg, false);
253
- out.push(...rows);
254
- i++;
255
- }
256
- return out;
257
- }
258
-
259
- /** Render a Markdown table as aligned columns. Header bolded, rows readable. */
260
- export function renderTable(out, header, body, colCount, width, fg) {
261
- const cols = Math.max(header.length, colCount, ...body.map((r) => r.length));
262
- const B = C.border;
263
- const val = (r, c) => (r && r[c] !== undefined ? String(r[c]) : '');
264
- // Per-column natural width (visual columns), reserving 2 padding each side.
265
- const natural = Array.from({ length: cols }, (_, c) => {
266
- let m = 0;
267
- const consider = (v) => { m = Math.max(m, visualCol(v)); };
268
- consider(val(header, c));
269
- for (const r of body) consider(val(r, c));
270
- return m;
271
- });
272
- // Cap total table width to the available width (minus borders).
273
- const availInner = Math.max(cols, width - (cols + 1));
274
- const totalNatural = natural.reduce((a, b) => a + 2 + b, 0);
275
- let widths;
276
- if (totalNatural <= availInner) {
277
- widths = natural;
278
- } else {
279
- // Scale down proportionally, but never below MIN_COL. A column squeezed to 1 is a column whose content is
280
- // unreadable, so the shrink stops at a width a word can still use and the ROW grows taller instead.
281
- const MIN_COL = 4;
282
- const over = totalNatural - availInner;
283
- const surplus = natural.reduce((a, b) => a + (b > MIN_COL ? b - MIN_COL : 0), 0);
284
- widths = natural.map((n) => {
285
- const shrink = over > 0 && surplus > 0 ? Math.round((Math.max(0, n - MIN_COL)) * (over / surplus)) : 0;
286
- return Math.max(Math.min(MIN_COL, n), n - shrink);
287
- });
288
- }
289
- // WRAP, DO NOT TRUNCATE. A cell whose text does not fit its column used to be emitted at full length, which pushed
290
- // every border after it to the right and broke the table's alignment for the rest of the row. The row now grows
291
- // taller: each cell is wrapped to its column, and every line is padded to the same width.
292
- const wrapCell = (text, w) => {
293
- if (!text) return [''];
294
- return wrapWords(text, Math.max(1, w));
295
- };
296
- // A cell renders its INLINE MARKDOWN (bold, code, links) — a table of `**name**` and `` `value` `` used to show the
297
- // asterisks and backticks verbatim, which is not what the author wrote.
298
- const styled = (text, w, bold) => {
299
- const plain = wrapCell(text, w);
300
- const paint = bold ? C.white + C.bold : C.gray;
301
- return plain.map((lineText) => {
302
- // Render the markdown FIRST, then pad the RESULT.
303
- //
304
- // The pad has to be measured on what the cell will actually PRINT, not on the source: `` `--verbose` `` is 11
305
- // characters of source but 9 on screen once the backticks become a colour, so padding by the source width left
306
- // the column short by two and every border after it moved left.
307
- const md = inlineMarkdown(lineText, C.gray, bold ? C.white : C.gray);
308
- const printed = visualCol(String(md).replace(/\x1b\[[0-9;]*m/g, ''));
309
- const pad = Math.max(0, w - printed);
310
- return col(' ', paint) + col(md, paint) + col(' '.repeat(pad) + ' ', paint);
311
- });
312
- };
313
- const rule = (left, mid, right) => col(left + widths.map((w) => '─'.repeat(w + 2)).join(mid) + right, B);
314
- // One logical row, as several physical lines when any cell wraps.
315
- const oneRow = (cells, bold) => {
316
- const rendered = [];
317
- for (let c = 0; c < cols; c++) rendered.push(styled(val(cells, c), widths[c], bold));
318
- const height = Math.max(1, ...rendered.map((r) => r.length));
319
- for (let lineIdx = 0; lineIdx < height; lineIdx++) {
320
- const parts = rendered.map((r, c) => (r[lineIdx] !== undefined
321
- ? r[lineIdx]
322
- : col(' ' + ' '.repeat(widths[c]) + ' ', bold ? C.white + C.bold : C.gray)));
323
- out.push(col('│', B) + parts.join(col('│', B)) + col('│', B));
324
- }
325
- };
326
- out.push(rule('╭', '┬', '╮'));
327
- oneRow(header, true);
328
- out.push(rule('├', '┼', '┤'));
329
- for (const r of body) oneRow(r, false);
330
- out.push(rule('╰', '┴', '╯'));
331
- }
332
-
333
- /** One line of markdown to rows: headings, rules, quotes, lists, then inline styles. */
334
- export function markdownLineToRows(line, width, fg, codeFg, isContinuation) {
335
- const out = [];
336
- const t = line.replace(/\s+$/, '');
337
-
338
- // Headings: `# Title`
339
- let m = /^(\s*)(#{1,6})\s+(.*)$/.exec(t);
340
- if (m && !isContinuation) {
341
- const hashCount = m[2].length;
342
- // h1 is bold white, h2 is plain white, h3+ is gray. Only h1 carries BOLD.
343
- const size = hashCount === 1 ? C.white + C.bold : hashCount === 2 ? C.white : C.gray;
344
- for (const w of wrapWords(m[3], width)) {
345
- out.push(col(w, size));
346
- }
347
- return out;
348
- }
349
- // Thematic break
350
- if (/^\s*(-{3,}|\*{3,}|_{3,})$/.test(t)) {
351
- out.push(col('─'.repeat(Math.min(width, Math.max(8, width))), C.gray));
352
- return out;
353
- }
354
- // Blockquote
355
- //
356
- // THE RULE AND THE TEXT ARE DIFFERENT COLOURS. The rule takes the theme colour, so a quote reads as a distinct block
357
- // in the transcript; the text takes the comment grey, so quoted material is visibly not the reply's own voice.
358
- // Colouring both the same made a quote indistinguishable from an indented paragraph.
359
- if (/^\s*>\s?/.test(t)) {
360
- const content = t.replace(/^\s*>\s?/, '');
361
- for (const w of wrapWords(content, Math.max(1, width - 2))) {
362
- out.push(col('▍ ', C.cyan) + col(w, C.comment));
363
- }
364
- return out;
365
- }
366
- // Unordered/ordered list — bold the bullet, keep content plain. Also handles task checkboxes.
367
- {
368
- const task = /^(\s*)([-*+]\s+)?\[( |x|X)\]\s+(.*)$/.exec(t);
369
- if (task && !isContinuation) {
370
- const checked = task[3] !== ' ';
371
- const box = checked ? col('✓', C.green) : col('○', C.gray);
372
- const content = col(' ' + inlineMarkdown(task[4], codeFg, fg), fg);
373
- for (const w of wrapWords(task[4], Math.max(1, width - 4))) {
374
- out.push(col(' ', C.gray) + box + (w === task[4] ? content : col(' ' + w, fg)));
375
- }
376
- return out;
377
- }
378
- const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(t);
379
- if (li && !isContinuation) {
380
- const isOrdered = /^\d/.test(li[2]);
381
- const bullet = isOrdered ? col(li[2], C.cyan) : col('•', C.cyan);
382
- const pad = isOrdered ? ' '.repeat(visualCol(li[2])) + ' ' : ' ';
383
- let first = true;
384
- for (const w of wrapWords(inlineMarkdown(li[3], codeFg, fg), Math.max(1, width - 2))) {
385
- out.push((first ? col('', C.gray) + bullet + ' ' : col(pad, C.gray)) + col(w, fg));
386
- first = false;
387
- }
388
- return out;
389
- }
390
- }
391
- // Inline styles: **bold**, *italic*, `code`, [text](url), $math$
392
- if (/[*`\[$]|\\\(/.test(t)) {
393
- for (const w of wrapWords(t, width)) out.push(col(inlineMarkdown(w, codeFg, fg), fg));
394
- return out;
395
- }
396
- // Plain - apply default foreground color
397
- for (const w of wrapWords(t, width)) out.push(col(w, fg));
398
- return out;
399
- }
400
-
401
- /**
402
- * Whether the terminal can receive a formula as a picture.
403
- *
404
- * Both halves are required: a protocol the terminal reported (Sixel today) and a cell size it reported (XTWINOPS 16).
405
- * Without the cell size the picture would be measured in guessed cells, which is what put a formula on the wrong rows
406
- * before — so a missing cell size falls back to text rather than guess.
407
- */
408
- export function mathImageCapable() {
409
- const caps = terminalCaps();
410
- if (!caps) return null;
411
- // KITTY FIRST. A terminal that speaks both (Kitty can be built with Sixel support) handles Kitty far better: the
412
- // pixels are uploaded once and every later frame is a placement, while a Sixel has to be retransmitted and moves the
413
- // cursor when it is drawn.
414
- const protocol = caps.kittyGraphics
415
- ? 'kitty'
416
- : (Array.isArray(caps.extensions) && caps.extensions.includes('sixel') ? 'sixel' : null);
417
- if (!protocol) return null;
418
- const cell = caps.cell && caps.cell.w > 0 && caps.cell.h > 0 ? caps.cell : null;
419
- return cell ? { protocol, cell } : null;
420
- }
421
-
422
- /** Ink colour for a typeset formula: the body text colour, so a picture sits in the text rather than beside it. */
423
- export const MATH_INK = { r: 220, g: 220, b: 220 };
424
-
425
- /**
426
- * The terminal's cell height in pixels, for cropping a picture that straddles the top of the window.
427
- *
428
- * A crop has to convert CELL ROWS to six-pixel BANDS; without the cell height the two units get confused and the image
429
- * is drawn from the wrong point in its own payload. 20 is the conventional monospace cell height and matches the
430
- * fallback `src/tex/` uses when the terminal never answers XTWINOPS 16.
431
- */
432
- export function mathCellHeight() {
433
- const caps = terminalCaps();
434
- const cell = caps && caps.cell;
435
- return cell && cell.h > 0 ? cell.h : 20;
436
- }
437
-
438
- /**
439
- * Rows for one display formula: a typeset bitmap when the terminal can show one, the Unicode layout when it cannot,
440
- * and nothing when the TeX is outside the subset (the caller then shows the source).
441
- *
442
- * @param {string} tex TeX without delimiters.
443
- * @param {number} width Columns available.
444
- * @param {boolean} closed The closing delimiter arrived. A formula still streaming keeps to the text form: a picture of
445
- * half a formula is worse than the TeX of half a formula.
446
- * @returns {string[]|null}
447
- */
448
- export function mathBlockRows(tex, width, closed) {
449
- const src = stripMathDelimiters(tex);
450
- if (!src) return null;
451
- // A picture sits where the text form does: one column of indent, and no wider than the panel.
452
- const room = Math.max(8, width - 2);
453
- if (closed) {
454
- const placed = placeTex(src, room);
455
- if (placed) return placed;
456
- }
457
- const rendered = renderLatex(src, { display: true });
458
- if (rendered === undefined) return null;
459
- return rendered
460
- .split('\n')
461
- .map((l) => col(l.slice(0, width), C.white));
462
- }
463
-
464
- /**
465
- * Remove the delimiters a formula may still be wrapped in.
466
- *
467
- * A `$$…$$` block and a ```latex fence both reach the typesetter, and the fence's content may carry the delimiters too
468
- * — a model writes the fence around `$$…$$` often enough that it is the common case, not the odd one. Typesetting the
469
- * delimiters along with the formula draws them as glyphs inside the picture.
470
- *
471
- * Only a delimiter that spans the WHOLE body is removed: a `$$` in the middle is TeX the author meant, and stripping it
472
- * would change the formula. The loop runs because a doubled wrapper leaves one pair behind after the first pass.
473
- */
474
- export function stripMathDelimiters(tex) {
475
- let s = String(tex || '').trim();
476
- for (;;) {
477
- const before = s;
478
- if (s.startsWith('$$') && s.endsWith('$$') && s.length > 4) {
479
- s = s.slice(2, -2).trim();
480
- } else if (s.startsWith('\\[') && s.endsWith('\\]') && s.length > 4) {
481
- s = s.slice(2, -2).trim();
482
- } else if (s.startsWith('\\(') && s.endsWith('\\)') && s.length > 4) {
483
- s = s.slice(2, -2).trim();
484
- }
485
- if (s === before) return s;
486
- }
487
- }
488
-
489
- /**
490
- * Typeset a formula into a frame row, or null when it cannot be placed as a picture here.
491
- *
492
- * The picture is one row of TEXT plus a payload: the row is the sentinel `image-row.js` understands, the rows below it
493
- * are blank, and the frame writer turns them into a cursor move and a graphics sequence. Every reason to decline is a
494
- * reason the caller already has a text fallback for, so this never throws.
495
- */
496
- export function placeTex(tex, room) {
497
- const capable = mathImageCapable();
498
- if (!capable) return null;
499
- try {
500
- // Measured first, because laying out is what rejects TeX outside the subset: a raster would be paid for and then
501
- // thrown away.
502
- const measured = measureTex(tex, { cell: capable.cell });
503
- if (!measured || measured.columns > room || measured.rows > TEX_MAX_ROWS) return null;
504
- const image = encodeTexImage(tex, { protocol: capable.protocol, cell: capable.cell, colour: MATH_INK });
505
- if (!image) return null;
506
- // THE SOURCE TRAVELS WITH THE ROW. A picture that straddles the top of the window has to be redrawn from its first
507
- // VISIBLE row, and only the TeX can produce that raster: cropping the encoded payload can only land on a six-pixel
508
- // band boundary, which leaves up to a quarter of a cell of the formula above the window and makes it slide as the
509
- // view scrolls. The frame writer reads this back and re-renders with `skipTop` when a picture needs cropping.
510
- const rows = [encodeImageRow(image.sequence, image.rows, image.columns, tex)];
511
- for (let r = 1; r < image.rows; r++) rows.push('');
512
- return rows;
513
- } catch {
514
- // A bitmap that cannot be drawn is a reason to show text, never a reason to lose the frame.
515
- return null;
516
- }
517
- }
518
-
519
- /**
520
- * Whether a `$...$` body is a formula rather than prose.
521
- *
522
- * Prices, shell variables and identifiers all use `$`: `costs $5 and $10`, `$HOME`, `${VAR}`. A body that starts or
523
- * ends with a space, is a bare number or an all-caps word is prose, and so is one with no TeX command and no operator
524
- * in it — `vitamin $C$` stays text while `$x^2$` becomes a formula.
525
- */
526
- export function looksLikeInlineMath(body) {
527
- if (/^\s/.test(body) || /\s$/.test(body)) return false;
528
- if (body.startsWith('{') || body.includes('`')) return false;
529
- if (/^\d+([.,]\d+)?$/.test(body)) return false;
530
- if (/^[A-Z][A-Z0-9_]*$/.test(body)) return false;
531
- return /\\[A-Za-z]+|[=+\-*/<>^_]/.test(body) || (/^[A-Za-z]$/.test(body));
532
- }
533
-
534
- /**
535
- * Apply inline markdown to a single line: `code`, **bold**, *italic*, ~~strike~~, [text](url).
536
- *
537
- * Order matters so inner tokens are handled safely. `base` is the surrounding foreground colour; every inline style
538
- * re-asserts it after its own reset, otherwise the bare `\e[0m` would cancel the base colour for the REST of the line
539
- * — plain text after a **bold** run used to lose its colour and fall back to the terminal default.
540
- */
541
- export function inlineMarkdown(s, codeFg, base) {
542
- const fb = base || '';
543
- let r = s;
544
- // Inline code first so it is not mangled by * [] ~.
545
- r = r.replace(/`([^`]+)`/g, (_, c) => col(c, codeFg) + fb);
546
- // INLINE MATH. After the code spans, so a formula inside backticks stays code, and before emphasis, so `*` and `_`
547
- // inside TeX cannot turn into italics. `\(...\)` is the other inline form models use.
548
- r = r.replace(/\$([^$\n]+?)\$|\\\(([^\n]+?)\\\)/g, (m, dollar, paren) => {
549
- const tex = dollar !== undefined ? dollar : paren;
550
- // A price or a shell variable is not math: `$5 and $10`, `$HOME`, `${VAR}`.
551
- if (dollar !== undefined && !looksLikeInlineMath(tex)) return m;
552
- const out = renderLatex(tex, { display: false });
553
- // Unsupported or multi-line: the source stands, because inline math sits inside wrapped prose.
554
- if (out === undefined || out.includes('\n')) return m;
555
- return out;
556
- });
557
- // Bold
558
- r = r.replace(/\*\*([^*]+)\*\*/g, (_, c) => C.bold + c + C.reset + fb);
559
- // Strikethrough
560
- r = r.replace(/~~([^~]+)~~/g, (_, c) => '\x1b[9m' + c + '\x1b[29m');
561
- // Italic
562
- r = r.replace(/(^|[^*])\*([^*\s][^*]*?)\*(?!\*)/g, (_, pre, c) => pre + '\x1b[3m' + c + '\x1b[23m');
563
- // Links: [text](url) -> text (cyan); autolink bare http(s) urls
564
- r = r.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, txt) => col(txt, C.cyan) + fb);
565
- r = r.replace(/(^|\s)(https?:\/\/[^\s]+)/g, (_, pre, url) => pre + col(url, C.cyan));
566
- return r;
567
- }
1
+ // Markdown → ANSI rows.
2
+ //
3
+ // One block in, a list of painted rows out. Nothing here knows about a transcript, a session or a screen: a caller
4
+ // hands over text and a width, which is what lets the same renderer serve a chat row, a tool result and a table cell.
5
+ //
6
+ // The incremental path exists because streaming rewrites only the LAST block of a growing reply. Splitting at blank
7
+ // lines outside a fence makes every earlier block final, so only the tail is re-rendered — verified to produce the
8
+ // same rows as a whole-document render, which is the property the cache depends on.
9
+
10
+ import { C } from './colors.js';
11
+ import { renderLatex } from './latex.js';
12
+ // THE TYPESETTER IS LOADED WHEN A PICTURE IS ACTUALLY NEEDED.
13
+ //
14
+ // `measureTex` / `encodeTexImage` pull in the whole TeX layout, metrics and raster pipeline: 21ms of module evaluation,
15
+ // which every session paid before the first frame — for a feature that (a) most replies do not use and (b) is skipped
16
+ // entirely when the terminal cannot show a bitmap. `placeTex` returns early in that case, so the common path never
17
+ // needs these at all.
18
+ //
19
+ // ESM has no synchronous require, so the first formula draws as its Unicode layout and the bitmap appears from the next
20
+ // frame. Asking for a picture twice to get it once is better than every startup paying for it.
21
+ let texMod = null;
22
+ let texLoading = null;
23
+ function loadTex() {
24
+ if (texMod) return texMod;
25
+ if (!texLoading) {
26
+ texLoading = import('./tex/index.js')
27
+ .then((m) => { texMod = m; return m; })
28
+ .catch(() => { texLoading = null; return null; });
29
+ }
30
+ return null;
31
+ }
32
+ import { encodeImageRow } from './image-row.js';
33
+ import { terminalCaps } from './term-caps.js';
34
+ import { col, visualCol, wrapWords } from './text.js';
35
+
36
+ /**
37
+ * Mermaid is loaded on first use, not at import.
38
+ *
39
+ * It costs ~54ms of module evaluation — the largest single item behind `latex` and `tui` — and it is only needed to draw
40
+ * a ```mermaid fence, which most sessions never contain. On a weak machine that is a visible slice of the blank screen
41
+ * before the first frame, paid for a feature the session may not use at all.
42
+ *
43
+ * `require`-style sync loading is not available in ESM, so the first mermaid block renders as its SOURCE and kicks off
44
+ * the load; the next frame draws the diagram. A diagram appearing one frame late is not something a reader notices,
45
+ * and it is strictly better than every session paying for it up front.
46
+ */
47
+ let mermaidMod = null;
48
+ let mermaidLoading = null;
49
+ function loadMermaid() {
50
+ if (mermaidMod) return mermaidMod;
51
+ if (!mermaidLoading) {
52
+ mermaidLoading = import('./mermaid/index.js')
53
+ .then((m) => { mermaidMod = m; return m; })
54
+ .catch(() => { mermaidLoading = null; return null; });
55
+ }
56
+ return null; // not ready yet; the caller falls back to the source this frame
57
+ }
58
+
59
+ /**
60
+ * Version of the markdown renderer, part of the incremental cache key.
61
+ *
62
+ * That cache is validated on the INPUT — text, width, colours — which cannot see that the renderer itself now produces
63
+ * different rows for the same input. A session that cached a block before a fence type learned to draw kept showing
64
+ * the old output, so the change looked like it had not shipped. Bump this whenever what `renderMdText` produces for
65
+ * the same input changes.
66
+ */
67
+ export const MD_RENDER_VERSION = 7; // 7: an image row carries the TeX that produced it
68
+
69
+ /**
70
+ * Render a growing markdown text, re-rendering only the last block.
71
+ *
72
+ * @param {object} msg carries `_mdCache` between calls
73
+ * @param {string} text
74
+ * @param {number} width
75
+ * @param {string} fg body colour
76
+ * @param {string} codeFg inline-code colour
77
+ * @returns {{headRows: string[], tailRows: string[], headCut: number}}
78
+ */
79
+ export function renderMdIncremental(msg, text, width, fg, codeFg) {
80
+ const src = text.replace(/\r\n/g, '\n');
81
+ let c = msg._mdCache;
82
+ // Layout identity: same width/colours and the same text. Comparing the text (not just its length) is required — a
83
+ // same-length replacement must re-render.
84
+ if (c && c.v === MD_RENDER_VERSION && c.width === width && c.fg === fg && c.codeFg === codeFg && c.text === src) {
85
+ return { headRows: c.headRows, tailRows: c.tailRows, headCut: c.headCut };
86
+ }
87
+ if (!c || c.v !== MD_RENDER_VERSION || c.width !== width || c.fg !== fg || c.codeFg !== codeFg) {
88
+ c = msg._mdCache = { v: MD_RENDER_VERSION, width, fg, codeFg };
89
+ }
90
+
91
+ const parts = splitBlocks(src);
92
+ // A block is final once a LATER block exists; the last one is still growing.
93
+ const headCount = Math.max(0, parts.length - 1);
94
+ // THE CACHED BLOCKS BELONG TO A VERSION OF THE RENDERER. Without that check a request for the same text, width and
95
+ // colours reuses rows produced by an OLDER renderer: the fast path above rejects them on `c.v`, but it leaves `c`
96
+ // untouched (its width and colours still match), and this reuse test then finds the block texts identical and hands
97
+ // back the old rows.
98
+ const canReuse = c.v === MD_RENDER_VERSION
99
+ && Array.isArray(c.blocks)
100
+ && Array.isArray(c.blockTexts)
101
+ && c.blockTexts.length >= headCount
102
+ && parts.length >= headCount
103
+ && c.blockTexts.slice(0, headCount).every((t, i) => t === parts[i]);
104
+
105
+ const blocks = canReuse ? c.blocks.slice(0, headCount) : parts.slice(0, headCount).map((b) => renderMdText(b, width, fg, codeFg));
106
+ const headRows = [];
107
+ for (const b of blocks) for (const r of b) headRows.push(r);
108
+ const tailRows = renderMdText(parts.length ? parts[parts.length - 1] : '', width, fg, codeFg);
109
+ const headCut = parts.length > 1 ? parts.slice(0, headCount).join('\n').length : 0;
110
+
111
+ msg._mdCache = {
112
+ v: MD_RENDER_VERSION,
113
+ text: src, width, fg, codeFg,
114
+ blocks, blockTexts: parts.slice(0, headCount),
115
+ headRows, tailRows, headCut,
116
+ };
117
+ return { headRows, tailRows, headCut };
118
+ }
119
+
120
+ /**
121
+ * Split at blank lines OUTSIDE a fence.
122
+ *
123
+ * The blank line(s) begin the NEXT block, so every block renders the same whether or not later blocks exist — that is
124
+ * the property the incremental cache depends on.
125
+ */
126
+ export function splitBlocks(src) {
127
+ if (src === '') return [''];
128
+ const lines = src.split('\n');
129
+ const out = [];
130
+ let cur = [];
131
+ let fence = false;
132
+ for (const ln of lines) {
133
+ const isFence = /^\s*(```+|~~~+)/.test(ln);
134
+ const blank = ln.trim() === '';
135
+ if (blank && !fence) {
136
+ if (cur.length) { out.push(cur); cur = []; }
137
+ cur.push(ln);
138
+ continue;
139
+ }
140
+ if (isFence) fence = !fence;
141
+ cur.push(ln);
142
+ }
143
+ if (cur.length) out.push(cur);
144
+ return out.map((b) => b.join('\n'));
145
+ }
146
+
147
+ /** Render a whole markdown document to painted rows. */
148
+ export function renderMdText(text, width, fg, codeFg) {
149
+ const src = String(text).replace(/\r\n/g, '\n');
150
+ const para = src.split('\n');
151
+ const out = [];
152
+ let i = 0;
153
+ const isTableSep = (l) => /^\s*\|?\s*:?-{2,}.*\|/.test(l) || /^\s*\|[-: ]+\|/.test(l);
154
+ const splitCells = (l) => {
155
+ const s = l.trim().replace(/^\|/, '').replace(/\|$/, '');
156
+ return s.split('|').map((c) => c.trim());
157
+ };
158
+
159
+ while (i < para.length) {
160
+ const line = para[i];
161
+ const t = line.replace(/\s+$/, '');
162
+ // DISPLAY MATH: `$$ ... $$` and `\[ ... \]`.
163
+ //
164
+ // A fence is what a model writes when it wants a code block, but a formula usually arrives as `$$`. It is laid out
165
+ // here as the formula it describes — stacked fractions, limits above a sum — and its source is what remains when
166
+ // the subset cannot express it, exactly as a math fence behaves. The opener has to start the line and the closer
167
+ // has to end one, so `cost is $$x$$ total` stays prose and is handled as inline math by the line renderer below.
168
+ const mathOpen = /^\s*(\$\$|\\\[)/.exec(t);
169
+ if (mathOpen) {
170
+ const open = mathOpen[1];
171
+ const close = open === '$$' ? '$$' : '\\]';
172
+ const after = t.slice(mathOpen.index + mathOpen[0].length);
173
+ let body = null;
174
+ let used = 0;
175
+ let closed = true;
176
+ // One-line form: `$$x = 1$$` with nothing but whitespace after the closer.
177
+ const oneLine = after.indexOf(close);
178
+ if (oneLine >= 0 && after.slice(oneLine + close.length).trim() === '') {
179
+ body = after.slice(0, oneLine);
180
+ used = 1;
181
+ } else if (after.trim() === '') {
182
+ // Multi-line form: everything up to the line that ends with the closer.
183
+ const collected = [];
184
+ let k = i + 1;
185
+ let found = false;
186
+ while (k < para.length) {
187
+ const cl = para[k].replace(/\s+$/, '');
188
+ if (cl.trimEnd().endsWith(close)) {
189
+ collected.push(cl.slice(0, cl.lastIndexOf(close)));
190
+ k++;
191
+ found = true;
192
+ break;
193
+ }
194
+ collected.push(para[k]);
195
+ k++;
196
+ }
197
+ body = collected.join('\n');
198
+ used = k - i;
199
+ // Still streaming: no closer yet, so the body is prose plus half a formula.
200
+ closed = found;
201
+ }
202
+ if (body !== null && closed) {
203
+ i += used;
204
+ // Same three fallbacks as a math fence: bitmap, Unicode layout, then the source.
205
+ const rows = mathBlockRows(body, width, true);
206
+ if (rows) {
207
+ out.push(...rows);
208
+ } else {
209
+ // Unsupported: show the TeX so the reader still gets the formula's meaning.
210
+ for (const l of body.split('\n')) out.push(col(' ' + l.slice(0, Math.max(1, width - 2)), C.white));
211
+ }
212
+ continue;
213
+ }
214
+ }
215
+ // Fenced code block. Rendered with a rule ABOVE (labelled with the language) and a matching full-width rule BELOW,
216
+ // so the block is visibly delimited.
217
+ const fm = /^\s*(`{3,}|~{3,})\s*(\S*)/.exec(t);
218
+ if (fm) {
219
+ const lang = fm[2] || '';
220
+ i++;
221
+ const buf = [];
222
+ const fenceChar = fm[1][0];
223
+ const fenceLen = fm[1].length;
224
+ const isCloser = (s) => {
225
+ const m = /^\s*(`{3,}|~{3,})\s*$/.exec(s);
226
+ return !!m && m[1][0] === fenceChar && m[1].length >= fenceLen;
227
+ };
228
+ while (i < para.length && !isCloser(para[i])) { buf.push(para[i]); i++; }
229
+ // Whether the closing fence was actually reached: an open fence means the text is still streaming.
230
+ const fenceClosed = i < para.length;
231
+ i++; // closing fence (no-op when the fence is still open)
232
+ const rule = (s) => col(s, C.gray);
233
+ // MATH FENCES ARE TYPESET. A `latex`/`tex`/`math` fence is TeX, not code: it is drawn as the formula it
234
+ // describes, and when the terminal speaks an image protocol it is drawn as a TYPESET BITMAP rather than as
235
+ // flattened Unicode.
236
+ //
237
+ // Three fallbacks, in order, and each one keeps the formula: the bitmap; the Unicode layout when the picture
238
+ // cannot be placed (no protocol, no cell size, too wide, too tall); the SOURCE when the subset cannot express
239
+ // the TeX at all.
240
+ if (/^(latex|tex|math)$/i.test(lang)) {
241
+ const tex = buf.join('\n').trim();
242
+ const rendered = mathBlockRows(tex, width, fenceClosed);
243
+ if (rendered) {
244
+ out.push(...rendered);
245
+ continue;
246
+ }
247
+ // Falls through to the plain code block: the source is all we have.
248
+ }
249
+ if (/^mermaid$/i.test(lang)) {
250
+ const diagramSrc = buf.join('\n');
251
+ // The module is fetched on the first mermaid block and draws from the NEXT frame; until then the source box is
252
+ // what the reader sees, which is the same fallback used when a diagram does not fit.
253
+ const mm = loadMermaid();
254
+ if (mm) {
255
+ let art = null;
256
+ try { art = mm.render(diagramSrc); } catch { art = null; }
257
+ // Wider than the panel: the frame is the honest answer, since truncating art would cut a box in half rather
258
+ // than say the diagram does not fit.
259
+ if (art && art.width <= width) {
260
+ // `toAnsi` keeps the role of every span, so the frame stays dim and the connectors cyan instead of the
261
+ // whole diagram arriving as plain white text.
262
+ const coloured = mm.toAnsi(art);
263
+ for (const l of coloured) out.push(l);
264
+ continue;
265
+ }
266
+ }
267
+ try {
268
+ if (mm) {
269
+ for (const l of mm.sourceBox(diagramSrc, width).plain) out.push(col(l, C.white));
270
+ continue;
271
+ }
272
+ } catch { /* fall through to the plain code block */ }
273
+ }
274
+ // Opening rule: `─ <lang> ` then `─` padding out to the FULL width.
275
+ if (lang) {
276
+ const head = `\u2500 ${lang} `;
277
+ out.push(rule(head + '─'.repeat(Math.max(1, width - visualCol(head)))));
278
+ } else {
279
+ out.push(rule('─'.repeat(Math.max(1, width))));
280
+ }
281
+ // Fenced code block CONTENT is plain body text — the default terminal colour, not the theme's cyan. The cyan is
282
+ // reserved for UI chrome and the language label; a large code block in cyan reads as "everything is the theme
283
+ // colour".
284
+ for (const cl of buf) out.push(col(cl.slice(0, width), C.white));
285
+ // Closing rule, matching the opening one.
286
+ out.push(rule('─'.repeat(Math.max(1, width))));
287
+ continue;
288
+ }
289
+ // Table: a header line followed by a separator line
290
+ if (t.includes('|') && i + 1 < para.length && isTableSep(para[i + 1])) {
291
+ const header = splitCells(t);
292
+ const sep = splitCells(para[i + 1]);
293
+ const body = [];
294
+ i += 2;
295
+ while (i < para.length && para[i].trim().includes('|') && !isTableSep(para[i])) { body.push(splitCells(para[i])); i++; }
296
+ renderTable(out, header, body, sep.length, width, fg);
297
+ continue;
298
+ }
299
+ // Fall through to single-line renderer
300
+ const rows = markdownLineToRows(t, width, fg, codeFg, false);
301
+ out.push(...rows);
302
+ i++;
303
+ }
304
+ return out;
305
+ }
306
+
307
+ /** Render a Markdown table as aligned columns. Header bolded, rows readable. */
308
+ export function renderTable(out, header, body, colCount, width, fg) {
309
+ const cols = Math.max(header.length, colCount, ...body.map((r) => r.length));
310
+ const B = C.border;
311
+ const val = (r, c) => (r && r[c] !== undefined ? String(r[c]) : '');
312
+ // Per-column natural width (visual columns), reserving 2 padding each side.
313
+ const natural = Array.from({ length: cols }, (_, c) => {
314
+ let m = 0;
315
+ const consider = (v) => { m = Math.max(m, visualCol(v)); };
316
+ consider(val(header, c));
317
+ for (const r of body) consider(val(r, c));
318
+ return m;
319
+ });
320
+ // Cap total table width to the available width (minus borders).
321
+ const availInner = Math.max(cols, width - (cols + 1));
322
+ const totalNatural = natural.reduce((a, b) => a + 2 + b, 0);
323
+ let widths;
324
+ if (totalNatural <= availInner) {
325
+ widths = natural;
326
+ } else {
327
+ // Scale down proportionally, but never below MIN_COL. A column squeezed to 1 is a column whose content is
328
+ // unreadable, so the shrink stops at a width a word can still use and the ROW grows taller instead.
329
+ const MIN_COL = 4;
330
+ const over = totalNatural - availInner;
331
+ const surplus = natural.reduce((a, b) => a + (b > MIN_COL ? b - MIN_COL : 0), 0);
332
+ widths = natural.map((n) => {
333
+ const shrink = over > 0 && surplus > 0 ? Math.round((Math.max(0, n - MIN_COL)) * (over / surplus)) : 0;
334
+ return Math.max(Math.min(MIN_COL, n), n - shrink);
335
+ });
336
+ }
337
+ // WRAP, DO NOT TRUNCATE. A cell whose text does not fit its column used to be emitted at full length, which pushed
338
+ // every border after it to the right and broke the table's alignment for the rest of the row. The row now grows
339
+ // taller: each cell is wrapped to its column, and every line is padded to the same width.
340
+ const wrapCell = (text, w) => {
341
+ if (!text) return [''];
342
+ return wrapWords(text, Math.max(1, w));
343
+ };
344
+ // A cell renders its INLINE MARKDOWN (bold, code, links) — a table of `**name**` and `` `value` `` used to show the
345
+ // asterisks and backticks verbatim, which is not what the author wrote.
346
+ const styled = (text, w, bold) => {
347
+ const plain = wrapCell(text, w);
348
+ const paint = bold ? C.white + C.bold : C.gray;
349
+ return plain.map((lineText) => {
350
+ // Render the markdown FIRST, then pad the RESULT.
351
+ //
352
+ // The pad has to be measured on what the cell will actually PRINT, not on the source: `` `--verbose` `` is 11
353
+ // characters of source but 9 on screen once the backticks become a colour, so padding by the source width left
354
+ // the column short by two and every border after it moved left.
355
+ const md = inlineMarkdown(lineText, C.gray, bold ? C.white : C.gray);
356
+ const printed = visualCol(String(md).replace(/\x1b\[[0-9;]*m/g, ''));
357
+ const pad = Math.max(0, w - printed);
358
+ return col(' ', paint) + col(md, paint) + col(' '.repeat(pad) + ' ', paint);
359
+ });
360
+ };
361
+ const rule = (left, mid, right) => col(left + widths.map((w) => '─'.repeat(w + 2)).join(mid) + right, B);
362
+ // One logical row, as several physical lines when any cell wraps.
363
+ const oneRow = (cells, bold) => {
364
+ const rendered = [];
365
+ for (let c = 0; c < cols; c++) rendered.push(styled(val(cells, c), widths[c], bold));
366
+ const height = Math.max(1, ...rendered.map((r) => r.length));
367
+ for (let lineIdx = 0; lineIdx < height; lineIdx++) {
368
+ const parts = rendered.map((r, c) => (r[lineIdx] !== undefined
369
+ ? r[lineIdx]
370
+ : col(' ' + ' '.repeat(widths[c]) + ' ', bold ? C.white + C.bold : C.gray)));
371
+ out.push(col('│', B) + parts.join(col('│', B)) + col('│', B));
372
+ }
373
+ };
374
+ out.push(rule('╭', '┬', '╮'));
375
+ oneRow(header, true);
376
+ out.push(rule('├', '┼', '┤'));
377
+ for (const r of body) oneRow(r, false);
378
+ out.push(rule('╰', '┴', '╯'));
379
+ }
380
+
381
+ /** One line of markdown to rows: headings, rules, quotes, lists, then inline styles. */
382
+ export function markdownLineToRows(line, width, fg, codeFg, isContinuation) {
383
+ const out = [];
384
+ const t = line.replace(/\s+$/, '');
385
+
386
+ // Headings: `# Title`
387
+ let m = /^(\s*)(#{1,6})\s+(.*)$/.exec(t);
388
+ if (m && !isContinuation) {
389
+ const hashCount = m[2].length;
390
+ // h1 is bold white, h2 is plain white, h3+ is gray. Only h1 carries BOLD.
391
+ const size = hashCount === 1 ? C.white + C.bold : hashCount === 2 ? C.white : C.gray;
392
+ for (const w of wrapWords(m[3], width)) {
393
+ out.push(col(w, size));
394
+ }
395
+ return out;
396
+ }
397
+ // Thematic break
398
+ if (/^\s*(-{3,}|\*{3,}|_{3,})$/.test(t)) {
399
+ out.push(col('─'.repeat(Math.min(width, Math.max(8, width))), C.gray));
400
+ return out;
401
+ }
402
+ // Blockquote
403
+ //
404
+ // THE RULE AND THE TEXT ARE DIFFERENT COLOURS. The rule takes the theme colour, so a quote reads as a distinct block
405
+ // in the transcript; the text takes the comment grey, so quoted material is visibly not the reply's own voice.
406
+ // Colouring both the same made a quote indistinguishable from an indented paragraph.
407
+ if (/^\s*>\s?/.test(t)) {
408
+ const content = t.replace(/^\s*>\s?/, '');
409
+ for (const w of wrapWords(content, Math.max(1, width - 2))) {
410
+ out.push(col('▍ ', C.cyan) + col(w, C.comment));
411
+ }
412
+ return out;
413
+ }
414
+ // Unordered/ordered list — bold the bullet, keep content plain. Also handles task checkboxes.
415
+ {
416
+ const task = /^(\s*)([-*+]\s+)?\[( |x|X)\]\s+(.*)$/.exec(t);
417
+ if (task && !isContinuation) {
418
+ const checked = task[3] !== ' ';
419
+ const box = checked ? col('✓', C.green) : col('○', C.gray);
420
+ const content = col(' ' + inlineMarkdown(task[4], codeFg, fg), fg);
421
+ for (const w of wrapWords(task[4], Math.max(1, width - 4))) {
422
+ out.push(col(' ', C.gray) + box + (w === task[4] ? content : col(' ' + w, fg)));
423
+ }
424
+ return out;
425
+ }
426
+ const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(t);
427
+ if (li && !isContinuation) {
428
+ const isOrdered = /^\d/.test(li[2]);
429
+ const bullet = isOrdered ? col(li[2], C.cyan) : col('•', C.cyan);
430
+ const pad = isOrdered ? ' '.repeat(visualCol(li[2])) + ' ' : ' ';
431
+ let first = true;
432
+ for (const w of wrapWords(inlineMarkdown(li[3], codeFg, fg), Math.max(1, width - 2))) {
433
+ out.push((first ? col('', C.gray) + bullet + ' ' : col(pad, C.gray)) + col(w, fg));
434
+ first = false;
435
+ }
436
+ return out;
437
+ }
438
+ }
439
+ // Inline styles: **bold**, *italic*, `code`, [text](url), $math$
440
+ if (/[*`\[$]|\\\(/.test(t)) {
441
+ for (const w of wrapWords(t, width)) out.push(col(inlineMarkdown(w, codeFg, fg), fg));
442
+ return out;
443
+ }
444
+ // Plain - apply default foreground color
445
+ for (const w of wrapWords(t, width)) out.push(col(w, fg));
446
+ return out;
447
+ }
448
+
449
+ /**
450
+ * Whether the terminal can receive a formula as a picture.
451
+ *
452
+ * Both halves are required: a protocol the terminal reported (Sixel today) and a cell size it reported (XTWINOPS 16).
453
+ * Without the cell size the picture would be measured in guessed cells, which is what put a formula on the wrong rows
454
+ * before — so a missing cell size falls back to text rather than guess.
455
+ */
456
+ export function mathImageCapable() {
457
+ const caps = terminalCaps();
458
+ if (!caps) return null;
459
+ // KITTY FIRST. A terminal that speaks both (Kitty can be built with Sixel support) handles Kitty far better: the
460
+ // pixels are uploaded once and every later frame is a placement, while a Sixel has to be retransmitted and moves the
461
+ // cursor when it is drawn.
462
+ const protocol = caps.kittyGraphics
463
+ ? 'kitty'
464
+ : (Array.isArray(caps.extensions) && caps.extensions.includes('sixel') ? 'sixel' : null);
465
+ if (!protocol) return null;
466
+ const cell = caps.cell && caps.cell.w > 0 && caps.cell.h > 0 ? caps.cell : null;
467
+ return cell ? { protocol, cell } : null;
468
+ }
469
+
470
+ /** Ink colour for a typeset formula: the body text colour, so a picture sits in the text rather than beside it. */
471
+ export const MATH_INK = { r: 220, g: 220, b: 220 };
472
+
473
+ /**
474
+ * The terminal's cell height in pixels, for cropping a picture that straddles the top of the window.
475
+ *
476
+ * A crop has to convert CELL ROWS to six-pixel BANDS; without the cell height the two units get confused and the image
477
+ * is drawn from the wrong point in its own payload. 20 is the conventional monospace cell height and matches the
478
+ * fallback `src/tex/` uses when the terminal never answers XTWINOPS 16.
479
+ */
480
+ export function mathCellHeight() {
481
+ const caps = terminalCaps();
482
+ const cell = caps && caps.cell;
483
+ return cell && cell.h > 0 ? cell.h : 20;
484
+ }
485
+
486
+ /**
487
+ * Rows for one display formula: a typeset bitmap when the terminal can show one, the Unicode layout when it cannot,
488
+ * and nothing when the TeX is outside the subset (the caller then shows the source).
489
+ *
490
+ * @param {string} tex TeX without delimiters.
491
+ * @param {number} width Columns available.
492
+ * @param {boolean} closed The closing delimiter arrived. A formula still streaming keeps to the text form: a picture of
493
+ * half a formula is worse than the TeX of half a formula.
494
+ * @returns {string[]|null}
495
+ */
496
+ export function mathBlockRows(tex, width, closed) {
497
+ const src = stripMathDelimiters(tex);
498
+ if (!src) return null;
499
+ // A picture sits where the text form does: one column of indent, and no wider than the panel.
500
+ const room = Math.max(8, width - 2);
501
+ if (closed) {
502
+ const placed = placeTex(src, room);
503
+ if (placed) return placed;
504
+ }
505
+ const rendered = renderLatex(src, { display: true });
506
+ if (rendered === undefined) return null;
507
+ return rendered
508
+ .split('\n')
509
+ .map((l) => col(l.slice(0, width), C.white));
510
+ }
511
+
512
+ /**
513
+ * Remove the delimiters a formula may still be wrapped in.
514
+ *
515
+ * A `$$…$$` block and a ```latex fence both reach the typesetter, and the fence's content may carry the delimiters too
516
+ * — a model writes the fence around `$$…$$` often enough that it is the common case, not the odd one. Typesetting the
517
+ * delimiters along with the formula draws them as glyphs inside the picture.
518
+ *
519
+ * Only a delimiter that spans the WHOLE body is removed: a `$$` in the middle is TeX the author meant, and stripping it
520
+ * would change the formula. The loop runs because a doubled wrapper leaves one pair behind after the first pass.
521
+ */
522
+ export function stripMathDelimiters(tex) {
523
+ let s = String(tex || '').trim();
524
+ for (;;) {
525
+ const before = s;
526
+ if (s.startsWith('$$') && s.endsWith('$$') && s.length > 4) {
527
+ s = s.slice(2, -2).trim();
528
+ } else if (s.startsWith('\\[') && s.endsWith('\\]') && s.length > 4) {
529
+ s = s.slice(2, -2).trim();
530
+ } else if (s.startsWith('\\(') && s.endsWith('\\)') && s.length > 4) {
531
+ s = s.slice(2, -2).trim();
532
+ }
533
+ if (s === before) return s;
534
+ }
535
+ }
536
+
537
+ /**
538
+ * Typeset a formula into a frame row, or null when it cannot be placed as a picture here.
539
+ *
540
+ * The picture is one row of TEXT plus a payload: the row is the sentinel `image-row.js` understands, the rows below it
541
+ * are blank, and the frame writer turns them into a cursor move and a graphics sequence. Every reason to decline is a
542
+ * reason the caller already has a text fallback for, so this never throws.
543
+ */
544
+ export function placeTex(tex, room) {
545
+ const capable = mathImageCapable();
546
+ if (!capable) return null;
547
+ // Loaded on first use — see loadTex. Until it lands the caller draws the Unicode layout, which is the same fallback
548
+ // used when a formula cannot be placed as a picture.
549
+ const T = loadTex();
550
+ if (!T) return null;
551
+ try {
552
+ // Measured first, because laying out is what rejects TeX outside the subset: a raster would be paid for and then
553
+ // thrown away.
554
+ const measured = T.measureTex(tex, { cell: capable.cell });
555
+ if (!measured || measured.columns > room || measured.rows > T.TEX_MAX_ROWS) return null;
556
+ const image = T.encodeTexImage(tex, { protocol: capable.protocol, cell: capable.cell, colour: MATH_INK });
557
+ if (!image) return null;
558
+ // THE SOURCE TRAVELS WITH THE ROW. A picture that straddles the top of the window has to be redrawn from its first
559
+ // VISIBLE row, and only the TeX can produce that raster: cropping the encoded payload can only land on a six-pixel
560
+ // band boundary, which leaves up to a quarter of a cell of the formula above the window and makes it slide as the
561
+ // view scrolls. The frame writer reads this back and re-renders with `skipTop` when a picture needs cropping.
562
+ const rows = [encodeImageRow(image.sequence, image.rows, image.columns, tex)];
563
+ for (let r = 1; r < image.rows; r++) rows.push('');
564
+ return rows;
565
+ } catch {
566
+ // A bitmap that cannot be drawn is a reason to show text, never a reason to lose the frame.
567
+ return null;
568
+ }
569
+ }
570
+
571
+ /**
572
+ * Whether a `$...$` body is a formula rather than prose.
573
+ *
574
+ * Prices, shell variables and identifiers all use `$`: `costs $5 and $10`, `$HOME`, `${VAR}`. A body that starts or
575
+ * ends with a space, is a bare number or an all-caps word is prose, and so is one with no TeX command and no operator
576
+ * in it — `vitamin $C$` stays text while `$x^2$` becomes a formula.
577
+ */
578
+ export function looksLikeInlineMath(body) {
579
+ if (/^\s/.test(body) || /\s$/.test(body)) return false;
580
+ if (body.startsWith('{') || body.includes('`')) return false;
581
+ if (/^\d+([.,]\d+)?$/.test(body)) return false;
582
+ if (/^[A-Z][A-Z0-9_]*$/.test(body)) return false;
583
+ return /\\[A-Za-z]+|[=+\-*/<>^_]/.test(body) || (/^[A-Za-z]$/.test(body));
584
+ }
585
+
586
+ /**
587
+ * Apply inline markdown to a single line: `code`, **bold**, *italic*, ~~strike~~, [text](url).
588
+ *
589
+ * Order matters so inner tokens are handled safely. `base` is the surrounding foreground colour; every inline style
590
+ * re-asserts it after its own reset, otherwise the bare `\e[0m` would cancel the base colour for the REST of the line
591
+ * — plain text after a **bold** run used to lose its colour and fall back to the terminal default.
592
+ */
593
+ export function inlineMarkdown(s, codeFg, base) {
594
+ const fb = base || '';
595
+ let r = s;
596
+ // Inline code first so it is not mangled by * [] ~.
597
+ r = r.replace(/`([^`]+)`/g, (_, c) => col(c, codeFg) + fb);
598
+ // INLINE MATH. After the code spans, so a formula inside backticks stays code, and before emphasis, so `*` and `_`
599
+ // inside TeX cannot turn into italics. `\(...\)` is the other inline form models use.
600
+ r = r.replace(/\$([^$\n]+?)\$|\\\(([^\n]+?)\\\)/g, (m, dollar, paren) => {
601
+ const tex = dollar !== undefined ? dollar : paren;
602
+ // A price or a shell variable is not math: `$5 and $10`, `$HOME`, `${VAR}`.
603
+ if (dollar !== undefined && !looksLikeInlineMath(tex)) return m;
604
+ const out = renderLatex(tex, { display: false });
605
+ // Unsupported or multi-line: the source stands, because inline math sits inside wrapped prose.
606
+ if (out === undefined || out.includes('\n')) return m;
607
+ return out;
608
+ });
609
+ // Bold
610
+ r = r.replace(/\*\*([^*]+)\*\*/g, (_, c) => C.bold + c + C.reset + fb);
611
+ // Strikethrough
612
+ r = r.replace(/~~([^~]+)~~/g, (_, c) => '\x1b[9m' + c + '\x1b[29m');
613
+ // Italic
614
+ r = r.replace(/(^|[^*])\*([^*\s][^*]*?)\*(?!\*)/g, (_, pre, c) => pre + '\x1b[3m' + c + '\x1b[23m');
615
+ // Links: [text](url) -> text (cyan); autolink bare http(s) urls
616
+ r = r.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, txt) => col(txt, C.cyan) + fb);
617
+ r = r.replace(/(^|\s)(https?:\/\/[^\s]+)/g, (_, pre, url) => pre + col(url, C.cyan));
618
+ return r;
619
+ }