Files
texrra-engine/docs/TEX_CORE.md
T

13 KiB
Executable File

TeX-compatible incremental core (route D)

Status: M0 architecture spike + M1 paragraph builder implemented in crates/texrra-tex-core. The production v1 engine in src/rust_typeset remains the default and is kept as a fallback while the TeX-compatible core grows.

Why route D

The v1 engine parses LaTeX into DocumentModel and lays it out with hand-written algorithms. That gives true incremental preview, but it cannot be page-identical for arbitrary .cls/.sty files: class files are TeX programs, and their layout primitives (\vbox, \halign, \output, \twocolumn, insertions, math lists, font metrics) are not executed.

Route D is a TeX-compatible execution/layout core designed for incremental operation from the start. It does not embed pdfTeX, XeTeX or Tectonic.

  • Layout::changed_pages / Engine::changed_pages() list the page indices whose sealed hash changed during the last edit.

M0 scope (this spike)

crates/texrra-tex-core currently provides:

  • VerticalItem::{Box, Glue, Penalty} and VerticalBox as the first vertical list model;
  • Unit::paragraph backed by the M1 box/glue/penalty paragraph builder;
  • Engine::layout that builds pages with a simple page goal;
  • Checkpoint before every top-level unit, containing the completed-page count, used vertical space and current page items;
  • Page hashes derived from both vertical items and the contributing unit sources;
  • Engine::edit which restores the checkpoint before the edited unit, re-executes only the suffix, compares page hashes, and reports recomputed_pages;
  • Unit::paragraph_style records whether a unit is text and can be re-flowed by Engine::edit; structural units (halign, insertion, float) are never rewritten from a plain source string.
  • serde round-trip for checkpoints.

M0 proves the incremental contract; M1 starts replacing the placeholder with horizontal material and a paragraph breaker. The page builder, math, fonts and class execution are still ahead.

M1 scope (paragraph builder)

crates/texrra-tex-core/src/paragraph.rs adds:

  • HorizontalItem::{Box, Glue, Penalty} and HorizontalBox as the horizontal list model;
  • ParagraphStyle with line_width, par_indent, line_height and glue stretch/shrink;
  • Cmr10Metrics, a CMR10 ASCII width table extracted from cmr10.tfm with tftopl, plus the fontdimen space/stretch/shrink values;
  • an item-stream Knuth-Plass-style dynamic program over character boxes, glue and penalty breakpoints that minimizes badness from glue stretch/shrink, allows overfull lines with an explicit overfull penalty, applies par_indent to the first line, and emits justified glue;
  • Paragraph { lines, height, width } and a paragraph-backed Unit.

M1 still does not hyphenate, process \discretionary, use real TFM metrics or compare against pdfTeX. Those are the next paragraph milestones.

Target architecture

  • Persistent TeX VM state: macros, registers, fonts, counters, output queue.
  • Stable IDs for top-level units.
  • Checkpoint at page boundaries plus unit boundaries.
  • Dependency graph for labels, references, counters, TOC and citations.
  • Dirty propagation: after a local edit, replay from the nearest checkpoint and stop at the first unchanged page hash.
  • Float/footnote queues restored with the checkpoint.

Milestones

Milestone Content Acceptance
M0 vertical list, page builder, checkpoint, page hash, edit demo edit on page 2 rebuilds only page 2
M1 TeX box/glue/penalty + paragraph builder (\par, \hsize, \parindent) partial: item stream, CMR10 metrics, pdfTeX fixture and minimum line fill; hyphenation next
M2 page builder + \output, \vsize, \topskip, footnotes, floats partial: \vsize page goal, \topskip, forced penalties, Insertion reserve, running Marks, OutputRoutine hook, top/bottom Float placement; interpreted \output, float pages next
M3 \halign, \omit, \span, \multispan, booktabs/longtable partial: Halign model with natural column widths, spans and rule rows; no \omit/\span token parsing or PDF painting yet
M4 math lists, scripts, fractions, radicals, accents, delimiters partial: MathAtom symbol/script/fraction boxes with CMR10 widths; no token conversion, radicals, accents or painter
M5 NFSS/TFM metrics, CM/Latin Modern same line/page breaks as reference
M6 class/package execution (article, sn-jnl) Overleaf page-count parity
M7 \special, PDF XObjects, hyperref annotations PDF structure parity

