April 2026

Terminal Math

claude -p … | termath --stream
**Ampère–Maxwell law.** A changing electric field drives a magnetic fieldAmpère–Maxwell law. A changing electric field drives a magnetic field
just as a current does. In differential form,
$$\nabla \times \mathbf{H} = \mathbf{J} + \frac{\partial \mathbf{D}}{\partial t}$$
∂D
∇ × H = J + ────
∂t
where $\mathbf{J}$ is the free current density and $\partial \mathbf{D} / \partial t$where J is the free current density and ∂D / ∂t
is the displacement current. The roots of $ax^2 + bx + c = 0$ areis the displacement current. The roots of ax² + bx + c = 0 are
$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
− b ± √b² − 4ac
x = ─────────────────
2a
```python
def roots(a, b, c):
d = (b**2 - 4*a*c) ** 0.5 # $x$ stays literal here
return (-b + d) / (2*a), (-b - d) / (2*a)
```

Overview

Terminal Math renders LaTeX maths in the terminal. Give it a whole message, prose, Markdown, code and all, and only the maths changes: typeset Unicode in any terminal, ASCII where Unicode is unsafe, and real Computer Modern images where the terminal can show them. It’s a TypeScript library and CLI with no required dependencies.

The Problem

Language models write maths in LaTeX, because that’s how maths is written everywhere they learned it. In a browser that’s fine: the chat page runs KaTeX and the reader sees an equation. In a terminal nothing renders it, so an answer about Maxwell’s equations arrives as \frac{\partial \mathbf{D}}{\partial t} and the reader typesets it in their head.

More of that reading happens in a terminal every month, inside Claude Code, Codex, and tools built like them. The existing options either flatten maths into one line of substituted symbols, which breaks at the first fraction, or render images through matplotlib, which needs Python and fails outright where people actually read these answers.

The Rule

Change the maths and nothing else. Every character that isn’t maths comes out exactly as it went in.

That’s what makes the library safe to put between a model and a screen. It can take an entire assistant message without the caller deciding what’s maths first, and a code sample with a dollar sign in it, a Markdown table, or a line of prose survives byte for byte. The same rule shapes the output: the library returns strings and never writes to the terminal itself, unless you explicitly ask it to probe one.

Whole Messages

A scanner walks the input line by line and hands out typed segments: fenced code, Markdown tables, display maths in $$ or \[ \], inline maths in $ or \( \), inline code, and plain text. Every character lands in exactly one segment, so rejoining them gives back the input, and only the maths segments are touched on the way through.

If a piece of maths doesn’t parse, it’s left as the original LaTeX rather than guessed at, so a malformed expression costs a pretty rendering and never the content.

text
**Ampère–Maxwell law.** A changing electric field drives a magnetic field
just as a current does. In differential form,
display
$$\nabla \times \mathbf{H} = \mathbf{J} + \frac{\partial \mathbf{D}}{\partial t}$$
text + inline
where $\mathbf{J}$ is the free current density and $\partial \mathbf{D} / \partial t$
is the displacement current. The roots of $ax^2 + bx + c = 0$ are
display
$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
code
```python
def roots(a, b, c):
d = (b**2 - 4*a*c) ** 0.5 # $x$ stays literal here
return (-b + d) / (2*a), (-b - d) / (2*a)
```
Highlighted spans are typeset. Everything else, including the $x$ in the comment, comes back unchanged.segments rejoin to the input, byte for byte
Figure 1. The scanner tags every line with one kind of segment and picks out the maths inside prose. Only the highlighted spans are typeset.

The Ladder

Terminals vary more than any other display. So instead of one output format there’s a ladder, kitty, iterm2, sixel, unicode, ascii, and the library walks down it until it reaches a rung the destination can display. The image rungs are real typesetting; the text rungs are a two-dimensional layout built from characters. There is always a rung that works.

  1. kitty✓ shown
  2. iterm2
  3. sixel
  4. unicode
  5. ascii

kitty

∇×H=J+∂D∂t\nabla \times \mathbf{H} = \mathbf{J} + \frac{\partial \mathbf{D}}{\partial t}
Figure 2. The ladder, walked: each scenario steps down past the rungs it can’t use, and lands on one that works.

An image rung is skipped for concrete reasons: no rasteriser installed, output going to a pipe or a file, a screen session, tmux without passthrough, an agent host in between, or an equation wider than the window, since a clipped image loses what wrapped text would keep. Inline maths stays text even on an image rung, because an image can’t reliably sit on the baseline of the line around it, and text can still be selected and copied.

Agent Hosts

Claude Code and Codex are the obvious places for this to run, and exactly where images can’t work. Model output is data to these hosts, not bytes for the terminal, and their interfaces repaint over anything drawn beneath them. The terminal may speak kitty perfectly well; the host in between doesn’t.

So the library reports the host separately from the terminal, and refuses image modes whenever a host is present, saying why. termath --caps prints the whole decision.

~/notes
$ termath --caps
mode kitty
terminal ghostty (TERM=xterm-ghostty)
tty true
size 80x24
unicode true
image protocol kitty
multiplexer none
agent host none
rasteriser resvg
$ CLAUDECODE=1 termath --caps
mode unicode
terminal ghostty (TERM=xterm-ghostty)
tty true
size 80x24
unicode true
image protocol kitty
multiplexer none
agent host claude-code
rasteriser resvg
downgraded running inside claude-code, whose TUI repaints over inline graphics
Figure 3. The same terminal, with and without an agent host in between.

For those hosts there are two ways in. Their print modes write plain text, so claude -p "..." | termath --stream typesets the answer deterministically, with the model not involved at all. For interactive sessions, which can’t be piped, termath install-skill writes one skill directory both hosts scan on startup, telling the model to run its draft through termath before answering. It touches no settings files and removes cleanly.

Architecture

There are two renderers, not one, and they share everything up to the syntax tree. A tokenizer and a recursive-descent parser turn the LaTeX into an AST covering scripts, fractions, roots, font commands, scaled delimiters, big operators, matrices, cases, accents, and boxes. From there the text rungs and the image rungs go separate ways.

The split is the project’s main design decision, and it came from getting it wrong first. The early image path drew the character grid at high resolution, which produced monospace spacing and superscripts the size of the base, and it looked wrong the moment it wasn’t held to a grid. A grid asks what fits in a cell. A printed equation asks where a glyph belongs. Those are different questions, so they got different engines.

LaTeXfrom the scanner's maths segments
tokenizer → parserrecursive descent
ASTscripts, fractions, roots, matrices, cases…

Text renderer

Box gridstyled cells, a tracked baseline
hcat, vcatjoined on baselines
unicode · ascii

Image renderer

TeX layoutboxes in em, one flat space
SVGone pass, one y flip
resvg or sharpoptional rasteriser
kitty · iterm2 · sixel
Figure 4. One parser, two engines: a grid of characters for the text rungs, real typesetting for the image rungs.

The Grid

The text renderer lays maths out as a Box: a grid of styled cells with a tracked baseline. Everything composes from a few primitives, and the important one is hcat, which joins boxes side by side aligned on their baselines, not their tops. That’s the whole reason J + sits level with the fraction bar in ∂D/∂t instead of with its numerator.

J +
∂D──∂t
✗ Joined on their tops
J +
∂D──∂t
✓ Joined on their baselines
Figure 5. Why hcat joins on baselines: aligned on their tops, the J + floats at the numerator.
export function hcat(boxes: Box[], gap = 0): Box {
	const nonEmpty = boxes.filter((b) => b.width > 0 || b.height > 0);
	if (nonEmpty.length === 0) return blankBox(0, 1, 0);

	let above = 0;
	let below = 0;
	for (const b of nonEmpty) {
		if (b.baseline > above) above = b.baseline;
		const bel = b.height - b.baseline - 1;
		if (bel > below) below = bel;
	}
	const outHeight = above + 1 + below;
	const outBaseline = above;

	let totalW = 0;
	for (let i = 0; i < nonEmpty.length; i++) {
		totalW += nonEmpty[i]!.width;
		if (i > 0) totalW += gap;
	}

	const out = blankBox(totalW, outHeight, outBaseline);
	let x = 0;
	for (let i = 0; i < nonEmpty.length; i++) {
		const b = nonEmpty[i]!;
		const y = outBaseline - b.baseline;
		blit(out, b, x, y);
		x += b.width;
		if (i < nonEmpty.length - 1) x += gap;
	}
	return out;
}

src/core/box.ts — join boxes left to right, lined up on the baseline.

Unicode has superscript and subscript digits and a handful of letters, so x_1^2 becomes x₁² when every character has a small form, and falls back to a shifted box when one doesn’t. ASCII mode keeps inline maths on one line in the linear form every plain-text reader knows, x_1^2, and draws display fractions with dashes.

Typesetting

