# TeX-compatible incremental core (route D) Status: **M0 architecture spike + M1 paragraph builder implemented** in `crates/texrra-tex-core`. The production v1 engine in `src/rust_typeset` remains the default and is kept as a fallback while the TeX-compatible core grows. ## Why route D The v1 engine parses LaTeX into `DocumentModel` and lays it out with hand-written algorithms. That gives true incremental preview, but it cannot be page-identical for arbitrary `.cls`/`.sty` files: class files are TeX programs, and their layout primitives (`\vbox`, `\halign`, `\output`, `\twocolumn`, insertions, math lists, font metrics) are not executed. Route D is a TeX-compatible execution/layout core designed for incremental operation from the start. It does **not** embed pdfTeX, XeTeX or Tectonic. - `Layout::changed_pages` / `Engine::changed_pages()` list the page indices whose sealed hash changed during the last edit. ## M0 scope (this spike) `crates/texrra-tex-core` currently provides: - `VerticalItem::{Box, Glue, Penalty}` and `VerticalBox` as the first vertical list model; - `Unit::paragraph` backed by the M1 box/glue/penalty paragraph builder; - `Engine::layout` that builds pages with a simple page goal; - `Checkpoint` before every top-level unit, containing the completed-page count, used vertical space and current page items; - `Page` hashes derived from both vertical items and the contributing unit sources; - `Engine::edit` which restores the checkpoint before the edited unit, re-executes only the suffix, compares page hashes, and reports `recomputed_pages`; - `Unit::paragraph_style` records whether a unit is text and can be re-flowed by `Engine::edit`; structural units (halign, insertion, float) are never rewritten from a plain source string. - serde round-trip for checkpoints. M0 proves the incremental contract; M1 starts replacing the placeholder with horizontal material and a paragraph breaker. The page builder, math, fonts and class execution are still ahead. ## M1 scope (paragraph builder) `crates/texrra-tex-core/src/paragraph.rs` adds: - `HorizontalItem::{Box, Glue, Penalty}` and `HorizontalBox` as the horizontal list model; - `ParagraphStyle` with `line_width`, `par_indent`, `line_height` and glue stretch/shrink; - `Cmr10Metrics`, a CMR10 ASCII width table extracted from `cmr10.tfm` with `tftopl`, plus the fontdimen space/stretch/shrink values; - an item-stream dynamic program over character boxes, glue and penalty breakpoints that minimizes TeX demerits (line penalty, badness, break penalties and adjacent fitness changes), applies `par_indent` to the first line, and bakes the justification into the glue widths of every non-final line; prefix sums over the item stream supply each candidate line width, stretch, shrink and glue order in O(1), so the search costs O(breakpoints^2) instead of rescanning every candidate line (a 2,700-word body now lays out in about 0.3 s instead of about 30 s); - `Paragraph { lines, height, width }` and a paragraph-backed `Unit`. M1 reads real CMR10 TFM metrics at runtime (advances, height/depth, italic correction, kern pairs, ff/fi/fl/ffi/ffl ligatures and the fontdimen glue parameters), hyphenates with TeX Live's `hyph-en-us` patterns and exceptions (`\lefthyphenmin=2`, `\righthyphenmin=3`), and reproduces TeX's paragraph breaker: pass 0 uses `\pretolerance` without hyphenation, pass 1 uses `\tolerance`, and a third pass with `\tolerance=10000` runs only when `\emergencystretch` is positive. With zero emergencystretch TeX's final pass keeps `\tolerance` and forces overfull breaks through artificial demerits; the fallback here mirrors that choice by taking the longest prefix within tolerance and otherwise the first prefix that overflows. Justification stretches normal glue past its nominal stretch (badness simply exceeds 100) and clamps shrink at the declared limit, so overfull lines stay overfull exactly as in TeX. Each line can take its measure and left offset from `\hangindent`/`\hangafter` or an explicit `\parshape` list (the route-D service reads `\parshape=...`, `\parfillskip`, `\lineskip`, `\lineskiplimit`, `\topskip`, `\maxdepth`, `\splittopskip` and the demerit registers (`\hyphenpenalty`, `\exhyphenpenalty`, `\doublehyphendemerits`, `\finalhyphendemerits`, `\linepenalty`, `\adjdemerits`) and `\sfcode` assignments from the source); the display list honours the same offsets. The bounds and hyphen demerits are `ParagraphStyle` fields mirroring `\pretolerance`, `\tolerance`, `\hyphenpenalty` and `\exhyphenpenalty`, `\linepenalty`, `\adjdemerits`, `\doublehyphendemerits`, `\finalhyphendemerits` and `\emergencystretch`, plus document-level `\hyphenation` exceptions (the route-D service reads `\hyphenation{...}` lines from the source); `\hyphenpenalty` at 10000 or more disables hyphenation and switches the fallback to a first-fit scan. `tests/oracle.rs` compares a matrix of measures (90, 100, 110, 120, 130, 150, 160, 180, 200, 220 and 240pt) against pdfLaTeX: every fixture matches word for word and within 0.05pt horizontally. The narrowest measures exercise hyphenated and overfull breaks (including a final line held at its declared shrink limit), 130-160pt the final-pass overfull box, and 180-240pt ordinary tolerance solutions. Two further fixtures pin register behaviour at 120pt: `\pretolerance=10000` stops before hyphenation and `\hyphenpenalty=10000` inhibits it, leaving the overfull first-fit lines TeX produces. A `\tolerance=10000` fixture matches pdfLaTeX at 100-240pt, and a 70/85pt fixture with `\pretolerance=10000 \tolerance=200` confirms that the pretolerance pass keeps loose one-word lines before hyphenation is considered. Hyphenated paragraphs are compared at 80, 100 and 120pt, and a 70/85pt fixture runs with `\doublehyphendemerits` and `\finalhyphendemerits` at 0 and 10000 so the reference breaks change with the demerits. A 120pt fixture with `\hangindent=20pt \hangafter=1` checks every line origin against pdfLaTeX as well as the word positions inside each line, and a `\parfillskip=0pt` fixture checks that a final line without `fil` glue is justified like any other line (the default `0pt plus 1fil` leaves it short). Two 150pt fixtures pin explicit interword glue: `\spaceskip` replaces the font glue (width kept, stretch/shrink following the space factor) and `\xspaceskip` is used verbatim once the factor reaches 2000; neither adds `\fontdimen7`. A 150pt fixture pins `\emergencystretch=10pt` (three lines instead of an overfull pair) and another pins `\leftskip=20pt` (narrowed measure and shifted origins). `route_d_multiline_bands_track_pdftex` rasterizes the same paragraph in both engines and compares ink bands, covering baseline placement and justification. ## Target architecture - Persistent TeX VM state: macros, registers, fonts, counters, output queue. - Stable IDs for top-level units. - Checkpoint at page boundaries plus unit boundaries. - Dependency graph for labels, references, counters, TOC and citations. - Dirty propagation: after a local edit, replay from the nearest checkpoint and stop at the first unchanged page hash. - Float/footnote queues restored with the checkpoint. ## Milestones | Milestone | Content | Acceptance | | --- | --- | --- | | M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 | | M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures | | M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions, bottom floats or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset, and `\mark{...}`/`\marks{...}` writes inside the routine are carried to the following page's mark list with their class; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets the pages the routine has not seen yet, even when the document raises insertion material; only a document that defers bottom floats keeps its initial goal, because the carried queue cannot be rebuilt after a retarget), `\ht255`, `\dp255` and `\wd255` expose the page box height, depth and width to the routine, and `\hsize` is readable (and assignable for the rest of the run) while `\wd255` tracks it; route-D sets `\hsize` from its 480pt text measure, insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments that outlive the routine (the paged builder runs the routine after each page, so an assigned `\dimen` or `\count` changes the insertion capacity and reservation of later pages); the configured `\skip` also reserves space above its class once per page in the paged builder, and a `\skip` assignment rebuilds the pages the routine has not seen yet with the new reservation, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine; `\vbadness` reports the badness of the break that produced the page and `\insertpenalties` the number of insertion items held over from it | | M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\addlinespace`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), `\multicolumn{n}{align}{...}` cells span columns with the requested alignment, `\cline{a-b}` draws a 0.4pt partial rule over a column range, though `\valign`, nested tables and full tabular parity remain open | | M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`, with `cmmi10`, `cmsy10` and `cmex10` glyphs embedded as Type1 outlines), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an approximation of TeX's `\split` behaviour; `align`/`align*` displays share column widths and number each row, while `gather`/`gather*` centre every row, `alignat` numbers rows the same way while ignoring its column-count argument, a `split` body inside `equation` is numbered once, and `multline` rows flush left and right around a single number); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation, with `1mu` = `1/18em` (a thin space is 3mu = 1.67pt at 10pt); `\mid` is a relation while `\colon` is punctuation; `\limits` stacks an operator's scripts above and below at TeX's script size and clearance (checked against pdfLaTeX word positions, including descender bases) while `\nolimits` keeps them beside the operator, `\substack{...}` stacks its rows with TeX's inter-row gaps, and an integral keeps its scripts beside it unless `\limits` asks otherwise, as TeX's display rules do; `\mskip`, `\mkern`, `\mspace`, `\hskip`, `\kern` and `\hspace` scan TeX dimensions (`mu`, `pt`, `em`, ...) and contribute their natural width, accepting `plus`/`minus` parts even though math boxes are not glue lists; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and wraps its text in parentheses while `\tag*` keeps it bare, and `\notag`/`\nonumber` suppress the number; `displaymath` environments (and `$$`/`\[` displays) stay unnumbered while `math` environments select inline math; math italic letters are embedded as Computer Modern Type1 outlines (`cmmi10`), and math alphabets map `\\mathbf`/`\\mathit`/`\\mathsf`/`\\mathtt` onto the bold, math-italic, sans and mono faces with their TFMs and `\\mathcal` onto the cmsy10 calligraphic capitals, with `\\boldsymbol`/`\\bm` mapping to the bold alphabet; `\mathfrak` maps onto the bundled eufm10 Fraktur letters (embedded as Type1 outlines); infix fractions `\over`, `\atop`, `\choose`, `\brace`, `\brack` and their `withdelims` forms build fractions from the current row, with the bar only for the `\over` forms; `\genfrac{left}{right}{thickness}{style}{num}{den}` builds a fraction with optional delimiters and no rule for an empty or `0pt` thickness; `\middle` delimiters are sized with their enclosing `\left`/`\right` group and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size | | M5 | NFSS/TFM metrics, CM/Latin Modern | **partial**: paragraph-level NFSS declarations and inline run composition over the built-in Roman/Bold/Italic/BoldItalic/Mono/MonoItalic/Sans/SansBold/SansItalic/SmallCaps/Slanted/BoldSlanted faces (CM has no sans bold-italic, so `cmss/bx/it` substitutes `cmss/bx/n`; `\scshape` selects cmcsc10 and a bold small caps request falls back to cmbx10; `\slshape` uses the slanted cmsl10 rather than the italic cmti10 and `\ttfamily\itshape` reaches cmitt10), per-face Computer Modern TFM metrics, and Type1 (PFB) outline embedding for every built-in face plus `cmmi10` math italics, `cmsy10` math symbols and `cmex10` big operators, with a Liberation subset falling back per glyph for characters outside the Type1 encodings, so ASCII on an accented line still uses the Computer Modern face, and Type1 faces carry a ToUnicode CMap built from the requested characters so extraction does not depend on ambiguous glyph names; paragraph base sizes from `\fontsize` and the article size commands scale glyph metrics and the default interline glue while the measure and authored skips stay absolute, a size command in the middle of a paragraph splits a sized run that is shaped and painted at its own type size, and inline math inside a styled run keeps its math boxes while the surrounding text keeps its face; accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark, while `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em; `\MakeUppercase`/`\MakeLowercase` (and `\uppercase`/`\lowercase`) transform their braced text and keep the surrounding face; full NFSS family/shape state and Type1 coverage for arbitrary Unicode remain open | | M6 | class/package execution (`article`, `sn-jnl`) | **partial**: a leading `\noindent` starts a paragraph flush with the measure, box commands `\mbox{...}`, `\hbox{...}` and `\makebox[width][position]{...}` keep their text in the flow, and `\hspace{...}`/`\hspace*{...}` reserve their TeX width in the running text, text-mode `\quad`/`\qquad` and `\,`/`\:`/`\;` insert the corresponding TeX spaces, `\enspace`, `\thinspace`, `\medspace` and `\thickspace` insert their named TeX widths, `\documentclass[...]` options are read and the article `10pt`/`11pt`/`12pt` base size sets the default paragraph font size and `\baselineskip` (13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`/`\def\baselinestretch{factor}`) scales that class baseline, while `\newlength{\name}` registers a named length that `\setlength` can assign and a later `\setlength{\parindent}{\name}` can read, and `\addtolength{\name}{...}` adjusts it; the `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom` options (and `\geometry{...}`) adjust the measure and page height; page numbers print centred below the text block (or right-aligned in a header on pages after the first under `\pagestyle{headings}`/`{myheadings}`, with the current numbered heading title uppercased at the header's left, while `myheadings` uses only explicit marks), `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), `\pagenumbering{roman|Roman|alph|Alph|arabic}` selects the format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page; `\title`/`\author`/`\date` are captured, `\hypersetup{pdftitle=...}` (also `pdfauthor`/`pdfsubject`/`pdfkeywords`) writes the PDF Info dictionary with UTF-16BE values for non-ASCII text (falling back to `\title`/`\author`), each numbered heading becomes a PDF bookmark in `/Outlines`, nested by heading level and pointing at its page, `\today` expands to the UTC calendar date in the title block and the body, and `\maketitle` expands into the centered article title block at the class sizes (with today's date when `\date` is absent and no date for `\date{}`); numbered `\section`/`\subsection`/`\subsubsection`/`\paragraph`/`\subparagraph` headings advance five-level article counters (article's `\setcounter{secnumdepth}` default of 3 numbers through `\subsubsection`, and raising it numbers the two deeper levels; `\setcounter{section}`/`{figure}`/`{table}`/`{equation}`/`{theorem}` offsets the next counter value, and `\stepcounter{name}`/`\refstepcounter{name}` bump it by one; `\arabic{name}`, `\roman{name}`, `\Roman{name}`, `\alph{name}`, `\Alph{name}` and `\value{name}` print the formatted counter) and paint at `\Large`/`\large`/`\normalsize` (the two deepest levels stay bold at the base size), starred headings stay unnumbered, and an optional `[short]` title replaces the long title in the table of contents and in running heads; the `abstract` environment expands into a centered bold heading and a 9pt body, `acks`/`acknowledgments`/`acknowledgements` environments render an unnumbered Acknowledgments heading and a `keywords` environment renders a bold `Keywords:` lead-in with its `\sep` entries comma-joined, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or immediately after it, with or without a blank line, or on a standalone label paragraph) resolves `\ref`/`\eqref` to the section number and inherits the heading title for `\nameref` while unknown references print `??`, and `\pageref{label}` reports the formatted page number of that heading, figure, table or equation after a probe layout (unknown labels print `??`), and `\appendix` restarts sectioning with letters (`A`, `A.1`), while an `appendices` environment does the same, and `\tableofcontents` lists the numbered headings through `\subsubsection` with 12pt per-level indentation and a right-aligned page number reached by dot leaders that fill the measure (the default article `tocdepth` of 3; `\setcounter{tocdepth}` changes the depth) while `\listoffigures`/`\listoftables` reproduce the numbered figure/table captions and append each float's page number after dot leaders that fill the measure (an optional `[short]` caption is used there while the long caption stays on the float); `verbatim` environments keep each source line as a monospaced 9pt paragraph indented by 12pt (leading whitespace is normalised), `\verb|...|` renders inline literal text in the mono face, siunitx's `\SI`/`\qty`, `\SIrange`, `\num` and `\si` expand with common unit macros such as `\metre` and `\per`, common text commands such as `\LaTeX`, `\TeX`, `\ldots`, `\dots`, `\S`, `\copyright`, `\pounds`, `\ss`/`\ae`/`\oe`/`\o`/`\l`/`\dh`/`\th` and symbol commands such as `\textquotesingle`, `\textunderscore`, `\textbraceleft`, `\textbraceright`, `\textdegree`/`\textmu`/`\textonehalf`/`\texteuro` expand to their characters, and a control word swallows the spaces that follow it, an explicit `\par` starts a new paragraph, layout-only commands such as `\protect`, `\relax`, `\ignorespaces`, `\unskip`, `\nobreak` and `\phantomsection` are dropped, `\phantom`/`\hphantom` reserve their measured width invisibly while `\vphantom` adds no width, `\scalebox`/`\resizebox`/`\rotatebox`/`\raisebox` keep their content at the natural size and position (no transform is modelled), `\href{url}{text}` keeps its text, `\url{...}` becomes typewriter text, and `\hyperref[label]{text}`, `\hyperlink{name}{text}` and `\hypertarget{name}{text}` keep their visible label (internal PDF targets are not modelled), `\autoref{label}` prefixes the number with the label's kind (`Section`, `Figure`, `Table`, `Equation`, or a theorem display), and `\nameref{label}` resolves it to the heading title or float caption (falling back to the number), while `\cref{...}`/`\Cref{...}` resolve comma-separated label lists to their kind and number (an equation label becomes `Equation `); a `~` in running text becomes a space (non-breaking behaviour is approximated), while `\url` keeps its tildes literal; `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it, and `\footnotemark`/`\footnotetext{...}` pair a marker with a deferred body in the same paragraph, and an optional `[n]` on either command selects an explicit number; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs (a custom `\bibitem[Label]{key}` label replaces the number in both the list and citations), and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`, an optional note like `\cite[p.~3]{...}` appears inside the brackets (`[1, p. 3]`), `\citep`/`\citet` behave like `\cite`, `\nocite` is ignored, and `\bibliography`/`\bibliographystyle` lines are consumed without running BibTeX); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics` embeds the referenced project image (PNG/JPEG/BMP are decoded into a PDF XObject, with a rule placeholder when the file is missing or cannot be decoded), and a standalone `\includegraphics` paragraph becomes an in-text graphic float, while a standalone `\rule{width}{height}` becomes an in-text rule box, with `width=`/`height=` taking dimensions or fractions of `\textwidth`/`\linewidth`/`\columnwidth`/`\paperwidth`/`\textheight`/`\paperheight`, `scale=` a percentage of the natural size, `keepaspectratio` shrinking both dimensions to fit, and `\graphicspath` directories searched with common image extensions when the path has no suffix; `longtable` environments are captured through the same tabular path, and a `tabular` wrapped in `\resizebox`/`\scalebox` is unwrapped before capture (including their `\endfirsthead`/`\endhead` markers), and a `table` environment becomes a float that carries its captured `tabular` body and a numbered `Table n:` caption whose text sits above the tabular as in LaTeX, while `\caption*` stays unnumbered for either float kind; `\tabcolsep` (or `\setlength{\tabcolsep}`) sets the glue on each side of every tabular column, with LaTeX's 6pt default when unset and twice that value between neighbouring columns, and `\renewcommand{\arraystretch}{factor}` (or `\def\arraystretch{factor}`) scales every tabular row height; tabular cell widths are measured with the Computer Modern Roman metrics, so column widths and cell alignment match pdfLaTeX (verified by a word-position oracle at LaTeX's default 6pt tabcolsep), the outer edges reserve one `\tabcolsep` each, and neighbouring columns are separated by twice the `\tabcolsep` value while a `tabular`/`longtable` optional position argument is accepted and ignored, and a row separator `\\[dim]` adds that vertical gap after its row, and `|` column separators paint 0.4pt vertical rules at their column boundaries, and `*{n}{cols}` repeats a column group n times; caption styling declarations such as `\captionsetup` and `\numberwithin` are consumed (their visual/number-scope effects are not modelled), and caption prefixes and the abstract heading can be renamed with `\renewcommand{\figurename}`, `\renewcommand{\tablename}` and `\renewcommand{\abstractname}`, while the bibliography, table of contents and float lists open with `References`/`Contents`/`List of Figures`/`List of Tables` headings renamed by `\renewcommand{\refname}`, `\renewcommand{\contentsname}`, `\renewcommand{\listfigurename}` and `\renewcommand{\listtablename}`; `theorem`/`lemma`/`corollary`/`proposition`/`definition`/`example`/`remark`/`proof` environments get a bold numbered heading (optionally with `[title]`), italic statements for the theorem group, an unnumbered proof whose optional argument replaces its heading text and whose body closes with a `□` symbol (an explicit `\qedhere` is replaced by it), and `\label`/`\ref` targets; `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` define custom environments with shared counters and section-scoped numbers; `itemize`/`enumerate`/`description` lists nest with depth-aware bullets (`•`, `–`, `*`), lettered/roman sub-labels and 12pt-per-level indentation, items take article's per-level `\topsep`/`\itemsep` plus `\partopsep` above the first item (top level 8+2/4pt at 10pt, 9+3/4.5pt at 11pt and 10+3/5pt at 12pt, with 4+2/2pt, 4.5+3/2pt and 5+3/2pt at the second level; `\setlength{\topsep}`, `\setlength{\itemsep}` and `\setlength{\partopsep}` override them, and a wrapped item hangs its continuation lines at the text indent while its first line stays at the bullet indent), an optional `\item[label]` overrides the generated marker, and `description` items print their term in bold before the definition, and a `\setcounter{enumi}` (or `enumii`/`enumiii`/`enumiv`) line before the first `\item` resumes the enumerate count; `center`/`flushleft`/`flushright` parse their body as blocks (so a nested list, graphic or rule keeps its own handling), a `quotation` environment splits its blank-line-separated paragraphs into blocks indented 20pt on both sides (nested lists add the margins to their own indentation), and `quote` uses the same 20pt margins, while `verse` keeps its explicit line breaks as separate 20pt-indented lines, and a `minipage{w}` environment lays its body out at width `w` (its optional position argument is ignored); `\def\name#1{...}` parameter texts and `\let\alias=\other` aliases are executed as textual definitions, `\chardef\name=` defines a character command, and a `\def` parameter text with literal delimiters (such as `#1,#2`) captures arguments up to those delimiters, and the scratch registers `\dimen0`-`\dimen255` and `\skip0`-`\skip255` hold dimensions and glue with the same assignment and `\advance` forms, and `\count0`-`\count255` take assignments, `\advance`, `\multiply` and `\divide` and print through `\the`/`\number`, while `\newcount\name` declares an integer register that `\name= `\numexpr` evaluates `+`, `-`, `*`, `/` and parentheses over integers and integer registers, either standalone or after `\the` `\newdimen\name` declares a dimension register whose value `\name=`, `\advance\name by `, `\multiply\name by ` and `\divide\name by ` update and which `\the\name` prints in TeX's `pt` form.....`, `\advance\name by ...`, `\multiply\name by ...` and `\divide\name by ...` update and that `\the\name`/`\number\name` print `\dimexpr ... \relax` evaluates `+`, `-`, `*` (by an integer) and `/` over dimensions and `\newdimen` registers and prints through `\the`, and `\glueexpr ... \relax` evaluates glue expressions over dimensions, `\newskip` registers and `plus`/`minus` components (parenthesised sub-expressions are allowed and register operands keep all three components), printing through `\the`; `\noexpand\token` keeps the token unexpanded for the current pass (a later pass still expands it), and a later `\def` with the same name replaces the earlier definition The LaTeX internals `\@namedef`, `\@nameuse`, `\@ifundefined`, `\@firstofone`, `\@firstoftwo`, `\@secondoftwo` and `\@empty` expand, and `\@ifstar{yes}{no}` / `\@ifnextchar{yes}{no}` choose a branch from the following token, and `@` counts as a letter in control words so `\makeatletter`-guarded names parse..; `\newenvironment{name}[n]{begin}{end}` definitions expand their begin/end codes around the environment body, with numbered arguments available in both; `\newif\ifname` flags default to false and `\nametrue`/`\namefalse` assignments, whether in the preamble or the body, select between `\ifname ... \else ... \fi` branches (and `\ifdefined\name` tests whether a macro is declared, and `\ifcat` compares the category codes of two tokens, `\unless` inverts the conditional that follows it, `\if` compares two character codes, and `\ifodd` tests the parity of an integer; `\ifnum` compares integers from literals, `\newcount` registers or `\value{counter}`, and `\ifx` compares token meanings (two macros are equal when their parameter text and body match) `\ifcase ` chooses the n-th `\or` branch and falls back to `\else` when the value is out of range..); project previews and PDF exports expand `\input{...}`/`\include{...}` from the project's files (the `.tex` suffix may be omitted) while unknown files stay literal text, and inline a project's own `.sty` files for `\usepackage{name}` and `.cls` files for `\documentclass` (rewritten to `article` with the original options kept), recursively inlining local `\RequirePackage` dependencies (up to eight levels, cycles skipped), inlining local `\input{...}` files inside class/package bodies (unresolved ones are dropped), `\AtBeginDocument`/`\AtEndDocument` bodies are executed while `\makeatletter`/`\makeatother` are stripped, dropping package/class boilerplate (`\ProvidesPackage`/`\ProvidesClass`, `\NeedsTeXFormat`, `\RequirePackage`) and inlining local base classes requested with `\LoadClass`/`\LoadClassWithOptions` (unknown bases keep LaTeX's article fallback); local class and package files execute their `\DeclareOption`/`\ExecuteOptions`/`\ProcessOptions` subset, so options named on `\documentclass[...]` or `\usepackage[...]` run their declaration code and `\ExecuteOptions` supplies defaults, and `\PassOptionsToPackage`/`\PassOptionsToClass` lines are collected from the preamble and merged into the next `\usepackage`/`\documentclass` request; a full class layout implementation and arbitrary package code remain open, and `\textcolor{name}{...}` paints an inline run in one of the standard named colours in both the SVG preview and the PDF, and a leading `\color{name}` switch colours the rest of its paragraph (`\definecolor` supports rgb, RGB, gray, HTML and cmyk models, `\pagecolor{name}` fills the page background, a `name!percent!other` spec mixes two named colours linearly, the second defaulting to white, and `\hypersetup{urlcolor=...}` colours `\href` labels and `linkbordercolor`/`urlbordercolor` request a 1pt coloured annotation border (`hidelinks` omits it; the SVG preview frames each link in the same colour), and `\colorbox{name}{...}` paints a filled rectangle behind its text with LaTeX's 3pt `\fboxsep` padding, and `\fcolorbox{frame}{background}{...}` draws a 0.4pt frame around that rectangle, while `\fbox{...}` draws the same frame without a background; `\newskip\name` declares a glue register whose width, stretch and shrink are updated by `\name=`, `\advance\name by ` and `\setlength{\name}{}`, and `\the\name` prints them as `wpt plus spt minus hpt`), and a `report`/`book` `\documentclass` adds numbered `\chapter` headings whose sections number `1.1` and whose `\appendix` chapters letter from `A` | It also drops the break hints `\linebreak`, `\nolinebreak`, `\pagebreak` and `\nopagebreak` and the discretionary hyphen `\-`. | M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity | ## Current limits - The M1 paragraph builder parses CMR10 TFM metrics (widths, height/depth, italic correction, kern pairs, ligatures), applies TeX Live's en-US hyphenation patterns and runs TeX's tolerance passes with demerits. The tolerance bounds, break penalties and flagged demerits are modelled, `\hyphenation` exceptions are inserted into the pattern trie, and `\hangindent`/`\hangafter`/`\parshape` change each line's measure and left offset, and `\parfillskip` (with or without `fil`) decides whether the last line is justified. Sentence spacing follows TeX's default `\sfcode` values: interword glue stretch is multiplied by the space factor, shrink is divided by it, `\fontdimen7` is added from factor 2000, and `\frenchspacing` disables the effect. `ParagraphStyle::space_factor_codes` carries explicit `\sfcode` assignments, which replace the built-in table for that character; a zero code leaves the running factor unchanged, as in TeX. Explicit `\spaceskip`/`\xspaceskip` replace the font glue, and hyphenation applies to a word's letter core so trailing punctuation does not suppress the pattern lookup (pdfTeX breaks `epsilon:` as `ep-`). `ParagraphStyle::ragged_right` models `\raggedright`: lines keep their natural width and fill greedily, because the infinite `fil` in `\rightskip` leaves no reason to stretch. `\looseness` asks for the natural line count shifted by up to nine lines (TeX's `[1,9]` window); the shift is kept only while a feasible layout exists at that count. When the requested count is infeasible pdfLaTeX can still emit a different alternative optimum; route-D keeps the ordinary optimum there, which the unit tests pin. Interline glue follows TeX: each baseline advances by `\baselineskip` when the resulting gap clears `\lineskiplimit`, otherwise by `\lineskip`; `\parskip` is appended between paragraph units in the vertical list. When a paragraph does not fit on the page it is split at line boundaries (`Paragraph::split_at`): the fragment keeps its baseline grid on the next page, `\parskip` is not charged inside the paragraph, and only a single unsplittable line is allowed to overflow at the top of a page. The scrolling builder splits paragraphs directly; for the paged builder each paragraph becomes one node per line joined by zero-width interline glue, so its page breaks also land between lines with the same overflowing-line rule. The breaker covers the full register list above, including generic `fil`/`fill` glue orders and `\prevgraf`; no P1 register gap is tracked. The pdfLaTeX oracle pins the 90-240pt measure matrix plus `\hangindent`, `\parfillskip`, sentence-spacing and `\looseness` fixtures; all match and no oracle fixture is ignored. - `\middle|` inside `\left...\right` is accepted as a delimiter symbol (not yet stretched). - `\sqrt[n]{x}` carries an optional degree atom; `\left.` is an empty delimiter with zero width. - `MathAtom::Accent { accent, base }` parses `\hat`, `\widehat`, `\tilde`, `\widetilde`, `\bar`, `\overline` and `\vec`; it adds accent height without changing the base width. - `MathAtom::Smash { body, top, bottom }` implements `\smash` and `\smash[t]`/`\smash[b]`. - `MathAtom::Phantom { body, horizontal, vertical }` implements `\phantom`, `\hphantom`, `\vphantom` dimension-only boxes. - `MathAtom::BigOperator { name }` gives `\sum`/`\prod` 12pt width and `\int` 8pt width with larger height/depth than text. - `MathAtom::Limits { base, sub, sup }` gives `\sum`, `\prod`, `\int`, `\lim`, `\sup`, `\inf` above/below scripts. - `MathAtom::Classed { class, body }` implements `\mathord`, `\mathop`, `\mathbin`, `\mathrel`, `\mathopen`, `\mathclose`, `\mathpunct` and `\mathinner` spacing overrides. - `MathAtom::SizedDelimiter { delimiter, size }` parses `\big`/`\Big`/`\bigg`/`\Bigg` (and `l`/`r` variants); extents are 8/11/14/17pt. - `MathAtom::Stack { top, base, above }` parses `\overset`/`\underset`; the decoration contributes 1pt of extra separation. - `MathAtom::Brace { base, above }` parses `\overbrace`/`\underbrace` and adds 2pt of height or depth. - `MathAtom::Binomial { numerator, denominator }` parses `\binom{n}{k}` / `\dbinom` / `\tbinom`; layout stacks the arguments with a 4pt delimiter allowance. - `\mathcal`, `\mathbb`, `\mathbf`, `\mathit`, `\mathsf`, `\mathtt`, `\mathfrak`, `\mathnormal` parse their argument as upright `Text` for metrics; visual alphabet selection waits for the NFSS math font layer. - Named operators (`\max`, `\min`, `\sin`, `\log`, `\det`, ...) parse as upright `Text` atoms. - `MathAtom::Underline { base }` parses `\underline{...}` and adds 2pt depth without changing width or height. - `MathAtom::Text(String)` parses `\text{...}` and `\mathrm{...}`; widths use upright CMR glyphs and spaces use the font space width. - `MathAtom::Delimited { left, right, body }` - Delimiter width grows with the body extent: each non-`.` delimiter is `0.35 * max(body height + depth, 7pt)` wide. and `\left...\right` parsing grow the delimiter box with the body height/depth. - `MathClass` and TeX's 0/3/4/5mu inter-atom table add spacing for binary/relation/open/close/punctuation atoms in `MathAtom::Row`. - `parse_math` converts a small TeX math subset (symbols, `{}` groups, `_`/`^` scripts, `\frac`, `\sqrt`) into `MathAtom::Row`. - `MathAtom::{Symbol, Script, Fraction}` and `layout_math` produce `MathBox { width, height, depth }`; `Unit::math` turns an atom into a vertical box. Parsing TeX math tokens and painting remain future M4 work. - M1 now inserts TeX en-US hyphenation points as `HorizontalItem:: Discretionary`: a break adds the hyphen width, a non-break keeps zero width. The line breaker scores these breakpoints with the same glue model as spaces. - `Unit::halign` lays out natural column widths, multi-column spans and rule rows as a `VerticalItem::Halign`; `Halign::cell_box` returns each cell's aligned rectangle for a future painter. It is not yet painted by v2. - Pages that start with a float also honour `Document::top_skip`. - `Unit::vertical` and `Unit::insertion` build arbitrary vertical material and reserved-height page insertions; insertion height is deducted from the usable page goal and the material is attached to `Page::insertions`. `Document::insertion_classes` sets a per-class page fraction; an insertion that would exceed the class limit ships the page and continues on the next one, splitting at item boundaries when the insertion itself is too tall. When only part of an insertion fits on the page where its anchor text ends, that part stays there and the remainder is held over to the next page, so later body text follows the held-over tail. `Document::insertion_skip` models TeX's `\skip\footins` and is reserved once before the first insertion class on a page; it defaults to zero, and `InsertionClass::skip` overrides it for a single insertion class. `InsertionClass::multiplier` models `\count` in thousandths: the page space a class reserves is `height * multiplier / 1000`, so 2000 makes a 30pt insertion cost 60pt of page height. `max_height` is the `\dimen` absolute cap. Full layout, incremental replay and the item-boundary splitter all use the same reserved height. Overflowing insertions are split at item boundaries: the fitting head stays on the anchor page and the tail is held over to the following page. - Page breaking handles vertical boxes/glue, `Document::top_skip` and forced vertical penalties (`penalty <= -10000`); positive penalties are recorded but not yet part of page badness. `VerticalItem::Insertion` material is attached to `Page::insertions` and reserves height from the page goal. `VerticalItem::Mark` material is collected into `Page::marks` and included in the page hash. `OutputRoutine::shipout` runs before sealing and may mutate each page; this models the `\output` stage in Rust. The interpreted subset lives in `output::OutputProgram` (`Document::output_routine`), which understands `\shipout\box255`, `\relax`, `\message{...}`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers `\pagegoal`, `\pagetotal`, `\pagedepth`, `\pagestretch`, `\pageshrink`, `\vsize`, `\topskip`, `\maxdepth`, `\outputpenalty`, `\pageno` and `\deadcycles`; `\pagegoal` is `\vsize` less the insertion space reserved on that page, as TeX shrinks the page goal when insertions are held over; `PageFragment` also reports the page's total glue stretch and shrink. In the paged builder, `Document::par_skip` is inserted as vertical glue between consecutive paragraph units and is discarded when it would start a page, matching TeX's paragraph spacing in vertical lists; a zero-extent glue node is still recorded when `\parskip` is zero, so consecutive paragraphs always offer the page builder a legal breakpoint. The routine cannot yet change page goals. The paged builder places top `Float` material at the top of a page and bottom `Float` material at the page bottom: a late top float starts the next page, a bottom float that cannot fit is deferred to the next page's bottom by `PageBuilder::build_with_deferred_bottom_floats`, which keeps filling the current page exactly as TeX does and carries the float on `PageFragment::bottom_floats`; a float taller than a page still ends the page instead of looping, and `Engine::layout_paged` defers through the same entry point, so route-D pages place the float at the next page's bottom. Stacked bottom floats reserve `\floatsep`, and `\bottomfraction` caps the bottom float share, and a page whose top floats reach `\floatpagefraction` ships without body material. Route-D preview/PDF draw pages through `display_list_with_layout` so the body clears `\textfloatsep` / the bottom float area; the scrolling builder still reserves height for bottom floats against `Document.text_fraction_percent` (default 50%) and seals float-only pages. - No macro state, output routine, math, fonts or PDF output in the new core yet. - The v1 server and project API still use `src/rust_typeset` and are unchanged. ## Verification ```sh cargo test -p texrra-tex-core --offline ``` The M0 tests cover page splitting, checkpoint serialization and page-local editing. Three M1 tests cover glue-based line breaking, paragraph indentation and empty paragraphs. `Unit::halign_from_source` parses `&` rows, `\\` separators, `\omit`, `\span`, `\multispan{n}` and `\hline` rule rows. `Unit::halign_from_source_with_template` additionally accepts an `l`/`c`/`r` column template. `VerticalItem::Rule { width, height }` and `Unit::rule(id, width, height)` add filled rules to the vertical list; rules consume page height like boxes. `\not` becomes `MathAtom::Negated`, preserving the base atom's geometry for a later overlaid slash. `\noalign{...}` material in a halign source is skipped while rows are scanned. `\bmod`/`\pmod{n}` parse to upright `mod` rows, with `\pmod` wrapping its argument in `(mod ...)`. `\pmod{n}` is a `Classed` relation, and `\not` inherits the base atom's math class for spacing. `\mathinner{...}` uses `MathClass::Inner` with 3mu on either side. `\boxed{x}` adds 3pt padding around its body in the math model. `Unit::vskip(id, height)` adds a vertical glue item to the page list. `Unit::penalty(id, value)` adds a vertical penalty; values <= -10000 force a page break. `\stackrel{top}{base}` shares the `Stack` layout with `\overset`. `\overrightarrow`/`\overleftarrow` parse as arrow accents (U+20D7/U+20D6). `\widecheck` and `\dddot` map to U+030C and U+20DB accents. ## Milestone status (route D) | Milestone | State | Notes | | --- | --- | --- | | M0 checkpoint engine | done | page list, page hashes, snapshot/restore, edit replay | | M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing with default and custom `\sfcode`/`\frenchspacing`, explicit `\spaceskip`/`\xspaceskip`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfTeX oracle matrix 90-240pt plus register, geometry and vertical-glue fixtures | | M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for documents made of box/glue/penalty/mark vertical material (a unit may span pages), while in-text floats flow inline through the page builder; paged layouts replay edits from the edited page (insertions, bottom floats and interpreted `\output` force a full rebuild), and insertions are placed through the builder too; `\output` interpreted for a `\shipout`/`\ifdim`/`\ifnum` register subset over page globals and `\outputpenalty`/`\pageno`/`\deadcycles` | | M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter | | M4 math | partial | atoms, scripts, fractions (including infix `\over`/`\atop`/`\choose`), roots, delimiters, accents, operators, classes, braces, boxed, negated, math alphabets (incl. `\mathcal`, `\mathbb` and `\mathfrak`), `align`/`gather` rows with per-row tags; no math painter/shrink wrapping | | M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style; route-D PDFs embed Knuth's Computer Modern Type1 programs (cmr10/cmbx10/cmti10/cmbxti10/cmtt10/cmss10/cmssbx10/cmssi10/cmcsc10/cmsl10/cmbxsl10/cmitt10) as `/Subtype /Type1` fonts with `/FontFile` (`Length1/2/3`), `/Encoding /Differences` and TFM `/Widths`, falling back per glyph to a Liberation subset when a character is outside the encoding while the rest of the face stays in Computer Modern | | M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; route-D reads `\documentclass` size options (10/11/12pt) into the paragraph base size and `\baselineskip`, executes `\newcommand`/`\renewcommand`/`\DeclareRobustCommand` macros textually (with numbered arguments, one `[default]` optional first argument and an eight-pass recursion guard; `\edef`/`\xdef` expand their bodies at definition time and `\csname...\endcsname` resolves to the named control sequence; `\expandafter` expands the zero-argument macro after its prefix once (chained prefixes expand in order), `\@gobble`/`\@gobbletwo` discard arguments and `\@ifmtarg{arg}{yes}{no}` chooses a branch by emptiness, and definition prefixes (`\long`, `\global`, `\outer`, `\protected`, plus `\gdef` and `\protected@edef`/`\protected@xdef`) are accepted), and expands `geometry`, `\setlength`, title/author/date, `\maketitle`, sectioning, theorem, float and bibliography markup; local `.cls`/`.sty` files are inlined, execute their `\DeclareOption` subset for the options given on `\documentclass`/`\usepackage`, and recurse through local `\LoadClass` bases, while full class layout execution remains absent | | M7 incremental integration | partial | route-D preview/PDF/edit endpoints plus opt-in `?engine=route-d` project preview, content-based page hashes and section/emphasis/display-math/inline-math/itemize/enumerate/description/quote/center/flushleft/flushright mapping; editor toggle in `texrra-web`; project route-D previews are memoised by a hash of the expanded source (32 entries) and invalidated automatically when the source changes; project route-D PDF exports are cached by the same expanded-source hash (eight entries) and report `X-Texrra-Cache: hit`/`miss`; the flat `POST /api/route-d/preview` and `/api/route-d/pdf` endpoints likewise memoise the last 32 previews and eight PDFs by source hash and report the same header; malformed sources answer 422 with a JSON `{"error": "..."}` body and never populate either cache, the flat caches keep the newest 32 previews and eight PDFs in FIFO order (eviction is covered by tests), and four concurrent identical flat previews (or three flat PDFs) share a single mutex-protected cache entry and return identical bodies; a deployment can default to route-D with `TEXRRA_ENGINE=route-d`, and an explicit `?engine=` overrides that default for both project previews and PDFs (v1 and route-d alike; covered by an engine-parameter matrix test); inline `$...$`/`\(...\)` math is laid out inside 10pt paragraphs, while larger paragraphs keep delimiters literal; `\href` labels paint PDF `/Link` URI annotations over their runs | v1 remains the production renderer; the route-D core is additive and tested independently. `\substack{a\\b}` parses each row and stacks them as `MathAtom::StackLines`. `\mathring{x}` is the U+030A ring accent. `\overleftrightarrow` uses U+20E1. `Unit::mark(id, class, text)` and `Unit::float(id, placement, width, height)` are convenience constructors for M2 page items. `\mathop` uses the Op spacing class (3mu against ordinary atoms). `\mathstrut` is a zero-width strut with 7pt height and 2pt depth. M3 painter: `Page::display_list()` and `Halign::display_list()` produce absolute text, rule and line primitives. `DisplayList::to_svg()` writes a standalone SVG; paragraph glyphs and math atoms are painted at their measured positions. PDF writer: `crates/texrra-tex-core/src/pdf.rs` writes multi-page PDF 1.4 with five embedded Liberation Type0/CID faces (Identity-H + ToUnicode + `/W` arrays), filled rectangles, diagonal rules, raw-RGB `/XObject` images, `/Annots` URI links and arbitrary `/special` operators. Ligature substitution and line-end italic correction are implemented; full NFSS family switching remains open. M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono,MonoItalic,Sans,SansBold,SansItalic,SmallCaps,Slanted,BoldSlanted}` plus the math faces. Roman/Bold/Italic/BoldItalic/Mono text are painted with embedded Liberation Type0/CID fonts, each with a ToUnicode CMap and `/W` width array. `cmr10.tfm` is parsed at runtime for widths, heights/depths, kern pairs and ff/fi/fl/ffi/ffl ligatures; line-end and math-script italic corrections and monospace/sans paragraph faces are applied; paragraph-level NFSS declarations (`\rmfamily`, `\sffamily`, `\ttfamily`, `\bfseries`, `\itshape`, `\texttt`, `\textsf`) select those faces and the `\fontfamily`/`\fontseries`/`\fontshape`/`\fontencoding`/`\selectfont` command forms and `\usefont{encoding}{family}{series}{shape}` plus legacy `\rm`/`\sf`/`\tt`/`\bf`/`\it`/`\sl`/`\up`/`\normalfont` declarations are parsed; inline `\textbf`/`\emph`/`\textit`/`\texttt`/`\textsf` groups and `{\bfseries ...}` declaration groups (including nesting) split a paragraph into styled runs, each shaped by its own TFM and painted with its own face; nested faces compose relatively (`\emph` inside bold yields bold italic via cmbxti10, `\emph` inside italic returns upright, `\sffamily\bfseries` yields cmssbx10 and `\sffamily\itshape` cmssi10, while bold-italic sans falls back to cmssbx10 as TeX's OT1 substitution does; `\scshape`/`\textsc` select cmcsc10, with the last shape command winning and bold small caps substituting cmbx10; `\slshape`/`\textsl` select cmsl10 (or cmbxsl10 with a bold series) instead of the italic cmti10, and `\ttfamily\itshape` selects cmitt10; declarations such as `\bfseries` also switch the face for the rest of their group, and `\em` toggles emphasis relative to the current run); styled runs are stored on the paragraph unit, so incremental edits rebuild them through `Engine::edit_runs` instead of flattening the paragraph back to one face; true family/series/shape switching remains open; route-D PDFs now embed all twelve Knuth Computer Modern Type1 programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) as simple fonts (PFB `Length1/2/3`, `/Encoding /Differences` from each program's built-in encoding, `/Widths` in 1000-unit text space from that face's TFM advances) for the characters the program encodes and a Liberation Type0 subset for the uncovered ones on the same page; `pdffonts` reports `Type 1` faces (CMR10, CMBX10, ...) and `pdftotext` still extracts the text. `Unit::paragraph` now builds its item stream with `layout_paragraph_with_font`, so CMR10 advances, kerns and ligatures drive paragraph widths; each glyph box also carries the TFM height/depth, and the painter emits glyphs at the box's own size when a mid-paragraph size command split the run (otherwise the paragraph's base size) (`\fontsize` and `\tiny`...`\Huge` scale the shaped metrics and default interline glue, while `\hsize`, `\parindent` and authored skips stay absolute) and the Type0 `/W` array reports CMR10 advances, and ligature boxes paint their component letters, so `pdftotext` keeps word boundaries instead of inserting spaces between letters. M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments. M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. A `[t]` float seen while a page is already being filled is installed at the top of that same page, exactly as TeX's `\@toplist` does: the page height gains the float plus one `\textfloatsep` (or `\floatsep` between stacked floats), so the body stops earlier instead of the float waiting for the next page; only a break before the float moves it forward. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item, and `Document::split_max_depth` (TeX `\splitmaxdepth`, `\maxdimen` by default) clamps the first held box's depth while moving the excess into its height); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the later candidate wins, matching the page builder's `least_page_cost` update with `<=`, so a page can take a later break even when it overfills the goal slightly; when no break fits within the glue shrink, the least overfull break is used instead. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. Each multi-line paragraph inserts TeX's `\clubpenalty` after its first line and `\widowpenalty` before its last (150 in LaTeX, overridable through `\clubpenalty`/`\widowpenalty`); a page penalty of 10000 or more is not a legal breakpoint, and forcing either register to -10000 breaks exactly where pdfLaTeX does (two page oracle fixtures). Display math units also reserve LaTeX's `\abovedisplayskip` above and `\belowdisplayskip` below (10pt plus 2pt minus 5pt at 10pt, 11pt/12pt class values otherwise); the four registers, including the short forms, are read from the source in both `\abovedisplayskip=10pt plus 2pt` and class-file `\abovedisplayskip 7\p@ \@plus 2\p@` spelling, `\belowdisplayskip \abovedisplayskip` copies resolve, and a page oracle pins a display that no longer fits moving to the next page exactly as pdfLaTeX does. Class setup written inside `\AtBeginDocument{...}` is lifted ahead of `\begin{document}` and executed as preamble, and `\newgeometry{...}` applies its options there; an explicit `textheight`/`textwidth` wins over margins, so the arXiv template's `\newgeometry{textheight=9in,textwidth=6.5in,top=1in}` keeps its 6.5in measure (the display-skip and geometry warnings it produced are gone). Paragraph boxes carry TeX depth: each node reports its last line's descent, so `\pagedepth` sees it, and the builder adds every box descent beyond `\maxdepth` to the page height while keeping the rest as page depth (TeX's per-box rule); route-D sources default `\maxdepth` to LaTeX's 5pt (0.5\topskip), and the page fixtures set it explicitly. A standalone `\smallskip`, `\medskip`, `\bigskip`, `\vskip` or `\vspace{...}` line between paragraphs becomes the following unit's `space_before` glue, carrying TeX's width plus its `plus`/`minus` parts (`\smallskip` is 3pt plus 1pt minus 1pt, and so on). Both page builders reserve it, the paged builder gets a real breakpoint with the glue's stretch and shrink, and edits preserve all three components; the command no longer leaks into the paragraph text. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and preview pages apply the same offsets to their display list so the editor and PDF agree. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance`, `\pretolerance`, `\hangindent`/`\hangafter`, `\spaceskip`/`\xspaceskip` and `\frenchspacing` into the paragraph styles; `\textwidth`/`\hsize` (including `\setlength{\textwidth}{...}`) set the paragraph measure, and `\setlength` also applies to the supported layout lengths with `\parskip` keeping its plus/minus glue; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty`, `\deadcycles` and `\maxdeadcycles`), dropping pages the routine does not ship. A `\mark{...}` or classed `\marks{...}` write inside the routine is recorded by the interpreter and placed at the front of the next page's marks, so the carried marks TeX exposes to the following page are reproduced. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\advance`, `\multiply` and `\divide` adjust those registers in place (`\advance\pageno by 2`, `\divide\deadcycles by 2`, `\advance\dimen2 by 5pt`), and an arithmetic `\vsize` change retargets later pages exactly like an assignment; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; Route-D sources map a standalone `\newpage`, `\clearpage` or `\cleardoublepage` onto `Document::page_breaks`, and `\onecolumn`/`\twocolumn` are consumed because the engine lays out one column (a `multicols` wrapper is consumed the same way), so the next paragraph starts on a fresh page (the paged builder turns each break into a `-10000` penalty node); the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet: the remaining fragments are rebuilt from the next node index with the new goal, which works with insertion material because class limits apply while the page is assembled; a deferred bottom float disables the retarget because the carried queue cannot be rebuilt. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. `\vbadness` carries the page's break badness and `\insertpenalties` counts insertion items the class limits held over, so an output routine can react to overfull breaks or split insertions. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. A document that contains a bottom float likewise rebuilds in full: a deferred float is carried on the page fragment, and a suffix replay starting at a page boundary cannot recover that queue. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: ten page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, a 30pt `\topskip`, a forced `\newpage`, stretchy `\vskip` glue between paragraphs, footnotes raised with `\footnotetext`, and a `[t]` float that reserves its height plus `\textfloatsep` on the page it appears, and `[b]` floats that fit or defer to the next page) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row heights and cell text widths to scaled points; the painter uses 10pt glyphs in 12pt rows. Rules and spans are painted; tall tables split at row boundaries (`Halign::split_for_height`) with column widths preserved. Math coverage includes fractions/roots, scripts, `\left...\right` with body-scaled delimiters, `\middle`, `\big`/`\Big`/`\bigg`/`\Bigg` and their `l`/`r` forms, control-sequence delimiters, accents (dot/check/breve/acute/grave/ring), `\text`/`\mathrm`, `\overbrace`/`\underbrace`, `\overset`/`\underset`, `\xrightarrow`/`\xleftarrow` with an optional below label, `\binom`, `\cancel`/`\bcancel`/`\xcancel`, `\bmod`/`\pmod`, fence symbols, `\operatorname*` and `\mathop` limits, and `\ensuremath{...}` lays its body out as math and re-enters text otherwise. Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph. The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1055 tests (439 route-D unit, 425 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 63 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4. ### M0 incremental demo `crates/texrra-tex-core/examples/incremental_article.rs` builds a three-paragraph article, edits the middle paragraph, and prints the pages that checkpoint replay rebuilt. The expected result is page 2 only when the edit does not change page 1's content or the page count. Run it with: ``` cargo run -p texrra-tex-core --example incremental_article ``` ### PDF smoke example `crates/texrra-tex-core/examples/pdf_display.rs` writes a Letter-size PDF with text, a rule, a 2x2 RGB XObject and a URI link: ``` cargo run -p texrra-tex-core --example pdf_display > /tmp/route-d.pdf ``` ### G1 audit (P0-P2) The `G1` scope of [`ROUTE_D_PLAN.md`](ROUTE_D_PLAN.md) is implemented and covered by the suite: | Milestone | Evidence | | --- | --- | | P0 oracle harness | `crates/texrra-tex-core/tests/oracle.rs` runs pdfLaTeX/pdftoppm/pdftotext comparisons, skips when a tool is missing, and covers 35 paragraph/page fixtures: measure matrix 90-240pt, `\tolerance`/`\pretolerance`/`\emergencystretch`, `\hangindent`/`\parshape`, `\parfillskip`, glues, sentence spacing, narrow-measure pretolerance, page breaks, floats, insertions and `\newpage`. | | P1 paragraphs | TeX passes and demerits (`\pretolerance`/`\tolerance`, adjacent fitness 0-3, line penalty, `\adjdemerits`, double/final hyphen demerits, `\emergencystretch`), hyphenation from flat/exception data, `\hangindent`/`\hangafter`/`\parshape`, `\looseness`, `\leftskip`/`\rightskip`/`\parfillskip` with `fil`, `\baselineskip`/`\lineskip`/`\lineskiplimit`, `\parskip` with plus/minus, `\spaceskip`/`\xspaceskip`, `\sfcode`/`\frenchspacing`, `\tolerance`-family registers, interword `fil`/`fill` glue, italic correction and TFM kerning/ligatures. | | P2 page builder | TeX candidate-break cost and legal glue breaks, glue setting (`\raggedbottom`/`\flushbottom`, glue orders), `\vsize`/`\voffset`/`\topskip`/`\maxdepth`, paper size, marks (classed, carried to the next page), insertion classes (`\count`/`\dimen`/`\skip`, splitting, held-over, dedicated held pages), and interpreted `\output` with `\shipout\box255`, conditionals, arithmetic, mark writes, register reads/assignments and page retargeting. Floats keep their top/bottom/in-text/float-page policies. | Residual approximations, documented rather than special-cased: - the content of `\box255` is not inspectable (its width/height/depth are); - `\topmarks`/`\firstmarks`/`\botmarks` are not readable by the routine; - an assigned `\vsize` cannot retarget a document that defers bottom floats; - paged replay falls back to a full rebuild when an interpreted `\output` routine or insertions are present; - a narrow-measure `\tolerance=10000` break can differ from TeX's demerit optimum because the model uses the simplified badness table; - NFSS family switching and multi-face Computer Modern outlines are not implemented (route-D embeds Liberation faces). ### G2 audit (M3-M7) The `M3`-`M7` stage of the roadmap is implemented to the extent recorded below. The goal ran for 90 rounds and landed 123 commits (`8c42f2d..c9a074b`); the workspace suite is at 839 tests. | Milestone | Evidence | | --- | --- | | M3 `\halign` | shared column widths, `l`/`c`/`r`/`p{width}` with wrapped cells, `\tabskip`, `@{}`/`@{\hspace{...}}`, booktabs rule weights and partial spans, `\cline`, `\noalign{\vskip}`, `\multicolumn`, longtable heads/feet, `*{n}{cols}`, vertical `|` rules, optional position/bracket arguments, row `\\[dim]` gaps, LaTeX `tabular`/`longtable` capture, `tabularx` targets whose `X` columns share the leftover width, `\multirow{n}{width}{text}` cells expanding to their text on the first row of the span, and page splitting that keeps column geometry. | | M4 math | `cases`, `matrix`/`pmatrix`/`bmatrix`/`Bmatrix`/`vmatrix`/`Vmatrix` and `array` environments laid out as two-dimensional grids with sized delimiters; Computer Modern math metrics (cmmi/cmsy/cmex/msbm/eufm) embedded as Type1 outlines, TeX's 3/4/5mu class table, `\mid`/`\colon`, `\mskip`-family dimension scans, `\frac` and infix fraction forms, `\left`/`\right`/`\middle` and `\big` CMEX sizing, `align`/`gather`/`alignat` row layout with per-row tags, `split` blocks numbered once and `multline` edge alignment, equation numbering with `\eqref`/`\ref`/`\tag`/`\notag`, `cases` with `&`-separated cells, matrix delimiters and `array` column specs (matrix rows advance 12pt and cases 14.4pt, matching amsmath's `\arraystretch`, and pmatrix/cases word positions are checked against pdfLaTeX within 1pt), math alphabets (`\mathbf`/`\mathit`/`\mathsf`/`\mathtt`/`\mathcal`/`\mathbb`/`\mathfrak`) wide-display line splitting, `\operatorname`/`\operatorname*` upright operator names with optional stacked limits, and `\DeclareMathOperator` definitions. | | M5 fonts | twelve Computer Modern text programs (roman/bold/italic/bold-italic/mono/sans/sans-bold/sans-italic/small-caps/slanted/bold-slanted/mono-italic) plus four math programs, all embedded as Type1 with TFM widths; NFSS declarations, legacy switches, paragraph/inline runs with relative composition, per-run base sizes, superscripts/subscripts, accent composition, case commands, per-glyph Liberation fallback and Type1 ToUnicode CMaps; colour, link and explicit-size runs are split in 10pt paragraphs, while larger class sizes keep those commands on the plain-text path. | | M6 class execution | article size options and `\linespread`, title/author/date and `\maketitle`, five-level sectioning with counters, TOC and float lists with page numbers and dot leaders, floats and in-text graphics with `\includegraphics` sizing/`\graphicspath`, footnote insertions, `thebibliography`/`\cite`, theorem environments and `\newtheorem`, nested lists with article skips and hanging indents, `quotation`/`quote`/`verse`, `minipage`, `\today`, page numbering, label/counter renaming, and preamble macro execution (`\newcommand`/`\def`/`\let`/`\newenvironment`/`\newif`/`\newlength`/`\newcounter`). Project `.cls`/`.sty` files are inlined with `\DeclareOption`/`\ProcessOptions`/`\ExecuteOptions`, `\LoadClass` inheritance, recursive `\RequirePackage`, local `\input`, `\AtBeginDocument` hooks and `\PassOptionsToClass`/`\PassOptionsToPackage`. | | M7 service | route-D preview/PDF/edit endpoints and the `?engine=route-d` project switch, `TEXRRA_ENGINE` default, memoised project previews/PDFs (source and image bytes in the key), flat endpoint caches with FIFO eviction and concurrency coverage, JSON 422 errors, PDF `/Link` annotations from `\href`, per-glyph Unicode extraction, and a `warnings` array in preview JSON that reports unsupported environments and control words that survived layout instead of failing silently (custom `\newtheorem`/`\newenvironment` names count as supported, and three compatibility corpus documents render with an empty array). | Residuals are deliberate and documented rather than template special cases: - class files are executed as declarations, options, macros and includes; their full layout code is still modelled by route-D's native semantics instead of being interpreted token by token; - arbitrary package code and BibTeX are not executed; - `\box255` content remains uninspectable beyond its dimensions; - a table cell or list item cannot yet contain a `minipage`; - floats and insertions take the scrolling-builder path in the paged incremental replay; - Unicode coverage follows the Liberation fallback subset. ### Open milestones The staged program that closes these milestones is described in [`ROUTE_D_PLAN.md`](ROUTE_D_PLAN.md). Route D currently covers M0-M4/M6 as a working subset. The remaining milestones are deliberately open rather than approximated: - **M1**: the paragraph model covers generic `fil`/`fill` glue orders and `\prevgraf`, plus the tolerance, penalty and demerit registers, `\hyphenation` exceptions, `\hangindent`/`\parshape`, `\parfillskip` with or without `fil`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, the default `\sfcode`/`\frenchspacing` sentence spacing, explicit `\spaceskip`/`\xspaceskip`, stretch and shrink on the inter-paragraph `\parskip` glue, and `\raggedright` (infinite `\rightskip` fil) are modelled. - **M2**: `Engine::layout` keeps the scrolling builder as the non-paged fallback, while route-D previews and PDFs run `Engine::layout_paged`. `page::PageBuilder` implements TeX's candidate-breakpoint cost (badness + penalty, glue stretch/shrink, `\topskip`, `\maxdepth`), legal glue breaks (glue after glue is not a breakpoint and the glue at a break is discarded), `\raggedbottom`/`\flushbottom` and the `\vfil`/`\vfill`/`\vfilll` orders, per-page `\vsize` and `\maxdepth`, top/bottom/in-text floats with `\floatsep`/`\textfloatsep`/`\intextsep` and the fraction/count limits, and insertion classes with `\count`, `\dimen` and `\skip`, splitting and held-over material. `Document::output_routine` is interpreted after every paged page for `\shipout\box255`, `\relax`, `\message`, `\mark`/`\marks`, `\ifdim`, `\ifnum`, `\ifodd`, `\ifcase`, `\advance`/`\multiply`/`\divide` and register assignments; the routine reads `\pagegoal`, `\pagetotal`, `\pagedepth`, the page stretch registers, `\vbadness`, `\insertpenalties`, `\ht255`/`\dp255`/`\wd255`, `\hsize`, `\vsize`, `\topskip`, `\maxdepth`, `\outputpenalty`, `\pageno`, `\deadcycles`, `\maxdeadcycles`, `\prevgraf` and the insertion registers, and its `\vsize`, `\dimen`, `\count` and `\skip` assignments rebuild the pages it has not seen yet. Explicit `\hoffset`/`\voffset` offsets are applied by the PDF writer and the preview display list. - **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. only used text faces embed Liberation Serif/Mono as Type0/Identity-H; each face is subset to the glyphs actually used (composite components included, glyph IDs retained); FontFile2 and ToUnicode streams use Flate compression; the ToUnicode CMap follows the used characters; ff/fi/fl/ffi/ffl ligatures come from TFM, and CMR10 italic corrections are applied at line ends; full NFSS family switching is not implemented. - **M6**: class-file execution and the parser side of `\output`/`\insert` are still semantic: the source parser maps LaTeX constructs onto the document model and `Document::output_routine` is the interpreted program. `OutputRoutine::wants_break` remains a Rust hook for forcing a page break between units, insertion material is stacked by class from the page bottom, and the page box (`\box255`) exposes width/height/depth but not its content. Class files contribute multi-line `\newcommand`/`\def`/`\newenvironment` bodies: the source is joined at balanced braces and the whole definition is captured, while `\ifhmode`/`\ifvmode`/`\ifmmode` resolve as the horizontal/vertical/math approximations. The arXiv class now previews with no warnings in two pages: `\maketitle`/`\thanks` stay on the native title path, heading commands are not expanded through class redefinitions, `\keywords` becomes a plain paragraph, `\lipsum[n]` expands to filler text, comments and external `\bibliography` commands are dropped, and `center`/flush environments that follow text start their own block. `geometry`'s `top`/`bottom` options shift the page body below the sheet edge (the arXiv template's first baseline now sits at 1in + 12pt instead of the page edge), while an explicit `textheight` still wins over margins. `\pagestyle{fancy}` with `\fancyhf`/`\fancyhead`/`\fancyfoot` and the `\lhead`/`\chead`/`\rhead`/`\lfoot`/`\cfoot`/`\rfoot` shorthands paint L/C/R running heads at `top margin - headsep` and feet at `text height + footskip`, expand `\thepage` per page, resolve `\leftmark`/`\rightmark` from the last `\markboth`/`\markright` (including marks written inside running text) or, when no explicit mark is set, from the current numbered heading on that page, draw `\headrulewidth`, and suppress the head and number on a title page; the arXiv template shows `A Preprint` (right) and its short title (centre) on pages after the title page. - Page hashes cover rendered items/insertions/marks/floats, not source-dependency metadata, so replaying an earlier page cannot change its hash merely by re-attaching source hashes. - **M7**: `POST /api/route-d/preview`, `/api/route-d/pdf` and `/api/route-d/edit/{unit}` expose route-D pages, PDF export and edit diff. The project preview can opt in with `POST /api/projects/{id}/preview?engine=route-d`; `route_d::project_preview_json` strips the preamble/body wrapper and keeps a project-scoped `(paragraphs, Engine)` session. An unchanged source returns `changedPages: []` and `recomputedPages: 0`; same-count paragraph edits and structural edits that keep a non-empty paragraph prefix are rebuilt from the first difference through `Engine::relayout_from`, which reuses the sealed pages before that checkpoint; edits without a reusable prefix fall back to a full layout. The v1 semantic pipeline remains the default fallback. LaTeX-to-route-D semantic mapping is still a subset, and `route_d_page_matches_pdftex_raster_geometry` lays out a 480pt CMR10 paragraph at the same scaled-point geometry the server uses, rasterizes the route-D PDF and a pdfTeX Letter page at 72 dpi, and asserts matching ink line count plus left/right/bottom edges. It skips on hosts without `pdflatex`/`pdftoppm`. Exact glyph-outline pixel equality is still open because the two paths use different font outlines. - `\middle` does not scale with its enclosing delimiter; math delimiters are scaled glyphs rather than TeX delimiter variants. ## Limits and remaining gaps The suite currently stands at 1055 passing tests, with the workspace clean. Route-D serves both flat `/preview` and project preview/PDF requests by default (automatic v1 fallback; `?engine=v1` or `TEXRRA_ENGINE=v1` opts out). The objective's areas are implemented to the limits below; complex-script shaping is outside pdfLaTeX's own scope. A corpus sweep of the three `examples/` documents and the arXiv template reports 0 warnings for all four (guillemets, inline spacing, `\parbox`, `\orcidlink` and bare `\hrule` are handled), and the server test `corpus_documents_preview_without_warnings` keeps that true. The current verification snapshot lives in `docs/ROUTE_D_STATUS.md`. Status by area: service default is done (flat and project endpoints); saveboxes are measured and frozen apart from image-only bodies; tables support real nested tabulars but not `\valign`; fonts expose the twelve CM faces plus fontspec family aliases; the macro engine remains textual (scopes, parameters, `\futurelet`, `\aftergroup`, `\afterassignment`, `\scantokens`, token registers) without a full token stream or general catcode table. The open items are: - **Macro engine scope**: `\def`-style definitions, registers, conditionals, `\csname`, `\expandafter`, delimited parameters and `\edef` are executed textually. `@` is a letter in a control word only between `\makeatletter` and `\makeatother` (grouping restores the state); user names containing it are canonicalised through a private-use placeholder, while route-D's own `\@...`/`\p@`-style names and a small internal list stay literal so their handlers keep matching. A line-based capture only consumes a definition when it ends the line. Runtime expansion keeps a scope stack for `{}` and `\begingroup`/`\endgroup`: a `\def` inside a group is local to it, while a top-level `\def` or any `\gdef` updates the document table; grouping braces are removed after command parsing. Runtime `\let\alias=\target` and `\chardef\name=` also define (or locally shadow) commands, and the line-based capture only runs before `\begin{document}` and outside braces, so a definition on its own line inside a group stays local. `\edef`/`\xdef` lines in the preamble and in the body expand their bodies (including `\csname`) when read, while a plain `\def` stays lazy. `\gdef`/`\xdef` and an inline `\global\def` update the global table and clear any same-name group shadow. A runtime `\def` also parses its parameter text, so a body-embedded `\def\foo#1{...}` (undelimited or delimited) expands with its arguments instead of leaking. A `\catcode` assignment is consumed for any target (backtick, bare or code-point form); `@` (values 11/12) and `%` (value 12 makes comments literal) are applied, so class files that set them directly work, while other catcode values are consumed but not applied yet. Comment stripping now lives in the same canonicalisation pass. There is no token stream. A runtime `\csname ... \endcsname` (also inside ordinary macro bodies) expands its contents and resolves the named macro, consuming the target's arguments when it is parameterised and yielding nothing when undefined. `\futurelet\alias\command ` binds the looked-ahead token to the alias without consuming it, and `\aftergroup` (or `\aftergroup{...}`) queues its token until the enclosing `{}` or `\begingroup` closes, then injects it after the group. `\afterassignment` moves the token behind the following register or `\def` assignment so it runs once the assignment has been processed. `\scantokens{...}` replaces itself with the group text so later passes re-tokenise and expand it again. Token registers work in the common forms: `\newtoks\name`, `\name={...}`, `\toks0={...}` and `\the\toks0` / `\the\name` store and splice the register text. `\string` prints the token without expanding it, with backslash/braces carried through private-use placeholders so they render but never re-tokenise. `\meaning` prints `macro:->` for a macro (or `\relax` for an undefined control sequence) with the same literal escaping. `\expanded{...}` expands its argument immediately, `\unexpanded{...}` keeps its tokens out of the current edef-style pass (they expand later at use time), and `\detokenize{...}` prints it literally. `\protect` before a token keeps it from expanding in an edef-style pass; in normal text it is dropped and the token expands as usual. Conditionals are evaluated after macro expansion with their operand tokens protected from expansion, then before register expansion. - **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox` bodies are inserted as one unbreakable inline box (interword spaces become fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox width/height/depth are measured at definition and frozen (a box keeps its definition size inside differently sized text), and `\wd`/`\ht`/`\dp` expand to those metrics; a box whose body contains `\includegraphics` measures the decoded image at 72 dpi, honouring explicit width/height options. - **Tables**: `\multirow` centres over its rows, `array` column modifiers `>{}`/`<{}` and the outer `\tabcolsep` margins are parsed. A nested `tabular` is attached to its outer cell as a real inner table: column widths and row heights account for it, the inner table is painted at the cell position, and page splitting remaps its row index. Images inside a nested table are not merged into the outer display list. `\valign` is rewritten into a transposed `tabular` (column-major input becomes rows); its preamble alignments and vertical rules are ignored and the cells are left-aligned. - **Fonts**: the twelve Computer Modern faces and four math faces are embedded as Type1 with per-glyph Liberation fallback. Greek math commands map to their Unicode letters and render through the math-italic fallback (widths approximate the TFM metrics). fontspec's `\setmainfont`/`\setsansfont`/ `\setmonofont` are consumed, and `\newfontfamily` maps a family to the closest engine face by name (sans/mono/serif). Complex scripts such as Devanagari, Thai and emoji have no shaping fallback and render as missing glyphs; arbitrary external font families remain open. - **Inline runs**: colour/link/sized runs split at any base size. Inline math renders at any base size: the 10pt math display list is scaled as a unit (glyphs, advances, rules and delimiters) to the paragraph size, so 12pt and `\large` documents keep formulas in proportion with no literal `$`.