Files
texrra-engine/README.md
T

67 KiB
Raw Blame History

texrra engine

Texrra is building a TeX engine for live editing of existing LaTeX projects. It tracks inputs and compilation state, reuses eligible work after edits, and publishes updated pages with source locations. The delivery targets are a library, a CLI, and editor integration. The current Route-D implementation is the development baseline. Upstream TeX components are candidates for reuse where their state, file effects, and cancellation can be verified.

The product goal defines compatibility and live preview acceptance. The publisher matrix covers original journals, two-column journals, conferences, and arXiv.

Native execution bootstrap

The current Route-D entry is available through the developer CLI and the native editor example. Its implementation and remaining work are tracked in the stage progress. The separate frontend repository is texrra-web.

Native fonts come from an explicit resource World. For the checked-in examples, configure the actual TFM/PFB directories and an installed font-map directory:

export TFMFONTS="$PWD/crates/texrra-tex-core/assets"
export T1FONTS="$PWD/assets/fonts"
# Example TeX Live map directory on this development system; configure yours.
export TEXFONTMAPS=/var/lib/texmf/fonts/map/pdftex/updmap
cargo run --release -- native examples/native-bootstrap/main.tex /tmp/bootstrap.pdf
cargo run --release -- native --initex --etex examples/native-bootstrap/dynamic-fonts.tex /tmp/fonts.pdf
cargo run --release -- native --job --initex --etex examples/native-bootstrap/native-job.tex /tmp/native-job.pdf
cargo run --release -- native --job --initex --etex examples/native-bootstrap/device.tex /tmp/device.pdf

--job selects actual online native page/output/shipout execution. It exports only boxes really shipped by the token executor; deferred I/O runs when its original material is shipped. Each shipout captures its actual paper, origin/offsets and mag; zero paper dimensions use the real box's dimensions. The logical box and actual font resources are retained, with a common physical transform for PDF/SVG. Native mag/true and device state records the supported semantics and remaining PDF configuration/precision work. The entry without --job remains a list-measurement tool for existing algorithm gates; its host canvas does not certify native pagination. There is no automatic fallback between these targets. See native pages and remaining device work.

INITEX starts with actual nullfont and zero layout dimensions. Non-INITEX bootstrap loads its initial cmr10 through World. The current native job reports missing resources directly. Use --texmf-root, resource search environment variables and --input-policy for distribution/project resources; --resource-manifest records actual reads, versions and negative lookups, including failed jobs. The CLI defaults to TeX 8-bit input. Use --input-profile xetex --etex for the native XeTeX language and output profile, or --input-profile unicode for the existing scalar-input mode. Build and load format images with the same profile.

This entry executes native tokens, expansion, scoped state, real streams, measured h/v/math lists, paragraph breaking and display transitions without v1 or source preprocessing. It now carries actual sized FontId resources through text, math, geometry, SVG and PDF. Live fontdimen and em/ex affect their real consumers; output uses actual map/encoding/PFB resources. See native font execution and boundaries. The native editor example exercises the shared compile session and page updates. The production HTTP routes still use the older implementation. Format boot, active compatibility gaps, and whole-project results are tracked in the stage progress.

Streaming TFM keep/pass/boundary execution is connected to actual lists. Owned discretionary branches and actual ligature hyphenation/reconstitution now feed line breaking, packing, diagnostics and output. Two-pass mathematical noad ligature/kern and operator limits/display/rebox execution also use actual font instances and list consumers. Canonical raw paragraph line boxes, running rules/overfull markers, actual shifts/unboxing/lastbox and native math subboxes are connected. Nested boxes suspend and restore actual math/display frames; output and math reuse the same raw-list traversal. Original-list vert_break/vsplit, live split parameters and per-class split marks now execute. Paragraph/adjusted-hbox/display marks migrate at actual pack time; mark expansion retains real input contexts and byte diagnostics. Online page contributions, real output groups/shipout, page marks and deferred file I/O now execute natively. The four-page reference job matches all 174 words, actual auxiliary bytes and all four raster pages. Real mag/true, actual true font sizes and per-shipout paper/origin/offsets now execute; the 15-job/29-page device oracle passes. Real PDF file state, versions, compression, object streams/xref and original-sp precision now execute. The new 28-configuration/56-page and retained device matrices have zero word-box, paper and raster XOR differences. Independent 105-page object stream rollover also passes. Native jobs with \pdfoutput=0 can write binary DVI. Specify the DVI destination explicitly with texrra native --load-format latex.tfx --input-profile tex8bit input.tex output.dvi. The writer serializes the actual shipouts. DVI drivers receive special payloads in their original page order. DVI evidence Actual PK resolution, bitmap decoding, Type3 output and shared text cursor now execute; 384 independent glyphs and a 43-job/86-page oracle pass with zero bitmap/word-box/paper/raster differences. Missing devices/resources fail. Actual native ownership/resource statistics and page-break diagnostics now execute; 16 jobs/48 pages match reference ink and 216 exact page diagnostics. Trace controls preserve native PDF bytes. Actual paragraph traces, canonical-zero glue and owned ordinary side-script lists also execute; 8 jobs/32 pages have 24 exact reports and 5436 pass/decision lines with zero word/raster differences. Other tracing consumers, compound math fields, insertions, format images, real NFSS/article and compile sessions remain required by P2-M1. Unsupported commands and resources are explicit errors.

Component contracts and independent reference checks:

The UI and compatibility features described below belong to the existing application; they do not certify native token-kernel LaTeX portability.

Repository layout

Clone both repositories as siblings so the engine can discover the frontend:

texrra/
  texrra-engine/   # this repository: Rust engine and HTTP server
  texrra-web/      # texrra-web: static editor frontend

