From 66ceabad0e944c9900aa371fbf4fbf7bc3899228 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 24 Oct 2026 03:46:50 +0800 Subject: [PATCH] Draw big operators with cmex10 outlines --- crates/texrra-tex-core/src/cmr10.rs | 72 +++++++++++++++++++++------- crates/texrra-tex-core/src/lib.rs | 28 +++++++++++ crates/texrra-tex-core/src/math.rs | 21 ++++++++ crates/texrra-tex-core/src/pdf.rs | 46 ++++++++++++++++-- crates/texrra-tex-core/src/render.rs | 18 +++++-- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 8 ++-- 7 files changed, 167 insertions(+), 28 deletions(-) diff --git a/crates/texrra-tex-core/src/cmr10.rs b/crates/texrra-tex-core/src/cmr10.rs index 7688ce5..9d9819b 100644 --- a/crates/texrra-tex-core/src/cmr10.rs +++ b/crates/texrra-tex-core/src/cmr10.rs @@ -152,6 +152,12 @@ impl Cmr10Metrics { return width; } } + if let Some(slot) = math_extension_slot(character) { + let width = math_extension_metrics().width(char::from(slot)); + if width > 0 { + return width; + } + } } let width = self.metrics().width(character); if width > 0 { width } else { 327_680 } @@ -168,6 +174,9 @@ impl Cmr10Metrics { if let Some(slot) = math_symbol_slot(character) { return math_symbol_metrics().height(char::from(slot)); } + if let Some(slot) = math_extension_slot(character) { + return math_extension_metrics().height(char::from(slot)); + } } self.metrics().height(character) } @@ -183,6 +192,9 @@ impl Cmr10Metrics { if let Some(slot) = math_symbol_slot(character) { return math_symbol_metrics().depth(char::from(slot)); } + if let Some(slot) = math_extension_slot(character) { + return math_extension_metrics().depth(char::from(slot)); + } } self.metrics().depth(character) } @@ -195,6 +207,9 @@ impl Cmr10Metrics { if let Some(slot) = math_symbol_slot(character) { return math_symbol_metrics().italic(char::from(slot)); } + if let Some(slot) = math_extension_slot(character) { + return math_extension_metrics().italic(char::from(slot)); + } } self.metrics().italic(character) } @@ -234,28 +249,53 @@ impl Cmr10Metrics { /// Metrics for a named Computer Modern extension big operator (`\sum` and friends). pub fn cmex_operator(name: &str) -> Option<(i64, i64, i64)> { let slot = match name { - "sum" => 'P', - "prod" => 'Q', - "coprod" => 'R', - "int" => 'S', - "oint" => 'T', - "bigcap" => 'U', - "bigcup" => 'V', - "bigsqcup" => 'W', - "bigvee" => 'X', - "bigwedge" => 'Y', - "bigodot" => 'Z', - "bigotimes" => '[', - "bigoplus" => '\\', - "biguplus" => ']', + "sum" => 80, + "prod" => 81, + "coprod" => 96, + "int" => 82, + "oint" => 72, + "bigcap" => 84, + "bigcup" => 83, + "bigsqcup" => 85, + "bigvee" => 87, + "bigwedge" => 86, + "bigodot" => 74, + "bigotimes" => 78, + "bigoplus" => 76, + "biguplus" => 85, _ => return None, }; let metrics = math_extension_metrics(); - let width = metrics.width(slot); + let width = metrics.width(char::from(slot)); if width == 0 { return None; } - Some((width, metrics.height(slot), metrics.depth(slot))) + Some(( + width, + metrics.height(char::from(slot)), + metrics.depth(char::from(slot)), + )) +} + +/// Map a Unicode n-ary operator to its slot in the bundled cmex10 font. +pub fn math_extension_slot(character: char) -> Option { + let slot = match character { + '\u{2211}' => 80, // \sum + '\u{220F}' => 81, // \prod + '\u{2210}' => 96, // \coprod + '\u{222B}' => 82, // \int + '\u{222E}' => 72, // \oint + '\u{22C2}' => 84, // \bigcap + '\u{22C3}' => 83, // \bigcup + '\u{2A06}' => 85, // \bigsqcup + '\u{22C1}' => 87, // \bigvee + '\u{22C0}' => 86, // \bigwedge + '\u{2A00}' => 74, // \bigodot + '\u{2A02}' => 78, // \bigotimes + '\u{2A01}' => 76, // \bigoplus + _ => return None, + }; + Some(slot) } #[cfg(test)] diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 1da50c4..112ca3b 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -6413,6 +6413,34 @@ mod tests { assert!(svg.contains(">x")); } + #[test] + fn big_operators_paint_with_the_cmex_face() { + let atom = crate::math::parse_math("\\sum_{i=1}^{n}"); + let document = Document::new( + 400, + vec![Unit::math(1, atom, &crate::cmr10::Cmr10Metrics::new())], + ); + let engine = Engine::layout(&document); + let list = engine.pages()[0].display_list(); + let item = list + .items + .iter() + .find(|item| { + matches!( + item, + DisplayItem::Text { + font: crate::render::FontFace::MathExtension, + .. + } + ) + }) + .expect("sum should use the CMEX face"); + if let DisplayItem::Text { text, .. } = item { + assert_eq!(text, "\u{2211}"); + } + assert!(list.to_svg().contains('\u{2211}')); + } + #[test] fn bottom_float_content_is_painted_at_the_page_bottom() { let mut document = Document::new(100, Vec::new()); diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index 959964b..db99438 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -835,6 +835,27 @@ fn parse_delimiter(chars: &[char], index: usize) -> (char, usize) { } } +/// Unicode n-ary operator for a `\sum`-style big operator name. +pub(crate) fn big_operator_character(name: &str) -> Option { + let character = match name { + "sum" => '\u{2211}', + "prod" => '\u{220F}', + "coprod" => '\u{2210}', + "int" => '\u{222B}', + "oint" => '\u{222E}', + "bigcap" => '\u{22C2}', + "bigcup" => '\u{22C3}', + "bigsqcup" => '\u{2A06}', + "bigvee" => '\u{22C1}', + "bigwedge" => '\u{22C0}', + "bigodot" => '\u{2A00}', + "bigotimes" => '\u{2A02}', + "bigoplus" => '\u{2A01}', + _ => return None, + }; + Some(character) +} + fn math_symbol_command(name: &str) -> Option { let character = match name { "cdot" => '\u{00B7}', diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 31a0e7a..660dabf 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -16,7 +16,7 @@ use crate::cmr10::Cmr10Metrics; use crate::render::{DisplayItem, DisplayList, FontFace}; use crate::type1::Type1Font; -const FACE_COUNT: usize = 8; +const FACE_COUNT: usize = 9; fn deflate(bytes: &[u8]) -> Vec { let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default()); @@ -80,6 +80,12 @@ static FULL_FACES: [PdfFace; FACE_COUNT] = [ italic_angle: 0, font: OnceLock::new(), }, + PdfFace { + bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"), + base: "LiberationSerif-MathExtension", + italic_angle: 0, + font: OnceLock::new(), + }, ]; static MIN_FACES: [PdfFace; FACE_COUNT] = [ @@ -131,6 +137,12 @@ static MIN_FACES: [PdfFace; FACE_COUNT] = [ italic_angle: 0, font: OnceLock::new(), }, + PdfFace { + bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"), + base: "LiberationSerif-MathExtension", + italic_angle: 0, + font: OnceLock::new(), + }, ]; fn minimal_text_char(ch: char) -> bool { @@ -261,6 +273,7 @@ fn font_resource(font: FontFace) -> &'static str { FontFace::Sans => "F6", FontFace::MathItalic => "F7", FontFace::MathSymbol => "F8", + FontFace::MathExtension => "F9", } } @@ -284,6 +297,7 @@ fn type1_bytes(slot: usize) -> Option<&'static [u8]> { Some(include_bytes!("../../../assets/fonts/cmss10.pfb")), Some(include_bytes!("../../../assets/fonts/cmmi10.pfb")), Some(include_bytes!("../../../assets/fonts/cmsy10.pfb")), + Some(include_bytes!("../../../assets/fonts/cmex10.pfb")), ]; PFBS[slot] } @@ -497,11 +511,16 @@ fn write_pdf( return None; } let font = type1_fonts()[slot].as_ref()?; - if slot == FontFace::MathSymbol as usize { + if slot == FontFace::MathSymbol as usize || slot == FontFace::MathExtension as usize { let codes = used_chars[slot] .iter() .filter_map(|character| { - crate::cmr10::math_symbol_slot(*character).map(|code| (*character, code)) + let code = if slot == FontFace::MathSymbol as usize { + crate::cmr10::math_symbol_slot(*character) + } else { + crate::cmr10::math_extension_slot(*character) + }; + code.map(|code| (*character, code)) }) .collect(); return Some((font, codes)); @@ -552,7 +571,9 @@ fn write_pdf( (metrics.width(*character) * 100 / 65_536) as i64 }); widths.push(width.to_string()); - let glyph = if slot == FontFace::MathSymbol as usize { + let glyph = if slot == FontFace::MathSymbol as usize + || slot == FontFace::MathExtension as usize + { font.name_for_code(code).map(|name| (code, name)) } else { by_code @@ -886,6 +907,23 @@ mod type1_pdf_tests { assert!(!text.contains("/BaseFont /CMR10"), "{text}"); } + #[test] + fn math_operators_embed_cmex10() { + let mut list = hello_list(); + list.items[0] = DisplayItem::Text { + x: 0, + y: 800_000, + size: 655_360, + text: "\u{2211}".to_string(), + font: FontFace::MathExtension, + }; + let pdf = write(&[list]); + let text = String::from_utf8_lossy(&pdf); + assert!(text.contains("/BaseFont /CMEX10"), "{text}"); + assert!(text.contains("/summationtext"), "{text}"); + assert!(!text.contains("/BaseFont /CMR10"), "{text}"); + } + #[test] fn math_symbols_embed_cmsy10() { let mut list = hello_list(); diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 28051f0..81cebc4 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -23,6 +23,8 @@ pub enum FontFace { MathItalic, /// Computer Modern math symbols (`cmsy10`), addressed by TeX slot. MathSymbol, + /// Computer Modern math extensions (`cmex10`), addressed by TeX slot. + MathExtension, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -1069,14 +1071,24 @@ impl Page { }); } MathAtom::BigOperator { name } => { - for (index, character) in name.chars().enumerate() { + if let Some(character) = math::big_operator_character(name) { list.push(DisplayItem::Text { - font: FontFace::Roman, - x: x + index as i64 * font.width(character), + font: FontFace::MathExtension, + x, y: baseline, size, text: character.to_string(), }); + } else { + for (index, character) in name.chars().enumerate() { + list.push(DisplayItem::Text { + font: FontFace::Roman, + x: x + index as i64 * font.width(character), + y: baseline, + size, + text: character.to_string(), + }); + } } } MathAtom::SizedDelimiter { delimiter, .. } => { diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 6dad928..571b8ba 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`). 540 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 542 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 9e22f1a..d86f559 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -131,8 +131,8 @@ 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`, with `cmmi10` and `cmsy10` glyphs embedded as Type1 outlines), `\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 | +| 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`, with `cmmi10`, `cmsy10` and `cmex10` glyphs embedded as Type1 outlines), `\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, `cmsy10` math symbols and `cmex10` big operators, 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 | @@ -365,9 +365,9 @@ M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row hei Math coverage includes fractions/roots, scripts, `\left...\right` with body-scaled delimiters, `\middle`, `\big`/`\Big`/`\bigg`/`\Bigg` and their `l`/`r` forms, control-sequence delimiters, accents (dot/check/breve/acute/grave/ring), `\text`/`\mathrm`, `\overbrace`/`\underbrace`, `\overset`/`\underset`, `\binom`, `\cancel`/`\bcancel`/`\xcancel`, `\bmod`/`\pmod`, fence symbols, `\operatorname*` and `\mathop` limits. -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. +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, `cmsy10` for math symbols and `cmex10` for big operators), 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 361 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 540 tests (361 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 363 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 542 tests (363 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