SLOPSHOPPER

veneer

Claude Code in the terminal with enhanced visuals, syntax highlighting, tool use, attached images, and more.

panebandspinnerrowscommandprompt
★ 1v0.1.2MITupdated 2026-10-26MitchMedeiros/veneer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · veneer
│ ┃ Veneer ✕ │ ┃ tab:settings tab:syntax ▗▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▖ │ ┃ ▐ fix the failing auth test and add an audit log call ▌ │ ┃ Themes ▝▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▘ │ ┃ ● Default │ ┃ + Browse popular themes... ⏺ Read(src/auth.ts) │ ┃ + New custom theme... ⎿ Read 6 lines │ ┃ │ ┃ typescript Edit file:///work/app/src/auth.ts │ ┃ ╭─────────────────────────────────────────╮ ⏺ Bash(bun test) │ ┃ │ // Sum the lengths of the words │ ⎿ 3 pass, 1 fail │ ┃ │ export function total(words: string[]): │ │ ┃ │ number { │ Done. I made refresh reject expired claims and added an audit call │ ┃ │ const empty = words.filter((word) => │ │ ┃ │ word !== ""); │ ✻ Worked for 42s · done 4:20 PM │ ┃ │ return empty.reduce((sum, word) => │ │ ┃ │ sum + word.length, 0); │ › /veneer │ ┃ │ } │ │ ┃ ╰─────────────────────────────────────────╯ │ ┃ java │ ┃ ╭─────────────────────────────────────────╮ │ ┃ │ // Greet each name │ │ ┃ │ static void greet(List<String> names) { │ │ ┃ │ names.forEach(name -> │ │ ┃ │ System.out.println("Hello, " + name)); │ │ ┃ │ } │ ✻ Thinking… ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Veneer
tab:settings tab:syntax Themes ● Default + Browse popular themes... + New custom theme... typescript ╭─────────────────────────────────────────────────────────╮ │ // Sum the lengths of the words │ │ export function total(words: string[]): number { │ │ const empty = words.filter((word) => word !== ""); │ │ return empty.reduce((sum, word) => sum + word.length, │ │ 0); │ │ } │ ╰─────────────────────────────────────────────────────────╯ java ╭─────────────────────────────────────────────────────────╮ │ // Greet each name │ │ static void greet(List<String> names) { │ │ names.forEach(name -> System.out.println("Hello, " │ │ + name)); │ │ } │ ╰─────────────────────────────────────────────────────────╯ python ╭─────────────────────────────────────────────────────────╮ │ # Count the words │ │ def count(text: str) -> dict[str, int]: │ │ words = text.lower().split() │ │ return {word: words.count(word) for word in │ │ set(words)} │ ╰─────────────────────────────────────────────────────────╯ Enter to select · Esc to cancel
Spinner
✻ Thinking…
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
Edit file:///work/app/src/auth.ts
README

Veneer

Veneer is a Claude Code mod that enhances the overall look and feel of the terminal. It uses the built-in Claude Code theming system for nearly everything. It adds customizable syntax highlighting for over 100 languages, using any theme on Open VSX or any theme in VS Code theme format. Furthermore, it can display attached and read images in the chat.

Table of Contents

Installing

Use the following slash commands inside Claude Code (requires Claude Code>=2.1.287):

/plugin marketplace add mitchmedeiros/veneer
/plugin install veneer@veneer

Or do both in one command from your shell (requires Claude Code>=2.1.292):

claude plugin install veneer --marketplace mitchmedeiros/veneer

Terminal Setup

Veneer works in any terminal. The sections below cover optional setup for specific terminals and features.

Image Support

To see diagrams and tables as images, and image previews in messages, you need:

This is a limitation of how Claude Code displays images.

Nerd Font Icons

If you want Nerd Font icons rather than Unicode, either use a terminal that ships with them built in or install them. If you still see Unicode symbols in Claude Code, enable the icons with /veneer icons nerd.

Rio

Launch Claude Code with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 to display images in Rio. In my testing, pictures look small with the default cellRatio, and a value of 1.9 fits better. Run /veneer cell-proportion 1.9 or change it in the settings pane.

tmux

For images in tmux, run tmux set -g allow-passthrough on (tmux>=3.3a). Then start Claude Code with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 and run /veneer text-based graphics off.

Syntax Highlighting

Run /syntax to pick a theme. It lists every theme file in ~/.claude/veneer/themes/.

To add a new theme, either choose Browse popular themes to download one of the 50 most popular, or choose New custom theme and provide:

  • the page URL or publisher.name for a theme on Open VSX
  • a path to a local theme file

If a theme on Open VSX has multiple variants (e.g. light, dark), you will be asked to choose one.

General Settings

Run /veneer to change every option below in one pane. It has a General tab and a Syntax tab.

To change a setting without opening the pane, run /veneer <setting> <value>, such as /veneer icons nerd. The setting can be either its display name or its option name, in any case: /veneer cell-proportion 1.9 and /veneer cellRatio 1.9 do the same thing. Switches take on or off.

Display NameSettingDefaultUse
Message alignmentmessageAlignleftleft or right
Message stylingstyleUserMessagetrueDraw your messages as a bubble. Off leaves it to a mod.
Iconsiconsautoauto, nerd or plain. Nerd Font or Unicode icons.
File linkslinksautoauto, link or text. How file paths are drawn.
Text-based graphicsnativeGraphicsfalseDraw tables, headings and Mermaid diagrams as text.
Diagram hintdiagramHinttrueOff stops Claude from responding with diagrams and math.
Spinner stylingstyleSpinnertrueTurn off to leave spinner styling to another mod.
Table fontfontFamilyblankFont for tables and headings. Blank uses defaults.
Cell proportioncellRatio2.9Terminal cell height over width. Fixes letterboxing.
Code blocksfenceBackgroundtrueFill code blocks with the syntax theme's background.
File readsreadBackgroundtrueThe same for the card of a file read.
Command and search outputoutputBackgroundtrueThe same for highlighted Bash and Grep output.
DiffsdiffBackgroundtrueThe same for diffs. Added and removed lines keep theirs.

Settings are stored under pluginConfigs in the global ~/.claude/settings.json.

Diagrams and charts

Veneer instructs Claude to draw mermaid fences when they add value. Veneer then parses these and displays them as images or text blocks. The supported types are:

KindOpens with
Flowchartgraph or flowchart, without subgraphs
StatestateDiagram or stateDiagram-v2
SequencesequenceDiagram
ClassclassDiagram
ERerDiagram
Piepie
XY chartxychart or xychart-beta, bars and lines, vertical or horizontal
Radarradar-beta
Sankeysankey or sankey-beta
Treemaptreemap-beta
Quadrant chartquadrantChart
Ganttgantt, with dependencies, milestones, dateFormat and axisFormat
Timelinetimeline
User journeyjourney
Kanbankanban, with ticket, assignee and priority metadata
Mind mapmindmap
Git graphgitGraph, with branches, merges, tags and cherry-picks
Packetpacket or packet-beta
Blockblock-beta, with spans, spaces, nested blocks and arrows
Architecturearchitecture-beta, with groups, services, junctions and ports
C4C4Context, C4Container, C4Component, C4Dynamic and C4Deployment

Math

Display equations ($$ ... $$, \[ ... \] and \begin{equation}, align, gather and multline blocks) are typeset with MathJax and drawn as images in the theme's text colour. An equation MathJax cannot read, or any equation where images are unavailable or text-based graphics is on, is drawn as Unicode text. Inline math ($ ... $ and \( ... \)) is always converted to Unicode text, such as x² + α ≤ ∑ᵢ₌₁ⁿ i, so it stays in the line. Anything in a code span or fence is left alone. The equation's TeX is copied from the button above it.

Supported Languages and File Types

Syntax highlighting is supported for 106 languages and file types:

  • Web: TypeScript, TSX, JavaScript, JSX, JSON, JSONC, JSON5, JSON Lines, HTML, CSS, SCSS, Sass, Less, Stylus, Vue, Pug, Handlebars, Jinja, Twig, Razor, GraphQL
  • Scripting and shells: Shell, Shell Session, Fish, PowerShell, Batch, AWK, Ruby, PHP, Perl, Lua, R, Julia, MATLAB, Tcl, Vim script
  • Systems and general purpose: Python, C, C++, Objective-C, Objective-C++, C#, F#, Visual Basic, Java, Kotlin, Scala, Groovy, Swift, Dart, Go, Rust, Zig, D, Nim, Crystal, Pascal, Fortran, COBOL, Solidity, GDScript
  • Functional and Lisp: Haskell, OCaml, Elm, PureScript, Elixir, Erlang, Clojure, Racket, Scheme, Common Lisp, Emacs Lisp
  • Data and config: YAML, TOML, INI, dotenv, XML, Protocol Buffers, Prisma, Terraform, HCL, Nix, Bicep, Dockerfile, Makefile, CMake, Nginx, Apache, systemd, SSH config, HTTP, Git commit messages
  • Documents: Markdown, MDX, LaTeX, BibTeX, reStructuredText, AsciiDoc, diff
  • Shaders and hardware: GLSL, HLSL, WGSL, Verilog, SystemVerilog, VHDL
  • SQL

Contributing

Requires Node 24 or later and the Claude Code CLI. Install the tooling once with npm install, which also sets up the pre-commit hook.

To test local changes, start Claude Code with claude --plugin-dir /path/to/veneer. For that session it loads your checkout instead of an installed copy of Veneer.

Other useful commands:

CommandDoes
npm run typecheckType-check with tsc
npm run validateRun claude plugin validate on the repo
npm testRun claude plugin test on the repo
npm run build:grammarsRebuild grammars/ from tools/languages.json
npm run build:mathRebuild the bundled MathJax in hooks/vendor/ from node_modules
npm run conformanceCompare the tokenizer with Shiki on tools/samples/
npm run check:themesFetch the popular themes from Open VSX (network, not in CI; -- --all for every theme)
Source 76 files
hooks/register.tsx 1299 lines
1import { atom, read, update } from "claude-code";
2import type { EngineInterface, PluginOptions, Register, RenderElement, Timer } from "claude-code";
3
4import type { Off, Palette, SettingsPane, SyntaxPane, Tab } from "../types";
5import { configOf } from "./config";
6import type { Backdrop, Config } from "./config";
7import { iconsArePlain, linksArePlain, OFF_TEXT, terminalOff } from "./gate";
8import { changeCounts, withBadges } from "./badge";
9import { diffCard, parseDiff } from "./diff";
10import { MAX_LINES } from "./fold";
11import { callIdOf, hiddenIdOf, toolGroup } from "./group";
12import { headingSketch } from "./heading";
13import { mathSketch } from "./math";
14import {
15  altOf,
16  draftImageIds,
17  imageSketch,
18  imagesOf,
19  pastedImagesOf,
20  PASTED_MARKER,
21  shrinkFactor,
22  sizeOfFound,
23  treeBytes,
24  withoutMarkers,
25} from "./image";
26import type { Found } from "./image";
27import { imageColumn } from "./image-card";
28import type { Shown } from "./image-card";
29import { hasDrawn, splitReply } from "./markdown";
30import type { Segment } from "./markdown";
31import { outputCard, parseOutput } from "./output";
32import { baseOf } from "./palette";
33import { cellHeightOf, hashOf, MAX_COLUMNS, pictureFor } from "./picture";
34import type { Font, Picture, PictureIo, Sketch } from "./picture";
35import { CARD_COLUMNS } from "./mermaid-card";
36import { diagramSketch, diagramText } from "./mermaid-diagram";
37import { MERMAID_HINT } from "./mermaid-hint";
38import { BULLET, GUTTER, MARGIN, replyTree } from "./reply";
39import { commandOfCall, pathOfCall, rememberInput } from "./calls";
40import { filePathOf, outputFill, paintCommand, paintDiff, paintFences, paintLines, paintOutput } from "./paint";
41import type { Painter } from "./paint";
42import { highlight, themeBackground, themeSwatch } from "./syntax/highlight";
43import type { SyntaxIo } from "./syntax/highlight";
44import {
45  DEFAULT_THEME,
46  NEW_THEME,
47  paneKeys,
48  PATH_KEY,
49  POPULAR_THEME,
50  SAMPLES,
51  syntaxPane,
52  THEME_KEY,
53} from "./syntax-pane";
54import { POPULAR_THEMES } from "./syntax-popular";
55import { fileUrl, flattenTheme, needsStrings, OPEN_VSX_ORIGIN, parseExtensionId, themesOf } from "./syntax-remote";
56import type { ExtensionId, ThemeChoice } from "./syntax-remote";
57import {
58  baseNameOf,
59  configDirOf,
60  expandHome,
61  importName,
62  themeNames,
63  themeProblem,
64  themesDirOf,
65  THEME_EXTENSION,
66  uniqueName,
67} from "./syntax-themes";
68import {
69  fieldOf,
70  groupSettings,
71  isTyped,
72  nextValue,
73  parseSettingChange,
74  SETTING_KEY,
75  SETTINGS_PREFIX,
76  settingsKeys,
77  settingsPane,
78  valueText,
79} from "./settings-pane";
80import type { Setting } from "./settings-pane";
81import { PANE_ID, tabbed, tabKeys } from "./pane-tabs";
82import { tableSketch } from "./table";
83import { toolRow } from "./tool-row";
84import type { Plain } from "./tool-row";
85import { loadPalette } from "./theme";
86import { userBubble } from "./user-message";
87
88const NOTICE_MS = 6000;
89
90// Why Veneer is off this session; null when it draws.
91const offAtom = atom({ plugin: "veneer", key: "off" } as const, null as Off | null);
92// Whether the icons are Unicode symbols, because the terminal has no Nerd Font to draw them or the setting says so.
93const plainIconsAtom = atom({ plugin: "veneer", key: "plainIcons" } as const, false);
94// Whether a file path is plain text, because Claude Code would print its address beside a link in this terminal.
95const plainLinksAtom = atom({ plugin: "veneer", key: "plainLinks" } as const, false);
96// The tool calls whose diff card shows every line.
97const expandedAtom = atom({ plugin: "veneer", key: "expanded" } as const, [] as string[]);
98const paletteAtom = atom({ plugin: "veneer", key: "palette" } as const, baseOf("dark") as Palette);
99// The syntax theme chosen with /syntax, by file name without `.json`; empty is the shipped default. Kept in the store.
100const syntaxAtom = atom({ plugin: "veneer", key: "syntax" } as const, "");
101const LIST_PANE: SyntaxPane = {
102  step: "list",
103  path: "",
104  content: "",
105  message: undefined,
106  page: 0,
107  extension: "",
108  variants: [],
109};
110const syntaxPaneAtom = atom({ plugin: "veneer", key: "syntaxPane" } as const, LIST_PANE);
111// The theme the picker's focus is on. It shows in place of the chosen one until the pane closes, as Claude's own theme
112// picker does; null when nothing is previewed.
113const syntaxPreviewAtom = atom({ plugin: "veneer", key: "syntaxPreview" } as const, null as string | null);
114// The tab of the pane that is open.
115const tabAtom = atom({ plugin: "veneer", key: "tab" } as const, "settings" as Tab);
116// The element the pane's focus ring is on, which the arrow keys move from when the pane would scroll.
117const focusAtom = atom({ plugin: "veneer", key: "focus" } as const, null as string | null);
118// The numbers of the images pasted into the prompt box and not yet sent.
119const draftImagesAtom = atom({ plugin: "veneer", key: "draftImages" } as const, [] as string[]);
120
121// The plugin's settings as they stand, by field name. Hooks read them from here so a change made in the `/veneer` pane or
122// in `/config` shows at once.
123const optionsAtom = atom({ plugin: "veneer", key: "options" } as const, {} as PluginOptions);
124const CLOSED_SETTINGS: SettingsPane = { editing: null, message: undefined };
125const settingsPaneAtom = atom({ plugin: "veneer", key: "settingsPane" } as const, CLOSED_SETTINGS);
126
127// The slash commands: each opens the pane, on the tab it names.
128const SYNTAX_COMMAND = "syntax";
129const SETTINGS_COMMAND = "veneer-settings";
130// What the pane asks for, as a request: rows when seated above the prompt, columns when docked beside the transcript.
131const PANE_ROWS = 24;
132const PANE_COLUMNS = 72;
133const SYNTAX_KEY = "syntaxTheme";
134const MAX_REDIRECTS = 3;
135
136// Opens a folded entry, or folds an open one again.
137function flip($: EngineInterface, id: string): void {
138  void update($, expandedAtom, (ids) => (ids.includes(id) ? ids.filter((other) => other !== id) : [...ids, id]));
139}
140
141async function themeFile($: EngineInterface, path: string): Promise<string | undefined> {
142  return $.fs.read(path).catch(() => undefined);
143}
144
145async function refreshPalette($: EngineInterface, theme?: unknown): Promise<void> {
146  const setting = theme ?? (await $.config.list()).find((row) => row.key === "theme")?.value;
147  const palette = await loadPalette(setting, await $.env.get("HOME"), await $.env.get("COLORFGBG"), (path) =>
148    themeFile($, path),
149  );
150
151  await update($, paletteAtom, () => palette);
152}
153
154const pictureIo = ($: EngineInterface): PictureIo => ({
155  run: async (argv, stdin) => (await $.process.run(argv, { stdin, timeoutMs: 5000 }).catch(() => null))?.exitCode === 0,
156  readBase64: (path) =>
157    $.fs.read(path, { as: "bytes" }).then(
158      (file) => file.base64,
159      () => undefined,
160    ),
161});
162
163// The folder the person's syntax themes are kept in, or undefined when no Claude folder can be found.
164async function themesFolder($: EngineInterface): Promise<string | undefined> {
165  const [configDir, home] = await Promise.all([$.env.get("CLAUDE_CONFIG_DIR"), $.env.get("HOME")]);
166  const root = configDirOf(configDir, home);
167
168  return root === undefined ? undefined : themesDirOf(root);
169}
170
171// The folder the saved themes are kept in and their names.
172async function savedThemes($: EngineInterface): Promise<{ folder: string | undefined; names: string[] }> {
173  const folder = await themesFolder($);
174
175  return { folder, names: folder === undefined ? [] : themeNames(await $.fs.list(folder).catch(() => [])) };
176}
177
178// The chosen syntax theme as a file path, empty for the shipped one, with what reads files.
179async function syntaxOf($: EngineInterface): Promise<{ io: SyntaxIo; themePath: string }> {
180  const [preview, chosen] = await Promise.all([read($, syntaxPreviewAtom), read($, syntaxAtom)]);
181  const name = preview ?? chosen;
182  const folder = name === "" ? undefined : await themesFolder($);
183  const io: SyntaxIo = { root: $.plugin.root, read: (path) => $.fs.read(path).catch(() => undefined) };
184
185  return { io, themePath: folder === undefined ? "" : `${folder}/${name}${THEME_EXTENSION}` };
186}
187
188// Highlights code with the syntax theme.
189async function painterFor($: EngineInterface): Promise<Painter> {
190  const { io, themePath } = await syntaxOf($);
191
192  return (hint, code) => highlight(io, themePath, hint, code);
193}
194
195// The fill the syntax theme sets behind a kind of card; undefined when that card has the switch off or the theme sets none.
196async function backgroundFor($: EngineInterface, config: Config, card: Backdrop): Promise<string | undefined> {
197  if (!config.backgrounds[card]) {
198    return undefined;
199  }
200
201  const { io, themePath } = await syntaxOf($);
202
203  return themeBackground(io, themePath);
204}
205
206async function showPane($: EngineInterface, pane: Partial<SyntaxPane>): Promise<void> {
207  await update($, syntaxPaneAtom, (current) => ({ ...current, ...pane }));
208}
209
210// Makes a theme the chosen one, now and in later sessions. Empty chooses the shipped default.
211async function chooseTheme($: EngineInterface, name: string): Promise<void> {
212  await (name === "" ? $.store.delete(SYNTAX_KEY) : $.store.set(SYNTAX_KEY, name));
213  await update($, syntaxAtom, () => name);
214}
215
216// Chooses a theme and closes the picker, which ends the preview.
217async function chooseAndClose($: EngineInterface, name: string): Promise<void> {
218  await chooseTheme($, name);
219  await $.ui.close({ id: PANE_ID });
220}
221
222type Fetched = { ok: boolean; status: number; text: string };
223
224// A text file from the network, with the redirects Open VSX answers file addresses with followed by hand in case the
225// host does not follow them. Undefined when the network cannot be reached.
226async function fetchText($: EngineInterface, url: string): Promise<Fetched | undefined> {
227  let target = url;
228
229  for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
230    const response = await $.http.fetch(target).catch(() => undefined);
231    const location = response?.headers.location;
232
233    if (response === undefined || response.status < 300 || response.status >= 400 || location === undefined) {
234      return response;
235    }
236
237    target = location.startsWith("/") ? `${OPEN_VSX_ORIGIN}${location}` : location;
238
239    if (!target.startsWith("https://")) {
240      return undefined;
241    }
242  }
243
244  return undefined;
245}
246
247// The text of a file inside an extension on Open VSX, or undefined when there is none.
248async function extensionFile($: EngineInterface, extension: ExtensionId, path: string): Promise<string | undefined> {
249  const file = await fetchText($, fileUrl(extension, path));
250
251  return file?.ok ? file.text : undefined;
252}
253
254// Reads the themes an extension on Open VSX holds. One theme is fetched at once; several are offered to choose from.
255async function loadExtension($: EngineInterface, extension: ExtensionId): Promise<void> {
256  const label = `${extension.publisher}.${extension.name}`;
257
258  await showPane($, { message: `Fetching ${label} from Open VSX...` });
259
260  const manifest = await fetchText($, fileUrl(extension, "package.json"));
261
262  if (manifest === undefined) {
263    return showPane($, { message: "Could not reach Open VSX." });
264  }
265
266  if (!manifest.ok) {
267    return showPane($, {
268      message:
269        manifest.status === 404 ? `Open VSX has no extension ${label}.` : `Open VSX answered ${manifest.status}.`,
270    });
271  }
272
273  let themes = themesOf(manifest.text);
274
275  if (needsStrings(themes)) {
276    const strings = await extensionFile($, extension, "package.nls.json");
277
278    themes = themesOf(manifest.text, strings);
279  }
280
281  const [only, ...others] = themes;
282
283  if (only === undefined) {
284    return showPane($, { message: `${label} has no color themes.` });
285  }
286
287  await (others.length === 0
288    ? loadVariant($, extension, only)
289    : showPane($, { step: "variant", extension: label, variants: themes, page: 0, message: undefined }));
290}
291
292// Fetches one theme of an extension on Open VSX, folds in the files it includes, and asks what to call it.
293async function loadVariant($: EngineInterface, extension: ExtensionId, theme: ThemeChoice): Promise<void> {
294  await showPane($, { message: `Fetching ${theme.label}...` });
295
296  const text = await extensionFile($, extension, theme.path);
297
298  if (text === undefined) {
299    return showPane($, { message: `Could not fetch ${theme.label} from Open VSX.` });
300  }
301
302  const content = await flattenTheme(text, theme.path, (path) => extensionFile($, extension, path.slice(1)));
303  const problem = content === undefined ? "That file is not valid JSON." : themeProblem(content);
304
305  await (problem === undefined
306    ? showPane($, { step: "name", path: theme.label, content: content ?? "", message: undefined })
307    : showPane($, { message: problem }));
308}
309
310// First step of adding a theme: an extension on Open VSX, or the file the person named.
311async function readThemeSource($: EngineInterface, input: string): Promise<void> {
312  const extension = parseExtensionId(input);
313
314  await (extension === undefined ? readThemeFile($, input) : loadExtension($, extension));
315}
316
317// The row of a paged list that was chosen: an extension from the popular list, or one theme of an extension.
318async function chooseRow($: EngineInterface, index: number): Promise<void> {
319  const pane = await read($, syntaxPaneAtom);
320
321  if (pane.step === "popular") {
322    const extension = parseExtensionId(POPULAR_THEMES[index]?.id ?? "");
323
324    return extension === undefined ? undefined : loadExtension($, extension);
325  }
326
327  const extension = parseExtensionId(pane.extension);
328  const theme = pane.variants[index];
329
330  return extension === undefined || theme === undefined ? undefined : loadVariant($, extension, theme);
331}
332
333// First step of adding a theme from a file: the file the person named, kept if it reads as a theme.
334async function readThemeFile($: EngineInterface, input: string): Promise<void> {
335  const path = expandHome(input.trim(), await $.env.get("HOME"));
336  const text = path === "" ? undefined : await $.fs.read(path).catch(() => undefined);
337  const problem = text === undefined ? `Could not read ${path === "" ? "an empty path" : path}.` : themeProblem(text);
338
339  await (problem === undefined
340    ? showPane($, { step: "name", path, content: text ?? "", message: undefined })
341    : showPane($, { message: problem }));
342}
343
344// Last step of adding a theme: copies the file into the themes folder under the name asked for, or its own name, with a
345// number added when that name is taken, and chooses it.
346async function importTheme($: EngineInterface, requested: string): Promise<void> {
347  const { path, content } = await read($, syntaxPaneAtom);
348  const folder = await themesFolder($);
349
350  if (folder === undefined) {
351    return showPane($, { step: "list", message: "The Claude folder could not be found." });
352  }
353
354  const taken = themeNames(await $.fs.list(folder).catch(() => []));
355  const name = uniqueName(importName(requested, path), taken);
356
357  try {
358    await $.fs.write(`${folder}/${name}${THEME_EXTENSION}`, content);
359  } catch {
360    return showPane($, { message: `Could not write ${name}${THEME_EXTENSION} to ${folder}.` });
361  }
362
363  await showPane($, LIST_PANE);
364  await chooseAndClose($, name);
365  $.ui.toast(`Added ${name} from ${baseNameOf(path)}.`);
366}
367
368// Whether a block of a reply is drawn as a picture: a table, a heading, an equation or a Mermaid fence, unless the settings leave
369// graphics to native drawing.
370function wantsPicture(segment: Segment, config: Config): segment is Exclude<Segment, { kind: "text" }> {
371  return (
372    !config.nativeGraphics &&
373    (segment.kind === "table" ||
374      segment.kind === "heading" ||
375      segment.kind === "math" ||
376      (segment.kind === "code" && segment.lang === "mermaid"))
377  );
378}
379
380// The picture a block of a reply is drawn as, or null where it stays text.
381function sketchOf(
382  segment: Exclude<Segment, { kind: "text" }>,
383  available: number,
384  palette: Palette,
385  font: Font,
386): Sketch | null {
387  switch (segment.kind) {
388    case "table":
389      return tableSketch(segment, available, palette, font);
390    case "heading":
391      return headingSketch(segment, available, palette, font);
392    case "math":
393      return mathSketch(segment.tex, available, palette, font);
394    case "code":
395      return diagramSketch(segment.code, available, palette, font);
396  }
397}
398
399const MAX_SHRINKS = 3;
400const MEMORY_REDUCED = 50;
401const reduced = new Set<string>();
402
403// The images as drawn under a row or a group: a picture each where pictures work, else the name and size. The pictures
404// of one call share the engine's size limit, so they are drawn again smaller until they fit, and the person is told once.
405async function shownImages(
406  $: EngineInterface,
407  found: readonly Found[],
408  config: Config,
409  columns: number,
410  canDraw: boolean,
411): Promise<Shown[]> {
412  const isOff = canDraw ? (await read($, offAtom)) !== null : true;
413  const text = (image: Found): Shown => ({ id: image.id, alt: altOf(image, sizeOfFound(image)), picture: null });
414
415  if (isOff || found.length === 0) {
416    return found.map(text);
417  }
418
419  const font = { family: config.fontFamily, cellHeight: cellHeightOf(config.cellRatio) };
420  const available = Math.min(MAX_COLUMNS, columns - 2 * MARGIN);
421  const dir = await pictureDir($);
422  const io = pictureIo($);
423  const look = `${dir}|${font.family}|${font.cellHeight}`;
424  const draw = (image: Found, width: number, rows: number) =>
425    pictureFor(
426      io,
427      dir,
428      `${look}|${width}|${rows}|image|${image.id}`,
429      () => imageSketch(image, width, rows, font.cellHeight, font),
430      font,
431    );
432  let pictures = await Promise.all(found.map((image) => draw(image, available, config.imageRows)));
433
434  for (let pass = 0; pass < MAX_SHRINKS; pass++) {
435    const factor = shrinkFactor(treeBytes(pictures));
436
437    if (factor === 1) {
438      break;
439    }
440
441    const key = found.map(({ id }) => id).join("|");
442
443    if (!reduced.has(key)) {
444      reduced.add(key);
445      $.ui.toast("Veneer made images smaller to fit Claude Code's size limit.", { timeoutMs: NOTICE_MS });
446
447      if (reduced.size > MEMORY_REDUCED) {
448        reduced.delete(reduced.values().next().value as string);
449      }
450    }
451
452    const current = pictures;
453
454    pictures = await Promise.all(
455      found.map((image, at) => {
456        const picture = current[at];
457
458        return picture === null || picture === undefined
459          ? null
460          : draw(
461              image,
462              Math.max(1, Math.floor(picture.columns * factor)),
463              Math.max(1, Math.floor(picture.rows * factor)),
464            );
465      }),
466    );
467  }
468
469  const fits = shrinkFactor(treeBytes(pictures)) === 1;
470
471  return found.map((image, at) => {
472    const picture = fits ? pictures[at] : null;
473
474    return picture === null || picture === undefined ? text(image) : { id: image.id, alt: picture.alt, picture };
475  });
476}
477
478const pasted = new Map<string, Found[]>();
479const MEMORY_PASTED = 20;
480
481// The images pasted into a prompt row, looked up once per row.
482async function pastedOf($: EngineInterface, requestId: string, text: string): Promise<Found[]> {
483  const known = pasted.get(requestId);
484
485  if (known !== undefined) {
486    return known;
487  }
488
489  const found = pastedImagesOf(await $.session.messages({ as: "api" }), text, requestId);
490
491  if (found === null) {
492    return [];
493  }
494
495  pasted.set(requestId, found);
496
497  if (pasted.size > MEMORY_PASTED) {
498    pasted.delete(pasted.keys().next().value as string);
499  }
500
501  return found;
502}
503
504const DRAFT_POLL_MS = 400;
505// Where Claude Code keeps a pasted image from the moment it is pasted: `<root>/claude-<uid>/<project>/<session>/images`.
506const IMAGE_ROOT = "/tmp/";
507const MEMORY_DRAFT_FILES = 4;
508const draftPaths = new Map<string, string>();
509const draftFiles = new Map<string, Found>();
510let draftWatch: Timer | undefined;
511
512// Keeps `draftImagesAtom` equal to the images the prompt box holds. A paste fires no `prompt.edit`, so the box is read
513// on a timer.
514function watchDraft($: EngineInterface): void {
515  draftWatch ??= $.clock.every(DRAFT_POLL_MS, () => {
516    void (async () => {
517      const ids = draftImageIds((await $.prompt.read()).text);
518      const shown = await read($, draftImagesAtom);
519
520      if (ids.join() !== shown.join()) {
521        await update($, draftImagesAtom, () => ids);
522      }
523    })().catch(() => null);
524  });
525}
526
527// The pasted images of the draft as the files Claude Code wrote them to; the few read last are kept so a redraw does not
528// read them again.
529async function draftImagesOf($: EngineInterface, ids: readonly string[]): Promise<Found[]> {
530  const session = await $.session.id();
531  const keyOf = (id: string) => `${session}/${id}`;
532
533  if (ids.some((id) => !draftPaths.has(keyOf(id)))) {
534    const run = await $.process
535      .run(["find", IMAGE_ROOT, "-maxdepth", "5", "-path", `*/${session}/images/*.png`], { timeoutMs: 3000 })
536      .catch(() => null);
537
538    for (const path of run?.stdout.split("\n") ?? []) {
539      const name = path.slice(path.lastIndexOf("/") + 1, -".png".length);
540
541      if (name !== "") {
542        draftPaths.set(keyOf(name), path);
543      }
544    }
545  }
546
547  const found = await Promise.all(
548    ids.map(async (id): Promise<Found[]> => {
549      const key = keyOf(id);
550      const held = draftFiles.get(key);
551      const path = draftPaths.get(key);
552
553      if (held !== undefined) {
554        return [held];
555      }
556
557      const file = path === undefined ? undefined : await $.fs.read(path, { as: "bytes" }).catch(() => undefined);
558
559      if (file === undefined) {
560        return [];
561      }
562
563      const image = { id: `draft#${key}`, base64: file.base64, mediaType: "image/png", name: `Image ${id}` };
564
565      draftFiles.set(key, image);
566
567      if (draftFiles.size > MEMORY_DRAFT_FILES) {
568        draftFiles.delete(draftFiles.keys().next().value as string);
569      }
570
571      return [image];
572    }),
573  );
574
575  return found.flat();
576}
577
578async function pictureDir($: EngineInterface): Promise<string> {
579  return `${((await $.env.get("TMPDIR")) ?? "/tmp").replace(/[\\/]+$/, "")}/veneer-pictures`;
580}
581
582// Creates the picture folder and drops pictures a week old.
583async function prepareFolder($: EngineInterface): Promise<void> {
584  const dir = await pictureDir($);
585
586  await $.process.run(["mkdir", "-p", dir], { timeoutMs: 2000 }).catch(() => null);
587  await $.process
588    .run(["find", dir, "-type", "f", "-name", "*.png", "-mtime", "+7", "-delete"], { timeoutMs: 5000 })
589    .catch(() => null);
590}
591
592// What this terminal cannot draw: icons by the setting and the terminal, links wherever pictures are off.
593async function plainOf($: EngineInterface): Promise<Plain> {
594  const [icons, links] = await Promise.all([read($, plainIconsAtom), read($, plainLinksAtom)]);
595
596  return { icons, links };
597}
598
599async function settle($: EngineInterface, { icons, links }: Pick<Config, "icons" | "links">): Promise<Off | null> {
600  const env = {
601    force: await $.env.get("CLAUDE_CODE_FORCE_TERMINAL_IMAGES"),
602    tmux: await $.env.get("TMUX"),
603    program: await $.env.get("TERM_PROGRAM"),
604    term: await $.env.get("TERM"),
605    kittyWindow: await $.env.get("KITTY_WINDOW_ID"),
606    weztermExecutable: await $.env.get("WEZTERM_EXECUTABLE"),
607    ghosttyResources: await $.env.get("GHOSTTY_RESOURCES_DIR"),
608  };
609  const terminal = terminalOff(env);
610  const probe =
611    terminal === null ? await $.process.run(["resvg", "--version"], { timeoutMs: 2000 }).catch(() => null) : null;
612  const off = terminal ?? (probe?.exitCode === 0 ? null : "resvg");
613
614  await update($, offAtom, () => off);
615  await update($, plainIconsAtom, () => iconsArePlain(icons, env));
616  await update($, plainLinksAtom, () => linksArePlain(links, env));
617
618  const chosen = await $.store.get(SYNTAX_KEY);
619
620  await update($, syntaxAtom, () => (typeof chosen === "string" ? chosen : ""));
621  await $.command
622    .register({ name: PANE_ID, description: "Change Veneer's settings and syntax theme" })
623    .catch(() => null);
624  await $.command.register({ name: SETTINGS_COMMAND, description: "Change Veneer's settings" }).catch(() => null);
625  await $.command.register({ name: SYNTAX_COMMAND, description: "Choose the syntax theme for code" }).catch(() => null);
626  await refreshPalette($);
627
628  if (off === null) {
629    await prepareFolder($);
630  }
631
632  return off;
633}
634
635const configNow = async ($: EngineInterface): Promise<Config> => configOf(await read($, optionsAtom));
636
637// Takes the settings as `/config` holds them, which may be newer than the ones the plugin was registered with.
638async function seedOptions($: EngineInterface, options: PluginOptions): Promise<void> {
639  const rows = await $.config.list().catch(() => []);
640  const current = rows
641    .filter(({ key }) => key.startsWith(SETTINGS_PREFIX))
642    .map(({ key, value }) => [fieldOf(key), value] as const);
643
644  await update($, optionsAtom, () => ({ ...options, ...Object.fromEntries(current) }));
645}
646
647async function settingsOf($: EngineInterface): Promise<Setting[]> {
648  return (await $.config.list()).filter(({ key }) => key.startsWith(SETTINGS_PREFIX));
649}
650
651async function showSettings($: EngineInterface, pane: Partial<SettingsPane>): Promise<void> {
652  await update($, settingsPaneAtom, (current) => ({ ...current, ...pane }));
653}
654
655// Writes one setting the way `/config` does and takes it into effect. The terminal is settled again where the setting
656// decides what it draws with.
657async function writeSetting(
658  $: EngineInterface,
659  setting: Setting,
660  value: Setting["value"],
661): Promise<string | undefined> {
662  const { deny } = await $.config.set({ key: setting.key, value }).catch((error: unknown) => ({ deny: String(error) }));
663
664  if (deny !== undefined) {
665    return `${setting.label} was not changed: ${deny}`;
666  }
667
668  const field = fieldOf(setting.key);
669
670  await update($, optionsAtom, (current) => ({ ...current, [field]: value }));
671
672  if (field === "icons" || field === "links") {
673    await settle($, await configNow($));
674  }
675
676  return undefined;
677}
678
679async function applySetting($: EngineInterface, setting: Setting, value: Setting["value"]): Promise<void> {
680  await showSettings($, { editing: null, message: await writeSetting($, setting, value) });
681}
682
683// `/veneer <setting> <value>`: changes one setting without opening the pane. Bare `/veneer` opens the pane.
684async function runSettingsCommand($: EngineInterface, args: string): Promise<{ text?: string }> {
685  if (args.trim() === "") {
686    return openPane($, "settings");
687  }
688
689  const change = parseSettingChange(await settingsOf($), args);
690
691  if ("error" in change) {
692    return { text: change.error };
693  }
694
695  const failure = await writeSetting($, change.setting, change.value);
696
697  return {
698    text: failure ?? `${change.setting.label} set to ${valueText({ ...change.setting, value: change.value })}.`,
699  };
700}
701
702// A press on a setting: a switch or a choice moves on, and a typed setting turns into a field.
703async function changeSetting($: EngineInterface, setting: Setting): Promise<void> {
704  await (isTyped(setting)
705    ? showSettings($, { editing: setting.key, message: undefined })
706    : applySetting($, setting, nextValue(setting)));
707}
708
709async function submitSetting($: EngineInterface, setting: Setting, text: string): Promise<void> {
710  const value = setting.kind === "number" ? Number(text) : text.trim();
711
712  await (Number.isNaN(value)
713    ? showSettings($, { editing: null, message: `${setting.label} takes a number.` })
714    : applySetting($, setting, value));
715}
716
717// Shows a tab from its first step: no field open, no import half done, no theme previewed.
718async function switchTab($: EngineInterface, tab: Tab): Promise<void> {
719  await update($, tabAtom, () => tab);
720  await showPane($, LIST_PANE);
721  await showSettings($, CLOSED_SETTINGS);
722  await update($, syntaxPreviewAtom, () => null);
723}
724
725async function openPane($: EngineInterface, tab: Tab): Promise<{ text?: string }> {
726  await switchTab($, tab);
727
728  const opened = await $.ui.open({
729    id: PANE_ID,
730    title: "Veneer",
731    focus: true,
732    closeOnEscape: true,
733    rows: PANE_ROWS,
734    columns: PANE_COLUMNS,
735  });
736
737  return opened.isPlaced ? {} : { text: "The Veneer pane could not be shown: " + opened.reason };
738}
739
740export const register: Register = (on, options) => {
741  on("session.start", async ($, e, next) => {
742    await seedOptions($, options);
743
744    const off = await settle($, await configNow($));
745
746    if (off !== null) {
747      $.ui.toast(OFF_TEXT[off], { timeoutMs: NOTICE_MS });
748    }
749
750    watchDraft($);
751
752    return next(e);
753  });
754
755  // A reload of the mod starts no session, so the first edit to the prompt box starts the watch.
756  on("prompt.edit", ($, e, next) => {
757    watchDraft($);
758
759    return next(e);
760  });
761
762  // /clear, /resume and /branch reset the session's state and skip session.start.
763  on("classic.SessionStart", { source: ["clear", "resume", "fork"] }, async ($, e, next) => {
764    await seedOptions($, options);
765    await settle($, await configNow($));
766
767    return next(e);
768  });
769
770  on("prompt.compose", async ($, e, next) => {
771    const result = await next(e);
772    const isHeadless = e.surfaces.length === 0 || e.traits.includes("bare") || e.traits.includes("print");
773
774    return isHeadless || !(await configNow($)).diagramHint
775      ? result
776      : { sections: [...result.sections, { id: "veneer:diagrams", text: MERMAID_HINT, scope: "session" as const }] };
777  });
778
779  on("ui.render", { component: "UserMessage" }, async ($, e, next) => {
780    const { text, origin } = e.props;
781    const config = await configNow($);
782    const hasImages = config.images && text.includes(PASTED_MARKER);
783
784    if (
785      e.surface !== "terminal" ||
786      (!config.styleUserMessage && !hasImages) ||
787      origin.kind !== "composer" ||
788      text.trim() === ""
789    ) {
790      return next(e);
791    }
792
793    const found = hasImages ? await pastedOf($, e.requestId, text) : [];
794    const words = found.length > 0 ? withoutMarkers(text) : text;
795    const native = await next(words === text || words === "" ? e : { ...e, props: { ...e.props, text: words } });
796
797    if (native.type !== "engine") {
798      return native;
799    }
800
801    const ui = $.ui.resolve(e);
802    const columns = e.viewport?.columns ?? 100;
803    const withImages = async (row: RenderElement | null): Promise<RenderElement> => {
804      if (found.length === 0) {
805        return row ?? native;
806      }
807
808      const { Box } = ui;
809      const shown = await shownImages($, found, config, columns, "Image" in ui);
810
811      return (
812        <Box flexDirection="column">
813          {row}
814          {imageColumn(ui, shown, MARGIN, config.align === "right" ? "flex-end" : "flex-start")}
815        </Box>
816      );
817    };
818
819    if (words === "") {
820      return withImages(null);
821    }
822
823    if (!config.styleUserMessage) {
824      return withImages(native);
825    }
826
827    const copy = {
828      scope: `bubble:${e.requestId}`,
829      isPlain: await read($, plainIconsAtom),
830      onCopy: async () => {
831        const { isCopied } = await $.ui.copy({ text: words, surface: e.surface });
832
833        $.ui.toast(isCopied ? "Message copied" : "Copy failed");
834      },
835    };
836
837    return withImages(userBubble(ui, words, columns, config.align, copy));
838  });
839
840  on("ui.render", { component: "AssistantMessage" }, async ($, e, next) => {
841    const native = await next(e);
842    const { text, isFirstOfReply, isSummary } = e.props;
843
844    // A tree another mod returned is theirs; only core's own drawing is replaced.
845    if (e.surface !== "terminal" || native.type !== "engine" || isSummary === true || text.trim() === "") {
846      return native;
847    }
848
849    const ui = $.ui.resolve(e);
850    const segments = splitReply(text);
851    const bullet = isFirstOfReply ? BULLET : null;
852    const hasPictures = "Image" in ui && hasDrawn(segments);
853    const hasCode = segments.some((segment) => segment.kind === "code");
854    const [config, isPlain, off] = await Promise.all([
855      configNow($),
856      read($, plainIconsAtom),
857      hasPictures ? read($, offAtom) : null,
858    ]);
859    const isPictured = hasPictures && off === null;
860    const [fences, fenceBackground, palette, dir] = await Promise.all([
861      hasCode ? painterFor($).then((paint) => paintFences(paint, segments)) : undefined,
862      hasCode ? backgroundFor($, config, "fences") : undefined,
863      isPictured ? read($, paletteAtom) : undefined,
864      isPictured ? pictureDir($) : undefined,
865    ]);
866    const copyFor = (index: number, source: string, noun: string) => ({
867      scope: `copy:${e.requestId}:${index}`,
868      isPlain,
869      onCopy: async () => {
870        const { isCopied } = await $.ui.copy({ text: source, surface: e.surface });
871
872        $.ui.toast(isCopied ? `${noun} copied` : "Copy failed");
873      },
874    });
875    const drawn = new Map<Segment, { picture: Picture; alt: string }>();
876    const width = (e.viewport?.columns ?? 100) - GUTTER - 2 * MARGIN;
877    const diagramOf = (source: string) =>
878      diagramText(source, { columns: width - CARD_COLUMNS, ratio: config.cellRatio });
879
880    if (!isPictured || palette === undefined || dir === undefined) {
881      return replyTree(ui, segments, drawn, bullet, fences, fenceBackground, copyFor, width, diagramOf);
882    }
883
884    const font = { family: config.fontFamily, cellHeight: cellHeightOf(config.cellRatio) };
885    const available = Math.min(MAX_COLUMNS, width);
886    const io = pictureIo($);
887    const look = `${dir}|${available}|${font.family}|${font.cellHeight}|${hashOf(JSON.stringify(palette))}`;
888
889    await Promise.all(
890      segments.map(async (segment) => {
891        if (!wantsPicture(segment, config)) {
892          return;
893        }
894
895        const picture = await pictureFor(
896          io,
897          dir,
898          `${look}|${segment.kind}|${segment.raw}`,
899          () => sketchOf(segment, available, palette, font),
900          font,
901        );
902
903        if (picture !== null) {
904          drawn.set(segment, { picture, alt: picture.alt });
905        }
906      }),
907    );
908
909    return replyTree(ui, segments, drawn, bullet, fences, fenceBackground, copyFor, width, diagramOf);
910  });
911
912  on("ui.render", { component: "ToolUse" }, async ($, e, next) => {
913    if (e.props.tool === "Bash" || e.props.tool === "Read") {
914      rememberInput(e.props.tool_use_id, e.props.input);
915    }
916
917    const native = await next(e);
918    const { isRunning, isErrored, output } = e.props;
919
920    if (e.surface !== "terminal" || native.type !== "engine") {
921      return native;
922    }
923
924    const ui = $.ui.resolve(e);
925    const changes = !isRunning && !isErrored ? changeCounts(output) : null;
926    const [commandRuns, plain, cwd, isAnsi] = await Promise.all([
927      e.props.tool === "Bash" ? painterFor($).then((paint) => paintCommand(paint, e.props)) : undefined,
928      plainOf($),
929      $.session.cwd(),
930      changes === null ? undefined : read($, paletteAtom).then((palette) => palette.isAnsi),
931    ]);
932    const row = toolRow(ui, e.props, cwd, commandRuns, plain) ?? native;
933
934    return changes === null || isAnsi === undefined ? row : withBadges(ui, row, changes, isAnsi, plain.icons);
935  });
936
937  on("ui.render", { component: "ToolResult" }, async ($, e, next) => {
938    const native = await next(e);
939
940    if (e.surface !== "terminal" || native.type !== "engine" || e.props.isErrored) {
941      return native;
942    }
943
944    const found = imagesOf(e.props, pathOfCall(e.props.tool_use_id));
945
946    if (found.length > 0) {
947      const config = await configNow($);
948
949      if (!config.images) {
950        return native;
951      }
952
953      const ui = $.ui.resolve(e);
954      const { Box } = ui;
955      const shown = await shownImages($, found, config, e.viewport?.columns ?? 100, "Image" in ui);
956
957      return (
958        <Box flexDirection="column">
959          {native}
960          {imageColumn(ui, shown, MARGIN)}
961        </Box>
962      );
963    }
964
965    const { tool, output } = e.props;
966    const diff = parseDiff(output);
967    const lines = diff === null ? parseOutput(tool, output, await $.session.cwd()) : null;
968
969    if (diff === null && lines === null) {
970      return native;
971    }
972
973    const id = e.props.tool_use_id;
974    const path = tool === "Read" || diff !== null ? filePathOf(output) : undefined;
975    const [config, open, paint, palette] = await Promise.all([
976      configNow($),
977      read($, expandedAtom),
978      path !== undefined || tool === "Bash" || tool === "Grep" ? painterFor($) : undefined,
979      diff === null ? undefined : read($, paletteAtom),
980    ]);
981    const expanded = open.includes(id);
982    const toggle = () => flip($, id);
983    const ui = $.ui.resolve(e);
984    // A folded card shows its first lines only, so only those are tokenized; unfolding paints the rest.
985    const visible = expanded ? Infinity : MAX_LINES;
986
987    if (diff === null) {
988      const shown = lines ?? [];
989
990      if (paint === undefined) {
991        return outputCard(ui, shown, expanded, toggle, id);
992      }
993
994      const [painted, background] = await Promise.all([
995        path === undefined
996          ? paintOutput(paint, tool, commandOfCall(id), shown)
997          : paintLines(paint, path, shown.slice(0, visible)).then((head) => [...head, ...shown.slice(visible)]),
998        backgroundFor($, config, path === undefined ? "output" : "reads"),
999      ]);
1000
1001      return outputCard(ui, painted, expanded, toggle, id, outputFill(background, path !== undefined, painted));
1002    }
1003
1004    const [runs, background] = await Promise.all([
1005      path === undefined || paint === undefined
1006        ? []
1007        : paintDiff(paint, path, { ...diff, lines: diff.lines.slice(0, visible) }),
1008      backgroundFor($, config, "diffs"),
1009    ]);
1010
1011    return diffCard(ui, diff, palette?.isAnsi ?? false, expanded, toggle, id, runs, background);
1012  });
1013
1014  on("ui.render", { component: "Spinner" }, async ($, e, next) => {
1015    const native = await next(e);
1016
1017    if (e.surface !== "terminal" || !(await configNow($)).styleSpinner || native.type !== "engine") {
1018      return native;
1019    }
1020
1021    const { Box } = $.ui.resolve(e);
1022
1023    return (
1024      <Box marginLeft={MARGIN} marginRight={MARGIN}>
1025        {native}
1026      </Box>
1027    );
1028  });
1029
1030  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
1031    const native = await next(e);
1032    const ids = await read($, draftImagesAtom);
1033
1034    if (e.surface !== "terminal" || e.props.hasSurvey || native.type !== "engine" || ids.length === 0) {
1035      return native;
1036    }
1037
1038    const config = await configNow($);
1039
1040    if (!config.images) {
1041      return native;
1042    }
1043
1044    const ui = $.ui.resolve(e);
1045    const found = await draftImagesOf($, ids);
1046    const fit = { ...config, imageRows: Math.min(config.imageRows, Math.max(2, e.props.maxRows - 2)) };
1047    const shown = await shownImages($, found, fit, e.props.bodyColumns, "Image" in ui);
1048
1049    return imageColumn(ui, shown, MARGIN) ?? native;
1050  });
1051
1052  on("ui.render", { component: "ToolGroup" }, async ($, e, next) => {
1053    const native = await next(e);
1054
1055    if (e.surface !== "terminal" || native.type !== "engine" || e.props.isExpanded) {
1056      return native;
1057    }
1058
1059    const [config, expandedIds, cwd] = await Promise.all([configNow($), read($, expandedAtom), $.session.cwd()]);
1060    const open = new Set(expandedIds);
1061    const { calls } = e.props;
1062    const showsRows = calls.length === 1 || open.has(`group:${e.requestId}`);
1063    const paint =
1064      showsRows && calls.some((call) => call.tool === "Bash" || call.tool === "Grep") ? await painterFor($) : undefined;
1065    const commandRuns = await Promise.all(
1066      calls.map((call) => (paint === undefined ? undefined : paintCommand(paint, call))),
1067    );
1068    const paintedOutput = await Promise.all(
1069      calls.map(async (call) => {
1070        const lines =
1071          paint === undefined || call.isRunning ? null : parseOutput(call.tool, call.output, cwd, call.isErrored);
1072        const command = (call.input as { command?: unknown } | null | undefined)?.command;
1073
1074        return paint === undefined || lines === null || call.isErrored
1075          ? undefined
1076          : paintOutput(paint, call.tool, typeof command === "string" ? command : undefined, lines);
1077      }),
1078    );
1079
1080    const ui = $.ui.resolve(e);
1081    const columns = e.viewport?.columns ?? 100;
1082    const foundIn = calls.map((call, i) => {
1083      const path = (call.input as { file_path?: unknown } | null | undefined)?.file_path;
1084
1085      return {
1086        id: callIdOf(call, e.requestId, i),
1087        found: showsRows && config.images ? imagesOf(call, typeof path === "string" ? path : undefined) : [],
1088      };
1089    });
1090    const imageCalls = new Set(foundIn.filter(({ found }) => found.length > 0).map(({ id }) => id));
1091    const drawn = foundIn.map(({ id, found }) => (open.has(hiddenIdOf(id)) ? [] : found));
1092    const [reads, output, plain, shown] = await Promise.all([
1093      paint === undefined ? undefined : backgroundFor($, config, "reads"),
1094      paint === undefined ? undefined : backgroundFor($, config, "output"),
1095      plainOf($),
1096      shownImages($, drawn.flat(), config, columns, "Image" in ui),
1097    ]);
1098    let taken = 0;
1099    const images = drawn.map((found) => {
1100      const column = imageColumn(ui, shown.slice(taken, taken + found.length), 2);
1101
1102      taken += found.length;
1103
1104      return column;
1105    });
1106
1107    return toolGroup(
1108      ui,
1109      calls,
1110      e.requestId,
1111      cwd,
1112      { open, toggle: (id) => flip($, id) },
1113      commandRuns,
1114      paintedOutput,
1115      paint === undefined ? {} : { reads, output },
1116      plain,
1117      images,
1118      imageCalls,
1119    );
1120  });
1121
1122  on("command.run", { command: PANE_ID }, ($, e) => runSettingsCommand($, e.args));
1123
1124  on("command.run", { command: SETTINGS_COMMAND }, ($, e) => runSettingsCommand($, e.args));
1125
1126  on("command.run", { command: SYNTAX_COMMAND }, ($) => openPane($, "syntax"));
1127
1128  // The picker previews the theme its focus is on; the preview ends with the pane, however it closes. Moving the focus
1129  // off a field puts the row it replaced back.
1130  on("ui.focus", { component: "Pane", requestId: PANE_ID }, async ($, e, next) => {
1131    const result = await next(e);
1132    const value = e.element?.startsWith(THEME_KEY) ? e.element.slice(THEME_KEY.length) : undefined;
1133
1134    if (result.deny === undefined) {
1135      await update($, focusAtom, () => e.element ?? null);
1136
1137      const { editing } = await read($, settingsPaneAtom);
1138
1139      if (e.element !== undefined && editing !== null && e.element !== `${SETTING_KEY}${editing}`) {
1140        await showSettings($, { editing: null });
1141      }
1142
1143      if (e.element !== undefined && e.element !== PATH_KEY && (await read($, syntaxPaneAtom)).step === "path") {
1144        await showPane($, LIST_PANE);
1145      }
1146
1147      await update($, syntaxPreviewAtom, () =>
1148        value === undefined || value === NEW_THEME || value === POPULAR_THEME
1149          ? null
1150          : value === DEFAULT_THEME
1151            ? ""
1152            : value,
1153      );
1154    }
1155
1156    return result;
1157  });
1158
1159  on("ui.close", { id: PANE_ID }, async ($, e, next) => {
1160    await update($, syntaxPreviewAtom, () => null);
1161    await update($, focusAtom, () => null);
1162    await showSettings($, CLOSED_SETTINGS);
1163
1164    return next(e);
1165  });
1166
1167  // Where the pane is taller than its room the engine scrolls it on an arrow key and the focus stays put. A single-row
1168  // move by the keys walks the focus instead, which brings its element into view; past either end, and for the wheel and
1169  // the page keys, the pane scrolls as before.
1170  on("ui.scroll", { requestId: PANE_ID }, async ($, e, next) => {
1171    if (e.origin.kind !== "person" || e.pointer !== undefined || Math.abs(e.by) !== 1) {
1172      return next(e);
1173    }
1174
1175    const rows =
1176      (await read($, tabAtom)) === "settings"
1177        ? settingsKeys(groupSettings(await settingsOf($)))
1178        : paneKeys(await read($, syntaxPaneAtom), (await savedThemes($)).names, (await themesFolder($)) !== undefined);
1179    const keys = [...tabKeys, ...rows];
1180    const focused = await read($, focusAtom);
1181    const target = keys[(focused === null ? -1 : keys.indexOf(focused)) + e.by];
1182
1183    if (target === undefined) {
1184      return next(e);
1185    }
1186
1187    await $.ui.focus({ requestId: PANE_ID, key: target }).catch(() => null);
1188
1189    return {};
1190  });
1191
1192  on("ui.render", { component: "Pane", requestId: PANE_ID }, async ($, e, next) => {
1193    if (e.surface !== "terminal") {
1194      return next(e);
1195    }
1196
1197    const ui = $.ui.resolve(e);
1198    const tab = await read($, tabAtom);
1199    const select = (chosen: Tab) => void switchTab($, chosen);
1200
hooks/config.ts 78 lines
1import type { PluginOptions } from "claude-code";
2
3export type Config = {
4  align: "left" | "right";
5  fontFamily: string;
6  cellRatio: number;
7  backgrounds: Record<Backdrop, boolean>;
8  icons: "auto" | "nerd" | "plain";
9  links: "auto" | "link" | "text";
10  nativeGraphics: boolean;
11  images: boolean;
12  imageRows: number;
13  diagramHint: boolean;
14  styleUserMessage: boolean;
15  styleSpinner: boolean;
16};
17
18// The cards that may take the syntax theme's `editor.background`.
19export type Backdrop = "fences" | "reads" | "output" | "diffs";
20
21const BACKDROP_OPTIONS = {
22  fences: "fenceBackground",
23  reads: "readBackground",
24  output: "outputBackground",
25  diffs: "diffBackground",
26} as const satisfies Record<Backdrop, string>;
27
28// A switch that is on unless set to false, as a boolean or as the text a settings file may hold.
29const onUnlessFalse = (value: unknown): boolean => value !== false && value !== "false";
30
31// Tried in order after the configured font, so a blank or unknown name still draws in a sans-serif face.
32const FALLBACK_FONTS = [
33  "Arial",
34  "Helvetica Neue",
35  "Helvetica",
36  "Segoe UI",
37  "Liberation Sans",
38  "DejaVu Sans",
39  "Noto Sans",
40  "Roboto",
41];
42const DEFAULT_RATIO = 2.9;
43
44// A terminal cell's height over its width; anything outside what real terminals use keeps the default.
45const ratioOf = (value: unknown): number => {
46  const ratio = Number(value);
47
48  return ratio >= 1 && ratio <= 6 ? ratio : DEFAULT_RATIO;
49};
50
51const DEFAULT_IMAGE_ROWS = 14;
52
53// The tallest an image draws, in rows; anything outside 2 to 250 keeps the default.
54const imageRowsOf = (value: unknown): number => {
55  const rows = Math.floor(Number(value));
56
57  return rows >= 2 && rows <= 250 ? rows : DEFAULT_IMAGE_ROWS;
58};
59
60export const configOf = (options: PluginOptions): Config => ({
61  align: options.messageAlign === "right" ? "right" : "left",
62  fontFamily: [typeof options.fontFamily === "string" ? options.fontFamily.trim() : "", ...FALLBACK_FONTS]
63    .filter((font) => font !== "")
64    .join(", "),
65  cellRatio: ratioOf(options.cellRatio),
66  backgrounds: Object.fromEntries(
67    Object.entries(BACKDROP_OPTIONS).map(([card, option]) => [card, onUnlessFalse(options[option])]),
68  ) as Record<Backdrop, boolean>,
69  icons: options.icons === "nerd" || options.icons === "plain" ? options.icons : "auto",
70  links: options.links === "link" || options.links === "text" ? options.links : "auto",
71  nativeGraphics: options.nativeGraphics === true || options.nativeGraphics === "true",
72  images: onUnlessFalse(options.images),
73  imageRows: imageRowsOf(options.imageRows),
74  diagramHint: onUnlessFalse(options.diagramHint),
75  styleUserMessage: onUnlessFalse(options.styleUserMessage),
76  styleSpinner: onUnlessFalse(options.styleSpinner),
77});
78
hooks/gate.ts 70 lines
1import type { Off } from "../types";
2
3// The variables that say what the terminal is; each read where `$.env.get` can name it.
4export type TerminalEnv = {
5  force: string | undefined;
6  tmux: string | undefined;
7  program: string | undefined;
8  term: string | undefined;
9  kittyWindow: string | undefined;
10  weztermExecutable: string | undefined;
11  ghosttyResources: string | undefined;
12};
13
14export const OFF_TEXT: Record<Off, string> = {
15  tmux: "Images are not supported in this tmux session. Falling back to text replacements.",
16  terminal: "Images are not supported in this session. Falling back to text replacements.",
17  resvg: "Images need resvg (brew install resvg). Falling back to text replacements.",
18};
19
20// Terminals that carry their own symbol font, by `TERM_PROGRAM` and by `TERM`.
21const SYMBOL_PROGRAMS = new Set(["ghostty", "WezTerm", "rio"]);
22const SYMBOL_TERMS = new Set(["xterm-ghostty", "xterm-kitty", "wezterm", "rio"]);
23
24// Claude Code draws pictures with kitty Unicode placeholders and turns them on only in kitty and Ghostty. WezTerm, Rio
25// and Warp show an image's alt text instead.
26const PICTURE_PROGRAMS = new Set(["ghostty"]);
27const PICTURE_TERMS = new Set(["xterm-ghostty", "xterm-kitty"]);
28
29// Pictures are drawn in kitty and Ghostty, and not inside a multiplexer unless forced.
30export function terminalOff(env: TerminalEnv): Off | null {
31  if (env.force === "1") {
32    return null;
33  }
34
35  if (env.tmux) {
36    return "tmux";
37  }
38
39  const draws =
40    PICTURE_PROGRAMS.has(env.program ?? "") ||
41    PICTURE_TERMS.has(env.term ?? "") ||
42    env.kittyWindow !== undefined ||
43    env.ghosttyResources !== undefined;
44
45  return draws ? null : "terminal";
46}
47
48// Terminals that carry their own symbol font, so the Nerd Font icons draw with nothing installed. Ghostty's resources
49// folder variable, like the kitty and WezTerm ones, outlives a multiplexer that rewrites `TERM_PROGRAM` and `TERM`.
50export const hasSymbolFont = (env: TerminalEnv): boolean =>
51  SYMBOL_PROGRAMS.has(env.program ?? "") ||
52  SYMBOL_TERMS.has(env.term ?? "") ||
53  env.kittyWindow !== undefined ||
54  env.weztermExecutable !== undefined ||
55  env.ghosttyResources !== undefined;
56
57// Terminals where a file path is shown in full as plain text and not as a link. Claude Code prints the address beside the
58// text of a link in a terminal it does not know to open links. Rio finds the path in the text and opens it itself, and
59// Terminal.app opens neither a link nor a path.
60const PLAIN_LINK_PROGRAMS = new Set(["rio", "Apple_Terminal"]);
61
62// Whether a file path is plain text: always when the setting is `text`, never when it is `link`, and by the terminal when
63// it is `auto`.
64export const linksArePlain = (setting: "auto" | "link" | "text", env: TerminalEnv): boolean =>
65  setting === "text" || (setting === "auto" && (PLAIN_LINK_PROGRAMS.has(env.program ?? "") || env.term === "rio"));
66
67// The icons to draw: Nerd Font ones when the setting is `nerd`, or `auto` in a terminal with its own symbol font.
68export const iconsArePlain = (setting: "auto" | "nerd" | "plain", env: TerminalEnv): boolean =>
69  setting === "plain" || (setting === "auto" && !hasSymbolFont(env));
70
hooks/badge.tsx 62 lines
1import type { ElementTable, RenderElement } from "claude-code";
2
3import { hunksOf } from "./diff";
4
5type Ui = Pick<ElementTable, "Box" | "Text">;
6
7export type Changes = { added: number; removed: number };
8
9const ANSI_TEXT = "#000000";
10
11// Powerline half circles, which Ghostty and kitty draw without any font installed.
12const LEFT_CAP = "";
13const RIGHT_CAP = "";
14
15// Added and removed line counts from an edit's stored result, or null when it holds no change.
16export function changeCounts(output: unknown): Changes | null {
17  const patches = hunksOf(output);
18
19  if (patches === null) {
20    return null;
21  }
22
23  const lines = patches.flatMap((patch) => (Array.isArray(patch?.lines) ? (patch.lines as unknown[]) : []));
24  const added = lines.filter((line) => typeof line === "string" && line.startsWith("+")).length;
25  const removed = lines.filter((line) => typeof line === "string" && line.startsWith("-")).length;
26
27  return added + removed === 0 ? null : { added, removed };
28}
29
30// The native row with a pill for the lines added and one for the lines removed, on the row's own first line. Fills and
31// text are theme tokens, so a pill matches Claude Code's own diff on every theme, colour-blind ones included. On the
32// ansi themes the success and error colours are the diff fills' own, so the text is a fixed black, which the terminal's
33// own palette cannot wash out as it does white on those fills. In plain mode, for terminals that do not draw Powerline
34// glyphs, a pill is a filled block with square ends.
35export function withBadges(
36  { Box, Text }: Ui,
37  native: RenderElement,
38  changes: Changes,
39  isAnsi: boolean,
40  isPlain = false,
41): RenderElement {
42  const plain = isAnsi ? ANSI_TEXT : null;
43
44  const pill = (label: string, fill: string, color: string) => (
45    <Text key={label}>
46      {isPlain ? null : <Text color={fill}>{LEFT_CAP}</Text>}
47      <Text color={color} backgroundColor={fill} bold>{` ${label} `}</Text>
48      {isPlain ? null : <Text color={fill}>{RIGHT_CAP}</Text>}
49    </Text>
50  );
51
52  return (
53    <Box flexDirection="row">
54      <Box flexShrink={1}>{native}</Box>
55      <Box flexShrink={0} marginTop={1} marginLeft={1} marginRight={1} gap={1}>
56        {changes.added > 0 ? pill(`+${changes.added}`, "diffAdded", plain ?? "success") : null}
57        {changes.removed > 0 ? pill(`-${changes.removed}`, "diffRemoved", plain ?? "error") : null}
58      </Box>
59    </Box>
60  );
61}
62
hooks/diff.tsx 135 lines
1import type { ElementTable, RenderElement } from "claude-code";
2
3import { foldButton, MAX_LINES, TAB } from "./fold";
4import { MARGIN } from "./reply";
5import { lineChildren } from "./syntax/runs";
6import type { StyledRun } from "./syntax/types";
7
8type Ui = Pick<ElementTable, "Box" | "Text" | "Button">;
9
10export type DiffLine = {
11  kind: "add" | "remove" | "context";
12  text: string;
13  oldNumber: number | null;
14  newNumber: number | null;
15};
16
17export type Diff = { lines: DiffLine[]; breaks: ReadonlySet<number>; created?: boolean };
18
19type Hunk = { oldStart?: number; newStart?: number; lines?: unknown };
20
21// The hunks of an edit's stored result. A newly created file stores no patch, only its content, so that becomes one hunk
22// of added lines.
23export function hunksOf(output: unknown): Hunk[] | null {
24  const result = output as { type?: unknown; content?: unknown; structuredPatch?: unknown } | null | undefined;
25
26  if (Array.isArray(result?.structuredPatch) && result.structuredPatch.length > 0) {
27    return result.structuredPatch as Hunk[];
28  }
29
30  if (result?.type === "create" && typeof result.content === "string" && result.content !== "") {
31    const lines = result.content.replace(/\n$/, "").split("\n");
32
33    return [{ oldStart: 0, newStart: 1, lines: lines.map((line) => `+${line}`) }];
34  }
35
36  return null;
37}
38
39// The stored patch of an edit as numbered lines, with the indexes where a new hunk starts. Null when it holds none.
40export function parseDiff(output: unknown): Diff | null {
41  const patch = hunksOf(output);
42
43  if (patch === null) {
44    return null;
45  }
46
47  const lines: DiffLine[] = [];
48  const breaks = new Set<number>();
49
50  for (const hunk of patch) {
51    let oldNumber = hunk.oldStart ?? 1;
52    let newNumber = hunk.newStart ?? 1;
53
54    if (lines.length > 0) {
55      breaks.add(lines.length);
56    }
57
58    for (const raw of Array.isArray(hunk.lines) ? hunk.lines : []) {
59      if (typeof raw !== "string") {
60        continue;
61      }
62
63      const text = raw.slice(1).replace(/\t/g, TAB);
64
65      if (raw.startsWith("+")) {
66        lines.push({ kind: "add", text, oldNumber: null, newNumber: newNumber++ });
67      } else if (raw.startsWith("-")) {
68        lines.push({ kind: "remove", text, oldNumber: oldNumber++, newNumber: null });
69      } else {
70        lines.push({ kind: "context", text, oldNumber: oldNumber++, newNumber: newNumber++ });
71      }
72    }
73  }
74
75  const created = (output as { type?: unknown } | null | undefined)?.type === "create";
76
77  return lines.some((line) => line.kind !== "context") ? { lines, breaks, created } : null;
78}
79
80// The edit as a rounded card of numbered lines. A changed line's code is filled with the theme's diff token, so it matches
81// Claude Code's own diff on every theme, and the fill starts right of its number. Like Claude Code's own diff there is
82// one number column, coloured on changed lines in the line's own fill colour, as the badges are filled: the line's
83// new number, or its old one where it was removed. The ansi themes draw the diff without fills, so there the numbers
84// and text take the success and error colours. A background fills the card under the lines; changed lines keep their fill.
85export function diffCard(
86  ui: Ui,
87  diff: Diff,
88  isAnsi: boolean,
89  expanded: boolean,
90  toggle: () => void,
91  id: string,
92  runs: readonly (StyledRun[] | undefined)[] = [],
93  background?: string,
94): RenderElement {
95  const { Box, Text } = ui;
96  const shown = expanded ? diff.lines : diff.lines.slice(0, MAX_LINES);
97  const numberOf = (line: DiffLine) => line.newNumber ?? line.oldNumber;
98  const digits = Math.max(1, ...shown.map((line) => String(numberOf(line) ?? "").length));
99  const plainLines = diff.created === true;
100  const tone = (kind: DiffLine["kind"]) =>
101    plainLines ? undefined : kind === "add" ? "success" : kind === "remove" ? "error" : undefined;
102  const fillOf = (kind: DiffLine["kind"]) =>
103    isAnsi || plainLines ? undefined : kind === "add" ? "diffAdded" : kind === "remove" ? "diffRemoved" : undefined;
104  const numberTone = (kind: DiffLine["kind"]) => (isAnsi ? tone(kind) : fillOf(kind));
105
106  return (
107    <Box
108      flexDirection="column"
109      marginLeft={MARGIN}
110      marginRight={MARGIN}
111      borderStyle="round"
112      borderColor="subtle"
113      backgroundColor={background}
114    >
115      {shown.map((line, i) => (
116        <Box key={`line-${i}`} flexDirection="column">
117          {diff.breaks.has(i) ? <Text dimColor>{`${" ".repeat(digits + 2)}⋯`}</Text> : null}
118          <Box flexDirection="row">
119            <Text
120              color={numberTone(line.kind)}
121              dimColor={line.kind === "context" || plainLines}
122            >{` ${String(numberOf(line) ?? "").padStart(digits)} `}</Text>
123            <Box flexGrow={1} flexShrink={1} paddingLeft={1} backgroundColor={fillOf(line.kind)}>
124              <Text color={isAnsi ? tone(line.kind) : undefined} wrap="wrap">
125                {lineChildren(ui, line.text, runs[i])}
126              </Text>
127            </Box>
128          </Box>
129        </Box>
130      ))}
131      {foldButton(ui, diff.lines.length, expanded, toggle, id)}
132    </Box>
133  );
134}
135
hooks/fold.tsx 32 lines
1import type { ElementTable, RenderElement } from "claude-code";
2
3type Ui = Pick<ElementTable, "Box" | "Button" | "Text">;
4
5// Lines drawn before the rest is folded into a count.
6export const MAX_LINES = 24;
7export const TAB = "    ";
8
9// The line under a folded card that shows the rest when pressed, and folds it again. Null when everything fits. The id
10// keeps the key of one card's button apart from another's in the same tree.
11export function foldButton(
12  { Box, Button, Text }: Ui,
13  total: number,
14  expanded: boolean,
15  toggle: () => void,
16  id: string,
17) {
18  if (total <= MAX_LINES) {
19    return null;
20  }
21
22  return (
23    <Box paddingLeft={1}>
24      <Button key={`fold:${id}`} plain onPress={toggle}>
25        <Text color="claude">
26          {expanded ? "Show fewer lines" : `Show ${total - MAX_LINES} more line${total - MAX_LINES === 1 ? "" : "s"}`}
27        </Text>
28      </Button>
29    </Box>
30  ) as RenderElement;
31}
32
hooks/group.tsx 169 lines
1import type { ElementTable, RenderElement } from "claude-code";
2
3import { outputCard, parseOutput } from "./output";
4import type { OutputLine } from "./output";
5import { outputFill } from "./paint";
6import { MARGIN } from "./reply";
7import { lineChildren } from "./syntax/runs";
8import type { StyledRun } from "./syntax/types";
9import type { Look, Plain, ToolCall } from "./tool-row";
10import { inputOf, lookFor, NOT_PLAIN, pathHover, pathOf, shortPath, toneOf } from "./tool-row";
11
12type Ui = Pick<ElementTable, "Box" | "Button" | "Link" | "Text">;
13
14export type GroupCall = ToolCall;
15
16// Which entries are open, by id, and the press that flips one.
17export type Folds = { open: ReadonlySet<string>; toggle: (id: string) => void };
18
19type Tone = ReturnType<typeof toneOf>;
20type Segment = { look: Look; count: number; tone: Tone };
21
22const SEVERITY: readonly Tone[] = ["success", "suggestion", "error"];
23
24// The calls as one segment per tool name, in the order each first appears. A segment takes the worst colour of its calls:
25// the error colour if one failed, else the running colour if one still runs.
26function segmentsOf(calls: readonly GroupCall[], isPlain: boolean): Segment[] {
27  const found = new Map<string, Segment>();
28
29  for (const call of calls) {
30    const look = lookFor(call.tool, isPlain);
31    const segment = found.get(look.label) ?? { look, count: 0, tone: "success" as Tone };
32    const tone = toneOf(call);
33
34    found.set(look.label, {
35      ...segment,
36      count: segment.count + 1,
37      tone: SEVERITY.indexOf(tone) > SEVERITY.indexOf(segment.tone) ? tone : segment.tone,
38    });
39  }
40
41  return [...found.values()];
42}
43
44// The id a call's row is kept open or shut by.
45export const callIdOf = (call: Pick<GroupCall, "tool_use_id">, groupId: string, index: number): string =>
46  `call:${call.tool_use_id ?? `${groupId}:${index}`}`;
47
48// The id that is in `open` while the images of a call are folded away.
49export const hiddenIdOf = (callId: string): string => `hidden:${callId}`;
50
51// A run of finished calls as one line of counts, `Command 2  Read 3`, which opens into a row for each call, and each row
52// that has output opens into its card. A run of one call has nothing to count, so it is drawn as its row. The whole line takes the text colour while the pointer is on it. A path stays a
53// link beside its row's button, so a click on it opens the file and a click on the rest folds the row. The images a
54// call returned, drawn by the caller, sit under its row; a click on the row of a call in `imageCalls` folds them away
55// and shows them again.
56export function toolGroup(
57  { Box, Button, Link, Text }: Ui,
58  calls: readonly GroupCall[],
59  id: string,
60  cwd: string,
61  { open, toggle }: Folds,
62  detailRuns: readonly (StyledRun[] | undefined)[] = [],
63  paintedOutput: readonly (OutputLine[] | undefined)[] = [],
64  fills: { reads?: string; output?: string } = {},
65  plain: Plain = NOT_PLAIN,
66  images: readonly (RenderElement | null)[] = [],
67  imageCalls: ReadonlySet<string> = new Set(),
68): RenderElement {
69  const fillOf = (tool: string, lines: readonly OutputLine[]) =>
70    tool === "Read"
71      ? fills.reads
72      : tool === "Bash" || tool === "Grep"
73        ? outputFill(fills.output, false, lines)
74        : undefined;
75  const iconGap = plain.icons ? " " : "  ";
76  const groupId = `group:${id}`;
77  const groupOpen = open.has(groupId);
78  const single = calls.length === 1;
79  const lit = (scope: string) =>
80    ({ scope, color: "text", dimColor: false, backgroundColor: "userMessageBackground", inverse: false }) as const;
81  const summaryLit = lit(groupId);
82
83  const summary = (
84    <Box flexDirection="row" marginTop={1} marginLeft={MARGIN} marginRight={MARGIN}>
85      <Button key={groupId} plain hover={summaryLit} onPress={() => toggle(groupId)}>
86        {segmentsOf(calls, plain.icons).flatMap((segment, i) => {
87          const { tone } = segment;
88
89          return [
90            <Text key={`icon-${i}`} color={tone} hover={summaryLit}>{`${segment.look.icon}${iconGap}`}</Text>,
91            <Text key={`label-${i}`} color={tone} bold hover={summaryLit}>{`${segment.look.label} `}</Text>,
92            <Text key={`count-${i}`} color={tone} hover={summaryLit}>{`${segment.count}  `}</Text>,
93          ];
94        })}
95      </Button>
96    </Box>
97  );
98
99  if (!single && !groupOpen) {
100    return summary;
101  }
102
103  const rows = calls.map((call, i) => {
104    const callId = callIdOf(call, id, i);
105    const look = lookFor(call.tool, plain.icons);
106    const input = inputOf(call.input);
107    const detail = look.detail(input);
108    const path = pathOf(look, input);
109    const tone = toneOf(call);
110    const lines = call.isRunning
111      ? null
112      : (paintedOutput[i] ?? parseOutput(call.tool, call.output, cwd, call.isErrored));
113    const callOpen = lines !== null && open.has(callId);
114    const rowLit = lit(callId);
115    const moreId = `more:${callId}`;
116    const press = () => {
117      if (lines !== null) {
118        toggle(callId);
119      } else if (imageCalls.has(callId)) {
120        toggle(hiddenIdOf(callId));
121      }
122    };
123
124    return (
125      <Box key={callId} flexDirection="column" marginLeft={single ? 2 : 4} marginTop={single ? 1 : 0}>
126        <Box flexDirection="row" gap={2}>
127          <Button key={`row:${callId}`} plain hover={rowLit} onPress={press}>
128            <Text key="icon" color={tone} dimColor={call.isRunning} hover={rowLit}>{`${look.icon}${iconGap}`}</Text>
129            <Text key="label" color={tone} bold hover={rowLit}>
130              {look.label}
131            </Text>
132            {detail === undefined || path !== undefined ? null : (
133              <Text key="detail" dimColor wrap="truncate-end" hover={rowLit}>
134                {"  "}
135                {lineChildren({ Text }, detail, detailRuns[i], rowLit)}
136              </Text>
137            )}
138          </Button>
139          {detail === undefined || path === undefined ? null : (
140            <Text dimColor wrap="truncate-end" hover={plain.links ? undefined : pathHover(callId)}>
141              {plain.links ? detail : <Link href={`file://${encodeURI(path)}`}>{shortPath(detail, cwd)}</Link>}
142            </Text>
143          )}
144        </Box>
145        {callOpen ? (
146          <Box marginLeft={2} flexDirection="column">
147            {outputCard(
148              { Box, Button, Text },
149              lines,
150              open.has(moreId),
151              () => toggle(moreId),
152              callId,
153              fillOf(call.tool, lines),
154            )}
155          </Box>
156        ) : null}
157        {images[i] ?? null}
158      </Box>
159    );
160  });
161
162  return (
163    <Box flexDirection="column">
164      {single ? null : summary}
165      {rows}
166    </Box>
167  );
168}
169
hooks/heading.ts 20 lines
1import type { Palette } from "../types";
2import type { Heading } from "./markdown";
3import { CELL_WIDTH, fill, svgDocument } from "./picture";
4import type { Font, Sketch } from "./picture";
5import { escapeXml, measure, wrap } from "./svg-text";
6
7// Type size by heading level; each fits one cell row at the default proportion.
8const SIZES = [46, 40, 34, 31];
9
10// A heading as a one-row picture, as wide as its text up to `availColumns`.
11export function headingSketch(heading: Heading, availColumns: number, palette: Palette, font: Font): Sketch {
12  const size = SIZES[heading.level - 1] ?? SIZES[SIZES.length - 1]!;
13  const width = Math.min(availColumns * CELL_WIDTH, Math.ceil(measure(heading.text, size) * 1.06) + CELL_WIDTH);
14  const columns = Math.max(1, Math.ceil(width / CELL_WIDTH));
15  const [text = ""] = wrap(heading.text, columns * CELL_WIDTH, size, 1);
16  const body = `<text x="0" y="${font.cellHeight / 2 + size * 0.35}" font-size="${size}" font-weight="bold" ${fill(heading.level <= 2 ? palette.accent : palette.text)}>${escapeXml(text)}</text>`;
17
18  return { svg: svgDocument(columns, 1, font.cellHeight, font.family, body), columns, rows: 1, alt: heading.text };
19}
20
hooks/math.ts 47 lines
1import type { Palette } from "../types";
2import { CELL_WIDTH, fill, rowsFor, svgDocument } from "./picture";
3import type { Font, Sketch } from "./picture";
4import { texToSvg } from "./vendor/math-svg.js";
5
6// Type size as a share of the cell height, and the room around an equation.
7const SIZE_RATIO = 0.62;
8const INDENT = 2 * CELL_WIDTH;
9const PAD_RATIO = 0.5;
10const UNITS_PER_EM = 1000;
11
12const VIEW_BOX = /viewBox="(-?[\d.]+) (-?[\d.]+) ([\d.]+) ([\d.]+)"/;
13const ROOT = /^<svg\b[^>]*>([\s\S]*)<\/svg>$/;
14
15// Display math as a picture, indented, in the theme's text colour and as large as fits `availColumns`. Null where
16// MathJax cannot read the TeX, so it is left to the text fallback.
17export function mathSketch(tex: string, availColumns: number, palette: Palette, font: Font): Sketch | null {
18  let svg: string;
19
20  try {
21    svg = texToSvg(tex, true);
22  } catch {
23    return null;
24  }
25
26  const box = VIEW_BOX.exec(svg)?.slice(1).map(Number);
27  const body = ROOT.exec(svg.trim())?.[1];
28
29  if (box === undefined || body === undefined || box.length !== 4) {
30    return null;
31  }
32
33  const [, , boxWidth = 0, boxHeight = 0] = box;
34  const em = font.cellHeight * SIZE_RATIO;
35  const room = availColumns * CELL_WIDTH - INDENT;
36  const scale = Math.min(1, room / ((boxWidth * em) / UNITS_PER_EM));
37  const width = (boxWidth * em * scale) / UNITS_PER_EM;
38  const height = (boxHeight * em * scale) / UNITS_PER_EM;
39  const columns = Math.min(availColumns, Math.ceil((INDENT + width) / CELL_WIDTH));
40  const rows = rowsFor(height + font.cellHeight * PAD_RATIO * 2, font.cellHeight);
41  const top = (rows * font.cellHeight - height) / 2;
42  const ink = body.replaceAll("currentColor", palette.text);
43  const nested = `<svg x="${INDENT}" y="${top}" width="${width}" height="${height}" viewBox="${box.join(" ")}" ${fill(palette.text)}>${ink}</svg>`;
44
45  return { svg: svgDocument(columns, rows, font.cellHeight, font.family, nested), columns, rows, alt: tex };
46}
47
hooks/image.ts 280 lines
1import { CELL_WIDTH, MAX_CELLS, svgDocument } from "./picture";
2import type { Font, Sketch } from "./picture";
3import { escapeXml } from "./svg-text";
4
5// An image a tool call returned or a prompt carried: an id unique in the session, its bytes as the model saw them, the
6// MIME type and a name to show. `size` is known up front when the tool reported it.
7export type Found = {
8  id: string;
9  base64: string;
10  mediaType: string;
11  name: string;
12  size?: Size;
13};
14
15export type Size = { width: number; height: number };
16
17// The marker a prompt's text holds in place of each image pasted into it.
18export const PASTED_MARKER = "[Image #";
19
20// The numbers of the images a draft holds, as its `[Image #n]` markers give them.
21export const draftImageIds = (draft: string): string[] =>
22  [...draft.matchAll(/\[Image #(\d+)\]/g)].flatMap((match) => (match[1] === undefined ? [] : [match[1]]));
23
24// A prompt's text without its image markers, which the pictures drawn under the row stand in for.
25export const withoutMarkers = (text: string): string => text.replace(/\[Image #\d+\][ \t]*/g, "").trim();
26
27const isRecord = (value: unknown): value is Record<string, unknown> =>
28  typeof value === "object" && value !== null && !Array.isArray(value);
29
30// The image a Messages API block holds, or nothing for any other block.
31function ofBlock(block: unknown, id: string, name: string): Found[] {
32  if (!isRecord(block) || block.type !== "image" || !isRecord(block.source)) {
33    return [];
34  }
35
36  const { type, media_type: mediaType, data } = block.source;
37
38  return type === "base64" && typeof mediaType === "string" && typeof data === "string"
39    ? [{ id, base64: data, mediaType, name }]
40    : [];
41}
42
43const baseName = (path: string): string => path.slice(path.lastIndexOf("/") + 1);
44
45function ofRead(id: string, path: string | undefined, output: unknown): Found[] {
46  if (!isRecord(output) || output.type !== "image" || !isRecord(output.file)) {
47    return [];
48  }
49
50  const { base64, type, dimensions } = output.file;
51
52  if (typeof base64 !== "string" || typeof type !== "string") {
53    return [];
54  }
55
56  const width = isRecord(dimensions) ? Number(dimensions.displayWidth) : NaN;
57  const height = isRecord(dimensions) ? Number(dimensions.displayHeight) : NaN;
58
59  return [
60    {
61      id: `${id}#0`,
62      base64,
63      mediaType: type,
64      name: path === undefined ? "image" : baseName(path),
65      size: width > 0 && height > 0 ? { width, height } : undefined,
66    },
67  ];
68}
69
70// The blocks of an MCP result: the list itself, or the `content` of a result object.
71const blocksOf = (output: unknown): unknown[] =>
72  Array.isArray(output) ? output : isRecord(output) && Array.isArray(output.content) ? output.content : [];
73
74function ofMcp(id: string, tool: string, output: unknown): Found[] {
75  const images = blocksOf(output).filter((block) => isRecord(block) && block.type === "image");
76  const name = tool.slice(tool.lastIndexOf("__") + 2);
77
78  return images.flatMap((block, at) => ofBlock(block, `${id}#${at}`, images.length > 1 ? `${name} ${at + 1}` : name));
79}
80
81// The images a finished tool call returned: a Read of an image file, or the image blocks of an MCP tool's result.
82export function imagesOf(call: { tool_use_id?: string; tool: string; output?: unknown }, path?: string): Found[] {
83  const { tool_use_id: id, tool, output } = call;
84
85  if (id === undefined) {
86    return [];
87  }
88
89  if (tool === "Read") {
90    return ofRead(id, path, output);
91  }
92
93  return tool.startsWith("mcp__") ? ofMcp(id, tool, output) : [];
94}
95
96// The images pasted into a prompt, from the conversation as the model reads it: those of the latest user message whose
97// text is the prompt's. A prompt row carries only its text, and the `[Image #n]` markers in it are numbered through the
98// session, so the text names its message. Null when no message holds the text, as before it is stored or after a
99// compaction dropped it.
100export function pastedImagesOf(
101  messages: ReadonlyArray<{ role: string; content: ReadonlyArray<unknown> }>,
102  text: string,
103  id: string,
104): Found[] | null {
105  const message = messages.findLast(
106    ({ role, content }) =>
107      role === "user" && content.some((block) => isRecord(block) && block.type === "text" && block.text === text),
108  );
109
110  if (message === undefined) {
111    return null;
112  }
113
114  const images = message.content.filter((block) => isRecord(block) && block.type === "image");
115
116  return images.flatMap((block, at) => ofBlock(block, `${id}#${at}`, `Image ${at + 1}`));
117}
118
119const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47];
120
121// An image file's size in pixels, read from its header; null for a format not known here or a header cut short.
122export function sizeOf(base64: string, mediaType: string): Size | null {
123  try {
124    const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
125    const at = (index: number) => bytes[index] ?? 0;
126    const big = (index: number) => (at(index) << 8) | at(index + 1);
127    const little = (index: number) => at(index) | (at(index + 1) << 8);
128
129    if (mediaType === "image/png" && PNG_SIGNATURE.every((byte, i) => at(i) === byte)) {
130      return { width: (big(16) << 16) | big(18), height: (big(20) << 16) | big(22) };
131    }
132
133    if (mediaType === "image/gif") {
134      return { width: little(6), height: little(8) };
135    }
136
137    if (mediaType === "image/jpeg") {
138      return jpegSize(bytes);
139    }
140
141    return mediaType === "image/webp" ? webpSize(bytes) : null;
142  } catch {
143    return null;
144  }
145}
146
147// The frame header of a JPEG: the first start-of-frame marker holds the height and then the width.
148function jpegSize(bytes: Uint8Array): Size | null {
149  const at = (index: number) => bytes[index] ?? 0;
150
151  for (let i = 2; i + 9 < bytes.length;) {
152    if (at(i) !== 0xff) {
153      i++;
154      continue;
155    }
156
157    const marker = at(i + 1);
158
159    if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
160      return { height: (at(i + 5) << 8) | at(i + 6), width: (at(i + 7) << 8) | at(i + 8) };
161    }
162
163    i += marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9) ? 2 : 2 + ((at(i + 2) << 8) | at(i + 3));
164  }
165
166  return null;
167}
168
169// The first chunk of a WebP file says its size in one of three layouts: lossy, lossless or extended.
170function webpSize(bytes: Uint8Array): Size | null {
171  const at = (index: number) => bytes[index] ?? 0;
172  const tag = String.fromCharCode(at(12), at(13), at(14), at(15));
173
174  if (tag === "VP8 ") {
175    return { width: (at(26) | (at(27) << 8)) & 0x3fff, height: (at(28) | (at(29) << 8)) & 0x3fff };
176  }
177
178  if (tag === "VP8L") {
179    return {
180      width: 1 + (((at(22) & 0x3f) << 8) | at(21)),
181      height: 1 + (((at(24) & 0x0f) << 10) | (at(23) << 2) | ((at(22) & 0xc0) >> 6)),
182    };
183  }
184
185  return tag === "VP8X"
186    ? {
187        width: 1 + (at(24) | (at(25) << 8) | (at(26) << 16)),
188        height: 1 + (at(27) | (at(28) << 8) | (at(29) << 16)),
189      }
190    : null;
191}
192
193// The cells a picture takes: its own size at 20 pixels a column, never wider than the room or taller than `maxRows`,
194// with its shape kept.
195export function boxFor(size: Size, available: number, maxRows: number, cellHeight: number) {
196  const tallest = Math.min(MAX_CELLS, maxRows);
197  let columns = Math.max(1, Math.min(available, Math.ceil(size.width / CELL_WIDTH)));
198  let rows = Math.ceil((columns * CELL_WIDTH * (size.height / size.width)) / cellHeight);
199
200  if (rows > tallest) {
201    rows = tallest;
202    columns = Math.max(1, Math.min(columns, Math.floor((rows * cellHeight * (size.width / size.height)) / CELL_WIDTH)));
203  }
204
205  return { columns, rows: Math.max(1, rows) };
206}
207
208// What the engine takes of the pictures in one tree, a little under its 2 MiB, so the PNGs of a row or a group share it.
209export const TREE_BYTES = 1.9 * 1024 * 1024;
210
211const SHRINK_MARGIN = 0.95;
212
213// The bytes of a base64 string once decoded.
214const bytesOf = (base64: string): number => Math.floor((base64.length * 3) / 4);
215
216// The bytes the pictures of one tree come to; a picture that could not be drawn counts nothing.
217export const treeBytes = (pictures: ReadonlyArray<{ png: string } | null>): number =>
218  pictures.reduce((sum, picture) => sum + (picture === null ? 0 : bytesOf(picture.png)), 0);
219
220// The scale for each side of a tree's pictures so that they fit the budget, 1 when they already do. A PNG's size follows
221// its pixel count, so a side scales with the square root of the overflow, less a margin for art that compresses worse
222// when it is smaller.
223export const shrinkFactor = (bytes: number): number =>
224  bytes <= TREE_BYTES ? 1 : Math.sqrt(TREE_BYTES / bytes) * SHRINK_MARGIN;
225
226const MEMORY_SIZES = 200;
227const sizes = new Map<string, Size | null>();
228
229// The size of an image: as the tool reported it, or read once from its header.
230export function sizeOfFound(found: Found): Size | null {
231  if (found.size !== undefined) {
232    return found.size;
233  }
234
235  const known = sizes.get(found.id);
236
237  if (known !== undefined) {
238    return known;
239  }
240
241  const size = sizeOf(found.base64, found.mediaType);
242
243  sizes.set(found.id, size);
244
245  if (sizes.size > MEMORY_SIZES) {
246    sizes.delete(sizes.keys().next().value as string);
247  }
248
249  return size;
250}
251
252// What the picture says where it cannot be drawn.
253export const altOf = ({ name }: Found, size: Size | null | undefined): string =>
254  size === null || size === undefined ? name : `${name} · ${size.width}×${size.height}`;
255
256// An SVG that holds the image inside the box of cells, shrunk to fit and centred, for `resvg` to decode and scale. Null
257// where the size is unknown.
258export function imageSketch(
259  found: Found,
260  available: number,
261  maxRows: number,
262  cellHeight: number,
263  font: Font,
264): Sketch | null {
265  const size = sizeOfFound(found);
266
267  if (size === null || size.width < 1 || size.height < 1) {
268    return null;
269  }
270
271  const { columns, rows } = boxFor(size, available, maxRows, cellHeight);
272  const width = columns * CELL_WIDTH;
273  const height = rows * cellHeight;
274  const image =
275    `<image x="0" y="0" width="${width}" height="${height}" preserveAspectRatio="xMidYMid meet" ` +
276    `href="data:${escapeXml(found.mediaType)};base64,${found.base64}"/>`;
277
278  return { svg: svgDocument(columns, rows, cellHeight, font.family, image), columns, rows, alt: altOf(found, size) };
279}
280
hooks/image-card.tsx 38 lines
1import type { ElementTable, RenderElement } from "claude-code";
2
3import type { Picture } from "./picture";
4
5type Ui = Pick<ElementTable, "Box" | "Text"> & Partial<Pick<Extract<ElementTable, { Image: unknown }>, "Image">>;
6
7// An image as drawn: its picture, or null where it can only be named.
8export type Shown = { id: string; alt: string; picture: Picture | null };
9
10// The images under a row, one under another. An image with no picture, or any image where the terminal has no `Image`
11// element, is its name and size in dim text.
12export function imageColumn(
13  { Box, Text, Image }: Ui,
14  shown: readonly Shown[],
15  margin: number,
16  alignSelf: "flex-start" | "flex-end" = "flex-start",
17): RenderElement | null {
18  if (shown.length === 0) {
19    return null;
20  }
21
22  return (
23    <Box flexDirection="column" marginLeft={margin} marginRight={margin} alignSelf={alignSelf}>
24      {shown.map(({ id, alt, picture }) =>
25        picture === null || Image === undefined ? (
26          <Text key={id} dimColor>
27            {alt}
28          </Text>
29        ) : (
30          <Box key={id} flexShrink={0}>
31            <Image source={{ png: picture.png }} columns={picture.columns} rows={picture.rows} alt={alt} />
32          </Box>
33        ),
34      )}
35    </Box>
36  );
37}
38
hooks/markdown.ts 198 lines
1import { inlineMath } from "./math-unicode";
2
3export type Align = "left" | "right" | "center";
4
5export type Table = { kind: "table"; header: string[]; align: Align[]; rows: string[][]; raw: string };
6
7export type Heading = { kind: "heading"; level: number; text: string; raw: string };
8
9export type Code = { kind: "code"; lang: string; code: string; raw: string };
10
11export type Math = { kind: "math"; tex: string; raw: string };
12
13export type Segment = { kind: "text"; text: string } | Table | Heading | Code | Math;
14
15const SEPARATOR = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
16const FENCE = /^(\s*)(`{3,}|~{3,})\s*([^\s`]*)/;
17
18const closesFence = (line: string, marker: string): boolean => {
19  const text = line.trim();
20
21  return text.length >= marker.length && text === marker[0]!.repeat(text.length);
22};
23const HEADING = /^ {0,3}(#{1,4})\s+(.+?)(?:\s+#+)?\s*$/;
24const MATH_OPEN = /^\s*(?:\$\$|\\\[|\\begin\{(?:equation|align|gather|multline|eqnarray)\*?\})/;
25const MATH_ENVIRONMENT = /^\s*\\begin\{([a-z]+\*?)\}/;
26
27// The display equation that starts on line `start`: its TeX, and the line it ends on. Null where it has not closed, as
28// while the reply streams, or where text follows it on its last line.
29function displayMath(lines: readonly string[], start: number): { tex: string; end: number } | null {
30  const rest = lines.slice(start).join("\n").trimStart();
31  const environment = MATH_ENVIRONMENT.exec(rest)?.[1];
32  const [open, close] =
33    environment !== undefined ? ["", `\\end{${environment}}`] : rest.startsWith("$$") ? ["$$", "$$"] : ["\\[", "\\]"];
34  const stop = rest.indexOf(close, open.length);
35
36  if (stop === -1) {
37    return null;
38  }
39
40  const consumed = rest.slice(0, stop + close.length);
41  const tail = rest.slice(consumed.length).split("\n")[0] ?? "";
42  const tex = environment === undefined ? rest.slice(open.length, stop).trim() : consumed;
43
44  return tex === "" || tail.trim() !== "" ? null : { tex, end: start + consumed.split("\n").length - 1 };
45}
46
47// Inline marks read as noise in a picture, where they cannot be styled.
48const plain = (text: string): string =>
49  inlineMath(text)
50    .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
51    .replace(/\*\*|__|`/g, "")
52    .replace(/\\\|/g, "|")
53    .trim();
54
55const cellsOf = (line: string): string[] =>
56  line
57    .trim()
58    .replace(/^\|/, "")
59    .replace(/(?<!\\)\|$/, "")
60    .split(/(?<!\\)\|/)
61    .map(plain);
62
63const alignOf = (cell: string): Align => {
64  const spec = cell.trim();
65
66  if (spec.startsWith(":") && spec.endsWith(":")) {
67    return "center";
68  }
69
70  return spec.endsWith(":") ? "right" : "left";
71};
72
73const MEMORY_REPLIES = 64;
74const splits = new Map<string, Segment[]>();
75
76// The reply as runs of text with each table, heading and closed code fence taken out as its own segment. A fence still
77// open, as while the reply streams, stays text with everything after it. A reply is split once however often it is
78// drawn.
79export function splitReply(markdown: string): Segment[] {
80  const known = splits.get(markdown);
81
82  if (known !== undefined) {
83    return known;
84  }
85
86  const segments = split(markdown);
87
88  splits.set(markdown, segments);
89
90  if (splits.size > MEMORY_REPLIES) {
91    splits.delete(splits.keys().next().value as string);
92  }
93
94  return segments;
95}
96
97function split(markdown: string): Segment[] {
98  const lines = markdown.split("\n");
99  const segments: Segment[] = [];
100  let text: string[] = [];
101
102  const flush = () => {
103    if (text.join("\n").trim() !== "") {
104      segments.push({ kind: "text", text: inlineMath(text.join("\n")) });
105    }
106
107    text = [];
108  };
109
110  for (let i = 0; i < lines.length; i++) {
111    const line = lines[i] ?? "";
112
113    const fence = FENCE.exec(line);
114
115    if (fence !== null) {
116      const marker = fence[2]!;
117      const close = lines.findIndex((other, at) => at > i && closesFence(other, marker));
118
119      if (close === -1) {
120        text.push(...lines.slice(i));
121        break;
122      }
123
124      const indent = fence[1]!.length;
125      const body = lines
126        .slice(i + 1, close)
127        .map((row) => row.slice(Math.min(indent, row.length - row.trimStart().length)));
128
129      flush();
130      segments.push({
131        kind: "code",
132        lang: fence[3]!.toLowerCase(),
133        code: body.join("\n"),
134        raw: lines.slice(i, close + 1).join("\n"),
135      });
136      i = close;
137      continue;
138    }
139
140    const math = MATH_OPEN.test(line) ? displayMath(lines, i) : null;
141
142    if (math !== null) {
143      flush();
144      segments.push({ kind: "math", tex: math.tex, raw: lines.slice(i, math.end + 1).join("\n") });
145      i = math.end;
146      continue;
147    }
148
149    const heading = HEADING.exec(line);
150
151    // The last line of the text may still be streaming; a line is final once another follows it.
152    if (heading !== null && i < lines.length - 1) {
153      flush();
154      segments.push({ kind: "heading", level: heading[1]!.length, text: plain(heading[2]!), raw: line });
155      continue;
156    }
157
158    const separator = lines[i + 1] ?? "";
159    const header = line.includes("|") && SEPARATOR.test(separator) ? cellsOf(line) : [];
160    const isTable = header.length > 1 && cellsOf(separator).length === header.length;
161
162    let end = i + 2;
163
164    while (isTable && end < lines.length && (lines[end] ?? "").includes("|") && (lines[end] ?? "").trim() !== "") {
165      end++;
166    }
167
168    // A table is final once a line that is not a row follows it; until then it may still be growing.
169    if (!isTable || end >= lines.length) {
170      text.push(line);
171      continue;
172    }
173
174    const fit = (cells: string[]) => Array.from({ length: header.length }, (_, col) => cells[col] ?? "");
175
176    flush();
177    segments.push({
178      kind: "table",
179      header,
180      align: fit(
181        separator
182          .trim()
183          .replace(/^\||\|$/g, "")
184          .split("|"),
185      ).map(alignOf),
186      rows: lines.slice(i + 2, end).map((row) => fit(cellsOf(row))),
187      raw: lines.slice(i, end).join("\n"),
188    });
189    i = end - 1;
190  }
191
192  flush();
193
194  return segments;
195}
196
197export const hasDrawn = (segments: readonly Segment[]): boolean => segments.some((segment) => segment.kind !== "text");
198