The server resolves the frontend from TEXRRA_WEB_DIR when set, otherwise from a sibling web or texrra-web directory (./web, ./texrra-web and their ../ forms). It serves index.html, styles.css, app.js, and favicon.svg; preview font faces are generated by the engine at /fonts.css and /fonts/*.ttf.

Run

git clone https://git.iloveuulove.me/gloamxun/texrra-engine.git engine
git clone https://git.iloveuulove.me/gloamxun/texrra-web.git web
cd engine
cargo run --release -- serve examples/hello.tex 4174

Open http://127.0.0.1:4174. Without an explicit port the server uses 4173. TEXRRA_WEB_DIR can point at the web checkout when it is not a sibling directory.

The server keeps projects in projects/; set TEXRRA_PROJECTS_DIR to use another directory. When the projects directory is empty, the input .tex file's directory is imported as the first project, so the sample document is ready to open. Edits are saved to the file inside the project and recompiled after a short pause.

Testing

cargo test --workspace

The suite has two layers. tests/typeset.rs drives CompilerSession directly and checks the three examples, the arXiv Letter fixture, starred headings, box and rule painting, error reporting, and page-hash cache stability. tests/server.rs starts the real texrra serve binary on an ephemeral port and checks static frontend assets, font CSS, the project API, preview/PDF responses, path traversal rejection, and the renamed /texrra legacy endpoint.

Project API

Endpoint Purpose
GET /api/projects Project list with files and metadata
POST /api/projects?name= Create a project from a ZIP body
POST /api/projects/new?name= Create an empty project
GET /api/projects/<id> Project metadata and file list
DELETE /api/projects/<id> Delete a project
GET /api/projects/<id>/zip Download the project as a ZIP
GET /api/projects/<id>/raw?path= Read a file (download=1 downloads it)
PUT /api/projects/<id>/file?path= Write a text file
POST /api/projects/<id>/files?path= Upload a file
DELETE /api/projects/<id>/file?path= Delete a file
POST /api/projects/<id>/preview Live preview of the main file
POST /api/projects/<id>/pdf PDF of the main file

Projects are ordinary directories:

projects/
  hello/
    hello.tex
    plot.png
  .meta/hello.meta        # display name, main file, timestamps

The upload path rejects absolute paths and .., ignores directory entries, rejects encrypted and ZIP64 archives, and caps a project at 64 MB / 2000 files.

Real-time preview

The frontend shows the Rust layout result live:

  • Every request lays out the document into the same positioned page frames the PDF painter consumes, then serializes each page to inline SVG. Text baselines, line breaks, table rules, image placement, and math boxes therefore match the PDF instead of being re-approximated by the browser.
  • The preview page keeps one <div> per page and replaces only the pages whose content hash changed, so typing does not reload the whole view, jump the scroll position, or repaint unchanged pages.
  • Fonts are served once from /fonts.css and /fonts/*.ttf with long-lived cache headers, so a preview response is only the changed page markup.
  • Font faces, font metrics, and the math metrics snapshot stay cached in the compiler session across requests. A warm edit compiles and transfers in a few milliseconds for the sample document; set TEXRRA_TIMING=1 to log the per-stage timings the server prints.
  • The 导出 PDF button runs the full PDF path and downloads the result. Documents whose layout still falls back to the genpdf page flow report that the live preview is unavailable instead of showing a partial page.

The HTTP endpoints are:

Endpoint Purpose
GET /, /index.html, /styles.css, /app.js Static texrra-web frontend
GET /api/projects... Project management API (see above)
GET /fonts.css, GET /fonts/*.ttf Preview font faces

Legacy single-file endpoints are still available for scripting: GET /source, POST /preview, POST /compile, and POST /texrra operate on the .tex file passed to serve.

Current Rust compiler scope

It handles document metadata, \maketitle, and \today (UTC), A4 pages, geometry margins (margin, top, right, bottom, left, hmargin, and vmargin with mm, cm, in, pt, or bp units), paragraphs, numbered and starred heading levels (article sections; report/book chapters with sections numbered 1.1), paragraph indentation (\parindent), \hfill, serif/sans/monospaced text, true small caps, itemize/enumerate lists, page breaks, basic display and inline math, figures, tables whose cell widths use Computer Modern metricss, section/figure/table references, numeric citations from a manual bibliography or a local .bib file, and natbib-style author-year citations for the arXiv template. A4 pages use 25 mm margins unless geometry sets them. The PDF always embeds its Liberation Serif/Mono/Sans faces (and any CJK fallback), so glyphs do not depend on fonts installed in the reader; font programs and ToUnicode maps are Flate-compressed, so PDFs are larger than Base-14 output but render reliably.

LaTeX compatibility layer

Real templates can load local .sty files and use the common LaTeX parameterization commands:

  • \newif / \iffoo / \footrue / \foofalse conditionals, including \else and \fi branches.
  • \newlength, \setlength, and \addtolength (skip registers), plus \newcounter / \setcounter / \addtocounter.
  • \newcommand, \renewcommand, \providecommand, \def, \let, and legacy commands such as \setlength-style kernel macros; \long/\global/ \outer/\protected definition prefixes, \gdef, and \protected@edef/\protected@xdef are accepted.
  • \newenvironment / \renewenvironment are accepted; layout-critical environments (abstract, figure, table, lists, tabular) keep the engine's native behavior, and redefinitions of the structural commands (\section, \maketitle, font-size commands, font family defaults) are ignored rather than replaced with TeX box code the layout engine cannot run.
  • \AtBeginDocument bodies run immediately, which lets styles apply \newgeometry.
  • Package files are read with @ as a letter, so \@title-style internals tokenize correctly.
  • The abstract environment indents its body as a quotation, and \paragraph produces an unnumbered bold run-in heading.

\documentclass[options]{class} parses class options, accepts the built-in article, report, book, letter, minimal, and standalone classes, and loads a local <class>.cls when one exists. \DeclareOption, \DeclareOption*, \ProcessOptions, \ProcessOptions*, \ExecuteOptions, \PassOptionsToPackage, and \PassOptionsToClass implement the LaTeX option protocol, so local classes and packages receive their options (including options passed before \usepackage). Paper-size options (a4paper, a5paper, b5paper, letterpaper, legalpaper, executivepaper, and landscape) are honored from both the class options and geometry options/\geometry{...} settings, including paperwidth, paperheight, textwidth, and textheight. textwidth centers the text block and textheight sizes it below the current top margin. The chosen page size drives the PDF pages, the positioned layout, and the SVG preview.

\textwidth, \textheight, \linewidth, and \columnwidth are live named length registers: they start at the A4 text block and are updated by \documentclass paper options, \geometry, and \newgeometry, so \parbox{\textwidth}, \rule{\textwidth}{...}, and \includegraphics[width=0.5\textwidth] all follow the current page setup.

Page styles are painted in both the PDF and the SVG preview: \pagestyle{empty|plain|fancy} sets the document default, \thispagestyle{...} overrides one page, and fancyhdr's \fancyhead/ \fancyfoot plus \lhead/\chead/\rhead/\lfoot/\cfoot/\rfoot place runs in the left, center, or right slot. \thepage is resolved when the page is painted, so the footer shows the real page number. Decoration tokens are expanded at the start of the document, after packages have renewed macros such as the short title, and fancy headers get the usual 0.4pt rule below them. The default style is plain (a centered page number).

The following packages are accepted as built-ins: geometry, graphicx, amsmath, amssymb, amsfonts, booktabs, hyperref, cite, natbib, inputenc, fontenc, url, nicefrac, microtype, cleveref, lipsum, doi, authblk, and fancyhdr. Their commands are approximated where they affect text (\url becomes breakable monospace (a ~ outside URLs becomes a space, while URLs keep their tildes), \nicefrac, \cref, \doi, \lipsum, \verb); \hypersetup and \microtypesetup remain PDF-backend no-ops, while fancyhdr's page decorations are painted natively.

Figure and table captions are numbered (Figure 1: ..., Table 1: ...), and \ref to a figure/table label resolves to that number. Display math that is wider than the text column is scaled to fit the column; route-D instead splits wide display formulas at top-level operators. Latin text is hyphenated with plain TeX's English patterns (two letters before and three after the hyphen) through the Knuth–Plass line breaker; math and CJK text are not hyphenated.

\parbox[position]{width}{...} is a block box with a fixed width: the content is wrapped at width, placed in the vertical flow, and painted without a frame (the optional position argument is parsed but ignored). \fbox{...} remains the framed variant of the same block machinery, and its frame/padding are applied only when framing is requested. Like \fbox, a \parbox is an atomic vertical block rather than an inline object.

NFSS-style declarations are supported with TeX group scoping: \bfseries/\bf, \itshape/\slshape/\it, \ttfamily/\tt, \sffamily/\sf, and the resets \normalfont, \upshape, \rmfamily, \mdseries, \rm. They stay active until the end of the current group and nest correctly ({\bfseries a {\normalfont b} c} restores bold for c). \textrm, \textup, \textmd, \textsl, \textsf, \textnormal are grouped style commands for roman/upright/medium/slanted/sans/normal text; \em is an italic declaration (an approximation of the LaTeX toggling behaviour). \scshape and \textsc{...} use true small caps: lowercase letters are rendered as uppercase glyphs at 80% of the surrounding size, while existing uppercase letters keep the full size. Sans, bold, and italic small caps select the matching family and face.

\mbox{...} and \makebox{...} are inline horizontal boxes: the content is measured as a single unbreakable unit, spaces inside become fixed-width kerns (no stretching, no line break, and hyphenation is suppressed inside the box), and nested boxes and inline rules are preserved. Boxes that do not fit on the current line overflow like an overfull TeX hbox rather than wrapping. \makebox[width][l|c|r]{...} fixes the box width and aligns its content, \raisebox{lift}{...} lifts inline content by a dimension, and \fbox{...} draws a framed inline box with 3pt padding and a 0.4pt rule. The \begin{minipage}[t]{width}...\end{minipage} environment lays its content out as a width-constrained block; \vbox{...} and \vtop{...} are accepted as full-text-width blocks.

\checkmark, \textdagger, \textdaggerdbl, \textperiodcentered, \textsection, \textparagraph, \textbrokenbar, and \textvisiblespace expand to ✓ † ‡ · § ¶ ¦ ␣. \hfill and \hfil are infinite horizontal glue: they stretch the current line to the right margin, including the last line of a paragraph.

Numeric/unit symbols \textperthousand, \textonehalf, \textonequarter, \textthreequarters, \textonesuperior, \texttwosuperior, \textthreesuperior, \textordfeminine, \textordmasculine, \textohm, and \textcelsius expand to ‰ ½ ¼ ¾ ¹ ² ³ ª º Ω °C.

Typographic/currency symbols \textasciitilde, \textasciicircum, \textless, \textgreater, \textbar, \textunderscore, \guillemotleft, \guillemotright, \textquotesingle, \texteuro, \textsterling, \textyen, \textcent, \textdegree, \textpm, and \textmu expand to their Unicode characters.

Letter macros \ss, \ae, \AE, \oe, \OE, \aa, \AA, \o, \O, \l, \L, and \i expand to their Unicode letters.

Text punctuation macros \ldots, \dots, \textendash, \textemdash, \textquoteleft, \textquoteright, \textquotedblleft, and \textquotedblright expand to their Unicode characters.

Text symbols \S, \P, \dag, \ddag, \copyright, \textbullet, \textregistered, and \texttrademark expand to their Unicode characters (§ ¶ † ‡ © • ® ™).

\linebreak, \nolinebreak, \nopagebreak, and \samepage are accepted (their optional [penalty] argument is consumed) as advisory no-ops: line and page breaking stay automatic, and forced breaks continue to use \\ and \newpage.

\thinspace (1/6em), \negthinspace, \enspace (1/2em), \medspace (2/9em), \negmedspace, \thickspace (5/18em), and \negthickspace are horizontal skips, so they produce real gaps in text (previously \enspace was an ordinary space and the others were undefined).

\quad and \qquad are horizontal skips of 1em and 2em, so they produce real gaps in text as well as in math (previously they were math-space events that collapsed to an ordinary space in text).

\vspace and \hspace are primitives that accept both the braced form and the starred form (\vspace*{12pt}, \hspace*{1cm}); the star is consumed and the dimension is passed to \vskip/\hskip.

\textwidth, \textheight, \linewidth, and \columnwidth are live named length registers updated from the page size and geometry, so \parbox{\textwidth} and \rule{\textwidth}{1pt} follow the current text block. The mm-to-TeX-point conversion differs from TeX by about 0.4%.

\smallbreak, \medbreak, \bigbreak add the corresponding skip (the encouraged page break itself is not inserted yet). \tableofcontents, \listoffigures, and \listoftables generate a heading followed by one entry per numbered section or captioned figure/table; page numbers are filled in after pagination. Entries use infinite glue for right-aligned page numbers rather than dotted leaders.

Vertical skips are active: \smallskip, \medskip, and \bigskip map to 3pt/6pt/12pt \vskip glue, and \addvspace{...} forwards its argument to \vskip (ordinary \vspace{...} already did).

\hrule is a full-width block rule (0.4pt high by default): it occupies its own vertical slot, paints a filled rectangle in the PDF and SVG preview, and is separated from surrounding paragraphs like a normal block. The plain-TeX height and width arguments are parsed (\hrule height 6pt, \hrule width 60mm height 2pt); without a width the rule spans the text block.

The center environment is a block: its content wraps at the text width and every line is centered without justification (natural spaces), so \begin{center}\url{...}\end{center} and centered short text match LaTeX. \centering, \raggedright, and \raggedleft are paragraph-level declarations: the affected runs use natural space widths, the declaration is scoped by groups and the matching environments, centered lines are offset by half the leftover width, and ragged-left/right lines are not stretched to the margin.

\rule[raise]{width}{height} is rendered as a filled rectangle in both the PDF and the SVG preview, including raised and dropped rules; a zero-thickness rule reserves space without painting ink. PDF rectangles are native path operators (vendored genpdf fill_rect/draw_rect), so rules and frames no longer create image XObjects. \fbox{...} is an inline framed box: the content is measured as a single unbreakable unit, wrapped in 3pt padding and a 0.4pt frame, and painted in both the PDF and the SVG preview.

Base font-size class options 10pt, 11pt, and 12pt now set the body size and propagate through headings, title material, lists, tables, block boxes, footnotes, and the default paragraph indent. The article default is 10pt, matching LaTeX. A document-level \renewcommand{\maketitle} replaces the engine title block. Journal classes that distribute front matter through commands such as \author, \affil, \abstract, and \keywords are captured as structured metadata. The sn-jnl class then renders a journal title block: centered title, numbered author lines with affiliation marks, affiliation list, e-mail line, abstract, and keywords. Class-internal \maketitle layout is still not executed; the engine builds the block from the captured metadata.

When a document loads arxiv.sty, the engine switches to a native preprint title style: top/bottom title rules, small-caps title with inline emphasis preserved (e.g. the italic arxiv in the class example), \undertitle, two-column author blocks with affiliations and monospaced e-mail addresses, a long date, and \thispagestyle{empty} on the first page. Class and package files that replace \maketitle itself are still ignored, so box-level template code cannot break the native layout. Ordinary text is now placed on a TeX baseline grid (1.2em line height, 0.8em ascent) instead of the fallback TrueType font's larger ascent/descent, which matches LaTeX line spacing and page breaks. Known gaps for full document classes: \parbox/\minipage are block-level rather than inline, and \vbox/\vtop capture vertical material but do not form an independent natural-width box with its own baseline.

\footnote{...} captures its content, emits a superscript marker, reserves space on the page where the paragraph ends, and paints the notes with a separator rule at the bottom of the page. Footnote lines are painted in body coordinates so they stay below the text block rather than overlapping it. \thanks{...} is a footnote in the title or author block and is painted at the bottom of the first page. Its measured height is reserved before body placement, so the last body line stays above the footnote area. Footnotes inside figure and table captions are collected and follow the caption's page; footnotes inside floats or arbitrary boxes are not collected yet.

Basic \input{file} imports are read relative to the main .tex file. Imported files participate in source mapping and frontend cache invalidation. Local style files and .bib files are tracked the same way; editing any of them refreshes the TeX expansion and preview model.

The Rust backend recognizes a compatibility subset of geometry, graphicx, amsmath, amssymb, booktabs, hyperref, cite, natbib, inputenc, and fontenc. The Rust TeX VM handles \usepackage and \RequirePackage in input order. It loads local .sty files from the importing file's directory, the main .tex directory, or directories listed in TEXRRA_STY_DIR (use the platform path separator for multiple directories). A local style can use \def, \newcommand, \renewcommand, and \providecommand to define macros; local package options, arbitrary TeX code, and the full LaTeX package ecosystem are not implemented. These LaTeX command definitions support up to nine parameters, including one optional first parameter with a default value. Unknown packages fail with a clear error. Hyperlinks (\href, \url, and resolved citations) use hyperref's green link colour; \orcidlink{id} renders the bundled official ORCID logo (2.2 mm) linked to orcid.org. Visible \url text also emits a real PDF /Link URI annotation; \href and ORCID-name links still need their target URL carried through the document model.

\includegraphics embeds PNG, JPEG, or BMP files relative to the .tex file, with width=/height=/scale=/keepaspectratio sizing. It supports width, height, and scale; width and height accept physical units or fractions of \linewidth. Images with transparency are not supported by the current PDF dependency. tabular rows use natural column widths (content width plus 6pt \tabcolsep), are centered in the text block, and draw \hline/\booktabs rules exactly over the table columns; l, c, r, and paragraph (p{...}) columns are supported. \multicolumn{n}{align}{...} spans columns, \cmidrule(r){a-b} and \cline{a-b} draw partial rules over a column range, and spanning cells distribute their width over the covered natural columns; the resulting width matches the reference XeLaTeX output. In route-D, \halign/\calign sources support l/c/r/p{width} cells, explicit \tabskip, @{}/@{\hspace{...}} column expressions, \noalign{\vskip ...} row glue, booktabs rule weights (\toprule/\bottomrule 0.8pt, \midrule/\cmidrule 0.5pt) with \cmidrule(lr){a-b} trims and ranges, row-level page splitting that repeats the column widths, longtable head/foot sections (\endfirsthead/\endhead/\endfoot/\endlastfoot) whose continuation chunks repeat the head rows and paint the foot block once, and LaTeX tabular and longtable sources mapped onto the same alignment path, where \multicolumn{n}{align}{...} cells span columns with the requested alignment and \cline{a-b} draws partial 0.4pt rules. Figures honor [htbp] placement hints ([t] is deferred to the top of the next page, [b] to the page bottom, [p] to a float page, [h] stays in the flow); a standalone \vspace{...} between paragraphs becomes vertical glue with its plus/minus parts; tables honor [t] by deferring the caption and rows to the next page, [b] at the page bottom, and [p] with a float page. \label, \ref, and \cite resolve section, figure, table, and bibliography numbers. \bibliography{file} reads a local .bib file (the .bib extension is optional) and formats common author/editor, title, journal, booktitle, volume, number, pages, publisher, institution, school, organization, edition, address, month, note, and year fields. BibTeX @string macros and single-level crossref inheritance are supported. Manual thebibliography entries also work. Documents loading natbib or arxiv.sty render \citet/\citep as author-year citations, format .bib entries in plainnat order (First Last, In ..., pages, publisher/year), add deterministic year suffixes (2014a, 2014b) when several entries share an author and year, indent continuation lines in the plainnat hanging style, and omit numeric bibliography labels; other documents keep numeric citations. Custom .bst sorting/formatting and page-number references (\pageref) are not implemented.

A paragraph starts with the current \parindent (17pt by default); the indent is recorded per paragraph and follows group scoping, \setlength, \addtolength, and \noindent. Headings and \maketitle suppress the next paragraph's indent.

Boxworks' Knuth–Plass line breaker lays out ordinary text paragraphs with the same Latin, CJK, and monospaced font faces used by the PDF renderer, including bold and italic variants, and applies font pair kerning to line-break widths. It adds breakpoints between CJK characters and observes basic punctuation restrictions. Unchanged plain-text paragraph line breaks are reused between edits; source expansion, parsing, and PDF export still run for the full document. Paragraphs with inline math and wide display equations use the Knuth–Plass pass: words break at spaces and top-level math sequences expose penalized breakpoints after relations, binary operators, and punctuation. Fractions, scripts, roots, and delimiters remain indivisible math boxes. Rust paints ordinary paragraph lines at their measured baselines and applies the line breaker's adjusted word spaces. For documents with no title block and only plain paragraphs and headings, Rust paginates and assigns line positions in one positioned-layout pass; genpdf paints those line boxes at the planned coordinates. Mixed-content documents still use genpdf for page composition. This fixed-spacing subset is an initial page-building slice, not full TeX page building. Display math preserves stacked fractions, indexed radicals, scripts, and math atom classes in its expression tree. PDF layout applies TeX's class spacing rules, stacks display limits for common large operators, draws fraction bars and root bars, and supports explicit math spaces. Radical signs use vertical OpenType MATH variants or assemblies when the metrics face provides them. A metrics face with an OpenType MATH table also supplies the axis height, fraction, script, radical-degree, display-limit, and vertical and horizontal glyph construction data. The compiler searches common TeX Live paths for STIX Two Math, New Computer Modern Math, then STIX Math. Set TEXRRA_MATH_METRICS_FONT to a TrueType or OpenType font with a MATH table to select another face; a configured font without the table is reported as an error.

Local math font files can be assigned to TeX's family registers. Paths resolve relative to the .tex file:

\font\mathface=fonts/Math-Regular.ttf
\textfont1=\mathface
\scriptfont1=\mathface
\scriptscriptfont1=\mathface

This selects the face for ordinary glyphs in family 1 at text, script, and scriptscript sizes. Assignments respect TeX grouping, and PDF and SVG use the same glyph outline. \\Uradical and \\Udelimiter also select their glyph variants and assemblies from the requested family; \\Umathaccent selects the accent glyph and horizontal construction from its family. Glyph-based standard accents such as \\hat, \\widehat, and \\overbrace use the current math family's font at the active style size. Regular text shaping is still incomplete. Classic \\left...\\right delimiters use \\delcode to select their small and large math families. Family assignments at text, script, and scriptscript sizes carry through to both PDF and SVG output. \\left...\\right selects the smallest available vertical glyph variant for delimiters and large display operators, and builds taller glyphs from the font's MATH assembly parts. \\left...\\right target sizing follows the assignable TeX parameters \\delimiterfactor (default 901) and \\delimitershortfall (default 5pt), including local and global assignments.

Route-D text faces follow the NFSS declarations and compose with the surrounding run: \sffamily\bfseries selects cmssbx10, \sffamily\itshape selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. \scshape/\textsc select the real cmcsc10 small-caps face, \slshape/\textsl use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and \ttfamily\itshape reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Characters outside a program's encoding fall back per glyph to a Liberation subset, so the ASCII letters of an accented word still use Computer Modern and Greek text keeps its Unicode text under PDF extraction, including capital Omega, because the embedded Type1 faces carry a ToUnicode CMap built from the requested characters rather than relying on glyph names. Accent commands such as \', \`, \", \^, \~, \c, \v and \= compose precomposed Unicode letters and fall back to the base letter plus a combining mark. \textsuperscript and \textsubscript set a 70% run raised or lowered by 0.4em. \MakeUppercase and \MakeLowercase (also \uppercase/\lowercase) transform their braced text while keeping the surrounding face. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. A \textcolor{name}{...} run paints 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 \colorbox{name}{...} paints a filled rectangle behind its text, and \fcolorbox{frame}{background}{...} draws a 0.4pt frame around that rectangle, while \fbox{...} draws the same frame without a background).. Section-wide declarations such as \bfseries apply from where they appear to the end of their group, and \em toggles emphasis relative to the surrounding face. Paragraph base sizes come from \fontsize{<size>}{<baselineskip>} and the article size commands (\tiny through \Huge), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options 10pt/11pt/12pt on \documentclass[...] set the default base size (and article \baselineskip of 12pt/13.6pt/14.5pt), and \linespread{factor} (or \renewcommand{\baselinestretch}{factor}) scales that baseline; a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. Inline math inside a styled run keeps its math face while the surrounding text retains its style. The paragraph measure follows \textwidth/\hsize (or \setlength{\textwidth}{...}), and \setlength accepts the other supported layout lengths, including a \parskip with plus/minus glue; a counter declared with \newcounter{name} starts at zero and can be changed by \setcounter/\addtocounter, and a length declared with \newlength{\name} can be set by \setlength{\name}{...} and then used as the value of a later \setlength{\parindent}{\name}, and \addtolength{\name}{...} adds to such a length, so class code that stores its dimensions in named lengths takes effect. The geometry package's margin/hmargin/vmargin/left/right/top/bottom/textwidth/textheight options (or \geometry{...}) are applied to the page measure and height; other package code is not executed. Block environments center, flushleft and flushright set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. A leading \noindent starts its paragraph flush with the measure. Page numbers print centred below the text block, \setcounter{page} offsets the printed number, \addtocounter{page} shifts it (\pagenumbering resets it to 1), and \pagenumbering{roman|Roman|alph|Alph|arabic} changes their format and \pagestyle{empty} suppresses them on every page and \thispagestyle{empty} on the first page. \hypersetup{pdftitle=...} writes the PDF Info dictionary (title, author, subject and keywords, UTF-16BE for non-ASCII text), each numbered heading becomes a PDF bookmark nested by heading level, \title, \author and \date are captured from the preamble, \today expands to the current date, and \maketitle expands into a centered title block at the article class sizes (using today's date when \date is absent and none for \date{}). \section, \subsection, \subsubsection, \paragraph and \subparagraph advance five-level article counters, prefix their titles with the number, and paint bold at \Large/\large/\normalsize (the two deepest levels stay at the base size); starred headings stay unnumbered, and an optional [short] title replaces the long title in the table of contents. The abstract environment expands into a centered bold heading and a 9pt body, and \maketitle joins multiple \and authors and turns \thanks notes into title footnotes. Section labels resolve \ref/\eqref to the heading number (standalone \label lines attach to the previous heading, unknown references print ??), and \pageref{label} reports that heading's formatted page number after a probe layout, \appendix restarts sectioning with letter numbers, \tableofcontents lists the numbered headings through \subsubsection with their page numbers right-aligned after dot leaders (the default article tocdepth of 3, changed by \setcounter{tocdepth}), \setcounter{secnumdepth} limits which levels are numbered, \setcounter{section}/{figure}/{table}/{equation}/{theorem} offsets the next counter value, \listoffigures/\listoftables reproduce the numbered captions with each float's page number right-aligned after dot leaders, verbatim keeps monospaced source lines, \verb|...| renders inline literal text monospaced, and text commands such as \LaTeX, \TeX, \ldots, \S, \ss, \ae, \oe, \o, \l, \dh, \th, \textdegree, \textmu, \textonehalf and \texteuro expand to their characters (a control word swallows the spaces that follow it), \href keeps its link text and paints a PDF /Link URI annotation over the label, and \url becomes typewriter text, and the abstract environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled cmmi10, cmsy10, cmex10, msbm10 and eufm10 TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, \mathcal capitals, \mathbb capitals and \mathfrak Fraktur letters each paint with their own face. Fractions can be written as \frac or with TeX's infix forms (\over, \atop, \choose, \brace, \brack, \overwithdelims, \atopwithdelims), and \genfrac takes explicit delimiters and rule thickness; only \over-style fractions draw a bar and fractions never draw parentheses. displaymath and math environments are accepted alongside $$, \[ and \(...\), and cases, matrix/pmatrix/bmatrix/Bmatrix/vmatrix/Vmatrix and array environments build a grid with the matching delimiters (an array column spec chooses left, centred or right alignment). \left/\right choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, \middle delimiters are sized with their group, and \big/\Big/\bigg/\Bigg paint at their selected CMEX size. align/align* displays share column widths, right-align even columns at their relations, and number each row (with \tag/\notag per row); gather/gather* centre each row instead, alignat numbers rows the same way while ignoring its column-count argument, a split body inside equation is numbered once, and multline sets its first row flush left, its last row flush right and the rest centred around a single number. Inter-atom spacing uses TeX's 3/4/5mu classes (1mu is 1/18em), \mid is a relation and \colon punctuation, \limits stacks an operator's scripts above and below using TeX's script size and clearance rules while \nolimits keeps them beside it, \substack{...} stacks its rows with TeX's inter-row gaps, and an integral stays sideways unless \limits is given, and \mskip/\mkern/\mspace/\hskip/\kern/\hspace scan TeX dimensions, taking the natural width of any plus/minus parts; \operatorname{...} sets an upright operator name, its starred form stacks following limits and \DeclareMathOperator{\name}{text} defines new ones. \footnote{...} leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A thebibliography environment turns its \bibitem entries into numbered [n] paragraphs, and \cite{...} resolves to [n]/[n, m] (unknown keys print [?]; optional citation notes are dropped, \citep/\citet behave like \cite, \nocite is ignored, and \bibliography/\bibliographystyle are consumed without BibTeX). A figure environment becomes a float at its [t]/[b]/[h] placement, its \caption numbers as Figure n: and feeds \ref, and \includegraphics embeds the referenced project image when it decodes (PNG/JPEG/BMP become a PDF XObject; missing or undecodable files keep the rule placeholder), a standalone \includegraphics paragraph becomes an in-text graphic float, and a standalone \rule{width}{height} becomes an in-text rule box; width=/height= take dimensions or fractions of \textwidth/\textheight, scale= a percentage, keepaspectratio fits both dimensions, and \graphicspath directories are searched (with .png/.jpg/.bmp fallbacks) when a path has no suffix. table environments likewise become floats carrying their captured tabular body, with Table n: captions that resolve from \ref. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and \caption* leaves either unnumbered; an optional [short] caption is used by \listoffigures/\listoftables while the long caption stays on the float; the glue on each side of a tabular column follows \tabcolsep (6pt by default), \arraystretch scales the tabular row heights, a begin-position option is accepted and ignored, and \\[dim] adds an extra gap after that row, and | rules in the column template paint vertical rules, and *{n}{cols} repeats a column group (a tabularx target width expands its X columns to share the leftover measure, and a \multirow{n}{width}{text} cell keeps its text on the first row of its span), and \renewcommand can rename the Figure/Table caption prefixes, the Abstract heading, and the References/Contents/List of Figures/List of Tables headings that open the bibliography, table of contents and float lists. Theorem-like environments (theorem, lemma, corollary, proposition, definition, example, remark, proof) produce a bold numbered heading with an optional [title], italic statements for the theorem group, and unnumbered proofs whose optional argument replaces the heading, with \label/\ref resolving to the theorem number. \newtheorem{env}[shared]{Display}, \newtheorem{env}{Display}[section] and \newtheorem*{env}{Display} add custom theorem environments: a shared counter numbers the env with its parent, [section] scopes numbers to the enclosing section, and the starred form stays unnumbered. In project previews and PDF exports, \input{...} and \include{...} expand from files in the same project (a missing .tex suffix is added), so chapter files render in place; a project's own .sty/.cls files are inlined for \usepackage{name}/\documentclass{name} with local \RequirePackage dependencies inlined recursively, local base classes named by \LoadClass/\LoadClassWithOptions inlined the same way, class and package bodies inlining their local \input{...} files (missing files are dropped), and package/class boilerplate dropped, \AtBeginDocument/\AtEndDocument bodies executed, and \makeatletter/\makeatother stripped; local class and package files run their \DeclareOption code for the options named on \documentclass[...] / \usepackage[...] (with \ExecuteOptions defaults), and preamble \PassOptionsToPackage/\PassOptionsToClass lines are merged into the next request, and unknown paths stay as literal text. Preview JSON also reports a warnings array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported rather than silently typeset. Route-D project previews are memoised by a hash of the expanded source (32 entries) and invalidated on edit; PDF exports cache the last eight results and the cache key also covers decoded image bytes, so replacing an image re-renders both. A malformed source answers 422 with a JSON error body and never populates either cache. itemize/enumerate/description environments nest arbitrarily: bullet labels cycle •/–/*, sub-enumerations use (a), roman and upper-letter labels, description items print their [term] in bold before the definition, an optional \item[label] replaces the generated marker, each depth adds 12pt of indentation, and list items take article's per-level \topsep, \itemsep and \partopsep (top level 8+2/4pt at 10pt, 9+3/4.5pt at 11pt and 10+3/5pt at 12pt; second level 4+2/2pt, 4.5+3/2pt and 5+3/2pt) unless \setlength{\topsep}, \setlength{\itemsep} or \setlength{\partopsep} override them, a wrapped item hangs its continuation lines at the text indent while its first line stays at the bullet indent, and an \setcounter{enumi} (or enumii/enumiii/enumiv) line before the first \item resumes enumerate numbering. A quotation environment splits its blank-line-separated paragraphs into blocks indented 20pt on both sides, and quote uses the same 20pt margins, and 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).

Inline $...$ and \(...\) math is laid out inside 10pt paragraphs (larger sizes keep the delimiters literal). \newcommand/\renewcommand/\DeclareRobustCommand definitions are captured from the preamble (and \providecommand only fills a name that is still undefined) and expanded textually, including numbered arguments and one [default] optional first argument; TeX's \def parameter texts and \let aliases are executed the same way, \edef/\xdef expand their bodies once at definition time and \csname...\endcsname builds the named control sequence, \expandafter runs the macro after its prefix once (chained zero-argument prefixes expand in order), and \newenvironment definitions wrap their bodies with the declared begin/end material. \newif flags select between \if...\else...\fi branches, with assignments honoured in the preamble or the body, so class conditionals like \ifdraft work, and \ifdefined\name tests whether a macro is declared. \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 <n> chooses the n-th \or branch and falls back to \else when the value is out of range.. the scratch registers \dimen0-\dimen255 and \skip0-\skip9 hold dimensions and glue with the same assignment and \advance forms, and \count0-\count9 take assignments, \advance, \multiply and \divide and print through \the/\number, while \newcount\name declares an integer register whose value \name= \dimexpr ... \relaxevaluates+, -, (by an integer) and/over dimensions and\newdimenregisters and prints through\the, while \glueexpr ... \relaxevaluates glue withplus/minuscomponents over dimensions and\newskipregisters, with parenthesised sub-expressions allowed and register operands keeping all three components;\noexpand\tokenkeeps the token unexpanded for the current pass (a later pass still expands it), and a later\defwith the same name replaces the earlier definition The LaTeX internals@namedef, @nameuse, @ifundefined, @firstofone, @firstoftwo, @secondoftwoand@emptyexpand, and@ifstar{yes}{no}/@ifnextchar{yes}{no}choose from the following token, and@counts as a letter in control words so\makeatletter-guarded names parse \numexprevaluates+, -, , /and parentheses over integers and integer registers, either standalone or after\the \newskip\namedeclares a glue register that\the\nameprints aswpt plus spt minus hpt. \newdimen\namedeclares a dimension register whose value\name=, \advance\name by , \multiply\name by and\divide\name by update and which\the\nameprints in TeX'spt form......., \advance\name by ..., \multiply\name by ... and \divide\name by ... update and which \the\name/\number\name print.

Route-D integration can also be checked against a real TeX page: cargo test -p texrra-tex-core --test route_d includes route_d_page_matches_pdftex_raster_geometry, which renders the route-D PDF and a pdfTeX Letter page at the same scaled-point geometry, rasterizes both with pdftoppm, and compares ink line count plus left, right, and bottom edges. It is skipped when pdflatex/pdftoppm are unavailable. route_d_multiline_bands_track_pdftex extends that check to a wrapped paragraph: the pixel rows that carry ink form one band per TeX line, and every band top, bottom, left edge and (except for the last line, whose width follows the break point) right edge must land within a couple of pixels of the pdfTeX page.

Route-D float placement mirrors TeX fractions:

  • Document::top_fraction_percent defaults to 70 (\topfraction); a taller top float keeps body text off its page.
  • Document::bottom_fraction_percent defaults to 30 (\bottomfraction); a bottom float that cannot fit is carried to the next page's bottom while the current page keeps filling, matching TeX's page builder.
  • Document::top_number, bottom_number and total_number default to TeX's 2, 1 and 12; they cap top floats, bottom floats and all floats on one page.
  • Document::float_sep defaults to 12pt (\floatsep); stacked top floats or stacked bottom floats reserve that gap between each other, in full layout and after Engine::edit.
  • Document::text_float_sep defaults to 20pt (\textfloatsep); a page that carries both floats and body text reserves one such gap between them. Page::display_list_with_layout(page_goal, text_float_sep) mirrors that in rendered output, while display_list_with_goal keeps the historic no-gap behaviour for callers without document settings.
  • A [t] float that appears while a page is already filling joins the top of that same page (TeX's \@toplist): its height plus \textfloatsep is charged to that page, so the body stops earlier; only a page break before the float moves it forward.
  • Floats that start a page sit at the top margin: float material does not consume \topskip; only body text does.
  • FloatPlacement::Here keeps an [h] float in the body flow: Document::in_text_sep (TeX \intextsep, default 12pt) separates it from the surrounding text, the float moves to the next page when it does not fit, and it counts against \totalnumber. Page::display_list_with_layout paints the float at the same flow position the page builder reserved.
  • Engine::edit applies the float fractions, number limits and separations, so incremental layout matches full layout.

These glyphs are rasterized at 600 dpi and shared by PDF and SVG. Ordinary math atom glyphs are rasterized from the selected font face at the same resolution, so PDF and SVG paint the same glyph image. A loaded MATH face supplies operators, relations, delimiters, Unicode Greek letters, and other single-symbol atoms. Default math-italic Latin letters also use that face when the glyph is available; bold, roman, and text styles use the corresponding Liberation Serif face. Lowercase Greek letters use the italic math family, while uppercase Greek letters use the current math family, following TeX's default mathcode behavior. Unavailable or non-outline glyphs use the text fallback. Without a MATH font, the compiler keeps the size-scaling fallback. Basic single-glyph subscript and superscript pairs use OpenType MathKernInfo when the face used to draw each glyph provides it; missing tables and compound expressions keep the default script placement. PDF and SVG share the resulting positions. \\hat, \\widehat, \\tilde, \\widetilde, \\overbrace, and \\underbrace use horizontal MATH variants and assemblies when available, with the same accent bitmap in both outputs. Bitmap accents are painted before the base glyph so their opaque background cannot clip the nucleus. matrix, pmatrix, bmatrix, Bmatrix, vmatrix, Vmatrix, cases, aligned, gathered, multline, and array environments build a two-dimensional math grid. Matrix delimiters are drawn around the grid, and array reads simple l, c, and r column specs. The unstarred equation, align, alignat, flalign, eqnarray, gather, and multline environments support equation numbers, \label, \tag, \nonumber, \tag*, \notag, and \ref. Alignment environments number rows independently; multline uses the full text width and has one number aligned with its final row. PDF and HTML preview use the same math row layout. This is a supported subset, not full amsmath behavior or OpenType math shaping for ordinary symbols and operators. Other unsupported TeX commands are reported as compile errors.

The default font paths cover common Linux installations. Set TEXRRA_FONT_DIR to a directory containing LiberationSerif-Regular.ttf, LiberationSerif-Bold.ttf, LiberationSerif-Italic.ttf, and LiberationSerif-BoldItalic.ttf if the fonts are elsewhere. For CJK output, set TEXRRA_CJK_FONT to a TrueType font file with the required glyphs when the system fallback cannot be found. For \texttt output, set TEXRRA_MONO_FONT_DIR when Liberation Mono is not in a common Linux font directory; for \textsf output, set TEXRRA_SANS_FONT_DIR when Liberation Sans is not in a common Linux font directory.

Experimental HTML endpoint

The /texrra endpoint remains available for inspecting the Rust parser's document model; it uses browser flow layout rather than the positioned page frames. The editor preview uses the live SVG pages described above, and the PDF export uses the same frames.

Box material example

examples/boxes.tex exercises the box material in one document: \fbox, inline \mbox, \parbox, the center environment, \hrule, vertical skips, and the NFSS style declarations.

Compatibility example

examples/compat.tex collects the accumulated compatibility layer in one document: spacing macros, symbols and letters, NFSS declarations, small caps, advisory breaks, starred \vspace/\hspace, center, \hrule, \fbox, \mbox, and \parbox.

New-template compatibility

The SIVP class (sn-jnl.cls) loads completely and sn-article.tex previews and exports a 14-page PDF; the Huawei E fragment (projects/e/问题一.tex) compiles to 16 A4 pages. This required generic TeX conditionals (\if, \ifx), \newcount/\newdimen, \char, 64-bit dimension scanning, tabular*/tabularx environments, and the math accent/operator/arrow vocabulary used by both documents. Both are covered by integration tests.

