Colorful, themeable rendering for Claude Code replies: tables, headings, code, numbers, paths and links.

<h1 align="center"><img src="docs/brand/banner.png" alt="prismantis" width="640"></h1>
<a href="https://github.com/NahumLitvin/prismantis/releases"><img src="https://img.shields.io/github/v/release/NahumLitvin/prismantis?style=flat-square&color=cba6f7" alt="Release"></a> <a href="https://github.com/NahumLitvin/prismantis/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/NahumLitvin/prismantis/ci.yml?branch=main&style=flat-square&label=ci" alt="CI"></a> <a href="LICENSE"><img src="https://img.shields.io/github/license/NahumLitvin/prismantis?style=flat-square&color=cba6f7" alt="License"></a> <img src="https://img.shields.io/badge/Claude%20Code-2.1.287%2B-cba6f7?style=flat-square" alt="Claude Code 2.1.287 or later"> <a href="https://github.com/hesreallyhim/awesome-claude-code"><img src="https://awesome.re/mentioned-badge.svg" alt="Mentioned in Awesome Claude Code"></a> <a href="https://statuslin.es/mods/prismantis"><img src="https://img.shields.io/badge/listed%20on-statuslin.es-c96442?style=flat-square" alt="Listed on statuslin.es"></a>
<a href="#install"><strong>Install</strong></a> · <a href="#themes">Themes</a> · <a href="#features">Features</a> · <a href="#configure">Configure</a> · <a href="docs/CHANGELOG.md">Changelog</a>

<sub>Same prompt, same model: plain Claude Code, then with prismantis. <a href="https://github.com/user-attachments/assets/7f4744fc-ca52-4ea3-adb3-43467190dc62">▶ Watch the full 44-second tour</a> (tables, charts, diagrams, diffs, callouts, right-to-left text).</sub>
mono, and copy buttons on everything./plugin to turn it off. Claude Code's own renderer comes back the moment you do.⧉ html (the clipboard helper) or turn on LaTeX (RaTeX's renderer)./plugin marketplace add NahumLitvin/prismantis
/plugin install prismantis@prismantis
Then run /prismantis setup to pick a theme and styles from drawn samples, and /prismantis demo for a tour of the main features. In a terminal, setup opens a pane: the arrows or Tab move through the styles of a step with a preview of the one in focus, Enter saves it and shows the next step. Where the session has no terminal, as in the desktop app, it walks the same steps in the transcript.
Requires Claude Code 2.1.287 or later. Run the two commands above.
To update, run this, then /reload in every open session. A session keeps the version it loaded until it reloads.
claude plugin marketplace update prismantis && claude plugin update prismantis@prismantis
To uninstall:
claude plugin uninstall prismantis@prismantis
For LaTeX math, install RaTeX's renderer and set latex to true; see LaTeX math. Until then formulas draw as text.
prismantis also runs in Codex, with themes for code, tables and diagrams and the same session note. Install, what works today, and the two Codex issues it waits on for parity: codex/README.md.
| Feature | What you get |
|---|---|
| Themes | /prismantis theme <name> switches on the spot. 17 themes and 20 color slots you can override |
| Tables | colored headers, rules, column alignment, colored numbers, sized to the terminal |
| Code | a language header and copy button, Prism highlighting in two dozen languages, shell lines colored like a prompt |
| Diagrams and charts | flowcharts, sequence, state, class and ER diagrams, bar and line charts, one color per box, participant and bar |
| Figures | `figure text pictures drawn as written in the theme's colors, for timelines, layouts and before and after; glyphs and markup checked before they are drawn |
| LaTeX math | $$ and `math formulas typeset as images in kitty and Ghostty by RaTeX, text everywhere else |
| Layout | back-to-back tables and diagrams sit side by side and wrap on narrow terminals |
| Copy buttons | ⧉ md, ⧉ art and ⧉ html on tables, [ ⧉ copy ] on code, lists and quotes, /prismantis copy without a mouse |
| Tool rows | Ran gh pr view 12, Read ~/src/app.ts, groups summed up as Ran 3 commands, read 2 files, with status dots; toolOutput: quiet hides what Claude only read and says in plain words what each call did |
| Turn footer | ✻ Baked for 6m 20s with the duration in the number color |
| Slash commands | command output (/cost, /context, plugin commands) gets the same tables and code styling |
| Diagram hints | a short model-only note on each prompt so Claude reaches for diagrams, charts and figures when they help, and builds explaining replies around the pictures |
| Text | bold, italic, strikethrough, inline code, links, versions, durations, percentages and clickable paths in their own colors |
| Headings, lists, quotes | 4 heading styles, nested lists, task lists, quotes with an accent bar |
| Your prompts | what you type draws in a bubble, an accent bar or a chevron, so you find your turns when you scroll back, and clock adds when you sent it and when the turn finished |
| Right to left | Hebrew and Arabic read right to left, with bullets, quote bars and table columns mirrored |
| Other mods | $.prismantis.markdown draws any markdown the way replies are drawn, for mod authors |


Dark: catppuccin-mocha (default), dracula, nord, tokyo-night, gruvbox-dark, rose-pine, everforest, github-dark, one-dark, solarized-dark, neon.
Light: catppuccin-latte, gruvbox-light, rose-pine-dawn, github-light, solarized-light.
mono drops the palette for bold and dim; alerts keep their colors. Switch with /prismantis theme nord, or run /prismantis for the help screen with every theme. Every palette is MIT licensed and credited in THIRD_PARTY_NOTICES.md.

Header cells take the tableHeader color, and the default box style puts a double line under the header. tableStyle picks box (the default, every cell boxed), rules, grid or minimal. :---: and ---: alignment is honored, numbers in cells get the number color, and columns shrink to fit the terminal.


Each code block gets a header row: the language on the left, a copy button on the right. The code sits indented below with no frame, so selecting it with the mouse copies only the code.
bash, sh, zsh, fish, powershell, unlabeled) color the command word, --flags, quoted strings and # comments, and restart after |, && and ;.


Code blocks tagged mermaid draw as colored text art:
graph LR, graph TD, decisions), sequence, state, class and ER diagramsxychart-beta, sized to the terminal widthpie charts as a circle with a colored legend, largest slice first, and gantt schedules as bars on a shared date or time axis, starting on a half cell and ending on an eighth so close durations draw apartpieStyle picks how a pie draws. round falls back to bars in ascii mode, with more slices than the theme has distinct colors (mono always) or in a narrow terminal:
round (default) | bars |
|---|---|
| a circle, each slice in its own color, with a legend | one bar per slice, largest first, with its share |
![]() | ![]() |

Diagrams too wide for the window, or over 80 lines, stay as code. mermaidAscii swaps box-drawing characters for + - |.
Some things read better as a picture than as a diagram: a timeout racing a retry, the layout of a screen, a system before and after a change. Code blocks tagged figure draw line by line as written, in the theme's colors:

{dim:timeout at 10 s, handler books at 12 s, retry books again} {note:0 s} {note:10 s} {note:12 s} {note:later} {accent:▏─────────────▏─────▏─────────────────▏} Provider {accent:██████████████}{warn:✗} timeout {accent:█} retry Handler {ok:████████████████████} 200, nobody waits Bookings 0 {ok:1} {warn:2 twice}
{role:text} colors a run: accent for frames, lines and arrows (diagram color), warn for the break or the risk, ok for what is healthy or done, note for time and effort, dim for side notes (comment color), strong for the one thing that matters (strong color); the rest takes the diagram text color. warn, ok and note take the theme's reddest, greenest and most amber accent color, each a different one and none the diagram color, so a risk never looks like a frame line in any theme; hex and rgb() colors you set take part in that pick, and a role whose own slot (flag, string or heading color) you set to a color name or ansi256() keeps that colormono, warn draws boldfigure line 4: "⚠" may draw as an emoji, use a text glyph⧉ source copies the block as Claude wrote it, ⧉ art the drawn textmermaid is on or off; only the diagram hints note follows mermaid
Display math, $$…$$ on lines of its own or a `math block, draws as a typeset image in the theme's diagram text color, one formula per line. With copy buttons on, its ⧉ copy button copies the formula's LaTeX, since selecting an image copies blank cells. It needs RaTeX's PNG renderer, a single binary that typesets KaTeX syntax in a few milliseconds without TeX, a browser or Node:
gh release download -R erweixin/RaTeX -p 'ratex-cli-*-aarch64-apple-darwin.tar.gz'
tar -xzf ratex-cli-*.tar.gz
mkdir -p ~/.local/bin
install ratex-cli-*/render ~/.local/bin/ratex-render
Pick the archive for your platform (x86_64-apple-darwin, x86_64-unknown-linux-musl, ...). Any directory on your PATH works, but the file must be named ratex-render.
LaTeX is off until you set latex to true. Then prismantis runs ratex-render once in kitty and Ghostty, outside tmux, or wherever CLAUDE_CODE_FORCE_TERMINAL_IMAGES makes Claude Code draw images, such as a background session viewed in one of them, and keeps LaTeX on only if that test formula comes back. If a later run fails, formulas already drawn stay and new ones stay text until you /reload. A reply shown before the test finishes draws its formulas as text, then redraws them as images. Anywhere else, without the renderer, or with latex off, formulas draw as text in a math code block. So does a formula the renderer rejects, or one too wide for the terminal even at one row. While LaTeX is on, the diagram hints note also tells Claude that $$ math renders. Inline $…$ draws as italic text without its dollar signs, with common commands such as \rho, \cdot and \le shown as symbols; amounts like $5 stay as written.
Formula text matches the reply text. A terminal image fills whole rows, so a formula that falls between two row counts is rendered again with more padding rather than stretched.

When tables, diagrams and figures follow each other, they share a row and wrap once the terminal runs out of width. A wide terminal shows a table, a flowchart and two charts side by side.

⧉ md copies the original Markdown and ⧉ art a boxed table that pastes well into Slack. ⧉ html copies a formatted table (headers, alignment, inline formatting) plus a tab-separated plain-text copy.[ ⧉ copy ] on each. Code copies without its fences, lists as markdown, quotes without their > markers.⧉ source copies the mermaid or figure source, ⧉ art the drawn art.⧉ copy reply, which copies the reply as Claude wrote it. Selecting right-to-left text on screen copies letters in drawn order, not reading order./prismantis copy copies the last reply, /prismantis copy code its last code block.copyButtonStyle picks where the buttons sit. inline, the default, is the look above. hover puts a dim ⧉ beside each block's first row instead, at its left on a right-to-left block, and one in the reply's bottom-right corner for the whole reply. Pointing at a ⧉ draws its buttons over it, so they take no line and nothing moves when they show; the pointer on the block itself shows nothing. ctrl+x tab does not reach a hidden button, and the mobile app, which has no pointer, draws them inline.

⧉ html shows in a local macOS terminal or a Linux graphical session. macOS needs nothing extra. Linux needs CopyQ running (see its Wayland caveats). On Ubuntu:
sudo apt install -y copyq && copyq --start-server && copyq config autostart true
Clicking works where the terminal passes clicks through, as fullscreen mode does. Terminals with copy-on-select, such as Warp, may grab the word "copy" instead.


Each tool call draws as one line: a verb and its target, Ran with a colored shell command, Read and Edited with the path, which opens the file on click like a path in a reply (see Text). A status dot shows done, running or failed, and output still draws below. Edits draw as a diff card in the theme's colors, and so do files a shell command changed (sed -i, a script), one card per file headed by its path. A file Write creates is no diff, as in Claude Code's own preview: Created <path> (N lines) heads its first 10 lines as numbered code in the theme's colors, and a click anywhere on it, title or lines, or on +N more lines opens the rest; show less or another click folds it again. A diff card or a new file's preview with lines folded away opens the same way. A file an Edit or a shell command creates shows its first 10 lines as added diff lines under the same header. A file a shell command deletes is one Deleted <path> (N lines) line, and a click on it opens its removed lines. A file moved unchanged is one Renamed <old> → <new> line. Before Claude Code 2.1.295, files Write creates keep Claude Code's own preview, a new file's lines open with a +N more lines button and a deleted file's with a show N lines button. In the desktop app a click on the code lines does nothing; the +N more lines button does it. In diff cards added and unchanged lines are highlighted in the file's language, removed lines stay plain as in Claude Code, and when a line is edited rather than rewritten, the words that changed get a deeper tint. diffStyle picks the look: card (default) frames the lines in a rounded box, full drops the box and tints each changed line across the width, marks drops the tint and colors only the + and − marks, and bar puts a colored ▌ before each changed line.
card (default) | full | marks | bar |
|---|---|---|---|
| rounded box, tinted lines | no box, lines tinted across the width | no tint, colored + and − | no tint, a colored ▌ before each changed line |
![]() | ![]() | ![]() | ![]() |
Collapsed groups draw one line too: Ran 3 commands, read 2 files · last: npm test, with · N failed in the flag color when any call failed. Expand a group (ctrl+o or --verbose): shell calls keep their colored command with the output boxed below, and other calls use Claude Code's own rows. ctrl+o on a reply shows the original text.
toolStyle keeps tool rows apart from what Claude says:
chat (default) | tree-dim | tree-bold | classic |
|---|---|---|---|
| dimmed on the right, capped at 60% of the width | tucked under the sentence with ⎿, dimmed | tree-dim with one-line sentences in bold | bold verb and status dot, full brightness |
![]() | ![]() | ![]() | ![]() |
toolOutput: quiet shows what Claude did, not what it read: reads, searches and read-only shell commands draw one plain row like Read src/report.py lines 1–10 and nothing under it. Edits keep their diff and failures show their real error; the full rules are in docs/tool-output.md.


The line that closes a turn keeps Claude Code's word and colors the duration: ✻ Baked for 6m 20s. Terminal only, since that's the only surface that draws it.
Output from slash commands, built-in or from other plugins, is drawn like a reply, copy buttons included. Errors keep Claude Code's own red line.
Claude rarely writes a chart unless it knows the terminal can draw one. With diagramHints on (the default), each prompt you type or another plugin sends carries a short note that only the model reads. It says tables, alerts, code, mermaid diagrams and xychart-beta charts render here, and asks for commands in fenced blocks, since only those get a copy button. A second part describes figures: prefer one over mermaid when position carries meaning (durations racing on a time axis, a screen layout, phases, before and after), keep mermaid for plain flows and charts, and draw none for short answers, code changes or reports; the prose never retells the picture. When you ask Claude to explain, compare or plan something and pictures would make it easier to grasp, it builds the reply around them, with the core on the first screen as a picture or a sentence. Then come the role markup, at most 74 columns so a figure fits an 80-column window, glyphs one column wide, and edge ticks ▏ for a time axis so █ bars line up.
The note costs about 630 tokens per prompt: about 275 for the main part and about 360 for the figure part, plus about 80 while LaTeX math is on, when it also says $$ formulas render. All three are counted with Claude's tokenizer. It's off whenever mermaid is off, and skipped for the prompt a headless claude -p run starts with and for background notifications; a prompt another plugin sends inside such a run still carries it.


Bold, italic, strikethrough, inline code, links and bare URLs, clickable as terminal hyperlinks. Numbers, versions (v2.14.0), durations (250ms, 3h), sizes (16Gi) and percentages (99.9%) take the number color, and paths like ~/src/app.ts the path color.
Paths open their file or folder on click, as do file:// links that show their own path, from Claude Code 2.1.289 on. A path that starts with ~/, ./ or ../ links to its file, with ~ read as your home folder and ./ from the session's project folder. A path that starts with
hooks/register.tsx 847 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, PromptOrigin, Register, RenderElement, RenderSurface } from 'claude-code'
3
4import { clockText, endedAt, promptKey, sentAt, withRecord } from './clock'
5import type { Formula } from './latex'
6import { LATEX_DPR, LATEX_FONT_PX, MAX_IMAGE_BYTES, fitImage, fitsImage, imageFile, imageOf, keepFormulas, mathOf, padFor, pickFormula, pngSize, ratexColor, renderedOf } from './latex'
7import type { Block } from './markdown'
8import { nestedBlocks, parse } from './markdown'
9import type { ClipboardBackend } from './clipboard'
10import { clipboardCommand } from './clipboard'
11import { FIGURE_HINT } from './figure'
12import { drawDiagrams } from './mermaid'
13import type { CopyButton, DrawPaste, Fold, TerminalEnv } from './render'
14import { MARK, bashEdits, drawMath, drawsHyperlinks, editNotes, fileRoot, hasShellOutput, instanceKey, isReadOnlyCall, leftToEngine, markerRoom, mirrored, noteTip, pasteLang, pathsToProbe, remember, rememberCall, renderBashEdits, renderBlocks, renderDiffCard, renderExpandedShell, renderFailure, renderShellResult, renderToolGroup, renderToolRow, renderTurnDuration, renderUserPrompt, takesClickableMarks, takesEditorLinks, takesHttpLinks, withoutBashEdits } from './render'
15import type { SetupStep } from './help'
16import { HINT, ISSUE_HINT, SETUP_DONE, SETUP_PANE_KEYS, SETUP_PANE_OPENED, THEME_PREVIEW, findSetup, helpText, languageShowcase, rtlShowcaseText, setupParts, setupSteps, setupText, showcaseText } from './help'
17import { PRESET_NAMES } from './presets'
18import type { Style } from './theme'
19import { RANDOM_THEMES, pickTheme, resolveStyle } from './theme'
20import type { Terminal } from './rtl'
21import { ROW_MARK_TEXT, TERMINALS, hasRtl, opensLatin } from './rtl'
22
23const HINTED_ORIGINS = ['composer', 'bridge', 'plugin'] as const satisfies readonly PromptOrigin['kind'][]
24
25const takesHint = (origin: PromptOrigin): boolean => HINTED_ORIGINS.some(kind => kind === origin.kind)
26
27const LATEX_HINT = 'This terminal typesets LaTeX math: a formula in $$…$$ on lines of its own, or in a ```math block, renders as an image (KaTeX syntax). Inline $…$ does not render, so write inline math as plain text or Unicode.'
28
29const detectTerminal = async ($: EngineInterface): Promise<Terminal | null> => {
30 const program = await $.env.get('TERM_PROGRAM')
31 const term = await $.env.get('TERM')
32 if ((await $.env.get('KITTY_WINDOW_ID')) || term === 'xterm-kitty') return 'kitty'
33 if (program === 'Apple_Terminal') return 'apple-terminal'
34 if (program === 'WarpTerminal') return 'warp'
35 if (program === 'ghostty') return 'ghostty'
36 if (program === 'WezTerm') return 'wezterm'
37 if (program === 'vscode') return 'vscode'
38 if (program === 'iTerm.app') return 'iterm'
39 if (term === 'alacritty' || (await $.env.get('ALACRITTY_WINDOW_ID'))) return 'alacritty'
40 if (await $.env.get('WT_SESSION')) return 'windows-terminal'
41 if (await $.env.get('VTE_VERSION')) return 'gnome'
42 if (await $.env.get('KONSOLE_VERSION')) return 'konsole'
43 return null
44}
45
46const applyRtl = async ($: EngineInterface, style: Style): Promise<Terminal | null> => {
47 if (style.rtl === 'off') return null
48 if (style.rtl !== 'auto') return style.rtl
49 const terminal = await detectTerminal($)
50 style.reorder = terminal !== null
51 if (terminal) style.shape = TERMINALS[terminal]
52 return terminal
53}
54
55const expandedCalls = new Set<string>()
56const readOnlyCalls = new Set<string>()
57
58const columnsOf = (viewport?: { columns?: number }) => Math.max(20, (viewport?.columns ?? 100) - 4)
59
60const formulas = atom({ plugin: 'prismantis', key: 'formulas' } as const, {})
61const latexDir = atom({ plugin: 'prismantis', key: 'dir' } as const, '')
62const unfolded = atom({ plugin: 'prismantis', key: 'unfolded' } as const, [] as string[])
63const sent = atom({ plugin: 'prismantis', key: 'sent' } as const, [])
64const turnEnds = atom({ plugin: 'prismantis', key: 'turnEnds' } as const, [])
65const setupAt = atom({ plugin: 'prismantis', key: 'setupAt' } as const, 0)
66const setupFocus = atom({ plugin: 'prismantis', key: 'setupFocus' } as const, '')
67const setupLand = atom({ plugin: 'prismantis', key: 'setupLand' } as const, '')
68const foundPaths = atom({ plugin: 'prismantis', key: 'foundPaths' } as const, [])
69
70const firstDrawn = async ($: EngineInterface, id: string): Promise<number> => {
71 const ref = { plugin: 'prismantis', key: 'drawn', id } as const
72 const { value } = await $.state.get(ref)
73 if (value !== undefined) return value
74 const now = await $.clock.now()
75 $.clock.after(0, () => void $.state.set(ref, now, { ifVersion: 0 }))
76 return now
77}
78
79type Typeset = Exclude<Formula, { error: true }> & { tex: string }
80
81const showsImages = async ($: EngineInterface): Promise<boolean> => {
82 if (await $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES')) return true
83 if (await $.env.get('TMUX')) return false
84 const terminal = await detectTerminal($)
85 return terminal === 'kitty' || terminal === 'ghostty'
86}
87
88type Latex = { command: string; dir: string }
89type LatexSession = { style: Style; color: string; pending: Set<string>; wanted: Set<string>; batch: string[]; engine?: Promise<Latex | null>; ready?: Latex | null; stopped?: boolean; queue: Promise<void> }
90
91const formulaKey = (color: string, tex: string) => `${color}\0${tex}`
92
93const typeset = async ($: EngineInterface, color: string, engine: Latex, texs: string[], fontSize = LATEX_FONT_PX, dpr = LATEX_DPR): Promise<Formula[]> => {
94 const { stdout } = await $.process.run(
95 [engine.command, '--output-dir', engine.dir, '--color', color, '--background-color', 'transparent', '--font-size', String(fontSize), '--dpr', String(dpr)],
96 { stdin: `${texs.join('\n')}\n`, timeoutMs: 2000 },
97 )
98 const rendered = renderedOf(stdout)
99 return Promise.all(texs.map(async (_, i): Promise<Formula> => {
100 if (!rendered.has(i + 1)) return { error: true }
101 const png = await $.fs.read(`${engine.dir}/${String(i + 1).padStart(4, '0')}.png`, { as: 'bytes' }).then(r => r.base64, () => '')
102 const size = png ? pngSize(png) : null
103 return size && fitsImage(png) ? { png, ...size } : { error: true }
104 }))
105}
106
107const withPadding = async ($: EngineInterface, color: string, engine: Latex, texs: string[], results: Formula[]): Promise<Formula[]> => {
108 const padded: Formula[] = []
109 for (const [i, result] of results.entries()) {
110 const pad = 'png' in result ? padFor(result) : null
111 const [again] = pad ? await typeset($, color, engine, [texs[i]!], pad.fontSize, pad.dpr).catch((): Formula[] => []) : []
112 padded.push(again && 'png' in again && 'png' in result ? { ...result, padded: again } : result)
113 }
114 return padded
115}
116
117const startLatex = async ($: EngineInterface, latex: LatexSession): Promise<Latex | null> => {
118 if (!latex.style.latex || !(await $.session.surfaces()).includes('terminal') || !(await showsImages($))) return null
119 const tmp = (await $.env.get('TMPDIR')) ?? (await $.env.get('TEMP')) ?? '/tmp'
120 const suffix = (await read($, latexDir)) || crypto.randomUUID()
121 await update($, latexDir, () => suffix)
122 const engine = { command: 'ratex-render', dir: `${tmp.replace(/[\\/]+$/, '')}/prismantis-latex-${await $.session.id()}-${suffix}` }
123 const [check] = await typeset($, latex.color, engine, ['x^2'])
124 return check && 'png' in check ? engine : null
125}
126
127const latexEngine = ($: EngineInterface, latex: LatexSession): Promise<Latex | null> =>
128 (latex.engine ??= startLatex($, latex)
129 .catch(() => null)
130 .then(engine => {
131 latex.ready = engine
132 if (engine) $.ui.invalidate('ui.render')
133 return engine
134 }))
135
136const stopLatex = (latex: LatexSession) => {
137 latex.stopped = true
138 latex.pending.clear()
139 latex.batch = []
140}
141
142const typesetLater = async ($: EngineInterface, latex: LatexSession, texs: string[]): Promise<void> => {
143 const color = latex.color
144 const engine = await latexEngine($, latex)
145 if (!engine || latex.stopped) return
146 const results = await typeset($, color, engine, texs).then(
147 done => withPadding($, color, engine, texs, done),
148 () => null,
149 )
150 if (!results) return stopLatex(latex)
151 const fresh = texs.map((tex, i) => [formulaKey(color, tex), results[i]!] as const)
152 await update($, formulas, store => keepFormulas(store, fresh, latex.wanted))
153 latex.wanted.clear()
154 for (const tex of texs) latex.pending.delete(formulaKey(color, tex))
155}
156
157const mathOfBlocks = async ($: EngineInterface, latex: LatexSession, surface: string, blocks: Block[]): Promise<Map<number, Typeset>> => {
158 const maths = [...blocks.entries()].flatMap(([i, block]) => {
159 const tex = mathOf(block)
160 return tex === null ? [] : [{ i, tex, key: formulaKey(latex.color, tex) }]
161 })
162 if (surface !== 'terminal' || maths.length === 0) return new Map()
163 void latexEngine($, latex)
164 if (!latex.ready) return new Map()
165 for (const { key } of maths) latex.wanted.add(key)
166 const store = (await read($, formulas)) as Record<string, Formula>
167 const missing = latex.stopped ? [] : [...new Map(maths.map(({ key, tex }) => [key, tex]))].filter(([key]) => !store[key] && !latex.pending.has(key))
168 if (missing.length) {
169 if (latex.batch.length === 0) {
170 $.clock.after(0, () => {
171 const texs = latex.batch
172 latex.batch = []
173 latex.queue = latex.queue.then(() => typesetLater($, latex, texs)).catch(() => stopLatex(latex))
174 })
175 }
176 for (const [key, tex] of missing) {
177 latex.pending.add(key)
178 latex.batch.push(tex)
179 }
180 }
181 return new Map(maths.flatMap(({ i, tex, key }) => {
182 const formula = store[key]
183 return formula && 'png' in formula ? [[i, { tex, ...formula }] as const] : []
184 }))
185}
186
187type Picture = { png: string; width: number; height: number; alt: string }
188
189const pictureOf = async ($: EngineInterface, src: string, home: string): Promise<Omit<Picture, 'alt'> | null> => {
190 const file = imageFile(src, home)
191 if (!file) return null
192 const stat = 'path' in file ? await $.fs.stat(file.path).catch(() => null) : null
193 if ('path' in file && (stat?.kind !== 'file' || stat.size > MAX_IMAGE_BYTES)) return null
194 const png = 'png' in file ? file.png : await $.fs.read(file.path, { as: 'bytes' }).then(r => r.base64, () => '')
195 const size = png ? pngSize(png) : null
196 return size && size.width > 0 && size.height > 0 && fitsImage(png) ? { png, ...size } : null
197}
198
199const loaded = new Map<string, Promise<Omit<Picture, 'alt'> | null>>()
200
201const picturesOf = async ($: EngineInterface, style: Style, probes: Probes, surface: string, blocks: Block[]): Promise<Map<number, Picture>> => {
202 const images = [...blocks.entries()].flatMap(([i, block]) => {
203 const image = imageOf(block)
204 return image ? [{ i, ...image }] : []
205 })
206 if (surface !== 'terminal' || images.length === 0 || !(await (probes.images ??= showsImages($).catch(() => false)))) return new Map()
207 await locate($, style)
208 const found = await Promise.all(images.map(async ({ i, alt, src }) => {
209 const picture = await remember(loaded, src, () => pictureOf($, src, style.home), 50)
210 return picture ? [[i, { ...picture, alt }] as const] : []
211 }))
212 return new Map(found.flat())
213}
214
215const locate = async ($: EngineInterface, style: Style) => {
216 style.cwd = await $.session.root().catch(() => style.cwd)
217 style.home ||= (await $.env.get('HOME').catch(() => undefined)) ?? (await $.env.get('USERPROFILE').catch(() => undefined)) ?? ''
218}
219
220const htmlBackend = async ($: EngineInterface): Promise<ClipboardBackend | null> => {
221 if (await $.env.get('SSH_CONNECTION') || await $.env.get('SSH_TTY')) return null
222 if (await $.env.get('OS') === 'Windows_NT') return 'windows'
223 const helper = await $.fs.stat('/usr/bin/osascript').catch(() => null)
224 if (helper?.kind === 'file') return 'macos'
225 return await $.env.get('WAYLAND_DISPLAY') || await $.env.get('DISPLAY') ? 'linux' : null
226}
227
228type LinkReach = { http: boolean; editor: boolean; marks: boolean; files: string | null; paths: boolean }
229
230type Probes = { terminal?: Promise<Terminal | null>; htmlCopy?: Promise<ClipboardBackend | null>; links?: Promise<LinkReach>; images?: Promise<boolean> }
231
232const terminalEnv = async ($: EngineInterface): Promise<TerminalEnv> => ({
233 FORCE_HYPERLINK: await $.env.get('FORCE_HYPERLINK'),
234 TERM_PROGRAM: await $.env.get('TERM_PROGRAM'),
235 TERM_PROGRAM_VERSION: await $.env.get('TERM_PROGRAM_VERSION'),
236 TERM: await $.env.get('TERM'),
237 WT_SESSION: await $.env.get('WT_SESSION'),
238 LC_TERMINAL: await $.env.get('LC_TERMINAL'),
239 VTE_VERSION: await $.env.get('VTE_VERSION'),
240 TERMINAL_EMULATOR: await $.env.get('TERMINAL_EMULATOR'),
241})
242
243const overSsh = async ($: EngineInterface): Promise<boolean> => Boolean(await $.env.get('SSH_CONNECTION') || await $.env.get('SSH_TTY'))
244
245const fileRootOf = async ($: EngineInterface): Promise<string> => {
246 const distro = await $.env.get('WSL_DISTRO_NAME')
247 const linuxTerminal = distro !== undefined && Boolean(await $.env.get('VTE_VERSION') || await $.env.get('KONSOLE_VERSION') || await $.env.get('KITTY_WINDOW_ID'))
248 return fileRoot(linuxTerminal ? undefined : distro)
249}
250
251const readLinkReach = async ($: EngineInterface, style: Style): Promise<LinkReach> => {
252 const base = await $.session.version().then(v => v.base, () => undefined)
253 const http = takesHttpLinks(base)
254 if (http) await locate($, style)
255 const files = http && !(await overSsh($).catch(() => true)) ? await fileRootOf($).catch(() => 'file://') : null
256 return { http, editor: takesEditorLinks(base), marks: takesClickableMarks(base), files, paths: files !== null && drawsHyperlinks(await terminalEnv($).catch(() => ({}))) }
257}
258
259const linkReach = ($: EngineInterface, probes: Probes, style: Style): Promise<LinkReach> => (probes.links ??= readLinkReach($, style))
260
261type PathChecks = { asked: Set<string>; batch: string[]; list?: readonly string[]; found: ReadonlySet<string> }
262
263const MAX_FOUND = 2000
264
265const statPaths = async ($: EngineInterface, paths: string[]): Promise<void> => {
266 const kinds = await Promise.all(paths.map(path => $.fs.stat(path).then(stat => stat.kind, () => 'other')))
267 const hits = paths.filter((_, i) => kinds[i] !== 'other')
268 if (hits.length) await update($, foundPaths, list => [...list, ...hits].slice(-MAX_FOUND))
269}
270
271const askPaths = ($: EngineInterface, checks: PathChecks, paths: string[]) => {
272 for (const path of paths) {
273 if (checks.asked.has(path)) continue
274 if (checks.batch.length === 0) {
275 $.clock.after(0, () => {
276 const batch = checks.batch
277 checks.batch = []
278 void statPaths($, batch).catch(() => undefined)
279 })
280 }
281 checks.asked.add(path)
282 checks.batch.push(path)
283 }
284}
285
286const withFoundPaths = async ($: EngineInterface, checks: PathChecks, style: Style, blocks: Block[]): Promise<Style> => {
287 const paths = pathsToProbe(blocks, style)
288 if (paths.length === 0) return style
289 askPaths($, checks, paths)
290 const list = await read($, foundPaths)
291 if (list !== checks.list) {
292 checks.list = list
293 checks.found = new Set(list)
294 }
295 return { ...style, found: checks.found }
296}
297
298const fileCard = async ($: EngineInterface, el: ReturnType<EngineInterface['ui']['resolve']>, output: unknown, id: string, style: Style, probes: Probes, drawn: () => Style, columns?: number): Promise<RenderElement | undefined> => {
299 const press = (await linkReach($, probes, style)).marks
300 if (leftToEngine(output, press)) return undefined
301 await locate($, style)
302 return renderDiffCard(el, drawn(), output, folder($, el, await read($, unfolded), press), id, columns)
303}
304
305const probe = async ($: EngineInterface, style: Style, probes: Probes): Promise<Terminal | null> => {
306 probes.terminal ??= applyRtl($, style)
307 const terminal = await probes.terminal
308 probes.htmlCopy ??= htmlBackend($)
309 const before = style.htmlCopy
310 style.htmlCopy = await probes.htmlCopy
311 if (style.htmlCopy !== before) $.ui.invalidate('ui.render')
312 return terminal
313}
314
315const copyTable = async ($: EngineInterface, backend: ClipboardBackend, html: string, text: string): Promise<string | null> => {
316 const systemRoot = backend === 'windows' ? await $.env.get('SystemRoot') : undefined
317 const command = clipboardCommand(backend, html, text, systemRoot)
318 if (backend === 'windows' && !systemRoot) return command.failure
319 const result = await $.process.run(command.argv, { stdin: command.stdin, timeoutMs: 5000 }).catch(() => null)
320 if (!result) return command.failure
321 return result.exitCode === 0 ? null : result.stderr.trim() || command.failure
322}
323
324const folder = ($: EngineInterface, el: ReturnType<EngineInterface['ui']['resolve']>, open?: string[], faces = false): Fold => (id, hidden, key, look) => {
325 if (!open) return null
326 const folded = !open.includes(id)
327 const label = folded ? look?.label ?? `+${hidden} more lines` : 'show less'
328 const toggle = () => update($, unfolded, ids => (folded ? [...ids, id].slice(-500) : ids.filter(x => x !== id)))
329 if (!faces) return { folded, faced: false, element: <el.Button key={key} variant="secondary" label={label} onPress={toggle} /> }
330 const element = look?.face ? <el.Button key={key} plain label={label} onPress={toggle}>{look.face(folded)}</el.Button> : <el.Button key={key} variant="secondary" label={label} onPress={toggle} />
331 return { folded, faced: look?.face !== undefined, element, around: (rows, hover) => <el.Button key={`${key}.rows`} plain label={label} hover={hover} onPress={toggle}>{rows}</el.Button> }
332}
333
334const drawMarkdown = ($: EngineInterface, el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, blocks: ReturnType<typeof parse>, columns: number, math: Map<number, Typeset> = new Map(), pictures: Map<number, Picture> = new Map(), reply?: string, open?: string[], notes?: { id: string; press: boolean }): RenderElement[] => {
335 const { Button } = el
336 const copy = (text: string | (() => string), key: string, label = '⧉ copy', html?: () => string) => {
337 const copied = async (surface: RenderSurface): Promise<string> => {
338 const content = typeof text === 'function' ? text() : text
339 const backend = style.htmlCopy
340 const failure = html && backend ? await copyTable($, backend, html(), content) : undefined
341 if (failure === null) return 'Copied formatted table'
342 const result = await $.ui.copy({ text: content, surface })
343 if (!result.isCopied) return `Copy failed: ${result.reason}`
344 return failure ? `Copied as plain text (${failure})` : 'Copied'
345 }
346 return style.copyButtons && (!html || style.htmlCopy) ? (
347 <Button
348 key={key}
349 variant="primary"
350 label={label}
351 onPress={async press => $.ui.toast(await copied(press.surface).catch(() => 'Copy failed'))}
352 />
353 ) : null
354 }
355 const drawn = drawDiagrams(el, style, blocks, columns - markerRoom(style))
356 const Image = 'Image' in el ? el.Image : null
357 if (Image) {
358 for (const [i, formula] of math) {
359 const picked = pickFormula(formula, columns)
360 if (picked) drawn.set(i, { element: <Image key={`b${i}`} source={{ png: picked.picture.png }} columns={picked.fit.columns} rows={picked.fit.rows} alt={formula.tex} /> })
361 }
362 for (const [i, picture] of pictures) {
363 const fit = fitImage(picture, columns)
364 drawn.set(i, { element: <Image key={`b${i}`} source={{ png: picture.png }} columns={fit.columns} rows={fit.rows} alt={picture.alt} /> })
365 }
366 }
367 const tip = notes?.press ? noteTip(blocks, text => void $.ui.toast(text)) : undefined
368 const elements = renderBlocks(el, notes ? { ...style, noteKey: instanceKey(notes.id) } : style, blocks, columns, drawMath(el, style, blocks, drawn), copy, folder($, el, open), tip)
369 const button = reply === undefined ? null : copy(reply, 'reply', '⧉ copy reply')
370 if (!button) return elements
371 return [...elements, style.copyButtonStyle === 'hover' ? replyMarker(el, button, notes?.id) : <el.Box key="reply" alignSelf="flex-end">{button}</el.Box>]
372}
373
374const replyMarker = (el: ReturnType<EngineInterface['ui']['resolve']>, button: RenderElement, id?: string) => {
375 const scope = `copy:${id === undefined ? '' : instanceKey(id)}:reply`
376 return (
377 <el.Box key="reply" position="absolute" bottom={0} right={-MARK} hover={{ scope }}>
378 <el.Text dimColor>⧉</el.Text>
379 <el.Box position="absolute" top={0} right={0} display="none" hover={{ scope, display: 'flex' }}>{button}</el.Box>
380 </el.Box>
381 )
382}
383
384const THEME_ARGS = [...PRESET_NAMES, 'random']
385
386type Picked = { theme: string; options: PluginOptions; latex: LatexSession }
387
388const setTheme = async ($: EngineInterface, picked: Picked, name: string): Promise<string> => {
389 const result = await $.config.set({ key: `${$.plugin.name}.theme`, value: name })
390 if (result.deny) return `Could not switch theme: ${result.deny}`
391 if (name !== 'random' || picked.options.theme !== 'random') return `Theme set to ${name}.`
392 const others = RANDOM_THEMES.filter(t => t !== picked.theme)
393 picked.theme = others[Math.floor(Math.random() * others.length)]!
394 const style = picked.latex.style
395 style.theme = resolveStyle({ ...picked.options, theme: picked.theme }).theme
396 picked.latex.color = ratexColor(style.theme.diagramText ?? style.theme.codeText ?? '#808080')
397 $.ui.invalidate('ui.render')
398 return `Theme set to random: ${picked.theme} for now.\nkeep it: /prismantis theme ${picked.theme}`
399}
400
401const saveSetupPick = async ($: EngineInterface, picked: Picked, step: SetupStep, value: string): Promise<string> =>
402 step.key === 'theme' ? setTheme($, picked, value) : $.config.set({ key: `${$.plugin.name}.${step.key}`, value }).then(r => (r.deny ? `Could not save ${step.key}: ${r.deny}` : `${step.title} set to ${value}.`))
403
404const SETUP_PANE = 'prismantis-setup'
405
406const SETUP_PICK = 'pick:'
407const SETUP_LIST_COLUMNS = 30
408const SETUP_HEAD_ROWS = 8
409
410const openPane = ($: EngineInterface) => $.ui.open({ id: SETUP_PANE, title: 'prismantis setup', focus: true, closeOnEscape: true, rows: 40, columns: 90 })
411
412const openSetupPane = async ($: EngineInterface): Promise<string | undefined> => {
413 await update($, setupAt, () => 0)
414 await update($, setupFocus, () => '')
415 await update($, setupLand, () => '')
416 const opened = await openPane($)
417 if (opened.isPlaced) return SETUP_PANE_OPENED
418 await $.ui.close({ id: SETUP_PANE })
419 return undefined
420}
421
422const pickKey = (step: SetupStep, value: string) => `${SETUP_PICK}${step.name}:${value}`
423
424const showSetupStep = async ($: EngineInterface, at: number, step: SetupStep, value: string): Promise<void> => {
425 await update($, setupFocus, () => value)
426 await update($, setupLand, () => pickKey(step, value))
427 await update($, setupAt, () => at)
428}
429
430const pickInPane = async ($: EngineInterface, picked: Picked, at: number, value: string, currentOf: (step: SetupStep) => string): Promise<void> => {
431 const steps = setupSteps(PRESET_NAMES)
432 const step = steps[at]!
433 const nextStep = steps[at + 1]
434 const done = `${step.title} set to ${value}.`
435 if (nextStep) await showSetupStep($, at + 1, nextStep, currentOf(nextStep))
436 else await $.ui.close({ id: SETUP_PANE })
437 $.ui.toast(nextStep ? done : `${done} Setup done.`)
438 const saved = await saveSetupPick($, picked, step, value)
439 if (saved === done) return
440 $.ui.toast(saved)
441 if (!saved.startsWith('Could not')) return
442 await showSetupStep($, at, step, value)
443 if (!nextStep) await openPane($)
444}
445
446const landSetupFocus = ($: EngineInterface, key: string): void => {
447 $.clock.after(0, async () => {
448 await $.ui.focus({ requestId: SETUP_PANE, key }).catch(() => undefined)
449 await update($, setupLand, land => (land === key ? '' : land))
450 })
451}
452
453const setup = async ($: EngineInterface, picked: Picked, origin: PromptOrigin, stepName?: string, pick?: string): Promise<string> => {
454 const inTerminal = !stepName && origin.kind === 'composer' && (await $.session.surfaces()).includes('terminal')
455 const opened = inTerminal ? await openSetupPane($) : undefined
456 if (opened) return opened
457 const steps = setupSteps(PRESET_NAMES)
458 const at = stepName ? steps.findIndex(s => s.name === stepName) : 0
459 const step = steps[at]
460 if (!step) return `Unknown setup step "${stepName}". Steps: ${steps.map(s => s.name).join(', ')}`
461 if (!pick) return setupText(setupParts(PRESET_NAMES, at))
462 const choices = step.key === 'theme' ? THEME_ARGS : step.options
463 const value = /^\d+$/.test(pick) ? step.options[Number(pick) - 1] : pick
464 if (!value || !choices.includes(value)) return `Unknown ${step.name} pick "${pick}". Pick 1-${step.options.length} or one of: ${choices.join(', ')}`
465 const saved = await saveSetupPick($, picked, step, value)
466 if (saved.startsWith('Could not')) return saved
467 return `${saved}\n\n${at + 1 < steps.length ? setupText(setupParts(PRESET_NAMES, at + 1)) : SETUP_DONE}`
468}
469
470const SETUP_GIT_STATUS = [
471 'On branch main',
472 'Changes not staged for commit:',
473 ' (use "git add <file>..." to update what will be committed)',
474 ' modified: src/app.ts',
475 '',
476 'no changes added to commit (use "git add" and/or "git commit -a")',
477]
478const SETUP_BUILD_ERROR = [
479 '> app@1.4.0 build',
480 '> tsc',
481 ...[3, 7, 12, 18, 25, 31, 40, 44, 52, 60].map(line => `src/app.ts(${line},5): error TS2322: Type 'string' is not assignable to type 'number'.`),
482 'Found 10 errors in the same file, starting at: src/app.ts:3',
483]
484
485const toolOutputSample = (el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, value: string, id: string, columns: number): RenderElement[] => {
486 const status = { tool: 'Bash', input: { command: 'git status' }, isRunning: false, isErrored: false, isInterrupted: false }
487 const build = { tool: 'Bash', input: { command: 'npm run build', description: 'Build the app' }, isRunning: false, isErrored: true, isInterrupted: false }
488 const statusRow = <el.Box key={`${id}s`}>{renderToolRow(el, style, status, columns)}</el.Box>
489 const buildRow = <el.Box key={`${id}r`}>{renderToolRow(el, style, build, columns)}</el.Box>
490 if (value === 'quiet') return [statusRow, buildRow, renderFailure(el, style, SETUP_BUILD_ERROR.join('\n'), `${id}e`) ?? <el.Box key={`${id}e`} />]
491 const folded = (lines: readonly string[], keep: number, color?: string) => [
492 ...lines.slice(0, keep).map((line, i) => <el.Text key={`l${i}`} color={color}>{`${i === 0 ? ' ⎿ ' : ' '}${line}`}</el.Text>),
493 <el.Text key="more" dimColor>{` … +${lines.length - keep} lines (ctrl+o to expand)`}</el.Text>,
494 ]
495 return [
496 statusRow,
497 <el.Box key={`${id}so`} flexDirection="column">
498 {folded(SETUP_GIT_STATUS, 3)}
499 <el.Text key="allowed" dimColor>{' ⎿ Allowed by auto mode classifier'}</el.Text>
500 </el.Box>,
501 buildRow,
502 <el.Box key={`${id}e`} flexDirection="column">{folded(['Error: Exit code 2', ...SETUP_BUILD_ERROR], 10, style.theme.codeFlag)}</el.Box>,
503 ]
504}
505
506const SETUP_TABLE = '| Item | Qty |\n|:-----|----:|\n| Apples | 3 |\n| Pears | 5 |'
507const SETUP_SENT = new Date(2026, 0, 15, 14, 32).getTime()
508
509const copySample = (el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, value: string, id: string, columns: number): RenderElement[] => {
510 const label: CopyButton = (_text, key, name = '⧉ copy', html) => (html && !style.htmlCopy ? null : <el.Text key={key} bold>{`[ ${name} ]`}</el.Text>)
511 const table = renderBlocks(el, style, parse(SETUP_TABLE, { numbers: style.highlightNumbers, paths: style.highlightPaths }), columns, new Map(), label)
512 return [
513 <el.Box key={`${id}t`} flexDirection="column">{table}</el.Box>,
514 ...(value === 'hover' ? [<el.Text key={`${id}h`} dimColor>{'Its buttons show only while the pointer is on its ⧉.'}</el.Text>] : []),
515 ]
516}
517
518const clockSample = (el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, value: string, id: string, columns: number): RenderElement[] => {
519 const time = value === '24h' || value === '12h' ? clockText(SETUP_SENT, SETUP_SENT, value) : undefined
520 const prompt = style.promptStyle === 'off' ? <el.Text dimColor>{`> ${time === undefined ? '' : `[${time}] `}fix the failing test`}</el.Text> : renderUserPrompt(el, style, 'fix the failing test', columns, time)
521 return [<el.Box key={`${id}p`}>{prompt}</el.Box>, <el.Box key={`${id}d`}>{renderTurnDuration(el, style, 'Baked', 115000, time)}</el.Box>]
522}
523
524const SETUP_EDIT = {
525 filePath: 'src/config.ts',
526 structuredPatch: [{ oldStart: 12, newStart: 12, lines: [' export const config = {', '- retries: 3,', '- timeout: 5000,', '+ retries: 5,', '+ timeout: 10_000,', ' verbose: false,', ' }'] }],
527}
528
529const diffSample = (el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, id: string, columns: number): RenderElement[] => [
530 <el.Box key={`${id}r`}>{renderToolRow(el, style, { tool: 'Edit', input: { file_path: 'src/config.ts' }, isRunning: false, isErrored: false, isInterrupted: false }, columns)}</el.Box>,
531 <el.Box key={`${id}d`} flexDirection="column">{renderDiffCard(el, style, SETUP_EDIT, () => null, id, columns)}</el.Box>,
532]
533
534type SetupView = { el: ReturnType<EngineInterface['ui']['resolve']>; base: Style; options: PluginOptions; at: number; step: SetupStep; current: string; columns: number; rows: number; pick: (value: string) => void }
535
536const setupKeyboardPane = ($: EngineInterface, v: SetupView, focused: string, randomTheme: string): RenderElement => {
537 const { el, step } = v
538 const choices = step.key === 'theme' ? THEME_ARGS : step.options
539 const shown = choices.includes(focused) ? focused : v.current
540 const sampled = shown === 'random' ? randomTheme : shown
541 const parts = setupParts(PRESET_NAMES, v.at)
542 const options = parts.options.filter(o => o.value === sampled).map(o => (step.key === 'theme' ? { ...o, text: `${o.text.split('\n\n')[0]}\n\n${THEME_PREVIEW}` } : o))
543 const drawn = drawSetup($, el, v.base, v.options, { at: v.at, before: '', parts: { ...parts, options, tail: '' } }, Math.max(40, v.columns - SETUP_LIST_COLUMNS))
544 const buttons = choices.map(value => <el.Button key={pickKey(step, value)} label={value === v.current ? `${value} (now)` : value} variant={value === shown ? 'primary' : 'secondary'} autoFocus={value === v.current ? true : undefined} onPress={() => v.pick(value)} />)
545 const fits = choices.length + SETUP_HEAD_ROWS <= v.rows
546 return (
547 <el.Box flexDirection="column" rowGap={1} {...(fits ? { height: v.rows, overflow: 'hidden' as const } : {})}>
548 <el.Box flexDirection="column" flexShrink={0}>{drawn[0]}</el.Box>
549 <el.Box flexShrink={0}><el.Text dimColor>{SETUP_PANE_KEYS}</el.Text></el.Box>
550 <el.Box flexDirection="row" columnGap={4} flexShrink={1} overflow="hidden">
551 <el.Box flexDirection="column" flexShrink={0}>{buttons}</el.Box>
552 <el.Box flexDirection="column" flexGrow={1} overflow="hidden">
553 <el.Box flexDirection="column" flexShrink={0}>{drawn.slice(1, -1)}</el.Box>
554 </el.Box>
555 </el.Box>
556 </el.Box>
557 )
558}
559
560const drawSetup = ($: EngineInterface, el: ReturnType<EngineInterface['ui']['resolve']>, base: Style, options: PluginOptions, found: NonNullable<ReturnType<typeof findSetup>>, columns: number): RenderElement[] => {
561 const key = setupSteps(PRESET_NAMES)[found.at]!.key
562 const md = (style: Style, text: string, id: string) => <el.Box key={id} flexDirection="column" rowGap={1}>{drawMarkdown($, el, style, parse(text, { numbers: style.highlightNumbers, paths: style.highlightPaths }), columns)}</el.Box>
563 const sample = (style: Style, value: string, id: string): RenderElement[] => {
564 if (key === 'promptStyle') return [value === 'off' ? <el.Text key={id} dimColor>{'> fix the failing test'}</el.Text> : <el.Box key={id}>{renderUserPrompt(el, style, 'fix the failing test', columns)}</el.Box>]
565 if (key === 'toolStyle') return [md({ ...style, narration: style.toolStyle === 'tree-bold' }, 'Reading the config.', `${id}s`), <el.Box key={id}>{renderToolRow(el, style, { tool: 'Read', input: { file_path: 'src/config.ts' }, isRunning: false, isErrored: false, isInterrupted: false }, columns)}</el.Box>]
566 if (key === 'toolOutput') return toolOutputSample(el, style, value, id, columns)
567 if (key === 'diffStyle') return diffSample(el, style, id, columns)
568 if (key === 'copyButtonStyle') return copySample(el, style, value, id, columns)
569 if (key === 'clock') return clockSample(el, style, value, id, columns)
570 return []
571 }
572 const picks = found.parts.options.map(({ value, text }, i) => {
573 const style = key === 'theme' ? { ...base, theme: resolveStyle({ ...options, theme: value }).theme } : { ...base, [key]: value }
574 return <el.Box key={`o${i}`} flexDirection="column">{md(style, text, 'm')}{sample(style, value, 'x')}</el.Box>
575 })
576 return [...(found.before ? [md(base, found.before, 'before')] : []), md(base, found.parts.head, 'head'), ...picks, md(base, found.parts.tail, 'tail')]
577}
578
579const hintsFor = (style: Style, latex: LatexSession, nth: number): string[] => [
580 ...(style.diagramHints ? [HINT, FIGURE_HINT, ...(latex.ready && !latex.stopped ? [LATEX_HINT] : [])] : []),
581 ...(style.issueHint && nth % 10 === 0 ? [ISSUE_HINT] : []),
582]
583
584const localeOf = async ($: EngineInterface, asked?: string): Promise<string> => asked ?? (await $.env.get('LC_ALL').catch(() => undefined)) ?? (await $.env.get('LANG').catch(() => undefined)) ?? ''
585
586export const register: Register = (on, options) => {
587 on('engine.create', async (_$, e, next) => ({ ...(await next(e)), prismantis: { markdown: async () => undefined } }))
588 if (options.enabled === false) return
589 const firstTheme = pickTheme(options.theme)
590 const style = resolveStyle({ ...options, theme: firstTheme })
591 const parsed = new Map<string, ReturnType<typeof parse>>()
592 const parseCached = (text: string, cache = parsed, limit?: number) => remember(cache, text, () => parse(text, { numbers: style.highlightNumbers, paths: style.highlightPaths }), limit)
593 const shared = new Map<string, ReturnType<typeof parse>>()
594 let terminal: Terminal | null = null
595 const fit = (viewport?: { isFullscreen?: boolean }): Style => (terminal === 'apple-terminal' && viewport?.isFullscreen ? { ...style, shape: 'inverse' } : style)
596 let prompts = 0
597 const latex: LatexSession = { style, color: ratexColor(style.theme.diagramText ?? style.theme.codeText ?? '#808080'), pending: new Set(), wanted: new Set(), batch: [], queue: Promise.resolve() }
598 const picked: Picked = { theme: firstTheme, options, latex }
599 const probes: Probes = {}
600 const pathChecks: PathChecks = { asked: new Set(), batch: [], found: new Set() }
601 const forSurface = (base: Style, surface: RenderSurface, links: LinkReach): Style => {
602 const drawn = surface === 'terminal' ? (links.http || links.editor ? { ...base, httpLinks: links.http, editorLinks: links.editor, fileLinks: links.files, pathLinks: links.paths } : base) : { ...base, htmlCopy: null, nativeCode: true, gridFace: surface === 'desktop' }
603 return surface === 'mobile' && drawn.copyButtonStyle === 'hover' ? { ...drawn, copyButtonStyle: 'inline' } : drawn
604 }
605 const fullWidth = (text: string) => (style.reorder && hasRtl(text) ? { width: '100%' as const } : {})
606
607 const quiet = style.toolOutput === 'quiet'
608 const shellCommands = new Map<string, string>()
609 const noteCommand = (id: string | undefined, tool: string, input: unknown) => {
610 const command = tool === 'Bash' && input !== null && typeof input === 'object' ? (input as { command?: unknown }).command : undefined
611 if (!id || typeof command !== 'string') return
612 shellCommands.delete(id)
613 shellCommands.set(id, command)
614 if (shellCommands.size > 500) shellCommands.delete(shellCommands.keys().next().value!)
615 }
616 let firstEdit: string | undefined
617 if (options.toolRows !== false) {
618 on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
619 await locate($, style)
620 for (const call of e.props.calls) noteCommand(call.tool_use_id, call.tool, call.input)
621 if (quiet) for (const call of e.props.calls) if (call.tool_use_id && isReadOnlyCall(call.tool, call.input)) rememberCall(readOnlyCalls, call.tool_use_id)
622 if (e.props.isExpanded) {
623 for (const call of e.props.calls) if (call.tool_use_id) rememberCall(expandedCalls, call.tool_use_id, 500)
624 return next(e)
625 }
626 return renderToolGroup($.ui.resolve(e), forSurface(fit(e.viewport), e.surface, await linkReach($, probes, style)), e.props.calls, e.props.isActive, e.viewport?.columns)
627 })
628 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
629 await locate($, style)
630 noteCommand(e.props.tool_use_id, e.props.tool, e.props.input)
631 if (quiet && isReadOnlyCall(e.props.tool, e.props.input)) rememberCall(readOnlyCalls, e.props.tool_use_id)
632 if (!expandedCalls.has(e.props.tool_use_id)) return renderToolRow($.ui.resolve(e), forSurface(fit(e.viewport), e.surface, await linkReach($, probes, style)), e.props, e.viewport?.columns)
633 const shell = e.props.tool === 'Bash' || e.props.tool === 'PowerShell'
634 return shell && typeof e.props.output !== 'string' ? renderExpandedShell($.ui.resolve(e), fit(e.viewport), e.props, e.viewport?.columns) : next(e)
635 })
636 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
637 const cards = (): Style => ({ ...fit(e.viewport), pressPreview: e.surface === 'terminal' })
638 if ((e.props.tool === 'Edit' || e.props.tool === 'Write') && !e.props.isErrored) return (await fileCard($, $.ui.resolve(e), e.props.output, e.props.tool_use_id, style, probes, cards, e.viewport?.columns)) ?? next(e)
639 const edits = e.props.tool === 'Bash' && !e.props.isErrored ? bashEdits(e.props.output) : undefined
640 if (edits) {
641 await locate($, style)
642 const el = $.ui.resolve(e)
643 const output = withoutBashEdits(e.props.output)
644 const above = !hasShellOutput(output) ? null : quiet ? renderShellResult(el, fit(e.viewport), output) : await next({ ...e, props: { ...e.props, output } })
645 firstEdit ??= e.props.tool_use_id
646 const notes = editNotes(edits, firstEdit === e.props.tool_use_id, shellCommands.get(e.props.tool_use_id))
647 const drawn = renderBashEdits(el, forSurface(cards(), e.surface, await linkReach($, probes, style)), edits, folder($, el, await read($, unfolded), (await linkReach($, probes, style)).marks), e.props.tool_use_id, above !== null, notes, e.viewport?.columns)
648 return above === null ? drawn : <el.Box flexDirection="column">{above}{drawn}</el.Box>
649 }
650 if (!quiet) return next(e)
651 await locate($, style)
652 const el = $.ui.resolve(e)
653 const shell = e.props.tool === 'Bash' || e.props.tool === 'PowerShell'
654 const out = (e.props.output ?? {}) as Record<string, unknown>
655 if (shell && (out.backgroundTaskId || out.isImage || out.interrupted)) return next(e)
656 if (e.props.isErrored) return renderFailure(el, fit(e.viewport), e.props.output) ?? next(e)
657 if (readOnlyCalls.has(e.props.tool_use_id)) return <el.Box />
658 return shell ? renderShellResult(el, fit(e.viewport), e.props.output) : next(e)
659 })
660 }
661
662 on('tool.call', async (_$, e, next) => {
663 const done = await next(e)
664 pathChecks.asked = new Set(pathChecks.found)
665 return done
666 })
667
668 on('session.start', async ($, e, next) => {
669 terminal = await probe($, style, probes)
670 void latexEngine($, latex)
671 const started = await next(e)
672 await $.command
673 .register({ name: 'prismantis', description: 'Switch the prismantis theme, pick styles from samples, copy the last reply, or show the demo', argumentHint: '[theme [<name> | random] | setup [<step> [<pick>]] | copy [code] | demo]' })
674 .catch(() => undefined)
675 return started
676 })
677
678 on('command.run', { command: 'prismantis' }, async ($, e) => {
679 const [first, second, third] = e.args.trim().split(/\s+/)
680 const [sub, name] = THEME_ARGS.includes(first ?? '') ? ['theme', first] : [first, second]
681 if (sub === 'demo') return { text: showcaseText(PRESET_NAMES) + languageShowcase(await localeOf($, name)) }
682 if (sub === 'setup') return { text: await setup($, picked, e.origin, name, third) }
683 if (sub === 'copy') {
684 const reply = (await $.session.messages()).findLast(m => m.role === 'assistant' && m.text.trim())
685 if (!reply) return { text: 'Nothing to copy yet.' }
686 const code = name === 'code' ? nestedBlocks(parseCached(reply.text)).findLast(b => b.kind === 'code') : undefined
687 if (name === 'code' && code?.kind !== 'code') return { text: 'The last reply has no code block.' }
688 const result = await $.ui.copy({ text: code?.kind === 'code' ? code.lines.join('\n') : reply.text })
689 return { text: result.isCopied ? `Copied the last ${code ? 'code block' : 'reply'}.` : `Copy failed: ${result.reason}` }
690 }
691 if (sub === 'demo-rtl') {
692 terminal = await probe($, style, probes)
693 return { text: rtlShowcaseText() }
694 }
695 if (sub !== 'theme') return { text: helpText(PRESET_NAMES) }
696 if (!name) return { text: options.theme === 'random' ? `current: ${picked.theme} (random)\nkeep it: /prismantis theme ${picked.theme}` : `current: ${picked.theme}` }
697 if (!THEME_ARGS.includes(name)) return { text: `Unknown theme "${name}". Themes: ${PRESET_NAMES.join(', ')}, random` }
698 return { text: await setTheme($, picked, name) }
699 })
700
701 on('ui.render', { component: 'TurnDuration' }, async ($, e) => {
702 const at = style.clock === 'off' ? undefined : endedAt(await read($, turnEnds), e.props.durationMs, await firstDrawn($, e.requestId))
703 const time = at === undefined ? undefined : clockText(at, await $.clock.now(), style.clock)
704 return renderTurnDuration($.ui.resolve(e), style, e.props.word, e.props.durationMs, time)
705 })
706
707 on('turn.complete', async ($, e, next) => {
708 if (style.clock !== 'off' && e.agentId === undefined) {
709 const at = await $.clock.now()
710 await update($, turnEnds, list => withRecord(list, { durationMs: e.durationMs, at }))
711 }
712 return next(e)
713 })
714
715 on('prompt.submit', async ($, e, next) => {
716 if (style.clock !== 'off' && (e.origin.kind === 'composer' || e.origin.kind === 'bridge')) {
717 const at = await $.clock.now()
718 await update($, sent, list => withRecord(list, { text: promptKey(e.text), at }))
719 }
720 terminal = await probe($, style, probes)
721 if (!takesHint(e.origin)) return next(e)
722 if (style.diagramHints) void latexEngine($, latex)
723 const hints = hintsFor(style, latex, prompts++)
724 return hints.length ? next({ ...e, context: [...(e.context ?? []), ...hints] }) : next(e)
725 })
726
727 let landing = ''
728 const currentOf = (step: SetupStep): string => (step.key === 'theme' ? (options.theme === 'random' ? 'random' : picked.theme) : String(style[step.key]))
729
730 on('ui.focus', async ($, e, next) => {
731 if (e.component === 'Pane' && e.requestId === SETUP_PANE && e.element?.startsWith(SETUP_PICK)) await update($, setupFocus, () => e.element!.slice(e.element!.indexOf(':', SETUP_PICK.length) + 1))
732 return next(e)
733 })
734
735 on('ui.scroll', { component: 'Pane', requestId: SETUP_PANE }, async ($, e, next) => {
736 if (e.origin.kind !== 'person' || e.pointer || Math.abs(e.by) !== 1) return next(e)
737 const steps = setupSteps(PRESET_NAMES)
738 const step = steps[Math.min(await read($, setupAt), steps.length - 1)]!
739 const choices = step.key === 'theme' ? THEME_ARGS : step.options
740 const focused = await read($, setupFocus)
741 const at = choices.indexOf(choices.includes(focused) ? focused : currentOf(step))
742 const target = choices[at + e.by]
743 if (target === undefined) return next(e)
744 await $.ui.focus({ requestId: SETUP_PANE, key: pickKey(step, target) }).catch(() => undefined)
745 return {}
746 })
747
748 on('ui.render', { component: 'Pane', requestId: SETUP_PANE }, async ($, e) => {
749 const steps = setupSteps(PRESET_NAMES)
750 const at = Math.min(await read($, setupAt), steps.length - 1)
751 const step = steps[at]!
752 const land = await read($, setupLand)
753 if (land !== landing) {
754 landing = land
755 if (land) landSetupFocus($, land)
756 }
757 const base = { ...forSurface(fit(e.viewport), e.surface, await linkReach($, probes, style)), copyButtons: false, pathLinks: false }
758 const view: SetupView = { el: $.ui.resolve(e), base, options, at, step, current: currentOf(step), columns: e.props.bodyColumns, rows: e.props.scroll.bodyRows, pick: value => void pickInPane($, picked, at, value, currentOf) }
759 return setupKeyboardPane($, view, await read($, setupFocus), picked.theme)
760 })
761
762 on('ui.render', { component: 'InfoNotice' }, async (_$, e, next) =>
763 mirrored(style) && hasRtl(e.props.text) && opensLatin(e.props.text) ? next({ ...e, props: { ...e.props, text: ROW_MARK_TEXT + e.props.text } }) : next(e))
764
765 on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
766 if (e.props.isErrored) return next(e)
767 if (e.props.text.includes('\u001b')) return next(e)
768 const found = e.props.command === 'prismantis' ? findSetup(PRESET_NAMES, e.props.text) : undefined
769 if (found) {
770 const el = $.ui.resolve(e)
771 const base = { ...forSurface(fit(e.viewport), e.surface, await linkReach($, probes, style)), copyButtons: false, pathLinks: false }
772 return <el.Box flexDirection="column" rowGap={1}>{drawSetup($, el, base, options, found, columnsOf(e.viewport))}</el.Box>
773 }
774 const blocks = parseCached(e.props.text)
775 if (blocks.length === 0) return next(e)
776 const el = $.ui.resolve(e)
777 const { Box } = el
778 const reach = await linkReach($, probes, style)
779 const math = await mathOfBlocks($, latex, e.surface, blocks)
780 const pictures = await picturesOf($, style, probes, e.surface, blocks)
781 const open = await read($, unfolded)
782 const surfaceStyle = await withFoundPaths($, pathChecks, forSurface(fit(e.viewport), e.surface, reach), blocks)
783 return <Box flexDirection="column" rowGap={1} {...fullWidth(e.props.text)}>{drawMarkdown($, el, surfaceStyle, blocks, columnsOf(e.viewport), math, pictures, undefined, open, { id: e.requestId, press: reach.marks })}</Box>
784 })
785
786 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
787 const kind = e.props.origin.kind
788 const own = kind === 'composer' || kind === 'bridge' || (kind === 'unclassified' && !e.props.from && !e.props.task)
789 if (!own) return next(e)
790 const at = style.clock === 'off' ? undefined : sentAt(await read($, sent), e.props.text, await firstDrawn($, e.requestId))
791 const time = at === undefined ? undefined : clockText(at, await $.clock.now(), style.clock)
792 if (style.promptStyle === 'off') return time === undefined ? next(e) : next({ ...e, props: { ...e.props, text: `[${time}] ${e.props.text}` } })
793 const el = $.ui.resolve(e)
794 const drawn = forSurface(fit(e.viewport), e.surface, await linkReach($, probes, style))
795 const columns = columnsOf(e.viewport)
796 const open = await read($, unfolded)
797 const paste: DrawPaste = (body, key) => {
798 const lines = body.split('\n')
799 const title = `pasted text · ${lines.length} lines`
800 const toggle = folder($, el, open)(`${e.requestId}:${key}`, lines.length, key, { label: title })
801 const opened = toggle?.folded === false
802 return (
803 <el.Box key={key} borderStyle="double" borderColor={drawn.theme.codeComment} paddingX={1} flexDirection="column" alignSelf="flex-start">
804 {opened ? <el.Box key="head" flexDirection="row" justifyContent="space-between" columnGap={4}><el.Text color={drawn.theme.codeComment}>{title}</el.Text>{toggle.element}</el.Box> : toggle?.element ?? null}
805 {opened ? drawMarkdown($, el, drawn, [{ kind: 'code', lang: pasteLang(body), lines, raw: body }], columns - 8, undefined, undefined, undefined, open) : null}
806 </el.Box>
807 )
808 }
809 return renderUserPrompt(el, drawn, e.props.text, columns, time, paste)
810 })
811
812 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
813 const blocks = parseCached(e.props.text)
814 if (blocks.length === 0) return next(e)
815 const el = $.ui.resolve(e)
816 const { Box, Text } = el
817 const narration = style.toolStyle === 'tree-bold' && blocks.length === 1 && blocks[0]!.kind === 'paragraph'
818 const reach = await linkReach($, probes, style)
819 const math = await mathOfBlocks($, latex, e.surface, blocks)
820 const pictures = await picturesOf($, style, probes, e.surface, blocks)
821 const surfaceStyle = await withFoundPaths($, pathChecks, forSurface(fit(e.viewport), e.surface, reach), blocks)
822 const open = await read($, unfolded)
823 const reply = blocks.length > 1 || hasRtl(e.props.text) ? e.props.text : undefined
824 const corner = reply !== undefined && markerRoom(surfaceStyle) > 0
825 return (
826 <Box key="msg" flexDirection="row">
827 <Box width={2} flexShrink={0}>
828 <Text color={style.theme.accent}>{e.props.isFirstOfReply ? '●' : ' '}</Text>
829 </Box>
830 <Box flexDirection="column" rowGap={1} flexGrow={1}>
831 {drawMarkdown($, el, narration ? { ...surfaceStyle, narration } : surfaceStyle, blocks, columnsOf(e.viewport), math, pictures, reply, open, { id: e.requestId, press: reach.marks })}
832 </Box>
833 {corner ? <Box width={MARK} flexShrink={0} /> : null}
834 </Box>
835 )
836 })
837
838 on('prismantis.markdown', async ($, e, next) => {
839 const blocks = parseCached(e.text, shared, 20)
840 if (blocks.length === 0) return next(e)
841 const el = $.ui.resolve({ surface: e.surface, component: 'AssistantMessage' })
842 const { Box } = el
843 const surfaceStyle = forSurface(style, e.surface, await linkReach($, probes, style))
844 return { value: <Box flexDirection="column" rowGap={1} {...fullWidth(e.text)}>{drawMarkdown($, el, { ...surfaceStyle, copyButtons: false }, blocks, Math.max(20, e.columns || 0))}</Box> }
845 })
846}
847hooks/clock.ts 39 lines1import type { Clock } from './theme'
2
3export type Sent = { text: string; at: number }
4export type TurnEnd = { durationMs: number; at: number }
5
6const KEEP = 500
7const SLACK_MS = 2000
8const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
9
10const two = (n: number) => String(n).padStart(2, '0')
11
12export const clockText = (at: number, now: number, clock: Clock): string => {
13 const d = new Date(at)
14 const h = d.getHours()
15 const time = clock === '12h' ? `${h % 12 === 0 ? 12 : h % 12}:${two(d.getMinutes())} ${h < 12 ? 'AM' : 'PM'}` : `${two(h)}:${two(d.getMinutes())}`
16 const today = new Date(now)
17 const isToday = d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth() && d.getDate() === today.getDate()
18 return isToday ? time : `${MONTHS[d.getMonth()]} ${d.getDate()} ${time}`
19}
20
21export const promptKey = (text: string) => text.trim().replace(/\s+/g, ' ').slice(0, 300)
22
23export const withRecord = <T>(list: readonly T[], record: T): T[] => [...list, record].slice(-KEEP)
24
25export const sentAt = (sent: readonly Sent[], text: string, drawnAt: number): number | undefined => {
26 const key = promptKey(text)
27 return sent.findLast(one => one.text === key && one.at <= drawnAt)?.at
28}
29
30export const endedAt = (ends: readonly TurnEnd[], durationMs: number, drawnAt: number): number | undefined => {
31 let best: TurnEnd | undefined
32 for (const end of ends) {
33 if (end.at > drawnAt) continue
34 const gap = Math.abs(end.durationMs - durationMs)
35 if (gap <= SLACK_MS && (best === undefined || gap <= Math.abs(best.durationMs - durationMs))) best = end
36 }
37 return best?.at
38}
39hooks/latex.ts 136 lines1import type { Block } from './markdown'
2
3type Picture = { png: string; width: number; height: number }
4
5export type Formula = (Picture & { padded?: Picture }) | { error: true }
6
7type Size = { width: number; height: number }
8type Fit = { columns: number; rows: number }
9
10export const LATEX_FONT_PX = 80
11export const LATEX_DPR = 1
12const PX_PER_ROW = LATEX_FONT_PX * LATEX_DPR
13const CELL_RATIO = 0.5
14const RATEX_MARGIN_PX = 10
15export const MAX_IMAGE_BYTES = 2 * 1024 * 1024
16
17const ANSI16 = ['000000', 'cd0000', '00cd00', 'cdcd00', '0000ee', 'cd00cd', '00cdcd', 'e5e5e5', '7f7f7f', 'ff0000', '00ff00', 'ffff00', '5c5cff', 'ff00ff', '00ffff', 'ffffff']
18const ANSI_NAMES = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
19
20const hex = (...rgb: number[]): string => `#${rgb.map(n => Math.max(0, Math.min(255, n)).toString(16).padStart(2, '0')).join('')}`
21
22const ansi256 = (n: number): string => {
23 if (n < 16) return `#${ANSI16[n]}`
24 const level = (v: number) => (v ? 55 + v * 40 : 0)
25 if (n < 232) return hex(level(Math.floor((n - 16) / 36)), level(Math.floor((n - 16) / 6) % 6), level((n - 16) % 6))
26 const gray = 8 + (n - 232) * 10
27 return hex(gray, gray, gray)
28}
29
30export const ratexColor = (color: string): string => {
31 const c = color.trim()
32 const rgb = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i.exec(c)
33 if (rgb) return hex(...rgb.slice(1).map(Number))
34 const ansi = /^ansi256\((\d+)\)$/i.exec(c)
35 if (ansi) return ansi256(Number(ansi[1]))
36 const name = /^(black|red|green|yellow|blue|magenta|cyan|white|gray|grey)(bright)?$/i.exec(c)
37 if (!name?.[2]) return c
38 const base = name[1]!.toLowerCase()
39 return `#${ANSI16[base === 'gray' || base === 'grey' ? 8 : ANSI_NAMES.indexOf(base) + 8]}`
40}
41
42const MAX_FORMULAS = 50
43
44export const keepFormulas = <T,>(store: Record<string, T>, fresh: readonly (readonly [string, T])[], wanted: ReadonlySet<string>): Record<string, T> => {
45 const added = new Set(fresh.map(([key]) => key))
46 const entries = [...Object.entries(store).filter(([key]) => !added.has(key)), ...fresh]
47 const spare = entries.filter(([key]) => !wanted.has(key) && !added.has(key)).map(([key]) => key)
48 const dropped = new Set(spare.slice(0, Math.max(0, entries.length - MAX_FORMULAS)))
49 return Object.fromEntries(entries.filter(([key]) => !dropped.has(key)))
50}
51
52export const fitsImage = (base64: string): boolean => (base64.length * 3) / 4 <= MAX_IMAGE_BYTES
53
54const naturalRows = (size: Size): number => size.height / PX_PER_ROW
55
56export const padFor = (size: Size): { rows: number; fontSize: number; dpr: number } | null => {
57 const natural = naturalRows(size)
58 const below = Math.floor(natural)
59 const above = Math.max(1, Math.ceil(natural))
60 if ((below >= 1 && below / natural >= 0.9) || above / natural <= 1.05) return null
61 const dpr = LATEX_DPR + (above * PX_PER_ROW - size.height) / (2 * RATEX_MARGIN_PX)
62 return { rows: above, fontSize: PX_PER_ROW / dpr, dpr }
63}
64
65export const mathOf = (block: Block): string | null => {
66 if (block.kind !== 'code' || block.lang.toLowerCase() !== 'math' || block.isOpen) return null
67 const tex = block.lines.map(line => line.replace(/(^|[^\\])%.*$/, '$1')).join(' ').replace(/\s+/g, ' ').trim()
68 return tex === '' || tex.startsWith('#') ? null : tex
69}
70
71export const pngSize = (base64: string): Size | null => {
72 const head = atob(base64.slice(0, 32))
73 if (!head.startsWith('\x89PNG')) return null
74 const word = (at: number) => [0, 1, 2, 3].reduce((n, i) => n * 256 + head.charCodeAt(at + i), 0)
75 return { width: word(16), height: word(20) }
76}
77
78const rowsOf = (size: Size): number => Math.min(255, Math.max(1, Math.round(naturalRows(size))))
79
80const fitFormula = (size: Size, columns: number): Fit | null => {
81 const aspect = size.width / size.height / CELL_RATIO
82 const room = Math.min(255, columns - 2)
83 let rows = rowsOf(size)
84 while (rows > 1 && Math.round(aspect * rows) > room) rows--
85 const width = Math.max(1, Math.round(aspect * rows))
86 return width <= room ? { columns: width, rows } : null
87}
88
89export const pickFormula = (formula: Exclude<Formula, { error: true }>, columns: number): { picture: Picture; fit: Fit } | null => {
90 if (formula.padded) {
91 const fit = fitFormula(formula.padded, columns)
92 if (fit && fit.rows === rowsOf(formula.padded)) return { picture: formula.padded, fit }
93 }
94 const fit = fitFormula(formula, columns)
95 return fit ? { picture: formula, fit } : null
96}
97
98export const renderedOf = (stdout: string): Set<number> => new Set([...stdout.matchAll(/^OK\s+(\d+)\s/gm)].map(m => Number(m[1])))
99
100const IMAGE_PX_PER_COLUMN = 10
101const IMAGE_MAX_ROWS = 20
102
103export const imageOf = (block: Block): { alt: string; src: string } | null => {
104 if (block.kind !== 'paragraph') return null
105 const [only, ...rest] = block.inline.filter(n => n.kind !== 'text' || n.text.trim())
106 return only?.kind === 'image' && rest.length === 0 ? { alt: only.text, src: only.src } : null
107}
108
109const local = (path: string): { path: string } | null => (path.replace(/\\/g, '/').startsWith('//') ? null : { path })
110
111const decoded = (text: string): string | null => {
112 try {
113 return decodeURIComponent(text)
114 } catch {
115 return null
116 }
117}
118
119export const imageFile = (src: string, home: string): { png: string } | { path: string } | null => {
120 const data = /^data:image\/png;base64,([A-Za-z0-9+/]{32,}=*)$/i.exec(src)
121 if (data) return { png: data[1]! }
122 if (/^file:\/\//i.test(src)) {
123 const path = decoded(src.slice(7))?.replace(/^localhost(?=\/)/i, '')
124 return path?.startsWith('/') ? local(path) : null
125 }
126 if (src.startsWith('~/')) return home ? { path: `${home}${src.slice(1)}` } : null
127 return /^[a-z][a-z0-9+.-]*:/i.test(src) ? null : local(src)
128}
129
130export const fitImage = (size: Size, columns: number): Fit => {
131 const aspect = size.width / size.height / CELL_RATIO
132 const wide = Math.max(1, Math.min(255, columns - 2, Math.ceil(size.width / IMAGE_PX_PER_COLUMN)))
133 const rows = Math.max(1, Math.min(IMAGE_MAX_ROWS, Math.round(wide / aspect)))
134 return { columns: Math.max(1, Math.min(wide, Math.round(rows * aspect))), rows }
135}
136hooks/markdown.ts 471 lines1export type Inline =
2 | { kind: 'text'; text: string }
3 | { kind: 'strong'; children: Inline[] }
4 | { kind: 'emphasis'; children: Inline[] }
5 | { kind: 'strike'; children: Inline[] }
6 | { kind: 'code'; text: string; href?: string }
7 | { kind: 'math'; text: string }
8 | { kind: 'link'; text: string; href: string }
9 | { kind: 'image'; text: string; src: string }
10 | { kind: 'number'; text: string }
11 | { kind: 'path'; text: string; href?: string }
12 | { kind: 'dim'; text: string }
13 | { kind: 'footnote'; text: string; note?: number }
14
15export type Note = { mark: string; inline: Inline[]; note: number }
16
17export type Block = { raw: string } & (
18 | { kind: 'heading'; level: number; inline: Inline[] }
19 | { kind: 'paragraph'; inline: Inline[] }
20 | { kind: 'list'; ordered: boolean; items: ListItem[] }
21 | { kind: 'code'; lang: string; lines: string[]; isOpen?: true }
22 | { kind: 'quote'; blocks: Block[] }
23 | { kind: 'alert'; level: AlertLevel; blocks: Block[] }
24 | { kind: 'rule' }
25 | { kind: 'table'; header: Inline[][]; align: ('left' | 'right' | 'center')[]; rows: Inline[][][] }
26 | { kind: 'notes'; notes: Note[] }
27)
28
29export type ListItem = { marker: string; depth: number; task?: boolean; inline: Inline[]; blocks?: Block[] }
30
31type Draft = Block extends infer B ? (B extends unknown ? Omit<B, 'raw'> : never) : never
32
33export type AlertLevel = 'note' | 'tip' | 'important' | 'warning' | 'caution'
34const ALERT = /^\[!(note|tip|important|warning|caution)\]\s*(.*)$/i
35
36export type Highlight = { numbers: boolean; paths: boolean }
37
38export const FIGURE_ROLES = ['accent', 'warn', 'ok', 'note', 'dim', 'strong'] as const
39
40const ROLE_MARKUP = new RegExp(`\\{(?:${FIGURE_ROLES.join('|')}):([^{}]*)\\}`, 'g')
41
42const MAX_INLINE = 4000
43const MAX_QUOTE_DEPTH = 8
44const QUOTE = /^\s*>/
45const TABLE_SEP = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/
46const LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/
47const FENCE = /^\s*(`{3,}|~{3,})\s*([\w+-]*)/
48const NOTE_DEF = /^\[\^([^\]\s]+)\]:\s*(.*)$/
49const TAG_LINE = /^\s*<\/?[a-z][\w-]*>\s*$/i
50const SUPERSCRIPT = '⁰¹²³⁴⁵⁶⁷⁸⁹'
51
52const splitRow = (line: string): string[] => {
53 const trimmed = line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '')
54 const cells: string[] = []
55 let cell = ''
56 for (let i = 0; i < trimmed.length; i++) {
57 const ch = trimmed[i]
58 if (ch === '\\' && trimmed[i + 1] === '|') {
59 cell += '|'
60 i++
61 } else if (ch === '|') {
62 cells.push(cell.trim())
63 cell = ''
64 } else {
65 cell += ch
66 }
67 }
68 cells.push(cell.trim())
69 return cells
70}
71
72const CELL_BREAK = /(`+)(?!`).+?(?<!`)\1(?!`)|<br\s*\/?>/gi
73
74const parseCell = (text: string, hl: Highlight): Inline[] => {
75 const out: Inline[] = []
76 let at = 0
77 for (const m of text.matchAll(CELL_BREAK)) {
78 if (m[1] !== undefined) continue
79 out.push(...parseInline(text.slice(at, m.index).trim(), hl), { kind: 'text', text: '\n' })
80 at = m.index + m[0].length
81 }
82 return at ? [...out, ...parseInline(text.slice(at).trim(), hl)] : parseInline(text, hl)
83}
84
85const INLINE = /(`+)(?!`)(.+?)(?<!`)\1(?!`)|\[([^\]]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\)|\*\*(?!\s)((?:[^*]|\*[^*\s][^*]*?(?<!\s)\*)+?)(?<!\s)\*\*|(?<![\w_])__(?!\s)([^_]+?)(?<!\s)__(?![\w_])|~~([^~]+?)~~|(?<![\w*])\*([^*\s][^*]*?)(?<!\s)\*(?!\w)|(?<![\w_])_([^_\s][^_]*?)(?<!\s)_(?!\w)|(https?:\/\/(?:[^\s<>()]|\([^\s<>()]*\))*(?:[^\s<>().,;:!?'"]|\([^\s<>()]*\)))|(?<![\\$\w])\$(?=\S)((?:\\.|[^$\n\\])+?)(?<=\S)\$(?![\w$])|\[\^([^\]\s]+)\]|!\[([^\]]*)\]\(((?:[^()\s]|\([^()\s]*\))+)\)/g
86const NUMBER = /(?<![\w.#/-])(v?\d+(?:[.,:]\d+)*(?:%|ms|s|m|h|d|Gi|Mi|GB|MB|KB|x)?)(?![\w/])/g
87const PATH = /(?<![\w/.:])((?:~|\.{1,2})?\/[\w.@+-]+(?:\/[\w.@+-]*)*)/g
88
89const decorate = (raw: string, hl: Highlight): Inline[] => {
90 const text = raw.replace(ROLE_MARKUP, '$1')
91 if (!hl.numbers && !hl.paths) return [{ kind: 'text', text }]
92 const marks: { start: number; end: number; kind: 'number' | 'path' }[] = []
93 if (hl.paths) for (const m of text.matchAll(PATH)) marks.push({ start: m.index, end: m.index + m[0].length, kind: 'path' })
94 if (hl.numbers) {
95 for (const m of text.matchAll(NUMBER)) {
96 const start = m.index
97 if (!marks.some(p => start < p.end && start + m[0].length > p.start)) {
98 marks.push({ start, end: start + m[0].length, kind: 'number' })
99 }
100 }
101 }
102 marks.sort((a, b) => a.start - b.start)
103 const out: Inline[] = []
104 let at = 0
105 for (const m of marks) {
106 if (m.start > at) out.push({ kind: 'text', text: text.slice(at, m.start) })
107 out.push({ kind: m.kind, text: text.slice(m.start, m.end) })
108 at = m.end
109 }
110 if (at < text.length) out.push({ kind: 'text', text: text.slice(at) })
111 return out
112}
113
114export const parseInline = (text: string, hl: Highlight): Inline[] => {
115 if (text.length > MAX_INLINE) return [{ kind: 'text', text }]
116 const out: Inline[] = []
117 let at = 0
118 for (const m of text.matchAll(INLINE)) {
119 if (m.index > at) out.push(...decorate(text.slice(at, m.index), hl))
120 if (m[2] !== undefined) out.push({ kind: 'code', text: m[2] })
121 else if (m[3] !== undefined) out.push({ kind: 'link', text: m[3].replace(/^`([^`]+)`$/, '$1'), href: m[4]! })
122 else if (m[5] !== undefined || m[6] !== undefined) out.push({ kind: 'strong', children: parseInline(m[5] ?? m[6] ?? "", hl) })
123 else if (m[7] !== undefined) out.push({ kind: 'strike', children: parseInline(m[7], hl) })
124 else if (m[8] !== undefined || m[9] !== undefined) out.push({ kind: 'emphasis', children: parseInline(m[8] ?? m[9] ?? "", hl) })
125 else if (m[10] !== undefined) out.push({ kind: 'link', text: m[10], href: m[10] })
126 else if (m[11] !== undefined) out.push(...(isTex(m[11]) ? [{ kind: 'math' as const, text: texText(m[11]) }] : decorate(m[0], hl)))
127 else if (m[12] !== undefined) out.push({ kind: 'footnote', text: m[12] })
128 else if (m[14] !== undefined) out.push({ kind: 'image', text: m[13] || 'image', src: m[14] })
129 at = m.index + m[0].length
130 }
131 if (at < text.length) out.push(...decorate(text.slice(at), hl))
132 return out
133}
134
135const TEX: Record<string, string> = {
136 alpha: 'α', beta: 'β', gamma: 'γ', Gamma: 'Γ', delta: 'δ', Delta: 'Δ', epsilon: 'ε', varepsilon: 'ε', zeta: 'ζ', eta: 'η', theta: 'θ', Theta: 'Θ', iota: 'ι', kappa: 'κ', lambda: 'λ', Lambda: 'Λ', mu: 'μ', nu: 'ν', xi: 'ξ', Xi: 'Ξ', pi: 'π', Pi: 'Π', rho: 'ρ', sigma: 'σ', Sigma: 'Σ', tau: 'τ', upsilon: 'υ', phi: 'φ', varphi: 'φ', Phi: 'Φ', chi: 'χ', psi: 'ψ', Psi: 'Ψ', omega: 'ω', Omega: 'Ω',
137 cdot: '·', times: '×', div: '÷', pm: '±', mp: '∓', le: '≤', leq: '≤', ge: '≥', geq: '≥', neq: '≠', ne: '≠', approx: '≈', sim: '∼', equiv: '≡', propto: '∝', infty: '∞', to: '→', rightarrow: '→', leftarrow: '←', Rightarrow: '⇒', iff: '⇔', mapsto: '↦',
138 sum: 'Σ', prod: '∏', int: '∫', iint: '∬', oint: '∮', partial: '∂', nabla: '∇', in: '∈', notin: '∉', subset: '⊂', subseteq: '⊆', cup: '∪', cap: '∩', forall: '∀', exists: '∃', neg: '¬', land: '∧', lor: '∨', emptyset: '∅',
139 ldots: '…', cdots: '⋯', dots: '…', ell: 'ℓ', hbar: 'ℏ', lceil: '⌈', rceil: '⌉', lfloor: '⌊', rfloor: '⌋', langle: '⟨', rangle: '⟩', mid: '∣', quad: ' ', qquad: ' ',
140}
141const FUNCTIONS = new Set(['ln', 'log', 'exp', 'min', 'max', 'sin', 'cos', 'tan', 'lim', 'det', 'sup', 'inf', 'arg', 'deg', 'gcd', 'Pr'])
142const PLAIN = new Set(['text', 'mathrm', 'mathit', 'mathbf', 'textbf', 'texttt', 'mathsf', 'operatorname', 'boldsymbol'])
143const SPACES: Record<string, string> = { ',': ' ', ';': ' ', ':': ' ', ' ': ' ', '!': '', '\\': ' ', '{': '{', '}': '}', '%': '%', '$': '$', '&': '&', '#': '#', '_': '_' }
144const scriptMap = (from: string, to: string) => new Map(Array.from(from).map((c, i) => [c, Array.from(to)[i]!]))
145const SUP = scriptMap('0123456789+-−=()niabcdefghjklmoprstuvwxyzABDEGHIJKLMNOPRTUVW', '⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁻⁼⁽⁾ⁿⁱᵃᵇᶜᵈᵉᶠᵍʰʲᵏˡᵐᵒᵖʳˢᵗᵘᵛʷˣʸᶻᴬᴮᴰᴱᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾᴿᵀᵁⱽᵂ')
146const SUB = scriptMap('0123456789+-−=()aehijklmnoprstuvx', '₀₁₂₃₄₅₆₇₈₉₊₋₋₌₍₎ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓ')
147const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
148const FONTS: Record<string, string> = { mathbb: '𝔸𝔹ℂ𝔻𝔼𝔽𝔾ℍ𝕀𝕁𝕂𝕃𝕄ℕ𝕆ℙℚℝ𝕊𝕋𝕌𝕍𝕎𝕏𝕐ℤ', mathcal: '𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵' }
149const FN = '\u0000'
150
151const script = (text: string, map: Map<string, string>, mark: string) => {
152 const chars = Array.from(text)
153 const values = new Set(map.values())
154 if (chars.length > 0 && chars.every(c => map.has(c) || values.has(c))) return chars.map(c => map.get(c) ?? c).join('')
155 return mark + (chars.length === 1 ? text : `(${text})`)
156}
157const atomic = (text: string) => /^√?[\p{L}\p{N}.,]+$/u.test(text) || Array.from(text).length === 1
158
159const texUnicode = (tex: string): string => {
160 let i = 0
161 const name = () => {
162 const m = /^[A-Za-z]+/.exec(tex.slice(i))
163 if (m) return (i += m[0].length, m[0])
164 return tex[i++] ?? ''
165 }
166 const arg = (): string => {
167 while (tex[i] === ' ') i++
168 if (tex[i] === '{') {
169 let depth = 0
170 const start = ++i
171 for (; i < tex.length; i++) {
172 if (tex[i] === '\\') i++
173 else if (tex[i] === '{') depth++
174 else if (tex[i] === '}' && depth-- === 0) break
175 }
176 return tex.slice(start, i++)
177 }
178 if (tex[i] === '\\') return (i++, `\\${name()}`)
179 return tex[i++] ?? ''
180 }
181 const out: string[] = []
182 const prev = () => out.join('').slice(-1)
183 while (i < tex.length) {
184 const c = tex[i++]!
185 if (c === '\\') {
186 const cmd = name()
187 if (Object.hasOwn(SPACES, cmd)) out.push(SPACES[cmd]!)
188 else if (cmd === 'frac' || cmd === 'dfrac' || cmd === 'tfrac') {
189 const top = texUnicode(arg())
190 const bottom = texUnicode(arg())
191 const frac = `${atomic(top) ? top : `(${top})`}/${atomic(bottom) ? bottom : `(${bottom})`}`
192 const loose = /^$|[\s(=,[]$/.test(prev()) && /^(\s|$|\\right|[)\],])/.test(tex.slice(i))
193 out.push(loose ? frac : `(${frac})`)
194 } else if (cmd === 'sqrt') {
195 const inner = texUnicode(arg())
196 out.push(`√${atomic(inner) ? inner : `(${inner})`}`)
197 } else if (PLAIN.has(cmd)) out.push(cmd === 'text' ? arg() : texUnicode(arg()))
198 else if (Object.hasOwn(FONTS, cmd)) out.push(Array.from(arg()).map(l => (LETTERS.includes(l) ? Array.from(FONTS[cmd]!)[LETTERS.indexOf(l)]! : l)).join(''))
199 else if (cmd === 'left' || cmd === 'right' || cmd === 'big' || cmd === 'Big' || cmd === 'bigg') {
200 const d = tex[i] === '\\' ? (i++, name()) : tex[i++] ?? ''
201 out.push(d === '.' ? '' : d === '{' || d === '}' ? d : Object.hasOwn(TEX, d) ? TEX[d]! : d)
202 } else if (FUNCTIONS.has(cmd)) out.push(cmd + FN)
203 else out.push(Object.hasOwn(TEX, cmd) ? TEX[cmd]! : `\\${cmd}`)
204 } else if (c === '^' || c === '_') out.push(script(texUnicode(arg()), c === '^' ? SUP : SUB, c))
205 else if (c === '{') {
206 i--
207 out.push(texUnicode(arg()))
208 } else if (c === '}' ) continue
209 else if (c === '~' || c === '&') out.push(' ')
210 else out.push(c)
211 }
212 return out.join('')
213}
214
215const isTex = (tex: string) => /[\\^_={}]/.test(tex) || /^[A-Za-z]$/.test(tex)
216
217export const texText = (tex: string): string =>
218 texUnicode(tex)
219 .replace(new RegExp(`${FN}(?=[\\p{L}\\p{N}])`, 'gu'), ' ')
220 .replaceAll(FN, '')
221 .replace(/\)\(/g, ')·(')
222 .replace(/ {2,}/g, ' ')
223 .trim()
224
225export const inlineText = (inline: Inline[]): string =>
226 inline.map(n => ('children' in n ? inlineText(n.children) : n.text)).join('')
227
228const mathAt = (lines: string[], start: number): { lines: string[]; end: number } | null => {
229 const trimmed = (n: number) => (lines[n] ?? '').trim()
230 const first = trimmed(start)
231 if (!first.startsWith('$$')) return null
232 const open = first.slice(2)
233 let end = start
234 if (!(open.length >= 2 && open.endsWith('$$'))) {
235 end = start + 1
236 while (end < lines.length && !trimmed(end).endsWith('$$')) {
237 if (trimmed(end) === '') return null
238 end++
239 }
240 if (end === lines.length) return null
241 }
242 const body = end === start ? [open.slice(0, -2)] : [open, ...lines.slice(start + 1, end), trimmed(end).slice(0, -2)]
243 const tex = body.filter(line => line.trim() !== '').map((line, i, all) => (i === 0 || i === all.length - 1 ? line.trim() : line))
244 return tex.length ? { lines: tex, end } : null
245}
246
247export const displayText = (inline: Inline[]): string =>
248 inline.map(n => (n.kind === 'link' && n.text !== n.href ? `${n.text} (${n.href})` : 'children' in n ? displayText(n.children) : n.text)).join('')
249
250export const isWebLink = (href: string): boolean => /^(https?:|mailto:)/i.test(href)
251
252const markOf = (n: number) => [...String(n)].map(d => SUPERSCRIPT[Number(d)]).join('')
253
254const numberNotes = (blocks: Block[], defs: Map<string, string>, hl: Highlight): Block[] => {
255 const order = new Map<string, number>()
256 const seen = (nodes: Inline[]): void => nodes.forEach(n => {
257 if (n.kind === 'footnote' && defs.has(n.text) && !order.has(n.text)) order.set(n.text, order.size + 1)
258 else if ('children' in n) seen(n.children)
259 })
260 const fix = (nodes: Inline[]): Inline[] => nodes.map(n =>
261 n.kind === 'footnote' ? (order.has(n.text) ? { kind: 'footnote', text: markOf(order.get(n.text)!), note: order.get(n.text)! } : { kind: 'text', text: `[^${n.text}]` })
262 : 'children' in n ? { ...n, children: fix(n.children) } : n)
263 const mapInlines = (b: Block, f: (nodes: Inline[]) => Inline[]): Block =>
264 'inline' in b ? { ...b, inline: f(b.inline) }
265 : b.kind === 'list' ? { ...b, items: b.items.map(it => ({ ...it, inline: f(it.inline), ...(it.blocks ? { blocks: it.blocks.map(c => mapInlines(c, f)) } : {}) })) }
266 : b.kind === 'table' ? { ...b, header: b.header.map(f), rows: b.rows.map(r => r.map(f)) }
267 : b.kind === 'quote' || b.kind === 'alert' ? { ...b, blocks: b.blocks.map(c => mapInlines(c, f)) }
268 : b
269 blocks.forEach(b => mapInlines(b, nodes => (seen(nodes), nodes)))
270 for (const label of defs.keys()) if (!order.has(label)) order.set(label, order.size + 1)
271 const out = blocks.map(b => mapInlines(b, fix))
272 const notes = [...defs].sort(([a], [b]) => order.get(a)! - order.get(b)!).map(([label, text]) => ({ mark: markOf(order.get(label)!), inline: fix(parseInline(text, hl)), note: order.get(label)! }))
273 return defs.size ? [...out, { kind: 'notes', notes, raw: '' }] : out
274}
275
276export const CONTROL = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b\[[0-?]*[ -/]*[@-~]|\u001b[@-_]?|[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g
277
278export const parse = (raw: string, hl: Highlight): Block[] => {
279 const source = raw.replace(CONTROL, '')
280 const blocks = parseBlocks(source, hl)
281 return source.includes('[^') ? numberNotes(blocks, notesOf(source), hl) : blocks
282}
283
284const notesOf = (source: string, defs = new Map<string, string>(), depth = 0): Map<string, string> => {
285 const lines = source.replace(/\r\n?/g, '\n').split('\n')
286 let closer: RegExp | undefined
287 let last: string | undefined
288 for (let i = 0; i < lines.length; i++) {
289 const line = lines[i]!
290 if (!closer && depth < MAX_QUOTE_DEPTH && QUOTE.test(line)) {
291 const body: string[] = []
292 while (i < lines.length && QUOTE.test(lines[i]!)) body.push(lines[i++]!.replace(/^\s*>\s?/, ''))
293 i--
294 notesOf(body.join('\n'), defs, depth + 1)
295 last = undefined
296 continue
297 }
298 const run = FENCE.exec(line)?.[1]
299 const fenced = closer !== undefined || run !== undefined
300 if (closer?.test(line)) closer = undefined
301 else if (!closer && run) closer = closerOf(run)
302 const def = fenced ? null : NOTE_DEF.exec(line)
303 if (def) {
304 last = def[1]!
305 if (!defs.has(last)) defs.set(last, def[2] ?? '')
306 } else if (last !== undefined && /^\s{2,}\S/.test(line)) defs.set(last, `${defs.get(last)} ${line.trim()}`)
307 else last = undefined
308 }
309 return defs
310}
311
312const indentOf = (line: string): number => (line.match(/^\s*/)?.[0] ?? '').replace(/\t/g, ' ').length
313const closerOf = (run: string) => new RegExp(`^\\s*\\${run[0]}{${run.length},}\\s*$`)
314
315export const nestedBlocks = (blocks: Block[]): Block[] =>
316 blocks.flatMap(b => [b, ...nestedBlocks(b.kind === 'list' ? b.items.flatMap(it => it.blocks ?? []) : b.kind === 'quote' || b.kind === 'alert' ? b.blocks : [])])
317
318const tableRows = (lines: string[], width: number, hl: Highlight): Inline[][][] => {
319 const end = lines.findIndex(l => !l.includes('|') || l.trim() === '')
320 return lines.slice(0, end < 0 ? lines.length : end).map(l => {
321 const cells = splitRow(l)
322 return Array.from({ length: width }, (_, c) => parseCell(cells[c] ?? '', hl))
323 })
324}
325
326const parseBlocks = (source: string, hl: Highlight, depth = 0): Block[] => {
327 const lines = source.replace(/\r\n?/g, '\n').split('\n')
328 const at = (n: number) => lines[n] ?? ''
329 const blocks: Block[] = []
330 const add = (block: Draft, from: number, to: number) => blocks.push({ ...block, raw: lines.slice(from, to).join('\n') } as Block)
331 let paraStart = 0
332 let para: string[] = []
333
334 const flush = (end: number) => {
335 if (para.length) add({ kind: 'paragraph', inline: parseInline(para.join(' '), hl) }, paraStart, end)
336 para = []
337 }
338
339 for (let i = 0; i < lines.length; i++) {
340 const line = at(i)
341 const fence = FENCE.exec(line)
342 if (fence) {
343 flush(i)
344 const start = i
345 const run = fence[1] ?? '```'
346 const closer = closerOf(run)
347 const body: string[] = []
348 i++
349 while (i < lines.length && !closer.test(at(i))) body.push(at(i++))
350 add({ kind: 'code', lang: fence[2] ?? '', lines: body, ...(i < lines.length ? {} : { isOpen: true as const }) }, start, i + 1)
351 continue
352 }
353 const math = mathAt(lines, i)
354 if (math) {
355 flush(i)
356 add({ kind: 'code', lang: 'math', lines: math.lines }, i, math.end + 1)
357 i = math.end
358 continue
359 }
360 if (line.trim() === '') {
361 flush(i)
362 continue
363 }
364 if (NOTE_DEF.test(line)) {
365 flush(i)
366 while (/^\s{2,}\S/.test(at(i + 1))) i++
367 continue
368 }
369 if (TAG_LINE.test(line)) {
370 flush(i)
371 add({ kind: 'paragraph', inline: [{ kind: 'dim', text: line.trim() }] }, i, i + 1)
372 continue
373 }
374 const heading = /^(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/.exec(line)
375 if (heading) {
376 flush(i)
377 add({ kind: 'heading', level: (heading[1] ?? '#').length, inline: parseInline(heading[2] ?? '', hl) }, i, i + 1)
378 continue
379 }
380 if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
381 flush(i)
382 add({ kind: 'rule' }, i, i + 1)
383 continue
384 }
385 if (line.includes('|') && i + 1 < lines.length && TABLE_SEP.test(at(i + 1))) {
386 flush(i)
387 const start = i
388 const header = splitRow(line)
389 const align = splitRow(at(i + 1)).map(c =>
390 c.startsWith(':') && c.endsWith(':') ? 'center' : c.endsWith(':') ? 'right' : 'left',
391 )
392 const rows = tableRows(lines.slice(i + 2), header.length, hl)
393 i += 2 + rows.length
394 add({ kind: 'table', header: header.map(c => parseCell(c, { numbers: false, paths: false })), align, rows }, start, i)
395 i--
396 continue
397 }
398 if (depth < MAX_QUOTE_DEPTH && QUOTE.test(line)) {
399 flush(i)
400 const start = i
401 const body: string[] = []
402 while (i < lines.length && QUOTE.test(at(i))) body.push(at(i++).replace(/^\s*>\s?/, ''))
403 const alert = ALERT.exec(body[0] ?? '')
404 const inner = (rows: string[]) => parseBlocks(rows.join('\n'), hl, depth + 1)
405 if (alert) add({ kind: 'alert', level: alert[1]!.toLowerCase() as AlertLevel, blocks: inner([alert[2]!, ...body.slice(1)]) }, start, i)
406 else {
407 const quoted = inner(body)
408 if (quoted.length) add({ kind: 'quote', blocks: quoted }, start, i)
409 }
410 i--
411 continue
412 }
413 const item = LIST_ITEM.exec(line)
414 if (item) {
415 flush(i)
416 const start = i
417 const ordered = /\d/.test(item[2] ?? '')
418 const items: ListItem[] = []
419 const contentIndent: number[] = []
420 while (i < lines.length) {
421 const it = LIST_ITEM.exec(at(i))
422 if (it) {
423 const lead = indentOf(it[1] ?? '')
424 contentIndent.push(lead + (it[2] ?? '').length + 1)
425 const task = /^\[([ xX])\]\s+(.*)$/.exec(it[3] ?? '')
426 items.push({ marker: it[2] ?? '-', depth: Math.floor(lead / 2), ...(task ? { task: task[1] !== ' ' } : {}), inline: parseInline(task ? task[2]! : it[3] ?? '', hl) })
427 } else if (/^\s{2,}\S/.test(at(i)) && items.length) {
428 const indent = indentOf(at(i))
429 let owner = items.length - 1
430 while (owner > 0 && contentIndent[owner]! > indent) owner--
431 const target = items[owner]!
432 const fence = FENCE.exec(at(i))
433 const last = target.blocks?.at(-1)
434 if (fence) {
435 const from = i
436 const run = fence[1] ?? '```'
437 const closer = closerOf(run)
438 const strip = new RegExp(`^ {0,${indent}}`)
439 const body: string[] = []
440 i++
441 while (i < lines.length && !closer.test(at(i)) && (at(i).trim() === '' || indentOf(at(i)) >= indent)) body.push(at(i++).replace(strip, ''))
442 const isOpen = i === lines.length
443 if (!isOpen && !closer.test(at(i))) {
444 while (body.at(-1)?.trim() === '') body.pop()
445 i--
446 }
447 target.blocks = [...(target.blocks ?? []), { kind: 'code', lang: fence[2] ?? '', lines: body, ...(isOpen ? { isOpen: true as const } : {}), raw: lines.slice(from, i + 1).join('\n') }]
448 } else if (last?.kind === 'paragraph') {
449 last.inline = [...last.inline, { kind: 'text', text: ' ' }, ...parseInline(at(i).trim(), hl)]
450 last.raw += `\n${at(i)}`
451 } else if (last) {
452 target.blocks!.push({ kind: 'paragraph', inline: parseInline(at(i).trim(), hl), raw: at(i) })
453 } else {
454 target.inline = [...target.inline, { kind: 'text', text: ' ' }, ...parseInline(at(i).trim(), hl)]
455 }
456 } else {
457 break
458 }
459 i++
460 }
461 add({ kind: 'list', ordered, items }, start, i)
462 i--
463 continue
464 }
465 if (!para.length) paraStart = i
466 para.push(line.trim())
467 }
468 flush(lines.length)
469 return blocks
470}
471hooks/clipboard.ts 70 lines1export const MAC_TABLE_COPY = `
2ObjC.import('AppKit')
3var input = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile
4var payload = JSON.parse(ObjC.unwrap($.NSString.alloc.initWithDataEncoding(input, $.NSUTF8StringEncoding)))
5var item = $.NSPasteboardItem.alloc.init
6if (!item.setStringForType(payload.html, $.NSPasteboardTypeHTML) ||
7 !item.setStringForType(payload.text, $.NSPasteboardTypeString)) throw new Error('Cannot encode table')
8var pasteboard = $.NSPasteboard.generalPasteboard
9if (!pasteboard || !pasteboard.writeObjects) throw new Error('macOS clipboard is unavailable to this session')
10pasteboard.clearContents
11if (!pasteboard.writeObjects($.NSArray.arrayWithObject(item))) throw new Error('Cannot write clipboard')
12if (ObjC.unwrap(pasteboard.stringForType($.NSPasteboardTypeHTML)) !== payload.html ||
13 ObjC.unwrap(pasteboard.stringForType($.NSPasteboardTypeString)) !== payload.text) throw new Error('Clipboard verification failed')
14`
15
16export const LINUX_TABLE_COPY = `
17var table = JSON.parse(str(arguments[1]))
18copy('text/html', table.html, 'text/plain', table.text)
19if (str(clipboard('text/html')) !== table.html ||
20 str(clipboard('text/plain')) !== table.text) throw new Error('Clipboard verification failed')
21`
22
23export const WIN_TABLE_COPY = `
24$ErrorActionPreference = 'Stop'
25try {
26 Add-Type -AssemblyName System.Windows.Forms
27 $payload = [Console]::In.ReadToEnd() | ConvertFrom-Json
28 $utf8 = New-Object Text.UTF8Encoding($false)
29 $fragment = [string]$payload.html
30 $lf = [string][char]10
31 $crlf = [string][char]13 + $lf
32 $template = 'Version:1.0' + $crlf + 'StartHTML:{0:D10}' + $crlf + 'EndHTML:{1:D10}' + $crlf + 'StartFragment:{2:D10}' + $crlf + 'EndFragment:{3:D10}' + $crlf
33 $headerLen = $utf8.GetByteCount(($template -f 0, 0, 0, 0))
34 $prefix = '<html>' + $lf + '<head>' + $lf + '<meta charset="utf-8">' + $lf + '</head>' + $lf + '<body>' + $lf + '<!--StartFragment-->' + $lf
35 $suffix = $lf + '<!--EndFragment-->' + $lf + '</body>' + $lf + '</html>'
36 $startFragment = $headerLen + $utf8.GetByteCount($prefix)
37 $endFragment = $startFragment + $utf8.GetByteCount($fragment)
38 $endHtml = $endFragment + $utf8.GetByteCount($suffix)
39 $cf = ($template -f $headerLen, $endHtml, $startFragment, $endFragment) + $prefix + $fragment + $suffix
40 $data = New-Object System.Windows.Forms.DataObject
41 $data.SetData('HTML Format', (New-Object IO.MemoryStream(, [byte[]]($utf8.GetBytes($cf) + [byte]0))))
42 $data.SetData([System.Windows.Forms.DataFormats]::UnicodeText, [string]$payload.text)
43 [System.Windows.Forms.Clipboard]::SetDataObject($data, $true)
44} catch {
45 [Console]::Error.WriteLine($_.Exception.Message)
46 exit 1
47}
48`
49
50export type ClipboardBackend = 'macos' | 'linux' | 'windows'
51
52const ascii = (json: string): string =>
53 Array.from({ length: json.length }, (_, i) => {
54 const unit = json.charCodeAt(i)
55 return unit > 0x7e ? `\\u${unit.toString(16).padStart(4, '0')}` : json[i]
56 }).join('')
57
58export const clipboardCommand = (backend: ClipboardBackend, html: string, text: string, systemRoot?: string) => backend === 'windows'
59 ? {
60 stdin: ascii(JSON.stringify({ html, text: text.replace(/\r?\n/g, '\r\n') })),
61 argv: [`${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, '-NoProfile', '-NonInteractive', '-STA', '-Command', WIN_TABLE_COPY],
62 failure: 'Windows clipboard helper failed',
63 }
64 : {
65 stdin: JSON.stringify({ html, text }),
66 ...backend === 'macos'
67 ? { argv: ['/usr/bin/osascript', '-l', 'JavaScript', '-e', MAC_TABLE_COPY], failure: 'macOS clipboard helper failed' }
68 : { argv: ['copyq', 'eval', LINUX_TABLE_COPY, '-'], failure: 'CopyQ failed; install and start CopyQ in the graphical session' },
69 }
70hooks/figure.tsx 381 lines1import type { ElementTable, RenderElement } from 'claude-code'
2
3import { cells, graphemes, heldLtr, mirrored, remember, width } from './render'
4import { FIGURE_ROLES } from './markdown'
5import { asIs, hasRtl, holdEngine, holdText, holdVisual, led } from './rtl'
6import type { Style, Theme } from './theme'
7
8type FigureRole = (typeof FIGURE_ROLES)[number]
9
10type FigureRun = { text: string; role?: FigureRole }
11
12type FigureFinding = { line: number; message: string }
13
14export const FIGURE_MAX_COLUMNS = 100
15
16export const FIGURE_MAX_LINES = 80
17
18export const FIGURE_SAFE_COLUMNS = 74
19
20const RAW_MAX_LINE = FIGURE_MAX_COLUMNS * 4
21
22const LISTED_GLYPHS = 8
23
24export const FIGURE_GLYPHS = '─│┌┐└┘├┤┬┴┼═║→←►◄▲▼✓✗●○█▏■□·'
25
26export const FIGURE_HINT = [
27 'A fenced block whose opening line is exactly ```figure is drawn as a text picture, as written.',
28 'Prefer one over mermaid when position carries meaning: durations racing on a time axis, a screen layout, phases, before/after; mermaid stays for plain flows and charts; none for short answers, code changes or reports. The prose never retells the picture.',
29 'When asked to explain, compare or plan something and pictures would help, build the reply around them, with the core on the first screen as a picture or a sentence.',
30 'Figures only: color with {role:text}, not nested: accent for lines, warn for risk, ok for healthy, note for time, dim for asides, strong for emphasis.',
31 `At most ${FIGURE_SAFE_COLUMNS} columns, glyphs one column wide such as ${FIGURE_GLYPHS}, no emoji or tabs; markup takes no columns, so align on the drawn text and pad box rows to the top border. CJK letters take two columns, count them twice. Draw a time axis with edge ticks like ▏───▏───▏, not ├┼┤: █ fills its cell, ├┼┤ sit mid-cell.`,
32].join(' ')
33
34const MARKUP = new RegExp(`\\{(${FIGURE_ROLES.join('|')}):([^{}]*)\\}`, 'g')
35const MARKER = /\{([A-Za-z][\w-]*):/g
36const TEXT_FORMS: Record<string, string> = { '▶': '►', '◀': '◄' }
37const ROLE_TOKENS: Record<FigureRole, keyof Theme> = { accent: 'diagram', warn: 'codeFlag', ok: 'codeString', note: 'heading', dim: 'codeComment', strong: 'strong' }
38const EMOJI_CAPABLE = /\p{Extended_Pictographic}|\p{Emoji_Presentation}|\u20e3/u
39const CONTROL = /[\0-\x08\x0b-\x1f\x7f-\x9f]/
40const DIRECTION_MARK = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/
41const INVISIBLE = /[\u00ad\u200b-\u200d\u2028\u2029\ufeff]/
42const isRole = (name: string | undefined): name is FigureRole => FIGURE_ROLES.some(role => role === name)
43
44export const isFigureLang = (lang: string): boolean => lang.toLowerCase() === 'figure'
45
46const textForm = (text: string): string => text.replace(/[▶◀]/g, glyph => TEXT_FORMS[glyph] ?? glyph)
47
48export const figureRuns = (line: string): FigureRun[] => {
49 const runs: FigureRun[] = []
50 let at = 0
51 for (const match of line.matchAll(MARKUP)) {
52 const [whole, role, text = ''] = match
53 if (match.index > at) runs.push({ text: textForm(line.slice(at, match.index)) })
54 if (text && isRole(role)) runs.push({ text: textForm(text), role })
55 at = match.index + whole.length
56 }
57 if (at < line.length) runs.push({ text: textForm(line.slice(at)) })
58 return runs
59}
60
61export const figureText = (line: string): string => figureRuns(line).map(run => run.text).join('')
62
63const swapsTwoLetters = (name: string, role: string): boolean => {
64 if (name.length !== role.length) return false
65 const differ = [...name].flatMap((letter, i) => (letter === role[i] ? [] : [i]))
66 const [first = -1, second = -1] = differ
67 return differ.length === 2 && second === first + 1 && name[first] === role[second] && name[second] === role[first]
68}
69
70const markupMessage = (marker: RegExpExecArray, drawn: ReadonlySet<number>, lastClose: number): string | undefined => {
71 const [written, name = ''] = marker
72 if (drawn.has(marker.index)) return undefined
73 const lower = name.toLowerCase()
74 const role = FIGURE_ROLES.find(candidate => candidate === lower || swapsTwoLetters(lower, candidate))
75 if (!role) return undefined
76 if (name !== role) return `"${written}" is not a role, roles are ${FIGURE_ROLES.join(', ')} in lower case`
77 if (lastClose < marker.index + written.length) return `"${written}" is not closed, end it with }`
78 return `"${written}" holds braces, markup does not nest`
79}
80
81const markupMessages = (line: string): string[] => {
82 const drawn = new Set([...line.matchAll(MARKUP)].map(match => match.index))
83 const lastClose = line.lastIndexOf('}')
84 return [...line.matchAll(MARKER)].flatMap(marker => markupMessage(marker, drawn, lastClose) ?? [])
85}
86
87const quoted = (glyphs: readonly string[]): string => {
88 const distinct = [...new Set(glyphs)]
89 const listed = distinct.slice(0, LISTED_GLYPHS).map(glyph => `"${glyph}"`).join(', ')
90 return distinct.length > LISTED_GLYPHS ? `${listed} and ${distinct.length - LISTED_GLYPHS} more` : listed
91}
92
93const lineMessages = (line: string): string[] => {
94 const text = figureText(line)
95 const glyphs = graphemes(text)
96 const emoji = glyphs.filter(glyph => EMOJI_CAPABLE.test(glyph))
97 const columns = width(text)
98 return [
99 ...(columns > FIGURE_MAX_COLUMNS ? [`${columns} columns wide, at most ${FIGURE_MAX_COLUMNS}`] : []),
100 ...(text.includes('\t') ? ['tab, use spaces'] : []),
101 ...(CONTROL.test(text) ? ['control character, use plain text'] : []),
102 ...(DIRECTION_MARK.test(text) ? ['direction mark, use plain text'] : []),
103 ...(INVISIBLE.test(text) ? ['invisible character, use plain text'] : []),
104 ...(emoji.length ? [`${quoted(emoji)} may draw as an emoji, use a text glyph`] : []),
105 ...markupMessages(line),
106 ]
107}
108
109const withoutTrailingBlanks = (lines: readonly string[]): readonly string[] => {
110 let end = lines.length
111 while (end > 0 && !lines[end - 1]?.trim()) end--
112 return lines.slice(0, end)
113}
114
115export const checkFigure = (lines: readonly string[], first = 0): FigureFinding[] =>
116 lines.flatMap((line, index) => lineMessages(line).map(message => ({ line: first + index + 1, message })))
117
118const leadingBlanks = (lines: readonly string[]): number => {
119 const start = lines.findIndex(line => line.trim())
120 return start < 0 ? lines.length : start
121}
122
123const ROLE_HUES = { warn: 0, ok: 120, note: 45 } as const
124
125type HuedRole = keyof typeof ROLE_HUES
126
127const INK: readonly (keyof Theme)[] = ['accent', 'heading', 'tableHeader', 'emphasis', 'inlineCode', 'codeCommand', 'codeFlag', 'codeString', 'link', 'path', 'number', 'bullet', 'quote']
128
129const HEX = /^#(?:[0-9a-f]{3}){1,2}$/i
130
131const RGB = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i
132
133const channelsOf = (color: string): readonly [number, number, number] | undefined => {
134 const value = color.trim()
135 if (HEX.test(value)) {
136 const full = value.length === 4 ? [...value.slice(1)].map(digit => digit + digit).join('') : value.slice(1)
137 const [r = 0, g = 0, b = 0] = [0, 2, 4].map(at => parseInt(full.slice(at, at + 2), 16))
138 return [r, g, b]
139 }
140 const rgb = RGB.exec(value)
141 return rgb ? [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])] : undefined
142}
143
144const colorKey = (channels: readonly [number, number, number]): string => channels.join(',')
145
146const hueOf = (channels: readonly [number, number, number]): { hue: number; saturation: number } => {
147 const [r, g, b] = channels.map(channel => Math.min(channel, 255) / 255) as [number, number, number]
148 const max = Math.max(r, g, b)
149 const spread = max - Math.min(r, g, b)
150 const lightness = (max + max - spread) / 2
151 const saturation = spread === 0 ? 0 : spread / (1 - Math.abs(2 * lightness - 1))
152 const sector = spread === 0 ? 0 : max === r ? ((g - b) / spread) % 6 : max === g ? (b - r) / spread + 2 : (r - g) / spread + 4
153 return { hue: (sector * 60 + 360) % 360, saturation }
154}
155
156const hueDistance = (a: number, b: number): number => Math.min(Math.abs(a - b), 360 - Math.abs(a - b))
157
158const pickedRoles = new WeakMap<Theme, Partial<Record<HuedRole, string>>>()
159
160export const figureRoleColors = (theme: Theme): Partial<Record<HuedRole, string>> => {
161 const known = pickedRoles.get(theme)
162 if (known) return known
163 const inks = [...new Set(INK.map(token => theme[token]).filter((color): color is string => color !== undefined))]
164 .flatMap(color => {
165 const channels = channelsOf(color)
166 return channels ? [{ color, key: colorKey(channels), ...hueOf(channels) }] : []
167 })
168 .filter(ink => ink.saturation > 0.15)
169 const frame = theme.diagram === undefined ? undefined : channelsOf(theme.diagram)
170 const taken = new Set(frame ? [colorKey(frame)] : [])
171 const picked: Partial<Record<HuedRole, string>> = {}
172 for (const role of Object.keys(ROLE_HUES) as HuedRole[]) {
173 const [best] = inks.filter(ink => !taken.has(ink.key)).sort((a, b) => hueDistance(a.hue, ROLE_HUES[role]) - hueDistance(b.hue, ROLE_HUES[role]))
174 if (!best) continue
175 picked[role] = best.color
176 taken.add(best.key)
177 }
178 pickedRoles.set(theme, picked)
179 return picked
180}
181
182const isHued = (role: FigureRole): role is HuedRole => role in ROLE_HUES
183
184const runColor = (style: Style, role: FigureRole | undefined): string | undefined => {
185 if (!role) return style.theme.diagramText
186 const own = style.theme[ROLE_TOKENS[role]]
187 if (!isHued(role) || (own !== undefined && !channelsOf(own))) return own
188 return figureRoleColors(style.theme)[role] ?? own
189}
190
191const isBold = (style: Style, role: FigureRole | undefined): boolean => role === 'strong' || (role === 'warn' && !runColor(style, 'warn'))
192
193const heldRuns = (style: Style, runs: readonly FigureRun[]): FigureRun[] => {
194 const hold = !hasRtl(runs.map(run => run.text).join('')) ? null : mirrored(style) ? holdText : style.shape === 'engine' ? holdEngine : style.reorder && style.shape === 'visual' ? holdVisual : null
195 const chars = runs.flatMap(run => [...run.text])
196 const roles = runs.flatMap(run => [...run.text].map(() => run.role))
197 const base = hold ? hold(chars) : asIs(chars)
198 const { cells, from } = mirrored(style) ? led(chars, base) : base
199 const held: FigureRun[] = []
200 cells.forEach((ch, p) => {
201 const role = roles[from[p]!]
202 const last = held.at(-1)
203 if (last && last.role === role) last.text += ch
204 else held.push(role ? { text: ch, role } : { text: ch })
205 })
206 return held
207}
208
209const figureElement = ({ Box, Text }: ElementTable, style: Style, rows: readonly (readonly FigureRun[])[], key: string): RenderElement => (
210 <Box key={key} flexDirection="column" paddingLeft={mirrored(style) ? 0 : 2}>
211 {rows.map((row, i) => {
212 const runs = heldRuns(style, row)
213 return (
214 <Text key={`${key}.${i}`} {...heldLtr(style)}>
215 {runs.length
216 ? runs.map((run, r) => (
217 <Text key={`r${r}`} color={runColor(style, run.role)} bold={isBold(style, run.role)} dimColor={run.role === 'dim' && !style.theme.codeComment}>
218 {run.text}
219 </Text>
220 ))
221 : ' '}
222 </Text>
223 )
224 })}
225 </Box>
226)
227
228type Cell = { glyph: string; role?: FigureRole }
229
230type Frame = { top: number; left: number; corner: number; edges: readonly number[] }
231
232const TOP_LEFT = '┌╔╭'
233const TOP_RIGHT = '┐╗╮'
234const BOTTOM_LEFT = '└╚╰'
235const BOTTOM_RIGHT = '┘╝╯'
236const SIDE = '│║├┤┼╟╢╠╣'
237const RULE = '─═'
238const MAX_REFRAMES = 200
239
240const isOf = (set: string, glyph: string | undefined): boolean => !!glyph && set.includes(glyph)
241
242const cellsOf = (runs: readonly FigureRun[]): Cell[] => runs.flatMap(run => cells(run.text).map(glyph => ({ glyph, role: run.role })))
243
244const runsOf = (row: readonly Cell[]): FigureRun[] =>
245 row.reduce<FigureRun[]>((runs, cell) => {
246 const last = runs.at(-1)
247 if (last && last.role === cell.role) last.text += cell.glyph
248 else runs.push(cell.role ? { text: cell.glyph, role: cell.role } : { text: cell.glyph })
249 return runs
250 }, [])
251
252const nearest = (row: readonly Cell[], from: number, target: number, set: string): number => {
253 let best = -1
254 row.forEach((cell, column) => {
255 if (column > from && isOf(set, cell.glyph) && (best < 0 || Math.abs(column - target) < Math.abs(best - target))) best = column
256 })
257 return best
258}
259
260const frameAt = (grid: readonly Cell[][], top: number, left: number): Frame | undefined => {
261 const row = grid[top]!
262 const corner = row.findIndex((cell, column) => column > left && (isOf(TOP_RIGHT, cell.glyph) || isOf(TOP_LEFT, cell.glyph)))
263 if (corner < 0 || !isOf(TOP_RIGHT, row[corner]?.glyph)) return undefined
264 const edges = [corner]
265 for (let line = top + 1; line < grid.length; line++) {
266 const cells = grid[line]!
267 const start = cells[left]?.glyph
268 if (isOf(BOTTOM_LEFT, start)) {
269 const end = nearest(cells, left, corner, BOTTOM_RIGHT)
270 return end < 0 ? undefined : { top, left, corner, edges: [...edges, end] }
271 }
272 if (!isOf(SIDE, start)) return undefined
273 const edge = nearest(cells, left, corner, SIDE)
274 if (edge < 0) return undefined
275 edges.push(edge)
276 }
277 return undefined
278}
279
280const framesOf = (grid: readonly Cell[][]): Frame[] =>
281 grid
282 .flatMap((row, top) => row.flatMap((cell, left) => (isOf(TOP_LEFT, cell.glyph) ? [frameAt(grid, top, left)] : [])))
283 .filter((frame): frame is Frame => frame !== undefined)
284 .sort((a, b) => a.corner - a.left - (b.corner - b.left))
285
286const fillOf = (row: readonly Cell[], edge: number, border: boolean): string => {
287 const before = row[edge - 1]?.glyph
288 return before && isOf(RULE, before) ? before : border ? '─' : ' '
289}
290
291const spareBefore = (row: readonly Cell[], edge: number, fill: string): number => {
292 let run = 0
293 while (row[edge - 1 - run]?.glyph === fill) run++
294 return Math.max(0, run - 1)
295}
296
297const blanks = (count: number, glyph: string, role?: FigureRole): Cell[] => Array.from({ length: count }, () => (glyph === ' ' || !role ? { glyph } : { glyph, role }))
298
299const spacesAfter = (row: readonly Cell[], edge: number, most: number): number => {
300 let run = 0
301 while (run < most && row[edge + 1 + run]?.glyph === ' ') run++
302 return run
303}
304
305const firstAfter = (row: readonly Cell[], column: number): number => row.findIndex((cell, at) => at > column && cell.glyph !== ' ' && cell.glyph !== '')
306
307const place = (row: Cell[], edge: number, target: number, shift: number, fill: string): boolean => {
308 if (target < edge) row.splice(target, edge - target)
309 if (target > edge) row.splice(edge, 0, ...blanks(target - edge, fill, row[edge]?.role))
310 if (shift > 0) row.splice(target + 1, 0, ...blanks(shift, ' '))
311 if (shift < 0) row.splice(target + 1, spacesAfter(row, target, -shift))
312 return target !== edge || shift !== 0
313}
314
315const pushRight = (grid: Cell[][], frame: Frame, frames: readonly Frame[], by: number): void => {
316 const bottom = frame.top + frame.edges.length - 1
317 const pushed = new Set(Array.from({ length: frame.edges.length }, (_, i) => frame.top + i))
318 for (const other of [...frames].sort((a, b) => a.left - b.left)) {
319 const rows = Array.from({ length: other.edges.length }, (_, i) => other.top + i)
320 if (other.left <= frame.corner || !rows.some(row => pushed.has(row))) continue
321 if (other.top <= bottom && other.top + other.edges.length - 1 >= frame.top && rows.every(row => row >= frame.top && row <= bottom)) continue
322 for (const row of rows) {
323 if (pushed.has(row)) continue
324 grid[row]!.splice(other.left, 0, ...blanks(by, ' '))
325 pushed.add(row)
326 }
327 }
328}
329
330const fit = (grid: Cell[][], frame: Frame, frames: readonly Frame[]): boolean => {
331 const last = frame.edges.length - 1
332 const rows = frame.edges.map((_, i) => grid[frame.top + i]!)
333 const fills = frame.edges.map((edge, i) => fillOf(rows[i]!, edge, i === 0 || i === last))
334 const reaches = frame.edges.map((edge, i) => (i === 0 ? edge : edge - spareBefore(rows[i]!, edge, fills[i]!)))
335 const target = Math.max(frame.corner, ...reaches)
336 const after = firstAfter(rows[0]!, frame.corner)
337 const shifts = frame.edges.map((edge, i) => (after >= 0 && firstAfter(rows[i]!, edge) === after ? edge - frame.corner : 0))
338 const moved = frame.edges.map((edge, i) => place(rows[i]!, edge, target, shifts[i]!, fills[i]!)).some(Boolean)
339 if (target > frame.corner) pushRight(grid, frame, frames, target - frame.corner)
340 return moved
341}
342
343export const reframe = (rows: readonly (readonly FigureRun[])[]): FigureRun[][] => {
344 const grid = rows.map(cellsOf)
345 for (let pass = 0; pass < MAX_REFRAMES; pass++) {
346 const frames = framesOf(grid)
347 if (!frames.some(frame => fit(grid, frame, frames))) break
348 }
349 return grid.map(runsOf)
350}
351
352type FigureDecision = { rows: readonly (readonly FigureRun[])[]; texts: readonly string[]; widest: number } | { note: string }
353
354const decisions = new Map<string, FigureDecision>()
355
356const drawable = (lines: readonly string[]): FigureDecision => {
357 const rows = reframe(lines.map(figureRuns))
358 const texts = rows.map(runs => runs.map(run => run.text).join(''))
359 return { rows, texts, widest: Math.max(0, ...texts.map(width)) }
360}
361
362const decide = (raw: readonly string[]): FigureDecision => {
363 const tooLong = raw.findIndex(line => line.length > RAW_MAX_LINE)
364 if (tooLong >= 0) return { note: `figure line ${tooLong + 1} is ${raw[tooLong]!.length} characters long` }
365 if (raw.length > FIGURE_MAX_LINES * 2) return { note: `figure has ${raw.length} lines, at most ${FIGURE_MAX_LINES}` }
366 const first = leadingBlanks(raw)
367 const lines = withoutTrailingBlanks(raw.slice(first))
368 if (lines.length > FIGURE_MAX_LINES) return { note: `figure has ${lines.length} lines, at most ${FIGURE_MAX_LINES}` }
369 const [finding] = checkFigure(lines, first)
370 return finding ? { note: `figure line ${finding.line}: ${finding.message}` } : drawable(lines)
371}
372
373export const drawFigure = (el: ElementTable, style: Style, block: { lines: readonly string[]; isOpen?: true }, columns: number, key: string): { element?: RenderElement; art?: string; note?: string } | null => {
374 if (block.isOpen) return null
375 const decision = remember(decisions, block.lines.join('\n'), () => decide(block.lines))
376 if ('note' in decision) return decision
377 if (decision.rows.length === 0) return null
378 if (decision.widest > columns - 2) return { note: `figure is ${decision.widest} cols, terminal is ${columns}` }
379 return { element: figureElement(el, style, decision.rows, key), art: decision.texts.join('\n') }
380}
381hooks/mermaid.tsx 337 lines1import type { ElementTable, RenderElement } from 'claude-code'
2
3import type { ChartArt } from './charts'
4import { ganttText, pieText } from './charts'
5import { drawFigure, isFigureLang } from './figure'
6import type { Block } from './markdown'
7import type { Drawn } from './render'
8import { cells, graphemes, heldLtr, mirrored, remember, width } from './render'
9import { asIs, hasRtl, holdEngine, holdRow, holdVisual, led } from './rtl'
10import type { Style, Theme } from './theme'
11import { renderMermaidAscii, setChartSize } from './vendor/mermaid-text.js'
12
13const MAX_LINES = 80
14const PAD = '\uFDD0'
15const textCache = new Map<string, string | null>()
16
17export const chartSize = (columns: number, source = '') => {
18 const labels = (/^\s*x-axis\b[^[\n]*\[([^\]\n]*)\]/m.exec(source)?.[1] ?? '').split(',').map(s => s.trim().replace(/^"|"$/g, ''))
19 const fit = labels.length * (Math.max(...labels.map(l => l.length)) + 2)
20 const width = Math.max(24, Math.min(60, Math.max(Math.floor(columns / 6), fit), columns - 12))
21 return { width, height: Math.max(8, Math.min(20, Math.round(width * 0.3))) }
22}
23
24const padWide = (source: string) => (/^[\x00-\x7F]*$/.test(source) ? source : graphemes(source).map(g => (g.length === 1 && width(g) === 2 ? g + PAD : g)).join(''))
25
26const unquoteCategories = (source: string) =>
27 source.replace(/^(\s*x-axis\b[^[\n]*\[)([^\]\n]*)\]/m, (_, head: string, items: string) => `${head}${items.replace(/"([^"]*)"/g, (_q, s: string) => s.replaceAll(',', ' '))}]`)
28
29const BLOCK = /[█▀▄]/
30
31const labelBars = (art: string, source: string): string => {
32 const series = source.match(/^\s*(bar|line)\b.*$/gm) ?? []
33 const values = /^\s*bar\b[^[\n]*\[([^\]\n]*)\]/m.exec(source)?.[1]?.split(',').map(v => v.trim())
34 if (series.length !== 1 || !values || /^\s*xychart(-beta)?\s+horizontal/m.test(source)) return art
35 const grid = ['', ...art.split('\n')].map(l => [...l])
36 const gutter = (r: number) => /^\s*(-?[\d.]+)[┤┼]/.exec(grid[r]?.join('') ?? '')?.[1]
37 const axis = grid.findLastIndex((_, r) => gutter(r) !== undefined)
38 const ticks = [...(grid[axis]?.join('') ?? '').matchAll(/┬|▀+/g)].map(m => m.index + Math.floor(m[0].length / 2))
39 if (ticks.length !== values.length) return art
40 const zero = grid.findIndex((_, r) => gutter(r) === '0')
41 const top = grid.findIndex((_, r) => gutter(r) !== undefined)
42 const base = zero !== -1 ? zero : gutter(top)?.startsWith('-') ? top : axis
43 ticks.forEach((x, k) => {
44 const filled = grid.flatMap((row, r) => (BLOCK.test(row[x] ?? '') ? [r] : []))
45 const y = Number(values[k]) < 0 ? (filled.at(-1) ?? base) + 1 : (filled[0] ?? base) - 1
46 const text = [...values[k]!]
47 const bar = grid[filled[0] ?? -1] ?? []
48 let [left, right] = [x, x]
49 while (BLOCK.test(bar[left - 1] ?? '')) left--
50 while (BLOCK.test(bar[right + 1] ?? '')) right++
51 const from = left + Math.ceil((right - left + 1 - text.length) / 2)
52 const row = y < axis ? grid[y] : undefined
53 if (!row) return
54 while (row.length < from + text.length) row.push(' ')
55 if (!text.every((_, i) => /[ ·]/.test(row[from + i] ?? ' '))) return
56 text.forEach((ch, i) => (row[from + i] = ch))
57 })
58 return grid.map(row => row.join('').trimEnd()).join('\n').replace(/^\n/, '')
59}
60
61const SIDEWAYS = /^(\s*(?:flowchart|graph)[ \t]+)(LR|RL)\b/
62
63const SUPPORTED = /^(flowchart|graph|statediagram(-v2)?|xychart(-beta)?|sequencediagram|classdiagram|erdiagram|pie|gantt)$/i
64
65const kindOf = (source: string) => source.replace(/^(\s*%%[^\n]*\n)+/, '').trim().split(/\s/)[0] ?? ''
66
67const unsupportedKind = (source: string): string | undefined => {
68 const kind = kindOf(source)
69 return kind && !SUPPORTED.test(kind) ? kind : undefined
70}
71
72const OWN: Record<string, typeof pieText> = {
73 pie: pieText,
74 gantt: (source, ascii, columns) => {
75 const text = ganttText(source, ascii, columns)
76 return text === null ? null : { text }
77 },
78}
79
80const INLINE_TAG = /<\/?(?:b|i|u|s|em|strong|del|code|small|sub|sup|span|mark)\b[^<>\n]*>/gi
81
82type Mark = { italic?: boolean; bold?: boolean; underline?: boolean; strikethrough?: boolean }
83const TAG_MARK: Record<string, keyof Mark> = { i: 'italic', em: 'italic', b: 'bold', strong: 'bold', u: 'underline', s: 'strikethrough', del: 'strikethrough' }
84
85export const inlineMarks = (source: string): [string[], Mark][] =>
86 [...source.matchAll(/<(i|em|b|strong|u|s|del)\b[^<>\n]*>([^<\n]+)<\/\1\s*>/gi)]
87 .map(m => [cells(m[2]!.trim()), { [TAG_MARK[m[1]!.toLowerCase()]!]: true }] as [string[], Mark])
88
89const fitted = new Map<string, ChartArt | null>()
90const artWidths = new Map<string, number>()
91const artWidth = (art: string) => remember(artWidths, art, () => Math.max(...art.split('\n').map(width)))
92
93export const mermaidText = (source: string, ascii: boolean, columns: number, pieColors = 0): string | null => mermaidArt(source, ascii, columns, pieColors)?.text ?? null
94
95const mermaidArt = (source: string, ascii: boolean, columns: number, pieColors: number): ChartArt | null =>
96 remember(fitted, `${ascii}:${columns}:${pieColors}:${source}`, () => {
97 source = source.replace(INLINE_TAG, '')
98 if (source.length > 8000 || source.split('\n').length > MAX_LINES) return null
99 const own = OWN[kindOf(source).toLowerCase()]
100 if (own) return own(source, ascii, columns, pieColors)
101 const art = draw(source, ascii, columns)
102 const text = art === null || artWidth(art) <= columns - 2 || !SIDEWAYS.test(source) ? art : (draw(source.replace(SIDEWAYS, '$1TD'), ascii, columns) ?? art)
103 return text === null ? null : { text, series: chartSeries(source, ascii, columns) }
104 })
105
106const prepared = (padded: string) => unquoteCategories(padded.replace(/^(\s*%%[^\n]*\n)+/, '')).replace(/(-->|-\.->|==>|---|-\.-|===)[ \t]+\|/g, '$1|')
107
108const NEUTRAL = '#808080'
109const PROBE = { fg: NEUTRAL, border: NEUTRAL, line: NEUTRAL, arrow: NEUTRAL, corner: NEUTRAL, junction: NEUTRAL, accent: '#ff0000', bg: '#000000' }
110const SGR = /\x1b\[([\d;]*)m/g
111
112const seriesOf = (colored: string): number[][] => {
113 const hues = colored.split('\n').map(line => {
114 const row: (string | undefined)[] = []
115 let hue: string | undefined
116 let at = 0
117 const take = (text: string) => graphemes(text).forEach(() => row.push(hue))
118 for (const m of line.matchAll(SGR)) {
119 take(line.slice(at, m.index))
120 hue = m[1]!.startsWith('38;2;') && m[1] !== '38;2;128;128;128' ? m[1] : undefined
121 at = m.index + m[0].length
122 }
123 take(line.slice(at))
124 return row
125 })
126 const legend = hues.find(row => row.some(Boolean)) ?? []
127 const order = [...new Set(legend.filter((h): h is string => h !== undefined))]
128 return hues.map(row => row.map(h => (h === undefined ? -1 : order.indexOf(h))))
129}
130
131const seriesCache = new Map<string, number[][] | null>()
132
133const chartSeries = (source: string, ascii: boolean, columns: number): number[][] | undefined => {
134 if (!/^\s*xychart/.test(source) || (source.match(/^\s*(bar|line)\b/gm) ?? []).length < 2) return undefined
135 const padded = padWide(source)
136 const size = chartSize(columns, padded)
137 return remember(seriesCache, `${ascii}:${size.width}:${source}`, () => {
138 try {
139 setChartSize(size.width, size.height)
140 return seriesOf(renderMermaidAscii(prepared(padded), { useAscii: ascii, colorMode: 'truecolor', theme: PROBE, paddingX: 3, paddingY: 1 }))
141 } catch {
142 return null
143 }
144 }) ?? undefined
145}
146
147const draw = (source: string, ascii: boolean, columns: number): string | null => {
148 const isChart = /^\s*xychart/.test(source)
149 const padded = padWide(source)
150 const size = chartSize(columns, isChart ? padded : '')
151 const key = `${ascii}:${isChart ? size.width : 0}:${source}`
152 return remember(textCache, key, () => {
153 try {
154 if (isChart) setChartSize(size.width, size.height)
155 const art = renderMermaidAscii(prepared(padded), { useAscii: ascii, colorMode: 'none', paddingX: 3, paddingY: 1 }).replace(/[ \t]+$/gm, '').trimEnd().replace(/▶/g, '►').replace(/◀/g, '◄')
156 return (isChart ? labelBars(art, padded) : art.split('\n').filter(l => !/^[\s│|]*$/.test(l)).join('\n')).replaceAll(PAD, '')
157 } catch {
158 return null
159 }
160 })
161}
162
163const LINE = /[─-╿◇▏]/
164const ARROW = /[►◄▲▼]/
165const PART = /[▐▏▎▍▌▋▊▉]/
166
167const barStart = (row: string[], c: number): number => {
168 const ch = row[c] ?? ''
169 const solid = BLOCK.test(ch) ? ch : PART.test(ch) && row[c + 1] === '█' ? '█' : PART.test(ch) && row[c - 1] === '█' ? '█' : ''
170 if (!solid) return -1
171 let start = BLOCK.test(ch) ? c : row[c + 1] === '█' ? c + 1 : c - 1
172 while (row[start - 1] === solid) start--
173 return start
174}
175
176type Painted = { grid: string[][]; colors: (string | undefined)[][] }
177
178export const diagramPalette = (t: Theme): string[] => [...new Set([t.link, t.number, t.heading, t.emphasis, t.path, t.codeFlag, t.accent])].filter((c): c is string => c !== undefined)
179
180const paint = (art: string, style: Style, series?: number[][]): Painted => {
181 const t = style.theme
182 const grid = art.split('\n').map(cells)
183 const cell = (r: number, c: number) => grid[r]?.[c] ?? ''
184 const color: (string | undefined)[][] = grid.map(row => row.map(() => undefined))
185 const palette = diagramPalette(t)
186 const next = (i: number) => palette[i % palette.length]
187 const labels = new Map<string, string | undefined>()
188
189 const rects: { r: number; c: number; r2: number; c2: number }[] = []
190 for (let r = 0; r < grid.length; r++) {
191 for (let c = 0; c < (grid[r]?.length ?? 0); c++) {
192 if (!/[┌╭(]/.test(cell(r, c))) continue
193 let c2 = c + 1
194 while (/[─┬┴┼▲▼]/.test(cell(r, c2))) c2++
195 if (!/[┐╮)]/.test(cell(r, c2)) || c2 === c + 1) continue
196 let r2 = r + 1
197 while (/[│├┤┼►◄]/.test(cell(r2, c))) r2++
198 if (!/[└╰(]/.test(cell(r2, c)) || !/[┘╯)]/.test(cell(r2, c2))) continue
199 rects.push({ r, c, r2, c2 })
200 }
201 }
202 const inside = (a: (typeof rects)[number], b: (typeof rects)[number]) => a !== b && b.r > a.r && b.r2 < a.r2 && b.c > a.c && b.c2 < a.c2
203 for (const box of rects.filter(a => !rects.some(b => inside(a, b)))) {
204 const { r, c, r2, c2 } = box
205 const label = grid.slice(r + 1, r2).map(row => row.slice(c + 1, c2).join('')).join(' ').trim()
206 if (!labels.has(label)) labels.set(label, next(labels.size))
207 const hue = labels.get(label)
208 for (let y = r; y <= r2; y++) for (let x = c; x <= c2; x++) if (cell(y, x).trim()) color[y]![x] = hue
209 }
210
211 const bars = [...new Set(grid.flatMap(row => row.flatMap((ch, c) => (BLOCK.test(ch) && row[c - 1] !== ch ? [c] : []))))].sort((a, b) => a - b)
212 const ends = bars.map(x => {
213 const row = grid.find(row => BLOCK.test(row[x] ?? ''))!
214 let end = x
215 while (row[end + 1] === row[x]) end++
216 return end
217 })
218 const tops = bars.map(x => {
219 const r = grid.findIndex(row => BLOCK.test(row[x] ?? ''))
220 return r * 2 + (grid[r]![x] === '▄' ? 1 : 0)
221 })
222 const single = bars.length > 1 && bars.every((x, i) => i === 0 || x - ends[i - 1]! > 2)
223 const barColor = (i: number) => (single ? (tops[i] === Math.min(...tops) ? t.emphasis ?? t.accent : t.quote) : next(i))
224 series?.forEach((row, r) => row.forEach((owner, c) => owner >= 0 && grid[r]?.[c]?.trim() && (color[r]![c] = next(owner))))
225 grid.forEach((row, r) =>
226 row.forEach((ch, c) => {
227 if (color[r]![c] !== undefined) return
228 const start = barStart(row, c)
229 if (start >= 0) color[r]![c] = barColor(bars.indexOf(start))
230 else if (ch === '·') color[r]![c] = t.rule
231 else if (ARROW.test(ch)) color[r]![c] = t.accent
232 else if (LINE.test(ch)) color[r]![c] = t.diagram
233 else if (/^\d+[┤┼]/.test(row.slice(c).join(''))) color[r]![c] = t.number
234 else color[r]![c] = t.diagramText
235 }),
236 )
237 return { grid, colors: color }
238}
239
240const paintPie = (art: string, slices: number[][], style: Style): Painted => {
241 const t = style.theme
242 const palette = diagramPalette(t)
243 const grid = art.split('\n').map(cells)
244 const hue = (slice: number) => (slice < 0 ? t.diagramText : palette[slice % palette.length])
245 return { grid, colors: grid.map((row, r) => row.map((_, c) => hue(slices[r]?.[c] ?? -1))) }
246}
247
248const painted = new WeakMap<Theme, Map<string, Painted>>()
249
250const piePainted = new WeakMap<Theme, WeakMap<number[][], Painted>>()
251
252const painting = (style: Style, art: string, slices?: number[][], series?: number[][]): Painted => {
253 if (!slices) {
254 const cache = painted.get(style.theme) ?? new Map<string, Painted>()
255 painted.set(style.theme, cache)
256 return remember(cache, art, () => paint(art, style, series))
257 }
258 const cache = piePainted.get(style.theme) ?? new WeakMap<number[][], Painted>()
259 piePainted.set(style.theme, cache)
260 const done = cache.get(slices) ?? paintPie(art, slices, style)
261 cache.set(slices, done)
262 return done
263}
264
265export const boxArt = ({ Box, Text }: ElementTable, style: Style, art: string, key: string, marks: [string[], Mark][] = [], slices?: number[][], series?: number[][]): RenderElement => {
266 const { grid, colors } = painting(style, art, slices, series)
267 const visual = style.reorder && style.shape === 'visual' && hasRtl(art)
268 return (
269 <Box key={key} flexDirection="column" paddingLeft={mirrored(style) ? 0 : 2}>
270 {grid.map((row, i) => {
271 const { cells: chars, from } = mirrored(style) ? led(row, holdRow(row)) : style.shape === 'engine' ? holdEngine(row) : visual ? holdVisual(row) : asIs(row)
272 const marked: (Mark | undefined)[] = row.map(() => undefined)
273 for (const [phrase, mark] of marks)
274 for (let c = 0; c + phrase.length <= row.length; c++)
275 if (phrase.every((ch, k) => row[c + k] === ch)) for (let k = 0; k < phrase.length; k++) marked[c + k] = mark
276 const hueAt = (p: number) => colors[i]?.[from[p]!]
277 const markAt = (p: number) => marked[from[p]!]
278 const parts: RenderElement[] = []
279 let at = 0
280 while (at < chars.length) {
281 const hue = hueAt(at)
282 const mark = markAt(at)
283 let end = at + 1
284 while (end < chars.length && hueAt(end) === hue && markAt(end) === mark) end++
285 parts.push(<Text key={`t${parts.length}`} color={hue} {...mark}>{chars.slice(at, end).join('')}</Text>)
286 at = end
287 }
288 return <Text key={`${key}.${i}`} {...heldLtr(style)}>{parts.length ? parts : ' '}</Text>
289 })}
290 </Box>
291 )
292}
293
294const EDGE_LABEL = /(-[-.=]+\s*)"([^"\n]+)"(\s*[-.=]+>)|\|([^|\n]+)\|/g
295
296const cap = (label: string, max: number) => {
297 const flat = label.replace(/<br\s*\/?>/gi, ' ').replace(/\s+/g, ' ').trim()
298 const chars = graphemes(flat)
299 return chars.length > max ? `${chars.slice(0, max - 1).join('').trimEnd()}…` : flat
300}
301
302export const shortenEdgeLabels = (source: string, max: number): string =>
303 source.replace(EDGE_LABEL, (_, open, quoted, close, piped) =>
304 quoted !== undefined ? `${open}"${cap(quoted, max)}"${close}` : `|${cap(piped, max)}|`)
305
306const pieColorsOf = (style: Style) => (style.pieStyle === 'round' ? diagramPalette(style.theme).length : 0)
307
308export const drawDiagrams = (el: ElementTable, style: Style, blocks: Block[], columns: number): Drawn => {
309 const drawn: Drawn = new Map()
310 const pieColors = pieColorsOf(style)
311 if (style.mermaid) {
312 for (const [i, block] of blocks.entries()) {
313 if (block.kind !== 'code' || block.lang.toLowerCase() !== 'mermaid') continue
314 const source = block.lines.join('\n')
315 let narrowest = Infinity
316 for (const max of [Infinity, 24, 12]) {
317 const art = mermaidArt(max === Infinity ? source : shortenEdgeLabels(source, max), style.mermaidAscii, columns, pieColors)
318 const wide = art === null ? Infinity : artWidth(art.text)
319 narrowest = Math.min(narrowest, wide)
320 if (art === null || wide > columns - 2) continue
321 drawn.set(i, { element: boxArt(el, style, art.text, `b${i}`, inlineMarks(source), art.slices, art.series), art: art.text })
322 break
323 }
324 if (!drawn.has(i) && !block.isOpen) {
325 const kind = unsupportedKind(source)
326 drawn.set(i, { note: kind ? `${kind} diagrams draw as source for now` : narrowest === Infinity ? 'diagram failed to render' : `diagram is ${narrowest} cols, terminal is ${columns}` })
327 }
328 }
329 }
330 for (const [i, block] of blocks.entries()) {
331 if (block.kind !== 'code' || !isFigureLang(block.lang)) continue
332 const figure = drawFigure(el, style, block, columns, `b${i}`)
333 if (figure) drawn.set(i, figure)
334 }
335 return drawn
336}
337hooks/render.tsx 2690 lines1import type { ElementTable, RenderElement, RenderNode, TextHoverProps } from 'claude-code'
2
3import { tableHtml, tableText } from './html'
4import type { Block, Inline } from './markdown'
5import { mathOf } from './latex'
6import { CONTROL, displayText, inlineText, isWebLink, nestedBlocks, texText } from './markdown'
7import type { Flow } from './rtl'
8import { LTR_BLANK, ROW_MARK, ROW_MARK_TEXT, WALL, codeVisual, commentTail, commentVisual, containsRtl, flow, hasRtl, heldCell, listMarker, opensLatin, terminalLine } from './rtl'
9import type { Style, Theme } from './theme'
10import type { PrismToken } from './vendor/prism.js'
11import { languages, tokenize } from './vendor/prism.js'
12
13const WIDE = /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{20000}-\u{3FFFD}\u20E3]|\p{Emoji_Presentation}|\p{Extended_Pictographic}\uFE0F/u
14const segmenter = new Intl.Segmenter()
15
16export const graphemes = (s: string): string[] => [...segmenter.segment(s)].map(g => g.segment)
17
18const CLUSTER_UNITS = 32
19
20const clusters = (s: string, count: number): string => {
21 let n = 0
22 for (const { index, segment } of segmenter.segment(s)) if (n++ === count || index + segment.length > count * CLUSTER_UNITS) return s.slice(0, index)
23 return s
24}
25
26export const cells = (s: string): string[] => (/^[ -~]*$/.test(s) ? [...s] : graphemes(s).flatMap(g => (WIDE.test(g) ? [g, ''] : [g])))
27
28const ZERO = /^[\p{M}\p{Default_Ignorable_Code_Point}]+$/u
29
30export const width = (s: string): number =>
31 /^[ -~]*$/.test(s) ? s.length
32 : s.length === 1 ? (ZERO.test(s) ? 0 : WIDE.test(s) ? 2 : 1)
33 : graphemes(s).reduce((w, g) => (ZERO.test(g) ? w : w + (WIDE.test(g) ? 2 : 1)), 0)
34
35const widestLine = (text: string): number => Math.max(...text.split('\n').map(width))
36
37const wrapRanges = (text: string, w: number): [number, number][] => {
38 const br = text.indexOf('\n')
39 if (br >= 0) return [...wrapRanges(text.slice(0, br), w), ...wrapRanges(text.slice(br + 1), w).map(([a, b]): [number, number] => [a + br + 1, b + br + 1])]
40 if (width(text) <= w) return [[0, text.length]]
41 const out: [number, number][] = []
42 let line: [number, number] | undefined
43 let used = 0
44 for (const word of text.matchAll(/\S+/g)) {
45 let start = word.index
46 const end = start + word[0].length
47 let size = width(word[0])
48 if (size > w) {
49 if (line) out.push(line)
50 line = undefined
51 let cut = start
52 let taken = 0
53 for (const g of graphemes(text.slice(start, end))) {
54 const step = width(g)
55 if (cut > start && taken + step > w) {
56 out.push([start, cut])
57 start = cut
58 size -= taken
59 taken = 0
60 if (size <= w) break
61 }
62 cut += g.length
63 taken += step
64 }
65 }
66 if (start === end) continue
67 const joined = line ? used + width(text.slice(line[1], start)) + size : Infinity
68 if (line && joined <= w) {
69 line = [line[0], end]
70 used = joined
71 } else {
72 if (line) out.push(line)
73 line = [start, end]
74 used = size
75 }
76 }
77 if (line) out.push(line)
78 return out.length ? out : [[0, 0]]
79}
80
81const sliceInline = (nodes: Inline[], from: number, to: number): Inline[] => {
82 const out: Inline[] = []
83 let at = 0
84 for (const n of nodes) {
85 const length = inlineText([n]).length
86 const a = Math.max(from - at, 0)
87 const b = Math.min(to - at, length)
88 at += length
89 if (a >= b) continue
90 if ('children' in n) out.push({ ...n, children: sliceInline(n.children, a, b) })
91 else out.push({ ...n, text: n.text.slice(a, b) })
92 }
93 return out
94}
95
96const hasLink = (nodes: Inline[]): boolean => nodes.some(n => n.kind === 'link' || ('children' in n && hasLink(n.children)))
97
98const headerRuns = (nodes: Inline[]): Inline[] =>
99 nodes.flatMap(n => (n.kind === 'footnote' ? [n] : 'children' in n ? headerRuns(n.children) : [{ kind: 'text' as const, text: n.text }]))
100 .reduce<Inline[]>((out, n) => {
101 const last = out[out.length - 1]
102 return n.kind === 'text' && last?.kind === 'text' ? [...out.slice(0, -1), { kind: 'text', text: last.text + n.text }] : [...out, n]
103 }, [])
104
105const HTTP_LINKS_FROM = [2, 1, 289]
106const EDITOR_LINKS_FROM = [2, 1, 294]
107const CLICKABLE_MARKS_FROM = [2, 1, 295]
108
109const releaseFrom = (from: readonly number[]) => (base?: string): boolean => {
110 const m = /^(\d+)\.(\d+)\.(\d+)/.exec(base ?? '')
111 if (!m) return false
112 const version = [Number(m[1]), Number(m[2]), Number(m[3])]
113 const at = version.findIndex((n, i) => n !== from[i])
114 return at === -1 || version[at]! > from[at]!
115}
116
117export const takesHttpLinks = releaseFrom(HTTP_LINKS_FROM)
118
119export const takesEditorLinks = releaseFrom(EDITOR_LINKS_FROM)
120
121export const takesClickableMarks = releaseFrom(CLICKABLE_MARKS_FROM)
122
123export const fileRoot = (distro?: string): string => (distro ? `file://wsl.localhost/${encodeURIComponent(distro)}` : 'file://')
124
125export type TerminalEnv = Partial<Record<'FORCE_HYPERLINK' | 'TERM_PROGRAM' | 'TERM_PROGRAM_VERSION' | 'TERM' | 'WT_SESSION' | 'LC_TERMINAL' | 'VTE_VERSION' | 'TERMINAL_EMULATOR', string>>
126
127const HYPERLINK_TERMINALS = ['ghostty', 'Hyper', 'kitty', 'alacritty', 'iTerm.app', 'iTerm2', 'WarpTerminal', 'Orca']
128
129const versionOf = (value = ''): number[] => {
130 const short = /^(\d{1,2})(\d{2})$/.exec(value)
131 return short ? [0, Number(short[1])] : value.split('.').map(n => Number.parseInt(n, 10))
132}
133
134const atLeast = (value: string | undefined, major: number, minor: number): boolean => {
135 const [a = Number.NaN, b = Number.NaN] = versionOf(value)
136 return a > major || (a === major && b >= minor)
137}
138
139const programLinks = (program: string, version: string | undefined): boolean =>
140 HYPERLINK_TERMINALS.includes(program)
141 || (program === 'WezTerm' && atLeast(version, 20200620, 0))
142 || (program === 'vscode' && atLeast(version, 1, 72))
143 || (program === 'tmux' && atLeast(version, 3, 4))
144
145export const drawsHyperlinks = (env: TerminalEnv): boolean => {
146 if (env.FORCE_HYPERLINK) return Number.parseInt(env.FORCE_HYPERLINK, 10) !== 0
147 const term = env.TERM ?? ''
148 const vte = env.VTE_VERSION
149 return env.WT_SESSION !== undefined
150 || programLinks(env.TERM_PROGRAM ?? '', env.TERM_PROGRAM_VERSION)
151 || HYPERLINK_TERMINALS.includes(env.LC_TERMINAL ?? '')
152 || (vte !== undefined && vte !== '0.50.0' && atLeast(vte, 0, 50))
153 || term === 'alacritty' || term.includes('kitty')
154 || env.TERMINAL_EMULATOR === 'JetBrains-JediTerm'
155}
156
157type Reach = Pick<Style, 'httpLinks' | 'editorLinks' | 'fileLinks' | 'pathLinks' | 'cwd' | 'home' | 'found'>
158
159const LAUNCHERS = new Set([
160 'app', 'command', 'tool', 'terminal', 'pkg', 'mpkg', 'mobileconfig', 'prefpane', 'workflow', 'action', 'fileloc', 'inetloc', 'webloc',
161 'exe', 'com', 'scr', 'pif', 'cpl', 'msi', 'msp', 'msu', 'msix', 'msixbundle', 'appx', 'appxbundle', 'appinstaller', 'application', 'appref-ms', 'vsix',
162 'bat', 'cmd', 'ps1', 'psc1', 'vbs', 'vbe', 'js', 'jse', 'wsf', 'wsh', 'wsc', 'hta', 'chm', 'msc', 'reg', 'xll', 'wsb', 'diagcab', 'ahk', 'au3',
163 'lnk', 'url', 'scf', 'settingcontent-ms',
164 'desktop', 'sh', 'bash', 'zsh', 'csh', 'ksh', 'run', 'appimage', 'deb', 'rpm', 'snap', 'flatpak', 'flatpakref',
165 'jar', 'jnlp', 'py', 'pyw', 'pyz', 'pyzw', 'pyc', 'pl', 'rb', 'rbw',
166])
167
168const unescaped = (text: string): string => text.replace(/%([0-9a-f]{2})/gi, (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)))
169
170const extensionOf = (name: string): string => /\.([^.]*)$/.exec(name.replace(/[. ]+$/, ''))?.[1] ?? ''
171
172const launches = (href: string): boolean => {
173 const path = unescaped(href.replace(/[?#].*$/, '')).toLowerCase().replace(/[/\\]+$/, '')
174 const name = path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1)
175 return /\.app[/\\]/.test(path) || name.split(/[:\u0000-\u001f]/).some(part => LAUNCHERS.has(extensionOf(part)))
176}
177
178const isHyperlink = (href: string, reach: Reach): boolean =>
179 (reach.httpLinks ? /^https?:/i : /^(https:|http:\/\/localhost(:\d+)?([/?#]|$))/i).test(href)
180 || (reach.editorLinks && /^vscode(-insiders)?:\/\/file\//i.test(href))
181 || (reach.fileLinks !== null && /^file:/i.test(href) && !launches(href))
182
183const plainLink = (text: string, href: string): string => {
184 const target = href.replace(/^mailto:/i, '')
185 return text === target || `http://${text}` === target ? target : `${text} (${target})`
186}
187
188const LINK_MAX = 2048
189
190const utf8Bytes = (cp: number): number => (cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4)
191
192const encodedLength = (href: string): number =>
193 [...href].reduce((length, ch) => {
194 const cp = ch.codePointAt(0)!
195 return length + (cp > 0x20 && cp < 0x7f ? 1 : 3 * utf8Bytes(cp))
196 }, 0)
197
198const fileHref = (root: string, href: string): string => {
199 const local = /^file:(?:\/\/(?:localhost)?)?(\/(?![a-z]:|\/)[^?#]*)(.*)$/i.exec(href)
200 return local && root !== 'file://' ? `${root}${local[1]}${local[2]}` : href
201}
202
203const absolutePath = (reach: Reach, path: string): string | undefined => {
204 const base = path.startsWith('~') ? reach.home : path.startsWith('.') ? reach.cwd : '/'
205 if (!base) return undefined
206 const parts: string[] = []
207 for (const part of `${slashes(base)}/${path.replace(/^~/, '').replace(/(?<=[^/.])\.+$/, '')}`.split('/')) {
208 if (part === '..') parts.pop()
209 else if (part !== '.' && part !== '') parts.push(part)
210 }
211 return `/${parts.join('/')}${path.endsWith('/') ? '/' : ''}`
212}
213
214const pathHref = (reach: Reach, path: string): string | undefined => {
215 const target = absolutePath(reach, path)
216 if (target === undefined || reach.fileLinks === null) return undefined
217 const href = `${reach.fileLinks}${encodeURI(target).replace(/[?#]/g, encodeURIComponent)}`
218 return href.length <= LINK_MAX && !launches(href) ? href : undefined
219}
220
221const toolHref = (reach: Reach, path: string): string | undefined => {
222 if (!reach.pathLinks || reach.fileLinks === null) return undefined
223 const forward = path.replace(/\\/g, '/')
224 if (/^[a-z]:\//i.test(forward)) return pathHref({ ...reach, fileLinks: 'file://' }, forward)
225 if (!forward.startsWith('//')) return pathHref(reach, /^[/~.]/.test(forward) ? forward : `./${forward}`)
226 const href = `file:${encodeURI(forward).replace(/[?#]/g, encodeURIComponent)}`
227 return href.length <= LINK_MAX && !launches(href) ? href : undefined
228}
229
230type LinkPiece = { text: string; path?: string }
231
232const pieceText = (pieces: LinkPiece[]): string => pieces.map(p => p.text).join('')
233
234const drawPieces = (el: ElementTable, style: Style, pieces: LinkPiece[]): string | (string | RenderElement)[] => {
235 const hrefs = pieces.map(p => (p.path === undefined ? undefined : toolHref(style, p.path)))
236 return hrefs.some(Boolean) ? pieces.map((p, i) => { const href = hrefs[i]; return href ? <el.Link key={`p${i}`} href={href} label={p.text} /> : p.text }) : pieceText(pieces)
237}
238
239const decoded = (text: string): string | undefined => {
240 try {
241 return decodeURIComponent(text)
242 } catch {
243 return undefined
244 }
245}
246
247const linkPath = (root: string, href: string): string | undefined => {
248 const local = root !== 'file://' && href.startsWith(`${root}/`) ? href.slice(root.length) : href.replace(/^file:(\/\/(localhost)?(?=\/))?/i, '')
249 return decoded(local.replace(/[?#].*$/, ''))
250}
251
252const labelPath = (reach: Reach, root: string, label: string): string | undefined => {
253 if (/^file:/i.test(label)) return linkPath(root, fileHref(root, label))
254 if (/^([a-z]:[\\/]|\\\\)/i.test(label)) return label.replace(/\\/g, '/').replace(/^(?=[a-z]:)/i, '/')
255 if (label.startsWith('/')) return label
256 return /^(~|\.{1,2})\//.test(label) ? absolutePath(reach, label) : undefined
257}
258
259const withoutSlash = (path: string | undefined): string | undefined => path?.replace(/(?<=.)\/+$/, '')
260
261const hidesFile = (reach: Reach, n: Extract<Inline, { kind: 'link' }>, href: string): boolean => {
262 const label = n.text.trim().replace(/[.,;:!?]+$/, '')
263 if (!/^file:/i.test(n.href) || label === n.href) return false
264 const root = reach.fileLinks ?? 'file://'
265 const shown = withoutSlash(labelPath(reach, root, label))
266 return shown === undefined || shown !== withoutSlash(linkPath(root, href))
267}
268
269const drawnLink = (n: Extract<Inline, { kind: 'link' }>, reach: Reach): Inline => {
270 const href = reach.fileLinks !== null && /^file:/i.test(n.href) ? fileHref(reach.fileLinks, n.href) : n.href
271 if (!isHyperlink(n.href, reach) || encodedLength(href) > LINK_MAX || hidesFile(reach, n, href)) return { kind: 'text', text: plainLink(n.text, n.href) }
272 return href === n.href ? n : { ...n, href }
273}
274
275const linksAsPath = (path: string): boolean => !path.startsWith('/') || /^\/[^/]+\/+[^/]/.test(path.replace(/\.+$/, ''))
276
277const drawnPath = (n: Extract<Inline, { kind: 'path' }>, reach: Reach): Inline => {
278 const href = reach.pathLinks && linksAsPath(n.text) ? pathHref(reach, n.text) : undefined
279 return href === undefined ? n : { ...n, href }
280}
281
282const PART = String.raw`[\p{L}\p{N}_@+-]+`
283const NAME = String.raw`\.?${PART}(?:\.${PART})*`
284const LOOSE_PATH = new RegExp(String.raw`(?<![\p{L}\p{N}_/\\.:~@+-])(?:[A-Za-z]:[\\/](?:${NAME}[\\/])*(?:${NAME})?|${NAME}(?:\/${NAME})*\/(?:${NAME})?|${PART}(?:\.${PART})+)(?![\p{L}\p{N}_/\\@+-]|\.[\p{L}\p{N}])`, 'gu')
285
286type Probe = { key: string; href: string }
287
288const looseProbe = (reach: Reach, spelling: string): Probe | undefined => {
289 const drive = /^[a-z]:[\\/]/i.test(spelling)
290 if (!drive && !reach.cwd) return undefined
291 const href = toolHref(reach, spelling)
292 const key = drive ? spelling.replace(/\\/g, '/') : `${slashes(reach.cwd)}/${spelling}`
293 return href === undefined ? undefined : { key: key.replace(/(?<=[^/:])\/+$/, ''), href }
294}
295
296const looseSpellings = (text: string): RegExpExecArray[] => [...text.matchAll(LOOSE_PATH)]
297
298const foundProbe = (reach: Reach, spelling: string): Probe | undefined => {
299 const probe = looseProbe(reach, spelling)
300 return probe && reach.found?.has(probe.key) ? probe : undefined
301}
302
303const loosePaths = (n: Extract<Inline, { kind: 'text' }>, reach: Reach): Inline[] => {
304 const out: Inline[] = []
305 let at = 0
306 for (const m of looseSpellings(n.text)) {
307 const probe = foundProbe(reach, m[0])
308 if (!probe) continue
309 if (m.index > at) out.push({ kind: 'text', text: n.text.slice(at, m.index) })
310 out.push({ kind: 'path', text: m[0], href: probe.href })
311 at = m.index + m[0].length
312 }
313 if (at === 0) return [n]
314 if (at < n.text.length) out.push({ kind: 'text', text: n.text.slice(at) })
315 return out
316}
317
318const looseCode = (n: Extract<Inline, { kind: 'code' }>, reach: Reach): Inline => {
319 const probe = isWholePath(n.text) ? foundProbe(reach, n.text) : undefined
320 return probe ? { ...n, href: probe.href } : n
321}
322
323const isWholePath = (text: string): boolean => looseSpellings(text).some(m => m[0] === text)
324
325const looseNode = (n: Inline, reach: Reach): Inline | Inline[] => {
326 if (n.kind === 'text') return loosePaths(n, reach)
327 return n.kind === 'code' ? looseCode(n, reach) : n
328}
329
330const linked = (node: Inline, reach: Reach): Inline => {
331 const n: Inline = node.kind === 'image' && isWebLink(node.src) ? { kind: 'link', text: node.text, href: node.src } : node
332 if (n.kind === 'link') return drawnLink(n, reach)
333 if (n.kind === 'path') return drawnPath(n, reach)
334 return 'children' in n ? { ...n, children: hyperlinks(n.children, reach) } : n
335}
336
337const hyperlinks = (nodes: Inline[], reach: Reach): Inline[] =>
338 reach.found?.size ? nodes.flatMap(node => looseNode(linked(node, reach), reach)) : nodes.map(node => linked(node, reach))
339
340const spellingsIn = (nodes: Inline[]): string[] =>
341 nodes.flatMap(n => {
342 if ('children' in n) return spellingsIn(n.children)
343 if (n.kind === 'code') return isWholePath(n.text) ? [n.text] : []
344 return n.kind === 'text' ? looseSpellings(n.text).map(m => m[0]) : []
345 })
346
347const inlinesOf = (block: Block): Inline[][] => {
348 switch (block.kind) {
349 case 'heading':
350 case 'paragraph':
351 return [block.inline]
352 case 'list':
353 return block.items.map(item => item.inline)
354 case 'table':
355 return [...block.header, ...block.rows.flat()]
356 case 'notes':
357 return block.notes.map(note => note.inline)
358 default:
359 return []
360 }
361}
362
363const spelled = new WeakMap<Block, string[]>()
364
365export const pathsToProbe = (blocks: Block[], reach: Reach): string[] => {
366 if (!reach.pathLinks || reach.fileLinks === null) return []
367 return nestedBlocks(blocks).flatMap(block => {
368 const spellings = spelled.get(block) ?? inlinesOf(block).flatMap(spellingsIn)
369 spelled.set(block, spellings)
370 return spellings.flatMap(spelling => looseProbe(reach, spelling)?.key ?? [])
371 })
372}
373
374const hyperlinkBlock = (block: Block, reach: Reach): Block => {
375 const drawn = (nodes: Inline[]) => hyperlinks(nodes, reach)
376 switch (block.kind) {
377 case 'heading':
378 case 'paragraph':
379 return { ...block, inline: drawn(block.inline) }
380 case 'list':
381 return { ...block, items: block.items.map(item => ({ ...item, inline: drawn(item.inline) })) }
382 case 'table':
383 return { ...block, header: block.header.map(drawn), rows: block.rows.map(r => r.map(drawn)) }
384 case 'notes':
385 return { ...block, notes: block.notes.map(note => ({ ...note, inline: drawn(note.inline) })) }
386 default:
387 return block
388 }
389}
390
391const hyperlinked = new WeakMap<Block, Record<string, Block>>()
392
393const drawable = (block: Block, reach: Reach): Block => {
394 const cached = hyperlinked.get(block) ?? {}
395 hyperlinked.set(block, cached)
396 const key = `${+reach.httpLinks}${+reach.editorLinks}${reach.fileLinks ?? ''}${reach.pathLinks ? `\0${reach.home}\0${reach.cwd}\0${reach.found?.size ?? 0}` : ''}`
397 return (cached[key] ??= hyperlinkBlock(block, reach))
398}
399
400const mostLines = (text: string, w: number): number => (text.match(/\S+/g)?.length ?? 0) + Math.ceil(width(text) / w)
401
402const textRows = (text: string, w: number): number =>
403 text.split('\n').reduce((sum, line) => sum + (width(line) <= w ? 1 : mostLines(line, Math.max(1, w))), 0)
404
405const heightOf = (blocks: Block[], w: number): number => blocks.reduce((sum, block, b) => sum + (b ? 1 : 0) + blockHeight(block, w), 0)
406
407const blockHeight = (block: Block, w: number): number => {
408 switch (block.kind) {
409 case 'heading':
410 return 2 * textRows(displayText(block.inline), w - 4) + 2
411 case 'paragraph':
412 return textRows(displayText(block.inline), w)
413 case 'list':
414 return block.items.reduce((sum, item) => {
415 const pad = item.depth * 2 + item.marker.length + 4
416 return sum + textRows(displayText(item.inline), w - pad) + (item.blocks ? heightOf(item.blocks, w - pad) + 1 : 0)
417 }, textRows(`${'━'.repeat(20)} ${block.items.length}/${block.items.length} done`, w))
418 case 'code':
419 return block.lines.reduce((sum, line) => sum + textRows(line, w - 8), 3)
420 case 'table': {
421 const { natural, words } = tableSize(block)
422 const widths = columnWidths(natural, w - 4, 3, words)
423 const tallest = (cells: Inline[][]) => Math.max(1, ...widths.map((cw, c) => textRows(displayText(cells[c] ?? []), cw)))
424 return block.rows.reduce((sum, row) => sum + 1 + tallest(row), 4 + tallest(block.header))
425 }
426 case 'quote':
427 return Math.max(1, heightOf(block.blocks, w - 2))
428 case 'alert':
429 return 3 + heightOf(block.blocks, w - 4)
430 case 'rule':
431 return 1
432 case 'notes':
433 return block.notes.reduce((sum, note) => sum + textRows(`${note.mark} ${displayText(note.inline)}`, w), 1)
434 }
435}
436
437const wrapInline = (nodes: Inline[], w: number): Inline[][] => {
438 const text = inlineText(nodes)
439 return width(text) <= w && !text.includes('\n') ? [nodes] : wrapRanges(text, w).map(([a, b]) => sliceInline(nodes, a, b))
440}
441
442export const mirrored = (style: Style) => style.shape === 'mirror'
443
444export const heldLtr = (style: Style) => (style.shape === 'engine' ? { dir: 'ltr' as const } : {})
445
446const heldLabel = (style: Style, label: string, text: string): string => (mirrored(style) && hasRtl(text) ? label.replace(/ $/, LTR_BLANK) : label)
447
448const heldRow = (el: ElementTable, style: Style, key: string, label: string, text: string, cell: RenderNode): RenderElement => (
449 <el.Box key={key} flexDirection="row">
450 <el.Text dimColor>{heldLabel(style, label, text)}</el.Text>
451 {cell}
452 </el.Box>
453)
454
455const flows = new Map<string, Flow | null>()
456const flowOf = (style: Style, nodes: Inline[], columns: number, mark = !(style.inside && mirrored(style))) =>
457 style.reorder && containsRtl(nodes) ? remember(flows, `${style.shape}\0${mark}\0${columns}\0${JSON.stringify(nodes)}`, () => flow(nodes, columns, width, style.shape, mark), 2000) : null
458
459const cellFlow = (style: Style, nodes: Inline[], held: boolean, mark: boolean) =>
460 held && style.reorder && containsRtl(nodes) ? remember(flows, `held\0${JSON.stringify(nodes)}`, () => heldCell(nodes), 2000) : flowOf(style, nodes, Infinity, mark)
461
462const noteHover = (style: Style, note: number | undefined) =>
463 note === undefined || style.noteKey === undefined ? {} : { hover: { scope: `fn:${style.noteKey}:${note}`, inverse: true } }
464
465const renderInline = (el: ElementTable, style: Style, nodes: Inline[], keyBase: string): RenderElement[] => {
466 const { Text } = el
467 const t = style.theme
468 return nodes.map((n, i) => {
469 const key = `${keyBase}.${i}`
470 switch (n.kind) {
471 case 'text':
472 return <Text key={key}>{n.text}</Text>
473 case 'strong':
474 return <Text key={key} bold color={t.strong}>{renderInline(el, style, n.children, key)}</Text>
475 case 'emphasis':
476 return <Text key={key} italic color={t.emphasis}>{renderInline(el, style, n.children, key)}</Text>
477 case 'strike':
478 return <Text key={key} strikethrough dimColor>{renderInline(el, style, n.children, key)}</Text>
479 case 'code':
480 return <Text key={key} color={t.inlineCode}>{n.href === undefined ? n.text : <el.Link href={n.href} label={n.text} />}</Text>
481 case 'math':
482 return <Text key={key} italic color={t.emphasis}>{n.text}</Text>
483 case 'link':
484 return n.text === n.href ? <Text key={key} color={t.link}><el.Link href={n.href} /></Text> : <el.Link key={key} href={n.href}><Text color={t.link}>{n.text}</Text></el.Link>
485 case 'image':
486 return <Text key={key} color={t.link}>{n.text}</Text>
487 case 'number':
488 return <Text key={key} color={t.number}>{n.text}</Text>
489 case 'path':
490 return <Text key={key} color={t.path}>{n.href === undefined ? n.text : <el.Link href={n.href} label={n.text} />}</Text>
491 case 'dim':
492 return n === ROW_MARK ? <Text key={key} color={t.rule}>{n.text}</Text> : <Text key={key} dimColor>{n.text}</Text>
493 case 'footnote':
494 return <Text key={key} color={t.accent} {...noteHover(style, n.note)}>{n.text}</Text>
495 }
496 })
497}
498
499const renderFlow = (el: ElementTable, style: Style, lines: Inline[][], key: string, props: TextLook = {}) => {
500 const { Text } = el
501 return lines.map((line, i) => <Text key={`${key}.${i}`} {...props}>{renderInline(el, style, line, `${key}.${i}`)}</Text>)
502}
503
504type Mark = { start: number; end: number; text: string; note: number }
505type TextLook = { italic?: boolean; color?: string; bold?: boolean; dimColor?: boolean; strikethrough?: boolean }
506
507const marksIn = (nodes: Inline[], at = 0): Mark[] => {
508 const out: Mark[] = []
509 for (const n of nodes) {
510 const length = inlineText([n]).length
511 if (n.kind === 'footnote' && n.note !== undefined) out.push({ start: at, end: at + length, text: n.text, note: n.note })
512 else if ('children' in n) out.push(...marksIn(n.children, at))
513 at += length
514 }
515 return out
516}
517
518const piecesOf = (text: string, a: number, b: number, columns: number, marks: Mark[]): (readonly [number, number])[] => {
519 if (width(text.slice(a, b)) <= columns) return [[a, b]]
520 const out: [number, number][] = []
521 let start = a
522 let at = a
523 let taken = 0
524 for (const g of graphemes(text.slice(a, b))) {
525 const step = width(g)
526 if (at > start && taken + step > columns) {
527 const cut = marks.find(m => m.start < at && at < m.end)?.start ?? at
528 if (cut > start) {
529 out.push([start, cut])
530 taken = width(text.slice(cut, at))
531 start = cut
532 }
533 }
534 at += g.length
535 taken += step
536 }
537 out.push([start, b])
538 return out
539}
540
541const pressInline = (el: ElementTable, style: Style, nodes: Inline[], columns: number, key: string, tip: Tip | undefined, look: TextLook = {}, box: { justifyContent?: 'flex-start' | 'flex-end' | 'center' } = {}): RenderElement | null => {
542 const marks = tip ? marksIn(nodes).flatMap(m => {
543 const press = tip(m.note)
544 return press ? [{ ...m, press }] : []
545 }) : []
546 if (!marks.length) return null
547 const { Box, Text, Button } = el
548 const run = (a: number, b: number) => <Text key={`${key}.t${a}`} {...look}>{renderInline(el, style, sliceInline(nodes, a, b), `${key}.t${a}`)}</Text>
549 const text = inlineText(nodes)
550 const words = [...text.matchAll(/\s*\S+\s*/g)].flatMap(m => piecesOf(text, m.index, m.index + m[0].length, Math.max(1, columns), marks))
551 return (
552 <Box key={key} flexDirection="row" flexWrap="wrap" {...box}>
553 {words.map(([a, b]) => {
554 const inside = marks.filter(m => m.start >= a && m.end <= b)
555 if (!inside.length) return run(a, b)
556 const parts: RenderElement[] = []
557 let at = a
558 for (const m of inside) {
559 if (m.start > at) parts.push(run(at, m.start))
560 parts.push(
561 <Button key={`${key}.n${m.start}`} plain {...noteHover(style, m.note)} onPress={m.press}>
562 <Text color={style.theme.accent} bold={look.bold}>{m.text}</Text>
563 </Button>,
564 )
565 at = m.end
566 }
567 if (at < b) parts.push(run(at, b))
568 return <Box key={`${key}.w${a}`} flexDirection="row" flexShrink={0}>{parts}</Box>
569 })}
570 </Box>
571 )
572}
573
574export const PRISM_COLORS: Record<string, keyof Theme> = {
575 comment: 'codeComment', prolog: 'codeComment', doctype: 'codeComment', cdata: 'codeComment',
576 string: 'codeString', char: 'codeString', 'template-string': 'codeString', 'attr-value': 'codeString', url: 'codeString',
577 number: 'number', boolean: 'number', constant: 'number', symbol: 'number', inserted: 'number',
578 keyword: 'codeFlag', important: 'codeFlag', atrule: 'codeFlag', rule: 'codeFlag', deleted: 'codeFlag',
579 function: 'codeCommand', 'class-name': 'codeCommand', builtin: 'codeCommand', key: 'codeCommand', selector: 'codeCommand',
580 property: 'link', tag: 'link', 'attr-name': 'emphasis', variable: 'emphasis', regex: 'path',
581}
582
583type Segment = { text: string; color?: string; italic: boolean }
584
585const shownCode = (text: string, style: Style, room?: number, command = false): string => (style.reorder ? codeVisual(text, style.shape, room, width, command) : text)
586
587const flatten = (tokens: PrismToken[], style: Style, color?: string, italic = false): Segment[] =>
588 tokens.flatMap(token => {
589 if (typeof token === 'string') return [{ text: token, color, italic }]
590 const names = [token.type, ...(Array.isArray(token.alias) ? token.alias : token.alias ? [token.alias] : [])]
591 const slot = names.map(n => PRISM_COLORS[n]).find(Boolean)
592 const inner = Array.isArray(token.content) ? token.content : [token.type === 'comment' && typeof token.content === 'string' && style.reorder ? commentVisual(token.content, style.shape) : token.content]
593 return flatten(inner, style, slot ? style.theme[slot] : color, italic || token.type === 'comment')
594 })
595
596export const remember = <T,>(cache: Map<string, T>, key: string, make: () => T, limit = 200): T => {
597 const hit = cache.get(key)
598 if (hit !== undefined) {
599 cache.delete(key)
600 cache.set(key, hit)
601 return hit
602 }
603 const value = make()
604 cache.set(key, value)
605 if (cache.size > limit) cache.delete(cache.keys().next().value!)
606 return value
607}
608
609const highlighted = new WeakMap<Theme, Map<string, Segment[][]>>()
610
611const grammarFor = (lang: string) => {
612 const name = lang.toLowerCase()
613 const grammar = Object.hasOwn(languages, name) ? languages[name] : undefined
614 return grammar !== null && typeof grammar === 'object' ? grammar : undefined
615}
616
617const shownSegment = (seg: Segment, piece: string, style: Style, room?: number): Segment => ({ ...seg, text: seg.italic ? piece : shownCode(piece, style, room) })
618
619const segmentRows = (style: Style, lines: string[], lang: string, room?: number): Segment[][] | null => {
620 const grammar = grammarFor(lang)
621 if (!grammar) return null
622 const code = lines.join('\n')
623 const cache = highlighted.get(style.theme) ?? new Map<string, Segment[][]>()
624 highlighted.set(style.theme, cache)
625 return remember(cache, `${style.reorder ? style.shape : ''}\0${room ?? ''}\0${lang}\0${code}`, () => {
626 const out: Segment[][] = [[]]
627 for (const seg of flatten(tokenize(code, grammar), style)) {
628 seg.text.split('\n').forEach((piece, i) => {
629 if (i > 0) out.push([])
630 if (piece) out[out.length - 1]!.push(shownSegment(seg, piece, style, room))
631 })
632 }
633 return out
634 })
635}
636
637export const highlightBlock = ({ Text }: ElementTable, style: Style, lines: string[], lang: string, key: string, room?: number): RenderElement[] | null => {
638 const rows = segmentRows(style, lines, lang, room)
639 if (!rows) return null
640 return rows.map((row, r) => (
641 <Text key={`${key}.${r}`} color={style.theme.codeText}>
642 {row.length ? row.map((s, i) => <Text key={`${key}.${r}.${i}`} color={s.color} italic={s.italic}>{s.text}</Text>) : ' '}
643 </Text>
644 ))
645}
646
647const gutterOf = (lines: string[], numbered: boolean) => (numbered ? String(lines.length).length + 2 : 0)
648
649const heldSegments = (style: Style, lines: string[], lang: string): Segment[][] =>
650 (isShellLang(lang) ? lines.map(line => shellLine(style, line)) : segmentRows(style, lines, lang)) ?? lines.map(text => (text ? [{ text, italic: false }] : []))
651
652const heldCode = (el: ElementTable, style: Style, lines: string[], shown: number, lang: string, gutter: number, room: number, key: string): RenderElement[] =>
653 heldSegments(style, lines, lang).slice(0, shown).flatMap((segs, i) =>
654 visualRows(tabbed(wordPieces(segs, null)), room).map((part, k) => (
655 <el.Box key={`${key}.h${i}.${k}`} flexDirection="row">
656 {numberedLine(el, style, ` ${gutter ? (k ? ' '.repeat(gutter + 2) : `${String(i + 1).padStart(gutter)} `) : ''}`, part, `${key}.h${i}.${k}`)}
657 </el.Box>
658 )))
659
660const codeRows = (el: ElementTable, style: Style, lines: string[], shown: number, lang: string, numbered: boolean, room: number, key: string): RenderElement[] => {
661 if (style.nativeCode) return [<el.Code key="code" source={lines.slice(0, shown).join('\n') || ' '} {...(lang ? { language: lang } : {})} {...(numbered ? { startLine: 1 } : {})} />]
662 const rows = (isShellLang(lang) ? null : highlightBlock(el, style, lines, lang, key, room))?.slice(0, shown) ?? lines.slice(0, shown).map((line, i) => codeLine(el, style, line, lang, `${key}.${i}`, room))
663 return style.shape === 'engine' ? rows.map((row, i) => <el.Text key={`${key}.ltr${i}`} {...heldLtr(style)}>{row}</el.Text>) : rows
664}
665
666const codeBody = (el: ElementTable, style: Style, rows: RenderElement[], gutter: number, held: boolean, more: RenderNode | null): RenderElement => {
667 const { Box, Text } = el
668 return (
669 <Box flexDirection="column" paddingLeft={held ? 0 : 2}>
670 {held || !gutter || style.nativeCode ? rows : rows.map((row, i) => row.type === 'Text' ? <Box key={`n${i}`} flexDirection="row"><Text color={style.theme.codeComment} dimColor>{`${String(i + 1).padStart(gutter)} `}</Text>{row}</Box> : row)}
671 {held && more ? <Box paddingLeft={2}>{more}</Box> : more}
672 </Box>
673 )
674}
675
676const isShellLang = (lang: string) => lang === '' || /^(sh|bash|zsh|shell|console|fish|powershell|ps1)$/i.test(lang)
677
678const BOX_DRAWING = /[\u2500-\u257F]/
679
680const SHELL_COMMENT = /^\s*#/
681
682export const codeLine = (el: ElementTable, style: Style, line: string, lang: string, key: string, room?: number): RenderElement => {
683 const { Text } = el
684 const t = style.theme
685 const isShell = isShellLang(lang)
686 if (BOX_DRAWING.test(line)) return <Text key={key} color={t.codeText}>{line}</Text>
687 const comment = style.reorder ? commentTail(line, style.shape) : null
688 if (comment) {
689 return (
690 <Text key={key} color={t.codeText}>
691 {comment.head ? codeLine(el, style, comment.head, lang, `${key}.h`) : null}
692 <Text color={t.codeComment}>{comment.marker + comment.tail}</Text>
693 </Text>
694 )
695 }
696 if (!isShell) return <Text key={key} color={t.codeText}>{shownCode(line, style, room) || ' '}</Text>
697 if (SHELL_COMMENT.test(line)) return <Text key={key} color={t.codeComment}>{line}</Text>
698 return <Text key={key} color={t.codeText}>{shellSegments(style, line, room).map((s, i) => <Text key={`${key}.${i}`} color={s.color}>{s.text}</Text>)}</Text>
699}
700
701const shellLine = (style: Style, line: string): Segment[] => {
702 if (!line) return []
703 if (BOX_DRAWING.test(line)) return [{ text: line, color: style.theme.codeText, italic: false }]
704 if (SHELL_COMMENT.test(line)) return [{ text: line, color: style.theme.codeComment, italic: false }]
705 return shellSegments(style, line)
706}
707
708const shellSegments = (style: Style, line: string, room?: number): Segment[] => {
709 const t = style.theme
710 let seenCommand = false
711 const colorOf = (p: string): string | undefined => {
712 if (/^\s+$/.test(p)) return undefined
713 if (/^["']/.test(p)) return t.codeString
714 if (/^--?[\w-]/.test(p)) return t.codeFlag
715 if (!seenCommand && !/^[$>|&;]+$/.test(p)) {
716 seenCommand = true
717 return t.codeCommand
718 }
719 if (/^(\||&&|;|\|\|)$/.test(p)) seenCommand = false
720 return undefined
721 }
722 return shownCode(line, style, room, true).split(/("[^"]*"|'[^']*'|\s+)/).filter(p => p !== '').map(text => ({ text, color: colorOf(text), italic: false }))
723}
724
725const longestWord = (text: string): number => Math.max(0, ...text.split(/\s+/).map(width))
726
727export const columnWidths = (natural: number[], available: number, gap: number, words: number[] = []): number[] => {
728 const room = Math.max(natural.length, available - gap * (natural.length - 1))
729 const total = natural.reduce((a, b) => a + b, 0)
730 if (total <= room) return natural
731 const minimum = natural.map((w, c) => Math.min(w, Math.max(1, words[c] ?? 1)))
732 const widths = natural.map(() => 0)
733 let open = natural.map((_, c) => c)
734 let left = room
735 for (let fixed = [-1]; fixed.length; ) {
736 const share = Math.floor(left / open.length)
737 const claim = (c: number) => (natural[c]! <= share ? natural[c]! : minimum[c]!)
738 const minimumsFit = open.reduce((a, c) => a + minimum[c]!, 0) <= left
739 const needed = open.reduce((a, c) => a + claim(c), 0)
740 fixed = open.filter(c => natural[c]! <= share)
741 if (minimumsFit && (!fixed.length || needed > left)) fixed = open.filter(c => minimum[c]! > share)
742 fixed.forEach(c => (widths[c] = claim(c), left -= widths[c]!))
743 open = open.filter(c => !fixed.includes(c))
744 }
745 open.forEach((c, i) => (widths[c] = Math.max(1, Math.floor(left / open.length) + (i < left % open.length ? 1 : 0))))
746 while (widths.reduce((a, b) => a + b, 0) > room) {
747 const widest = widths.indexOf(Math.max(...widths))
748 if (widths[widest]! <= 1) break
749 widths[widest]!--
750 }
751 return widths
752}
753
754const tableCells = (block: Extract<Block, { kind: 'table' }>) => [...block.header, ...block.rows.flat()]
755
756const mostlyRtl = (style: Style, lines: Inline[][]): boolean => lines.filter(line => flowOf(style, line, Infinity)?.base === 'R').length * 2 > lines.length
757
758const isRtlTable = (style: Style, block: Extract<Block, { kind: 'table' }>): boolean => mostlyRtl(style, tableCells(block).filter(cell => displayText(cell).trim() !== ''))
759
760const ART_WIDTH = 100
761
762const tableSize = (block: Extract<Block, { kind: 'table' }>) => {
763 const cells = [block.header, ...block.rows].map(r => block.header.map((_, c) => displayText(r[c] ?? [])))
764 const column = (measure: (s: string) => number) => block.header.map((_, c) => Math.max(...cells.map(r => measure(r[c]!))))
765 return { natural: column(widestLine), words: column(longestWord) }
766}
767
768export const tableArt = (block: Extract<Block, { kind: 'table' }>): string => {
769 const cells = [block.header, ...block.rows].map(r => block.header.map((_, c) => displayText(r[c] ?? [])))
770 const { natural, words } = tableSize(block)
771 const widths = columnWidths(natural, ART_WIDTH - 4, 3, words)
772 const pad = (text: string, c: number, align: 'left' | 'right' | 'center') => {
773 const room = Math.max(0, widths[c]! - width(text))
774 const left = align === 'right' ? room : align === 'center' ? Math.floor(room / 2) : 0
775 return ' '.repeat(left) + text + ' '.repeat(room - left)
776 }
777 const line = (l: string, m: string, r: string) => l + widths.map(w => '─'.repeat(w + 2)).join(m) + r
778 const row = (r: string[], header: boolean) => {
779 const lines = r.map((text, c) => wrapRanges(text, widths[c]!).map(([a, b]) => text.slice(a, b)))
780 return Array.from({ length: Math.max(...lines.map(l => l.length)) }, (_, i) =>
781 `│ ${lines.map((l, c) => pad(l[i] ?? '', c, header ? 'center' : block.align[c] ?? 'left')).join(' │ ')} │`)
782 }
783 const art = [line('┌', '┬', '┐'), ...row(cells[0]!, true), ...cells.slice(1).flatMap(r => [line('├', '┼', '┤'), ...row(r, false)]), line('└', '┴', '┘')]
784 return ['```', ...art, '```'].join('\n')
785}
786
787const clip = ({ Box }: ElementTable, w: number, drawn: RenderElement, key?: string) => (
788 <Box key={key} flexDirection="column" minWidth={w}>
789 <Box height={0} flexGrow={1} overflow="hidden">
790 {drawn}
791 </Box>
792 </Box>
793)
794
795const tableEdges = (style: Style, block: Extract<Block, { kind: 'table' }>, rtl: boolean, mirror: boolean) => {
796 const held = !rtl && mirrored(style) && tableCells(block).some(containsRtl)
797 return {
798 opening: mirror ? ROW_MARK_TEXT : held ? LTR_BLANK : '',
799 wall: (text: string) => (mirror ? text.replace('│', WALL) : held ? text.replace(/ $/, LTR_BLANK) : text),
800 held,
801 marked: !mirror && !held,
802 }
803}
804
805const renderTable = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'table' }>, columns: number, key: string, rtl: boolean, tip?: Tip) => {
806 const { Box, Text } = el
807 const t = style.theme
808 const box = style.tableStyle === 'box'
809 const gap = box ? 0 : style.tableStyle === 'grid' ? 3 : 2
810 const { natural, words } = tableSize(block)
811 const widths = box ? columnWidths(natural, columns - 4, 3, words) : columnWidths(natural, columns, gap, words)
812 const order = natural.map((_, c) => c)
813 const mirror = rtl && mirrored(style)
814 const flip = rtl && !mirror
815 const { opening, wall, held, marked } = tableEdges(style, block, rtl, mirror)
816 if (flip) order.reverse()
817 const lead = (k: string) => (opening ? <Text key={`${k}.m`} color={t.rule}>{opening}</Text> : null)
818 const columnGap = held ? 0 : gap
819 const spacer = (k: string) => (held ? <Text key={k}>{LTR_BLANK + ' '.repeat(gap - 1)}</Text> : null)
820 const ruleChar = style.tableStyle === 'grid' ? '━' : '─'
821 const justify = (c: number) =>
822 block.align[c] === 'right' ? 'flex-end' : block.align[c] === 'center' ? 'center' : 'flex-start'
823
824 const rule = (k: string, heavy: boolean) => (
825 <Box key={k} flexDirection="row" columnGap={columnGap}>
826 {lead(k)}
827 {order.map((c, i) => [
828 i > 0 && spacer(`${k}.${c}g`),
829 <Text key={`${k}.${c}`} color={t.tableRule} dimColor={!heavy && !t.tableRule}>
830 {(heavy ? ruleChar : '─').repeat(widths[c]!)}
831 </Text>,
832 ])}
833 </Box>
834 )
835
836 const bar = (k: string, text: string, lines = 1) => (
837 <Text key={k} color={t.tableRule} dimColor={!t.tableRule}>{Array.from({ length: lines }, () => text).join('\n')}</Text>
838 )
839 const clipped = (lines: number) => (k: string, text: string) => clip(el, width(text), bar(`${k}.b`, text, lines), k)
840 const edge = (k: string, [left, fill, mid, right]: string) =>
841 bar(k, (mirror ? WALL : left) + order.map(c => fill!.repeat(widths[c]! + 2)).join(mid) + (mirror ? WALL : right))
842
843 const terminalRow = (cells: Inline[][], k: string, isHeader: boolean) => {
844 const parts: Inline[] = box ? [{ kind: 'dim', text: '│ ' }] : []
845 order.forEach((c, i) => {
846 if (i > 0) parts.push(box ? { kind: 'dim', text: ' │ ' } : { kind: 'text', text: ' '.repeat(gap) })
847 const cell = flowOf({ ...style, shape: 'visual' }, cells[c] ?? [], Infinity)
848 const content = cell ? cell.lines[0]! : (cells[c] ?? [])
849 const pad = Math.max(0, widths[c]! - width(inlineText(content)))
850 const side = cell?.base === 'R' && block.align[c] !== 'center' ? 'flex-end' : justify(c)
851 const before = side === 'flex-end' ? pad : side === 'center' ? Math.floor(pad / 2) : 0
852 parts.push({ kind: 'text', text: ' '.repeat(before) }, ...(isHeader ? [{ kind: 'strong' as const, children: content }] : content), { kind: 'text', text: ' '.repeat(pad - before) })
853 })
854 if (box) parts.push({ kind: 'dim', text: ' │' })
855 return <Text key={k}>{renderInline(el, style, terminalLine(parts), k)}</Text>
856 }
857
858 const row = (cells: Inline[][], k: string, isHeader: boolean, border: (k: string, text: string) => RenderElement = bar) => rtl && style.shape === 'inverse' ? terminalRow(cells, k, isHeader) : (
859 <Box key={k} flexDirection="row" columnGap={columnGap} alignItems="stretch">
860 {!box && lead(k)}
861 {box && border(`${k}.l`, wall('│ '))}
862 {order.map((c, i) => {
863 const w = widths[c]!
864 const cell = cellFlow(style, cells[c] ?? [], held, marked)
865 const content = cell ? cell.lines[0]! : (cells[c] ?? [])
866 const side = mirror ? (block.align[c] === 'center' ? 'center' : 'flex-start') : cell?.base === 'R' && block.align[c] !== 'center' ? 'flex-end' : justify(c)
867 const runs = isHeader ? headerRuns(content) : content
868 const cellBox = (
869 <Box key={`${k}.${c}`} width={w} flexShrink={0} justifyContent={side}>
870 {pressInline(el, style, runs, w, `${k}.${c}.p`, tip, isHeader ? { bold: true, color: t.tableHeader } : {}, { justifyContent: side })
871 ?? (isHeader
872 ? <Text bold color={t.tableHeader}>{runs.some(n => n.kind === 'footnote') ? renderInline(el, style, runs, `${k}.${c}`) : inlineText(runs)}</Text>
873 : mirror && inlineText(content).trim() === '' ? <Text>{' '.repeat(w)}</Text>
874 : <Text>{renderInline(el, style, content, `${k}.${c}`)}</Text>)}
875 </Box>
876 )
877 return [i > 0 && (box ? border(`${k}.${c}s`, wall(' │ ')) : spacer(`${k}.${c}g`)), cellBox]
878 })}
879 {box && border(`${k}.r`, wall(' │'))}
880 </Box>
881 )
882
883 const wrappedRow = (cells: Inline[][], k: string, isHeader: boolean) => {
884 if (!isHeader && cells.some(hasLink)) return [row(cells, k, isHeader, clipped(Math.max(1, ...widths.map((w, c) => mostLines(displayText(cells[c] ?? []), w)))))]
885 const wrapped = widths.map((w, c) => {
886 const content = cells[c] ?? []
887 if (natural[c]! <= w && !inlineText(content).includes('\n')) return [content]
888 return wrapInline(isHeader ? headerRuns(content) : content, w)
889 })
890 return Array.from({ length: Math.max(...wrapped.map(l => l.length)) }, (_, i) =>
891 row(wrapped.map(l => l[i] ?? []), `${k}.${i}`, isHeader))
892 }
893
894 if (box) {
895 const lines: RenderElement[] = [edge(`${key}.t`, '┌─┬┐'), ...wrappedRow(block.header, `${key}.h`, true), edge(`${key}.hr`, '╞═╪╡')]
896 block.rows.forEach((r, i) => {
897 if (i > 0) lines.push(edge(`${key}.r${i}r`, '├─┼┤'))
898 lines.push(...wrappedRow(r, `${key}.r${i}`, false))
899 })
900 lines.push(edge(`${key}.b`, '└─┴┘'))
901 return <Box key={key} flexDirection="column" {...(flip ? { alignSelf: 'flex-end' as const } : {})}>{lines}</Box>
902 }
903
904 const body: RenderElement[] = [row(block.header, `${key}.h`, true), rule(`${key}.hr`, true)]
905 block.rows.forEach((r, i) => {
906 body.push(row(r, `${key}.r${i}`, false))
907 if (style.tableStyle !== 'minimal' && i < block.rows.length - 1) body.push(rule(`${key}.r${i}r`, false))
908 })
909 return <Box key={key} flexDirection="column" {...(flip ? { alignSelf: 'flex-end' as const } : {})}>{body}</Box>
910}
911
912const renderHeading = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'heading' }>, key: string) => {
913 const rtl = flowOf(style, block.inline, Infinity)
914 if (!rtl) return drawHeading(el, style, block, block.inline, key)
915 if (rtl.base === 'R' && mirrored(style) && style.headingStyle === 'banner' && block.level <= 2) return mirroredBanner(el, style, block.level, rtl.lines[0]!, key)
916 const heading = drawHeading(el, style, block, rtl.lines[0]!, key)
917 return rtl.base === 'R' && !mirrored(style) ? <el.Box key={key} alignSelf="flex-end">{heading}</el.Box> : heading
918}
919
920const mirroredBanner = (el: ElementTable, style: Style, level: number, inline: Inline[], key: string) => {
921 const { Box, Text } = el
922 const color = style.theme.heading
923 const text = <Text key={`${key}.h`} bold underline={level === 2} color={color}>{level === 1 ? `${WALL} ` : ''}{renderInline(el, style, inline, key)}{level === 1 ? ` ${WALL}` : ''}</Text>
924 if (level === 2) return text
925 const edge = (k: string) => <Text key={k} color={color}>{WALL + '━'.repeat(width(inlineText(inline)) + 2) + WALL}</Text>
926 return <Box key={key} flexDirection="column">{edge(`${key}.t`)}{text}{edge(`${key}.b`)}</Box>
927}
928
929const HEADING_RULE = 200
930
931const drawHeading = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'heading' }>, inline: Inline[], key: string) => {
932 const { Box, Text } = el
933 const t = style.theme
934 const color = block.level <= 2 ? t.heading : t.accent ?? t.heading
935 const label = inlineText(inline)
936 switch (style.headingStyle) {
937 case 'uppercase':
938 return <Text key={key} bold color={color}>{block.level === 1 ? label.toUpperCase() : label}</Text>
939 case 'underline':
940 return <Text key={key} bold underline={block.level <= 2} color={color}>{label}</Text>
941 case 'banner':
942 if (block.level === 1) return <Box key={key} alignSelf="flex-start" borderStyle="bold" borderColor={color} paddingX={1}><Text bold color={color}>{renderInline(el, style, inline, key)}</Text></Box>
943 return block.level === 2
944 ? <Box key={key} flexDirection="column" alignSelf="flex-start"><Text bold color={color}>{renderInline(el, style, inline, key)}</Text>{style.gridFace ? <Box flexDirection="row"><Box width={0} flexGrow={1} height={1} overflow="hidden"><Text color={color}>{'━'.repeat(HEADING_RULE)}</Text></Box></Box> : <Text color={color}>{'━'.repeat(width(label))}</Text>}</Box>
945 : <Text key={key} bold color={block.level === 3 ? color : t.strong}>{renderInline(el, style, inline, key)}</Text>
946 default:
947 return <Text key={key} bold color={color}>{renderInline(el, style, inline, key)}</Text>
948 }
949}
950
951const ALERT_COLOR = { note: 'blue', tip: 'green', important: 'magenta', warning: 'yellow', caution: 'red' } as const
952
953const prose = (style: Style) => (style.inside === 'quote' ? { italic: true, color: style.theme.quote } : {})
954
955const renderParagraph = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'paragraph' }>, columns: number, key: string, tip?: Tip) => {
956 const { Box, Text } = el
957 const rtl = flowOf(style, block.inline, columns)
958 if (rtl?.base === 'R') return <Box key={key} flexDirection="column" {...(mirrored(style) ? {} : { alignItems: 'flex-end' as const })}>{renderFlow(el, style, rtl.lines, key, prose(style))}</Box>
959 const inline = rtl ? rtl.lines[0]! : block.inline
960 return pressInline(el, style, inline, columns, key, tip, { ...(style.narration ? { bold: true } : {}), ...prose(style) }) ?? <Text key={key} bold={style.narration} {...prose(style)}>{renderInline(el, style, inline, key)}</Text>
961}
962
963const leadInline = (blocks: Block[]): Inline[] => {
964 const first = blocks[0]
965 if (first?.kind === 'paragraph' || first?.kind === 'heading') return first.inline
966 if (first?.kind === 'list') return first.items[0]?.inline ?? []
967 return first?.kind === 'quote' || first?.kind === 'alert' ? leadInline(first.blocks) : []
968}
969
970const renderNested = (el: ElementTable, style: Style, blocks: Block[], columns: number, key: string, copy?: CopyButton, fold?: Fold, tip?: Tip) =>
971 renderBlocks(el, style, blocks, columns, drawMath(el, style, blocks), copy && ((text, id, label, html) => copy(text, `${key}.${id}`, label, html)), fold && ((id, hidden, k) => fold(id, hidden, `${key}.${k}`)), tip)
972
973const quoteBar = (el: ElementTable, text: string, color: string | undefined, lines: number) =>
974 lines <= 1 ? <el.Text color={color}>{text}</el.Text> : clip(el, width(text), <el.Text color={color}>{Array.from({ length: lines }, () => text).join('\n')}</el.Text>)
975
976const renderQuote = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'quote' }>, columns: number, key: string, copy?: CopyButton, fold?: Fold, tip?: Tip) => {
977 const { Box } = el
978 const t = style.theme
979 const inner = columns - 2
980 const lines = heightOf(block.blocks, inner)
981 const body = <Box flexDirection="column" rowGap={1}>{renderNested(el, { ...style, inside: 'quote' }, block.blocks, inner, key, copy, fold, tip)}</Box>
982 if (!mirrored(style) && flowOf(style, leadInline(block.blocks), inner)?.base === 'R') {
983 return (
984 <Box key={key} flexDirection="row" justifyContent="flex-end" alignItems="stretch">
985 {body}
986 {quoteBar(el, ' │', t.accent, lines)}
987 </Box>
988 )
989 }
990 return (
991 <Box key={key} flexDirection="row" alignItems="stretch">
992 {quoteBar(el, mirrored(style) ? ROW_MARK_TEXT : '│ ', t.accent, lines)}
993 {body}
994 </Box>
995 )
996}
997
998const renderAlert = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'alert' }>, columns: number, key: string, copy?: CopyButton, fold?: Fold, tip?: Tip) => {
999 const { Box, Text } = el
1000 const color = ALERT_COLOR[block.level]
1001 const inner = columns - 4
1002 const hebrew = flowOf(style, leadInline(block.blocks), inner)?.base === 'R'
1003 const label = block.level[0]!.toUpperCase() + block.level.slice(1)
1004 const body = block.blocks.length ? <Box flexDirection="column" rowGap={1}>{renderNested(el, { ...style, inside: 'alert' }, block.blocks, inner, key, copy, fold, tip)}</Box> : null
1005 if (hebrew && mirrored(style)) {
1006 const lines = 1 + (block.blocks.length ? 1 + heightOf(block.blocks, inner) : 0)
1007 const edge = (k: string) => <Text key={k} color={color}>{WALL + '─'.repeat(inner + 2) + WALL}</Text>
1008 return (
1009 <Box key={key} flexDirection="column" alignSelf="flex-start">
1010 {edge(`${key}.t`)}
1011 <Box flexDirection="row" alignItems="stretch">
1012 {quoteBar(el, ROW_MARK_TEXT, color, lines)}
1013 <Box flexDirection="column" width={inner}>
1014 <Text bold color={color}>{label}</Text>
1015 {body}
1016 </Box>
1017 {quoteBar(el, ` ${WALL}`, color, lines)}
1018 </Box>
1019 {edge(`${key}.b`)}
1020 </Box>
1021 )
1022 }
1023 return (
1024 <Box key={key} flexDirection="column" alignSelf={hebrew ? 'flex-end' : 'flex-start'} {...(hebrew ? { alignItems: 'flex-end' as const } : {})} borderStyle="round" borderColor={color} paddingX={1}>
1025 <Text bold color={color}>{label}</Text>
1026 {body}
1027 </Box>
1028 )
1029}
1030
1031const listSide = (style: Style, block: Extract<Block, { kind: 'list' }>): 'R' | 'L' | undefined => {
1032 if (!style.reorder || !block.items.some(item => containsRtl(item.inline))) return undefined
1033 return mostlyRtl(style, block.items.map(item => item.inline)) ? 'R' : 'L'
1034}
1035
1036const leftItem = (el: ElementTable, style: Style, depth: number, lead: string, color: string | undefined, inline: Inline[], room: number, k: string, look: TextLook, tip?: Tip) => {
1037 const { Box, Text } = el
1038 return (
1039 <Box key={k} flexDirection="row" paddingLeft={depth * 2}>
1040 <Text color={color}>{lead}</Text>
1041 {pressInline(el, style, inline, room, `${k}.i`, tip, look) ?? <Text {...look}>{renderInline(el, style, inline, k)}</Text>}
1042 </Box>
1043 )
1044}
1045
1046const leadSide = (style: Style, block: Block, room: number) => (block.kind === 'list' ? listSide(style, block) : flowOf(style, leadInline([block]), room)?.base)
1047
1048const heldItem = (el: ElementTable, style: Style, item: Extract<Block, { kind: 'list' }>['items'][number], glyph: string, color: string | undefined, room: number, k: string, look: TextLook) => {
1049 const { Box, Text } = el
1050 const lines = mirrored(style) ? flowOf(style, item.inline, room - 1, false)!.lines.map(line => [{ kind: 'text' as const, text: LTR_BLANK }, ...line]) : flowOf(style, item.inline, room)!.lines
1051 return (
1052 <Box key={k} flexDirection="row" paddingLeft={item.depth * 2}>
1053 <Text color={color}>{mirrored(style) ? glyph : `${glyph} `}</Text>
1054 <Box flexDirection="column">{renderFlow(el, style, lines, k, look)}</Box>
1055 </Box>
1056 )
1057}
1058
1059const listRow = (el: ElementTable, style: Style, item: Extract<Block, { kind: 'list' }>['items'][number], glyph: string, glyphColor: string | undefined, side: 'R' | 'L' | undefined, room: number, k: string, look: TextLook, tip?: Tip) => {
1060 const { Box, Text } = el
1061 const rtl = flowOf(style, item.inline, room)
1062 const right = side ? side === 'R' : rtl?.base === 'R'
1063 const lines = rtl?.lines ?? [mirrored(style) ? [ROW_MARK, ...item.inline] : item.inline]
1064 const drawn = () => (rtl ? null : pressInline(el, style, lines[0]!, room, `${k}.i`, tip, look, mirrored(style) ? {} : { justifyContent: 'flex-end' })) ?? renderFlow(el, style, lines, k, look)
1065 return right && mirrored(style) ? (
1066 <Box key={k} flexDirection="row">
1067 <Text color={glyphColor}>{`${' '.repeat(item.depth * 2)}${glyph} `}</Text>
1068 <Box flexDirection="column">{drawn()}</Box>
1069 </Box>
1070 ) : right ? (
1071 <Box key={k} flexDirection="row" justifyContent="flex-end" paddingRight={item.depth * 2}>
1072 <Box flexDirection="column" alignItems="flex-end">{drawn()}</Box>
1073 <Text color={glyphColor}>{` ${listMarker(glyph, style.shape)}`}</Text>
1074 </Box>
1075 ) : rtl?.base === 'R' ? (
1076 heldItem(el, style, item, glyph, glyphColor, room, k, look)
1077 ) : (
1078 leftItem(el, style, item.depth, `${glyph} `, glyphColor, rtl ? rtl.lines[0]! : item.inline, room, k, look, tip)
1079 )
1080}
1081
1082const TASK_GLYPHS = { checks: ['[ ]', '[✓]'], ticks: ['○', '✓'], box: ['□', '✓'], progress: ['○', '✓'] } as const
1083
1084const renderList = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'list' }>, columns: number, key: string, copy?: CopyButton, fold?: Fold, tip?: Tip) => {
1085 const { Box, Text } = el
1086 const t = style.theme
1087 const tasks = block.items.filter(item => item.task !== undefined)
1088 const done = tasks.filter(item => item.task).length
1089 const filled = tasks.length ? Math.round((done / tasks.length) * 20) : 0
1090 const strike = style.taskStyle === 'checks' || style.taskStyle === 'box'
1091 const tick = style.taskStyle === 'ticks' || style.taskStyle === 'progress'
1092 const side = listSide(style, block)
1093 return (
1094 <Box key={key} flexDirection="column">
1095 {style.taskStyle === 'progress' && tasks.length > 0 && (
1096 <Text>
1097 <Text color={t.accent}>{'━'.repeat(filled)}</Text>
1098 <Text color={t.bullet} dimColor>{'─'.repeat(20 - filled)}</Text>
1099 <Text color={t.bullet}>{` ${done}/${tasks.length} done`}</Text>
1100 </Text>
1101 )}
1102 {block.items.map((item, i) => {
1103 const k = `${key}.${i}`
1104 const glyph = item.task !== undefined ? TASK_GLYPHS[style.taskStyle][item.task ? 1 : 0] : /\d/.test(item.marker) ? item.marker : item.depth ? '◦' : '•'
1105 const glyphColor = item.task && tick ? t.accent : t.bullet
1106 const pad = item.depth * 2 + glyph.length + 1
1107 const look = { ...(item.task === true ? { dimColor: true, strikethrough: strike } : {}), ...prose(style) }
1108 const row = listRow(el, style, item, glyph, glyphColor, side, columns - pad, k, look, tip)
1109 if (!item.blocks) return row
1110 return (
1111 <Box key={k} flexDirection="column">
1112 {row}
1113 <Box flexDirection="column" paddingLeft={pad}>{renderNested(el, style, item.blocks, columns - pad, k, copy, fold, tip)}</Box>
1114 </Box>
1115 )
1116 })}
1117 </Box>
1118 )
1119}
1120
1121export type CopyButton = (text: string | (() => string), key: string, label?: string, html?: () => string) => RenderElement | null
1122export type Drawn = Map<number, { element?: RenderElement; art?: string; note?: string }>
1123export type FoldLook = { label?: string; face?: (folded: boolean) => RenderElement }
1124export type Fold = (id: string, hidden: number, key: string, look?: FoldLook) => { folded: boolean; element: RenderElement; faced: boolean; around?: (rows: RenderElement, hover: TextHoverProps) => RenderElement } | null
1125export type Tip = (note: number) => (() => void) | undefined
1126
1127export const instanceKey = (id: string): string => {
1128 let h = 5381
1129 for (let i = 0; i < id.length; i++) h = (h * 33 + id.charCodeAt(i)) | 0
1130 return (h >>> 0).toString(36)
1131}
1132
1133export const noteTip = (blocks: Block[], toast: (text: string) => void): Tip | undefined => {
1134 const notes = blocks.find(block => block.kind === 'notes')
1135 if (notes?.kind !== 'notes') return undefined
1136 const text = new Map(notes.notes.map(note => [note.note, `${note.mark} ${inlineText(note.inline)}`]))
1137 return note => {
1138 const line = text.get(note)
1139 return line === undefined ? undefined : () => toast(line)
1140 }
1141}
1142
1143const NUMBER_AT = 10
1144const NUMBER_MAX = 400
1145const FOLD_AT = 30
1146const FOLD_SHOW = 20
1147
1148const codeId = (lines: string[]): string => {
1149 let h = 5381
1150 for (const line of lines) {
1151 for (let i = 0; i < line.length; i++) h = (h * 33 + line.charCodeAt(i)) | 0
1152 h = (h * 33 + 10) | 0
1153 }
1154 return `${lines.length}:${(h >>> 0).toString(36)}`
1155}
1156
1157const copySource = (style: Style, block: Block): string | undefined =>
1158 block.kind === 'code' ? block.lines.join('\n')
1159 : block.kind === 'table' ? block.raw
1160 : style.inside ? undefined
1161 : block.kind === 'list' ? block.raw
1162 : block.kind === 'quote' || block.kind === 'alert' ? block.raw.split('\n').map(line => line.replace(/^\s*>\s?/, '')).join('\n')
1163 : undefined
1164
1165export const drawMath = (el: ElementTable, style: Style, blocks: Block[], drawn: Drawn = new Map()): Drawn => {
1166 for (const [i, block] of blocks.entries()) {
1167 const tex = drawn.has(i) ? null : mathOf(block)
1168 const text = tex === null ? null : texText(tex)
1169 if (text && !text.includes('\\')) drawn.set(i, { element: <el.Box key={`b${i}`} paddingLeft={2}><el.Text italic color={style.theme.emphasis}>{text}</el.Text></el.Box> })
1170 }
1171 return drawn
1172}
1173
1174const opensWithCopy = (block: Block): boolean =>
1175 block.kind === 'quote' && (block.blocks[0]?.kind === 'code' || block.blocks[0]?.kind === 'table' || (block.blocks[0] !== undefined && opensWithCopy(block.blocks[0])))
1176
1177const holdsOnlyEmptyCode = (block: Block): boolean =>
1178 block.kind === 'quote' && block.blocks.length === 1 && ((block.blocks[0]!.kind === 'code' && block.blocks[0]!.lines.length === 0) || holdsOnlyEmptyCode(block.blocks[0]!))
1179
1180export const MARK = 2
1181
1182export const markerRoom = (style: Style): number => (style.copyButtons && style.copyButtonStyle === 'hover' ? MARK : 0)
1183
1184const codeLabel = (block: Extract<Block, { kind: 'code' }>): string => `── ${block.lang || 'code'}`
1185
1186type Float = { needs: number; marker: RenderElement; element: RenderElement }
1187
1188const buttonText = (button: RenderElement | null | undefined): string | undefined =>
1189 button?.type === 'Button' ? `[ ${button.props.label} ]` : button?.type === 'Text' ? (button.children ?? []).filter((c): c is string => typeof c === 'string').join('') : undefined
1190
1191const keyOf = (button: RenderElement): string => String(('props' in button ? (button.props as { key?: unknown } | undefined)?.key : undefined) ?? '')
1192
1193const markedRow = ({ Box }: ElementTable, key: string, element: RenderElement, float: Float, start: boolean) => (
1194 <Box key={key} flexDirection="column" {...(start ? { alignItems: 'flex-end' as const } : { alignSelf: 'flex-start' as const })}>
1195 <Box flexDirection="row" columnGap={1} minWidth={float.needs} {...(start ? { justifyContent: 'flex-end' as const } : {})}>
1196 {start ? float.marker : null}
1197 {element}
1198 {start ? null : float.marker}
1199 {float.element}
1200 </Box>hooks/help.ts 444 lines1import { RANDOM_THEMES } from './theme'
2
3export const HINT = [
4 'Replies in this session are drawn by the prismantis mod, which runs inside Claude Code and is not a command or tool to call: when the user asks to show something with prismantis, write it as markdown in the reply.',
5 'Markdown tables, GitHub alerts (> [!WARNING], > [!NOTE]), fenced code with a language tag, and ```mermaid blocks render as colored terminal graphics:',
6 'flowcharts, sequence diagrams, xychart-beta bar or line charts (name each series for the legend: line "east" [..]), pie charts and gantt schedules.',
7 'When a reply carries a numeric series or a flow that is easier to see than read, add a small diagram or chart with short labels, not a second picture of what a figure already shows.',
8 'Skip diagrams and pictures for short or simple answers.',
9 'Put any command or snippet the user may run or copy in a fenced block with a language tag, never inline code: fenced blocks get a copy button, inline code does not.',
10].join(' ')
11
12export const showcaseText = (themes: readonly string[]): string => `
13# prismantis
14
15Colored markdown for Claude Code replies: **bold**, *italic*, ~~struck~~, \`inline code\`, a [link](https://github.com/NahumLitvin/prismantis) and a bare URL https://github.com/NahumLitvin/prismantis/issues, both clickable, numbers like 99.9% and 250ms, paths like ~/src/app.ts.
16
17Paths like ~/src/app.ts, ./README.md and /tmp/app.ts open on click in a terminal that draws hyperlinks, and so does a local link that shows its own path, like [/tmp/notes.md](file:///tmp/notes.md), while slash commands like /config stay text. A local link with any other name, like [notes](file:///tmp/notes.md), draws as its name and target, so it cannot hide where a click goes.
18
19Paths written without ./, like docs/guide/ or src/app.ts:42, and Windows paths like C:\\work\\plan.md link too, once a check finds them on disk; prose like and/or stays text.
20
21Programs and launchers stay plain text, so a click never runs one: ./install.sh, ~/Desktop/setup.command and /Applications/Calculator.app keep the path color without a link.
22
23Code-shaped prose stays as written: f(*args, **kwargs), a link with parentheses [Foo_(bar)](https://en.wikipedia.org/wiki/Foo_(bar)), a file link [\`render.tsx\`](https://github.com/NahumLitvin/prismantis/blob/main/hooks/render.tsx) and **bold with *italic* inside**.
24
25## Commands
26
27| Command | Does |
28|---------|------|
29| \`/prismantis\` | This screen |
30| \`/prismantis theme <name>\` | Switch theme on the spot (\`/prismantis <name>\` works too), \`random\` for a new dark one now and each time the mod loads |
31| \`/prismantis copy\` | Copy the last reply, or \`copy code\` for its last code block |
32| \`/prismantis setup\` | Pick a theme and how tables, tasks, headings, copy buttons, prompts, times, tool rows, tool output, diffs and pie charts look, from drawn samples |
33| \`/config\` | Edit any option |
34
35> [!NOTE]
36> ${themes.length} themes ship with it. \`mono\` uses no color, only bold and dim.
37
38### Pick a theme
39
40\`\`\`bash
41/prismantis theme nord
42/prismantis theme github-light
43/prismantis theme random
44\`\`\`
45
461. Dark: ${themes.filter(t => RANDOM_THEMES.includes(t)).join(', ')}
472. Light: ${themes.filter(t => /latte|light|dawn/.test(t)).join(', ')}
483. Plain
49 - mono
50
51> [!TIP]
52> Any color slot beats the theme. Set \`headingColor\` or \`numberColor\` to a hex value in \`/config\`.
53
54## Everything it draws
55
56### Copy tables
57
58Use \`⧉ md\` for Markdown, \`⧉ art\` for chat, or \`⧉ html\` for a formatted table. \`⧉ html\` shows in a local macOS, Linux or Windows terminal and writes HTML and tab-separated plain text together; Linux needs CopyQ running. Pasted into Slack it makes a native table; Slack keeps cell text but drops bold, links and alignment. If that fails, it copies the plain text alone. Set \`copyButtonStyle\` to \`hover\` in \`/config\` and each block shows a dim ⧉ instead: point at it for its buttons.
59
60| Item | Quantity[^count] | Status |
61|:-----|---------:|:------:|
62| **Apples** | 3 | *Ready* |
63| Oranges | 5 | Pending |
64
65### Alerts
66
67> [!IMPORTANT]
68> After updating the plugin, open sessions need \`/reload\`.
69
70> [!WARNING]
71> Terminals that copy on select (Warp) can turn a click on a copy button into a selection. Use the keyboard shortcut.
72> Selecting a typeset formula copies blank cells. Its copy button copies the LaTeX.
73
74> [!CAUTION]
75> Claude Code refuses trees over 20000 nodes. A code block past about 500 highlighted lines falls back to plain text.
76
77### Task lists
78
79- [x] Parse the reply
80- [x] Draw it
81 - [x] Tables and code
82 - [ ] Diagrams on the desktop app
83- [ ] Ship the next release
84
85### Your prompts
86
87Scroll up: what you typed draws in a bubble. \`promptStyle\` switches to \`wide\`, \`bar\`, \`chevron\` or \`off\` in \`/config\`. Set \`clock\` to \`24h\` or \`12h\` and each prompt shows when you sent it, and each turn's last line when it finished. A paste of 4 lines or more draws in a double frame of its own, folded to one button that opens it as highlighted code.
88
89### Tool rows
90
91Tool calls draw as one line, dimmed on the right by default, and the file each one read or edited opens on click in a terminal that draws hyperlinks. Set \`toolStyle\` in \`/config\` to \`chat\`, \`tree-dim\`, \`tree-bold\` or \`classic\`. \`toolOutput: quiet\` in \`/config\` hides what Claude only read and says in plain words what each call did: \`Read src/app.ts lines 1–40\`, \`Searched src/ for "TODO"\`.
92
93Each edit draws as a diff card headed \`+N −M\`: code highlighted in the file's language, added and removed lines on a tint of the theme's own green and red with the changed words in a deeper tint, kept readable in every theme, long lines wrapped, the first 20 lines and a \`+K more lines\` button that opens the rest, as does a click anywhere on the card. Files a shell command changes (\`sed -i\`, a script) get the same card, one per file, headed by its path. Set \`diffStyle\` in \`/config\` for the look: \`card\`, \`full\`, \`marks\` or \`bar\`.
94
95A file Write creates shows its first 10 lines as numbered code in the theme's colors with no diff marks, and a click on it or on \`+K more lines\` opens the rest. A file an Edit or a shell command creates shows its first 10 lines as added lines under \`Created\`. A file a shell command removes is one \`Deleted\` line that opens to its removed lines on a click, and a file moved unchanged is one \`Renamed old → new\` line.
96
97### Quotes and rules
98
99> A quote keeps its text when you copy it, without the \`> \` markers.
100>
101> It keeps its paragraphs and lists too:
102> - **bold** and \`inline code\` stay styled
103> - each item gets its own row
104>
105> > A nested quote draws inside the bar.
106
107<summary>
108A line that holds only a tag draws dim, so wrapper tags show the reply's structure.
109</summary>
110
111---
112
113### Code
114
115\`\`\`json
116{ "theme": "dracula", "headingStyle": "banner", "mermaid": true }
117\`\`\`
118
119Blocks of 10 lines or more get line numbers. Past 30 lines they fold to the first 20 and a \`+M more lines\` button, \`show less\` folds them back; \`⧉ copy\` still copies the whole block.
120
121\`\`\`ts
122type Item = { name: string; price: number; qty: number }
123
124const basket: Item[] = [
125 { name: 'apples', price: 1.2, qty: 3 },
126 { name: 'oranges', price: 0.8, qty: 5 },
127 { name: 'pears', price: 1.5, qty: 2 },
128 { name: 'plums', price: 2.1, qty: 4 },
129 { name: 'grapes', price: 3.4, qty: 1 },
130 { name: 'lemons', price: 0.6, qty: 6 },
131 { name: 'melons', price: 4.0, qty: 1 },
132 { name: 'cherries', price: 5.5, qty: 2 },
133 { name: 'figs', price: 2.8, qty: 3 },
134 { name: 'limes', price: 0.5, qty: 8 },
135 { name: 'peaches', price: 1.9, qty: 4 },
136 { name: 'kiwis', price: 0.9, qty: 6 },
137]
138
139const total = (items: Item[]): number =>
140 items.reduce((sum, item) => sum + item.price * item.qty, 0)
141
142const cheapest = (items: Item[]): Item | undefined =>
143 [...items].sort((a, b) => a.price - b.price)[0]
144
145const byName = (items: Item[]): Item[] =>
146 [...items].sort((a, b) => a.name.localeCompare(b.name))
147
148const receipt = (items: Item[]): string[] =>
149 byName(items).map(item => \`\${item.name.padEnd(10)} \${item.qty} x \${item.price.toFixed(2)}\`)
150
151console.log(receipt(basket).join('\\n'))
152console.log('total', total(basket).toFixed(2))
153console.log('cheapest', cheapest(basket)?.name)
154\`\`\`
155
156#### Math
157
158$$
159\\int_0^\\infty e^{-x^2}\\,dx = \\frac{\\sqrt{\\pi}}{2}
160$$
161
162#### Images
163
164In kitty and Ghostty a PNG on a line of its own draws as a picture: a local path, \`~/\`, \`file://\` or a \`data:\` URL. Web images stay links, prismantis downloads nothing. Other terminals show the alt text in link color.
165
166
167
168#### Footnotes
169
170Latency fell to 120ms[^lat] after the cache change[^cache].
171
172Click a mark to see its note. Point at a note to light the marks that cite it. Both need Claude Code 2.1.295 or later.
173
174[^count]: Counted at close.
175[^lat]: Median of 50 runs.
176[^cache]: Entries expire after 10m.
177
178#### Diagrams
179
180\`\`\`mermaid
181flowchart LR
182 R["<i>Reply</i>"] --> P["<b>Parse</b>"]
183 P --> D["<u>Draw</u>"]
184 D --> S["<s>Screen</s>"]
185\`\`\`
186
187\`\`\`mermaid
188sequenceDiagram
189 participant U as You
190 participant C as Claude
191 participant P as prismantis
192 U->>C: prompt
193 C->>P: markdown
194 P-->>U: colored reply
195\`\`\`
196
197\`\`\`mermaid
198xychart-beta
199 title "Color options per group"
200 x-axis [text, head, num, code, diag]
201 y-axis "options" 0 --> 8
202 bar [7, 3, 2, 6, 2]
203\`\`\`
204
205Name each series and the legend says which line is which:
206
207\`\`\`mermaid
208xychart-beta
209 title "Replies per hour"
210 x-axis [09, 10, 11, 12, 13]
211 y-axis 0 --> 40
212 line "east" [30, 34, 22, 26, 31]
213 line "west" [12, 18, 25, 20, 14]
214\`\`\`
215
216A pie draws round with a legend. Set \`pieStyle\` to \`bars\` in \`/config\` for one bar per slice:
217
218\`\`\`mermaid
219pie showData title Time per reply stage
220 "Parse" : 3
221 "Draw" : 9
222 "Paint" : 5
223\`\`\`
224
225\`\`\`mermaid
226gantt
227 title Release week
228 dateFormat YYYY-MM-DD
229 section Build
230 Parser :p, 2026-10-05, 2d
231 Renderer :r, after p, 3d
232 section Ship
233 Review :after r, 2d
234 Release :milestone, 2026-10-12, 0d
235\`\`\`
236
237A diagram wider than the terminal stays source, with a dim line saying why:
238
239\`\`\`mermaid
240flowchart TD
241 Q[Queue] --> W1[Worker 1] & W2[Worker 2] & W3[Worker 3] & W4[Worker 4] & W5[Worker 5] & W6[Worker 6] & W7[Worker 7] & W8[Worker 8] & W9[Worker 9] & W10[Worker 10] & W11[Worker 11] & W12[Worker 12] & W13[Worker 13] & W14[Worker 14] & W15[Worker 15] & W16[Worker 16]
242\`\`\`
243
244A figure draws as written, its markup colored by role:
245
246\`\`\`figure
247{dim:timeout at 10 s, handler books at 12 s, retry books again}
248 {note:0 s} {note:10 s} {note:12 s} {note:later}
249 {accent:▏─────────────▏─────▏─────────────────▏}
250Provider {accent:██████████████}{warn:✗} timeout {accent:█} retry
251Handler {ok:████████████████████} 200, nobody waits
252Bookings 0 {ok:1} {warn:2 twice}
253\`\`\`
254
255A box whose rows slip off its frame is lined up with its corner:
256
257\`\`\`figure
258{accent:┌─ queue ──────────┐}
259{accent:│} {ok:● worker 1} {accent:│}
260{accent:│} {warn:▲ worker 2 slow} {accent:│}
261{accent:└──────────────────┘}
262\`\`\`
263`
264
265export const helpText = (themes: readonly string[]): string => `
266## Commands
267
268| Command | Does |
269|---------|------|
270| \`/prismantis theme <name>\` | Switch theme on the spot (\`/prismantis <name>\` works too), \`random\` for a new dark one now and each time the mod loads |
271| \`/prismantis copy\` | Copy the last reply, or \`copy code\` for its last code block |
272| \`/prismantis setup\` | Pick a theme and how tables, tasks, headings, copy buttons, prompts, times, tool rows, tool output, diffs and pie charts look, from drawn samples |
273| \`/prismantis demo\` | Full showcase, every element and diagram, plus a section in your language (Korean so far, or \`demo ko\`) |
274| \`/prismantis demo-rtl\` | Hebrew right-to-left showcase |
275
276### ${themes.length} themes
277
278- Dark: ${themes.filter(t => RANDOM_THEMES.includes(t)).join(', ')}
279- Light: ${themes.filter(t => /latte|light|dawn/.test(t)).join(', ')}
280- Plain: mono, no color, only bold and dim
281
282Docs and issues: https://github.com/NahumLitvin/prismantis
283
284> [!TIP]
285> Any color slot beats the theme. Set \`headingColor\` or \`numberColor\` to a hex value in \`/config\`.
286
287### Task lists
288
289- [x] Tables, diagrams and charts drawn in the terminal
290- [x] Copy tables as Markdown, art or HTML (macOS/Linux)
291- [ ] Pick a \`taskStyle\` in \`/config\`: checks, ticks, box or progress
292
293\`\`\`mermaid
294flowchart LR
295 R[Reply] --> P[Parse]
296 P --> D[Draw]
297 D --> S[Screen]
298\`\`\`
299
300\`\`\`mermaid
301xychart-beta
302 title "Color options per group"
303 x-axis [text, head, num, code, diag]
304 y-axis "options" 0 --> 8
305 bar [7, 3, 2, 6, 2]
306\`\`\`
307
308> [!CAUTION]
309> Claude Code refuses trees over 20000 nodes. A code block past about 500 highlighted lines falls back to plain text.
310`
311
312export const rtlShowcaseText = (): string => `
313# עברית מימין לשמאל
314
315**שלום חברים**, זו הדגמה של עברית עם מונחים באנגלית כמו \`kubectl\`, מספרים כמו 99.9% ו-250ms, נתיב כמו ~/src/app.ts וגם [קישור](https://github.com/NahumLitvin/prismantis).
316
317## רשימות
318
319- פרוסים בשני אזורים (us-east ו-eu-west)
320- Python מתאים גם לסקריפטים קצרים
321- מחליפים ערכת נושא עם \`/prismantis theme nord\`
322
3231. מתקינים את התוסף
3242. שואלים שאלה בעברית
325
326> עברית נקראת מימין לשמאל, גם בטרמינל בלי תמיכה בכיווניות
327
328> [!TIP]
329> כל ערכת נושא עובדת גם בעברית
330
331| שירות | אזור | גרסה |
332| :--- | :--- | ---: |
333| שער | us-east | 2.14.0 |
334| חיוב | eu-west | 1.8.3 |
335
336\`\`\`bash
337ls -la # רשימת הקבצים בתיקייה
338\`\`\`
339
340\`\`\`text
341טיוטה להודעה: הגרסה עלתה ב-14:20
342\`\`\`
343
344\`\`\`mermaid
345flowchart LR
346 A[בקשה חדשה] --> B{האם יש cache?}
347 B -->|כן| C[מחזירים מה-cache]
348 B -->|לא| D[פונים לשרת]
349\`\`\`
350`
351
352export const ISSUE_HINT = 'If the user says prismantis drew something wrong, offer (ask first) a minimal repro issue at https://github.com/NahumLitvin/prismantis/issues.'
353const KOREAN_SHOWCASE = `
354## 한국어
355
356**안녕하세요**, prismantis는 한국어 답변도 그대로 보여 줍니다. \`kubectl\` 같은 영문 명령어, 숫자 99.9%와 250ms, 경로 ~/src/app.ts도 함께 표시됩니다.
357
358- 서울 리전과 도쿄 리전에 배포
359- \`/prismantis theme nord\`로 테마 변경
360
361| 서비스 | 리전 | 버전 |
362| :--- | :--- | ---: |
363| 게이트웨이 | ap-northeast-2 | 2.14.0 |
364| 결제 | ap-northeast-1 | 1.8.3 |
365
366\`\`\`figure
367{accent:┌─ 빌드 ─────────────┐}
368{accent:│} 이미지 생성 완료 {accent:│}
369{accent:│} {ok:✓ 테스트 통과} {accent:│}
370{accent:│} {warn:▲ 배포 대기} {accent:│}
371{accent:└────────────────────┘}
372\`\`\`
373
374\`\`\`mermaid
375flowchart LR
376 A[새 요청] --> B{캐시 있음?}
377 B -->|예| C[캐시에서 반환]
378 B -->|아니오| D[서버 호출]
379\`\`\`
380`
381
382export const languageShowcase = (lang: string): string => (/^ko/i.test(lang) ? KOREAN_SHOWCASE : '')
383
384export type SetupStep = { name: string; key: 'theme' | 'tableStyle' | 'taskStyle' | 'headingStyle' | 'copyButtonStyle' | 'promptStyle' | 'clock' | 'toolStyle' | 'toolOutput' | 'diffStyle' | 'pieStyle'; title: string; note: string; options: readonly string[]; sample: string }
385
386export const setupSteps = (themes: readonly string[]): SetupStep[] => [
387 { name: 'theme', key: 'theme', title: 'Theme', note: 'Each theme draws the same line. `random` picks a new dark one each time the mod loads.', options: themes, sample: '**Bold**, `inline code`, 250ms and ~/src/app.ts.' },
388 { name: 'tables', key: 'tableStyle', title: 'Tables', note: 'How markdown tables draw.', options: ['box', 'rules', 'grid', 'minimal'], sample: '| Item | Qty |\n|:-----|----:|\n| Apples | 3 |\n| Pears | 5 |' },
389 { name: 'tasks', key: 'taskStyle', title: 'Tasks', note: 'How `- [ ]` and `- [x]` items draw.', options: ['checks', 'ticks', 'box', 'progress'], sample: '- [x] Parse the reply\n- [x] Draw it\n- [ ] Ship it' },
390 { name: 'headings', key: 'headingStyle', title: 'Headings', note: 'How `#` and `##` headings draw. Terminals have one font size, so headings stand out through style and color.', options: ['banner', 'bold', 'underline', 'uppercase'], sample: '# Release notes\n\n## Fixes\n\nTables keep their width.' },
391 { name: 'copy', key: 'copyButtonStyle', title: 'Copy buttons', note: 'Where the copy buttons on tables, code, diagrams and replies sit. `inline` shows them beside or above each block. `hover` puts a dim ⧉ beside each block instead and shows its buttons only while the pointer is on that ⧉, so they take no line; ctrl+x tab does not reach a hidden one, and the mobile app draws them inline. Needs `copyButtons` on.', options: ['inline', 'hover'], sample: '' },
392 { name: 'prompts', key: 'promptStyle', title: 'Your prompts', note: 'How what you type draws in the transcript. `off` keeps Claude Code\'s own look.', options: ['bubble', 'wide', 'bar', 'chevron', 'off'], sample: '' },
393 { name: 'clock', key: 'clock', title: 'Times', note: 'Whether your prompts show when you sent them and the line that closes each turn when it finished. A time from another day gets its date.', options: ['off', '24h', '12h'], sample: '' },
394 { name: 'tools', key: 'toolStyle', title: 'Tool rows', note: 'How tool rows sit next to Claude\'s sentences. Sharing sessions as screenshots? `chat` and `tree-dim` draw tool rows in dim gray, the first thing to blur when an image gets resized, so pick `tree-bold` or `classic`.', options: ['chat', 'tree-dim', 'tree-bold', 'classic'], sample: '' },
395 { name: 'output', key: 'toolOutput', title: 'Tool output', note: 'How much of a tool call shows. `full` keeps Claude Code\'s own results under each row. `quiet` names a shell call by what it does and shows a failure\'s last real line instead of its whole output; it also shows reads, searches and listings as their row only and drops approval lines. Edits keep their diff either way. Needs `toolRows` on.', options: ['full', 'quiet'], sample: '' },
396 { name: 'diffs', key: 'diffStyle', title: 'Diffs', note: 'How an edit or a new file draws under its row. `card` frames the lines in a rounded box, `full` drops the box and tints each changed line across the width, `marks` drops the tint and colors only the `+` and `−` marks, `bar` puts a colored `▌` before each changed line. Every look highlights the code and the words that changed. Needs `toolRows` on.', options: ['card', 'full', 'marks', 'bar'], sample: '' },
397 { name: 'pies', key: 'pieStyle', title: 'Pie charts', note: 'How mermaid `pie` charts draw. `round` falls back to bars in ascii mode, with more slices than the theme has distinct colors (mono always) or in a narrow terminal.', options: ['round', 'bars'], sample: '```mermaid\npie title Time per reply stage\n "Draw" : 9\n "Paint" : 5\n "Parse" : 3\n```' },
398]
399
400export type SetupParts = { head: string; options: { value: string; text: string }[]; tail: string }
401
402export const setupParts = (themes: readonly string[], at: number): SetupParts => {
403 const steps = setupSteps(themes)
404 const step = steps[at]!
405 const next = steps[at + 1]
406 return {
407 head: `## Setup ${at + 1}/${steps.length}: ${step.title}\n\n${step.note}`,
408 options: step.options.map((value, i) => ({ value, text: `### ${i + 1}. ${value}${step.key === 'theme' && value !== 'mono' && !RANDOM_THEMES.includes(value) ? ' (for a light terminal)' : ''}${step.sample ? `\n\n${step.sample}` : ''}` })),
409 tail: `Pick with \`/prismantis setup ${step.name} <number or name>\`${step.key === 'theme' ? ' or `random`' : ''}.${next ? ` Skip with \`/prismantis setup ${next.name}\`.` : ''} Stop any time, \`/prismantis setup\` starts over.`,
410 }
411}
412
413export const setupText = (parts: SetupParts): string => [parts.head, ...parts.options.map(o => o.text), parts.tail].join('\n\n')
414
415export const THEME_PREVIEW = [
416 '#### Release notes',
417 '',
418 '**Bold**, `inline code`, 250ms and ~/src/app.ts.',
419 '',
420 '| Service | Status | p95 |',
421 '|:--|:--|--:|',
422 '| api | healthy | 120ms |',
423 '| billing | degraded | 840ms |',
424 '',
425 '```ts',
426 'const total = items.reduce((sum, item) => sum + item.qty, 0)',
427 '```',
428].join('\n')
429
430export const SETUP_PANE_OPENED = 'Setup opened in a pane: ↑↓ or Tab moves through the styles with a preview, Enter saves it and shows the next step, Esc closes the pane. `/prismantis setup theme` walks the steps here instead.'
431
432export const SETUP_PANE_KEYS = '↑↓ or Tab moves, Enter saves and shows the next step, Esc closes.'
433
434export const SETUP_DONE = 'Setup done. Run `/prismantis setup` again any time, and `/config` has every other option.'
435
436export const findSetup = (themes: readonly string[], text: string): { at: number; before: string; parts: SetupParts } | undefined => {
437 for (let at = 0; at < setupSteps(themes).length; at++) {
438 const parts = setupParts(themes, at)
439 const whole = setupText(parts)
440 if (text.endsWith(whole)) return { at, before: text.slice(0, -whole.length).trim(), parts }
441 }
442 return undefined
443}
444hooks/presets.ts 140 lines1import type { Theme } from './theme'
2
3export const PRESETS = {
4 'catppuccin-mocha': {
5 accent: '#cba6f7', heading: '#f9e2af', tableHeader: '#f9e2af', strong: '#ffffff', emphasis: '#f5c2e7',
6 inlineCode: '#89dceb', codeText: '#cdd6f4', codeCommand: '#89b4fa', codeFlag: '#f38ba8', codeString: '#a6e3a1',
7 codeComment: '#6c7086', link: '#89b4fa', path: '#89dceb', number: '#a6e3a1', quote: '#9399b2',
8 rule: '#45475a', tableRule: '#585b70', bullet: '#cba6f7', diagram: '#89b4fa', diagramText: '#cdd6f4',
9 diffAdded: '#a6e3a1', diffRemoved: '#f38ba8',
10 },
11 'catppuccin-latte': {
12 accent: '#8839ef', heading: '#df8e1d', tableHeader: '#df8e1d', strong: '#11111b', emphasis: '#ea76cb',
13 inlineCode: '#04a5e5', codeText: '#4c4f69', codeCommand: '#1e66f5', codeFlag: '#d20f39', codeString: '#40a02b',
14 codeComment: '#9ca0b0', link: '#1e66f5', path: '#209fb5', number: '#40a02b', quote: '#6c6f85',
15 rule: '#bcc0cc', tableRule: '#acb0be', bullet: '#8839ef', diagram: '#1e66f5', diagramText: '#4c4f69',
16 diffAdded: '#3f9e2b', diffRemoved: '#d20f39',
17 },
18 dracula: {
19 accent: '#bd93f9', heading: '#bd93f9', tableHeader: '#f1fa8c', strong: '#f8f8f2', emphasis: '#ff79c6',
20 inlineCode: '#8be9fd', codeText: '#f8f8f2', codeCommand: '#50fa7b', codeFlag: '#ff79c6', codeString: '#f1fa8c',
21 codeComment: '#6272a4', link: '#8be9fd', path: '#ffb86c', number: '#bd93f9', quote: '#6272a4',
22 rule: '#44475a', tableRule: '#6272a4', bullet: '#ff79c6', diagram: '#bd93f9', diagramText: '#f8f8f2',
23 diffAdded: '#50fa7b', diffRemoved: '#ff5555',
24 },
25 nord: {
26 accent: '#88c0d0', heading: '#88c0d0', tableHeader: '#ebcb8b', strong: '#eceff4', emphasis: '#b48ead',
27 inlineCode: '#8fbcbb', codeText: '#d8dee9', codeCommand: '#88c0d0', codeFlag: '#81a1c1', codeString: '#a3be8c',
28 codeComment: '#4c566a', link: '#88c0d0', path: '#8fbcbb', number: '#b48ead', quote: '#81a1c1',
29 rule: '#3b4252', tableRule: '#4c566a', bullet: '#88c0d0', diagram: '#81a1c1', diagramText: '#d8dee9',
30 diffAdded: '#a3be8c', diffRemoved: '#bf616a',
31 },
32 'tokyo-night': {
33 accent: '#bb9af7', heading: '#7dcfff', tableHeader: '#e0af68', strong: '#c0caf5', emphasis: '#f7768e',
34 inlineCode: '#7dcfff', codeText: '#a9b1d6', codeCommand: '#7aa2f7', codeFlag: '#bb9af7', codeString: '#9ece6a',
35 codeComment: '#565f89', link: '#73daca', path: '#2ac3de', number: '#ff9e64', quote: '#9aa5ce',
36 rule: '#414868', tableRule: '#565f89', bullet: '#bb9af7', diagram: '#7aa2f7', diagramText: '#c0caf5',
37 diffAdded: '#9ece6a', diffRemoved: '#f7768e',
38 },
39 'gruvbox-dark': {
40 accent: '#d3869b', heading: '#fabd2f', tableHeader: '#fabd2f', strong: '#fbf1c7', emphasis: '#d3869b',
41 inlineCode: '#8ec07c', codeText: '#ebdbb2', codeCommand: '#83a598', codeFlag: '#fe8019', codeString: '#b8bb26',
42 codeComment: '#928374', link: '#83a598', path: '#8ec07c', number: '#d3869b', quote: '#a89984',
43 rule: '#3c3836', tableRule: '#504945', bullet: '#fe8019', diagram: '#83a598', diagramText: '#ebdbb2',
44 diffAdded: '#b8bb26', diffRemoved: '#fb4934',
45 },
46 'gruvbox-light': {
47 accent: '#8f3f71', heading: '#b57614', tableHeader: '#b57614', strong: '#282828', emphasis: '#8f3f71',
48 inlineCode: '#427b58', codeText: '#3c3836', codeCommand: '#076678', codeFlag: '#af3a03', codeString: '#79740e',
49 codeComment: '#928374', link: '#076678', path: '#427b58', number: '#8f3f71', quote: '#7c6f64',
50 rule: '#ebdbb2', tableRule: '#a89984', bullet: '#af3a03', diagram: '#076678', diagramText: '#3c3836',
51 diffAdded: '#79740e', diffRemoved: '#9d0006',
52 },
53 'rose-pine': {
54 accent: '#c4a7e7', heading: '#c4a7e7', tableHeader: '#f6c177', strong: '#e0def4', emphasis: '#ebbcba',
55 inlineCode: '#9ccfd8', codeText: '#e0def4', codeCommand: '#9ccfd8', codeFlag: '#eb6f92', codeString: '#f6c177',
56 codeComment: '#6e6a86', link: '#c4a7e7', path: '#9ccfd8', number: '#ebbcba', quote: '#908caa',
57 rule: '#26233a', tableRule: '#6e6a86', bullet: '#eb6f92', diagram: '#c4a7e7', diagramText: '#e0def4',
58 diffAdded: '#9ccfd8', diffRemoved: '#eb6f92',
59 },
60 'rose-pine-dawn': {
61 accent: '#907aa9', heading: '#907aa9', tableHeader: '#ea9d34', strong: '#464261', emphasis: '#d7827e',
62 inlineCode: '#56949f', codeText: '#464261', codeCommand: '#56949f', codeFlag: '#b4637a', codeString: '#ea9d34',
63 codeComment: '#9893a5', link: '#907aa9', path: '#286983', number: '#d7827e', quote: '#797593',
64 rule: '#f2e9e1', tableRule: '#9893a5', bullet: '#b4637a', diagram: '#907aa9', diagramText: '#464261',
65 diffAdded: '#56949f', diffRemoved: '#b4637a',
66 },
67 everforest: {
68 accent: '#a7c080', heading: '#e69875', tableHeader: '#dbbc7f', strong: '#d3c6aa', emphasis: '#d699b6',
69 inlineCode: '#83c092', codeText: '#d3c6aa', codeCommand: '#7fbbb3', codeFlag: '#e67e80', codeString: '#a7c080',
70 codeComment: '#859289', link: '#7fbbb3', path: '#83c092', number: '#d699b6', quote: '#9da9a0',
71 rule: '#475258', tableRule: '#7a8478', bullet: '#e69875', diagram: '#7fbbb3', diagramText: '#d3c6aa',
72 diffAdded: '#a7c080', diffRemoved: '#e67e80',
73 },
74 'github-dark': {
75 accent: '#d2a8ff', heading: '#79c0ff', tableHeader: '#ffa657', strong: '#e6edf3', emphasis: '#d2a8ff',
76 inlineCode: '#79c0ff', codeText: '#e6edf3', codeCommand: '#d2a8ff', codeFlag: '#ff7b72', codeString: '#a5d6ff',
77 codeComment: '#7d8590', link: '#58a6ff', path: '#7ee787', number: '#79c0ff', quote: '#7d8590',
78 rule: '#30363d', tableRule: '#8b949e', bullet: '#ff7b72', diagram: '#58a6ff', diagramText: '#e6edf3',
79 diffAdded: '#3fb950', diffRemoved: '#f85149',
80 },
81 'github-light': {
82 accent: '#8250df', heading: '#0550ae', tableHeader: '#953800', strong: '#1f2328', emphasis: '#8250df',
83 inlineCode: '#0550ae', codeText: '#1f2328', codeCommand: '#8250df', codeFlag: '#cf222e', codeString: '#0a3069',
84 codeComment: '#6e7781', link: '#0969da', path: '#116329', number: '#0550ae', quote: '#656d76',
85 rule: '#d0d7de', tableRule: '#6e7781', bullet: '#cf222e', diagram: '#0969da', diagramText: '#1f2328',
86 diffAdded: '#1a7f37', diffRemoved: '#cf222e',
87 },
88 'one-dark': {
89 accent: '#c678dd', heading: '#e06c75', tableHeader: '#e5c07b', strong: '#d19a66', emphasis: '#c678dd',
90 inlineCode: '#56b6c2', codeText: '#abb2bf', codeCommand: '#61afef', codeFlag: '#e06c75', codeString: '#98c379',
91 codeComment: '#5c6370', link: '#61afef', path: '#56b6c2', number: '#d19a66', quote: '#828997',
92 rule: '#3a3f4b', tableRule: '#5c6370', bullet: '#c678dd', diagram: '#61afef', diagramText: '#abb2bf',
93 diffAdded: '#98c379', diffRemoved: '#e06c75',
94 },
95 'solarized-dark': {
96 accent: '#6c71c4', heading: '#b58900', tableHeader: '#b58900', strong: '#eee8d5', emphasis: '#d33682',
97 inlineCode: '#2aa198', codeText: '#93a1a1', codeCommand: '#268bd2', codeFlag: '#cb4b16', codeString: '#859900',
98 codeComment: '#586e75', link: '#268bd2', path: '#2aa198', number: '#859900', quote: '#657b83',
99 rule: '#073642', tableRule: '#586e75', bullet: '#6c71c4', diagram: '#268bd2', diagramText: '#93a1a1',
100 diffAdded: '#859900', diffRemoved: '#dc322f',
101 },
102 'solarized-light': {
103 accent: '#6c71c4', heading: '#b58900', tableHeader: '#b58900', strong: '#073642', emphasis: '#d33682',
104 inlineCode: '#2aa198', codeText: '#586e75', codeCommand: '#268bd2', codeFlag: '#cb4b16', codeString: '#859900',
105 codeComment: '#93a1a1', link: '#268bd2', path: '#2aa198', number: '#859900', quote: '#839496',
106 rule: '#eee8d5', tableRule: '#93a1a1', bullet: '#6c71c4', diagram: '#268bd2', diagramText: '#586e75',
107 diffAdded: '#849800', diffRemoved: '#dc322f',
108 },
109 neon: {
110 accent: '#00e5ff', heading: '#00e5ff', tableHeader: '#00e5ff', strong: '#00e5ff', emphasis: '#a77bff',
111 inlineCode: '#ffcc33', codeText: '#c9d4f2', codeCommand: '#a77bff', codeFlag: '#ff3ea5', codeString: '#3dff9a',
112 codeComment: '#66708f', link: '#a77bff', path: '#ffcc33', number: '#3dff9a', quote: '#c9d4f2',
113 rule: '#343c5c', tableRule: '#343c5c', bullet: '#8b95b8', diagram: '#66708f', diagramText: '#c9d4f2',
114 diffAdded: '#3dff9a', diffRemoved: '#ff4d6d',
115 },
116 mono: {} as Theme,
117} satisfies Record<string, Theme>
118
119export type PresetName = keyof typeof PRESETS
120export const PRESET_NAMES = Object.keys(PRESETS) as PresetName[]
121
122export const PRESET_BACKGROUNDS: Partial<Record<PresetName, string>> = {
123 'catppuccin-mocha': '#1e1e2e',
124 'catppuccin-latte': '#eff1f5',
125 dracula: '#282a36',
126 nord: '#2e3440',
127 'tokyo-night': '#1a1b26',
128 'gruvbox-dark': '#282828',
129 'gruvbox-light': '#fbf1c7',
130 'rose-pine': '#191724',
131 'rose-pine-dawn': '#faf4ed',
132 everforest: '#2d353b',
133 'github-dark': '#0d1117',
134 'github-light': '#ffffff',
135 'one-dark': '#282c34',
136 'solarized-dark': '#002b36',
137 'solarized-light': '#fdf6e3',
138 neon: '#0b0e1a',
139}
140hooks/theme.ts 114 lines1import type { PluginOptions } from 'claude-code'
2
3import type { ClipboardBackend } from './clipboard'
4import type { PresetName } from './presets'
5import { PRESET_BACKGROUNDS, PRESET_NAMES, PRESETS } from './presets'
6import type { Shape, Terminal } from './rtl'
7import { TERMINALS } from './rtl'
8
9export const TOKENS = [
10 'accent', 'heading', 'strong', 'emphasis', 'inlineCode', 'codeText', 'codeCommand', 'codeFlag', 'codeString', 'codeComment',
11 'link', 'path', 'number', 'quote', 'rule', 'tableHeader', 'tableRule', 'bullet', 'diagram', 'diagramText', 'diffAdded', 'diffRemoved',
12] as const
13
14export type Theme = Partial<Record<(typeof TOKENS)[number], string>>
15
16export type Clock = 'off' | '24h' | '12h'
17
18export type Style = {
19 theme: Theme
20 background?: string
21 headingStyle: 'bold' | 'underline' | 'uppercase' | 'banner'
22 tableStyle: 'box' | 'rules' | 'grid' | 'minimal'
23 taskStyle: 'checks' | 'ticks' | 'box' | 'progress'
24 promptStyle: 'bubble' | 'wide' | 'bar' | 'chevron' | 'off'
25 clock: Clock
26 toolStyle: 'chat' | 'tree-dim' | 'tree-bold' | 'classic'
27 toolOutput: 'full' | 'quiet'
28 narration?: boolean
29 inside?: 'quote' | 'alert'
30 noteKey?: string
31 pressPreview?: boolean
32 diffStyle: 'card' | 'full' | 'marks' | 'bar'
33 pieStyle: 'round' | 'bars'
34 highlightNumbers: boolean
35 highlightPaths: boolean
36 mermaid: boolean
37 mermaidAscii: boolean
38 copyButtons: boolean
39 copyButtonStyle: 'inline' | 'hover'
40 htmlCopy: ClipboardBackend | null
41 nativeCode?: boolean
42 gridFace?: boolean
43 httpLinks: boolean
44 editorLinks: boolean
45 fileLinks: string | null
46 pathLinks: boolean
47 found?: ReadonlySet<string>
48 diagramHints: boolean
49 issueHint: boolean
50 rtl: 'auto' | Terminal | 'off'
51 reorder: boolean
52 shape: Shape
53 latex: boolean
54 cwd: string
55 home: string
56}
57
58const COLOR = /^(#[0-9a-f]{3}|#[0-9a-f]{6}|rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)|ansi256\(\d{1,3}\)|(black|red|green|yellow|blue|magenta|cyan|white|gray|grey)(Bright)?)$/i
59
60export const isColor = (value: unknown): value is string => typeof value === 'string' && COLOR.test(value.trim())
61
62const pick = <T extends string>(value: unknown, allowed: readonly T[], fallback: T): T =>
63 allowed.includes(value as T) ? (value as T) : fallback
64
65export const RANDOM_THEMES: readonly string[] = PRESET_NAMES.filter(t => !/latte|light|dawn/.test(t) && t !== 'mono')
66
67export const pickTheme = (value: unknown, random = Math.random): string => {
68 const name = value === 'random' ? RANDOM_THEMES[Math.floor(random() * RANDOM_THEMES.length)] : value
69 return (PRESET_NAMES as readonly unknown[]).includes(name) ? String(name) : 'catppuccin-mocha'
70}
71
72export const resolveStyle = (options: PluginOptions): Style => {
73 const preset = (PRESET_NAMES as string[]).includes(String(options.theme)) ? (String(options.theme) as PresetName) : 'catppuccin-mocha'
74 const base: Theme = PRESETS[preset]
75 const fromFields = Object.fromEntries(
76 TOKENS.filter(k => isColor(options[`${k}Color`])).map(k => [k, String(options[`${k}Color`]).trim()]),
77 )
78
79 const rtl = pick(options.rtl, ['auto', 'off', ...(Object.keys(TERMINALS) as Terminal[])], 'auto')
80
81 return {
82 theme: { ...base, ...fromFields },
83 ...(PRESET_BACKGROUNDS[preset] ? { background: PRESET_BACKGROUNDS[preset] } : {}),
84 headingStyle: pick(options.headingStyle, ['bold', 'underline', 'uppercase', 'banner'] as const, 'banner'),
85 tableStyle: pick(options.tableStyle, ['box', 'rules', 'grid', 'minimal'] as const, 'box'),
86 taskStyle: pick(options.taskStyle, ['checks', 'ticks', 'box', 'progress'] as const, 'checks'),
87 promptStyle: pick(options.promptStyle, ['bubble', 'wide', 'bar', 'chevron', 'off'] as const, 'bubble'),
88 clock: pick(options.clock, ['off', '24h', '12h'] as const, 'off'),
89 toolStyle: pick(options.toolStyle, ['chat', 'tree-dim', 'tree-bold', 'classic'] as const, 'chat'),
90 toolOutput: pick(options.toolOutput, ['full', 'quiet'] as const, 'full'),
91 diffStyle: pick(options.diffStyle, ['card', 'full', 'marks', 'bar'] as const, 'card'),
92 pieStyle: pick(options.pieStyle, ['round', 'bars'] as const, 'round'),
93 highlightNumbers: options.highlightNumbers !== false,
94 highlightPaths: options.highlightPaths !== false,
95 mermaid: options.mermaid !== false,
96 mermaidAscii: options.mermaidAscii === true,
97 copyButtons: options.copyButtons !== false,
98 copyButtonStyle: pick(options.copyButtonStyle, ['inline', 'hover'] as const, 'inline'),
99 htmlCopy: null,
100 httpLinks: false,
101 editorLinks: false,
102 fileLinks: null,
103 pathLinks: false,
104 diagramHints: options.diagramHints !== false && options.mermaid !== false,
105 issueHint: options.issueHint !== false,
106 rtl,
107 reorder: rtl !== 'auto' && rtl !== 'off',
108 shape: rtl === 'auto' || rtl === 'off' ? 'visual' : TERMINALS[rtl],
109 latex: options.latex === true,
110 cwd: '',
111 home: '',
112 }
113}
114hooks/rtl.ts 434 lines1import type { Inline } from './markdown'
2
3type Dir = 'R' | 'L'
4export type Flow = { base: Dir; lines: Inline[][] }
5export type Shape = 'visual' | 'words' | 'logical' | 'mirror' | 'inverse' | 'engine'
6
7export const TERMINALS = {
8 warp: 'visual',
9 ghostty: 'visual',
10 wezterm: 'visual',
11 vscode: 'visual',
12 alacritty: 'visual',
13 'windows-terminal': 'engine',
14 'apple-terminal': 'logical',
15 kitty: 'words',
16 iterm: 'mirror',
17 gnome: 'logical',
18 konsole: 'logical',
19} as const satisfies Record<string, Shape>
20
21export type Terminal = keyof typeof TERMINALS
22
23type Fmt = { wrap: ('strong' | 'emphasis' | 'strike')[]; leaf: 'text' | 'code' | 'math' | 'number' | 'path' | 'link' | 'dim' | 'footnote'; href?: string }
24type Unit = { ch: string; fmt: Fmt }
25
26const R = /[--ٟ٪-ۯۺ-ݿࢠ-ࣿיִ-﷿ﹰ-]/
27const L = /[A-Za-z0-9À-ɏ٠-٩۰-۹]/
28const LATIN = /[A-Za-zÀ-ɏ]/
29const MARK = /\p{M}/u
30const MIRROR: Record<string, string> = { '(': ')', ')': '(', '[': ']', ']': '[', '{': '}', '}': '{', '<': '>', '>': '<' }
31const DIGIT = /[0-9\u0660-\u0669\u06F0-\u06F9]/
32const TERMINATOR = /[#%\u2030\u00B0$\u20AC\u00A3\u00A5\u20AA]/
33const COMMENT = /^(.*?)((?:^|\s)(?:#|\/\/)\s+)(.*)$/
34
35const classify = (ch: string): Dir | null => (R.test(ch) ? 'R' : L.test(ch) ? 'L' : null)
36
37const byDigit = (us: Unit[], i: number): boolean => TERMINATOR.test(us[i]!.ch) && (DIGIT.test(us[i - 1]?.ch ?? '') || DIGIT.test(us[i + 1]?.ch ?? ''))
38
39const units = (text: string, fmt: Fmt): Unit[] => {
40 const out: Unit[] = []
41 for (const cp of text) {
42 const last = out.at(-1)
43 if (last && MARK.test(cp)) last.ch += cp
44 else out.push({ ch: cp, fmt })
45 }
46 return out
47}
48
49const flatten = (nodes: Inline[], wrap: Fmt['wrap'] = []): Unit[] =>
50 nodes.flatMap(n => {
51 switch (n.kind) {
52 case 'strong':
53 case 'emphasis':
54 case 'strike':
55 return flatten(n.children, [...wrap, n.kind])
56 case 'link':
57 return units(n.text, { wrap, leaf: 'link', href: n.href })
58 case 'image':
59 return units(n.text, { wrap, leaf: 'text' })
60 case 'path': {
61 const [, body = n.text, dot = ''] = /^(.*\w)(\.)$/.exec(n.text) ?? []
62 return [...units(body, { wrap, leaf: 'path', href: n.href }), ...units(dot, { wrap, leaf: 'text' })]
63 }
64 default:
65 return units(n.text, { wrap, leaf: n.kind })
66 }
67 })
68
69const sameFmt = (a: Fmt, b: Fmt) => a.leaf === b.leaf && a.href === b.href && a.wrap.length === b.wrap.length && a.wrap.every((k, i) => k === b.wrap[i])
70
71const leafNode = ({ leaf, href }: Fmt, text: string): Inline =>
72 leaf === 'link' ? { kind: 'link', text, href: href! } : leaf === 'path' && href ? { kind: 'path', text, href } : { kind: leaf, text }
73
74const rebuild = (all: Unit[]): Inline[] => {
75 const out: Inline[] = []
76 let i = 0
77 while (i < all.length) {
78 const fmt = all[i]!.fmt
79 let text = ''
80 let j = i
81 while (j < all.length && sameFmt(all[j]!.fmt, fmt)) text += all[j++]!.ch
82 out.push(fmt.wrap.reduceRight<Inline>((inner, kind) => ({ kind, children: [inner] }), leafNode(fmt, text)))
83 i = j
84 }
85 return out
86}
87
88const baseOf = (all: Unit[]): Dir => {
89 const words = all.map(u => u.ch).join('').split(/\s+/)
90 const rw = words.filter(w => R.test(w)).length
91 const lw = words.filter(w => LATIN.test(w) && !R.test(w)).length
92 if (rw !== lw) return rw > lw ? 'R' : 'L'
93 return all.map(u => classify(u.ch)).find(Boolean) ?? 'R'
94}
95
96const turn = <U extends Unit>(us: U[]): U[] => us.map(u => ({ ...u, ch: MIRROR[u.ch] ?? u.ch })).reverse()
97
98const reorder = <U extends Unit>(all: U[], base: Dir): U[] => {
99 const strong = all.map((u, i) => {
100 const own = classify(u.ch)
101 if (own) return own
102 if (u.fmt.leaf === 'code' || u.fmt.leaf === 'math' || u.fmt.leaf === 'path' || (u.fmt.leaf === 'link' && /^file:/i.test(u.fmt.href ?? ''))) return 'L'
103 return byDigit(all, i) ? 'L' : null
104 })
105 const prev: (Dir | null)[] = []
106 let seen: Dir | null = null
107 strong.forEach((s, i) => {
108 seen = s ?? seen
109 prev[i] = seen
110 })
111 const next: (Dir | null)[] = []
112 seen = null
113 for (let i = strong.length - 1; i >= 0; i--) {
114 seen = strong[i] ?? seen
115 next[i] = seen
116 }
117 const dir = strong.map((s, i): Dir => s ?? ((prev[i] ?? base) === (next[i] ?? base) ? (prev[i] ?? base) : base))
118 const runs: { d: Dir; u: U[] }[] = []
119 all.forEach((u, i) => {
120 const last = runs.at(-1)
121 if (last && last.d === dir[i]) last.u.push(u)
122 else runs.push({ d: dir[i]!, u: [u] })
123 })
124 const out = runs.map(r => (r.d === 'R' ? turn(r.u) : r.u))
125 return (base === 'R' ? out.reverse() : out).flat()
126}
127
128const LRM = '\u200E'
129
130const bidiClass = (ch: string): string =>
131 ch === LRM ? 'L' : R.test(ch) ? 'R' : /[٠-٩]/.test(ch) ? 'AN' : /[0-9۰-۹]/.test(ch) ? 'EN' : /\p{L}/u.test(ch) ? 'L' : /[+-]/.test(ch) ? 'ES' : /[#$%°£€¥₪‰¢]/.test(ch) ? 'ET' : /[,.:/]/.test(ch) ? 'CS' : 'N'
132
133const levelsOf = (all: Unit[], base: Dir): number[] => {
134 const t = all.map(u => bidiClass(u.ch))
135 t.forEach((c, i) => {
136 if ((c === 'ES' || c === 'CS') && t[i - 1] === 'EN' && t[i + 1] === 'EN') t[i] = 'EN'
137 else if (c === 'CS' && t[i - 1] === 'AN' && t[i + 1] === 'AN') t[i] = 'AN'
138 })
139 for (let i = 1; i < t.length; i++) if (t[i] === 'ET' && t[i - 1] === 'EN') t[i] = 'EN'
140 for (let i = t.length - 2; i >= 0; i--) if (t[i] === 'ET' && t[i + 1] === 'EN') t[i] = 'EN'
141 let strong: string = base
142 const w = t.map(c => {
143 if (c === 'L' || c === 'R') strong = c
144 return c === 'EN' && strong === 'L' ? 'L' : c === 'ES' || c === 'ET' || c === 'CS' ? 'N' : c
145 })
146 const rtlSide = (c?: string) => (c ?? base) !== 'L'
147 const ltr = base === 'L' ? 0 : 2
148 const rtl = 1
149 return w.map((c, i) => {
150 if (c !== 'N') return c === 'L' ? ltr : c === 'R' ? rtl : 2
151 let a = i
152 while (w[a] === 'N') a--
153 let b = i
154 while (w[b] === 'N') b++
155 const [before, after] = [rtlSide(w[a]), rtlSide(w[b])]
156 return before === after ? (before ? rtl : ltr) : base === 'L' ? 0 : 1
157 })
158}
159
160const terminalBidi = <U extends Unit>(all: U[], mirror = true): U[] => {
161 const levels = levelsOf(all, 'L')
162 let out = all.map((u, i) => ({ u: mirror && levels[i]! % 2 ? { ...u, ch: MIRROR[u.ch] ?? u.ch } : u, l: levels[i]! }))
163 for (let l = 2; l >= 1; l--) {
164 const done: typeof out = []
165 let run: typeof out = []
166 for (const x of out) {
167 if (x.l >= l) run.push(x)
168 else {
169 done.push(...run.reverse(), x)
170 run = []
171 }
172 }
173 out = [...done, ...run.reverse()]
174 }
175 return out.map(x => x.u)
176}
177
178export const terminalLine = (nodes: Inline[]): Inline[] => rebuild(terminalBidi(flatten(nodes)))
179
180const wrapUnits = (all: Unit[], max: number, measure: (s: string) => number): Unit[][] => {
181 const tokens: Unit[][] = []
182 all.forEach((u, i) => {
183 if (i === 0 || (u.ch !== ' ' && all[i - 1]!.ch === ' ')) tokens.push([])
184 tokens.at(-1)!.push(u)
185 })
186 const lines: Unit[][] = [[]]
187 let used = 0
188 const trim = (line: Unit[]) => {
189 while (line.at(-1)?.ch === ' ') line.pop()
190 }
191 for (const token of tokens) {
192 let core = token.length
193 while (core > 0 && token[core - 1]!.ch === ' ') core--
194 const w = token.slice(0, core).reduce((sum, u) => sum + measure(u.ch), 0)
195 if (lines.at(-1)!.length && used + w > max) {
196 trim(lines.at(-1)!)
197 lines.push([])
198 used = 0
199 }
200 lines.at(-1)!.push(...token)
201 used += w + (token.length - core)
202 }
203 trim(lines.at(-1)!)
204 return lines
205}
206
207const clusters = (text: string): string[] => units(text, { wrap: [], leaf: 'text' }).map(u => u.ch)
208
209const RUN = new RegExp(`(?:${R.source}|\\p{M})+`, 'gu')
210
211const shapeText = (text: string, shape: Shape): string =>
212 !R.test(text) ? text : shape === 'words' ? text.replace(RUN, run => clusters(run).reverse().join('')) : shape === 'inverse' ? terminalBidi(units(text, { wrap: [], leaf: 'text' })).map(u => u.ch).join('') : text
213
214const shapeNodes = (nodes: Inline[], shape: Shape): Inline[] =>
215 nodes.map(n => {
216 if ('children' in n) return { ...n, children: shapeNodes(n.children, shape) }
217 return { ...n, text: shapeText(n.text, shape) }
218 })
219
220export const containsRtl = (nodes: Inline[]): boolean => nodes.some(n => ('children' in n ? containsRtl(n.children) : R.test(n.text)))
221
222export const WALL = '׀'
223
224export const ROW_MARK_TEXT = `${WALL} `
225
226export const ROW_MARK: Inline = { kind: 'dim', text: ROW_MARK_TEXT }
227
228const asWritten = (shape: Shape) => shape === 'logical' || shape === 'mirror' || shape === 'engine'
229
230const ISOLATED: Fmt['leaf'][] = ['code', 'math', 'path']
231
232const HELD_EDGES: Fmt['leaf'][] = [...ISOLATED, 'link']
233
234const isolate = (all: Unit[]): Unit[] =>
235 all.flatMap((u, i) => {
236 if (!ISOLATED.includes(u.fmt.leaf)) return [u]
237 const mark = { ch: LRM, fmt: u.fmt }
238 const opens = i === 0 || !sameFmt(all[i - 1]!.fmt, u.fmt)
239 const closes = i === all.length - 1 || !sameFmt(all[i + 1]!.fmt, u.fmt)
240 return [...(opens ? [mark] : []), u, ...(closes ? [mark] : [])]
241 })
242
243const strongFrom = (line: Unit[], i: number, step: 1 | -1): Dir => {
244 for (let j = i; j >= 0 && j < line.length; j += step) {
245 const c = bidiClass(line[j]!.ch)
246 if (c === 'L' || c === 'R') return c
247 }
248 return 'R'
249}
250
251const anchored = (span: Unit[], i: number): boolean =>
252 classify(span[i]!.ch) !== null || byDigit(span, i)
253
254const swapEdges = (span: Unit[]): Unit[] => {
255 let a = 0
256 while (a < span.length && !anchored(span, a)) a++
257 let b = span.length
258 while (b > a && !anchored(span, b - 1)) b--
259 return [...turn(span.slice(b)), ...span.slice(a, b), ...turn(span.slice(0, a))]
260}
261
262const holdEdges = (line: Unit[]): Unit[] => {
263 const out = [...line]
264 for (let i = 0, j = 0; i < line.length; i = j) {
265 j = i + 1
266 if (!HELD_EDGES.includes(line[i]!.fmt.leaf)) continue
267 while (j < line.length && sameFmt(line[j]!.fmt, line[i]!.fmt)) j++
268 const span = line.slice(i, j)
269 if (!span.some(u => classify(u.ch) === 'R') && strongFrom(line, i - 1, -1) !== 'L' && strongFrom(line, j, 1) !== 'L') out.splice(i, span.length, ...swapEdges(span))
270 }
271 return out
272}
273
274const forEngine = (line: Unit[], lead: boolean): Unit[] => {
275 const first = isolate(line).map(u => bidiClass(u.ch)).find(c => c === 'L' || c === 'R')
276 const base = lead || first === 'R' ? 'R' : 'L'
277 const all = isolate(base === 'L' ? bindNumber(line) : line)
278 const levels = levelsOf(all, base)
279 return all.map((u, i) => (levels[i]! % 2 ? { ...u, ch: MIRROR[u.ch] ?? u.ch } : u))
280}
281
282const startsLatin = (line: Unit[]): boolean => line.map(u => bidiClass(u.ch)).find(c => c === 'L' || c === 'R') === 'L'
283
284export const opensLatin = (text: string): boolean => startsLatin(units(text, { wrap: [], leaf: 'text' }))
285
286const ordered = (line: Unit[], shape: Shape, base: Dir, lead: boolean): Unit[] =>
287 shape === 'engine' ? forEngine(line, lead) : shape === 'mirror' ? holdEdges(line) : asWritten(shape) ? line : shape === 'inverse' ? terminalBidi(reorder(line, base)) : reorder(line, base)
288
289export const flow = (nodes: Inline[], columns: number, measure: (s: string) => number, shape: Shape = 'visual', mark = true): Flow | null => {
290 if (!containsRtl(nodes)) return null
291 const all = flatten(nodes)
292 const base = shape === 'mirror' ? 'R' : baseOf(all)
293 const marked = mark && asWritten(shape) && base === 'R' && all.some(u => bidiClass(u.ch) === 'L')
294 const logical = base === 'R' ? wrapUnits(all, columns - (marked ? measure(ROW_MARK_TEXT) : 0), measure) : [all]
295 const lines = logical.map(line => {
296 const lead = marked && startsLatin(line)
297 const built = rebuild(ordered(line, shape, base, lead))
298 return lead ? [ROW_MARK, ...built] : built
299 })
300 return { base, lines: shape === 'words' ? lines.map(line => shapeNodes(line, shape)) : lines }
301}
302
303const visualText = (text: string, command = false): string => {
304 if (!R.test(text)) return text
305 const all = units(text, { wrap: [], leaf: 'text' })
306 return reorder(all, command && startsLatin(all) ? 'L' : baseOf(all)).map(u => u.ch).join('')
307}
308
309export const commentTail = (line: string, shape: Shape = 'visual'): { head: string; marker: string; tail: string } | null => {
310 if (asWritten(shape) || !R.test(line)) return null
311 const m = COMMENT.exec(line)
312 return m && R.test(m[3]!) ? { head: m[1]!, marker: m[2]!, tail: shapeText(visualText(m[3]!), shape) } : null
313}
314
315export const commentVisual = (text: string, shape: Shape = 'visual'): string => {
316 const c = commentTail(text, shape)
317 return c ? c.head + c.marker + c.tail : text
318}
319
320export const codeVisual = (text: string, shape: Shape = 'visual', max = Infinity, measure: (s: string) => number = s => s.length, command = false): string =>
321 asWritten(shape) || !R.test(text)
322 ? text
323 : text
324 .split('\n')
325 .flatMap(line => (measure(line) > max ? wrapUnits(units(line, { wrap: [], leaf: 'text' }), max, measure).map(row => row.map(u => u.ch).join('')) : [line]))
326 .map(line => shapeText(visualText(line, command), shape))
327 .join('\n')
328
329export const hasRtl = (text: string): boolean => R.test(text)
330
331export const LTR_BLANK = '⠀'
332
333const bindNumber = <U extends Unit>(all: U[]): U[] =>
334 all.map((u, i) => {
335 if (u.ch !== ' ' || !R.test(all[i - 1]?.ch ?? '') || !DIGIT.test(all[i + 1]?.ch ?? '')) return u
336 const next = all.slice(i + 1).find(n => bidiClass(n.ch) === 'L' || R.test(n.ch))
337 return next && R.test(next.ch) ? u : { ...u, ch: LTR_BLANK }
338 })
339
340const WORD = /[\p{L}\p{N}\p{P}]/u
341
342const DRAWN = /[←-⇿─-◿]/u
343
344const ASCII_DRAWN = /[-+|<>]/
345
346const LETTER = /[\p{L}\p{N}]/u
347
348const drawnAt = (all: Cell[], i: number) => {
349 const ch = all[i]!.ch
350 return DRAWN.test(ch) || (ASCII_DRAWN.test(ch) && !(LETTER.test(all[i - 1]?.ch ?? '') && LETTER.test(all[i + 1]?.ch ?? '')))
351}
352
353const inLabel = (chars: string[], c: number) => {
354 const [a = '', b = ''] = [chars[c - 1], chars[c + 1]]
355 return WORD.test(a) && WORD.test(b) && (R.test(a) || R.test(b))
356}
357
358type Cell = Unit & { at: number }
359
360export type Held = { cells: string[]; from: number[] }
361
362const PLAIN: Fmt = { wrap: [], leaf: 'text' }
363
364const rightToLeft = <U extends Unit>(all: U[]): U[] => (baseOf(all) !== 'R' ? bindNumber(all) : all.some(u => bidiClass(u.ch) === 'L') ? terminalBidi(reorder(all, 'R')) : all)
365
366export const heldCell = (nodes: Inline[]): Flow | null => {
367 if (!containsRtl(nodes)) return null
368 const all = flatten(nodes)
369 return { base: baseOf(all), lines: [rebuild(rightToLeft(all))] }
370}
371
372const byWords = (label: (words: Cell[]) => Cell[]) => (all: Cell[]): Cell[] => {
373 const out: Cell[] = []
374 let words: Cell[] = []
375 const flush = () => {
376 out.push(...(words.some(u => R.test(u.ch)) ? label(words) : words))
377 words = []
378 }
379 all.forEach((u, i) => {
380 if (!drawnAt(all, i)) words.push(u)
381 else {
382 flush()
383 out.push(u)
384 }
385 })
386 flush()
387 return out
388}
389
390const engineLabel = byWords(words => (baseOf(words) === 'R' ? terminalBidi(reorder(words, 'R'), false) : words))
391
392const visualLabel = byWords(words => reorder(words, baseOf(words)))
393
394const hold = (chars: string[], label: (all: Cell[]) => Cell[], blank: string[]): Held => {
395 const held: Held = { cells: [], from: [] }
396 let run: Cell[] = []
397 const flush = () => {
398 for (const u of label(run)) {
399 held.cells.push(u.ch)
400 held.from.push(u.at)
401 }
402 run = []
403 }
404 chars.forEach((ch, c) => {
405 if (ch === ' ' && !inLabel(chars, c)) {
406 flush()
407 for (const b of blank) {
408 held.cells.push(b)
409 held.from.push(c)
410 }
411 } else if (MARK.test(ch) && run.length) run.at(-1)!.ch += ch
412 else run.push({ ch, fmt: PLAIN, at: c })
413 })
414 flush()
415 return held
416}
417
418export const asIs = (chars: string[]): Held => ({ cells: chars, from: chars.map((_, c) => c) })
419
420export const holdText = (chars: string[]): Held => hold(chars, rightToLeft, [LTR_BLANK])
421
422export const listMarker = (marker: string, shape: Shape): string => (shape === 'logical' ? marker : marker.replace(/^(\d+)([.)])$/, (_, n: string, p: string) => (MIRROR[p] ?? p) + n))
423
424export const holdEngine = (chars: string[]): Held => (chars.some(ch => R.test(ch)) ? hold(chars, engineLabel, [LRM, ' ']) : asIs(chars))
425
426export const holdVisual = (chars: string[]): Held => (chars.some(ch => R.test(ch)) ? hold(chars, visualLabel, [' ']) : asIs(chars))
427
428export const holdRow = (chars: string[]): Held => (chars.some(ch => R.test(ch)) ? holdText(chars) : asIs(chars))
429
430export const led = (chars: string[], held: Held): Held => {
431 const blank = chars.some(ch => R.test(ch)) ? LTR_BLANK : ' '
432 return { cells: [blank, blank, ...held.cells], from: [-1, -1, ...held.from] }
433}
434