Current limits

  • The M1 paragraph builder uses a CMR10 ASCII metric table; it does not yet hyphenate, honor all penalties, apply kerning/ligatures, or parse arbitrary TFM files.

Multi-width pdfTeX comparison (same 24-word ASCII paragraph):

\hsize pdfTeX words per line current DP
120pt 5, 6, 7, 4 3, 4, 4, 4, 5
150pt 6, 7, 6, 4 4, 5, 6, 6
180pt 7, 7, 8 7, 7, 8
200pt 8, 7, 7 6, 7, 9

The remaining difference is the TeX tolerance/demerit model, not CMR10 metrics: TeX accepts moderately overfull lines that our DP rejects.

Concrete 120pt first-line candidates: a 3-word line has natural 109.4pt, stretch 4.6pt, badness 396; a 5-word line has natural 142.8pt, shrink 5.6pt, overfull ratio 4.11, badness 6942. TeX rejects the underfull candidate under its tolerance but still emits the moderately overfull 5-word line. Reproducing this needs a two-pass tolerance algorithm with an emergency overfull pass, not a single cost function.

  • \middle| inside \left...\right is accepted as a delimiter symbol (not yet stretched).
  • \sqrt[n]{x} carries an optional degree atom; \left. is an empty delimiter with zero width.
  • MathAtom::Accent { accent, base } parses \hat, \widehat, \tilde, \widetilde, \bar, \overline and \vec; it adds accent height without changing the base width.
  • MathAtom::Smash { body, top, bottom } implements \smash and \smash[t]/\smash[b].
  • MathAtom::Phantom { body, horizontal, vertical } implements \phantom, \hphantom, \vphantom dimension-only boxes.
  • MathAtom::BigOperator { name } gives \sum/\prod 12pt width and \int 8pt width with larger height/depth than text.
  • MathAtom::Limits { base, sub, sup } gives \sum, \prod, \int, \lim, \sup, \inf above/below scripts.
  • MathAtom::Classed { class, body } implements \mathord, \mathop, \mathbin, \mathrel, \mathopen, \mathclose, \mathpunct and \mathinner spacing overrides.
  • MathAtom::SizedDelimiter { delimiter, size } parses \big/\Big/\bigg/\Bigg (and l/r variants); extents are 8/11/14/17pt.
  • MathAtom::Stack { top, base, above } parses \overset/\underset; the decoration contributes 1pt of extra separation.
  • MathAtom::Brace { base, above } parses \overbrace/\underbrace and adds 2pt of height or depth.
  • MathAtom::Binomial { numerator, denominator } parses \binom{n}{k} / \dbinom / \tbinom; layout stacks the arguments with a 4pt delimiter allowance.
  • \mathcal, \mathbb, \mathbf, \mathit, \mathsf, \mathtt, \mathfrak, \mathnormal parse their argument as upright Text for metrics; visual alphabet selection waits for the NFSS math font layer.
  • Named operators (\max, \min, \sin, \log, \det, ...) parse as upright Text atoms.
  • MathAtom::Underline { base } parses \underline{...} and adds 2pt depth without changing width or height.
  • MathAtom::Text(String) parses \text{...} and \mathrm{...}; widths use upright CMR glyphs and spaces use the font space width.
  • MathAtom::Delimited { left, right, body }
  • Delimiter width grows with the body extent: each non-. delimiter is 0.35 * max(body height + depth, 7pt) wide. and \left...\right parsing grow the delimiter box with the body height/depth.
  • MathClass and TeX's 0/3/4/5mu inter-atom table add spacing for binary/relation/open/close/punctuation atoms in MathAtom::Row.
  • parse_math converts a small TeX math subset (symbols, {} groups, _/^ scripts, \frac, \sqrt) into MathAtom::Row.
  • MathAtom::{Symbol, Script, Fraction} and layout_math produce MathBox { width, height, depth }; Unit::math turns an atom into a vertical box. Parsing TeX math tokens and painting remain future M4 work.
  • M1 now inserts TeX en-US hyphenation points as HorizontalItem:: Discretionary: a break adds the hyphen width, a non-break keeps zero width. The line breaker scores these breakpoints with the same glue model as spaces.
  • Unit::halign lays out natural column widths, multi-column spans and rule rows as a VerticalItem::Halign; Halign::cell_box returns each cell's aligned rectangle for a future painter. It is not yet painted by v2.
  • Pages that start with a float also honour Document::top_skip.
  • Unit::vertical and Unit::insertion build arbitrary vertical material and reserved-height page insertions; insertion height is deducted from the usable page goal and the material is attached to Page::insertions.
  • Page breaking handles vertical boxes/glue, Document::top_skip and forced vertical penalties (penalty <= -10000); positive penalties are recorded but not yet part of page badness. VerticalItem::Insertion material is attached to Page::insertions and reserves height from the page goal. VerticalItem::Mark material is collected into Page::marks and included in the page hash. OutputRoutine::shipout runs before sealing and may mutate each page; this models the \output stage in Rust rather than as an interpreted token list, and cannot yet change page goals. Top Float material is deferred to the next page when it arrives late; bottom floats reserve height on the current page. Dedicated float pages and \textfraction-style policies are not implemented yet.
  • No macro state, output routine, math, fonts or PDF output in the new core yet.
  • The v1 server and project API still use src/rust_typeset and are unchanged.

Verification

cargo test -p texrra-tex-core --offline

The M0 tests cover page splitting, checkpoint serialization and page-local editing. Three M1 tests cover glue-based line breaking, paragraph indentation and empty paragraphs.

Unit::halign_from_source parses & rows, \\ separators, \omit, \span, \multispan{n} and \hline rule rows. Unit::halign_from_source_with_template additionally accepts an l/c/r column template. VerticalItem::Rule { width, height } and Unit::rule(id, width, height) add filled rules to the vertical list; rules consume page height like boxes.

\not becomes MathAtom::Negated, preserving the base atom's geometry for a later overlaid slash.

\noalign{...} material in a halign source is skipped while rows are scanned.

\bmod/\pmod{n} parse to upright mod rows, with \pmod wrapping its argument in (mod ...).

\pmod{n} is a Classed relation, and \not inherits the base atom's math class for spacing.

\mathinner{...} uses MathClass::Inner with 3mu on either side.

\boxed{x} adds 3pt padding around its body in the math model.

Unit::vskip(id, height) adds a vertical glue item to the page list.

Unit::penalty(id, value) adds a vertical penalty; values <= -10000 force a page break.

\stackrel{top}{base} shares the Stack layout with \overset.

\overrightarrow/\overleftarrow parse as arrow accents (U+20D7/U+20D6).

\widecheck and \dddot map to U+030C and U+20DB accents.

Milestone status (route D)

Milestone State Notes
M0 checkpoint engine done page list, page hashes, snapshot/restore, edit replay
M1 horizontal/paragraphs partial boxes/glue/penalties, CMR10 metrics, hyphenation, pdfTeX fixtures; tolerance/demerits still approximate
M2 vertical/page builder partial vsize, topskip, insertions, marks, output hook, top/bottom floats, rules, vskip, penalties; interpreted \output and float pages absent
M3 halign partial natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter
M4 math partial atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping
M5 NFSS/TFM partial CMR10 width table only
M6 specials/XObject not started
M7 incremental integration partial edit replay + page hashes, not wired into v1 preview

v1 remains the production renderer; the route-D core is additive and tested independently.

\substack{a\\b} parses each row and stacks them as MathAtom::StackLines.

\mathring{x} is the U+030A ring accent.

\overleftrightarrow uses U+20E1.

Unit::mark(id, class, text) and Unit::float(id, placement, width, height) are convenience constructors for M2 page items.

\mathop uses the Op spacing class (3mu against ordinary atoms).

\mathstrut is a zero-width strut with 7pt height and 2pt depth.

M3 painter prototype: Page::display_list() / Halign::display_list() produce absolute text and rule primitives, and DisplayList::to_svg() writes a standalone SVG. Paragraph text and math are not yet painted.

Paragraph painter: Unit::paragraph now stores VerticalItem::Paragraph, and Page::display_list() paints each line's HorizontalBox characters at their line advance. Boxes created by hyphenation carry -; justification is approximated by item widths.

Math painter: stores ; paints symbols, rows, scripts, fractions (with a rule), roots, delimiters, accents, underlines, boxes and stacks. Script/fraction positions are simplified TeX geometry.