The image renderer is a small proportional layout engine that follows the TeXbook closely enough to look like it. Boxes carry a width, a height above the baseline, and a depth below it, in em. Fractions sit on the maths axis with clearance around the rule, scripts scale to 70% and shift by TeX’s sup1 and sub1, large operators grow through the Size faces and take their limits above or beside depending on whether they’re \sum or \int, and spacing between atoms comes from TeX’s class table.

Every box keeps its primitives in one flat coordinate space instead of nested transforms. Nested transforms are where engines like this usually go wrong: a shift applied at the wrong level stays invisible until a deeply nested subscript drifts. With one space, the SVG emitter is a single pass with one flip of the y axis.

x=−b±b2−4ac2ax = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
the fraction sits on the maths axis
∇×H=J+∂D∂t\nabla \times \mathbf{H} = \mathbf{J} + \frac{\partial \mathbf{D}}{\partial t}
bold vectors, a nested fraction
∑n=1∞1n2=π26\sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}
limits above and below the sum
∣x∣={xx≥0−xx<0|x| = \begin{cases} x & x \ge 0 \\ -x & x < 0 \end{cases}
cases, with a grown brace
f′(x)=lim⁡h→0f(x+h)−f(x)hf'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}
limits under lim
∫01x2 dx=13\int_0^1 x^2 \, dx = \tfrac{1}{3}
limits beside the integral
Figure 6. The image path: fractions on the axis, operators that grow, limits above the sum and beside the integral.

The fonts ship with the package: thirteen KaTeX faces of Computer Modern, about 346 KB, with per-glyph metrics generated from the KaTeX build. That’s not polish. A stock Mac has none of the usual maths fonts, so a font-family list quietly falls back to Times and the output stops looking like mathematics. Bundling means an equation looks the same on every machine.

Protocols

The SVG is rasterised by whichever optional rasteriser is installed, resvg or sharp, and wrapped in the terminal’s protocol: kitty’s graphics protocol, iTerm2’s inline images, or sixel, with a tmux or screen envelope when needed. Without a rasteriser the ladder simply starts at Unicode.

  1. kitty graphics

    The image goes as base64 chunks the terminal decodes and places in its grid. Ghostty speaks it as well as kitty itself.

  2. iTerm2 inline images

    One escape sequence carrying the whole image, sized in terminal cells.

  3. Sixel

    The oldest of the three: six-pixel bands, at most 256 colours, and no alpha channel. Encoded in plain TypeScript.

Figure 7. The three image protocols the ladder can land on.

Sixel is the awkward one, and it’s written in plain TypeScript with no native dependency. It allows at most 256 colours and has no alpha channel, so the encoder uses median-cut quantisation, which suits images that are almost entirely greys, and treats alpha as a clean one-bit mask by default. Anti-aliased edges kept at full opacity would thicken every glyph and fill the palette with near-identical darks.

Detection reads the environment and never touches the terminal, so it’s safe to call from inside another program. Asking the terminal directly, for its cell size or graphics support, puts it into raw mode, and is strictly opt-in.

Streaming

Piping a model through termath and waiting for it to finish means staring at a blank screen, so --stream formats as the answer arrives. It buffers lines, tracks whether it’s inside a code fence or a display block, and flushes everything up to the last line outside both. A block is never split halfway.

The output is byte-identical to the batch path, which is fussier than it sounds. The newline between two flushes belongs to the second chunk, not the first; ending a chunk with it made the scanner add a blank line before the next display block, so the newline is carried across the boundary instead.

Verification

187 tests across 14 files cover the scanner’s round-trip guarantee, the parser, both renderers, capability detection, mode picking, the protocol encoders, and streaming equivalence. CI runs them on Node 18, 20, and 22, and again with a rasteriser installed so the image path is exercised for real.

Decisions

  • Not a LaTeX engine

    The parser covers the maths models actually write, not TeX. There are no macros, no packages, and no pretence of completeness, which is what keeps the library small, pure TypeScript, and fast enough to run on every message.

  • Rasterisers are optional

    Zero required dependencies was worth more than images by default. resvg or sharp unlock the image rungs when installed, and without them nothing fails; the ladder starts one rung lower.

  • The pipe beats the skill

    A skill depends on the model following instructions. A pipe does not involve the model at all. Both ship, but the docs recommend the pipe first, because formatting should not depend on whether the model remembered to do it.

What’s Next

Publishing comes first. The package is built and tested but not yet on npm, and npm install is the whole point of a drop-in.

After that, the text rungs need the attention the image rung got. They set a leading minus as if it were subtraction, so -b comes out as - b, and ASCII mode still lets the integral and summation signs through as Unicode. Both are small fixes in a renderer that otherwise does exactly what the image path does, in characters.