Capability matrix (current)

Area Implemented Remaining
Boxes \rule, inline framed \fbox, block \parbox/\minipage, \vbox/\vtop (vertical material capture), inline \mbox/\makebox, \raisebox, center, \hrule independent VBox natural width/baseline
Fonts serif/sans/mono faces, bold/italic/mono/sans declarations, group scoping, true scaled small caps —
Paragraphs Knuth-Plass breaking, TeX hyphenation, justification, \centering/\raggedright/\raggedleft, \parindent (17pt default), \hfill/\hfil —
Notes/floats footnotes with page-bottom insertion area, title/author \thanks, figure [htbp] placement (deferred top floats, bottom/page/here), table [t]/[b]/[p] placement table float-page queues, \textfraction
Contents \tableofcontents, \listoffigures, \listoftables generated from numbered headings and captions, dotted leaders, page numbers resolved after pagination per-chapter book/report contents
Pages A4/Letter/... page sizes, margins/geometry, automatic pagination, \newpage, \pagebreak, plain/fancy page styles, \thispagestyle, fancyhdr L/C/R headers and footers —
Links \href, \url, hyperref-green link text, \orcidlink{id} green iD badge, clickable PDF /Annots URI annotations for visible URLs, \href labels, and ORCID author badges —
Classes/packages built-in + local classes, option protocol, local package options, base font sizes 10/11/12pt, chapter headings and numbering, chapter page breaks, document-level custom \maketitle, native arxiv-style preprint title blocks (rules, \undertitle, author columns, long date) class-specific formatting beyond chapter breaks
Live preview incremental paragraph cache, page-hash diffing, SVG refresh —

