Files
texrra-engine/docs/compiler-architecture.md

1169 lines
81 KiB
Markdown
Raw Permalink 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.
# Rust-native LaTeX compiler direction
Product clarification, 2026-11-02: [NATIVE_PRODUCT_GOAL.md](NATIVE_PRODUCT_GOAL.md)
governs this architecture. The product is a native LaTeX kernel with complete
original-project portability and realtime incremental rendering. The Web app
is a test frontend. Typst informs sessions, dependencies, invalidation and reuse;
native TeX/LaTeX execution supplies language and layout semantics. Input/state/
resource identities must be built with execution, ahead of safe checkpointing.
G1 diagnostic work is a paused, incomplete supporting slice of that roadmap.
Product direction updated 2026-10-31: the target product is Route-D, fully
replacing v1 with its own native TeX execution, lists, layout and export.
The current-implementation descriptions below also document the older v1
pipeline and its Texlang adapter; those are historical audit material, not
the architecture to carry into Route-D. Independent verified components may
be ported behind Route-D-owned interfaces. See [the active plan](ROUTE_D_PLAN.md).
The owned Route-D token/state/primitive bootstrap and explicit partial e-TeX
macro/integer and job-time/I/O slices are implemented in texrra-tex-core::execution
(1153 tests, 90 token probes, 101 quantity probes, 12 filesystem comparisons and a shipout oracle).
Its strict native CLI bypasses this older adapter pipeline. The unmodified
format initializes native mathematical constants/registers and reaches pretolerance;
HTTP migration, full native format boot and font fidelity remain pending.
See [NATIVE_EXECUTION_CORE.md](NATIVE_EXECUTION_CORE.md) for current evidence.
## Goal
Build a Rust compiler whose output follows XeTeX/LaTeX behavior closely, while
making edits cheap to recompile and keeping the PDF preview tied to the same
layout result. XeTeX behavior is the compatibility target; invoking XeLaTeX is
not part of the Rust compiler.
XeTeX's source is the primary reference for the engine rewrite: its algorithms
and observable behavior are being reimplemented in Rust, with no XeLaTeX
subprocess in the product. The legacy source tree does not need to dictate the
Rust module boundaries. LaTeX is a macro format and package ecosystem layered
on the TeX engine, and a rendered document also depends on fonts, font shaping,
file lookup, and PDF output; compatibility has to cover those layers as well.
## Stage model
Typst documents four main stages: parsing, evaluation, layout, and export. It
also reuses prior work through incremental parsing and memoized evaluation and
layout. This compiler adopts the same separation while retaining TeX's mutable
macro expansion and box/glue layout model. See the [Typst compiler
architecture](https://github.com/typst/typst/blob/main/docs/dev/architecture.md).
1. **World and source inputs** resolve the main `.tex` file, `\input`, local
`.sty` and `.bib` files, images, fonts, and compiler settings. The world
records dependencies so edits can invalidate their dependents.
2. **Tokenization and expansion** preserve TeX tokens, source spans, grouping,
category codes, and macro state. Expansion produces syntax that later passes
can inspect without throwing away source locations.
3. **Primitive and format execution** consumes native tokens with real state,
groups, modes and horizontal/vertical/math lists. Actual kernel/class/package
code determines higher-level document behavior. Reference and bibliography
workflows retain real auxiliary dependencies and multi-pass convergence.
4. **Layout** measures and packs native boxes, glue, penalties and page lists.
Paragraph breaking, math conversion, alignments, insertions and page/output
routines operate on owned execution results. No second frontend infers
class/package behavior from source strings or template names.
5. **Export** turns final page frames into PDF. Other views, if added, consume
the same frames rather than implementing a second approximation of layout.
## Incremental compilation
The editor sends the complete source after a debounce. Preprocessing,
math lowering, semantic parsing, and PDF generation still visit the full
document. For cacheable documents, expansion can resume from the latest safe
body checkpoint whose input prefix is unchanged; other edits reuse the
preamble checkpoint or take the full expansion path. Paragraph and math caches
reuse unchanged layout results. Body and preamble VM snapshots are retained
only after TeX groups and environments are safe and the Rust input stack has no
pending source or macro replacement frames. Page breaking can retain stable page-start
anchors before the earliest changed block when the page geometry and fonts are
unchanged; each break also records how far its look-ahead reached, so edits
that touch that range invalidate the dependent page. Line placement and PDF
output are still rebuilt for the full document. Rich paragraph parsing now keys
on normalized token/event sequences with offsets relative to each paragraph;
cached math runs are refreshed from the current math events so a preceding edit
does not retain stale source locations.
Typst's architecture shows why deeper incremental behavior needs stable source
identities and cached phase results, not just a timer. This compiler should
retain a compilation session with:
- parsed regions keyed by source file and stable source spans;
- expansion results keyed by the input region and the macro/environment state
that reaches it;
- layout results keyed by semantic nodes, font metrics, and inherited layout
settings;
- dependency edges for references, bibliography entries, images, styles, and
fonts, so an edit invalidates the affected results.
TeX state means a change can affect more than the edited paragraph. For example,
a macro definition can invalidate later uses, while a changed label can affect
references elsewhere. The dependency graph must model those cases before the
compiler can safely reuse cached results.
## Current implementation
The `/compile` endpoint now calls the Rust implementation directly. The
pipeline preserves `\usepackage` and `\RequirePackage` in the TeX input
stream; the Rust VM loads supported local style files when those commands are
executed. `\newcommand`, `\renewcommand`, `\providecommand`, `\def`, and
`\gdef` use an engine-owned macro table and Rust argument substitution.
The shared `texrra-core` crate owns category-code and math-code values,
engine token values, source origins and locations, control-sequence names, macro definitions, parameter
matching, replacement instantiation, scoped macro tables, and the native
command-meaning table independently of Texlang's interned IDs. `engine::token`,
`engine::command`, `engine::macros`, and `engine::expansion` are compatibility
re-exports at the application boundary.
Texlang's temporary variable adapter re-exports the shared category-code and
math-code types.
`texrra-core::math_code::MathCodeTable`, `texrra-core::math_code::UnicodeMathCodeTable`, and
`texrra-core::math_code::DelimiterCodeTable` store the ordinary and Unicode math classifications and
delimiter registrations read by the Rust math frontend. Engine group hooks now
save and restore their local and global assignments; the Texlang variable
adapter does not maintain a second save stack for them. The compiler's
standard-component adapter omits the duplicate Texlang catcode, math-code, and
end-line-character state; its primitive map binds `\\catcode`, `\\mathcode`,
and `\\endlinechar` directly to the engine tables.
`texrra-core::math_style` owns TeX's eight math styles and the rules for
cramped, numerator, denominator, superscript, and subscript styles. The parser
and current 2D math layout consume this shared semantic model.
`texrra-core::math_list` owns atom-list boundaries, nested-list context,
TeX's rule for normalizing binary operators at list boundaries, and its
eight-class inter-atom spacing table. It also selects `\\mathchoice` branches
and resolves leading/trailing atom classes across nested expressions. It
selects thin, medium, thick, or zero mu glue from the active math style and
current math-skip settings. Its inline-math planner carries style and spacing
state through a sequence, emits explicit glue and penalties, and selects
relation/binary break opportunities while suppressing conflicts with following
relations or explicit penalties. The application measures formula boxes,
converts planned mu glue to backend units, and passes the resulting nodes to
Knuth–Plass.
`texrra-core::math_expr::MathExpr` now owns the typed math expression tree,
including source locations, atom classification, style metadata, scripts,
fractions, delimiters, and alignments. It also classifies character-like,
single-glyph, and operator nuclei for script and limit layout.
`texrra-core::math_alphabet` selects Unicode math alphabets and transforms
ordinary atoms through nested math expressions; the font backend supplies only
glyph-availability queries. The parser and PDF/SVG layout consume this engine
IR, while glyph measurement, rasterization, painting, and the recursive box
adapter remain in the application.
`texrra-core::document` owns the semantic document IR: document metadata,
page margins, paragraphs, headings, lists, tables, images, bibliography,
math, vertical nodes, source anchors, and unresolved references. The
application's `document` module is a compatibility re-export.
`texrra-core::document_parser::parse_document` consumes the source-mapped
expanded token/event stream and builds that IR; the application parser module is
a compatibility re-export. Reference resolution then produces the final
engine-owned model, which both PDF and HTML consume.
`texrra-core::references::resolve` performs reference and citation
resolution over that IR after parsing has collected the document-wide label
and citation tables. `CompilerSession` invokes this core phase directly.
`texrra-core::expanded` owns source-mapped expanded items and typed frontend
events, and `texrra-core::math_parser` consumes that stream to build the
math expression tree. The application modules retain compatibility re-exports
while the layout and font backends remain application-owned.
`texrra-core::math_constants` reads OpenType MATH constants into a
design-unit model and selects fraction, script, operator-limit, radical, and
bar parameters, including XeTeX fallback values. The font backend converts
these em-based parameters to page units. `texrra-core::math_layout` owns
math-sequence style and spacing planning, measured child placement,
fraction-box placement, ordinary script vertical placement and horizontal
script-kern placement, display-limit geometry, radical-box geometry, delimiter
target sizing, ordinary delimited-box and fenced-row placement, accent
placement, and alignment-box geometry from measured child boxes and resolved
spacing. It also groups
display-math rows, sizes `multline`, and positions equation numbers around the
formula using measured tag metrics. The application supplies font measurements
and initial math-skip settings, converts core spacing to page units, and paints
the result. PDF glyph images are placed by their lower-left corner because
`genpdf::render::Area::add_image` uses printpdf's lower-left coordinate
convention; the math box stores upper-left positions, so the painter adds the
image height before drawing. SVG uses the upper-left position directly.
`texrra-core::math_glyph` selects math-atom glyph text and font preference,
returns the engine-owned atom slant, and interprets OpenType MATH per-glyph
italic corrections, top accent attachment points, and height-dependent
corner-kern selection. The application maps the slant into backend styles,
opens fonts, maps characters to glyph IDs, converts OpenType values into
engine-owned `MathGlyphMetrics` and kern tables, converts design units to page
units, and reads glyph bounds and outlines. Script-kern nucleus traversal and
Unicode math-alphabet character mapping are core decisions; font glyph
availability remains a backend query. For math sequences, the core resolves
per-item math styles, spacing settings, class boundaries, and child contexts,
then positions measured child boxes; the application measures the children and
converts the returned coordinates to PDF units.
Each `MathFontMetrics` snapshot shares a per-glyph cache keyed by font-byte
identity and character, avoiding repeated font-face parsing and kern-table
expansion during layout.
Delimiter glyph assembly and outline access remain in the application.
`texrra-core::macros` scans `\def` targets, parameter text, and grouped
replacement bodies through a generic token-stream interface, then parses
parameter prefixes, delimiters, and replacement references using engine token
values. `texrra-core::expansion` scans macro arguments and instantiates
replacements; `texrra-core::input::InputStack` keeps tokenized replacement
frames alongside source frames. The adapter suspends pending VM tokens below a
Rust macro frame and lazily converts the selected engine token at the VM
boundary.
`texrra-core::command::NativeCommandTable` owns the ported primitive
meanings and scoped aliases. Texlang tags only route those tokens into the
adapter.
`\let` copies
the current engine-owned macro meaning by consulting the Rust macro table. A VM
hook now consults that table before command-map lookup during normal expansion
and `expand_once`, so the engine table decides macro expansion. Command-map
entries remain as reflection markers for VM primitives that inspect meanings.
The shared expansion dispatcher has a stable built-in identity so incremental
VM checkpoints can serialize those markers while macro bodies remain in the
Rust engine table.
`\edef` and `\xdef` expand a bounded token list before storing the result in
that same table. Macro definitions, argument matching, and substitution use
engine-owned `EngineToken` values; the Texlang adapter converts tokens while
reading the unexpanded stream and converts the finished replacement before
queueing it. Texlang still supplies that cursor and expansion stack, plus the
remaining primitive expansion runtime. It emits an ordered, source-spanned
token/event stream that the parser turns
into a `ParsedDocument`. The pipeline resolves document references, lays out
the resolved model, and writes PDF through `genpdf`.
`EngineSemanticState::command_meaning` now resolves each control sequence as
an engine macro or a native primitive, with macros taking precedence; both VM
adapter hooks consult this shared resolution. The VM-facing `CompilerState` delegates TeX semantics to
`texrra-core::state::EngineSemanticState` through the application adapter.
The core owns catcodes, math codes, assignment scope, macro definitions,
environment nesting, native-command meanings, and their group save/restore.
The adapter retains source I/O and registers that still use Texlang types.
Texlang-specific VM execution now lives in `texlang_adapter.rs`; the
`tex_expansion` module is a compatibility facade used by the compiler stages.
Texlang still owns the main execution loop and fallback dispatch. Rust macro
and native primitive meanings resolve through the engine state, and
`texrra-core::command::NativeCommandTable` owns the meanings of the ported layout,
arithmetic, and prefix primitives. The pre-execution adapter consults this
table; Texlang tags only route the token into that adapter. Primitive aliases
created by `\\let` copy their Rust meaning and follow group scope, while macro
definitions remove any shadowed native meaning. This change does not claim
XeTeX compatibility.
`texrra-core::input` owns source and tokenized replacement frames plus the
TeX file-name scanner;
`engine::input` remains a compatibility re-export. The project-owned `\\input`
and `\\endinput` primitives use this stack. Filename parsing follows XeTeX's
`more_name` and `scan_file_name`; the adapter supplies the working directory,
reads resolved files, records dependencies, supplies expanded tokens, and
bridges diagnostics.
`texrra-core::layout_primitive` owns the primitive set, operand scan order,
and typed effect contract for `\\par`, `\\newline`, `\\pagebreak`,
`\\penalty`, `\\kern`, `\\hskip`, and `\\vskip`; `engine::layout_primitive`
is a compatibility re-export. The Texlang adapter still provides the token
cursor and concrete integer, dimension, and glue scanners, then writes
source-located events from the core effects.
`NativeCommandTable` selects their Rust semantics, along with `\\advance`,
`\\multiply`, `\\divide`, `\\global`, `\\long`, `\\outer`, and `\\relax`. The
Texlang adapter still supplies the token cursor and converts typed layout
effects into source-located output events; other execution commands still use
the VM command map.
`engine::variable` also owns parsing and applying arithmetic-variable assignments
through a VM hook. Texlang still provides their descriptors and dynamic index
resolution; non-arithmetic variable assignments use its compatibility path.
`CompilerSession::interpret_document` now makes the frontend stages
explicit: `frontend::preprocess` returns `PreprocessedSource`,
`frontend::expand_tex` returns `ExpandedTexSource`, and
`frontend::lower_math` returns `LoweredDocumentSource`; only then does
`parser::parse_document` return a `ParsedDocument` with unresolved reference
nodes. `texrra-core::math_mode::validate_math_delimiters` validates inline
and display scope transitions, matching closes, and math-only command context;
this core state validates math scopes only; outer vertical and horizontal mode
transitions are still handled by the application document builder.
Math spacing in expanded items and the document IR uses the engine-owned
`MathMuGlue` value; only assignable VM variables retain Texlang's `MuGlue`,
which is converted when the expanded token snapshot is recorded. The math
layout and document IR modules no longer depend directly on Texlang types.
`texrra-core::glue::TeXGlue` owns glue width, stretch/shrink amounts, and
infinity orders; `engine::glue` is a compatibility re-export. Horizontal
`\\hskip` values preserve these fields through the expanded stream, document
runs, and inline math lists. Vertical `\\vskip` carries the same
glue fields into the Rust page-break node list. Positioned frames currently
apply its natural width; page-level glue setting is not yet implemented.
`texrra-core::integer` owns TeX integer scanning, including signs, octal
and hexadecimal forms, character constants, internal integer values, and
source-token retention. The adapter only supplies the token cursor and typed
variable lookup. Dimension expressions, register indices, and `\\penalty` use
that shared scanner. `engine::dimension` now scans explicit TeX dimensions and evaluates the
e-TeX `\\dimexpr` operators (`+`, `-`, `*`, `/`) with nested parentheses and
`\\relax` termination using scaled-point arithmetic. `\\glueexpr` uses the same
operators over width, stretch, shrink, and their TeX infinity orders. The Rust
scanner now parses decimal, octal, hexadecimal, and character-constant integers
for register indices and expression factors, and reads native typed register
variables directly from engine state. Active `\\count`,
`\\dimen`, `\\skip`, `\\muskip`, and `\\toks` values now live in sparse
Rust-owned tables in `engine::registers`; the corresponding `*def` aliases
point into those tables. Each table records local assignments for group
restore and clears those saves for global assignments. The old Texlang register
components have been removed from `CompilerState`. Texlang's `i32`, `Scaled`,
`Glue`, and `MuGlue` parsers now call Rust scanner hooks first, so assignments,
arithmetic operands, and explicit dimension/glue primitives share the same
engine scanners. The Rust state owns `\\mag` with TeX's 1000 default and
group-scoped assignment behavior; `true` dimensions use that value. `em` and
`ex` still use Texlang's 12 pt fallback until selected-font metrics are wired
into the scanner. The PDF backend does not yet apply `\\mag` as a whole-page
output scale, so this does not claim full XeTeX `\\mag` behavior. Unsupported
internal-value forms return to Texlang's parser.
The dimension and glue scanners serve `\\kern`, `\\hskip`, `\\vskip`, and math
`\\above` thickness.
`texrra-core::references::resolve` consumes the parsed type and returns the
resolved `DocumentModel`, so PDF and HTML receive the same post-semantic model.
PDF and HTML both use this same path. Preprocessing and expansion adaptation
are in `src/rust_typeset/frontend.rs`; math lowering and math syntax parsing are
in `crates/texrra-core/src/math_lowering.rs` and
`crates/texrra-core/src/math_parser.rs`. Semantic parsing and the document IR
are in `crates/texrra-core/src/document_parser.rs` and
`crates/texrra-core/src/document.rs` (`src/rust_typeset/parser.rs` and
`src/rust_typeset/document.rs` are compatibility re-exports). The PDF backend entry point is in
`src/rust_typeset/pdf.rs`. Rust page-break planning and positioned-frame
construction now live in `src/rust_typeset/pdf/layout.rs`; the PDF module owns
document/font setup and paints those frames through `genpdf`. The
`layout_document` returns positioned page frames, an optional cache snapshot,
and any page-break plan; the PDF backend consumes the frames and commits a
snapshot only after PDF rendering succeeds. If it cannot yet produce
Rust-owned frames, it preserves any valid page-break plan for the existing
`genpdf` flow. Documents made from title metadata, paragraphs, headings, and
math now use Rust-owned page frames. `itemize` and `enumerate` lists are stored
as nested item trees and use recursive Rust layout, hanging indents, the four
article list label styles, and 11pt article-style list spacing. Every list line
carries a stable page-break anchor and participates in the page-layout cache
key. Title metadata is currently laid out without page-layout snapshot reuse so
edits cannot reuse stale title positions. Custom `\\item` labels are not yet
represented in the document IR. Text lines, inline-math lines, and measured
two-dimensional math boxes are passed to the PDF painter at explicit vertical
offsets. Block display math uses one shared Rust layout routine for the cached
`MathBox`, formula position, row shifts, and equation-tag baselines; the PDF
painter and SVG renderer then consume those same calculated positions. The
browser editor previews these positioned page frames. `/preview` lays the
document out into the same `PositionedPage` items the PDF painter consumes, then
serializes each page to inline SVG in `src/rust_typeset/pdf/preview.rs`. The
browser page stack keeps one element per page and replaces only pages whose
content hash changed, so unchanged pages keep their DOM, scroll position, and
paint. Font faces and font metrics stay cached in `CompilerSession`, and font
files are served once from `/fonts/*` with immutable cache headers. `/compile`
paints the same frames to PDF, and `/texrra` remains the parser-model HTML
debug view. Simple
tables use Rust page frames too: cell lines, column alignment,
row heights, and horizontal rules are positioned by the page tree. Tables may
span pages with stable break anchors between rows, while each row stays intact.
A row taller than the available page still falls back to `genpdf`. Explicit
page breaks become forced page penalties in the Rust page
builder. Static images and their captions are measured and positioned as one
Rust page item; image-content fingerprints invalidate cached page breaks when
the file changes. Float queues and deferred `figure` placement are not yet
implemented. Simple resolved bibliography blocks now use Rust-owned frames
with a `References` heading and numbered, wrapped entries; full BibTeX style
semantics and custom `\\bibitem` labels are not represented yet. Unsupported
blocks still use the existing page-flow fallback for the whole document.
The document IR stores table column alignment in an engine-owned enum, and the
parser no longer imports `genpdf`; conversion to backend alignment happens only
inside the PDF layout path.
Shared TeX glyph metrics live in
`src/rust_typeset/box_font.rs` and
are used by both paragraph and math layout.
The preprocessing stage now preserves the input text and records source
locations; it does not rewrite package or command definitions. The TeX VM output
boundary records an ordered `ExpandedItem` stream:
expanded tokens retain their TeX category, control-sequence name, and source
location, while execution events retain their typed payload and source
location. A small local extension to `texlang` exposes executed brace-group
boundaries, which the stream records as typed events; math parsing uses the
stream for script categories and the events for nested groups. The document
parser now consumes the ordered token/event stream directly. The VM's serialized
text view remains inside expansion for checkpoint slicing and source-map lookup.
Math-shift normalization and math lowering operate directly on typed tokens and
events. The resulting `ExpandedTokenStream` retains typed items, events, and
source segments but no text buffer. Semantic math parsing reconstructs leaf
content from token categories, while paragraph text is likewise rebuilt from
token categories with control-sequence spelling handled explicitly. Source
segments retain character-boundary offsets for source-column mapping instead of
rescanning serialized output.
Math parsing returns source-located diagnostics for repeated superscripts or
subscripts instead of silently replacing the first script, and reports a
missing script argument instead of rendering `^` or `_` as an ordinary atom.
Only successfully parsed math trees enter the math parse cache.
Dollar math delimiters are recognized from math-shift tokens with an explicit
text/inline/display mode state: `$$` opens display math in text mode, `$` closes
inline math one token at a time, and display math requires a paired closer.
Unclosed math shifts produce source-located errors instead of plain text.
Macro-argument braces consumed while the VM reads an argument are not separate
execution events. This is a structural migration step, not a claim of XeTeX compatibility:
the VM is still Texlang rather than a XeTeX rewrite, and its box/glue lists and
page tree cover only a limited document subset. The frontend still scans source
to decide whether incremental snapshots are safe, but that scan does not alter
TeX execution.
The compatibility macros `\\makeatletter` and `\\makeatother` now change the VM's
catcode for `@`; preprocessing preserves control-sequence spelling instead of
rewriting `@` to `X`.
The engine-owned catcode table now follows local and global assignment scope:
group exit restores local changes, while global changes survive all open
groups. The mouth and Texlang's `\\catcode` variable adapter now read and mutate
the same table, removing the duplicated catcode array and post-assignment sync
step. `texrra-core::assignment_scope::AssignmentScope` owns the scoped
`\\globaldefs` value and applies its global/local override after the Rust
prefix scanner consumes `\\global`; `\\globaldefs` itself follows the same
group save rules. `engine::prefix` scans and validates `\\global`, `\\long`,
and `\\outer` using command tags as registry metadata. `\\gdef` and `\\xdef`
also honor a negative `\\globaldefs` instead of forcing global scope. Brace
groups, the `\\begingroup` / `\\endgroup` primitives, and non-document
environments share the engine save stack. `\\bgroup` /
`\\egroup` expand through the same group primitives. The project-owned mouth
supplies live tokenization; the VM remains Texlang-based for the execution
loop, primitive dispatch, and replacement-token transport. The Rust primitive
map now routes `\\advance`, `\\multiply`, and `\\divide` through
`engine::arithmetic`, which owns command dispatch and arithmetic, overflow, and
division-error behavior. Texlang parser hooks route integer, dimension, ordinary
glue, and math-glue values through the Rust scanners for assignments and
arithmetic operands. Arithmetic-variable assignment now uses the Rust-owned
assignment path, while descriptors and dynamic indices still pass through the
Texlang adapter.
`\newcommand`, `\renewcommand`, `\providecommand`, `\def`, and `\gdef` remain
in the input stream, and the preprocessor copies their replacement bodies
without inspecting them. The Rust VM stores definitions in its scoped macro
table and expands positional arguments itself. Rust macro definitions now
retain `\\long` and `\\outer`: non-long argument scans reject `\\par`, while
outer macro calls are rejected in Rust macro-argument scans, shared
braced/optional argument scans, generic Rust token-list scans, and expanded
definitions. The generic token-list adapter checks captured, unexpanded tokens
so token-register arguments keep their existing read behavior. This does not
yet cover every TeX scanner context. Unstarred
`\\newcommand` is long and its starred form is non-long. LaTeX command definitions
support one optional first parameter and up to eight following required
parameters when a default is present, or up to nine required parameters without
one. TeX `\def` / `\gdef` support ordered numbered parameters, literal prefixes
and delimiters, and replacement references; `\let` preserves an engine-owned
macro's current meaning using the macro table as its source of truth. `\edef`
and `\xdef` store Rust-owned definitions and replacement token values. Macro
arguments and replacement bodies retain engine trace IDs, which the adapter
maps to Texlang trace keys for source diagnostics; conversion occurs only at
the unexpanded-input and expansion-stack boundaries. This does not claim full
LaTeX command-definition compatibility.
Paragraph breaks, page
breaks, `\\maketitle`, title/author/date bodies, section headings, `\\begin` /
`\\end` environment boundaries, labels, references, citations, bibliography
item keys, and geometry settings travel as typed frontend events with their
arguments already consumed by the TeX expander. The metadata bodies use paired
typed events around ordinary expanded tokens, so they no longer need marker
strings. `\\begin` and `\\end` update a serialized, engine-owned environment
stack; `\\end` rejects an unmatched or out-of-order close during execution.
Non-document environments also open and close a TeX assignment group so local
definitions and register changes restore at `\\end`; the `document` environment
stays at top-level scope.
`array`, `tabular`, `alignedat`, and `alignat` preambles are consumed as TeX
token arguments and carried as typed environment events.
`\\bibitem` now reads its optional label and citation key in the VM and emits a
typed bibliography-item event; the optional label is still ignored by layout.
`\\bibliography` also reads its file list in the VM, loads and records `.bib`
dependencies there, and feeds formatted entries back through the VM token
stream. Generated bibliography tokens retain the originating command's source
location. The BibTeX reader and formatter are still a limited implementation.
Raw alignment-tab tokens become typed table or math-cell events according to
the active environment; a misplaced `&` reports a TeX-style error instead of
being rewritten into a literal ampersand. Bold, italic, and monospaced text switches, list items,
table cells, rules, and escaped ampersands now travel as typed events with
source locations instead of private string markers. Image commands now carry
their parsed options and path as one typed event, preserving the command's
source location and removing the marker pair used to hand image data to the
document parser. `\\includegraphics` now reads its star, optional key-value
options, and braced path from the VM token stream; common width and height
register names are normalized there instead of by scanning raw source text.
Captions use paired events, so the document parser can collect
their runs while still interpreting text styles, references, and inline math.
Escaped braces, ampersands, and `\\newline` also travel as typed events; their
literal characters and line-break behavior no longer pass through private
marker text.
Row breaks and math alignment cell boundaries also travel as typed events.
The `\\frac`, `\\dfrac`, `\\tfrac`, `\\binom`, `\\dbinom`, and `\\tbinom`
commands emit paired typed events for fraction start, argument boundary, and
end; the math parser consumes these into nested `MathExpr::Fraction` nodes.
Plain TeX's infix `\\over`, `\\atop`, `\\choose`, and `\\above <dimen>` are also
typed math events: they split the current math group into numerator and
denominator, with `\\over` drawing the font's default rule, `\\atop` omitting
it, `\\choose` adding stretched parentheses, and `\\above` using its explicit
rule thickness. A zero-thickness `\\above` uses the no-rule stack clearance.
The delimiter forms `\\overwithdelims`, `\\atopwithdelims`, and
`\\abovewithdelims` scan two delimiters (and then the dimension for the last
form), retaining their glyph and sizing settings on the fraction event. The
math parser wraps the shared fraction node in the same scalable delimiter box
used by `\\left` and `\\right`.
They lower to the same fraction node used by the braced commands, so PDF and
HTML preview keep the same two-dimensional layout. A second infix fraction
separator in the same math group reports TeX's ambiguity error at the second
separator. The custom rule and no-rule spacing follow XeTeX's
[fraction construction](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L24875-L24904).
The four TeX math-style commands are typed state changes inside the math tree.
They affect following atoms, spacing, fractions, operators, and scripts in the
current group, and nested groups restore their inherited style. The PDF and SVG
math-box layout consumes the same style-aware tree.
Text-mode math groups such as `\text{...}` use an upright text face at the
active math size rather than inheriting the surrounding math italic face.
Nested bold, italic, and monospaced text-style events remain separate styled
runs in the math tree. PDF and SVG preview use the selected family and preserve
formatting such as `\textbf{...}` and `\texttt{...}` inside `\text{...}`.
In math mode, `\phantom`, `\hphantom`, and `\vphantom` become box nodes in the
same tree. PDF and SVG layout measure the child once, then retain its full,
horizontal-only, or vertical-only extent while emitting no paint items.
The primitive `\\mathchoice` retains its display, text, script, and scriptscript
branches as scoped math trees. The shared PDF/SVG layout selects the branch from
the active TeX math style, including inside scripts and nested choices. Math-box
and inline-paragraph cache keys recursively retain only selected alternatives,
using the style transitions for fractions, scripts, roots, accents, and alignment
cells. Editing an unselected branch therefore preserves both the selected box
and the paragraph line-break result.
The `\\sqrt` command and its optional degree emit typed root-boundary events;
the math parser consumes them into nested `MathExpr::Root` nodes. `\\left`,
`\\middle`, and `\\right` emit typed delimiter events; paired fences become a
2D node whose delimiters share one content-based target height. Math font
switches, `\\operatorname` and common
operator macros, `\\overline`, `\\underline`, `\\vec`, and directional arrow
accents above and below the nucleus now use typed math events. `\\xleftarrow`,
`\\xrightarrow`, and `\\xleftrightarrow` currently accept one label. They enter
through `\\Umathaccent` as relation-class nodes, so the shared math layout can
use family-2 OpenType MATH glyph variants and horizontal assemblies. Optional
lower labels for these commands are not implemented yet. The math parser
consumes their event ranges into styled atoms and accent nodes.
The primitive math alphabet `\\mathtt` changes ordinary math leaves to the
same monospaced family used by PDF text and `\\texttt`, while keeping fractions,
scripts, and other two-dimensional structures intact.
The math alphabets `\\mathit`, `\\mathbf`, `\\boldsymbol`, `\\mathsf`,
`\\mathcal`, `\\mathbb`, and `\\mathfrak` map Latin and Greek letters and
supported digits to Unicode mathematical alphanumeric glyphs when the active
math font contains them. Missing glyphs retain the source character and use a
matching upright, bold, or italic text face; script kern and italic-correction
lookups use the mapped glyph when it is available. The Unicode mapping follows
the [Mathematical Alphanumeric Symbols chart](https://www.unicode.org/charts/PDF/U1D400.pdf).
`\\sqrt`, `\\left`, `\\middle`, and `\\right` are handled by Rust VM primitives; the frontend no longer scans
their arguments from raw source text. Root arguments are captured as TeX tokens
and returned to the VM expansion stack, preserving nested macros and group
execution while the typed root events delimit the resulting math tree.
The `\\mathord`, `\\mathop`, `\\mathbin`, `\\mathrel`, `\\mathopen`,
`\\mathclose`, `\\mathpunct`, and `\\mathinner` commands preserve their
explicit noad class as a typed wrapper around the math nucleus. Class wrappers
participate in TeX's math spacing table and operator limit placement without
flattening the nucleus into text.
The `\\stackrel` compatibility macro builds an operator with stacked limits
and restores the relation class around the resulting noad. `\\substack` lowers
to `smallmatrix`, so row breaks become a centered two-dimensional stack whose
entries use script style.
Ordinary math tokens capture their current engine `\\mathcode` in the source-spanned
VM token stream. The math parser carries its class, family, and slot into the math
IR, so assignments affect later tokens and respect the engine's grouping. The
`\\fam` integer parameter is also captured with each token; for class-7 math
codes, a current family from 0 to 15 overrides the family's math-code bits, and
the default `-1` leaves those bits in effect. Family 1 renders ordinary
variables in the italic face; family 0 stays upright, and printable ASCII
slots can remap the rendered glyph. Explicit roman math groups lower family 1
to the upright face while nested explicit font groups keep their own selection.
The VM now exposes `\\font`, `\\textfont`, `\\scriptfont`, and
`\\scriptscriptfont`: `\\font\\mathface=fonts/math.ttf` loads a local font
file, and the three family registers can assign that font to family 0–255.
Ordinary math atoms then use the assigned outline at the active math style size;
font-register state is captured with each expanded token so local assignments
survive into the math tree, and the same rasterized glyph is used by PDF and
SVG. This first slice does not yet shape regular text through `\\font` or use
math-active (`"8000`) expansion. Unicode characters with an unset zero code use the
existing character fallback.
The VM's `\\mathchar` primitive and `\\mathchardef` commands now emit typed
math-character events containing the 15-bit math code and current `\\fam`.
These become ordinary math atoms with the specified class, family, and slot;
using a math character outside math mode produces a source-located diagnostic.
The `\\mathchardef` primitive installs a scoped math-character command, and
`\\Umathchardef` installs a native scoped Unicode math-character command. Both
definitions honor local and global assignment scope; Unicode class-7 commands
read the current `\\fam` when they are used.
The `\\Umathchar` primitive also accepts XeTeX's class, family, and Unicode
character arguments and sends the resulting atom through the same math layout
path. Class 7 uses the current `\\fam` when it is in the supported range and
otherwise keeps the explicitly supplied family, matching XeTeX's `set_math_char`
behavior. Assigned font registers select the corresponding face for ordinary
glyphs; without an assignment, atoms keep the configured math font and existing
upright/italic fallback. Mathematical alphanumeric codepoints in
U+1D400–U+1D7FF prefer the configured MATH font when no family font overrides
them, preserving encoded italic and bold glyph forms when the face contains
them.
The packed `\\Umathcharnum` and `\\Umathcharnumdef` forms decode the same
class/family/Unicode-slot bit fields used by `\\Umathcode`, then share the
regular Unicode math-character event and layout path.
The `\\Udelimiter` primitive accepts Unicode opening and closing delimiter
types (4 and 5), family, and scalar glyph slot, then lowers to the same scalable
delimiter layout used by the PDF and SVG paths. Its family now selects the
glyph's MATH variant or assembly at the active style size, with the configured
MATH font as fallback when the family has no registered face. The initial size
target follows the active math style. Classic `\\left`, `\\middle`, and `\\right`
read the 24-bit `\\delcode` fields for small and large glyph families and slots.
Their family register snapshots select the matching face at text, script, or
scriptscript size, and the shared layout tries the small-family glyph before the
large-family glyph. Common ASCII delimiters default to family 0; users can assign
other delimiter codes with normal local and global TeX scoping.
Display-style single-glyph operators now use the assigned family font's
vertical MATH variants and `DisplayOperatorMinHeight` when available; operators
without an assigned family continue to use the configured MATH font.
Delimiter centering and display-operator alignment now read `AxisHeight` from
the current family-2 math font at the active style size when it supplies OpenType
MATH constants, falling back to the configured math metrics font otherwise.
Glyph-based standard accents (`\\hat`, `\\tilde`, `\\widehat`, `\\widetilde`,
`\\overbrace`, and `\\underbrace`) capture the current `\\fam` and use that
family's font and MATH construction at the active style size. Rule accents
(`\\overline` and `\\underline`) remain geometric rules and use the nucleus
font's MATH spacing and rule constants when available.
The `\\Uradical` primitive accepts a family and scalar glyph slot followed by
the radicand. It enters the same typed root node and shared PDF/SVG radical
layout as `\\sqrt`. The requested family now selects the radical glyph's MATH
variant or assembly at the active math style size. When that family has no
registered face, lookup falls back to the configured MATH font. Radical spacing
and degree placement use the selected face's MATH constants when present, then
fall back to the configured MATH metrics face.
The `\\Umathaccent` primitive accepts XeTeX's optional `fixed` and `bottom`
keywords, math class, family, and scalar glyph slot, then captures the following
nucleus as a typed accent node. Stretchable accents use horizontal MATH variants
or assemblies from the requested family, and fixed accents paint its requested
glyph. Accent placement reads `AccentBaseHeight` and the base glyph's top-accent
attachment from the nucleus face when available; the requested accent face
supplies the accent glyph and its top-accent attachment. Missing nucleus MATH
data falls back to the configured metrics face. When the family has no
registered face, glyph lookup falls back to the configured MATH font. Bottom
accents use the under-accent placement path.
`\\Umathcode` assignments now store the Unicode input character's math class,
family, and glyph slot in the engine-owned scoped variable table. Later occurrences consume that
mapping from the expanded token stream, and the math parse cache includes it in
its key. Class 7 uses the current `\\fam` when it is in the supported range;
otherwise it keeps the assigned family, matching the existing legacy-mathcode
fallback. Assigned font registers select ordinary atom glyphs; the configured
MATH font supplies structural glyph variants where no family font is assigned.
Math nodes capture family-2 font selections at the point where fractions and
delimiters are introduced. When the selected face has MATH data, its style
scales, fraction constants, and axis height drive those layouts; missing MATH
data falls back to the configured metrics face.
Explicit math spaces (`\\,`, `\\:`, `\\;`, `\\!`, `\\quad`, and `\\qquad`)
now travel as source-located glue events. `\\left` and `\\right` lower to typed
delimiter events whether written directly or reached through the prelude
macros. Script argument scanning now recognizes source-spanned math containers,
so an unbraced `\\frac`, `\\sqrt`, delimiter group, or styled atom remains one
script node. The document parser now consumes the same token/event stream.
Cross-reference and citation events remain typed unresolved inline runs through
document parsing; `references::resolve` handles them as a separate semantic
pass after all labels and citations have been collected.
The frontend now pairs math delimiters and display-math environment boundaries,
parses typed fraction, root, and delimiter events into `MathExpr`, and emits a
single typed inline or display math event. The document
parser inserts that expression directly; math bodies no longer pass through its
string accumulator, and there is no document-parser fallback that rewrites a
fraction to slash-separated text. Math nodes retain source locations down to atoms, fractions, roots,
delimiters, and scripts. The math parse cache keys source-origin segment
shape rather than absolute line and column numbers, then rebases cached node
locations to the current source map. The math-box cache removes source locations
from its keys, so moving a formula does not discard reusable geometry.
Within an expression, the parser reads ordinary characters and text/operator
leaves from expanded token values; its cache identity uses token and event data
rather than the serialized math string. Math environment names and preambles
arrive as typed VM events. Math lowering uses serialized byte ranges to copy
surrounding document content; source mapping still uses the serialized view to
translate VM offsets into original source columns.
Math lowering copies expanded items in item order instead of splitting them by
byte position. Space tokens and events are zero-width items, so they share their
byte position with the following token; position-based copying placed an event
between the space that preceded it and the token that followed, which moved the
space before `\ref`, `\cite`, `\textbf`, and inline math to the end of the
reference text. `ExpandedTokenStream::copy_items` now copies an item slice
together with its source segments and rebases both, and both lowering passes
track each event's item index so tokens that precede an event stay before it.
The private tag-string protocol and cross-reference string sentinels have been
removed. Reference and citation values remain typed inside their runs until the
dedicated reference-resolution pass runs after document parsing.
Preprocessing and macro expansion carry file, line, and column
locations through generated text; parsed blocks retain source anchors, which
the HTML preview exposes as `data-tex-source-*` attributes. Most non-math
commands are not yet represented as a source-spanned syntax tree.
Display math is a separate layout module at
`src/rust_typeset/math_layout.rs`. The document parser consumes token/event
items directly, but the document model is not yet a source-spanned syntax tree.
Each request checks the source identity, loaded file contents, and available
`.sty` filenames. The session retains three complete compilation snapshots in
least-recently-used order. An exact source/configuration hit with unchanged
dependencies skips preprocessing, TeX expansion, math lowering, and document
parsing; recent undo/redo versions can therefore reuse the complete semantic
model. A changed dependency invalidates that snapshot. Reads made by
The Rust `\input` adapter records each resolved file as a source dependency;
diagnostics in imported files retain their own source locations. Style,
bibliography, and input changes invalidate the cached result. Commands with untracked I/O or
dynamic token behavior bypass this cache. For cacheable documents with a
literal `\begin{document}` on a line whose preceding characters are
whitespace, the session retains a serialized Texlang VM checkpoint immediately
before that command. It preserves the preamble's macro definitions, catcodes,
registers, groups, and other VM state. The body is divided at blank-line
paragraph boundaries; after a chunk runs, a checkpoint is kept only when TeX
groups are closed and the active environment is empty or `document`. Up to
eight checkpoints are sampled across the body within a bounded memory budget.
On a later edit, the compiler finds the latest checkpoint whose preceding body
text is byte-for-byte unchanged, restores the VM and expanded output prefix,
then expands the remaining body. Runtime and preprocessing dependencies are
checked before reuse. This skips expansion of an unchanged body prefix, while
preprocessing, math lowering, semantic parsing, and PDF generation still visit
the full document. If a chunk ends while TeX is waiting for more input, the
compiler falls back to the unsplit expansion path. Documents that cannot use
the preamble checkpoint also use that full path. During each body pass,
math parse-cache identity uses expression text, expanded token values and
categories, math-code
values, source-origin segment shape, frontend events, and math environment.
Token and event positions are relative to the expression; absolute source line
and column numbers do not prevent reuse.
On a cache hit, the compiler rebases cached math-node locations to the current
source segments and events; ambiguous mappings decline reuse. Unchanged
equations can therefore retain parsed trees when edits above them move their
source locations. Paragraph line boxes and math subtrees can reuse layout
results too. Plain top-level paragraphs reuse their normalized run sequence by
exact expanded text. Top-level paragraphs with inline math, references, or
citations also reuse their run sequence when the full expanded token/event
sequence and source locations match; references stay unresolved in the cache
and are resolved against the current document after parsing. Styled paragraphs
and content inside lists, tables, figures, or bibliography continue through the
full parser. Every compile emits a fresh PDF.
The live HTML and PDF endpoints share the same `CompilerSession`, so an
unchanged expanded document reuses its parsed model across either endpoint.
The editor session now reuses cached Knuth–Plass line breaks for unchanged
plain-text paragraphs. The line breaker receives explicit glyph, glue, kern,
and penalty nodes, using the same Latin, CJK, and monospaced font faces as the
PDF renderer, including bold and italic variants. It includes pair kerning in
line-width calculations, offers breakpoints between CJK characters, and blocks
breaks after opening or before common closing punctuation and small kana. Cache
keys include the complete styled paragraph, line width, participating
font-content fingerprints, and size; a changed layout input produces a fresh
result. The cache stores packed line boxes with their glyphs and adjusted glue
widths. A Rust `TextLine` element paints them at explicit baselines, so
`genpdf` does not choose their line breaks or word-space positions again. It
provides the PDF drawing primitives; documents with blocks that do not yet fit
the Rust page model still use its page-flow fallback.
For documents made from paragraphs (including inline math), headings, lists,
simple tables, and display-math blocks, a Rust page builder creates a vertical
list of line boxes, table rows, spacing glue, and break penalties. It chooses
page-break anchors with TeX-style badness and penalty costs, then the PDF path
paints the positioned page frames directly.
This is a first port of the `vert_break` behavior in XeTeX's `xetex.web`,
limited to fixed-height boxes and the current paragraph/heading skips. Text and
math line boxes carry separate height and depth; page planning applies the
11pt article `\topskip` and 5.5pt `\maxdepth`, and measured multi-line
paragraphs add fixed glue to keep successive baselines at the configured
size-specific distance. The page builder keeps the current depth separate from
the accumulated page height, caps it at `\maxdepth`, and uses the same line
metrics and leading as positioned PDF frames. It also discards leading glue and
penalties before the first box on a page. If baseline glue would become
negative, line layout uses the article class's 1pt `\lineskip` fallback.
Vertical glue records normal and infinite stretch orders plus shrink. Page-break
costs use these amounts, including the 11pt article list `\topsep` and
`\itemsep` values. PDF frame placement still uses natural glue widths, so page
level stretch and shrink are not yet applied to the rendered page.
Display math uses the 11pt article normal skips (11pt plus 3pt minus 6pt) and
short skips (above: 0pt plus 3pt; below: 6.5pt plus 3.5pt minus 3pt). The
engine measures the preceding paragraph's final line and chooses the short skips when
the centered formula starts to the right of that line's natural end plus two
em. Paragraph glue that changes visible content forces the normal skips, as in
TeX's `\predisplaysize` calculation. The current model does not yet include
equation numbers, paragraph shapes, or display indentation. The class values
follow the [standard document class definitions](https://www.latex-project.org/help/documentation/classes.pdf),
and the short-skip decision follows XeTeX's
[display-math algorithm](https://tug.ctan.org/info/knuth-pdf/xetex/xetex.pdf).
Page-start anchors and each decision's look-ahead range are retained across
edits; planning resumes from the earliest page whose decision inspected changed
content. Font or page-geometry changes and non-tail block insertions/deletions
trigger a full page-break pass.
Simple resolved bibliography blocks also use Rust-owned frames: the heading
and numbered entries have stable line anchors, and bibliography keys and
resolved runs are part of the page-layout cache key. Full bibliography style
semantics and custom `\\bibitem` labels are not represented yet. A table row
taller than the available page still uses the `genpdf` fallback.
Explicit page breaks use forced penalties when the Rust page model can handle
the rest of the document. The Rust page builder does not yet model float
queues, insertion nodes, output routines, or page-level glue distribution.
Baseline glue is currently fixed and the supported size table is only a small
article-style subset.
Inline-math paragraphs also reuse their measured, positioned line boxes across
compiles. This bounded session cache keys source-independent math trees, styled
text runs, line width, font-content fingerprints, and math metrics, so moving
an unchanged formula in the source does not discard its PDF paragraph layout.
Inline formulas in the live preview are serialized from the measured math boxes,
so they share paragraph line breaks and glyph positions with the PDF. The
separate `/texrra` debug view still serializes inline formulas without the
positioned page frames.
Display and inline math now use positioned `MathBox` nodes. PDF paints those
nodes through its font cache; the HTML endpoint serializes the same layout
algorithm and font metrics as SVG, embedding the matching Liberation Serif
faces and, when used, Liberation Mono. SVG text spans carry the advance width
computed by the shared font cache and preserve whitespace, so browser text
spacing does not silently change the measured math box. The compiler session
retains one bounded FIFO cache of math boxes shared
by both renderers, keyed by each expression node, math style, font and
MATH-metrics fingerprints, and rendering style. PDF and HTML therefore paint
or serialize the same positioned box tree. Parent boxes share cached child
boxes, so editing one part of a fraction or script can reuse unchanged
subtrees. Changes to any layout input produce a fresh box, while unchanged
boxes are reused across both endpoints.
`CompilerSession` also retains the active `MathFontMetrics` across PDF and HTML
render calls. Its content fingerprint covers the selected MATH metrics face,
the four Liberation Serif faces, and each document-selected math font, so a
font-file change reloads the snapshot. Cloned metrics share the per-glyph MATH
data cache.
Inline expressions remain `MathExpr` values inside paragraph runs, while
display equations enter the same line-breaking stage without prose. Their
top-level sequence atoms become measured horizontal boxes. Word spaces are
stretchable glue; math relations, binary operators, and punctuation add
penalized breakpoints. A leading math-class spacer is dropped when a break
begins a new line. Fractions, scripts, radicals, and delimiters stay as
indivisible two-dimensional boxes. This is a first useful slice, not full TeX
math breaking: nested sequences remain indivisible, operator-specific
penalties and math font shaping are incomplete. Math alignment tabs and typed
row-break events form a two-dimensional cell grid. Matrix environments add their paired
delimiters; `cases` adds a left brace; `aligned` aligns right/left cell pairs
and inserts the inter-pair gap, while `alignedat` leaves pair spacing to the
source. `gathered` centers each row, and `array` reads simple `l`, `c`, and `r`
columns, single or repeated vertical rules (`|`), and repeated column patterns
such as `*{3}{c|}`. The source preamble is captured before TeX grouping removes
its braces. Array rules render as vector rectangles in SVG and 600 dpi RGB
images in PDF, using the default 5 pt column padding, 0.4 pt rule width, and
2 pt separation between repeated rules. This does not implement complete
`array` or `amsmath` alignment semantics. The editor displays this layout as
live SVG pages, and the PDF export paints the same frames. The separate
experimental HTML endpoint still serializes complete math expressions through
browser flow layout and does not share the positioned page frames. The box tree remains local
to math; deferred float placement is not yet represented by the positioned page
model. Paragraphs with or without inline math, headings, standalone display
math, nested lists, simple tables, static images with captions, resolved
bibliographies, and explicit page breaks use Rust-owned positioned page frames,
including title metadata. Unsupported blocks still route the whole document
through the `genpdf` page-flow fallback.
Alignment nodes also retain their environment's cell math style. `matrix`,
`array`, and `cases` lay out cells in text style; `smallmatrix` uses script
style; and `aligned`, `alignedat`, `gathered`, and display alignment
environments use display style. This controls nested fraction sizing, operator
variants, and math-class spacing inside each cell instead of inheriting the
outer formula's style unconditionally.
Alignment nodes also retain a baseline policy. Top-level display alignments
keep the first row baseline for row tags. Nested `aligned`, `split`, `gathered`,
matrix, array, and cases boxes center their vertical extent on the math axis, so
an enclosing `equation` retains the inner grid's geometry. The baseline follows
XeTeX's `make_vcenter` rule: math axis height plus half the box's total height
([XeTeX source](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L16363-L16372)). The axis uses the family-2 font's OpenType
MATH constant when available, with the configured metric as fallback.
## Rust core rewrite target
The current pipeline is a Rust implementation of a limited LaTeX subset, not a
Rust rewrite of the XeTeX core. It reconstructs a reduced document model from
the TeX VM's token/event stream and delegates PDF drawing, plus non-text-only
page flow, to `genpdf`. The full XeTeX behavior is not present.
The rewrite target keeps a clear boundary between four Rust-owned phases:
1. A source-aware TeX frontend owns tokenization, category codes, macro
expansion, and diagnostics. Commands and environments must remain structured
values rather than being encoded as marker strings.
2. A typesetting engine turns the expanded input into semantic nodes and then
TeX-like horizontal and vertical lists: glyph runs, glue, penalties, math
atoms, boxes, and insertions.
3. A page-layout engine performs shaping, line breaking, float placement, and
page breaking into one positioned page tree with baselines and source anchors.
4. PDF output and the live preview consume that same page tree, so both views
share glyph positions, line breaks, math geometry, and pagination.
Incremental recompilation belongs at the phase boundaries: source edits dirty
the affected syntax and macro dependencies, changed paragraphs invalidate only
their line boxes, and page-level changes reflow from the earliest affected
page. The current paragraph FIFO cache is an isolated optimization and is not
yet this dependency model.
The live preview adds one more reuse boundary: a preview response recomputes the
positioned frames, hashes each page's serialized SVG, and lets the browser
replace only changed pages. Reusing the frames themselves across requests,
rather than only their line boxes and page-break plan, is the next step toward
per-page incremental rendering.
The target is a native Rust rewrite of XeTeX's engine core, not a wrapper
around XeLaTeX. The upstream XeTeX and TeX sources are implementation
references: port well-scoped algorithms and routines into Rust where their
file-level licenses allow it, then organize them around the phase boundaries
above instead of preserving the legacy WEB/C/C++ layout line by line.
XeLaTeX compatibility has two layers: XeTeX engine semantics (tokens,
expansion, registers, boxes, glue, math, page building, font shaping, and
output) and the LaTeX format/package layer built on that engine. The current
`texlang`, `boxworks`, `rusttype`, and `genpdf` dependencies provide Rust
scaffolding, but their use does not make this limited subset equivalent to
XeTeX. The rewrite must eventually own the semantic and layout contracts above;
each dependency should be removed or kept only as a replaceable implementation
detail.
The rewrite proceeds in this order while keeping the editor runnable:
1. Make the source-spanned token/event stream the only input to the compiler
front end. The stream is emitted by the TeX VM, and both document parsing
and math structural parsing now consume it. The serialized view remains
inside VM checkpoint and source-map support; remove those remaining
dependencies and move source preprocessing that interprets TeX syntax into
the VM or source/file world layer.
2. Extend the VM into the TeX execution engine: modes, grouping and assignment
semantics, registers, horizontal/vertical lists, glue, penalties, boxes,
insertions, and math noads. `texlang` remains a replaceable token-VM
foundation; it is not the engine itself.
3. Add Unicode font selection and shaping, TeX paragraph and page building,
and an engine-owned positioned page tree. PDF and the live preview must both
export that tree. Replace `genpdf` as the owner of page composition during
this phase.
4. Load the LaTeX format and package tree on top of the engine, then expand
compatibility against XeLaTeX reference output and diagnostics. This layer
is what makes the result XeLaTeX/LaTeX-compatible for real documents; the
TeX engine alone is not sufficient.
The current dependency boundary and the source-by-source port order are tracked
in [the XeTeX Rust port map](xetex-rust-port-map.md). Treat the current engine
as a migration host until its TeX execution state, list model, typesetting
algorithms, and output tree have been replaced or verified against XeTeX.
Font shaping is an engine requirement: XeTeX compatibility includes Unicode
shaping and OpenType/AAT/Graphite behavior where the chosen font stack supports
them. Incremental compilation is safe only at phase boundaries that account for
TeX's mutable state. Expansion reuse must include the macro definitions,
registers, category codes, and mode at a checkpoint; an edit invalidates forward
until those state values match again. Layout reuse keys the resulting node lists,
fonts, and dimensions, while page composition reflows from the first changed
page.
Compatibility is tracked by observable behavior, not command names: each
slice records its TeX input, expected boxes/positions or PDF result, diagnostics,
font assumptions, and XeLaTeX reference behavior. A command is not marked
compatible merely because it parses or looks plausible.
The first math slice keeps display formulas as structured expressions through
PDF layout. The math tree now keeps ordinary, operator, binary, relation,
opening, closing, punctuation, and inner atoms distinct. Layout applies TeX's
8-by-8 math spacing table, including binary-operator normalization and
style-dependent thin, medium, and thick spaces. Automatic inter-atom spacing
uses TeX's `thinmuskip`, `medmuskip`, and `thickmuskip` variables, initialized to
the LaTeX defaults (3mu, 4mu plus 2mu minus 4mu, and 5mu plus 5mu). Assignments
use the VM's normal group and global-assignment semantics. The expansion stream
records the effective values at each math token, so incremental layout, PDF, and
SVG preview share the same math spacing. Inline math line breaking can adjust
relation and binary spacing using the configured stretch and shrink. Indexed
`\muskip` registers and `\muskipdef` aliases now read and write the engine's
Rust-owned table. Their typed parser delegates to the Rust math-glue scanner
for direct assignments and arithmetic operands. It handles `\\muexpr`, `mu`,
`plus`, `minus`, and scaling expressions, then falls back to Texlang for forms
the engine scanner does not yet handle.
Explicit `\\,`, `\\:`, `\\;`,
`\\!`, `\\quad`, and `\\qquad` spacing is represented by source-located math
glue events. Math groups without local style changes keep their atoms in the
surrounding math list, so binary-operator normalization sees operands across
braces. Style-changing groups retain their local math style while inheriting
the neighboring atom classes needed to normalize operators at their edges.
Display fractions use stacked numerators and denominators; roots draw a rule over
their nuclei and use vertical MATH variants or assemblies for the radical sign.
Radical variants target the nucleus's full height plus the selected clearance and
rule thickness. The sign's baseline aligns with the bottom of the rule; when the
largest available sign exceeds the target, the rule and sign move up by half the
excess, increasing the actual nucleus clearance by the same amount. Legacy fonts
without MATH constants use XeTeX's fallback clearance: one rule thickness plus
one quarter x-height in display style, or one quarter rule thickness otherwise.
The `RadicalExtraAscender` MATH constant is not used by XeTeX's radical routine.
Math-list boxes now use the natural top and bottom extents of their laid-out
children; explicit math glue contributes horizontal width without adding a text
line's vertical strut. Text boxes inside math keep their own text metrics. This
prevents paragraph line height from inflating fractions and script boxes, in
line with XeTeX's natural packing of the converted math list
([XeTeX source](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/xetexdir/xetex.web)).
`\\sqrt[n]{x}` places the degree as a scaled child using the radical-degree
MATH constants; display limits on `\\sum`, `\\prod`, `\\lim`,
`\\max`, and `\\min` stack above and below. `\\limits`, `\\nolimits`, and
`\\displaylimits` now explicitly control operator-script placement and remain
typed, source-located events through math parsing. These rules follow the algorithms
used by XeTeX's math parameter tables. `\\frac`, `\\dfrac`, and `\\tfrac` retain
their automatic, display, and text fraction styles; child sizes, vertical gaps,
and rule thickness come from the active math style and OpenType MATH constants.
The compatibility prelude also lowers `\\overset{...}{...}` and
`\\underset{...}{...}` to operator limits, so their annotations use the same
two-dimensional script boxes. The current lowering treats the annotated base as
an operator; AMS `\\binrel@` class preservation remains to be ported.
`\\binom`, `\\dbinom`, and `\\tbinom` now reuse this stacked fraction layout
without drawing a rule, then measure and stretch parentheses around the box.
Displayed operator limits also reserve the OpenType `StackGapMin` outside the
upper and lower scripts, corresponding to XeTeX's `BigOpSpacing5`; fonts without
a MATH table use a 0.1 em fallback. Single-glyph operators also skew their upper
and lower limits in opposite directions using half the glyph's math italic
correction, following XeTeX's `make_op` layout.
`\\left...\\right` computes its target height from the largest distance to the
math axis and applies `\\delimiterfactor` and `\\delimitershortfall` before
selecting a MATH variant or assembly. Both are assignable TeX variables with
defaults 901 and 5pt; assignments follow TeX's local grouping and `\\global`
rules. The frontend captures the values at formula closure and applies that
snapshot to every delimiter in the formula, including fraction delimiters and
the parentheses around `\\choose` and `\\binom`, matching TeX's later math-list
conversion step. Variant selection compares OpenType MATH advance measurements,
not the rasterized ink bounds; if no variant reaches the target, the layout tries
an assembly and otherwise keeps the largest available variant. Assembly parts
are expanded in their MATH-table order; vertical assemblies are painted in the
reverse order used by XeTeX's vertical box. Part offsets and connector overlap
use each part's MATH `fullAdvance`; glyph ink bounds determine the painted image
bounds independently of the TeX box extent. This follows XeTeX's `var_delimiter` and
OpenType's bottom-to-top vertical part order
([XeTeX source](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/xetexdir/xetex.web),
[OpenType MATH specification](https://learn.microsoft.com/en-us/typography/opentype/spec/math)).
The plain-TeX manual delimiter family (big, Big, bigg, and Bigg, with
left, middle, and right atom-class forms) uses fixed 8.5, 11.5, 14.5, and
17.5 TeX-point virtual boxes to select the matching MATH variant or assembly.
Superscripts on character-like nuclei use the active glyph face's OpenType MATH
italic-correction value when that face provides one. Fonts without a correction
table fall back to the rendered glyph's right-side ink overhang, and non-italic
faces receive no outline-based correction. The selected face follows the same
regular, bold, italic, and bold-italic Liberation Serif files embedded in PDF
and preview output. Script placement now
uses OpenType MATH top/bottom limits, baseline-drop constraints, the minimum
superscript/subscript gap, and the combined-script superscript-bottom constraint
used by XeTeX. Fonts without those constants use EM-based fallback values.
When a base atom selects a local math-family font, its MATH script scale-down,
script and operator-limit constants, italic correction, and MathKern data now
come from that face when available; missing MATH data falls back to the
configured metrics font.
All eight TeX math styles are represented, including cramped variants. Fraction
numerators and denominators now receive their separate `num_style` and
`denom_style`; radical and overline nuclei use cramped style, and subscript and
superscript children use their respective style transitions. Cramped
superscripts read the OpenType `SuperscriptShiftUpCramped` constant.
Unruled fractions such as `\\atop` and `\\choose` use `StackTopShiftUp` and
`StackBottomShiftDown` in text style. Display style follows XeTeX's `num1` and
`denom1` defaults and uses the fraction display-shift constants. The minimum
stack gap comes from the MATH table; without one, it falls back to three rule
thicknesses in text style and seven in display style, following XeTeX's
`make_fraction` path. Fractions rebox the numerator and denominator to the
larger child width without added horizontal padding. MATH
rule thicknesses are used as stored; without a MATH table, the engine uses a
0.04 em default rule and TeX's one-rule or three-rule per-side clearance.
For a single-glyph base, the layout reads per-glyph OpenType `MathKernInfo`
corner tables from the face used to draw each glyph. Script lookup follows
XeTeX's first-character scan: it skips leading math spaces, applies style
changes, selects the active `\\mathchoice` branch, and uses the first character-like
glyph even when the script continues with more content. It stops when the
script starts with a box or a non-character expression. The layout measures
the actual glyph bounds, evaluates both opposing-edge sums after vertical
placement, and chooses the numerically larger correction as XeTeX does. A
composite base, a boxed script nucleus, or missing MATH data retains the
default script offset. See the [XeTeX math-list algorithm](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/xetexdir/xetex.web)
and [XeTeX OpenType math-kern implementation](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/xetexdir/XeTeXOTMath.cpp).
Correction heights equal to a table transition use the kern range that begins
at that height, following the OpenType MATH interval rule.
Because this correction is stored in the shared math box, PDF and SVG use
identical positions.
SVG and PDF use the same rule geometry. These rules follow the algorithms
documented in the primary [TeX engine source](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/tex.web).
Math font switches for `\\mathbf`, `\\mathit`, `\\mathrm`, and `\\text` now
remain explicit nodes in the math tree. The same styled nodes feed PDF and SVG
layout, so bold, italic, and upright math select matching embedded font faces.
`\\overline` and `\\underline` now become two-dimensional accent boxes with
separate bar and nucleus positions. Their vertical gaps, rule thickness, and
reserved ascender/descender space come from the OpenType MATH table when
available; the fallback still lays the bars as rules above or below the body.
`\\hat`, `\\tilde`, `\\widehat`, `\\widetilde`, `\\overbrace`, and
`\\underbrace` are typed accent nodes. The narrow hat and tilde use fixed
math-font glyphs, while the wide variants and braces grow through horizontal
OpenType MATH variants and assemblies. Accent boxes keep the nucleus width,
allowing the painted glyph to overhang as in XeTeX. Top accents use the MATH
`AccentBaseHeight` (or the text font's x-height without a MATH table) and retain
the painted glyph baseline. Single-glyph bases and accent glyphs use their
`TopAccentAttachment` values when available. Accent bitmaps use the same
positions in PDF and SVG; faces without a construction use their available
accent glyph.
The math layout reads OpenType MATH constants for its axis, fraction, script,
radical, radical-degree, and delimiter dimensions when a MATH font is available.
It searches common TeX Live paths for STIX Two Math, New Computer Modern Math,
then STIX Math; setting `TEXRRA_MATH_METRICS_FONT` selects a specific face.
This uses the constants described in the
[OpenType MATH specification](https://learn.microsoft.com/en-us/typography/opentype/spec/math).
If none of those faces is available and no override is set, the compiler falls
back to Liberation Serif metrics. Vertical `\\left...\\right`
delimiters select the first MATH glyph variant large enough for the TeX math-axis
target; if no variant fits, the compiler adds extender parts from the font's
vertical assembly when needed, then distributes connector overlap evenly to
match the target, as described by OpenType MATH. PDF and SVG use the
same antialiased 600-dpi delimiter bitmap.
Math atom outlines are rasterized at 600 dpi and shared by the SVG and PDF
renderers. A loaded MATH face supplies single-symbol operators, relations,
delimiters, punctuation, Unicode Greek letters, and non-alphanumeric
ordinary-class symbols. Default math-italic Latin letters also use that face
when the glyph is available, so their advances, italic corrections, MathKern,
vertical bounds, and accent attachments come from the face used to paint them.
Bold, roman, and text styles use their corresponding Liberation Serif face.
Rasterized atoms derive their box height and baseline from the selected glyph
bounds while keeping its advance as the horizontal math width; text fallbacks
retain the configured font's line metrics. Lowercase Greek letters use the
italic math family, while
uppercase Greek letters use the current math family, following TeX's default
mathcode behavior. SVG keeps these images transparent; PDF composites them onto
white because this PDF backend cannot encode alpha images reliably. Unavailable
or non-outline glyphs fall back to text. Math atoms outside the ordinary class
select upright math style. Display-style single-glyph operators try OpenType
MATH vertical variants and assemblies with a target height of
`max(DisplayOperatorMinHeight, 1.25 × original glyph height)`, following
XeTeX's `make_op`. When the font has no usable construction, the original glyph
keeps its normal size. Delimiters without a usable MATH variant or assembly use
the original glyph's advance and ink bounds, then center its box on the math
axis instead of scaling a text glyph to fit the contents. Math alignment tabs and typed row-break events
now produce a two-dimensional cell grid. `aligned` columns alternate right and left alignment
with an inter-pair gap; `alignedat` and `alignat` use the same column alignment
without automatic gaps and consume their column-pair count. Matrices and
`gathered` center cells; `cases` left-aligns cells; and `array` accepts simple
`l`, `c`, and `r` columns, repeated column patterns, and vertical rules. Matrix environments add paired delimiters;
matrix and array cells use text style, while `smallmatrix` uses script style and
thick-space column gaps. `aligned`, `alignedat`, and `gathered` cells use display
style. Array rows use their measured cell struts, `cases` stretches those struts
by 1.2. Display alignments use the grouped `\jot` dimension (default 3 pt),
captured on the typed environment-start event and carried into the shared math
box layout, so local and global assignments affect subsequent alignments and
invalidate the relevant math parse key. Unstarred
`equation`, `align`, `alignat`, `flalign`, `eqnarray`, `gather`, and `multline`
environments advance a shared equation counter. `multline` lays out its first
row flush left within the full display width, its final row flush right, and
intervening rows centered; it receives one equation number on its final row.
Alignment rows can carry independent numbers, manual `\tag{...}` values or
unparenthesized `\tag*{...}` values,
`\nonumber` / `\notag` suppression, and `\label` references. The PDF renderer
and HTML preview place tags against the same math row baselines when tags fit,
so numbering follows the shared two-dimensional math layout. Tag widths are
measured before placement, with amsmath's half-quad
`\mintagsep` minimum gap ([package documentation](https://tug.ctan.org/macros/latex/required/amsmath/amsmath.pdf)) reserved to prevent a long tag from
overlapping a centered formula; multline reserves that space on the tagged
side. Each row is checked independently; a colliding tag gets a line directly
below its formula row, and later rows move down by the inserted line height.
This follows the row-specific layout model without reproducing all of amsmath's
tag and alignment adjustments. PDF and HTML preview share the same computed
tag positions and measured height. Starred
environments remain unnumbered unless a row has an explicit tag. Full
`amsmath` behavior and OpenType math shaping for ordinary symbols and operators
remain incomplete.
## XeTeX source and licensing
XeTeX is open source and its implementation is now a direct behavioral
reference for the Rust rewrite. The XeTeX upstream notes that its engine sources
live under `source/texk/web2c/xetexdir`. XeTeX portions carry MIT-style
permission, while `xetex.web` also includes a separate e-TeX notice restricting
copying that material. TeX Live as a whole has no single license. Each ported
slice must record its upstream file and applicable notice; do not infer a
license for one file from another. The engine is being restructured in Rust
around incremental phases; it is not a mechanical translation of the legacy
tree. See
the [XeTeX source
notes](https://github.com/TeX-Live/xetex/blob/master/INSTALL), [XeTeX copying
notice](https://raw.githubusercontent.com/TeX-Live/xetex/master/source/texk/web2c/xetexdir/COPYING),
and [TeX Live license information](https://github.com/TeX-Live/installer/blob/master/LICENSE.TL).
No XeTeX source has been copied into this repository as part of the current
milestone. The implementation remains a limited LaTeX subset. Runtime scanning
for the document, compatibility prelude, `\input` files, and `.sty` sources
now uses `texrra-core::mouth` through the `engine::mouth` compatibility
re-export. Texlang still owns the main VM loop and primitive execution, plus
some stdlib input paths such as `\read`.
`vendor/texlang` now has a lazy external-input adapter that preserves VM
expansion frames for nested sources, alongside its earlier brace-group hooks;
its upstream license is retained there. The expanded output retains
source-spanned tokens and typed events, and both document parsing and
math-expression parsing consume them. The compatibility serialization remains
for text-range copying, VM source mapping, and incremental checkpoint slicing.
The next core step is to replace Texlang's main execution loop and fallback
primitive dispatch with an engine-owned token interpreter, then generalize the
Rust-owned text page frames into shared engine lists and a positioned page tree.
`src/rust_typeset/page_builder.rs` is a behavior reimplementation of the
fixed-box page-break slice in XeTeX's `xetex.web`; it does not copy source text
and does not yet model the full page-builder state machine.