Files
texrra-engine/README.md
T

605 lines
42 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# texrra engine
Rust-native, Typst-inspired incremental LaTeX engine with a live preview
server. Typesetting is implemented in Rust; the engine does not invoke XeLaTeX,
LuaLaTeX, or pdfLaTeX. The web frontend is a separate repository,
[`texrra-web`](https://git.iloveuulove.me/gloamxun/texrra-web), served by this
engine as static files.
## Repository layout
Clone both repositories as siblings so the engine can discover the frontend:
```
texrra/
engine/ # this repository: Rust engine and HTTP server
web/ # texrra-web: static editor frontend
```
The server resolves the frontend from `TEXRRA_WEB_DIR` when set, otherwise from
`../web` and then `./web`. 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
```sh
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
```sh
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, paragraph indentation (`\parindent`),
`\hfill`, serif/sans/monospaced text, true small caps, itemize/enumerate lists,
page
breaks, basic display and inline math, figures, simple tables,
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.
- `\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, `\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. 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.
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, booktabs rule weights (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt) with `\cmidrule(lr){a-b}` trims and ranges, and row-level page splitting that repeats the column widths. Multi-page table headers are not implemented. 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); 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:
```tex
\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 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`](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. The v1 `/preview` and project APIs are unchanged and remain the default.
Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline. 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; 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.