The compatibility layer also covers spacing macros, text symbols/letters, style commands, break advisories, and document metadata; see the sections above.

PDF-only figures are rendered as placeholders sized from the source PDF page aspect ratio (until native PDF page embedding lands).

Numeric bibliographies render authors as Surname, I. rather than full given names.

Route D experimental core

crates/texrra-tex-core is the start of a TeX-compatible incremental layout core. It does not embed pdfTeX/XeTeX/Tectonic; it is a new Rust engine designed around page-boundary checkpoints and page-hash diffing. M0 implements vertical boxes/glue, a simple page builder, serializable checkpoints and a page-local edit demo. M1 adds the horizontal box/glue/penalty model, an item-stream Knuth-Plass-style paragraph builder, CMR10 metrics extracted from cmr10.tfm, and a matching pdfTeX line-break fixture. Paragraphs are split at line boundaries when they cross a page, and the pdfLaTeX oracle covers the 90-240pt measure matrix plus register, \hangindent/\parshape, \parfillskip, sentence-spacing with custom \sfcode, \spaceskip/\xspaceskip, \looseness and vertical-glue fixtures. Overflowing insertion material is split at item boundaries, with the tail held over to the next page. The production v1 engine remains the default until the new core reaches layout parity. See docs/TEX_CORE.md. The complete phased plan (P0 oracle harness, TeX-exact paragraphs, page builder and \\output, \\halign, math, Computer Modern fonts, class execution, service and incrementality targets) is in docs/ROUTE_D_PLAN.md.

The first M7 service integration is available as POST /api/route-d/preview, with PDF export at POST /api/route-d/pdf. It accepts blank-line-separated source with a small \section/\textbf/\emph/display-math/list subset, lays it out with the route-D page builder, and returns the v1-compatible preview shape plus per-page hashes and SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, the breaker follows TeX's \pretolerance/\tolerance/\emergencystretch passes with demerits (falling back to TeX's overfull fill when no feasible break exists), and the PDF /W array reports the same advances, so extracted text keeps word boundaries. Non-final lines bake their justification into the glue widths, so the PDF and the SVG preview are flush to the measure instead of showing natural spaces; with \raggedright (ParagraphStyle::ragged_right) lines keep their natural widths and fill greedily, because \rightskip carries an infinite fil. Interline spacing follows TeX (\baselineskip unless \lineskiplimit forces \lineskip), and Document::par_skip adds \parskip between paragraph units. page::PageBuilder selects page breaks by TeX's badness-plus-penalty cost, including glue setting with TeX orders (normal/\vfil/\vfill/\vfilll), \topskip and Document::max_depth (\maxdepth, with each paragraph's last-line descent exposed as \pagedepth and only the part beyond \maxdepth added to the page height), and breaks ties toward the later breakpoint (TeX's <= update), shipping the least overfull break only when nothing fits; Engine::layout_paged exposes it for documents of box/glue/penalty/mark/float/insertion units, expanding each paragraph into one node per line with a zero-width interline breakpoint, and route-D previews and PDFs run through it; insertion classes are placed through the same builder, with per-class limits, held-over material and Document::split_top_skip (\splittopskip, default 10pt) at the top of each continuation, with Document::split_max_depth (\splitmaxdepth, \maxdimen by default) clamping the first continued box's depth and moving the excess into its height, while Engine::layout keeps the scrolling builder as the non-paged fallback; paged layouts replay edits from the edited page, falling back to a full rebuild when insertions or an \output routine are present. Document::output_routine runs an interpreted \output program (\shipout\box255, \relax, \message, \ifdim, \ifnum and \ifodd over page registers; \pageno, \outputpenalty, \deadcycles, \vbadness (the break's badness) and \insertpenalties (insertion items held over) are readable, and each page fragment records the penalty that broke it and how much stretch each glue order carries, so \pagefilstretch, \pagefillstretch and \pagefilllstretch are readable) over those paged fragments, so a routine can drop pages it does not ship, or ship only the pages it wants based on the break penalty or page number. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. Document::h_offset and v_offset (\hoffset/\voffset) shift the exported page body through pdf::PageOrigin, leaving the sheet size unchanged, while Document::paper_width/paper_height (\paperwidth/\paperheight, default US Letter) set the MediaBox and the preview page box; the route-D endpoints read leading \hoffset/\voffset/\paperwidth/\paperheight dimension assignments from the submitted source. Page marks collected by \mark are exposed through Engine::top_mark, first_mark and bot_mark with TeX's carry-forward rules. Document::insertion_classes caps each insertion class to a page fraction and defers overflow to the next page (the paged builder applies the same limits and carries overflow onto dedicated pages), and InsertionClass::multiplier applies TeX's \count<number> reserve factor; Document::insertion_skip models \skip\footins once per page before the first insertion class, and InsertionClass::skip overrides it for one class. Engine::layout_paged feeds the same material through page::PageBuilder, which places top floats at the head of a page, defers a late float, reserves Document::text_float_sep above the body and applies the insertion class limits; bottom floats sit at the page bottom with Document::float_sep between them and a Document::bottom_fraction_percent cap, while in-text floats flow inline with their Document::in_text_sep gaps counted as body height. Vertical glue is set after the break: Document::ragged_bottom defaults to TeX's \raggedbottom, and setting it false applies \flushbottom, stretching StretchGlue so the page body reaches the goal; glue of the highest order with stretch absorbs the whole setting, so \vfil makes short pages free. POST /preview and the project APIs now default to route-D with a v1 fallback; ?engine=v1 (or TEXRRA_ENGINE=v1) forces the old pipeline.

Project previews and PDFs default to the new core (POST /api/projects/{id}/preview without a query); ?engine=v1 or TEXRRA_ENGINE=v1 forces the old v1 pipeline. An explicit ?engine= always wins for both previews and PDFs. The web client exposes this as the 引擎: v1 / 引擎: Route-D toggle in the preview toolbar; the choice is stored in localStorage and switches both the preview request and POST /api/projects/{id}/pdf, since the PDF handler honors the same engine=route-d query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages, and route-D PDF exports reuse an eight-entry cache keyed by the expanded source (X-Texrra-Cache: hit), and the flat /api/route-d/preview and /api/route-d/pdf endpoints memoise the last 32 previews and eight PDFs by source hash; text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through Engine::relayout_from, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. POST /api/route-d/edit/{unit} applies one paragraph edit to the last route-D document and returns the same page list plus changedPages and recomputedPages, exposing the checkpoint/page-hash diff from the core.