Space math atoms with the full TeX class table

This commit is contained in:
gloamxun committed 2026-10-24 01:51:10 +08:00
1 parent f7e89c78a2
commit 3cbfdabe03
3 files changed
+138 -22

No files matched your search

+135 -19
View File
@@ -144,28 +144,98 @@ pub fn math_class(character: char) -> MathClass {
}
}
/// TeX's spacing table in math units (1mu = 1/18em).
fn spacing_mu(left: MathClass, right: MathClass) -> i64 {
/// Width of one math unit at 10pt (TeX's `\thinmuskip` is 3mu).
const THIN_MU: i64 = 3 * 65_536 / 18;
/// Width of `\medmuskip` (4mu plus 2mu minus 4mu at 10pt).
const MED_MU: i64 = 4 * 65_536 / 18;
/// Width of `\thickmuskip` (5mu plus 5mu at 10pt).
const THICK_MU: i64 = 5 * 65_536 / 18;
/// TeX's inter-atom spacing table.
///
/// The result is the number of math units (0, thin, medium or thick) inserted
/// between two atoms of the given classes. Entries that TeX marks as
/// impossible cannot occur after `row_classes` normalises binary operators.
fn spacing_level(left: MathClass, right: MathClass) -> i64 {
use MathClass::*;
match (left, right) {
(Binary, Binary)
| (Relation, Relation)
| (Open, _)
| (_, Close)
| (_, Punctuation)
| (Punctuation, _) => 0,
(Ordinary, Binary) | (Binary, Ordinary) => 4,
(Ordinary, Relation) | (Relation, Ordinary) => 5,
(Binary, Relation) | (Relation, Binary) => 0,
(Inner, Inner) => 0,
(Inner, _) | (_, Inner) => 3,
(Op, Op) => 0,
(Op, _) | (_, Op) => 3,
(Ordinary, Ordinary) => 0,
(Ordinary, Ordinary) | (Ordinary, Open) | (Ordinary, Close) | (Ordinary, Punctuation) => 0,
(Ordinary, Op) | (Ordinary, Inner) => 1,
(Ordinary, Binary) => 2,
(Ordinary, Relation) => 3,
(Op, Ordinary) | (Op, Op) | (Op, Inner) => 1,
(Op, Binary) => 2,
(Op, Relation) => 3,
(Op, Open) | (Op, Close) | (Op, Punctuation) => 0,
(Binary, Ordinary) | (Binary, Op) | (Binary, Open) | (Binary, Inner) => 2,
(Binary, Binary) | (Binary, Relation) | (Binary, Close) | (Binary, Punctuation) => 0,
(Relation, Ordinary) | (Relation, Op) | (Relation, Open) | (Relation, Inner) => 3,
(Relation, Binary) | (Relation, Relation) | (Relation, Close) | (Relation, Punctuation) => {
0
}
(Open, Ordinary)
| (Open, Op)
| (Open, Binary)
| (Open, Relation)
| (Open, Open)
| (Open, Close)
| (Open, Punctuation)
| (Open, Inner) => 0,
(Close, Ordinary) | (Close, Open) | (Close, Close) | (Close, Punctuation) => 0,
(Close, Op) | (Close, Inner) => 1,
(Close, Binary) => 2,
(Close, Relation) => 3,
(Punctuation, Ordinary)
| (Punctuation, Op)
| (Punctuation, Binary)
| (Punctuation, Relation)
| (Punctuation, Open)
| (Punctuation, Close)
| (Punctuation, Punctuation)
| (Punctuation, Inner) => 1,
(Inner, Ordinary) | (Inner, Op) | (Inner, Open) | (Inner, Punctuation) => 1,
(Inner, Binary) => 2,
(Inner, Relation) | (Inner, Inner) => 3,
(Inner, Close) => 0,
}
}
fn spacing_width(left: MathClass, right: MathClass) -> i64 {
match spacing_level(left, right) {
1 => THIN_MU,
2 => MED_MU,
3 => THICK_MU,
_ => 0,
}
}
/// Classify the atoms of one math list and apply TeX's binary-operator
/// normalisation: a `\mathbin` that starts the list, follows an operator-like
/// atom, or precedes a relation/close/punctuation becomes ordinary.
fn row_classes(atoms: &[MathAtom]) -> Vec<MathClass> {
use MathClass::*;
let original: Vec<MathClass> = atoms.iter().map(atom_class).collect();
let mut classes = original.clone();
for (index, class) in original.iter().enumerate() {
if *class != Binary {
continue;
}
let previous_is_operand = index > 0;
let previous_forbids = index == 0
|| matches!(
original[index - 1],
Binary | Op | Relation | Open | Punctuation
);
let next_forbids = index + 1 == original.len()
|| matches!(original[index + 1], Relation | Close | Punctuation);
if previous_forbids || next_forbids {
classes[index] = Ordinary;
}
let _ = previous_is_operand;
}
classes
}
fn scaled(value: i64, factor: f64) -> i64 {
(value as f64 * factor).round() as i64
}
@@ -207,6 +277,11 @@ fn atom_class(atom: &MathAtom) -> MathClass {
MathAtom::Row(atoms) => atoms.last().map(atom_class).unwrap_or(MathClass::Ordinary),
MathAtom::Negated { base } => atom_class(base),
MathAtom::Cancel { base, .. } => atom_class(base),
MathAtom::BigOperator { .. } => MathClass::Op,
MathAtom::Limits { base, .. } => atom_class(base),
MathAtom::Fraction { .. } | MathAtom::Binomial { .. } | MathAtom::Delimited { .. } => {
MathClass::Inner
}
_ => MathClass::Ordinary,
}
}
@@ -303,12 +378,11 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
let mut width = 0;
let mut height = 0;
let mut depth = 0;
let classes = row_classes(atoms);
for (index, atom) in atoms.iter().enumerate() {
let boxed = layout_math(atom, font);
if index > 0 {
let left = atom_class(&atoms[index - 1]);
let right = atom_class(atom);
width += spacing_mu(left, right) * 65_536 / 18;
width += spacing_width(classes[index - 1], classes[index]);
}
width += boxed.width;
height = height.max(boxed.height);
@@ -1976,3 +2050,45 @@ mod delimiter_selection_tests {
assert!(tall.width > plain.width);
}
}
#[cfg(test)]
mod spacing_class_tests {
use super::*;
use crate::cmr10::Cmr10Metrics;
fn width(source: &str) -> i64 {
layout_math(&parse_math(source), &Cmr10Metrics::Math).width
}
#[test]
fn punctuation_gets_a_thin_space() {
let font = Cmr10Metrics::Math;
let packed = font.width('a') + font.width(',') + font.width('b');
assert_eq!(width("a,b") - packed, 3 * 65_536 / 18);
}
#[test]
fn binary_operators_at_list_edges_become_ordinary() {
let font = Cmr10Metrics::Math;
let plus = font.width('+');
let a = font.width('a');
assert_eq!(width("+a"), plus + a);
assert_eq!(width("a+"), a + plus);
}
#[test]
fn relation_and_binary_spacing_stay_distinct() {
let font = Cmr10Metrics::Math;
let base = font.width('x') + font.width('+') + font.width('y');
assert_eq!(width("x+y") - base, 2 * (4 * 65_536 / 18));
let relation = font.width('x') + font.width('=') + font.width('y');
assert_eq!(width("x=y") - relation, 2 * (5 * 65_536 / 18));
}
#[test]
fn big_operators_are_operator_atoms() {
let font = Cmr10Metrics::Math;
let sum = width(r"\sum");
assert_eq!(width(r"\sum x") - sum - font.width('x'), 3 * 65_536 / 18);
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`). 502 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 506 workspace tests are green and no oracle
fixture is ignored.
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
+2 -2
View File
@@ -131,7 +131,7 @@ and justification.
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures |
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions, bottom floats or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset, and `\mark{...}`/`\marks<n>{...}` writes inside the routine are carried to the following page's mark list with their class; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets the pages the routine has not seen yet, even when the document raises insertion material; only a document that defers bottom floats keeps its initial goal, because the carried queue cannot be rebuilt after a retarget), `\ht255`, `\dp255` and `\wd255` expose the page box height, depth and width to the routine, and `\hsize` is readable (and assignable for the rest of the run) while `\wd255` tracks it; route-D sets `\hsize` from its 480pt text measure, insertion class registers `\count<n>`/`\dimen<n>`/`\skip<n>` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments that outlive the routine (the paged builder runs the routine after each page, so an assigned `\dimen<n>` or `\count<n>` changes the insertion capacity and reservation of later pages); the configured `\skip<n>` also reserves space above its class once per page in the paged builder, and a `\skip<n>` assignment rebuilds the pages the routine has not seen yet with the new reservation, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine; `\vbadness` reports the badness of the break that produced the page and `\insertpenalties` the number of insertion items held over from it |
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), though `\valign`, nested tables and full tabular parity remain open |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an explicit approximation of TeX's `\split`/`align` behaviour); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; no full TeX math spacing classes yet |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an explicit approximation of TeX's `\split`/`align` behaviour); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation |
| 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 |
@@ -367,7 +367,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 342 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 502 tests (342 route-D unit, 15 engine unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 v1 unit, 1 core unit), with none ignored. v1 remains the live server path.
The crate currently has 346 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 506 tests (346 route-D unit, 15 engine unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 v1 unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo