diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index a54a3b8..e97ba70 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -4139,6 +4139,30 @@ mod tests { ))); } + #[test] + fn math_alphabet_paints_with_its_type1_face() { + use crate::render::{DisplayItem, FontFace}; + let document = Document::new( + 1_000_000, + vec![Unit::math( + 1, + crate::math::parse_math("\\mathbf{x}"), + &Cmr10Metrics::Math, + )], + ); + let engine = Engine::layout(&document); + let list = engine.pages()[0].display_list(); + let faces: Vec = list + .items + .iter() + .filter_map(|item| match item { + DisplayItem::Text { text, font, .. } if text == "x" => Some(*font), + _ => None, + }) + .collect(); + assert_eq!(faces, vec![FontFace::Bold]); + } + #[test] fn edit_on_second_page_only_rebuilds_second_page() { let mut document = document(); diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index 4de5069..959964b 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -6,6 +6,15 @@ use crate::cmr10::{Cmr10Metrics, cmex_delimiter}; +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum MathAlphabet { + Roman, + Bold, + Italic, + Sans, + Mono, +} + #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum MathAtom { Symbol(char), @@ -16,6 +25,10 @@ pub enum MathAtom { degree: Option>, }, Text(String), + Alphabet { + text: String, + alphabet: MathAlphabet, + }, Delimited { left: char, right: char, @@ -274,6 +287,27 @@ pub fn split_math_lines(atom: &MathAtom, font: &Cmr10Metrics, max_width: i64) -> lines.into_iter().map(MathAtom::Row).collect() } +/// Metrics for the built-in math alphabets. +/// +/// Mathematical italic letters are the default math face (`cmmi10`); the +/// upright faces reuse the paragraph TFMs so `\mathbf`, `\mathsf` and +/// `\mathtt` get the same advances as their text counterparts. +pub(crate) fn alphabet_metrics(font: Cmr10Metrics, alphabet: MathAlphabet) -> Cmr10Metrics { + match alphabet { + MathAlphabet::Roman => font, + MathAlphabet::Italic => Cmr10Metrics::Math, + MathAlphabet::Bold => { + Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Bold) + } + MathAlphabet::Sans => { + Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Sans) + } + MathAlphabet::Mono => { + Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Mono) + } + } +} + fn atom_class(atom: &MathAtom) -> MathClass { match atom { MathAtom::Symbol(character) => math_class(*character), @@ -417,6 +451,23 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { height: 6 * 65_536, depth: 2 * 65_536, }, + MathAtom::Alphabet { text, alphabet } => { + let metrics = alphabet_metrics(*font, *alphabet); + MathBox { + width: text + .chars() + .map(|character| { + if character == ' ' { + metrics.space() + } else { + metrics.width(character) + } + }) + .sum(), + height: 6 * 65_536, + depth: 2 * 65_536, + } + } MathAtom::Delimited { left, right, body } => { let body_box = layout_math(body, font); let delta = body_box.height + body_box.depth; @@ -1267,7 +1318,17 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) { if after < chars.len() { after += 1; } - (MathAtom::Text(text), after) + let alphabet = match command.as_str() { + "mathbf" => Some(MathAlphabet::Bold), + "mathit" => Some(MathAlphabet::Italic), + "mathsf" => Some(MathAlphabet::Sans), + "mathtt" => Some(MathAlphabet::Mono), + _ => None, + }; + match alphabet { + Some(alphabet) => (MathAtom::Alphabet { text, alphabet }, after), + None => (MathAtom::Text(text), after), + } } "not" => { let (base, after) = parse_atom(chars, next); @@ -1446,6 +1507,34 @@ mod tests { assert!(indexed.height > plain.height); } + #[test] + fn math_bold_letters_use_bold_metrics() { + let font = Cmr10Metrics::Math; + let plain = layout_math(&parse_math("\\mathrm{x}"), &font); + let bold = layout_math(&parse_math("\\mathbf{x}"), &font); + let bold_metrics = Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Bold); + assert_eq!(bold.width, bold_metrics.width('x')); + assert_ne!(bold.width, plain.width); + } + + #[test] + fn math_italic_letters_use_the_math_face() { + let font = Cmr10Metrics::Math; + let italic = layout_math(&parse_math("\\mathit{x}"), &font); + assert_eq!(italic.width, Cmr10Metrics::Math.width('x')); + } + + #[test] + fn math_sans_and_typewriter_use_their_metrics() { + let font = Cmr10Metrics::Math; + let sans = layout_math(&parse_math("\\mathsf{x}"), &font); + let mono = layout_math(&parse_math("\\mathtt{x}"), &font); + let sans_metrics = Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Sans); + let mono_metrics = Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Mono); + assert_eq!(sans.width, sans_metrics.width('x')); + assert_eq!(mono.width, mono_metrics.width('x')); + } + #[test] fn mathcal_keeps_character_widths() { let font = Cmr10Metrics::default(); diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 0885703..9e5796b 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -682,6 +682,31 @@ impl Page { cursor += font.width(character); } } + MathAtom::Alphabet { text, alphabet } => { + let metrics = math::alphabet_metrics(*font, *alphabet); + let face = match alphabet { + math::MathAlphabet::Roman => FontFace::Roman, + math::MathAlphabet::Bold => FontFace::Bold, + math::MathAlphabet::Italic => FontFace::MathItalic, + math::MathAlphabet::Sans => FontFace::Sans, + math::MathAlphabet::Mono => FontFace::Mono, + }; + let mut cursor = x; + for character in text.chars() { + list.push(DisplayItem::Text { + font: face, + x: cursor, + y: baseline, + size, + text: character.to_string(), + }); + cursor += if character == ' ' { + metrics.space() + } else { + metrics.width(character) + }; + } + } MathAtom::Row(atoms) => { let mut cursor = x; for child in atoms { diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index a58f79c..a3ec8ce 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -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`). 534 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 538 workspace tests are green and no oracle fixture is ignored. Status after G1 (P0-P2): the paragraph model reproduces TeX's passes, diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 7f667b5..814182c 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -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{...}` 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`/`\dimen`/`\skip` 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` or `\count` changes the insertion capacity and reservation of later pages); the configured `\skip` also reserves space above its class once per page in the paged builder, and a `\skip` 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`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and `\notag`/`\nonumber` suppress it; math italic letters are embedded as Computer Modern Type1 outlines (`cmmi10`) | +| 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; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and `\notag`/`\nonumber` suppress it; math italic letters are embedded as Computer Modern Type1 outlines (`cmmi10`), and math alphabets map `\\mathbf`/`\\mathit`/`\\mathsf`/`\\mathtt` onto the bold, math-italic, sans and mono faces with their TFMs | | M5 | NFSS/TFM metrics, CM/Latin Modern | **partial**: paragraph-level NFSS declarations and inline run composition over the built-in Roman/Bold/Italic/BoldItalic/Mono/Sans faces, per-face Computer Modern TFM metrics, and Type1 (PFB) outline embedding for every built-in face plus `cmmi10` math italics, with Liberation subsets used only as a fallback for characters outside the Type1 encodings; full NFSS family/shape state and Type1 coverage for arbitrary Unicode remain open | | 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, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`, plus `cmmi10` for mathematical italic letters), falling back to Liberation subsets only for characters the Type1 encodings cannot address. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 355 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 534 tests (355 route-D unit, 33 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 359 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 538 tests (359 route-D unit, 33 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo