SLOPSHOPPER

prismantis

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

panespinnerrowscommandtoastprompt
★ 4v0.34.0MITupdated 2026-10-22ahmadhammoud56/MOAA/plugins/prismantis
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · prismantis
│ ┃ prismantis-setup ✕ ╭─────────────────────────────────────────────────────────────────╮ │ ┃ Setup 1/11: Theme │ fix the failing auth test and add an audit log call │ │ ┃ ━━━━━━━━━━━━━━━━━ ╰─────────────────────────────────────────────────────────────────╯ │ ┃ │ ┃ Each theme draws the same line. random picks ⏺ Read(src/auth.ts) │ ┃ a new dark one each time the mod loads. ⎿ Read 6 lines │ ┃ Edited src/auth.ts … ● │ ┃ ↑↓ or Tab moves, Enter saves and shows the ⏺ Bash(bun test) │ ┃ next step, Esc closes. ⎿ 3 pass, 1 fail │ ┃ │ ┃ [ catppuccin-mocha (now) ] 1. catppuccin- Done. I made refresh reject expired claims and added an audit call. │ ┃ [ catppuccin-latte ] │ ┃ [ dracula ] Release notes ✻ Worked for 42s │ ┃ [ nord ] │ ┃ [ tokyo-night ] Bold, inline c › /prismantis │ ┃ [ gruvbox-dark ] Commands │ ┃ [ gruvbox-light ] ┌─────────┬─── ━━━━━━━━ │ ┃ [ rose-pine ] │ Service │ St │ ┃ [ rose-pine-dawn ] ╞═════════╪═══ [ ⧉ md ] [ ⧉ art │ ┃ [ everforest ] │ api │ he ┌──────────────────────────┬─────────────────────────────────────── │ ┃ [ github-dark ] ├─────────┼─── ─────────────────────────────────────────────────────────────────── │ ┃ [ github-light ] │ billing │ de ─────────────────┐ │ ┃ [ one-dark ] └─────────┴─── │ Command │ Does │ ┃ [ solarized-dark ] ╞══════════════════════════╪═══════════════════════════════════════ │ ┃ [ solarized-light ] ── ts ═══════════════════════════════════════════════════════════════════ │ ┃ [ mono ] const total ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · prismantis-setup
Setup 1/11: Theme ━━━━━━━━━━━━━━━━━ Each theme draws the same line. random picks a new dark one each time the mod loads. ↑↓ or Tab moves, Enter saves and shows the next step, Esc closes. [ catppuccin-mocha (now) ] 1. catppuccin-mocha [ catppuccin-latte ] [ dracula ] Release notes [ nord ] [ tokyo-night ] Bold, inline code, 250ms and ~ [ gruvbox-dark ] [ gruvbox-light ] ┌─────────┬──────────┬───────┐ [ rose-pine ] │ Service │ Status │ p95 │ [ rose-pine-dawn ] ╞═════════╪══════════╪═══════╡ [ everforest ] │ api │ healthy │ 120ms │ [ github-dark ] ├─────────┼──────────┼───────┤ [ github-light ] │ billing │ degraded │ 840ms │ [ one-dark ] └─────────┴──────────┴───────┘ [ solarized-dark ] [ solarized-light ] ── ts [ mono ] const total = items.reduce(( [ random ] 0)
Turn line
✻ Worked for 42s
Your message
╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ fix the failing auth test and add an audit log call │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
Claude's reply
Done. I made refresh reject expired claims and added an audit call.
Tool row
Edited src/auth.ts … ●
Command output
Commands ━━━━━━━━ [ ⧉ md ] [ ⧉ art ] ┌──────────────────────────┬──────────────────────────────────────────────────────────────────────── ───────────────────────────────────────────────────────┐ │ Command │ Does ╞══════════════════════════╪════════════════════════════════════════════════════════════════════════ ═══════════════════════════════════════════════════════╡ │ /prismantis theme <name> │ Switch theme on the spot (/prismantis <name> works too), random for a n ├──────────────────────────┼──────────────────────────────────────────────────────────────────────── ───────────────────────────────────────────────────────┤ │ /prismantis copy │ Copy the last reply, or copy code for its last code block ├──────────────────────────┼──────────────────────────────────────────────────────────────────────── ───────────────────────────────────────────────────────┤ │ /prismantis setup │ Pick a theme and how tables, tasks, headings, copy buttons, prompts, ti │ │ look, from drawn samples ├──────────────────────────┼──────────────────────────────────────────────────────────────────────── ───────────────────────────────────────────────────────┤ │ /prismantis demo │ Full showcase, every element and diagram, plus a section in your langua ├──────────────────────────┼──────────────────────────────────────────────────────────────────────── ───────────────────────────────────────────────────────┤ │ /prismantis demo-rtl │ Hebrew right-to-left showcase └──────────────────────────┴──────────────────────────────────────────────────────────────────────── ───────────────────────────────────────────────────────┘ 16 themes [ ⧉ copy ] • Dark: catppuccin-mocha, dracula, nord, tokyo-night, gruvbox-dark, rose-pine, everforest, github-dark, one-dark, solarized-dark • Light: catppuccin-latte, gruvbox-light, rose-pine-dawn, github-light, solarized-light • Plain: mono, no color, only bold and dim Docs and issues: https://github.com/NahumLitvin/prismantis ╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Tip │ │ Any color slot beats the theme. Set headingColor or numberColor to a hex value in /config. │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ Task lists [ ⧉ copy ] [✓] Tables, diagrams and charts drawn in the terminal [✓] Copy tables as Markdown, art or HTML (macOS/Linux) [ ] Pick a taskStyle in /config: checks, ticks, box or progress [ ⧉ source ] [ ⧉ art ] ┌───────┐ ┌───────┐ ┌──────┐ ┌────────┐ │ Reply ├──►│ Parse ├──►│ Draw ├──►│ Screen │ └───────┘ └───────┘ └──────┘ └────────┘ ╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Caution │ │ Claude Code refuses trees over 20000 nodes. A code block past about 500 highlighted lines falls │ │ back to plain text. │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
README

<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>

Plain Claude Code replies wiping into prismantis: a table, a bar chart and a mermaid flowchart

<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>

TL;DR

  • Claude Code prints mermaid as source and tool calls as walls of text. prismantis draws them: real charts and flowcharts, typeset LaTeX math in kitty and Ghostty, colored tables and code, and quiet tool rows.
  • 15 palettes plus mono, and copy buttons on everything.
  • Two commands to install, /plugin to turn it off. Claude Code's own renderer comes back the moment you do.
  • No network calls. It runs a program only when you click ⧉ 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.

Install

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.

Codex

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.

Features

FeatureWhat you get
Themes/prismantis theme <name> switches on the spot. 16 themes and 20 color slots you can override
Tablescolored headers, rules, column alignment, colored numbers, sized to the terminal
Codea language header and copy button, Prism highlighting in two dozen languages, shell lines colored like a prompt
Diagrams and chartsflowcharts, 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
Layoutback-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 rowsRan 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 commandscommand output (/cost, /context, plugin commands) gets the same tables and code styling
Diagram hintsa 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
Textbold, italic, strikethrough, inline code, links, versions, durations, percentages and clickable paths in their own colors
Headings, lists, quotes4 heading styles, nested lists, task lists, quotes with an accent bar
Your promptswhat 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 leftHebrew 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

Themes

The same reply in all 15 color themes, ten dark and five light: a tip box, a task list, a flowchart and a bar chart

Random theme: plain Claude Code on the left, prismantis with theme random on the right

Dark: catppuccin-mocha (default), dracula, nord, tokyo-night, gruvbox-dark, rose-pine, everforest, github-dark, one-dark, solarized-dark.

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.

Tables

Tables: plain Claude Code on the left, prismantis on the right

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.

Code

Code: plain Claude Code on the left, prismantis on the right

Code fold: plain Claude Code on the left, prismantis numbering and folding a 45 line block on the right

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.

  • Prism highlights JavaScript, TypeScript, JSX/TSX, Python, Go, Rust, Java, Kotlin, Swift, C, C++, C#, Ruby, JSON, YAML, TOML, SQL, HTML, CSS, Dockerfile, HCL, Lua and diff.
  • Shell blocks (bash, sh, zsh, fish, powershell, unlabeled) color the command word, --flags, quoted strings and # comments, and restart after |, && and ;.

Diagrams and charts

Diagrams and charts: plain Claude Code on the left, prismantis on the right

Diagrams and charts: plain Claude Code on the left, prismantis on the right

Diagram too wide: plain Claude Code on the left, prismantis falling back to the source with a note on the right

Code blocks tagged mermaid draw as colored text art:

  • flowcharts (graph LR, graph TD, decisions), sequence, state, class and ER diagrams
  • bar and line charts with xychart-beta, sized to the terminal width
  • pie 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 apart
  • each box and participant gets its own theme color, the same at both ends of a sequence diagram
  • bars in a multi-series chart get their own colors; a single-series chart prints each value above its bar and colors the tallest one
  • gridlines stay dim, axis numbers use the number color

pieStyle 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 legendone bar per slice, largest first, with its share
roundbars

A round pie of visitors by referrer with a colored legend, beside a gantt chart of a week of releases on a shared date axis

Diagrams too wide for the window, or over 80 lines, stay as code. mermaidAscii swaps box-drawing characters for + - |.

Figures

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:

A figure drawn by prismantis: a time axis with ticks at 0, 10 and 12 s, the provider bar timing out at 10 s, the handler bar finishing at 12 s, and bookings going from 0 to 1 to 2

{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 color
  • ▶ and ◀ draw as ► and ◄, as in diagrams, so no glyph turns into an emoji; in mono, warn draws bold
  • a figure stays a code block while it streams (so a reply that opens with a figure shows its markup until the block closes), when it has more than 80 lines, when a line is wider than the window or than 100 columns, and when a line would not draw as written: a glyph that may draw as an emoji or takes two columns, a tab, a control character, a direction mark or another character that draws no column (a zero-width space, a soft hyphen), or role markup in the wrong case, misspelled, nested or left open; once the block is closed, a dim line above it says why, such as figure line 4: "⚠" may draw as an emoji, use a text glyph
  • frames are not checked: a box that does not close or a side, corner or divider out of its column draws as written, as Claude typed it, so a frame that is slightly off still draws
  • ⧉ source copies the block as Claude wrote it, ⧉ art the drawn text
  • figures draw whether mermaid is on or off; only the diagram hints note follows mermaid
  • Claude learns about figures from the diagram hints note: prefer a figure over mermaid when position carries meaning (durations racing on a time axis, a screen layout, phases, before and after); when you ask to explain, compare or plan something and pictures would make it easier to grasp, build the reply around them, with the core on the first screen; the prose does not retell the picture; then the roles, the width and the glyphs that draw cleanly; plain flows and charts stay mermaid

LaTeX math

LaTeX math: plain Claude Code on the left, prismantis on the right

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.

Layout

Layout: plain Claude Code on the left, prismantis on the right

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.

Copy buttons

Copy buttons: plain Claude Code on the left, prismantis on the right

  • Tables: ⧉ 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.
  • Code, lists and quotes: [ ⧉ copy ] on each. Code copies without its fences, lists as markdown, quotes without their > markers.
  • Diagrams and figures: ⧉ source copies the mermaid or figure source, ⧉ art the drawn art.
  • Whole replies: replies with more than one block, or any Hebrew or Arabic, end with ⧉ 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.
  • No mouse: /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.

copyButtonStyle hover: at rest a table, a bash block and the reply each show a dim ⧉; with the pointer on the table's ⧉, its ⧉ md, ⧉ art and ⧉ html buttons draw over the marker and the end of the header row

⧉ 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.

Tool rows

Tool rows: plain Claude Code on the left, prismantis on the right

Diff cards: plain Claude Code on the left, prismantis on the right

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)fullmarksbar
rounded box, tinted linesno box, lines tinted across the widthno tint, colored + and −no tint, a colored ▌ before each changed line
cardfullmarksbar

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-dimtree-boldclassic
dimmed on the right, capped at 60% of the widthtucked under the sentence with ⎿, dimmedtree-dim with one-line sentences in boldbold verb and status dot, full brightness
chattree-dimtree-boldclassic

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.

quiet: rows say what was read, nothing drawn under reads

Turn footer

Turn footer: plain Claude Code on the left, prismantis on the right

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.

Slash commands

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.

Diagram hints

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.

Text

Text: plain Claude Code on the left, prismantis on the right

Footnotes: plain Claude Code on the left, prismantis on the right

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 / links

Source 17 files
hooks/register.tsx 838 lines
1import { 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, 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>()
56
57const savePng = async ($: EngineInterface, art: string): Promise<string> => {
58  const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.'
59  const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
60  const tmp = (await $.env.get('TEMP')) ?? home
61  const out = `${tmp}/prismantis-${stamp}.png`
62  const script = `${$.plugin.root}/scripts/text2png.py`
63  for (const python of ['python', 'py', 'python3']) {
64    const run = await $.process.run([python, script, out], { stdin: art }).catch(() => undefined)
65    if (run?.exitCode === 0) return out
66  }
67  throw new Error('no python with pillow')
68}
69
70const copyPngToClipboard = async ($: EngineInterface, path: string): Promise<boolean> => {
71  const file = path.replace(/\//g, '\\')
72  const script = `Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $f='${file.replace(/'/g, "''")}'; $i=[System.Drawing.Image]::FromFile($f); $b=New-Object System.Drawing.Bitmap($i); $i.Dispose(); [System.Windows.Forms.Clipboard]::SetImage($b); $b.Dispose(); Remove-Item -LiteralPath $f`
73  const run = await $.process.run(['powershell', '-NoProfile', '-STA', '-Command', script]).catch(() => undefined)
74  return run?.exitCode === 0
75}
76
77const readOnlyCalls = new Set<string>()
78
79const columnsOf = (viewport?: { columns?: number }) => Math.max(20, (viewport?.columns ?? 100) - 4)
80
81const formulas = atom({ plugin: 'prismantis', key: 'formulas' } as const, {})
82const latexDir = atom({ plugin: 'prismantis', key: 'dir' } as const, '')
83const unfolded = atom({ plugin: 'prismantis', key: 'unfolded' } as const, [] as string[])
84const sent = atom({ plugin: 'prismantis', key: 'sent' } as const, [])
85const turnEnds = atom({ plugin: 'prismantis', key: 'turnEnds' } as const, [])
86const setupAt = atom({ plugin: 'prismantis', key: 'setupAt' } as const, 0)
87const setupFocus = atom({ plugin: 'prismantis', key: 'setupFocus' } as const, '')
88const setupLand = atom({ plugin: 'prismantis', key: 'setupLand' } as const, '')
89
90const firstDrawn = async ($: EngineInterface, id: string): Promise<number> => {
91  const ref = { plugin: 'prismantis', key: 'drawn', id } as const
92  const { value } = await $.state.get(ref)
93  if (value !== undefined) return value
94  const now = await $.clock.now()
95  $.clock.after(0, () => void $.state.set(ref, now, { ifVersion: 0 }))
96  return now
97}
98
99type Typeset = Exclude<Formula, { error: true }> & { tex: string }
100
101const showsImages = async ($: EngineInterface): Promise<boolean> => {
102  if (await $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES')) return true
103  if (await $.env.get('TMUX')) return false
104  const terminal = await detectTerminal($)
105  return terminal === 'kitty' || terminal === 'ghostty'
106}
107
108type Latex = { command: string; dir: string }
109type 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> }
110
111const formulaKey = (color: string, tex: string) => `${color}\0${tex}`
112
113const typeset = async ($: EngineInterface, color: string, engine: Latex, texs: string[], fontSize = LATEX_FONT_PX, dpr = LATEX_DPR): Promise<Formula[]> => {
114  const { stdout } = await $.process.run(
115    [engine.command, '--output-dir', engine.dir, '--color', color, '--background-color', 'transparent', '--font-size', String(fontSize), '--dpr', String(dpr)],
116    { stdin: `${texs.join('\n')}\n`, timeoutMs: 2000 },
117  )
118  const rendered = renderedOf(stdout)
119  return Promise.all(texs.map(async (_, i): Promise<Formula> => {
120    if (!rendered.has(i + 1)) return { error: true }
121    const png = await $.fs.read(`${engine.dir}/${String(i + 1).padStart(4, '0')}.png`, { as: 'bytes' }).then(r => r.base64, () => '')
122    const size = png ? pngSize(png) : null
123    return size && fitsImage(png) ? { png, ...size } : { error: true }
124  }))
125}
126
127const withPadding = async ($: EngineInterface, color: string, engine: Latex, texs: string[], results: Formula[]): Promise<Formula[]> => {
128  const padded: Formula[] = []
129  for (const [i, result] of results.entries()) {
130    const pad = 'png' in result ? padFor(result) : null
131    const [again] = pad ? await typeset($, color, engine, [texs[i]!], pad.fontSize, pad.dpr).catch((): Formula[] => []) : []
132    padded.push(again && 'png' in again && 'png' in result ? { ...result, padded: again } : result)
133  }
134  return padded
135}
136
137const startLatex = async ($: EngineInterface, latex: LatexSession): Promise<Latex | null> => {
138  if (!latex.style.latex || !(await $.session.surfaces()).includes('terminal') || !(await showsImages($))) return null
139  const tmp = (await $.env.get('TMPDIR')) ?? (await $.env.get('TEMP')) ?? '/tmp'
140  const suffix = (await read($, latexDir)) || crypto.randomUUID()
141  await update($, latexDir, () => suffix)
142  const engine = { command: 'ratex-render', dir: `${tmp.replace(/[\\/]+$/, '')}/prismantis-latex-${await $.session.id()}-${suffix}` }
143  const [check] = await typeset($, latex.color, engine, ['x^2'])
144  return check && 'png' in check ? engine : null
145}
146
147const latexEngine = ($: EngineInterface, latex: LatexSession): Promise<Latex | null> =>
148  (latex.engine ??= startLatex($, latex)
149    .catch(() => null)
150    .then(engine => {
151      latex.ready = engine
152      if (engine) $.ui.invalidate('ui.render')
153      return engine
154    }))
155
156const stopLatex = (latex: LatexSession) => {
157  latex.stopped = true
158  latex.pending.clear()
159  latex.batch = []
160}
161
162const typesetLater = async ($: EngineInterface, latex: LatexSession, texs: string[]): Promise<void> => {
163  const color = latex.color
164  const engine = await latexEngine($, latex)
165  if (!engine || latex.stopped) return
166  const results = await typeset($, color, engine, texs).then(
167    done => withPadding($, color, engine, texs, done),
168    () => null,
169  )
170  if (!results) return stopLatex(latex)
171  const fresh = texs.map((tex, i) => [formulaKey(color, tex), results[i]!] as const)
172  await update($, formulas, store => keepFormulas(store, fresh, latex.wanted))
173  latex.wanted.clear()
174  for (const tex of texs) latex.pending.delete(formulaKey(color, tex))
175}
176
177const mathOfBlocks = async ($: EngineInterface, latex: LatexSession, surface: string, blocks: Block[]): Promise<Map<number, Typeset>> => {
178  const maths = [...blocks.entries()].flatMap(([i, block]) => {
179    const tex = mathOf(block)
180    return tex === null ? [] : [{ i, tex, key: formulaKey(latex.color, tex) }]
181  })
182  if (surface !== 'terminal' || maths.length === 0) return new Map()
183  void latexEngine($, latex)
184  if (!latex.ready) return new Map()
185  for (const { key } of maths) latex.wanted.add(key)
186  const store = (await read($, formulas)) as Record<string, Formula>
187  const missing = latex.stopped ? [] : [...new Map(maths.map(({ key, tex }) => [key, tex]))].filter(([key]) => !store[key] && !latex.pending.has(key))
188  if (missing.length) {
189    if (latex.batch.length === 0) {
190      $.clock.after(0, () => {
191        const texs = latex.batch
192        latex.batch = []
193        latex.queue = latex.queue.then(() => typesetLater($, latex, texs)).catch(() => stopLatex(latex))
194      })
195    }
196    for (const [key, tex] of missing) {
197      latex.pending.add(key)
198      latex.batch.push(tex)
199    }
200  }
201  return new Map(maths.flatMap(({ i, tex, key }) => {
202    const formula = store[key]
203    return formula && 'png' in formula ? [[i, { tex, ...formula }] as const] : []
204  }))
205}
206
207type Picture = { png: string; width: number; height: number; alt: string }
208
209const pictureOf = async ($: EngineInterface, src: string, home: string): Promise<Omit<Picture, 'alt'> | null> => {
210  const file = imageFile(src, home)
211  if (!file) return null
212  const stat = 'path' in file ? await $.fs.stat(file.path).catch(() => null) : null
213  if ('path' in file && (stat?.kind !== 'file' || stat.size > MAX_IMAGE_BYTES)) return null
214  const png = 'png' in file ? file.png : await $.fs.read(file.path, { as: 'bytes' }).then(r => r.base64, () => '')
215  const size = png ? pngSize(png) : null
216  return size && size.width > 0 && size.height > 0 && fitsImage(png) ? { png, ...size } : null
217}
218
219const loaded = new Map<string, Promise<Omit<Picture, 'alt'> | null>>()
220
221const picturesOf = async ($: EngineInterface, style: Style, probes: Probes, surface: string, blocks: Block[]): Promise<Map<number, Picture>> => {
222  const images = [...blocks.entries()].flatMap(([i, block]) => {
223    const image = imageOf(block)
224    return image ? [{ i, ...image }] : []
225  })
226  if (surface !== 'terminal' || images.length === 0 || !(await (probes.images ??= showsImages($).catch(() => false)))) return new Map()
227  await locate($, style)
228  const found = await Promise.all(images.map(async ({ i, alt, src }) => {
229    const picture = await remember(loaded, src, () => pictureOf($, src, style.home), 50)
230    return picture ? [[i, { ...picture, alt }] as const] : []
231  }))
232  return new Map(found.flat())
233}
234
235const locate = async ($: EngineInterface, style: Style) => {
236  style.cwd = await $.session.root().catch(() => style.cwd)
237  style.home ||= (await $.env.get('HOME').catch(() => undefined)) ?? (await $.env.get('USERPROFILE').catch(() => undefined)) ?? ''
238}
239
240const htmlBackend = async ($: EngineInterface): Promise<ClipboardBackend | null> => {
241  if (await $.env.get('SSH_CONNECTION') || await $.env.get('SSH_TTY')) return null
242  if (await $.env.get('OS') === 'Windows_NT') return 'windows'
243  const helper = await $.fs.stat('/usr/bin/osascript').catch(() => null)
244  if (helper?.kind === 'file') return 'macos'
245  return await $.env.get('WAYLAND_DISPLAY') || await $.env.get('DISPLAY') ? 'linux' : null
246}
247
248type LinkReach = { http: boolean; editor: boolean; marks: boolean; files: string | null; paths: boolean }
249
250type Probes = { terminal?: Promise<Terminal | null>; htmlCopy?: Promise<ClipboardBackend | null>; links?: Promise<LinkReach>; images?: Promise<boolean> }
251
252const terminalEnv = async ($: EngineInterface): Promise<TerminalEnv> => ({
253  FORCE_HYPERLINK: await $.env.get('FORCE_HYPERLINK'),
254  TERM_PROGRAM: await $.env.get('TERM_PROGRAM'),
255  TERM_PROGRAM_VERSION: await $.env.get('TERM_PROGRAM_VERSION'),
256  TERM: await $.env.get('TERM'),
257  WT_SESSION: await $.env.get('WT_SESSION'),
258  LC_TERMINAL: await $.env.get('LC_TERMINAL'),
259  VTE_VERSION: await $.env.get('VTE_VERSION'),
260  TERMINAL_EMULATOR: await $.env.get('TERMINAL_EMULATOR'),
261})
262
263const overSsh = async ($: EngineInterface): Promise<boolean> => Boolean(await $.env.get('SSH_CONNECTION') || await $.env.get('SSH_TTY'))
264
265const fileRootOf = async ($: EngineInterface): Promise<string> => {
266  const distro = await $.env.get('WSL_DISTRO_NAME')
267  const linuxTerminal = distro !== undefined && Boolean(await $.env.get('VTE_VERSION') || await $.env.get('KONSOLE_VERSION') || await $.env.get('KITTY_WINDOW_ID'))
268  return fileRoot(linuxTerminal ? undefined : distro)
269}
270
271const readLinkReach = async ($: EngineInterface, style: Style): Promise<LinkReach> => {
272  const base = await $.session.version().then(v => v.base, () => undefined)
273  const http = takesHttpLinks(base)
274  if (http) await locate($, style)
275  const files = http && !(await overSsh($).catch(() => true)) ? await fileRootOf($).catch(() => 'file://') : null
276  return { http, editor: takesEditorLinks(base), marks: takesClickableMarks(base), files, paths: files !== null && drawsHyperlinks(await terminalEnv($).catch(() => ({}))) }
277}
278
279const linkReach = ($: EngineInterface, probes: Probes, style: Style): Promise<LinkReach> => (probes.links ??= readLinkReach($, style))
280
281const fileCard = async ($: EngineInterface, el: ReturnType<EngineInterface['ui']['resolve']>, output: unknown, id: string, style: Style, probes: Probes, drawn: () => Style, columns?: number): Promise<RenderElement | undefined> => {
282  const press = (await linkReach($, probes, style)).marks
283  if (leftToEngine(output, press)) return undefined
284  await locate($, style)
285  return renderDiffCard(el, drawn(), output, folder($, el, await read($, unfolded), press), id, columns)
286}
287
288const probe = async ($: EngineInterface, style: Style, probes: Probes): Promise<Terminal | null> => {
289  probes.terminal ??= applyRtl($, style)
290  const terminal = await probes.terminal
291  probes.htmlCopy ??= htmlBackend($)
292  const before = style.htmlCopy
293  style.htmlCopy = await probes.htmlCopy
294  const png = Boolean(await $.env.get('PRISMANTIS_PNG_BUTTON').catch(() => undefined))
295  if (style.htmlCopy !== before || style.pngCopy !== png) $.ui.invalidate('ui.render')
296  style.pngCopy = png
297  return terminal
298}
299
300const copyTable = async ($: EngineInterface, backend: ClipboardBackend, html: string, text: string): Promise<string | null> => {
301  const systemRoot = backend === 'windows' ? await $.env.get('SystemRoot') : undefined
302  const command = clipboardCommand(backend, html, text, systemRoot)
303  if (backend === 'windows' && !systemRoot) return command.failure
304  const result = await $.process.run(command.argv, { stdin: command.stdin, timeoutMs: 5000 }).catch(() => null)
305  if (!result) return command.failure
306  return result.exitCode === 0 ? null : result.stderr.trim() || command.failure
307}
308
309const folder = ($: EngineInterface, el: ReturnType<EngineInterface['ui']['resolve']>, open?: string[], faces = false): Fold => (id, hidden, key, look) => {
310  if (!open) return null
311  const folded = !open.includes(id)
312  const label = folded ? look?.label ?? `+${hidden} more lines` : 'show less'
313  const toggle = () => update($, unfolded, ids => (folded ? [...ids, id].slice(-500) : ids.filter(x => x !== id)))
314  if (!faces) return { folded, faced: false, element: <el.Button key={key} variant="secondary" label={label} onPress={toggle} /> }
315  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} />
316  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> }
317}
318
319const 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[] => {
320  const { Button } = el
321  const copy = (text: string | (() => string), key: string, label = '⧉ copy', html?: () => string) => {
322    const copied = async (surface: RenderSurface): Promise<string> => {
323      const content = typeof text === 'function' ? text() : text
324      const backend = style.htmlCopy
325      const failure = html && backend ? await copyTable($, backend, html(), content) : undefined
326      if (failure === null) return 'Copied formatted table'
327      const result = await $.ui.copy({ text: content, surface })
328      if (!result.isCopied) return `Copy failed: ${result.reason}`
329      return failure ? `Copied as plain text (${failure})` : 'Copied'
330    }
331    return style.copyButtons && (!html || style.htmlCopy) ? (
332      <Button
333        key={key}
334        variant="primary"
335        label={label}
336        onPress={async press => $.ui.toast(await copied(press.surface).catch(() => 'Copy failed'))}
337      />
338    ) : null
339  }
340  const png = (text: string | (() => string), key: string, label = '▣ png') =>
341    style.copyButtons && style.pngCopy ? (
342      <Button
343        key={key}
344        variant="primary"
345        label={label}
346        onPress={() => {
347          savePng($, typeof text === 'function' ? text() : text)
348            .then(async path => $.ui.toast((await copyPngToClipboard($, path)) ? 'Copied image' : `Clipboard copy failed, image kept at ${path}`))
349            .catch(() => $.ui.toast('PNG save failed (needs python + pillow)'))
350        }}
351      />
352    ) : null
353  const drawn = drawDiagrams(el, style, blocks, columns - markerRoom(style))
354  const Image = 'Image' in el ? el.Image : null
355  if (Image) {
356    for (const [i, formula] of math) {
357      const picked = pickFormula(formula, columns)
358      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} /> })
359    }
360    for (const [i, picture] of pictures) {
361      const fit = fitImage(picture, columns)
362      drawn.set(i, { element: <Image key={`b${i}`} source={{ png: picture.png }} columns={fit.columns} rows={fit.rows} alt={picture.alt} /> })
363    }
364  }
365  const tip = notes?.press ? noteTip(blocks, text => void $.ui.toast(text)) : undefined
366  const elements = renderBlocks(el, notes ? { ...style, noteKey: instanceKey(notes.id) } : style, blocks, columns, drawMath(el, style, blocks, drawn), copy, folder($, el, open), tip, png)
367  const button = reply === undefined ? null : copy(reply, 'reply', '⧉ copy reply')
368  if (!button) return elements
369  return [...elements, style.copyButtonStyle === 'hover' ? replyMarker(el, button, notes?.id) : <el.Box key="reply" alignSelf="flex-end">{button}</el.Box>]
370}
371
372const replyMarker = (el: ReturnType<EngineInterface['ui']['resolve']>, button: RenderElement, id?: string) => {
373  const scope = `copy:${id === undefined ? '' : instanceKey(id)}:reply`
374  return (
375    <el.Box key="reply" position="absolute" bottom={0} right={-MARK} hover={{ scope }}>
376      <el.Text dimColor>⧉</el.Text>
377      <el.Box position="absolute" top={0} right={0} display="none" hover={{ scope, display: 'flex' }}>{button}</el.Box>
378    </el.Box>
379  )
380}
381
382const THEME_ARGS = [...PRESET_NAMES, 'random']
383
384type Picked = { theme: string; options: PluginOptions; latex: LatexSession }
385
386const setTheme = async ($: EngineInterface, picked: Picked, name: string): Promise<string> => {
387  const result = await $.config.set({ key: `${$.plugin.name}.theme`, value: name })
388  if (result.deny) return `Could not switch theme: ${result.deny}`
389  if (name !== 'random' || picked.options.theme !== 'random') return `Theme set to ${name}.`
390  const others = RANDOM_THEMES.filter(t => t !== picked.theme)
391  picked.theme = others[Math.floor(Math.random() * others.length)]!
392  const style = picked.latex.style
393  style.theme = resolveStyle({ ...picked.options, theme: picked.theme }).theme
394  picked.latex.color = ratexColor(style.theme.diagramText ?? style.theme.codeText ?? '#808080')
395  $.ui.invalidate('ui.render')
396  return `Theme set to random: ${picked.theme} for now.\nkeep it: /prismantis theme ${picked.theme}`
397}
398
399const saveSetupPick = async ($: EngineInterface, picked: Picked, step: SetupStep, value: string): Promise<string> =>
400  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}.`))
401
402const SETUP_PANE = 'prismantis-setup'
403
404const SETUP_PICK = 'pick:'
405const SETUP_LIST_COLUMNS = 30
406const SETUP_HEAD_ROWS = 8
407
408const openPane = ($: EngineInterface) => $.ui.open({ id: SETUP_PANE, title: 'prismantis setup', focus: true, closeOnEscape: true, rows: 40, columns: 90 })
409
410const openSetupPane = async ($: EngineInterface): Promise<string | undefined> => {
411  await update($, setupAt, () => 0)
412  await update($, setupFocus, () => '')
413  await update($, setupLand, () => '')
414  const opened = await openPane($)
415  if (opened.isPlaced) return SETUP_PANE_OPENED
416  await $.ui.close({ id: SETUP_PANE })
417  return undefined
418}
419
420const pickKey = (step: SetupStep, value: string) => `${SETUP_PICK}${step.name}:${value}`
421
422const showSetupStep = async ($: EngineInterface, at: number, step: SetupStep, value: string): Promise<void> => {
423  await update($, setupFocus, () => value)
424  await update($, setupLand, () => pickKey(step, value))
425  await update($, setupAt, () => at)
426}
427
428const pickInPane = async ($: EngineInterface, picked: Picked, at: number, value: string, currentOf: (step: SetupStep) => string): Promise<void> => {
429  const steps = setupSteps(PRESET_NAMES)
430  const step = steps[at]!
431  const nextStep = steps[at + 1]
432  const done = `${step.title} set to ${value}.`
433  if (nextStep) await showSetupStep($, at + 1, nextStep, currentOf(nextStep))
434  else await $.ui.close({ id: SETUP_PANE })
435  $.ui.toast(nextStep ? done : `${done} Setup done.`)
436  const saved = await saveSetupPick($, picked, step, value)
437  if (saved === done) return
438  $.ui.toast(saved)
439  if (!saved.startsWith('Could not')) return
440  await showSetupStep($, at, step, value)
441  if (!nextStep) await openPane($)
442}
443
444const landSetupFocus = ($: EngineInterface, key: string): void => {
445  $.clock.after(0, async () => {
446    await $.ui.focus({ requestId: SETUP_PANE, key }).catch(() => undefined)
447    await update($, setupLand, land => (land === key ? '' : land))
448  })
449}
450
451const setup = async ($: EngineInterface, picked: Picked, origin: PromptOrigin, stepName?: string, pick?: string): Promise<string> => {
452  const inTerminal = !stepName && origin.kind === 'composer' && (await $.session.surfaces()).includes('terminal')
453  const opened = inTerminal ? await openSetupPane($) : undefined
454  if (opened) return opened
455  const steps = setupSteps(PRESET_NAMES)
456  const at = stepName ? steps.findIndex(s => s.name === stepName) : 0
457  const step = steps[at]
458  if (!step) return `Unknown setup step "${stepName}". Steps: ${steps.map(s => s.name).join(', ')}`
459  if (!pick) return setupText(setupParts(PRESET_NAMES, at))
460  const choices = step.key === 'theme' ? THEME_ARGS : step.options
461  const value = /^\d+$/.test(pick) ? step.options[Number(pick) - 1] : pick
462  if (!value || !choices.includes(value)) return `Unknown ${step.name} pick "${pick}". Pick 1-${step.options.length} or one of: ${choices.join(', ')}`
463  const saved = await saveSetupPick($, picked, step, value)
464  if (saved.startsWith('Could not')) return saved
465  return `${saved}\n\n${at + 1 < steps.length ? setupText(setupParts(PRESET_NAMES, at + 1)) : SETUP_DONE}`
466}
467
468const SETUP_GIT_STATUS = [
469  'On branch main',
470  'Changes not staged for commit:',
471  '  (use "git add <file>..." to update what will be committed)',
472  '        modified:   src/app.ts',
473  '',
474  'no changes added to commit (use "git add" and/or "git commit -a")',
475]
476const SETUP_BUILD_ERROR = [
477  '> app@1.4.0 build',
478  '> tsc',
479  ...[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'.`),
480  'Found 10 errors in the same file, starting at: src/app.ts:3',
481]
482
483const toolOutputSample = (el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, value: string, id: string, columns: number): RenderElement[] => {
484  const status = { tool: 'Bash', input: { command: 'git status' }, isRunning: false, isErrored: false, isInterrupted: false }
485  const build = { tool: 'Bash', input: { command: 'npm run build', description: 'Build the app' }, isRunning: false, isErrored: true, isInterrupted: false }
486  const statusRow = <el.Box key={`${id}s`}>{renderToolRow(el, style, status, columns)}</el.Box>
487  const buildRow = <el.Box key={`${id}r`}>{renderToolRow(el, style, build, columns)}</el.Box>
488  if (value === 'quiet') return [statusRow, buildRow, renderFailure(el, style, SETUP_BUILD_ERROR.join('\n'), `${id}e`) ?? <el.Box key={`${id}e`} />]
489  const folded = (lines: readonly string[], keep: number, color?: string) => [
490    ...lines.slice(0, keep).map((line, i) => <el.Text key={`l${i}`} color={color}>{`${i === 0 ? '  ⎿  ' : '     '}${line}`}</el.Text>),
491    <el.Text key="more" dimColor>{`     … +${lines.length - keep} lines (ctrl+o to expand)`}</el.Text>,
492  ]
493  return [
494    statusRow,
495    <el.Box key={`${id}so`} flexDirection="column">
496      {folded(SETUP_GIT_STATUS, 3)}
497      <el.Text key="allowed" dimColor>{'  ⎿  Allowed by auto mode classifier'}</el.Text>
498    </el.Box>,
499    buildRow,
500    <el.Box key={`${id}e`} flexDirection="column">{folded(['Error: Exit code 2', ...SETUP_BUILD_ERROR], 10, style.theme.codeFlag)}</el.Box>,
501  ]
502}
503
504const SETUP_TABLE = '| Item | Qty |\n|:-----|----:|\n| Apples | 3 |\n| Pears | 5 |'
505const SETUP_SENT = new Date(2026, 0, 15, 14, 32).getTime()
506
507const copySample = (el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, value: string, id: string, columns: number): RenderElement[] => {
508  const label: CopyButton = (_text, key, name = '⧉ copy', html) => (html && !style.htmlCopy ? null : <el.Text key={key} bold>{`[ ${name} ]`}</el.Text>)
509  const table = renderBlocks(el, style, parse(SETUP_TABLE, { numbers: style.highlightNumbers, paths: style.highlightPaths }), columns, new Map(), label)
510  return [
511    <el.Box key={`${id}t`} flexDirection="column">{table}</el.Box>,
512    ...(value === 'hover' ? [<el.Text key={`${id}h`} dimColor>{'Its buttons show only while the pointer is on its ⧉.'}</el.Text>] : []),
513  ]
514}
515
516const clockSample = (el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, value: string, id: string, columns: number): RenderElement[] => {
517  const time = value === '24h' || value === '12h' ? clockText(SETUP_SENT, SETUP_SENT, value) : undefined
518  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)
519  return [<el.Box key={`${id}p`}>{prompt}</el.Box>, <el.Box key={`${id}d`}>{renderTurnDuration(el, style, 'Baked', 115000, time)}</el.Box>]
520}
521
522const SETUP_EDIT = {
523  filePath: 'src/config.ts',
524  structuredPatch: [{ oldStart: 12, newStart: 12, lines: [' export const config = {', '-  retries: 3,', '-  timeout: 5000,', '+  retries: 5,', '+  timeout: 10_000,', '   verbose: false,', ' }'] }],
525}
526
527const diffSample = (el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, id: string, columns: number): RenderElement[] => [
528  <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>,
529  <el.Box key={`${id}d`} flexDirection="column">{renderDiffCard(el, style, SETUP_EDIT, () => null, id, columns)}</el.Box>,
530]
531
532type SetupView = { el: ReturnType<EngineInterface['ui']['resolve']>; base: Style; options: PluginOptions; at: number; step: SetupStep; current: string; columns: number; rows: number; pick: (value: string) => void }
533
534const setupKeyboardPane = ($: EngineInterface, v: SetupView, focused: string, randomTheme: string): RenderElement => {
535  const { el, step } = v
536  const choices = step.key === 'theme' ? THEME_ARGS : step.options
537  const shown = choices.includes(focused) ? focused : v.current
538  const sampled = shown === 'random' ? randomTheme : shown
539  const parts = setupParts(PRESET_NAMES, v.at)
540  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))
541  const drawn = drawSetup($, el, v.base, v.options, { at: v.at, before: '', parts: { ...parts, options, tail: '' } }, Math.max(40, v.columns - SETUP_LIST_COLUMNS))
542  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)} />)
543  const fits = choices.length + SETUP_HEAD_ROWS <= v.rows
544  return (
545    <el.Box flexDirection="column" rowGap={1} {...(fits ? { height: v.rows, overflow: 'hidden' as const } : {})}>
546      <el.Box flexDirection="column" flexShrink={0}>{drawn[0]}</el.Box>
547      <el.Box flexShrink={0}><el.Text dimColor>{SETUP_PANE_KEYS}</el.Text></el.Box>
548      <el.Box flexDirection="row" columnGap={4} flexShrink={1} overflow="hidden">
549        <el.Box flexDirection="column" flexShrink={0}>{buttons}</el.Box>
550        <el.Box flexDirection="column" flexGrow={1} overflow="hidden">
551          <el.Box flexDirection="column" flexShrink={0}>{drawn.slice(1, -1)}</el.Box>
552        </el.Box>
553      </el.Box>
554    </el.Box>
555  )
556}
557
558const drawSetup = ($: EngineInterface, el: ReturnType<EngineInterface['ui']['resolve']>, base: Style, options: PluginOptions, found: NonNullable<ReturnType<typeof findSetup>>, columns: number): RenderElement[] => {
559  const key = setupSteps(PRESET_NAMES)[found.at]!.key
560  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>
561  const sample = (style: Style, value: string, id: string): RenderElement[] => {
562    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>]
563    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>]
564    if (key === 'toolOutput') return toolOutputSample(el, style, value, id, columns)
565    if (key === 'diffStyle') return diffSample(el, style, id, columns)
566    if (key === 'copyButtonStyle') return copySample(el, style, value, id, columns)
567    if (key === 'clock') return clockSample(el, style, value, id, columns)
568    return []
569  }
570  const picks = found.parts.options.map(({ value, text }, i) => {
571    const style = key === 'theme' ? { ...base, theme: resolveStyle({ ...options, theme: value }).theme } : { ...base, [key]: value }
572    return <el.Box key={`o${i}`} flexDirection="column">{md(style, text, 'm')}{sample(style, value, 'x')}</el.Box>
573  })
574  return [...(found.before ? [md(base, found.before, 'before')] : []), md(base, found.parts.head, 'head'), ...picks, md(base, found.parts.tail, 'tail')]
575}
576
577const hintsFor = (style: Style, latex: LatexSession, nth: number): string[] => [
578  ...(style.diagramHints ? [HINT, FIGURE_HINT, ...(latex.ready && !latex.stopped ? [LATEX_HINT] : [])] : []),
579  ...(style.issueHint && nth % 10 === 0 ? [ISSUE_HINT] : []),
580]
581
582const localeOf = async ($: EngineInterface, asked?: string): Promise<string> => asked ?? (await $.env.get('LC_ALL').catch(() => undefined)) ?? (await $.env.get('LANG').catch(() => undefined)) ?? ''
583
584export const register: Register = (on, options) => {
585  on('engine.create', async (_$, e, next) => ({ ...(await next(e)), prismantis: { markdown: async () => undefined } }))
586  if (options.enabled === false) return
587  const firstTheme = pickTheme(options.theme)
588  const style = resolveStyle({ ...options, theme: firstTheme })
589  const parsed = new Map<string, ReturnType<typeof parse>>()
590  const parseCached = (text: string, cache = parsed, limit?: number) => remember(cache, text, () => parse(text, { numbers: style.highlightNumbers, paths: style.highlightPaths }), limit)
591  const shared = new Map<string, ReturnType<typeof parse>>()
592  let terminal: Terminal | null = null
593  const fit = (viewport?: { isFullscreen?: boolean }): Style => (terminal === 'apple-terminal' && viewport?.isFullscreen ? { ...style, shape: 'inverse' } : style)
594  let prompts = 0
595  const latex: LatexSession = { style, color: ratexColor(style.theme.diagramText ?? style.theme.codeText ?? '#808080'), pending: new Set(), wanted: new Set(), batch: [], queue: Promise.resolve() }
596  const picked: Picked = { theme: firstTheme, options, latex }
597  const probes: Probes = {}
598  const forSurface = (base: Style, surface: RenderSurface, links: LinkReach): Style => {
599    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 }
600    return surface === 'mobile' && drawn.copyButtonStyle === 'hover' ? { ...drawn, copyButtonStyle: 'inline' } : drawn
601  }
602  const fullWidth = (text: string) => (style.reorder && hasRtl(text) ? { width: '100%' as const } : {})
603
604  const quiet = style.toolOutput === 'quiet'
605  const shellCommands = new Map<string, string>()
606  const noteCommand = (id: string | undefined, tool: string, input: unknown) => {
607    const command = tool === 'Bash' && input !== null && typeof input === 'object' ? (input as { command?: unknown }).command : undefined
608    if (!id || typeof command !== 'string') return
609    shellCommands.delete(id)
610    shellCommands.set(id, command)
611    if (shellCommands.size > 500) shellCommands.delete(shellCommands.keys().next().value!)
612  }
613  let firstEdit: string | undefined
614  if (options.toolRows !== false) {
615    on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
616      await locate($, style)
617      for (const call of e.props.calls) noteCommand(call.tool_use_id, call.tool, call.input)
618      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)
619      if (e.props.isExpanded) {
620        for (const call of e.props.calls) if (call.tool_use_id) rememberCall(expandedCalls, call.tool_use_id, 500)
621        return next(e)
622      }
623      return renderToolGroup($.ui.resolve(e), forSurface(fit(e.viewport), e.surface, await linkReach($, probes, style)), e.props.calls, e.props.isActive, e.viewport?.columns)
624    })
625    on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
626      await locate($, style)
627      noteCommand(e.props.tool_use_id, e.props.tool, e.props.input)
628      if (quiet && isReadOnlyCall(e.props.tool, e.props.input)) rememberCall(readOnlyCalls, e.props.tool_use_id)
629      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)
630      const shell = e.props.tool === 'Bash' || e.props.tool === 'PowerShell'
631      return shell && typeof e.props.output !== 'string' ? renderExpandedShell($.ui.resolve(e), fit(e.viewport), e.props) : next(e)
632    })
633    on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
634      const cards = (): Style => ({ ...fit(e.viewport), pressPreview: e.surface === 'terminal' })
635      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)
636      const edits = e.props.tool === 'Bash' && !e.props.isErrored ? bashEdits(e.props.output) : undefined
637      if (edits) {
638        await locate($, style)
639        const el = $.ui.resolve(e)
640        const output = withoutBashEdits(e.props.output)
641        const above = !hasShellOutput(output) ? null : quiet ? renderShellResult(el, fit(e.viewport), output) : await next({ ...e, props: { ...e.props, output } })
642        firstEdit ??= e.props.tool_use_id
643        const notes = editNotes(edits, firstEdit === e.props.tool_use_id, shellCommands.get(e.props.tool_use_id))
644        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)
645        return above === null ? drawn : <el.Box flexDirection="column">{above}{drawn}</el.Box>
646      }
647      if (!quiet) return next(e)
648      await locate($, style)
649      const el = $.ui.resolve(e)
650      const shell = e.props.tool === 'Bash' || e.props.tool === 'PowerShell'
651      const out = (e.props.output ?? {}) as Record<string, unknown>
652      if (shell && (out.backgroundTaskId || out.isImage || out.interrupted)) return next(e)
653      if (e.props.isErrored) return renderFailure(el, fit(e.viewport), e.props.output) ?? next(e)
654      if (readOnlyCalls.has(e.props.tool_use_id)) return <el.Box />
655      return shell ? renderShellResult(el, fit(e.viewport), e.props.output) : next(e)
656    })
657  }
658
659  on('session.start', async ($, e, next) => {
660    terminal = await probe($, style, probes)
661    void latexEngine($, latex)
662    const started = await next(e)
663    await $.command
664      .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]' })
665      .catch(() => undefined)
666    return started
667  })
668
669  on('command.run', { command: 'prismantis' }, async ($, e) => {
670    const [first, second, third] = e.args.trim().split(/\s+/)
671    const [sub, name] = THEME_ARGS.includes(first ?? '') ? ['theme', first] : [first, second]
672    if (sub === 'demo') return { text: showcaseText(PRESET_NAMES) + languageShowcase(await localeOf($, name)) }
673    if (sub === 'setup') return { text: await setup($, picked, e.origin, name, third) }
674    if (sub === 'copy') {
675      const reply = (await $.session.messages()).findLast(m => m.role === 'assistant' && m.text.trim())
676      if (!reply) return { text: 'Nothing to copy yet.' }
677      const code = name === 'code' ? nestedBlocks(parseCached(reply.text)).findLast(b => b.kind === 'code') : undefined
678      if (name === 'code' && code?.kind !== 'code') return { text: 'The last reply has no code block.' }
679      const result = await $.ui.copy({ text: code?.kind === 'code' ? code.lines.join('\n') : reply.text })
680      return { text: result.isCopied ? `Copied the last ${code ? 'code block' : 'reply'}.` : `Copy failed: ${result.reason}` }
681    }
682    if (sub === 'demo-rtl') {
683      terminal = await probe($, style, probes)
684      return { text: rtlShowcaseText() }
685    }
686    if (sub !== 'theme') return { text: helpText(PRESET_NAMES) }
687    if (!name) return { text: options.theme === 'random' ? `current: ${picked.theme} (random)\nkeep it: /prismantis theme ${picked.theme}` : `current: ${picked.theme}` }
688    if (!THEME_ARGS.includes(name)) return { text: `Unknown theme "${name}". Themes: ${PRESET_NAMES.join(', ')}, random` }
689    return { text: await setTheme($, picked, name) }
690  })
691
692  on('ui.render', { component: 'TurnDuration' }, async ($, e) => {
693    const at = style.clock === 'off' ? undefined : endedAt(await read($, turnEnds), e.props.durationMs, await firstDrawn($, e.requestId))
694    const time = at === undefined ? undefined : clockText(at, await $.clock.now(), style.clock)
695    return renderTurnDuration($.ui.resolve(e), style, e.props.word, e.props.durationMs, time)
696  })
697
698  on('turn.complete', async ($, e, next) => {
699    if (style.clock !== 'off' && e.agentId === undefined) {
700      const at = await $.clock.now()
701      await update($, turnEnds, list => withRecord(list, { durationMs: e.durationMs, at }))
702    }
703    return next(e)
704  })
705
706  on('prompt.submit', async ($, e, next) => {
707    if (style.clock !== 'off' && (e.origin.kind === 'composer' || e.origin.kind === 'bridge')) {
708      const at = await $.clock.now()
709      await update($, sent, list => withRecord(list, { text: promptKey(e.text), at }))
710    }
711    terminal = await probe($, style, probes)
712    if (!takesHint(e.origin)) return next(e)
713    if (style.diagramHints) void latexEngine($, latex)
714    const hints = hintsFor(style, latex, prompts++)
715    return hints.length ? next({ ...e, context: [...(e.context ?? []), ...hints] }) : next(e)
716  })
717
718  let landing = ''
719  const currentOf = (step: SetupStep): string => (step.key === 'theme' ? (options.theme === 'random' ? 'random' : picked.theme) : String(style[step.key]))
720
721  on('ui.focus', async ($, e, next) => {
722    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))
723    return next(e)
724  })
725
726  on('ui.scroll', { component: 'Pane', requestId: SETUP_PANE }, async ($, e, next) => {
727    if (e.origin.kind !== 'person' || e.pointer || Math.abs(e.by) !== 1) return next(e)
728    const steps = setupSteps(PRESET_NAMES)
729    const step = steps[Math.min(await read($, setupAt), steps.length - 1)]!
730    const choices = step.key === 'theme' ? THEME_ARGS : step.options
731    const focused = await read($, setupFocus)
732    const at = choices.indexOf(choices.includes(focused) ? focused : currentOf(step))
733    const target = choices[at + e.by]
734    if (target === undefined) return next(e)
735    await $.ui.focus({ requestId: SETUP_PANE, key: pickKey(step, target) }).catch(() => undefined)
736    return {}
737  })
738
739  on('ui.render', { component: 'Pane', requestId: SETUP_PANE }, async ($, e) => {
740    const steps = setupSteps(PRESET_NAMES)
741    const at = Math.min(await read($, setupAt), steps.length - 1)
742    const step = steps[at]!
743    const land = await read($, setupLand)
744    if (land !== landing) {
745      landing = land
746      if (land) landSetupFocus($, land)
747    }
748    const base = { ...forSurface(fit(e.viewport), e.surface, await linkReach($, probes, style)), copyButtons: false, pathLinks: false }
749    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) }
750    return setupKeyboardPane($, view, await read($, setupFocus), picked.theme)
751  })
752
753  on('ui.render', { component: 'InfoNotice' }, async (_$, e, next) =>
754    mirrored(style) && hasRtl(e.props.text) && opensLatin(e.props.text) ? next({ ...e, props: { ...e.props, text: ROW_MARK_TEXT + e.props.text } }) : next(e))
755
756  on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
757    if (e.props.isErrored) return next(e)
758    if (e.props.text.includes('\u001b')) return next(e)
759    const found = e.props.command === 'prismantis' ? findSetup(PRESET_NAMES, e.props.text) : undefined
760    if (found) {
761      const el = $.ui.resolve(e)
762      const base = { ...forSurface(fit(e.viewport), e.surface, await linkReach($, probes, style)), copyButtons: false, pathLinks: false }
763      return <el.Box flexDirection="column" rowGap={1}>{drawSetup($, el, base, options, found, columnsOf(e.viewport))}</el.Box>
764    }
765    const blocks = parseCached(e.props.text)
766    if (blocks.length === 0) return next(e)
767    const el = $.ui.resolve(e)
768    const { Box } = el
769    const reach = await linkReach($, probes, style)
770    const math = await mathOfBlocks($, latex, e.surface, blocks)
771    const pictures = await picturesOf($, style, probes, e.surface, blocks)
772    const open = await read($, unfolded)
773    const surfaceStyle = forSurface(fit(e.viewport), e.surface, reach)
774    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>
775  })
776
777  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
778    const kind = e.props.origin.kind
779    const own = kind === 'composer' || kind === 'bridge' || (kind === 'unclassified' && !e.props.from && !e.props.task)
780    if (!own) return next(e)
781    const at = style.clock === 'off' ? undefined : sentAt(await read($, sent), e.props.text, await firstDrawn($, e.requestId))
782    const time = at === undefined ? undefined : clockText(at, await $.clock.now(), style.clock)
783    if (style.promptStyle === 'off') return time === undefined ? next(e) : next({ ...e, props: { ...e.props, text: `[${time}] ${e.props.text}` } })
784    const el = $.ui.resolve(e)
785    const drawn = forSurface(fit(e.viewport), e.surface, await linkReach($, probes, style))
786    const columns = columnsOf(e.viewport)
787    const open = await read($, unfolded)
788    const paste: DrawPaste = (body, key) => {
789      const lines = body.split('\n')
790      const title = `pasted text · ${lines.length} lines`
791      const toggle = folder($, el, open)(`${e.requestId}:${key}`, lines.length, key, { label: title })
792      const opened = toggle?.folded === false
793      return (
794        <el.Box key={key} borderStyle="double" borderColor={drawn.theme.codeComment} paddingX={1} flexDirection="column" alignSelf="flex-start">
795          {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}
796          {opened ? drawMarkdown($, el, drawn, [{ kind: 'code', lang: pasteLang(body), lines, raw: body }], columns - 8, undefined, undefined, undefined, open) : null}
797        </el.Box>
798      )
799    }
800    return renderUserPrompt(el, drawn, e.props.text, columns, time, paste)
801  })
802
803  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
804    const blocks = parseCached(e.props.text)
805    if (blocks.length === 0) return next(e)
806    const el = $.ui.resolve(e)
807    const { Box, Text } = el
808    const narration = style.toolStyle === 'tree-bold' && blocks.length === 1 && blocks[0]!.kind === 'paragraph'
809    const reach = await linkReach($, probes, style)
810    const math = await mathOfBlocks($, latex, e.surface, blocks)
811    const pictures = await picturesOf($, style, probes, e.surface, blocks)
812    const surfaceStyle = forSurface(fit(e.viewport), e.surface, reach)
813    const open = await read($, unfolded)
814    const reply = blocks.length > 1 || hasRtl(e.props.text) ? e.props.text : undefined
815    const corner = reply !== undefined && markerRoom(surfaceStyle) > 0
816    return (
817      <Box key="msg" flexDirection="row">
818        <Box width={2} flexShrink={0}>
819          <Text color={style.theme.accent}>{e.props.isFirstOfReply ? '●' : ' '}</Text>
820        </Box>
821        <Box flexDirection="column" rowGap={1} flexGrow={1}>
822          {drawMarkdown($, el, narration ? { ...surfaceStyle, narration } : surfaceStyle, blocks, columnsOf(e.viewport), math, pictures, reply, open, { id: e.requestId, press: reach.marks })}
823        </Box>
824        {corner ? <Box width={MARK} flexShrink={0} /> : null}
825      </Box>
826    )
827  })
828
829  on('prismantis.markdown', async ($, e, next) => {
830    const blocks = parseCached(e.text, shared, 20)
831    if (blocks.length === 0) return next(e)
832    const el = $.ui.resolve({ surface: e.surface, component: 'AssistantMessage' })
833    const { Box } = el
834    const surfaceStyle = forSurface(style, e.surface, await linkReach($, probes, style))
835    return { value: <Box flexDirection="column" rowGap={1} {...fullWidth(e.text)}>{drawMarkdown($, el, { ...surfaceStyle, copyButtons: false }, blocks, Math.max(20, e.columns || 0))}</Box> }
836  })
837}
838
hooks/clock.ts 39 lines
1import 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}
39
hooks/latex.ts 136 lines
1import 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}
136
hooks/markdown.ts 458 lines
1export 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 }
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 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
73const NUMBER = /(?<![\w.#/-])(v?\d+(?:[.,:]\d+)*(?:%|ms|s|m|h|d|Gi|Mi|GB|MB|KB|x)?)(?![\w/])/g
74const PATH = /(?<![\w/.:])((?:~|\.{1,2})?\/[\w.@+-]+(?:\/[\w.@+-]*)*)/g
75
76const decorate = (raw: string, hl: Highlight): Inline[] => {
77  const text = raw.replace(ROLE_MARKUP, '$1')
78  if (!hl.numbers && !hl.paths) return [{ kind: 'text', text }]
79  const marks: { start: number; end: number; kind: 'number' | 'path' }[] = []
80  if (hl.paths) for (const m of text.matchAll(PATH)) marks.push({ start: m.index, end: m.index + m[0].length, kind: 'path' })
81  if (hl.numbers) {
82    for (const m of text.matchAll(NUMBER)) {
83      const start = m.index
84      if (!marks.some(p => start < p.end && start + m[0].length > p.start)) {
85        marks.push({ start, end: start + m[0].length, kind: 'number' })
86      }
87    }
88  }
89  marks.sort((a, b) => a.start - b.start)
90  const out: Inline[] = []
91  let at = 0
92  for (const m of marks) {
93    if (m.start > at) out.push({ kind: 'text', text: text.slice(at, m.start) })
94    out.push({ kind: m.kind, text: text.slice(m.start, m.end) })
95    at = m.end
96  }
97  if (at < text.length) out.push({ kind: 'text', text: text.slice(at) })
98  return out
99}
100
101export const parseInline = (text: string, hl: Highlight): Inline[] => {
102  if (text.length > MAX_INLINE) return [{ kind: 'text', text }]
103  const out: Inline[] = []
104  let at = 0
105  for (const m of text.matchAll(INLINE)) {
106    if (m.index > at) out.push(...decorate(text.slice(at, m.index), hl))
107    if (m[2] !== undefined) out.push({ kind: 'code', text: m[2] })
108    else if (m[3] !== undefined) out.push({ kind: 'link', text: m[3].replace(/^`([^`]+)`$/, '$1'), href: m[4]! })
109    else if (m[5] !== undefined || m[6] !== undefined) out.push({ kind: 'strong', children: parseInline(m[5] ?? m[6] ?? "", hl) })
110    else if (m[7] !== undefined) out.push({ kind: 'strike', children: parseInline(m[7], hl) })
111    else if (m[8] !== undefined || m[9] !== undefined) out.push({ kind: 'emphasis', children: parseInline(m[8] ?? m[9] ?? "", hl) })
112    else if (m[10] !== undefined) out.push({ kind: 'link', text: m[10], href: m[10] })
113    else if (m[11] !== undefined) out.push(...(isTex(m[11]) ? [{ kind: 'math' as const, text: texText(m[11]) }] : decorate(m[0], hl)))
114    else if (m[12] !== undefined) out.push({ kind: 'footnote', text: m[12] })
115    else if (m[14] !== undefined) out.push({ kind: 'image', text: m[13] || 'image', src: m[14] })
116    at = m.index + m[0].length
117  }
118  if (at < text.length) out.push(...decorate(text.slice(at), hl))
119  return out
120}
121
122const TEX: Record<string, string> = {
123  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: 'Ω',
124  cdot: '·', times: '×', div: '÷', pm: '±', mp: '∓', le: '≤', leq: '≤', ge: '≥', geq: '≥', neq: '≠', ne: '≠', approx: '≈', sim: '∼', equiv: '≡', propto: '∝', infty: '∞', to: '→', rightarrow: '→', leftarrow: '←', Rightarrow: '⇒', iff: '⇔', mapsto: '↦',
125  sum: 'Σ', prod: '∏', int: '∫', iint: '∬', oint: '∮', partial: '∂', nabla: '∇', in: '∈', notin: '∉', subset: '⊂', subseteq: '⊆', cup: '∪', cap: '∩', forall: '∀', exists: '∃', neg: '¬', land: '∧', lor: '∨', emptyset: '∅',
126  ldots: '…', cdots: '⋯', dots: '…', ell: 'ℓ', hbar: 'ℏ', lceil: '⌈', rceil: '⌉', lfloor: '⌊', rfloor: '⌋', langle: '⟨', rangle: '⟩', mid: '∣', quad: ' ', qquad: '  ',
127}
128const FUNCTIONS = new Set(['ln', 'log', 'exp', 'min', 'max', 'sin', 'cos', 'tan', 'lim', 'det', 'sup', 'inf', 'arg', 'deg', 'gcd', 'Pr'])
129const PLAIN = new Set(['text', 'mathrm', 'mathit', 'mathbf', 'textbf', 'texttt', 'mathsf', 'operatorname', 'boldsymbol'])
130const SPACES: Record<string, string> = { ',': ' ', ';': ' ', ':': ' ', ' ': ' ', '!': '', '\\': ' ', '{': '{', '}': '}', '%': '%', '$': '$', '&': '&', '#': '#', '_': '_' }
131const scriptMap = (from: string, to: string) => new Map(Array.from(from).map((c, i) => [c, Array.from(to)[i]!]))
132const SUP = scriptMap('0123456789+-−=()niabcdefghjklmoprstuvwxyzABDEGHIJKLMNOPRTUVW', '⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁻⁼⁽⁾ⁿⁱᵃᵇᶜᵈᵉᶠᵍʰʲᵏˡᵐᵒᵖʳˢᵗᵘᵛʷˣʸᶻᴬᴮᴰᴱᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾᴿᵀᵁⱽᵂ')
133const SUB = scriptMap('0123456789+-−=()aehijklmnoprstuvx', '₀₁₂₃₄₅₆₇₈₉₊₋₋₌₍₎ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓ')
134const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
135const FONTS: Record<string, string> = { mathbb: '𝔸𝔹ℂ𝔻𝔼𝔽𝔾ℍ𝕀𝕁𝕂𝕃𝕄ℕ𝕆ℙℚℝ𝕊𝕋𝕌𝕍𝕎𝕏𝕐ℤ', mathcal: '𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵' }
136const FN = '\u0000'
137
138const script = (text: string, map: Map<string, string>, mark: string) => {
139  const chars = Array.from(text)
140  const values = new Set(map.values())
141  if (chars.length > 0 && chars.every(c => map.has(c) || values.has(c))) return chars.map(c => map.get(c) ?? c).join('')
142  return mark + (chars.length === 1 ? text : `(${text})`)
143}
144const atomic = (text: string) => /^√?[\p{L}\p{N}.,]+$/u.test(text) || Array.from(text).length === 1
145
146const texUnicode = (tex: string): string => {
147  let i = 0
148  const name = () => {
149    const m = /^[A-Za-z]+/.exec(tex.slice(i))
150    if (m) return (i += m[0].length, m[0])
151    return tex[i++] ?? ''
152  }
153  const arg = (): string => {
154    while (tex[i] === ' ') i++
155    if (tex[i] === '{') {
156      let depth = 0
157      const start = ++i
158      for (; i < tex.length; i++) {
159        if (tex[i] === '\\') i++
160        else if (tex[i] === '{') depth++
161        else if (tex[i] === '}' && depth-- === 0) break
162      }
163      return tex.slice(start, i++)
164    }
165    if (tex[i] === '\\') return (i++, `\\${name()}`)
166    return tex[i++] ?? ''
167  }
168  const out: string[] = []
169  const prev = () => out.join('').slice(-1)
170  while (i < tex.length) {
171    const c = tex[i++]!
172    if (c === '\\') {
173      const cmd = name()
174      if (Object.hasOwn(SPACES, cmd)) out.push(SPACES[cmd]!)
175      else if (cmd === 'frac' || cmd === 'dfrac' || cmd === 'tfrac') {
176        const top = texUnicode(arg())
177        const bottom = texUnicode(arg())
178        const frac = `${atomic(top) ? top : `(${top})`}/${atomic(bottom) ? bottom : `(${bottom})`}`
179        const loose = /^$|[\s(=,[]$/.test(prev()) && /^(\s|$|\\right|[)\],])/.test(tex.slice(i))
180        out.push(loose ? frac : `(${frac})`)
181      } else if (cmd === 'sqrt') {
182        const inner = texUnicode(arg())
183        out.push(`√${atomic(inner) ? inner : `(${inner})`}`)
184      } else if (PLAIN.has(cmd)) out.push(cmd === 'text' ? arg() : texUnicode(arg()))
185      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(''))
186      else if (cmd === 'left' || cmd === 'right' || cmd === 'big' || cmd === 'Big' || cmd === 'bigg') {
187        const d = tex[i] === '\\' ? (i++, name()) : tex[i++] ?? ''
188        out.push(d === '.' ? '' : d === '{' || d === '}' ? d : Object.hasOwn(TEX, d) ? TEX[d]! : d)
189      } else if (FUNCTIONS.has(cmd)) out.push(cmd + FN)
190      else out.push(Object.hasOwn(TEX, cmd) ? TEX[cmd]! : `\\${cmd}`)
191    } else if (c === '^' || c === '_') out.push(script(texUnicode(arg()), c === '^' ? SUP : SUB, c))
192    else if (c === '{') {
193      i--
194      out.push(texUnicode(arg()))
195    } else if (c === '}' ) continue
196    else if (c === '~' || c === '&') out.push(' ')
197    else out.push(c)
198  }
199  return out.join('')
200}
201
202const isTex = (tex: string) => /[\\^_={}]/.test(tex) || /^[A-Za-z]$/.test(tex)
203
204export const texText = (tex: string): string =>
205  texUnicode(tex)
206    .replace(new RegExp(`${FN}(?=[\\p{L}\\p{N}])`, 'gu'), ' ')
207    .replaceAll(FN, '')
208    .replace(/\)\(/g, ')·(')
209    .replace(/ {2,}/g, ' ')
210    .trim()
211
212export const inlineText = (inline: Inline[]): string =>
213  inline.map(n => ('children' in n ? inlineText(n.children) : n.text)).join('')
214
215const mathAt = (lines: string[], start: number): { lines: string[]; end: number } | null => {
216  const trimmed = (n: number) => (lines[n] ?? '').trim()
217  const first = trimmed(start)
218  if (!first.startsWith('$$')) return null
219  const open = first.slice(2)
220  let end = start
221  if (!(open.length >= 2 && open.endsWith('$$'))) {
222    end = start + 1
223    while (end < lines.length && !trimmed(end).endsWith('$$')) {
224      if (trimmed(end) === '') return null
225      end++
226    }
227    if (end === lines.length) return null
228  }
229  const body = end === start ? [open.slice(0, -2)] : [open, ...lines.slice(start + 1, end), trimmed(end).slice(0, -2)]
230  const tex = body.filter(line => line.trim() !== '').map((line, i, all) => (i === 0 || i === all.length - 1 ? line.trim() : line))
231  return tex.length ? { lines: tex, end } : null
232}
233
234export const displayText = (inline: Inline[]): string =>
235  inline.map(n => (n.kind === 'link' && n.text !== n.href ? `${n.text} (${n.href})` : 'children' in n ? displayText(n.children) : n.text)).join('')
236
237export const isWebLink = (href: string): boolean => /^(https?:|mailto:)/i.test(href)
238
239const markOf = (n: number) => [...String(n)].map(d => SUPERSCRIPT[Number(d)]).join('')
240
241const numberNotes = (blocks: Block[], defs: Map<string, string>, hl: Highlight): Block[] => {
242  const order = new Map<string, number>()
243  const seen = (nodes: Inline[]): void => nodes.forEach(n => {
244    if (n.kind === 'footnote' && defs.has(n.text) && !order.has(n.text)) order.set(n.text, order.size + 1)
245    else if ('children' in n) seen(n.children)
246  })
247  const fix = (nodes: Inline[]): Inline[] => nodes.map(n =>
248    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}]` })
249    : 'children' in n ? { ...n, children: fix(n.children) } : n)
250  const mapInlines = (b: Block, f: (nodes: Inline[]) => Inline[]): Block =>
251    'inline' in b ? { ...b, inline: f(b.inline) }
252    : b.kind === 'list' ? { ...b, items: b.items.map(it => ({ ...it, inline: f(it.inline), ...(it.blocks ? { blocks: it.blocks.map(c => mapInlines(c, f)) } : {}) })) }
253    : b.kind === 'table' ? { ...b, header: b.header.map(f), rows: b.rows.map(r => r.map(f)) }
254    : b.kind === 'quote' || b.kind === 'alert' ? { ...b, blocks: b.blocks.map(c => mapInlines(c, f)) }
255    : b
256  blocks.forEach(b => mapInlines(b, nodes => (seen(nodes), nodes)))
257  for (const label of defs.keys()) if (!order.has(label)) order.set(label, order.size + 1)
258  const out = blocks.map(b => mapInlines(b, fix))
259  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)! }))
260  return defs.size ? [...out, { kind: 'notes', notes, raw: '' }] : out
261}
262
263export const CONTROL = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b\[[0-?]*[ -/]*[@-~]|\u001b[@-_]?|[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g
264
265export const parse = (raw: string, hl: Highlight): Block[] => {
266  const source = raw.replace(CONTROL, '')
267  const blocks = parseBlocks(source, hl)
268  return source.includes('[^') ? numberNotes(blocks, notesOf(source), hl) : blocks
269}
270
271const notesOf = (source: string, defs = new Map<string, string>(), depth = 0): Map<string, string> => {
272  const lines = source.replace(/\r\n?/g, '\n').split('\n')
273  let closer: RegExp | undefined
274  let last: string | undefined
275  for (let i = 0; i < lines.length; i++) {
276    const line = lines[i]!
277    if (!closer && depth < MAX_QUOTE_DEPTH && QUOTE.test(line)) {
278      const body: string[] = []
279      while (i < lines.length && QUOTE.test(lines[i]!)) body.push(lines[i++]!.replace(/^\s*>\s?/, ''))
280      i--
281      notesOf(body.join('\n'), defs, depth + 1)
282      last = undefined
283      continue
284    }
285    const run = FENCE.exec(line)?.[1]
286    const fenced = closer !== undefined || run !== undefined
287    if (closer?.test(line)) closer = undefined
288    else if (!closer && run) closer = closerOf(run)
289    const def = fenced ? null : NOTE_DEF.exec(line)
290    if (def) {
291      last = def[1]!
292      if (!defs.has(last)) defs.set(last, def[2] ?? '')
293    } else if (last !== undefined && /^\s{2,}\S/.test(line)) defs.set(last, `${defs.get(last)} ${line.trim()}`)
294    else last = undefined
295  }
296  return defs
297}
298
299const indentOf = (line: string): number => (line.match(/^\s*/)?.[0] ?? '').replace(/\t/g, '  ').length
300const closerOf = (run: string) => new RegExp(`^\\s*\\${run[0]}{${run.length},}\\s*$`)
301
302export const nestedBlocks = (blocks: Block[]): Block[] =>
303  blocks.flatMap(b => [b, ...nestedBlocks(b.kind === 'list' ? b.items.flatMap(it => it.blocks ?? []) : b.kind === 'quote' || b.kind === 'alert' ? b.blocks : [])])
304
305const tableRows = (lines: string[], width: number, hl: Highlight): Inline[][][] => {
306  const end = lines.findIndex(l => !l.includes('|') || l.trim() === '')
307  return lines.slice(0, end < 0 ? lines.length : end).map(l => {
308    const cells = splitRow(l)
309    return Array.from({ length: width }, (_, c) => parseInline(cells[c] ?? '', hl))
310  })
311}
312
313const parseBlocks = (source: string, hl: Highlight, depth = 0): Block[] => {
314  const lines = source.replace(/\r\n?/g, '\n').split('\n')
315  const at = (n: number) => lines[n] ?? ''
316  const blocks: Block[] = []
317  const add = (block: Draft, from: number, to: number) => blocks.push({ ...block, raw: lines.slice(from, to).join('\n') } as Block)
318  let paraStart = 0
319  let para: string[] = []
320
321  const flush = (end: number) => {
322    if (para.length) add({ kind: 'paragraph', inline: parseInline(para.join(' '), hl) }, paraStart, end)
323    para = []
324  }
325
326  for (let i = 0; i < lines.length; i++) {
327    const line = at(i)
328    const fence = FENCE.exec(line)
329    if (fence) {
330      flush(i)
331      const start = i
332      const run = fence[1] ?? '```'
333      const closer = closerOf(run)
334      const body: string[] = []
335      i++
336      while (i < lines.length && !closer.test(at(i))) body.push(at(i++))
337      add({ kind: 'code', lang: fence[2] ?? '', lines: body, ...(i < lines.length ? {} : { isOpen: true as const }) }, start, i + 1)
338      continue
339    }
340    const math = mathAt(lines, i)
341    if (math) {
342      flush(i)
343      add({ kind: 'code', lang: 'math', lines: math.lines }, i, math.end + 1)
344      i = math.end
345      continue
346    }
347    if (line.trim() === '') {
348      flush(i)
349      continue
350    }
351    if (NOTE_DEF.test(line)) {
352      flush(i)
353      while (/^\s{2,}\S/.test(at(i + 1))) i++
354      continue
355    }
356    if (TAG_LINE.test(line)) {
357      flush(i)
358      add({ kind: 'paragraph', inline: [{ kind: 'dim', text: line.trim() }] }, i, i + 1)
359      continue
360    }
361    const heading = /^(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/.exec(line)
362    if (heading) {
363      flush(i)
364      add({ kind: 'heading', level: (heading[1] ?? '#').length, inline: parseInline(heading[2] ?? '', hl) }, i, i + 1)
365      continue
366    }
367    if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
368      flush(i)
369      add({ kind: 'rule' }, i, i + 1)
370      continue
371    }
372    if (line.includes('|') && i + 1 < lines.length && TABLE_SEP.test(at(i + 1))) {
373      flush(i)
374      const start = i
375      const header = splitRow(line)
376      const align = splitRow(at(i + 1)).map(c =>
377        c.startsWith(':') && c.endsWith(':') ? 'center' : c.endsWith(':') ? 'right' : 'left',
378      )
379      const rows = tableRows(lines.slice(i + 2), header.length, hl)
380      i += 2 + rows.length
381      add({ kind: 'table', header: header.map(c => parseInline(c, { numbers: false, paths: false })), align, rows }, start, i)
382      i--
383      continue
384    }
385    if (depth < MAX_QUOTE_DEPTH && QUOTE.test(line)) {
386      flush(i)
387      const start = i
388      const body: string[] = []
389      while (i < lines.length && QUOTE.test(at(i))) body.push(at(i++).replace(/^\s*>\s?/, ''))
390      const alert = ALERT.exec(body[0] ?? '')
391      const inner = (rows: string[]) => parseBlocks(rows.join('\n'), hl, depth + 1)
392      if (alert) add({ kind: 'alert', level: alert[1]!.toLowerCase() as AlertLevel, blocks: inner([alert[2]!, ...body.slice(1)]) }, start, i)
393      else {
394        const quoted = inner(body)
395        if (quoted.length) add({ kind: 'quote', blocks: quoted }, start, i)
396      }
397      i--
398      continue
399    }
400    const item = LIST_ITEM.exec(line)
401    if (item) {
402      flush(i)
403      const start = i
404      const ordered = /\d/.test(item[2] ?? '')
405      const items: ListItem[] = []
406      const contentIndent: number[] = []
407      while (i < lines.length) {
408        const it = LIST_ITEM.exec(at(i))
409        if (it) {
410          const lead = indentOf(it[1] ?? '')
411          contentIndent.push(lead + (it[2] ?? '').length + 1)
412          const task = /^\[([ xX])\]\s+(.*)$/.exec(it[3] ?? '')
413          items.push({ marker: it[2] ?? '-', depth: Math.floor(lead / 2), ...(task ? { task: task[1] !== ' ' } : {}), inline: parseInline(task ? task[2]! : it[3] ?? '', hl) })
414        } else if (/^\s{2,}\S/.test(at(i)) && items.length) {
415          const indent = indentOf(at(i))
416          let owner = items.length - 1
417          while (owner > 0 && contentIndent[owner]! > indent) owner--
418          const target = items[owner]!
419          const fence = FENCE.exec(at(i))
420          const last = target.blocks?.at(-1)
421          if (fence) {
422            const from = i
423            const run = fence[1] ?? '```'
424            const closer = closerOf(run)
425            const strip = new RegExp(`^ {0,${indent}}`)
426            const body: string[] = []
427            i++
428            while (i < lines.length && !closer.test(at(i)) && (at(i).trim() === '' || indentOf(at(i)) >= indent)) body.push(at(i++).replace(strip, ''))
429            const isOpen = i === lines.length
430            if (!isOpen && !closer.test(at(i))) {
431              while (body.at(-1)?.trim() === '') body.pop()
432              i--
433            }
434            target.blocks = [...(target.blocks ?? []), { kind: 'code', lang: fence[2] ?? '', lines: body, ...(isOpen ? { isOpen: true as const } : {}), raw: lines.slice(from, i + 1).join('\n') }]
435          } else if (last?.kind === 'paragraph') {
436            last.inline = [...last.inline, { kind: 'text', text: ' ' }, ...parseInline(at(i).trim(), hl)]
437            last.raw += `\n${at(i)}`
438          } else if (last) {
439            target.blocks!.push({ kind: 'paragraph', inline: parseInline(at(i).trim(), hl), raw: at(i) })
440          } else {
441            target.inline = [...target.inline, { kind: 'text', text: ' ' }, ...parseInline(at(i).trim(), hl)]
442          }
443        } else {
444          break
445        }
446        i++
447      }
448      add({ kind: 'list', ordered, items }, start, i)
449      i--
450      continue
451    }
452    if (!para.length) paraStart = i
453    para.push(line.trim())
454  }
455  flush(lines.length)
456  return blocks
457}
458
hooks/clipboard.ts 70 lines
1export 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  }
70
hooks/figure.tsx 381 lines
1import 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}
381
hooks/mermaid.tsx 337 lines
1import 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}
337
hooks/render.tsx 2503 lines
1import 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, texText } from './markdown'
7import type { Flow } from './rtl'
8import { LTR_BLANK, ROW_MARK, ROW_MARK_TEXT, WALL, codeVisual, commentTail, commentVisual, containsRtl, flow, hasRtl, listMarker, 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
18export const cells = (s: string): string[] => (/^[ -~]*$/.test(s) ? [...s] : graphemes(s).flatMap(g => (WIDE.test(g) ? [g, ''] : [g])))
19
20const ZERO = /^[\p{M}\p{Default_Ignorable_Code_Point}]+$/u
21
22export const width = (s: string): number =>
23  /^[ -~]*$/.test(s) ? s.length
24  : s.length === 1 ? (ZERO.test(s) ? 0 : WIDE.test(s) ? 2 : 1)
25  : graphemes(s).reduce((w, g) => (ZERO.test(g) ? w : w + (WIDE.test(g) ? 2 : 1)), 0)
26
27const wrapRanges = (text: string, w: number): [number, number][] => {
28  if (width(text) <= w) return [[0, text.length]]
29  const out: [number, number][] = []
30  let line: [number, number] | undefined
31  let used = 0
32  for (const word of text.matchAll(/\S+/g)) {
33    let start = word.index
34    const end = start + word[0].length
35    let size = width(word[0])
36    if (size > w) {
37      if (line) out.push(line)
38      line = undefined
39      let cut = start
40      let taken = 0
41      for (const g of graphemes(text.slice(start, end))) {
42        const step = width(g)
43        if (cut > start && taken + step > w) {
44          out.push([start, cut])
45          start = cut
46          size -= taken
47          taken = 0
48          if (size <= w) break
49        }
50        cut += g.length
51        taken += step
52      }
53    }
54    if (start === end) continue
55    const joined = line ? used + width(text.slice(line[1], start)) + size : Infinity
56    if (line && joined <= w) {
57      line = [line[0], end]
58      used = joined
59    } else {
60      if (line) out.push(line)
61      line = [start, end]
62      used = size
63    }
64  }
65  if (line) out.push(line)
66  return out.length ? out : [[0, 0]]
67}
68
69const sliceInline = (nodes: Inline[], from: number, to: number): Inline[] => {
70  const out: Inline[] = []
71  let at = 0
72  for (const n of nodes) {
73    const length = inlineText([n]).length
74    const a = Math.max(from - at, 0)
75    const b = Math.min(to - at, length)
76    at += length
77    if (a >= b) continue
78    if ('children' in n) out.push({ ...n, children: sliceInline(n.children, a, b) })
79    else out.push({ ...n, text: n.text.slice(a, b) })
80  }
81  return out
82}
83
84const hasLink = (nodes: Inline[]): boolean => nodes.some(n => n.kind === 'link' || ('children' in n && hasLink(n.children)))
85
86const headerRuns = (nodes: Inline[]): Inline[] =>
87  nodes.flatMap(n => (n.kind === 'footnote' ? [n] : 'children' in n ? headerRuns(n.children) : [{ kind: 'text' as const, text: n.text }]))
88    .reduce<Inline[]>((out, n) => {
89      const last = out[out.length - 1]
90      return n.kind === 'text' && last?.kind === 'text' ? [...out.slice(0, -1), { kind: 'text', text: last.text + n.text }] : [...out, n]
91    }, [])
92
93const HTTP_LINKS_FROM = [2, 1, 289]
94const EDITOR_LINKS_FROM = [2, 1, 294]
95const CLICKABLE_MARKS_FROM = [2, 1, 295]
96
97const releaseFrom = (from: readonly number[]) => (base?: string): boolean => {
98  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(base ?? '')
99  if (!m) return false
100  const version = [Number(m[1]), Number(m[2]), Number(m[3])]
101  const at = version.findIndex((n, i) => n !== from[i])
102  return at === -1 || version[at]! > from[at]!
103}
104
105export const takesHttpLinks = releaseFrom(HTTP_LINKS_FROM)
106
107export const takesEditorLinks = releaseFrom(EDITOR_LINKS_FROM)
108
109export const takesClickableMarks = releaseFrom(CLICKABLE_MARKS_FROM)
110
111export const fileRoot = (distro?: string): string => (distro ? `file://wsl.localhost/${encodeURIComponent(distro)}` : 'file://')
112
113export type TerminalEnv = Partial<Record<'FORCE_HYPERLINK' | 'TERM_PROGRAM' | 'TERM_PROGRAM_VERSION' | 'TERM' | 'WT_SESSION' | 'LC_TERMINAL' | 'VTE_VERSION' | 'TERMINAL_EMULATOR', string>>
114
115const HYPERLINK_TERMINALS = ['ghostty', 'Hyper', 'kitty', 'alacritty', 'iTerm.app', 'iTerm2', 'WarpTerminal']
116
117const versionOf = (value = ''): number[] => {
118  const short = /^(\d{1,2})(\d{2})$/.exec(value)
119  return short ? [0, Number(short[1])] : value.split('.').map(n => Number.parseInt(n, 10))
120}
121
122const atLeast = (value: string | undefined, major: number, minor: number): boolean => {
123  const [a = Number.NaN, b = Number.NaN] = versionOf(value)
124  return a > major || (a === major && b >= minor)
125}
126
127const programLinks = (program: string, version: string | undefined): boolean =>
128  HYPERLINK_TERMINALS.includes(program)
129  || (program === 'WezTerm' && atLeast(version, 20200620, 0))
130  || (program === 'vscode' && atLeast(version, 1, 72))
131  || (program === 'tmux' && atLeast(version, 3, 4))
132
133export const drawsHyperlinks = (env: TerminalEnv): boolean => {
134  if (env.FORCE_HYPERLINK) return Number.parseInt(env.FORCE_HYPERLINK, 10) !== 0
135  const term = env.TERM ?? ''
136  const vte = env.VTE_VERSION
137  return env.WT_SESSION !== undefined
138    || programLinks(env.TERM_PROGRAM ?? '', env.TERM_PROGRAM_VERSION)
139    || HYPERLINK_TERMINALS.includes(env.LC_TERMINAL ?? '')
140    || (vte !== undefined && vte !== '0.50.0' && atLeast(vte, 0, 50))
141    || term === 'alacritty' || term.includes('kitty')
142    || env.TERMINAL_EMULATOR === 'JetBrains-JediTerm'
143}
144
145type Reach = Pick<Style, 'httpLinks' | 'editorLinks' | 'fileLinks' | 'pathLinks' | 'cwd' | 'home'>
146
147const LAUNCHERS = new Set([
148  'app', 'command', 'tool', 'terminal', 'pkg', 'mpkg', 'mobileconfig', 'prefpane', 'workflow', 'action', 'fileloc', 'inetloc', 'webloc',
149  'exe', 'com', 'scr', 'pif', 'cpl', 'msi', 'msp', 'msu', 'msix', 'msixbundle', 'appx', 'appxbundle', 'appinstaller', 'application', 'appref-ms', 'vsix',
150  'bat', 'cmd', 'ps1', 'psc1', 'vbs', 'vbe', 'js', 'jse', 'wsf', 'wsh', 'wsc', 'hta', 'chm', 'msc', 'reg', 'xll', 'wsb', 'diagcab', 'ahk', 'au3',
151  'lnk', 'url', 'scf', 'settingcontent-ms',
152  'desktop', 'sh', 'bash', 'zsh', 'csh', 'ksh', 'run', 'appimage', 'deb', 'rpm', 'snap', 'flatpak', 'flatpakref',
153  'jar', 'jnlp', 'py', 'pyw', 'pyz', 'pyzw', 'pyc', 'pl', 'rb', 'rbw',
154])
155
156const unescaped = (text: string): string => text.replace(/%([0-9a-f]{2})/gi, (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)))
157
158const extensionOf = (name: string): string => /\.([^.]*)$/.exec(name.replace(/[. ]+$/, ''))?.[1] ?? ''
159
160const launches = (href: string): boolean => {
161  const path = unescaped(href.replace(/[?#].*$/, '')).toLowerCase().replace(/[/\\]+$/, '')
162  const name = path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1)
163  return /\.app[/\\]/.test(path) || name.split(/[:\u0000-\u001f]/).some(part => LAUNCHERS.has(extensionOf(part)))
164}
165
166const isHyperlink = (href: string, reach: Reach): boolean =>
167  (reach.httpLinks ? /^https?:/i : /^(https:|http:\/\/localhost(:\d+)?([/?#]|$))/i).test(href)
168  || (reach.editorLinks && /^vscode(-insiders)?:\/\/file\//i.test(href))
169  || (reach.fileLinks !== null && /^file:/i.test(href) && !launches(href))
170
171const plainLink = (text: string, href: string): string => {
172  const target = href.replace(/^mailto:/i, '')
173  return text === target || `http://${text}` === target ? target : `${text} (${target})`
174}
175
176const LINK_MAX = 2048
177
178const utf8Bytes = (cp: number): number => (cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4)
179
180const encodedLength = (href: string): number =>
181  [...href].reduce((length, ch) => {
182    const cp = ch.codePointAt(0)!
183    return length + (cp > 0x20 && cp < 0x7f ? 1 : 3 * utf8Bytes(cp))
184  }, 0)
185
186const fileHref = (root: string, href: string): string => {
187  const local = /^file:(?:\/\/(?:localhost)?)?(\/(?![a-z]:|\/)[^?#]*)(.*)$/i.exec(href)
188  return local && root !== 'file://' ? `${root}${local[1]}${local[2]}` : href
189}
190
191const absolutePath = (reach: Reach, path: string): string | undefined => {
192  const base = path.startsWith('~') ? reach.home : path.startsWith('.') ? reach.cwd : '/'
193  if (!base) return undefined
194  const parts: string[] = []
195  for (const part of `${slashes(base)}/${path.replace(/^~/, '').replace(/(?<=[^/.])\.+$/, '')}`.split('/')) {
196    if (part === '..') parts.pop()
197    else if (part !== '.' && part !== '') parts.push(part)
198  }
199  return `/${parts.join('/')}${path.endsWith('/') ? '/' : ''}`
200}
201
202const pathHref = (reach: Reach, path: string): string | undefined => {
203  const target = absolutePath(reach, path)
204  if (target === undefined || reach.fileLinks === null) return undefined
205  const href = `${reach.fileLinks}${encodeURI(target).replace(/[?#]/g, encodeURIComponent)}`
206  return href.length <= LINK_MAX && !launches(href) ? href : undefined
207}
208
209const toolHref = (reach: Reach, path: string): string | undefined => {
210  if (!reach.pathLinks || reach.fileLinks === null) return undefined
211  const forward = path.replace(/\\/g, '/')
212  if (/^[a-z]:\//i.test(forward)) return pathHref({ ...reach, fileLinks: 'file://' }, forward)
213  if (!forward.startsWith('//')) return pathHref(reach, /^[/~.]/.test(forward) ? forward : `./${forward}`)
214  const href = `file:${encodeURI(forward).replace(/[?#]/g, encodeURIComponent)}`
215  return href.length <= LINK_MAX && !launches(href) ? href : undefined
216}
217
218type LinkPiece = { text: string; path?: string }
219
220const pieceText = (pieces: LinkPiece[]): string => pieces.map(p => p.text).join('')
221
222const drawPieces = (el: ElementTable, style: Style, pieces: LinkPiece[]): string | (string | RenderElement)[] => {
223  const hrefs = pieces.map(p => (p.path === undefined ? undefined : toolHref(style, p.path)))
224  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)
225}
226
227const decoded = (text: string): string | undefined => {
228  try {
229    return decodeURIComponent(text)
230  } catch {
231    return undefined
232  }
233}
234
235const linkPath = (root: string, href: string): string | undefined => {
236  const local = root !== 'file://' && href.startsWith(`${root}/`) ? href.slice(root.length) : href.replace(/^file:(\/\/(localhost)?(?=\/))?/i, '')
237  return decoded(local.replace(/[?#].*$/, ''))
238}
239
240const labelPath = (reach: Reach, root: string, label: string): string | undefined => {
241  if (/^file:/i.test(label)) return linkPath(root, fileHref(root, label))
242  if (/^([a-z]:[\\/]|\\\\)/i.test(label)) return label.replace(/\\/g, '/').replace(/^(?=[a-z]:)/i, '/')
243  if (label.startsWith('/')) return label
244  return /^(~|\.{1,2})\//.test(label) ? absolutePath(reach, label) : undefined
245}
246
247const withoutSlash = (path: string | undefined): string | undefined => path?.replace(/(?<=.)\/+$/, '')
248
249const hidesFile = (reach: Reach, n: Extract<Inline, { kind: 'link' }>, href: string): boolean => {
250  const label = n.text.trim().replace(/[.,;:!?]+$/, '')
251  if (!/^file:/i.test(n.href) || label === n.href) return false
252  const root = reach.fileLinks ?? 'file://'
253  const shown = withoutSlash(labelPath(reach, root, label))
254  return shown === undefined || shown !== withoutSlash(linkPath(root, href))
255}
256
257const drawnLink = (n: Extract<Inline, { kind: 'link' }>, reach: Reach): Inline => {
258  const href = reach.fileLinks !== null && /^file:/i.test(n.href) ? fileHref(reach.fileLinks, n.href) : n.href
259  if (!isHyperlink(n.href, reach) || encodedLength(href) > LINK_MAX || hidesFile(reach, n, href)) return { kind: 'text', text: plainLink(n.text, n.href) }
260  return href === n.href ? n : { ...n, href }
261}
262
263const linksAsPath = (path: string): boolean => !path.startsWith('/') || /^\/[^/]+\/+[^/]/.test(path.replace(/\.+$/, ''))
264
265const drawnPath = (n: Extract<Inline, { kind: 'path' }>, reach: Reach): Inline => {
266  const href = reach.pathLinks && linksAsPath(n.text) ? pathHref(reach, n.text) : undefined
267  return href === undefined ? n : { ...n, href }
268}
269
270const hyperlinks = (nodes: Inline[], reach: Reach): Inline[] =>
271  nodes.map(node => {
272    const n: Inline = node.kind === 'image' && isWebLink(node.src) ? { kind: 'link', text: node.text, href: node.src } : node
273    if (n.kind === 'link') return drawnLink(n, reach)
274    if (n.kind === 'path') return drawnPath(n, reach)
275    return 'children' in n ? { ...n, children: hyperlinks(n.children, reach) } : n
276  })
277
278const hyperlinkBlock = (block: Block, reach: Reach): Block => {
279  const drawn = (nodes: Inline[]) => hyperlinks(nodes, reach)
280  switch (block.kind) {
281    case 'heading':
282    case 'paragraph':
283      return { ...block, inline: drawn(block.inline) }
284    case 'list':
285      return { ...block, items: block.items.map(item => ({ ...item, inline: drawn(item.inline) })) }
286    case 'table':
287      return { ...block, header: block.header.map(drawn), rows: block.rows.map(r => r.map(drawn)) }
288    case 'notes':
289      return { ...block, notes: block.notes.map(note => ({ ...note, inline: drawn(note.inline) })) }
290    default:
291      return block
292  }
293}
294
295const hyperlinked = new WeakMap<Block, Record<string, Block>>()
296
297const drawable = (block: Block, reach: Reach): Block => {
298  const cached = hyperlinked.get(block) ?? {}
299  hyperlinked.set(block, cached)
300  const key = `${+reach.httpLinks}${+reach.editorLinks}${reach.fileLinks ?? ''}${reach.pathLinks ? `\0${reach.home}\0${reach.cwd}` : ''}`
301  return (cached[key] ??= hyperlinkBlock(block, reach))
302}
303
304const mostLines = (text: string, w: number): number => (text.match(/\S+/g)?.length ?? 0) + Math.ceil(width(text) / w)
305
306const textRows = (text: string, w: number): number => (width(text) <= w ? 1 : mostLines(text, Math.max(1, w)))
307
308const heightOf = (blocks: Block[], w: number): number => blocks.reduce((sum, block, b) => sum + (b ? 1 : 0) + blockHeight(block, w), 0)
309
310const blockHeight = (block: Block, w: number): number => {
311  switch (block.kind) {
312    case 'heading':
313      return 2 * textRows(displayText(block.inline), w - 4) + 2
314    case 'paragraph':
315      return textRows(displayText(block.inline), w)
316    case 'list':
317      return block.items.reduce((sum, item) => {
318        const pad = item.depth * 2 + item.marker.length + 4
319        return sum + textRows(displayText(item.inline), w - pad) + (item.blocks ? heightOf(item.blocks, w - pad) + 1 : 0)
320      }, textRows(`${'━'.repeat(20)} ${block.items.length}/${block.items.length} done`, w))
321    case 'code':
322      return block.lines.reduce((sum, line) => sum + textRows(line, w - 8), 3)
323    case 'table': {
324      const { natural, words } = tableSize(block)
325      const widths = columnWidths(natural, w - 4, 3, words)
326      const tallest = (cells: Inline[][]) => Math.max(1, ...widths.map((cw, c) => textRows(displayText(cells[c] ?? []), cw)))
327      return block.rows.reduce((sum, row) => sum + 1 + tallest(row), 4 + tallest(block.header))
328    }
329    case 'quote':
330      return Math.max(1, heightOf(block.blocks, w - 2))
331    case 'alert':
332      return 3 + heightOf(block.blocks, w - 4)
333    case 'rule':
334      return 1
335    case 'notes':
336      return block.notes.reduce((sum, note) => sum + textRows(`${note.mark} ${displayText(note.inline)}`, w), 1)
337  }
338}
339
340const wrapInline = (nodes: Inline[], w: number): Inline[][] => {
341  const text = inlineText(nodes)
342  return width(text) <= w ? [nodes] : wrapRanges(text, w).map(([a, b]) => sliceInline(nodes, a, b))
343}
344
345export const mirrored = (style: Style) => style.shape === 'mirror'
346
347export const heldLtr = (style: Style) => (style.shape === 'engine' ? { dir: 'ltr' as const } : {})
348
349const flows = new Map<string, Flow | null>()
350const flowOf = (style: Style, nodes: Inline[], columns: number, mark = !(style.inside && mirrored(style))) =>
351  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
352
353const noteHover = (style: Style, note: number | undefined) =>
354  note === undefined || style.noteKey === undefined ? {} : { hover: { scope: `fn:${style.noteKey}:${note}`, inverse: true } }
355
356const renderInline = (el: ElementTable, style: Style, nodes: Inline[], keyBase: string): RenderElement[] => {
357  const { Text } = el
358  const t = style.theme
359  return nodes.map((n, i) => {
360    const key = `${keyBase}.${i}`
361    switch (n.kind) {
362      case 'text':
363        return <Text key={key}>{n.text}</Text>
364      case 'strong':
365        return <Text key={key} bold color={t.strong}>{renderInline(el, style, n.children, key)}</Text>
366      case 'emphasis':
367        return <Text key={key} italic color={t.emphasis}>{renderInline(el, style, n.children, key)}</Text>
368      case 'strike':
369        return <Text key={key} strikethrough dimColor>{renderInline(el, style, n.children, key)}</Text>
370      case 'code':
371        return <Text key={key} color={t.inlineCode}>{n.text}</Text>
372      case 'math':
373        return <Text key={key} italic color={t.emphasis}>{n.text}</Text>
374      case 'link':
375        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>
376      case 'image':
377        return <Text key={key} color={t.link}>{n.text}</Text>
378      case 'number':
379        return <Text key={key} color={t.number}>{n.text}</Text>
380      case 'path':
381        return <Text key={key} color={t.path}>{n.href === undefined ? n.text : <el.Link href={n.href} label={n.text} />}</Text>
382      case 'dim':
383        return n === ROW_MARK ? <Text key={key} color={t.rule}>{n.text}</Text> : <Text key={key} dimColor>{n.text}</Text>
384      case 'footnote':
385        return <Text key={key} color={t.accent} {...noteHover(style, n.note)}>{n.text}</Text>
386    }
387  })
388}
389
390const renderFlow = (el: ElementTable, style: Style, lines: Inline[][], key: string, props: TextLook = {}) => {
391  const { Text } = el
392  return lines.map((line, i) => <Text key={`${key}.${i}`} {...props}>{renderInline(el, style, line, `${key}.${i}`)}</Text>)
393}
394
395type Mark = { start: number; end: number; text: string; note: number }
396type TextLook = { italic?: boolean; color?: string; bold?: boolean; dimColor?: boolean; strikethrough?: boolean }
397
398const marksIn = (nodes: Inline[], at = 0): Mark[] => {
399  const out: Mark[] = []
400  for (const n of nodes) {
401    const length = inlineText([n]).length
402    if (n.kind === 'footnote' && n.note !== undefined) out.push({ start: at, end: at + length, text: n.text, note: n.note })
403    else if ('children' in n) out.push(...marksIn(n.children, at))
404    at += length
405  }
406  return out
407}
408
409const piecesOf = (text: string, a: number, b: number, columns: number, marks: Mark[]): (readonly [number, number])[] => {
410  if (width(text.slice(a, b)) <= columns) return [[a, b]]
411  const out: [number, number][] = []
412  let start = a
413  let at = a
414  let taken = 0
415  for (const g of graphemes(text.slice(a, b))) {
416    const step = width(g)
417    if (at > start && taken + step > columns) {
418      const cut = marks.find(m => m.start < at && at < m.end)?.start ?? at
419      if (cut > start) {
420        out.push([start, cut])
421        taken = width(text.slice(cut, at))
422        start = cut
423      }
424    }
425    at += g.length
426    taken += step
427  }
428  out.push([start, b])
429  return out
430}
431
432const 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 => {
433  const marks = tip ? marksIn(nodes).flatMap(m => {
434    const press = tip(m.note)
435    return press ? [{ ...m, press }] : []
436  }) : []
437  if (!marks.length) return null
438  const { Box, Text, Button } = el
439  const run = (a: number, b: number) => <Text key={`${key}.t${a}`} {...look}>{renderInline(el, style, sliceInline(nodes, a, b), `${key}.t${a}`)}</Text>
440  const text = inlineText(nodes)
441  const words = [...text.matchAll(/\s*\S+\s*/g)].flatMap(m => piecesOf(text, m.index, m.index + m[0].length, Math.max(1, columns), marks))
442  return (
443    <Box key={key} flexDirection="row" flexWrap="wrap" {...box}>
444      {words.map(([a, b]) => {
445        const inside = marks.filter(m => m.start >= a && m.end <= b)
446        if (!inside.length) return run(a, b)
447        const parts: RenderElement[] = []
448        let at = a
449        for (const m of inside) {
450          if (m.start > at) parts.push(run(at, m.start))
451          parts.push(
452            <Button key={`${key}.n${m.start}`} plain {...noteHover(style, m.note)} onPress={m.press}>
453              <Text color={style.theme.accent} bold={look.bold}>{m.text}</Text>
454            </Button>,
455          )
456          at = m.end
457        }
458        if (at < b) parts.push(run(at, b))
459        return <Box key={`${key}.w${a}`} flexDirection="row" flexShrink={0}>{parts}</Box>
460      })}
461    </Box>
462  )
463}
464
465export const PRISM_COLORS: Record<string, keyof Theme> = {
466  comment: 'codeComment', prolog: 'codeComment', doctype: 'codeComment', cdata: 'codeComment',
467  string: 'codeString', char: 'codeString', 'template-string': 'codeString', 'attr-value': 'codeString', url: 'codeString',
468  number: 'number', boolean: 'number', constant: 'number', symbol: 'number', inserted: 'number',
469  keyword: 'codeFlag', important: 'codeFlag', atrule: 'codeFlag', rule: 'codeFlag', deleted: 'codeFlag',
470  function: 'codeCommand', 'class-name': 'codeCommand', builtin: 'codeCommand', key: 'codeCommand', selector: 'codeCommand',
471  property: 'link', tag: 'link', 'attr-name': 'emphasis', variable: 'emphasis', regex: 'path',
472}
473
474type Segment = { text: string; color?: string; italic: boolean }
475
476const shownCode = (text: string, style: Style, room?: number, command = false): string => (style.reorder ? codeVisual(text, style.shape, room, width, command) : text)
477
478const flatten = (tokens: PrismToken[], style: Style, color?: string, italic = false): Segment[] =>
479  tokens.flatMap(token => {
480    if (typeof token === 'string') return [{ text: token, color, italic }]
481    const names = [token.type, ...(Array.isArray(token.alias) ? token.alias : token.alias ? [token.alias] : [])]
482    const slot = names.map(n => PRISM_COLORS[n]).find(Boolean)
483    const inner = Array.isArray(token.content) ? token.content : [token.type === 'comment' && typeof token.content === 'string' && style.reorder ? commentVisual(token.content, style.shape) : token.content]
484    return flatten(inner, style, slot ? style.theme[slot] : color, italic || token.type === 'comment')
485  })
486
487export const remember = <T,>(cache: Map<string, T>, key: string, make: () => T, limit = 200): T => {
488  const hit = cache.get(key)
489  if (hit !== undefined) {
490    cache.delete(key)
491    cache.set(key, hit)
492    return hit
493  }
494  const value = make()
495  cache.set(key, value)
496  if (cache.size > limit) cache.delete(cache.keys().next().value!)
497  return value
498}
499
500const highlighted = new WeakMap<Theme, Map<string, Segment[][]>>()
501
502const grammarFor = (lang: string) => {
503  const name = lang.toLowerCase()
504  const grammar = Object.hasOwn(languages, name) ? languages[name] : undefined
505  return grammar !== null && typeof grammar === 'object' ? grammar : undefined
506}
507
508const shownSegment = (seg: Segment, piece: string, style: Style, room?: number): Segment => ({ ...seg, text: seg.italic ? piece : shownCode(piece, style, room) })
509
510const segmentRows = (style: Style, lines: string[], lang: string, room?: number): Segment[][] | null => {
511  const grammar = grammarFor(lang)
512  if (!grammar) return null
513  const code = lines.join('\n')
514  const cache = highlighted.get(style.theme) ?? new Map<string, Segment[][]>()
515  highlighted.set(style.theme, cache)
516  return remember(cache, `${style.reorder ? style.shape : ''}\0${room ?? ''}\0${lang}\0${code}`, () => {
517    const out: Segment[][] = [[]]
518    for (const seg of flatten(tokenize(code, grammar), style)) {
519      seg.text.split('\n').forEach((piece, i) => {
520        if (i > 0) out.push([])
521        if (piece) out[out.length - 1]!.push(shownSegment(seg, piece, style, room))
522      })
523    }
524    return out
525  })
526}
527
528export const highlightBlock = ({ Text }: ElementTable, style: Style, lines: string[], lang: string, key: string, room?: number): RenderElement[] | null => {
529  const rows = segmentRows(style, lines, lang, room)
530  if (!rows) return null
531  return rows.map((row, r) => (
532    <Text key={`${key}.${r}`} color={style.theme.codeText}>
533      {row.length ? row.map((s, i) => <Text key={`${key}.${r}.${i}`} color={s.color} italic={s.italic}>{s.text}</Text>) : ' '}
534    </Text>
535  ))
536}
537
538const gutterOf = (lines: string[], numbered: boolean) => (numbered ? String(lines.length).length + 2 : 0)
539
540const isShellLang = (lang: string) => lang === '' || /^(sh|bash|zsh|shell|console|fish|powershell|ps1)$/i.test(lang)
541
542export const codeLine = (el: ElementTable, style: Style, line: string, lang: string, key: string, room?: number): RenderElement => {
543  const { Text } = el
544  const t = style.theme
545  const isShell = isShellLang(lang)
546  if (/[\u2500-\u257F]/.test(line)) return <Text key={key} color={t.codeText}>{line}</Text>
547  const comment = style.reorder ? commentTail(line, style.shape) : null
548  if (comment) {
549    return (
550      <Text key={key} color={t.codeText}>
551        {comment.head ? codeLine(el, style, comment.head, lang, `${key}.h`) : null}
552        <Text color={t.codeComment}>{comment.marker + comment.tail}</Text>
553      </Text>
554    )
555  }
556  if (!isShell) return <Text key={key} color={t.codeText}>{shownCode(line, style, room) || ' '}</Text>
557  if (/^\s*#/.test(line)) return <Text key={key} color={t.codeComment}>{line}</Text>
558  const parts = shownCode(line, style, room, true).split(/("[^"]*"|'[^']*'|\s+)/).filter(p => p !== '')
559  let seenCommand = false
560  return (
561    <Text key={key} color={t.codeText}>
562      {parts.map((p, i) => {
563        if (/^\s+$/.test(p)) return <Text key={`${key}.${i}`}>{p}</Text>
564        if (/^["']/.test(p)) return <Text key={`${key}.${i}`} color={t.codeString}>{p}</Text>
565        if (/^--?[\w-]/.test(p)) return <Text key={`${key}.${i}`} color={t.codeFlag}>{p}</Text>
566        if (!seenCommand && !/^[$>|&;]+$/.test(p)) {
567          seenCommand = true
568          return <Text key={`${key}.${i}`} color={t.codeCommand}>{p}</Text>
569        }
570        if (/^(\||&&|;|\|\|)$/.test(p)) seenCommand = false
571        return <Text key={`${key}.${i}`}>{p}</Text>
572      })}
573    </Text>
574  )
575}
576
577const longestWord = (text: string): number => Math.max(0, ...text.split(/\s+/).map(width))
578
579export const columnWidths = (natural: number[], available: number, gap: number, words: number[] = []): number[] => {
580  const room = Math.max(natural.length, available - gap * (natural.length - 1))
581  const total = natural.reduce((a, b) => a + b, 0)
582  if (total <= room) return natural
583  const minimum = natural.map((w, c) => Math.min(w, Math.max(1, words[c] ?? 1)))
584  const widths = natural.map(() => 0)
585  let open = natural.map((_, c) => c)
586  let left = room
587  for (let fixed = [-1]; fixed.length; ) {
588    const share = Math.floor(left / open.length)
589    const claim = (c: number) => (natural[c]! <= share ? natural[c]! : minimum[c]!)
590    const minimumsFit = open.reduce((a, c) => a + minimum[c]!, 0) <= left
591    const needed = open.reduce((a, c) => a + claim(c), 0)
592    fixed = open.filter(c => natural[c]! <= share)
593    if (minimumsFit && (!fixed.length || needed > left)) fixed = open.filter(c => minimum[c]! > share)
594    fixed.forEach(c => (widths[c] = claim(c), left -= widths[c]!))
595    open = open.filter(c => !fixed.includes(c))
596  }
597  open.forEach((c, i) => (widths[c] = Math.max(1, Math.floor(left / open.length) + (i < left % open.length ? 1 : 0))))
598  while (widths.reduce((a, b) => a + b, 0) > room) {
599    const widest = widths.indexOf(Math.max(...widths))
600    if (widths[widest]! <= 1) break
601    widths[widest]!--
602  }
603  return widths
604}
605
606const tableCells = (block: Extract<Block, { kind: 'table' }>) => [...block.header, ...block.rows.flat()]
607
608const mostlyRtl = (style: Style, lines: Inline[][]): boolean => lines.filter(line => flowOf(style, line, Infinity)?.base === 'R').length * 2 > lines.length
609
610const isRtlTable = (style: Style, block: Extract<Block, { kind: 'table' }>): boolean => mostlyRtl(style, tableCells(block).filter(cell => displayText(cell).trim() !== ''))
611
612const ART_WIDTH = 100
613
614const tableSize = (block: Extract<Block, { kind: 'table' }>) => {
615  const cells = [block.header, ...block.rows].map(r => block.header.map((_, c) => displayText(r[c] ?? [])))
616  const column = (measure: (s: string) => number) => block.header.map((_, c) => Math.max(...cells.map(r => measure(r[c]!))))
617  return { natural: column(width), words: column(longestWord) }
618}
619
620export const tableArt = (block: Extract<Block, { kind: 'table' }>): string => {
621  const cells = [block.header, ...block.rows].map(r => block.header.map((_, c) => displayText(r[c] ?? [])))
622  const { natural, words } = tableSize(block)
623  const widths = columnWidths(natural, ART_WIDTH - 4, 3, words)
624  const pad = (text: string, c: number, align: 'left' | 'right' | 'center') => {
625    const room = Math.max(0, widths[c]! - width(text))
626    const left = align === 'right' ? room : align === 'center' ? Math.floor(room / 2) : 0
627    return ' '.repeat(left) + text + ' '.repeat(room - left)
628  }
629  const line = (l: string, m: string, r: string) => l + widths.map(w => '─'.repeat(w + 2)).join(m) + r
630  const row = (r: string[], header: boolean) => {
631    const lines = r.map((text, c) => wrapRanges(text, widths[c]!).map(([a, b]) => text.slice(a, b)))
632    return Array.from({ length: Math.max(...lines.map(l => l.length)) }, (_, i) =>
633      `│ ${lines.map((l, c) => pad(l[i] ?? '', c, header ? 'center' : block.align[c] ?? 'left')).join(' │ ')} │`)
634  }
635  const art = [line('┌', '┬', '┐'), ...row(cells[0]!, true), ...cells.slice(1).flatMap(r => [line('├', '┼', '┤'), ...row(r, false)]), line('└', '┴', '┘')]
636  return ['```', ...art, '```'].join('\n')
637}
638
639const clip = ({ Box }: ElementTable, w: number, drawn: RenderElement, key?: string) => (
640  <Box key={key} flexDirection="column" minWidth={w}>
641    <Box height={0} flexGrow={1} overflow="hidden">
642      {drawn}
643    </Box>
644  </Box>
645)
646
647const tableEdges = (style: Style, block: Extract<Block, { kind: 'table' }>, rtl: boolean, mirror: boolean) => {
648  const held = !rtl && mirrored(style) && tableCells(block).some(containsRtl)
649  return {
650    opening: mirror ? ROW_MARK_TEXT : held ? LTR_BLANK : '',
651    wall: (text: string) => (mirror ? text.replace('│', WALL) : held ? text.replace(/ $/, LTR_BLANK) : text),
652    held,
653    marked: !mirror && !held,
654  }
655}
656
657const renderTable = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'table' }>, columns: number, key: string, rtl: boolean, tip?: Tip) => {
658  const { Box, Text } = el
659  const t = style.theme
660  const box = style.tableStyle === 'box'
661  const gap = box ? 0 : style.tableStyle === 'grid' ? 3 : 2
662  const { natural, words } = tableSize(block)
663  const widths = box ? columnWidths(natural, columns - 4, 3, words) : columnWidths(natural, columns, gap, words)
664  const order = natural.map((_, c) => c)
665  const mirror = rtl && mirrored(style)
666  const flip = rtl && !mirror
667  const { opening, wall, held, marked } = tableEdges(style, block, rtl, mirror)
668  if (flip) order.reverse()
669  const lead = (k: string) => (opening ? <Text key={`${k}.m`} color={t.rule}>{opening}</Text> : null)
670  const columnGap = held ? 0 : gap
671  const spacer = (k: string) => (held ? <Text key={k}>{LTR_BLANK + ' '.repeat(gap - 1)}</Text> : null)
672  const ruleChar = style.tableStyle === 'grid' ? '━' : '─'
673  const justify = (c: number) =>
674    block.align[c] === 'right' ? 'flex-end' : block.align[c] === 'center' ? 'center' : 'flex-start'
675
676  const rule = (k: string, heavy: boolean) => (
677    <Box key={k} flexDirection="row" columnGap={columnGap}>
678      {lead(k)}
679      {order.map((c, i) => [
680        i > 0 && spacer(`${k}.${c}g`),
681        <Text key={`${k}.${c}`} color={t.tableRule} dimColor={!heavy && !t.tableRule}>
682          {(heavy ? ruleChar : '─').repeat(widths[c]!)}
683        </Text>,
684      ])}
685    </Box>
686  )
687
688  const bar = (k: string, text: string, lines = 1) => (
689    <Text key={k} color={t.tableRule} dimColor={!t.tableRule}>{Array.from({ length: lines }, () => text).join('\n')}</Text>
690  )
691  const clipped = (lines: number) => (k: string, text: string) => clip(el, width(text), bar(`${k}.b`, text, lines), k)
692  const edge = (k: string, [left, fill, mid, right]: string) =>
693    bar(k, (mirror ? WALL : left) + order.map(c => fill!.repeat(widths[c]! + 2)).join(mid) + (mirror ? WALL : right))
694
695  const terminalRow = (cells: Inline[][], k: string, isHeader: boolean) => {
696    const parts: Inline[] = box ? [{ kind: 'dim', text: '│ ' }] : []
697    order.forEach((c, i) => {
698      if (i > 0) parts.push(box ? { kind: 'dim', text: ' │ ' } : { kind: 'text', text: ' '.repeat(gap) })
699      const cell = flowOf({ ...style, shape: 'visual' }, cells[c] ?? [], Infinity)
700      const content = cell ? cell.lines[0]! : (cells[c] ?? [])
701      const pad = Math.max(0, widths[c]! - width(inlineText(content)))
702      const side = cell?.base === 'R' && block.align[c] !== 'center' ? 'flex-end' : justify(c)
703      const before = side === 'flex-end' ? pad : side === 'center' ? Math.floor(pad / 2) : 0
704      parts.push({ kind: 'text', text: ' '.repeat(before) }, ...(isHeader ? [{ kind: 'strong' as const, children: content }] : content), { kind: 'text', text: ' '.repeat(pad - before) })
705    })
706    if (box) parts.push({ kind: 'dim', text: ' │' })
707    return <Text key={k}>{renderInline(el, style, terminalLine(parts), k)}</Text>
708  }
709
710  const row = (cells: Inline[][], k: string, isHeader: boolean, border: (k: string, text: string) => RenderElement = bar) => rtl && style.shape === 'inverse' ? terminalRow(cells, k, isHeader) : (
711    <Box key={k} flexDirection="row" columnGap={columnGap} alignItems="stretch">
712      {!box && lead(k)}
713      {box && border(`${k}.l`, wall('│ '))}
714      {order.map((c, i) => {
715        const w = widths[c]!
716        const cell = flowOf(style, cells[c] ?? [], Infinity, marked)
717        const content = cell ? cell.lines[0]! : (cells[c] ?? [])
718        const side = mirror ? (block.align[c] === 'center' ? 'center' : 'flex-start') : cell?.base === 'R' && block.align[c] !== 'center' ? 'flex-end' : justify(c)
719        const runs = isHeader ? headerRuns(content) : content
720        const cellBox = (
721          <Box key={`${k}.${c}`} width={w} flexShrink={0} justifyContent={side}>
722            {pressInline(el, style, runs, w, `${k}.${c}.p`, tip, isHeader ? { bold: true, color: t.tableHeader } : {}, { justifyContent: side })
723              ?? (isHeader
724                ? <Text bold color={t.tableHeader}>{runs.some(n => n.kind === 'footnote') ? renderInline(el, style, runs, `${k}.${c}`) : inlineText(runs)}</Text>
725                : mirror && inlineText(content).trim() === '' ? <Text>{' '.repeat(w)}</Text>
726                : <Text>{renderInline(el, style, content, `${k}.${c}`)}</Text>)}
727          </Box>
728        )
729        return [i > 0 && (box ? border(`${k}.${c}s`, wall(' │ ')) : spacer(`${k}.${c}g`)), cellBox]
730      })}
731      {box && border(`${k}.r`, wall(' │'))}
732    </Box>
733  )
734
735  const wrappedRow = (cells: Inline[][], k: string, isHeader: boolean) => {
736    if (!isHeader && cells.some(hasLink)) return [row(cells, k, isHeader, clipped(Math.max(1, ...widths.map((w, c) => mostLines(displayText(cells[c] ?? []), w)))))]
737    const wrapped = widths.map((w, c) => {
738      const content = cells[c] ?? []
739      if (natural[c]! <= w) return [content]
740      return wrapInline(isHeader ? headerRuns(content) : content, w)
741    })
742    return Array.from({ length: Math.max(...wrapped.map(l => l.length)) }, (_, i) =>
743      row(wrapped.map(l => l[i] ?? []), `${k}.${i}`, isHeader))
744  }
745
746  if (box) {
747    const lines: RenderElement[] = [edge(`${key}.t`, '┌─┬┐'), ...wrappedRow(block.header, `${key}.h`, true), edge(`${key}.hr`, '╞═╪╡')]
748    block.rows.forEach((r, i) => {
749      if (i > 0) lines.push(edge(`${key}.r${i}r`, '├─┼┤'))
750      lines.push(...wrappedRow(r, `${key}.r${i}`, false))
751    })
752    lines.push(edge(`${key}.b`, '└─┴┘'))
753    return <Box key={key} flexDirection="column" {...(flip ? { alignSelf: 'flex-end' as const } : {})}>{lines}</Box>
754  }
755
756  const body: RenderElement[] = [row(block.header, `${key}.h`, true), rule(`${key}.hr`, true)]
757  block.rows.forEach((r, i) => {
758    body.push(row(r, `${key}.r${i}`, false))
759    if (style.tableStyle !== 'minimal' && i < block.rows.length - 1) body.push(rule(`${key}.r${i}r`, false))
760  })
761  return <Box key={key} flexDirection="column" {...(flip ? { alignSelf: 'flex-end' as const } : {})}>{body}</Box>
762}
763
764const renderHeading = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'heading' }>, key: string) => {
765  const rtl = flowOf(style, block.inline, Infinity)
766  if (!rtl) return drawHeading(el, style, block, block.inline, key)
767  if (rtl.base === 'R' && mirrored(style) && style.headingStyle === 'banner' && block.level <= 2) return mirroredBanner(el, style, block.level, rtl.lines[0]!, key)
768  const heading = drawHeading(el, style, block, rtl.lines[0]!, key)
769  return rtl.base === 'R' && !mirrored(style) ? <el.Box key={key} alignSelf="flex-end">{heading}</el.Box> : heading
770}
771
772const mirroredBanner = (el: ElementTable, style: Style, level: number, inline: Inline[], key: string) => {
773  const { Box, Text } = el
774  const color = style.theme.heading
775  const text = <Text key={`${key}.h`} bold underline={level === 2} color={color}>{level === 1 ? `${WALL} ` : ''}{renderInline(el, style, inline, key)}{level === 1 ? ` ${WALL}` : ''}</Text>
776  if (level === 2) return text
777  const edge = (k: string) => <Text key={k} color={color}>{WALL + '━'.repeat(width(inlineText(inline)) + 2) + WALL}</Text>
778  return <Box key={key} flexDirection="column">{edge(`${key}.t`)}{text}{edge(`${key}.b`)}</Box>
779}
780
781const drawHeading = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'heading' }>, inline: Inline[], key: string) => {
782  const { Box, Text } = el
783  const t = style.theme
784  const color = block.level <= 2 ? t.heading : t.accent ?? t.heading
785  const label = inlineText(inline)
786  switch (style.headingStyle) {
787    case 'uppercase':
788      return <Text key={key} bold color={color}>{block.level === 1 ? label.toUpperCase() : label}</Text>
789    case 'underline':
790      return <Text key={key} bold underline={block.level <= 2} color={color}>{label}</Text>
791    case 'banner':
792      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>
793      return block.level === 2
794        ? <Box key={key} flexDirection="column" alignSelf="flex-start"><Text bold color={color}>{renderInline(el, style, inline, key)}</Text><Text color={color}>{'━'.repeat(width(label))}</Text></Box>
795        : <Text key={key} bold color={block.level === 3 ? color : t.strong}>{renderInline(el, style, inline, key)}</Text>
796    default:
797      return <Text key={key} bold color={color}>{renderInline(el, style, inline, key)}</Text>
798  }
799}
800
801const ALERT_COLOR = { note: 'blue', tip: 'green', important: 'magenta', warning: 'yellow', caution: 'red' } as const
802
803const prose = (style: Style) => (style.inside === 'quote' ? { italic: true, color: style.theme.quote } : {})
804
805const renderParagraph = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'paragraph' }>, columns: number, key: string, tip?: Tip) => {
806  const { Box, Text } = el
807  const rtl = flowOf(style, block.inline, columns)
808  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>
809  const inline = rtl ? rtl.lines[0]! : block.inline
810  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>
811}
812
813const leadInline = (blocks: Block[]): Inline[] => {
814  const first = blocks[0]
815  if (first?.kind === 'paragraph' || first?.kind === 'heading') return first.inline
816  if (first?.kind === 'list') return first.items[0]?.inline ?? []
817  return first?.kind === 'quote' || first?.kind === 'alert' ? leadInline(first.blocks) : []
818}
819
820const renderNested = (el: ElementTable, style: Style, blocks: Block[], columns: number, key: string, copy?: CopyButton, fold?: Fold, tip?: Tip) =>
821  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)
822
823const quoteBar = (el: ElementTable, text: string, color: string | undefined, lines: number) =>
824  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>)
825
826const renderQuote = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'quote' }>, columns: number, key: string, copy?: CopyButton, fold?: Fold, tip?: Tip) => {
827  const { Box } = el
828  const t = style.theme
829  const inner = columns - 2
830  const lines = heightOf(block.blocks, inner)
831  const body = <Box flexDirection="column" rowGap={1}>{renderNested(el, { ...style, inside: 'quote' }, block.blocks, inner, key, copy, fold, tip)}</Box>
832  if (!mirrored(style) && flowOf(style, leadInline(block.blocks), inner)?.base === 'R') {
833    return (
834      <Box key={key} flexDirection="row" justifyContent="flex-end" alignItems="stretch">
835        {body}
836        {quoteBar(el, ' │', t.accent, lines)}
837      </Box>
838    )
839  }
840  return (
841    <Box key={key} flexDirection="row" alignItems="stretch">
842      {quoteBar(el, mirrored(style) ? ROW_MARK_TEXT : '│ ', t.accent, lines)}
843      {body}
844    </Box>
845  )
846}
847
848const renderAlert = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'alert' }>, columns: number, key: string, copy?: CopyButton, fold?: Fold, tip?: Tip) => {
849  const { Box, Text } = el
850  const color = ALERT_COLOR[block.level]
851  const inner = columns - 4
852  const hebrew = flowOf(style, leadInline(block.blocks), inner)?.base === 'R'
853  const label = block.level[0]!.toUpperCase() + block.level.slice(1)
854  const body = block.blocks.length ? <Box flexDirection="column" rowGap={1}>{renderNested(el, { ...style, inside: 'alert' }, block.blocks, inner, key, copy, fold, tip)}</Box> : null
855  if (hebrew && mirrored(style)) {
856    const lines = 1 + (block.blocks.length ? 1 + heightOf(block.blocks, inner) : 0)
857    const edge = (k: string) => <Text key={k} color={color}>{WALL + '─'.repeat(inner + 2) + WALL}</Text>
858    return (
859      <Box key={key} flexDirection="column" alignSelf="flex-start">
860        {edge(`${key}.t`)}
861        <Box flexDirection="row" alignItems="stretch">
862          {quoteBar(el, ROW_MARK_TEXT, color, lines)}
863          <Box flexDirection="column" width={inner}>
864            <Text bold color={color}>{label}</Text>
865            {body}
866          </Box>
867          {quoteBar(el, ` ${WALL}`, color, lines)}
868        </Box>
869        {edge(`${key}.b`)}
870      </Box>
871    )
872  }
873  return (
874    <Box key={key} flexDirection="column" alignSelf={hebrew ? 'flex-end' : 'flex-start'} {...(hebrew ? { alignItems: 'flex-end' as const } : {})} borderStyle="round" borderColor={color} paddingX={1}>
875      <Text bold color={color}>{label}</Text>
876      {body}
877    </Box>
878  )
879}
880
881const listSide = (style: Style, block: Extract<Block, { kind: 'list' }>): 'R' | 'L' | undefined => {
882  if (!style.reorder || !block.items.some(item => containsRtl(item.inline))) return undefined
883  return mostlyRtl(style, block.items.map(item => item.inline)) ? 'R' : 'L'
884}
885
886const leftItem = (el: ElementTable, style: Style, depth: number, lead: string, color: string | undefined, inline: Inline[], room: number, k: string, look: TextLook, tip?: Tip) => {
887  const { Box, Text } = el
888  return (
889    <Box key={k} flexDirection="row" paddingLeft={depth * 2}>
890      <Text color={color}>{lead}</Text>
891      {pressInline(el, style, inline, room, `${k}.i`, tip, look) ?? <Text {...look}>{renderInline(el, style, inline, k)}</Text>}
892    </Box>
893  )
894}
895
896const leadSide = (style: Style, block: Block, room: number) => (block.kind === 'list' ? listSide(style, block) : flowOf(style, leadInline([block]), room)?.base)
897
898const heldItem = (el: ElementTable, style: Style, item: Extract<Block, { kind: 'list' }>['items'][number], glyph: string, color: string | undefined, room: number, k: string, look: TextLook) => {
899  const { Box, Text } = el
900  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
901  return (
902    <Box key={k} flexDirection="row" paddingLeft={item.depth * 2}>
903      <Text color={color}>{mirrored(style) ? glyph : `${glyph} `}</Text>
904      <Box flexDirection="column">{renderFlow(el, style, lines, k, look)}</Box>
905    </Box>
906  )
907}
908
909const 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) => {
910  const { Box, Text } = el
911  const rtl = flowOf(style, item.inline, room)
912  const right = side ? side === 'R' : rtl?.base === 'R'
913  const lines = rtl?.lines ?? [mirrored(style) ? [ROW_MARK, ...item.inline] : item.inline]
914  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)
915  return right && mirrored(style) ? (
916    <Box key={k} flexDirection="row">
917      <Text color={glyphColor}>{`${' '.repeat(item.depth * 2)}${glyph} `}</Text>
918      <Box flexDirection="column">{drawn()}</Box>
919    </Box>
920  ) : right ? (
921    <Box key={k} flexDirection="row" justifyContent="flex-end" paddingRight={item.depth * 2}>
922      <Box flexDirection="column" alignItems="flex-end">{drawn()}</Box>
923      <Text color={glyphColor}>{` ${listMarker(glyph, style.shape)}`}</Text>
924    </Box>
925  ) : rtl?.base === 'R' ? (
926    heldItem(el, style, item, glyph, glyphColor, room, k, look)
927  ) : (
928    leftItem(el, style, item.depth, `${glyph} `, glyphColor, rtl ? rtl.lines[0]! : item.inline, room, k, look, tip)
929  )
930}
931
932const TASK_GLYPHS = { checks: ['[ ]', '[✓]'], ticks: ['○', '✓'], box: ['□', '✓'], progress: ['○', '✓'] } as const
933
934const renderList = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'list' }>, columns: number, key: string, copy?: CopyButton, fold?: Fold, tip?: Tip) => {
935  const { Box, Text } = el
936  const t = style.theme
937  const tasks = block.items.filter(item => item.task !== undefined)
938  const done = tasks.filter(item => item.task).length
939  const filled = tasks.length ? Math.round((done / tasks.length) * 20) : 0
940  const strike = style.taskStyle === 'checks' || style.taskStyle === 'box'
941  const tick = style.taskStyle === 'ticks' || style.taskStyle === 'progress'
942  const side = listSide(style, block)
943  return (
944    <Box key={key} flexDirection="column">
945      {style.taskStyle === 'progress' && tasks.length > 0 && (
946        <Text>
947          <Text color={t.accent}>{'━'.repeat(filled)}</Text>
948          <Text color={t.bullet} dimColor>{'─'.repeat(20 - filled)}</Text>
949          <Text color={t.bullet}>{` ${done}/${tasks.length} done`}</Text>
950        </Text>
951      )}
952      {block.items.map((item, i) => {
953        const k = `${key}.${i}`
954        const glyph = item.task !== undefined ? TASK_GLYPHS[style.taskStyle][item.task ? 1 : 0] : /\d/.test(item.marker) ? item.marker : item.depth ? '◦' : '•'
955        const glyphColor = item.task && tick ? t.accent : t.bullet
956        const pad = item.depth * 2 + glyph.length + 1
957        const look = { ...(item.task === true ? { dimColor: true, strikethrough: strike } : {}), ...prose(style) }
958        const row = listRow(el, style, item, glyph, glyphColor, side, columns - pad, k, look, tip)
959        if (!item.blocks) return row
960        return (
961          <Box key={k} flexDirection="column">
962            {row}
963            <Box flexDirection="column" paddingLeft={pad}>{renderNested(el, style, item.blocks, columns - pad, k, copy, fold, tip)}</Box>
964          </Box>
965        )
966      })}
967    </Box>
968  )
969}
970
971export type CopyButton = (text: string | (() => string), key: string, label?: string, html?: () => string) => RenderElement | null
972export type Drawn = Map<number, { element?: RenderElement; art?: string; note?: string }>
973export type FoldLook = { label?: string; face?: (folded: boolean) => RenderElement }
974export type Fold = (id: string, hidden: number, key: string, look?: FoldLook) => { folded: boolean; element: RenderElement; faced: boolean; around?: (rows: RenderElement, hover: TextHoverProps) => RenderElement } | null
975export type Tip = (note: number) => (() => void) | undefined
976
977export const instanceKey = (id: string): string => {
978  let h = 5381
979  for (let i = 0; i < id.length; i++) h = (h * 33 + id.charCodeAt(i)) | 0
980  return (h >>> 0).toString(36)
981}
982
983export const noteTip = (blocks: Block[], toast: (text: string) => void): Tip | undefined => {
984  const notes = blocks.find(block => block.kind === 'notes')
985  if (notes?.kind !== 'notes') return undefined
986  const text = new Map(notes.notes.map(note => [note.note, `${note.mark} ${inlineText(note.inline)}`]))
987  return note => {
988    const line = text.get(note)
989    return line === undefined ? undefined : () => toast(line)
990  }
991}
992
993const NUMBER_AT = 10
994const NUMBER_MAX = 400
995const FOLD_AT = 30
996const FOLD_SHOW = 20
997
998const codeId = (lines: string[]): string => {
999  let h = 5381
1000  for (const line of lines) {
1001    for (let i = 0; i < line.length; i++) h = (h * 33 + line.charCodeAt(i)) | 0
1002    h = (h * 33 + 10) | 0
1003  }
1004  return `${lines.length}:${(h >>> 0).toString(36)}`
1005}
1006
1007const copySource = (style: Style, block: Block): string | undefined =>
1008  block.kind === 'code' ? block.lines.join('\n')
1009  : block.kind === 'table' ? block.raw
1010  : style.inside ? undefined
1011  : block.kind === 'list' ? block.raw
1012  : block.kind === 'quote' || block.kind === 'alert' ? block.raw.split('\n').map(line => line.replace(/^\s*>\s?/, '')).join('\n')
1013  : undefined
1014
1015export const drawMath = (el: ElementTable, style: Style, blocks: Block[], drawn: Drawn = new Map()): Drawn => {
1016  for (const [i, block] of blocks.entries()) {
1017    const tex = drawn.has(i) ? null : mathOf(block)
1018    const text = tex === null ? null : texText(tex)
1019    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> })
1020  }
1021  return drawn
1022}
1023
1024const opensWithCopy = (block: Block): boolean =>
1025  block.kind === 'quote' && (block.blocks[0]?.kind === 'code' || block.blocks[0]?.kind === 'table' || (block.blocks[0] !== undefined && opensWithCopy(block.blocks[0])))
1026
1027const holdsOnlyEmptyCode = (block: Block): boolean =>
1028  block.kind === 'quote' && block.blocks.length === 1 && ((block.blocks[0]!.kind === 'code' && block.blocks[0]!.lines.length === 0) || holdsOnlyEmptyCode(block.blocks[0]!))
1029
1030export const MARK = 2
1031
1032export const markerRoom = (style: Style): number => (style.copyButtons && style.copyButtonStyle === 'hover' ? MARK : 0)
1033
1034const codeLabel = (block: Extract<Block, { kind: 'code' }>): string => `── ${block.lang || 'code'}`
1035
1036type Float = { needs: number; marker: RenderElement; element: RenderElement }
1037
1038const buttonText = (button: RenderElement | null | undefined): string | undefined =>
1039  button?.type === 'Button' ? `[ ${button.props.label} ]` : button?.type === 'Text' ? (button.children ?? []).filter((c): c is string => typeof c === 'string').join('') : undefined
1040
1041const keyOf = (button: RenderElement): string => String(('props' in button ? (button.props as { key?: unknown } | undefined)?.key : undefined) ?? '')
1042
1043const markedRow = ({ Box }: ElementTable, key: string, element: RenderElement, float: Float, start: boolean) => (
1044  <Box key={key} flexDirection="column" {...(start ? { alignItems: 'flex-end' as const } : { alignSelf: 'flex-start' as const })}>
1045    <Box flexDirection="row" columnGap={1} minWidth={float.needs} {...(start ? { justifyContent: 'flex-end' as const } : {})}>
1046      {start ? float.marker : null}
1047      {element}
1048      {start ? null : float.marker}
1049      {float.element}
1050    </Box>
1051  </Box>
1052)
1053
1054export const renderBlocks = (el: ElementTable, style: Style, blocks: Block[], columns: number, drawn: Drawn = new Map(), copy?: CopyButton, fold?: Fold, tip?: Tip, png?: CopyButton): RenderElement[] => {
1055  const { Box, Text } = el
1056  const t = style.theme
1057  const hover = style.copyButtonStyle === 'hover'
1058  const reserved = (buttons: (RenderElement | null | undefined)[]): number =>
1059    buttons.reduce<number>((w, button) => {
1060      const shown = buttonText(button)
1061      return shown === undefined ? w : w + (w ? 1 : 0) + width(shown)
1062    }, 0)
1063  const fitted = (parts: (RenderElement | null | undefined)[]): RenderElement[] =>
1064    parts.reduce<RenderElement[]>((kept, part) => (part && (!kept.length || reserved([...kept, part]) <= columns) ? [...kept, part] : kept), [])
1065  const scopeOf = (button: RenderElement): string => `copy:${style.noteKey ?? ''}:${keyOf(button)}`
1066  const floating = (kept: RenderElement[], low = false, start = false): Float => {
1067    const scope = scopeOf(kept[0]!)
1068    return {
1069      needs: reserved(kept),
1070      marker: <Box flexShrink={0} alignSelf={low ? 'flex-end' : 'flex-start'} hover={{ scope }}><Text dimColor>⧉</Text></Box>,
1071      element: <Box position="absolute" {...(low ? { bottom: 0 } : { top: 0 })} {...(start ? { left: 0 } : { right: 0 })} display="none" hover={{ scope, display: 'flex' }}>{kept.flatMap((button, i) => (i ? [<Text key={`gap${i}`}> </Text>, button] : [button]))}</Box>,
1072    }
1073  }
1074  const shown = blocks.map(block => drawable(block, style))
1075  const rtlTables = shown.map(block => style.reorder && block.kind === 'table' && isRtlTable(style, block))
1076  const buttons = blocks.map((block, b) => {
1077    const text = hover && holdsOnlyEmptyCode(block) ? undefined : copySource(style, block)
1078    const isPlainCode = block.kind === 'code' && !drawn.get(b)?.element
1079    const art = drawn.get(b)?.art ?? (block.kind === 'table' ? () => tableArt(block) : undefined)
1080    const first = text === undefined || isPlainCode ? null : copy?.(text, `copy${b}`, block.kind === 'table' ? '⧉ md' : art === undefined ? undefined : '⧉ source')
1081    const second = first && art !== undefined ? copy?.(art, `art${b}`, '⧉ art') : null
1082    const html = first && block.kind === 'table' ? copy?.(() => tableText(block), `html${b}`, '⧉ html', () => tableHtml(block)) : null
1083    const image = second && art !== undefined ? png?.(art, `png${b}`, '▣ png') ?? null : null
1084    return { first, second, html, image }
1085  })
1086  const codeHead = (label: string, button: RenderElement | null) => {
1087    if (!hover || !button) return null
1088    const float = floating([button])
1089    return { ...float, minWidth: Math.min(columns, width(label) + 1 + float.needs) }
1090  }
1091  const room = (b: number) => (hover && buttons[b]!.first ? columns - MARK : columns)
1092  const beside = (b: number) => (!buttons[b]!.first ? columns : hover ? columns - MARK : columns - reserved([buttons[b]!.first]) - 2)
1093  const rendered = shown.map((block, b) => {
1094    const key = `b${b}`
1095    switch (block.kind) {
1096      case 'heading':
1097        return renderHeading(el, style, block, key)
1098      case 'paragraph':
1099        return drawn.get(b)?.element ?? renderParagraph(el, style, block, columns, key, tip)
1100      case 'quote':
1101        return renderQuote(el, style, block, beside(b), key, copy, fold, tip)
1102      case 'alert':
1103        return renderAlert(el, style, block, beside(b), key, copy, fold, tip)
1104      case 'rule':
1105        return <Text key={key} color={t.rule} dimColor={!t.rule}>{'─'.repeat(Math.max(8, Math.min(columns, 80)))}</Text>
1106      case 'code': {
1107        const done = drawn.get(b)?.element
1108        if (done) return done
1109        const note = drawn.get(b)?.note
1110        const lines = block.lines
1111        const toggle = lines.length > FOLD_AT ? fold?.(codeId(lines), lines.length - FOLD_SHOW, `fold${b}`) : null
1112        const shown = toggle?.folded ? FOLD_SHOW : lines.length
1113        const numbered = lines.length >= NUMBER_AT && lines.length <= NUMBER_MAX
1114        const room = columns - 2 - gutterOf(lines, numbered)
1115        const drawnRows = (isShellLang(block.lang) ? null : highlightBlock(el, style, lines, block.lang, key, room))?.slice(0, shown) ?? lines.slice(0, shown).map((line, i) => codeLine(el, style, line, block.lang, `${key}.${i}`, room))
1116        const rows = style.nativeCode ? [<el.Code key="code" source={lines.slice(0, shown).join('\n') || ' '} {...(block.lang ? { language: block.lang } : {})} {...(numbered ? { startLine: 1 } : {})} />]
1117          : style.shape === 'engine' ? drawnRows.map((row, i) => <Text key={`${key}.ltr${i}`} {...heldLtr(style)}>{row}</Text>) : drawnRows
1118        const gutter = String(lines.length).length
1119        const button = copy?.(lines.join('\n'), `copy${b}`) ?? null
1120        const label = codeLabel(block)
1121        const head = codeHead(label, button)
1122        return (
1123          <Box key={key} flexDirection="column" alignSelf="flex-start" minWidth={head?.minWidth}>
1124            {note ? <Text color={t.codeComment}>{note}</Text> : null}
1125            <Box flexDirection="row" justifyContent="space-between" columnGap={head ? 1 : 4}>
1126              <Text color={t.codeComment}>{label}</Text>
1127              {head ? head.marker : button}
1128              {head?.element}
1129            </Box>
1130            <Box flexDirection="column" paddingLeft={2}>
1131              {!numbered || style.nativeCode ? rows : rows.map((row, i) => row.type === 'Text' ? <Box key={`n${i}`} flexDirection="row"><Text color={t.codeComment} dimColor>{`${String(i + 1).padStart(gutter)}  `}</Text>{row}</Box> : row)}
1132              {toggle?.element ?? null}
1133            </Box>
1134          </Box>
1135        )
1136      }
1137      case 'list':
1138        return renderList(el, style, block, room(b), key, copy, fold, tip)
1139      case 'table':
1140        return renderTable(el, style, block, room(b), key, rtlTables[b]!, tip)
1141      case 'notes':
1142        return (
1143          <Box key={key} flexDirection="column">
1144            <Text dimColor>{'─'.repeat(Math.min(columns, 12))}</Text>
1145            {block.notes.map((note, i) => <Text key={`${key}.${i}`} dimColor {...noteHover(style, note.note)}>{note.mark} {renderInline(el, style, note.inline, `${key}.${i}`)}</Text>)}
1146          </Box>
1147        )
1148    }
1149  })
1150  const copied = rendered.map((element, b) => {
1151    const block = blocks[b]!
1152    const { first, second, html, image } = buttons[b]!
1153    if (!first) return element
1154    const { Box } = el
1155    const hebrew = style.reorder && hasRtl(block.raw)
1156    const rtl = hebrew && !mirrored(style)
1157    const mirror = hebrew && mirrored(style)
1158    if (hover) {
1159      const wide = rtl && (block.kind === 'list' || block.kind === 'quote' || block.kind === 'alert' || rtlTables[b])
1160      const start = !!wide && (!!rtlTables[b] || leadSide(style, block, room(b)) === 'R')
1161      return markedRow(el, `c${b}`, element, floating(fitted([first, second, html, image]), opensWithCopy(block), start), start)
1162    }
1163    const button = second ? (
1164      <el.Box key={`copies${b}`} flexDirection="row" columnGap={1}>
1165        {first}
1166        {second}
1167        {html}
1168        {image}
1169      </el.Box>
1170    ) : first
1171    return (block.kind === 'quote' || block.kind === 'alert') && !mirrored(style) ? (
1172      <Box key={`c${b}`} flexDirection="row" columnGap={2} {...(rtl ? { justifyContent: 'flex-end' as const } : {})}>
1173        {element}
1174        {opensWithCopy(block) ? <Box alignSelf="flex-end">{button}</Box> : button}
1175      </Box>
1176    ) : (
1177      <Box key={`c${b}`} flexDirection="column" {...(mirror ? { width: '100%' } : rtl && (block.kind === 'list' || rtlTables[b]) ? {} : { alignSelf: 'flex-start' as const })}>
1178        <Box justifyContent="flex-end">{button}</Box>
1179        {element}
1180      </Box>
1181    )
1182  })
1183  const isFigure = (b: number) => blocks[b]?.kind === 'table' || drawn.get(b)?.art !== undefined
1184  const out: RenderElement[] = []
1185  for (let b = 0; b < rendered.length; b++) {
1186    if (!isFigure(b) || !isFigure(b + 1)) {
1187      out.push(copied[b]!)
1188      continue
1189    }
1190    const start = b
1191    while (isFigure(b + 1)) b++
1192    out.push(
1193      <Box key={`row${start}`} flexDirection="row" flexWrap="wrap" columnGap={4} rowGap={1}>
1194        {copied.slice(start, b + 1).map((figure, i) => <Box key={`f${start + i}`} flexShrink={0}>{figure}</Box>)}
1195      </Box>,
1196    )
1197  }
1198  return out
1199}
1200
hooks/help.ts 442 lines
1import { 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
19Programs 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.
20
21Code-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**.
22
23## Commands
24
25| Command | Does |
26|---------|------|
27| \`/prismantis\` | This screen |
28| \`/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 |
29| \`/prismantis copy\` | Copy the last reply, or \`copy code\` for its last code block |
30| \`/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 |
31| \`/config\` | Edit any option |
32
33> [!NOTE]
34> ${themes.length} themes ship with it. \`mono\` uses no color, only bold and dim.
35
36### Pick a theme
37
38\`\`\`bash
39/prismantis theme nord
40/prismantis theme github-light
41/prismantis theme random
42\`\`\`
43
441. Dark: ${themes.filter(t => RANDOM_THEMES.includes(t)).join(', ')}
452. Light: ${themes.filter(t => /latte|light|dawn/.test(t)).join(', ')}
463. Plain
47   - mono
48
49> [!TIP]
50> Any color slot beats the theme. Set \`headingColor\` or \`numberColor\` to a hex value in \`/config\`.
51
52## Everything it draws
53
54### Copy tables
55
56Use \`⧉ 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.
57
58| Item | Quantity[^count] | Status |
59|:-----|---------:|:------:|
60| **Apples** | 3 | *Ready* |
61| Oranges | 5 | Pending |
62
63### Alerts
64
65> [!IMPORTANT]
66> After updating the plugin, open sessions need \`/reload\`.
67
68> [!WARNING]
69> Terminals that copy on select (Warp) can turn a click on a copy button into a selection. Use the keyboard shortcut.
70> Selecting a typeset formula copies blank cells. Its copy button copies the LaTeX.
71
72> [!CAUTION]
73> Claude Code refuses trees over 20000 nodes. A code block past about 500 highlighted lines falls back to plain text.
74
75### Task lists
76
77- [x] Parse the reply
78- [x] Draw it
79  - [x] Tables and code
80  - [ ] Diagrams on the desktop app
81- [ ] Ship the next release
82
83### Your prompts
84
85Scroll 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.
86
87### Tool rows
88
89Tool 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"\`.
90
91Each 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\`.
92
93A 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.
94
95### Quotes and rules
96
97> A quote keeps its text when you copy it, without the \`> \` markers.
98>
99> It keeps its paragraphs and lists too:
100> - **bold** and \`inline code\` stay styled
101> - each item gets its own row
102>
103> > A nested quote draws inside the bar.
104
105<summary>
106A line that holds only a tag draws dim, so wrapper tags show the reply's structure.
107</summary>
108
109---
110
111### Code
112
113\`\`\`json
114{ "theme": "dracula", "headingStyle": "banner", "mermaid": true }
115\`\`\`
116
117Blocks 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.
118
119\`\`\`ts
120type Item = { name: string; price: number; qty: number }
121
122const basket: Item[] = [
123  { name: 'apples', price: 1.2, qty: 3 },
124  { name: 'oranges', price: 0.8, qty: 5 },
125  { name: 'pears', price: 1.5, qty: 2 },
126  { name: 'plums', price: 2.1, qty: 4 },
127  { name: 'grapes', price: 3.4, qty: 1 },
128  { name: 'lemons', price: 0.6, qty: 6 },
129  { name: 'melons', price: 4.0, qty: 1 },
130  { name: 'cherries', price: 5.5, qty: 2 },
131  { name: 'figs', price: 2.8, qty: 3 },
132  { name: 'limes', price: 0.5, qty: 8 },
133  { name: 'peaches', price: 1.9, qty: 4 },
134  { name: 'kiwis', price: 0.9, qty: 6 },
135]
136
137const total = (items: Item[]): number =>
138  items.reduce((sum, item) => sum + item.price * item.qty, 0)
139
140const cheapest = (items: Item[]): Item | undefined =>
141  [...items].sort((a, b) => a.price - b.price)[0]
142
143const byName = (items: Item[]): Item[] =>
144  [...items].sort((a, b) => a.name.localeCompare(b.name))
145
146const receipt = (items: Item[]): string[] =>
147  byName(items).map(item => \`\${item.name.padEnd(10)} \${item.qty} x \${item.price.toFixed(2)}\`)
148
149console.log(receipt(basket).join('\\n'))
150console.log('total', total(basket).toFixed(2))
151console.log('cheapest', cheapest(basket)?.name)
152\`\`\`
153
154#### Math
155
156$$
157\\int_0^\\infty e^{-x^2}\\,dx = \\frac{\\sqrt{\\pi}}{2}
158$$
159
160#### Images
161
162In 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.
163
164![prism band](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAAAoCAIAAAAAIrR+AAACdElEQVR42u3TewcQBgAA8ZNkkkySJEmSJJOWrW3t/cyWJJlMkmQmSZIkSSaTJEmSJEmStLS0trX3smVLkiRJkiTJZCZJdrNvsP0xNu73Fc4hOBAfwyH4OA7HkTgax+J4nIiTcQpOw+k4A1/EV/FNfBtn41x8F9/DhbgY38eluBxX4mpci+vxQ/wIN+NW3I47cTfuxf14EA/jUTyOJ/EUfo3f44/4M57DC3gJr+A1vIG38A7+ir/hfXyIf/BIHsjvck/uym25KdflqlyWi3JezsoZOS3fyVfyuZyQY3JEDskB2Sd7ZJfskG2yRTbJRtkg62SNrJIVskw+kCWySBbIfJknc2SWzJQ35BV5QZ6Vp2SqPCGTZIKMkzEySkbIMBkqg2WQDPgrwAAchINxKA7DETgKx+A4nICT8Amcik/hM/g8voyv40ychXNwHs7HBbgIl+AHuAxX4Cpcg+twA27ETbgFt+EO3IV7cB8ewEN4BI/hCfwMv8Rv8TSewbN4Hi/iZbyK1/Em3sa7eA9/xwf4iD/kodyX3+RXuSO35IZckytySS7IOflFfpIf5Bs5JSfluByVw3JQ9ste2S07Zbtslc3ykXwo62WtrJaVslyWyvuyWBbKe/KuzJXZ8o68Ja/JSzJDpss0mSKTZaKMl7EyWkbKcHlchshjMvDvHvAkPo3P/TsHfIyf4Kf4xT88YABJ/rcaOGngJA2cpIGTBk7SwEkaOEkDJw2cpIGTNHDSwEkaOEkDJ2ngpIGTNHCSBk7SwEkDJ2ngJA2cNHCSBk7SwEkaOGngJA2cpIGTNHDSwEkaOEkDJw2cpIGTNHCSBk4aOMl/yZ8SRd1gPq93WQAAAABJRU5ErkJggg==)
165
166#### Footnotes
167
168Latency fell to 120ms[^lat] after the cache change[^cache].
169
170Click 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.
171
172[^count]: Counted at close.
173[^lat]: Median of 50 runs.
174[^cache]: Entries expire after 10m.
175
176#### Diagrams
177
178\`\`\`mermaid
179flowchart LR
180    R["<i>Reply</i>"] --> P["<b>Parse</b>"]
181    P --> D["<u>Draw</u>"]
182    D --> S["<s>Screen</s>"]
183\`\`\`
184
185\`\`\`mermaid
186sequenceDiagram
187    participant U as You
188    participant C as Claude
189    participant P as prismantis
190    U->>C: prompt
191    C->>P: markdown
192    P-->>U: colored reply
193\`\`\`
194
195\`\`\`mermaid
196xychart-beta
197    title "Color options per group"
198    x-axis [text, head, num, code, diag]
199    y-axis "options" 0 --> 8
200    bar [7, 3, 2, 6, 2]
201\`\`\`
202
203Name each series and the legend says which line is which:
204
205\`\`\`mermaid
206xychart-beta
207    title "Replies per hour"
208    x-axis [09, 10, 11, 12, 13]
209    y-axis 0 --> 40
210    line "east" [30, 34, 22, 26, 31]
211    line "west" [12, 18, 25, 20, 14]
212\`\`\`
213
214A pie draws round with a legend. Set \`pieStyle\` to \`bars\` in \`/config\` for one bar per slice:
215
216\`\`\`mermaid
217pie showData title Time per reply stage
218    "Parse" : 3
219    "Draw" : 9
220    "Paint" : 5
221\`\`\`
222
223\`\`\`mermaid
224gantt
225    title Release week
226    dateFormat YYYY-MM-DD
227    section Build
228    Parser   :p, 2026-10-05, 2d
229    Renderer :r, after p, 3d
230    section Ship
231    Review   :after r, 2d
232    Release  :milestone, 2026-10-12, 0d
233\`\`\`
234
235A diagram wider than the terminal stays source, with a dim line saying why:
236
237\`\`\`mermaid
238flowchart TD
239    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]
240\`\`\`
241
242A figure draws as written, its markup colored by role:
243
244\`\`\`figure
245{dim:timeout at 10 s, handler books at 12 s, retry books again}
246          {note:0 s}           {note:10 s}  {note:12 s}              {note:later}
247          {accent:▏─────────────▏─────▏─────────────────▏}
248Provider  {accent:██████████████}{warn:✗} timeout               {accent:█} retry
249Handler   {ok:████████████████████} 200, nobody waits
250Bookings  0                   {ok:1}                 {warn:2 twice}
251\`\`\`
252
253A box whose rows slip off its frame is lined up with its corner:
254
255\`\`\`figure
256{accent:┌─ queue ──────────┐}
257{accent:│} {ok:● worker 1} {accent:│}
258{accent:│} {warn:▲ worker 2 slow}      {accent:│}
259{accent:└──────────────────┘}
260\`\`\`
261`
262
263export const helpText = (themes: readonly string[]): string => `
264## Commands
265
266| Command | Does |
267|---------|------|
268| \`/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 |
269| \`/prismantis copy\` | Copy the last reply, or \`copy code\` for its last code block |
270| \`/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 |
271| \`/prismantis demo\` | Full showcase, every element and diagram, plus a section in your language (Korean so far, or \`demo ko\`) |
272| \`/prismantis demo-rtl\` | Hebrew right-to-left showcase |
273
274### ${themes.length} themes
275
276- Dark: ${themes.filter(t => RANDOM_THEMES.includes(t)).join(', ')}
277- Light: ${themes.filter(t => /latte|light|dawn/.test(t)).join(', ')}
278- Plain: mono, no color, only bold and dim
279
280Docs and issues: https://github.com/NahumLitvin/prismantis
281
282> [!TIP]
283> Any color slot beats the theme. Set \`headingColor\` or \`numberColor\` to a hex value in \`/config\`.
284
285### Task lists
286
287- [x] Tables, diagrams and charts drawn in the terminal
288- [x] Copy tables as Markdown, art or HTML (macOS/Linux)
289- [ ] Pick a \`taskStyle\` in \`/config\`: checks, ticks, box or progress
290
291\`\`\`mermaid
292flowchart LR
293    R[Reply] --> P[Parse]
294    P --> D[Draw]
295    D --> S[Screen]
296\`\`\`
297
298\`\`\`mermaid
299xychart-beta
300    title "Color options per group"
301    x-axis [text, head, num, code, diag]
302    y-axis "options" 0 --> 8
303    bar [7, 3, 2, 6, 2]
304\`\`\`
305
306> [!CAUTION]
307> Claude Code refuses trees over 20000 nodes. A code block past about 500 highlighted lines falls back to plain text.
308`
309
310export const rtlShowcaseText = (): string => `
311# עברית מימין לשמאל
312
313**שלום חברים**, זו הדגמה של עברית עם מונחים באנגלית כמו \`kubectl\`, מספרים כמו 99.9% ו-250ms, נתיב כמו ~/src/app.ts וגם [קישור](https://github.com/NahumLitvin/prismantis).
314
315## רשימות
316
317- פרוסים בשני אזורים (us-east ו-eu-west)
318- Python מתאים גם לסקריפטים קצרים
319- מחליפים ערכת נושא עם \`/prismantis theme nord\`
320
3211. מתקינים את התוסף
3222. שואלים שאלה בעברית
323
324> עברית נקראת מימין לשמאל, גם בטרמינל בלי תמיכה בכיווניות
325
326> [!TIP]
327> כל ערכת נושא עובדת גם בעברית
328
329| שירות | אזור | גרסה |
330| :--- | :--- | ---: |
331| שער | us-east | 2.14.0 |
332| חיוב | eu-west | 1.8.3 |
333
334\`\`\`bash
335ls -la # רשימת הקבצים בתיקייה
336\`\`\`
337
338\`\`\`text
339טיוטה להודעה: הגרסה עלתה ב-14:20
340\`\`\`
341
342\`\`\`mermaid
343flowchart LR
344  A[בקשה חדשה] --> B{האם יש cache?}
345  B -->|כן| C[מחזירים מה-cache]
346  B -->|לא| D[פונים לשרת]
347\`\`\`
348`
349
350export 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.'
351const KOREAN_SHOWCASE = `
352## 한국어
353
354**안녕하세요**, prismantis는 한국어 답변도 그대로 보여 줍니다. \`kubectl\` 같은 영문 명령어, 숫자 99.9%와 250ms, 경로 ~/src/app.ts도 함께 표시됩니다.
355
356- 서울 리전과 도쿄 리전에 배포
357- \`/prismantis theme nord\`로 테마 변경
358
359| 서비스 | 리전 | 버전 |
360| :--- | :--- | ---: |
361| 게이트웨이 | ap-northeast-2 | 2.14.0 |
362| 결제 | ap-northeast-1 | 1.8.3 |
363
364\`\`\`figure
365{accent:┌─ 빌드 ─────────────┐}
366{accent:│} 이미지 생성 완료   {accent:│}
367{accent:│} {ok:✓ 테스트 통과}      {accent:│}
368{accent:│} {warn:▲ 배포 대기}        {accent:│}
369{accent:└────────────────────┘}
370\`\`\`
371
372\`\`\`mermaid
373flowchart LR
374  A[새 요청] --> B{캐시 있음?}
375  B -->|예| C[캐시에서 반환]
376  B -->|아니오| D[서버 호출]
377\`\`\`
378`
379
380export const languageShowcase = (lang: string): string => (/^ko/i.test(lang) ? KOREAN_SHOWCASE : '')
381
382export 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 }
383
384export const setupSteps = (themes: readonly string[]): SetupStep[] => [
385  { 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.' },
386  { 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 |' },
387  { 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' },
388  { 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.' },
389  { 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: '' },
390  { 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: '' },
391  { 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: '' },
392  { 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: '' },
393  { 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: '' },
394  { 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: '' },
395  { 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```' },
396]
397
398export type SetupParts = { head: string; options: { value: string; text: string }[]; tail: string }
399
400export const setupParts = (themes: readonly string[], at: number): SetupParts => {
401  const steps = setupSteps(themes)
402  const step = steps[at]!
403  const next = steps[at + 1]
404  return {
405    head: `## Setup ${at + 1}/${steps.length}: ${step.title}\n\n${step.note}`,
406    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}` : ''}` })),
407    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.`,
408  }
409}
410
411export const setupText = (parts: SetupParts): string => [parts.head, ...parts.options.map(o => o.text), parts.tail].join('\n\n')
412
413export const THEME_PREVIEW = [
414  '#### Release notes',
415  '',
416  '**Bold**, `inline code`, 250ms and ~/src/app.ts.',
417  '',
418  '| Service | Status | p95 |',
419  '|:--|:--|--:|',
420  '| api | healthy | 120ms |',
421  '| billing | degraded | 840ms |',
422  '',
423  '```ts',
424  'const total = items.reduce((sum, item) => sum + item.qty, 0)',
425  '```',
426].join('\n')
427
428export 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.'
429
430export const SETUP_PANE_KEYS = '↑↓ or Tab moves, Enter saves and shows the next step, Esc closes.'
431
432export const SETUP_DONE = 'Setup done. Run `/prismantis setup` again any time, and `/config` has every other option.'
433
434export const findSetup = (themes: readonly string[], text: string): { at: number; before: string; parts: SetupParts } | undefined => {
435  for (let at = 0; at < setupSteps(themes).length; at++) {
436    const parts = setupParts(themes, at)
437    const whole = setupText(parts)
438    if (text.endsWith(whole)) return { at, before: text.slice(0, -whole.length).trim(), parts }
439  }
440  return undefined
441}
442
hooks/presets.ts 132 lines
1import 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  mono: {} as Theme,
110} satisfies Record<string, Theme>
111
112export type PresetName = keyof typeof PRESETS
113export const PRESET_NAMES = Object.keys(PRESETS) as PresetName[]
114
115export const PRESET_BACKGROUNDS: Partial<Record<PresetName, string>> = {
116  'catppuccin-mocha': '#1e1e2e',
117  'catppuccin-latte': '#eff1f5',
118  dracula: '#282a36',
119  nord: '#2e3440',
120  'tokyo-night': '#1a1b26',
121  'gruvbox-dark': '#282828',
122  'gruvbox-light': '#fbf1c7',
123  'rose-pine': '#191724',
124  'rose-pine-dawn': '#faf4ed',
125  everforest: '#2d353b',
126  'github-dark': '#0d1117',
127  'github-light': '#ffffff',
128  'one-dark': '#282c34',
129  'solarized-dark': '#002b36',
130  'solarized-light': '#fdf6e3',
131}
132
hooks/theme.ts 114 lines
1import 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  pngCopy: boolean
42  nativeCode?: boolean
43  httpLinks: boolean
44  editorLinks: boolean
45  fileLinks: string | null
46  pathLinks: boolean
47  diagramHints: boolean
48  issueHint: boolean
49  rtl: 'auto' | Terminal | 'off'
50  reorder: boolean
51  shape: Shape
52  latex: boolean
53  cwd: string
54  home: string
55}
56
57const 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
58
59export const isColor = (value: unknown): value is string => typeof value === 'string' && COLOR.test(value.trim())
60
61const pick = <T extends string>(value: unknown, allowed: readonly T[], fallback: T): T =>
62  allowed.includes(value as T) ? (value as T) : fallback
63
64export const RANDOM_THEMES: readonly string[] = PRESET_NAMES.filter(t => !/latte|light|dawn/.test(t) && t !== 'mono')
65
66export const pickTheme = (value: unknown, random = Math.random): string => {
67  const name = value === 'random' ? RANDOM_THEMES[Math.floor(random() * RANDOM_THEMES.length)] : value
68  return (PRESET_NAMES as readonly unknown[]).includes(name) ? String(name) : 'catppuccin-mocha'
69}
70
71export const resolveStyle = (options: PluginOptions): Style => {
72  const preset = (PRESET_NAMES as string[]).includes(String(options.theme)) ? (String(options.theme) as PresetName) : 'catppuccin-mocha'
73  const base: Theme = PRESETS[preset]
74  const fromFields = Object.fromEntries(
75    TOKENS.filter(k => isColor(options[`${k}Color`])).map(k => [k, String(options[`${k}Color`]).trim()]),
76  )
77
78  const rtl = pick(options.rtl, ['auto', 'off', ...(Object.keys(TERMINALS) as Terminal[])], 'auto')
79
80  return {
81    theme: { ...base, ...fromFields },
82    ...(PRESET_BACKGROUNDS[preset] ? { background: PRESET_BACKGROUNDS[preset] } : {}),
83    headingStyle: pick(options.headingStyle, ['bold', 'underline', 'uppercase', 'banner'] as const, 'banner'),
84    tableStyle: pick(options.tableStyle, ['box', 'rules', 'grid', 'minimal'] as const, 'box'),
85    taskStyle: pick(options.taskStyle, ['checks', 'ticks', 'box', 'progress'] as const, 'checks'),
86    promptStyle: pick(options.promptStyle, ['bubble', 'wide', 'bar', 'chevron', 'off'] as const, 'bubble'),
87    clock: pick(options.clock, ['off', '24h', '12h'] as const, 'off'),
88    toolStyle: pick(options.toolStyle, ['chat', 'tree-dim', 'tree-bold', 'classic'] as const, 'chat'),
89    toolOutput: pick(options.toolOutput, ['full', 'quiet'] as const, 'full'),
90    diffStyle: pick(options.diffStyle, ['card', 'full', 'marks', 'bar'] as const, 'card'),
91    pieStyle: pick(options.pieStyle, ['round', 'bars'] as const, 'round'),
92    highlightNumbers: options.highlightNumbers !== false,
93    highlightPaths: options.highlightPaths !== false,
94    mermaid: options.mermaid !== false,
95    mermaidAscii: options.mermaidAscii === true,
96    copyButtons: options.copyButtons !== false,
97    copyButtonStyle: pick(options.copyButtonStyle, ['inline', 'hover'] as const, 'inline'),
98    htmlCopy: null,
99    pngCopy: false,
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}
114
hooks/rtl.ts 413 lines
1import 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 units = (text: string, fmt: Fmt): Unit[] => {
38  const out: Unit[] = []
39  for (const cp of text) {
40    const last = out.at(-1)
41    if (last && MARK.test(cp)) last.ch += cp
42    else out.push({ ch: cp, fmt })
43  }
44  return out
45}
46
47const flatten = (nodes: Inline[], wrap: Fmt['wrap'] = []): Unit[] =>
48  nodes.flatMap(n => {
49    switch (n.kind) {
50      case 'strong':
51      case 'emphasis':
52      case 'strike':
53        return flatten(n.children, [...wrap, n.kind])
54      case 'link':
55        return n.text === n.href
56          ? units(n.text, { wrap, leaf: 'link', href: n.href })
57          : [...units(n.text, { wrap, leaf: 'link', href: n.href }), ...units(` (${n.href})`, { wrap, leaf: 'dim' })]
58      case 'image':
59        return units(n.text, { wrap, leaf: 'text' })
60      case 'path':
61        return units(n.text, { wrap, leaf: 'path', href: n.href })
62      default:
63        return units(n.text, { wrap, leaf: n.kind })
64    }
65  })
66
67const 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])
68
69const leafNode = ({ leaf, href }: Fmt, text: string): Inline =>
70  leaf === 'link' ? { kind: 'link', text, href: href! } : leaf === 'path' && href ? { kind: 'path', text, href } : { kind: leaf, text }
71
72const rebuild = (all: Unit[]): Inline[] => {
73  const out: Inline[] = []
74  let i = 0
75  while (i < all.length) {
76    const fmt = all[i]!.fmt
77    let text = ''
78    let j = i
79    while (j < all.length && sameFmt(all[j]!.fmt, fmt)) text += all[j++]!.ch
80    out.push(fmt.wrap.reduceRight<Inline>((inner, kind) => ({ kind, children: [inner] }), leafNode(fmt, text)))
81    i = j
82  }
83  return out
84}
85
86const baseOf = (all: Unit[]): Dir => {
87  const words = all.map(u => u.ch).join('').split(/\s+/)
88  const rw = words.filter(w => R.test(w)).length
89  const lw = words.filter(w => LATIN.test(w) && !R.test(w)).length
90  if (rw !== lw) return rw > lw ? 'R' : 'L'
91  return all.map(u => classify(u.ch)).find(Boolean) ?? 'R'
92}
93
94const turn = <U extends Unit>(us: U[]): U[] => us.map(u => ({ ...u, ch: MIRROR[u.ch] ?? u.ch })).reverse()
95
96const reorder = <U extends Unit>(all: U[], base: Dir): U[] => {
97  const strong = all.map((u, i) => {
98    const own = classify(u.ch)
99    if (own) return own
100    if (u.fmt.leaf === 'code' || u.fmt.leaf === 'math' || u.fmt.leaf === 'path') return 'L'
101    return TERMINATOR.test(u.ch) && (DIGIT.test(all[i - 1]?.ch ?? '') || DIGIT.test(all[i + 1]?.ch ?? '')) ? 'L' : null
102  })
103  const prev: (Dir | null)[] = []
104  let seen: Dir | null = null
105  strong.forEach((s, i) => {
106    seen = s ?? seen
107    prev[i] = seen
108  })
109  const next: (Dir | null)[] = []
110  seen = null
111  for (let i = strong.length - 1; i >= 0; i--) {
112    seen = strong[i] ?? seen
113    next[i] = seen
114  }
115  const dir = strong.map((s, i): Dir => s ?? ((prev[i] ?? base) === (next[i] ?? base) ? (prev[i] ?? base) : base))
116  const runs: { d: Dir; u: U[] }[] = []
117  all.forEach((u, i) => {
118    const last = runs.at(-1)
119    if (last && last.d === dir[i]) last.u.push(u)
120    else runs.push({ d: dir[i]!, u: [u] })
121  })
122  const out = runs.map(r => (r.d === 'R' ? turn(r.u) : r.u))
123  return (base === 'R' ? out.reverse() : out).flat()
124}
125
126const LRM = '\u200E'
127
128const bidiClass = (ch: string): string =>
129  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'
130
131const levelsOf = (all: Unit[], base: Dir): number[] => {
132  const t = all.map(u => bidiClass(u.ch))
133  t.forEach((c, i) => {
134    if ((c === 'ES' || c === 'CS') && t[i - 1] === 'EN' && t[i + 1] === 'EN') t[i] = 'EN'
135    else if (c === 'CS' && t[i - 1] === 'AN' && t[i + 1] === 'AN') t[i] = 'AN'
136  })
137  for (let i = 1; i < t.length; i++) if (t[i] === 'ET' && t[i - 1] === 'EN') t[i] = 'EN'
138  for (let i = t.length - 2; i >= 0; i--) if (t[i] === 'ET' && t[i + 1] === 'EN') t[i] = 'EN'
139  let strong: string = base
140  const w = t.map(c => {
141    if (c === 'L' || c === 'R') strong = c
142    return c === 'EN' && strong === 'L' ? 'L' : c === 'ES' || c === 'ET' || c === 'CS' ? 'N' : c
143  })
144  const rtlSide = (c?: string) => (c ?? base) !== 'L'
145  const ltr = base === 'L' ? 0 : 2
146  const rtl = 1
147  return w.map((c, i) => {
148    if (c !== 'N') return c === 'L' ? ltr : c === 'R' ? rtl : 2
149    let a = i
150    while (w[a] === 'N') a--
151    let b = i
152    while (w[b] === 'N') b++
153    const [before, after] = [rtlSide(w[a]), rtlSide(w[b])]
154    return before === after ? (before ? rtl : ltr) : base === 'L' ? 0 : 1
155  })
156}
157
158const terminalBidi = <U extends Unit>(all: U[], mirror = true): U[] => {
159  const levels = levelsOf(all, 'L')
160  let out = all.map((u, i) => ({ u: mirror && levels[i]! % 2 ? { ...u, ch: MIRROR[u.ch] ?? u.ch } : u, l: levels[i]! }))
161  for (let l = 2; l >= 1; l--) {
162    const done: typeof out = []
163    let run: typeof out = []
164    for (const x of out) {
165      if (x.l >= l) run.push(x)
166      else {
167        done.push(...run.reverse(), x)
168        run = []
169      }
170    }
171    out = [...done, ...run.reverse()]
172  }
173  return out.map(x => x.u)
174}
175
176export const terminalLine = (nodes: Inline[]): Inline[] => rebuild(terminalBidi(flatten(nodes)))
177
178const wrapUnits = (all: Unit[], max: number, measure: (s: string) => number): Unit[][] => {
179  const tokens: Unit[][] = []
180  all.forEach((u, i) => {
181    if (i === 0 || (u.ch !== ' ' && all[i - 1]!.ch === ' ')) tokens.push([])
182    tokens.at(-1)!.push(u)
183  })
184  const lines: Unit[][] = [[]]
185  let used = 0
186  const trim = (line: Unit[]) => {
187    while (line.at(-1)?.ch === ' ') line.pop()
188  }
189  for (const token of tokens) {
190    let core = token.length
191    while (core > 0 && token[core - 1]!.ch === ' ') core--
192    const w = token.slice(0, core).reduce((sum, u) => sum + measure(u.ch), 0)
193    if (lines.at(-1)!.length && used + w > max) {
194      trim(lines.at(-1)!)
195      lines.push([])
196      used = 0
197    }
198    lines.at(-1)!.push(...token)
199    used += w + (token.length - core)
200  }
201  trim(lines.at(-1)!)
202  return lines
203}
204
205const clusters = (text: string): string[] => units(text, { wrap: [], leaf: 'text' }).map(u => u.ch)
206
207const RUN = new RegExp(`(?:${R.source}|\\p{M})+`, 'gu')
208
209const shapeText = (text: string, shape: Shape): string =>
210  !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
211
212const shapeNodes = (nodes: Inline[], shape: Shape): Inline[] =>
213  nodes.map(n => {
214    if ('children' in n) return { ...n, children: shapeNodes(n.children, shape) }
215    return { ...n, text: shapeText(n.text, shape) }
216  })
217
218export const containsRtl = (nodes: Inline[]): boolean => nodes.some(n => ('children' in n ? containsRtl(n.children) : R.test(n.text)))
219
220export const WALL = '׀'
221
222export const ROW_MARK_TEXT = `${WALL} `
223
224export const ROW_MARK: Inline = { kind: 'dim', text: ROW_MARK_TEXT }
225
226const asWritten = (shape: Shape) => shape === 'logical' || shape === 'mirror' || shape === 'engine'
227
228const ISOLATED: Fmt['leaf'][] = ['code', 'math', 'path']
229
230const isolate = (all: Unit[]): Unit[] =>
231  all.flatMap((u, i) => {
232    if (!ISOLATED.includes(u.fmt.leaf)) return [u]
233    const mark = { ch: LRM, fmt: u.fmt }
234    const opens = i === 0 || !sameFmt(all[i - 1]!.fmt, u.fmt)
235    const closes = i === all.length - 1 || !sameFmt(all[i + 1]!.fmt, u.fmt)
236    return [...(opens ? [mark] : []), u, ...(closes ? [mark] : [])]
237  })
238
239const strongFrom = (line: Unit[], i: number, step: 1 | -1): Dir => {
240  for (let j = i; j >= 0 && j < line.length; j += step) {
241    const c = bidiClass(line[j]!.ch)
242    if (c === 'L' || c === 'R') return c
243  }
244  return 'R'
245}
246
247const swapEdges = (span: Unit[]): Unit[] => {
248  let a = 0
249  while (a < span.length && !classify(span[a]!.ch)) a++
250  let b = span.length
251  while (b > a && !classify(span[b - 1]!.ch)) b--
252  return [...turn(span.slice(b)), ...span.slice(a, b), ...turn(span.slice(0, a))]
253}
254
255const holdEdges = (line: Unit[]): Unit[] => {
256  const out = [...line]
257  for (let i = 0, j = 0; i < line.length; i = j) {
258    j = i + 1
259    if (!ISOLATED.includes(line[i]!.fmt.leaf)) continue
260    while (j < line.length && sameFmt(line[j]!.fmt, line[i]!.fmt)) j++
261    const span = line.slice(i, j)
262    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))
263  }
264  return out
265}
266
267const forEngine = (line: Unit[], lead: boolean): Unit[] => {
268  const all = isolate(line)
269  const first = all.map(u => bidiClass(u.ch)).find(c => c === 'L' || c === 'R')
270  const levels = levelsOf(all, lead || first === 'R' ? 'R' : 'L')
271  return all.map((u, i) => (levels[i]! % 2 ? { ...u, ch: MIRROR[u.ch] ?? u.ch } : u))
272}
273
274const startsLatin = (line: Unit[]): boolean => line.map(u => bidiClass(u.ch)).find(c => c === 'L' || c === 'R') === 'L'
275
276export const opensLatin = (text: string): boolean => startsLatin(units(text, { wrap: [], leaf: 'text' }))
277
278const ordered = (line: Unit[], shape: Shape, base: Dir, lead: boolean): Unit[] =>
279  shape === 'engine' ? forEngine(line, lead) : shape === 'mirror' ? holdEdges(line) : asWritten(shape) ? line : shape === 'inverse' ? terminalBidi(reorder(line, base)) : reorder(line, base)
280
281export const flow = (nodes: Inline[], columns: number, measure: (s: string) => number, shape: Shape = 'visual', mark = true): Flow | null => {
282  if (!containsRtl(nodes)) return null
283  const all = flatten(nodes)
284  const base = shape === 'mirror' ? 'R' : baseOf(all)
285  const marked = mark && asWritten(shape) && base === 'R' && all.some(u => bidiClass(u.ch) === 'L')
286  const logical = base === 'R' ? wrapUnits(all, columns - (marked ? measure(ROW_MARK_TEXT) : 0), measure) : [all]
287  const lines = logical.map(line => {
288    const lead = marked && startsLatin(line)
289    const built = rebuild(ordered(line, shape, base, lead))
290    return lead ? [ROW_MARK, ...built] : built
291  })
292  return { base, lines: shape === 'words' ? lines.map(line => shapeNodes(line, shape)) : lines }
293}
294
295const visualText = (text: string, command = false): string => {
296  if (!R.test(text)) return text
297  const all = units(text, { wrap: [], leaf: 'text' })
298  return reorder(all, command && startsLatin(all) ? 'L' : baseOf(all)).map(u => u.ch).join('')
299}
300
301export const commentTail = (line: string, shape: Shape = 'visual'): { head: string; marker: string; tail: string } | null => {
302  if (asWritten(shape) || !R.test(line)) return null
303  const m = COMMENT.exec(line)
304  return m && R.test(m[3]!) ? { head: m[1]!, marker: m[2]!, tail: shapeText(visualText(m[3]!), shape) } : null
305}
306
307export const commentVisual = (text: string, shape: Shape = 'visual'): string => {
308  const c = commentTail(text, shape)
309  return c ? c.head + c.marker + c.tail : text
310}
311
312export const codeVisual = (text: string, shape: Shape = 'visual', max = Infinity, measure: (s: string) => number = s => s.length, command = false): string =>
313  asWritten(shape) || !R.test(text)
314    ? text
315    : text
316        .split('\n')
317        .flatMap(line => (measure(line) > max ? wrapUnits(units(line, { wrap: [], leaf: 'text' }), max, measure).map(row => row.map(u => u.ch).join('')) : [line]))
318        .map(line => shapeText(visualText(line, command), shape))
319        .join('\n')
320
321export const hasRtl = (text: string): boolean => R.test(text)
322
323export const LTR_BLANK = '⠀'
324
325const WORD = /[\p{L}\p{N}\p{P}]/u
326
327const DRAWN = /[←-⇿─-◿]/u
328
329const ASCII_DRAWN = /[-+|<>]/
330
331const LETTER = /[\p{L}\p{N}]/u
332
333const drawnAt = (all: Cell[], i: number) => {
334  const ch = all[i]!.ch
335  return DRAWN.test(ch) || (ASCII_DRAWN.test(ch) && !(LETTER.test(all[i - 1]?.ch ?? '') && LETTER.test(all[i + 1]?.ch ?? '')))
336}
337
338const inLabel = (chars: string[], c: number) => {
339  const [a = '', b = ''] = [chars[c - 1], chars[c + 1]]
340  return WORD.test(a) && WORD.test(b) && (R.test(a) || R.test(b))
341}
342
343type Cell = Unit & { at: number }
344
345export type Held = { cells: string[]; from: number[] }
346
347const PLAIN: Fmt = { wrap: [], leaf: 'text' }
348
349const rightToLeft = (all: Cell[]): Cell[] => (baseOf(all) === 'R' && all.some(u => bidiClass(u.ch) === 'L') ? terminalBidi(reorder(all, 'R')) : all)
350
351const byWords = (label: (words: Cell[]) => Cell[]) => (all: Cell[]): Cell[] => {
352  const out: Cell[] = []
353  let words: Cell[] = []
354  const flush = () => {
355    out.push(...(words.some(u => R.test(u.ch)) ? label(words) : words))
356    words = []
357  }
358  all.forEach((u, i) => {
359    if (!drawnAt(all, i)) words.push(u)
360    else {
361      flush()
362      out.push(u)
363    }
364  })
365  flush()
366  return out
367}
368
369const engineLabel = byWords(words => (baseOf(words) === 'R' ? terminalBidi(reorder(words, 'R'), false) : words))
370
371const visualLabel = byWords(words => reorder(words, baseOf(words)))
372
373const hold = (chars: string[], label: (all: Cell[]) => Cell[], blank: string[]): Held => {
374  const held: Held = { cells: [], from: [] }
375  let run: Cell[] = []
376  const flush = () => {
377    for (const u of label(run)) {
378      held.cells.push(u.ch)
379      held.from.push(u.at)
380    }
381    run = []
382  }
383  chars.forEach((ch, c) => {
384    if (ch === ' ' && !inLabel(chars, c)) {
385      flush()
386      for (const b of blank) {
387        held.cells.push(b)
388        held.from.push(c)
389      }
390    } else if (MARK.test(ch) && run.length) run.at(-1)!.ch += ch
391    else run.push({ ch, fmt: PLAIN, at: c })
392  })
393  flush()
394  return held
395}
396
397export const asIs = (chars: string[]): Held => ({ cells: chars, from: chars.map((_, c) => c) })
398
399export const holdText = (chars: string[]): Held => hold(chars, rightToLeft, [LTR_BLANK])
400
401export const listMarker = (marker: string, shape: Shape): string => (shape === 'logical' ? marker : marker.replace(/^(\d+)([.)])$/, (_, n: string, p: string) => (MIRROR[p] ?? p) + n))
402
403export const holdEngine = (chars: string[]): Held => (chars.some(ch => R.test(ch)) ? hold(chars, engineLabel, [LRM, ' ']) : asIs(chars))
404
405export const holdVisual = (chars: string[]): Held => (chars.some(ch => R.test(ch)) ? hold(chars, visualLabel, [' ']) : asIs(chars))
406
407export const holdRow = (chars: string[]): Held => (chars.some(ch => R.test(ch)) ? holdText(chars) : asIs(chars))
408
409export const led = (chars: string[], held: Held): Held => {
410  const blank = chars.some(ch => R.test(ch)) ? LTR_BLANK : ' '
411  return { cells: [blank, blank, ...held.cells], from: [-1, -1, ...held.from] }
412}
413