Skip to main content

The typesetting engine

Rendered from corpus/wiki/typeset.md · updated 2026-11-02

This page is generated from the project corpus and rewritten on every docs build. Edit the source in corpus/, not here.

packages/typeset turns a subset of LaTeX into a PDF. It is ours, and it is not TeX. Built by the engine foundation (2026-08-26) and extended by the figures, tables and bibliography work (2026-08-29) (figures, tables, bibliography) and the math work (2026-08-29) (mathematics). See D38 for why the engine exists at all, and D41 for how math is done.

The scope line: syntax, not semantics​

LaTeX is not a file format, it is a program — \catcode lets a document redefine what characters mean mid-parse, so there is no parser to write, only a macro-expansion machine that must then execute the kernel. Measured 2026-08-26: tex.web is 25,010 lines of literate Pascal, the kernel 79 .dtx files, 4.81 MB, before article.cls.

We do not do that. We accept LaTeX-shaped documents and implement the commands ourselves. This is only defensible because the owner has nothing to import (the LaTeX editor's spec). If a legacy .tex corpus ever appears, D38 is the first thing to revisit.

The loud-failure contract — the spine​

An unimplemented command produces a diagnostic with file and line, never a silent skip and never a guess. A dropped \thanks is a missing footnote in a published document; a silently-ignored \hspace is a table that looks right and is wrong.

Two codes carry the distinction, and it is checked in review:

  • unsupported — real LaTeX we deliberately do not implement.
  • undefined-command / undefined-environment — not a thing at all.

Conflating them makes the diagnostic useless to a writer. This has been got wrong twice and caught both times: \begin{equation} reported undefined-environment, and a self-including \input borrowed budget-exceeded. Treat a borrowed code as a bug, not a detail.

No I/O — the security design, not a limitation​

compile(files: Record<string, Uint8Array>, entrypoint, opts) -> { pdf, pages, diagnostics, stats }

A pure function over an in-memory file map. No filesystem, no network, no child processes, no eval. src/ compiles with "types": [] so Node APIs will not even typecheck there.

This deletes the sandboxing problem rather than solving it. \write18 cannot execute because no shell escape is written; \input{/etc/passwd} cannot read anything because \input resolves against files or becomes a missing-file diagnostic. Path confinement and symlink escape are not engine concerns — they exist only where the LaTeX editor (2026-08-27) accepts uploads.

What replaces a wall-clock timeout is a deterministic step budget: reproducible where a timer is not, so "this compile was stopped" is testable. Plus output-size and page caps.

Known limitation: fontkit pulls node:fs into the module graph transitively (and mathjax does the same). No document can reach either — the engine only calls fontkit.create(bytes), and math's require/autoload are off precisely so a document cannot steer a load. dist/ will not load in a host that bans fs; a browser bundle is unaffected.

Fonts and the math renderer are both injected, for the same reason: the caller owns acquisition. Omitting either is an error, never a silent substitution.

The pipeline​

parse → macro → doc → layout → pdf
StageWhat it does
src/parse/@unified-latex → our AST, every node carrying a 1-based SourceRef
src/macro/builtin tables, \newcommand expansion, the step budget
src/doc/document model: blocks, inlines, counters, labels, \ref
src/layout/box/glue, Knuth–Plass line breaking, hyphenation, page building
src/image/PNG/JPEG decode to intrinsic size, and the PDF XObject embed
src/math/TeX → MathJax SVG, plus the subset gate (D41) — typeset-math.md
src/font/fontkit wrapper over committed Latin Modern (GUST FL)
src/pdf/pdf-lib document structure; glyphs positioned by us

Line breaking is total-fit, not greedy — TeX's badness, fitness classes and demerits with their values cited. The load-bearing test enumerates all 2^n breakings of a short paragraph, scores them with an independently-written demerits function, and asserts the chosen one is the minimum: a proof rather than an assertion.

Glyphs are positioned explicitly. pdf-lib sums unkerned advances and writes them into /W, so drawText would render unkerned — not merely mismeasure. /W carries the unkerned advance and a TJ array carries the kern difference, recomputed from the running pen so rounding cannot drift.

The document is laid out twice. \ref resolves during the build, but \pageref cannot: a page number needs layout, and writing it in changes the reference's width. The loop runs to a fixed point, capped at three — LaTeX's .aux cycle. A document with no markers lays out once.

What the engine sets​

The full In and Out lists, construct by construct, are typeset-scope.md.

ConstructStateNotes
Prose, sections, ToC, lists, footnotes, \ref, \newcommand, verbatimthe engine foundation (2026-08-26)
Figures and tables (figure/table, [htbp], \caption, \listoffigures/\listoftables)the figures, tables and bibliography work (2026-08-29)A float that can never be placed is a diagnostic; nothing is dropped
\includegraphics — PNG and JPEGthe figures, tables and bibliography work (2026-08-29)width=/height=/scale=, \textwidth-relative. Format from the signature, never the extension
tabular — l c r, p{}, | rules, \hline, \cline, \multicolumnthe figures, tables and bibliography work (2026-08-29)Columns measured in a first pass, set in a second
Bibliography — .bib parser, one numeric style, \citethe figures, tables and bibliography work (2026-08-29)An unknown key is a diagnostic and prints [?]
Mathematics — inline and display, align/gather/split, matrices, growing delimiters, the symbol coveragethe math work (2026-08-29)MathJax v4 SVG, gated to the declared subset (D41)

Images embed verbatim wherever they can. PDF's /Predictor 15 is PNG's per-scanline filtering and a /DCTDecode stream is a JPEG datastream, so PNG colour types 0/2/3 and every accepted JPEG go in as the file's own bytes. Since those paths never look at a pixel, every PNG chunk's CRC is verified — a bit-flip in IDAT would otherwise reach a reader as a broken picture with nothing saying why. Types 4 and 6 are decoded, because PDF has no interleaved alpha and it must split out into an /SMask. Refused with a reason rather than embedded wrong: interlaced PNG, tRNS, CMYK and progressive JPEG, non-8-bit precision.

Two float rules. A float taller than \textheight is placed anyway, on its own page, with an overfull-box warning — an oversized figure the author can see beats one that is nowhere. But a float asking for [h] and nothing else that does not fit is an error: moving it would put it where the source forbade.

the declared Out list report unsupported, not undefined-command. \rotatebox, \multirow, booktabs' rules and subfigure/subcaption are real LaTeX we declined — telling an author no such command exists is false. builtins.ts carries them as unsupported rows with a detail saying why, matching how wrapfigure/tabularx/longtable were already handled.

Mathematics​

The math work (2026-08-29), decision D41: MathJax v4 SVG, our own SVG→PDF emitter, and the subset gated on the MathML. It has its own page — typeset-math.md.

A convention that will bite you​

packages/typeset/src/** relative imports carry an explicit .ts suffix, not .js, and the package is erasable syntax only. Node's type stripping does not rewrite specifiers, so a .js suffix breaks node --test, while tsc rewrites .ts on emit. This deliberately differs from apps/api, which uses .js — do not "fix" one to match the other.

Testing​

The engine foundation (2026-08-26) brought the repo's first test suite (node --test, no framework — Node runs the TypeScript directly). Goldens record a layout dump — each box's content, x, y, width, font — never PDF bytes, which are not reproducible. Rounded to 3 decimals: far below what a reader can see, far above float noise, so goldens neither flap nor hide a real change.

What the reviews keep finding​

Three scoped finders, twice now, and every serious finding spanned files owned by different chunks — the ToC sharing an Inline[] with its heading so \pageref printed the wrong page; a budget latch keyed on a diagnostic code two unrelated failures also used. Per-chunk verification was honest and still insufficient, because each chunk was right about its own half. Budget the review accordingly on 39 and 40.

Two later findings broke the pattern, and both were diagnostic-free wrong pictures — the failure mode the loud-failure contract cannot catch by construction, because nothing was unimplemented and so nothing had anything to report. The figures, tables and bibliography work (2026-08-29): a tabular row stopping short of the last column drew the table's right border partway across the grid. The math work (2026-08-29): math reached a finished PDF as blank space, because a switch over a grown union had no exhaustiveness check. Geometry needs assertions on coordinates, and every dispatcher over a union needs a never guard — both now have one.

See decisions.md D38, and glossary-authoring.md for Typesetting engine, Supported subset and Diagnostic.