From c9ad1e209a0fe607013f80f8f8851dd597571e9c Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 24 Oct 2026 01:26:29 +0800 Subject: [PATCH] Split wide display formulas into lines --- README.md | 3 ++- crates/texrra-tex-core/src/lib.rs | 43 ++++++++++++++++++++++++++++++ crates/texrra-tex-core/src/math.rs | 30 +++++++++++++++++++++ docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 4 +-- src/route_d.rs | 31 ++++++++++++++++----- 6 files changed, 103 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 4720857..e55d872 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,8 @@ PDF-backend no-ops, while fancyhdr's page decorations are painted natively. Figure and table captions are numbered (`Figure 1: ...`, `Table 1: ...`), and `\ref` to a figure/table label resolves to that number. Display math that is -wider than the text column is scaled to fit the column. Latin text is hyphenated +wider than the text column is scaled to fit the column; route-D instead +splits wide display formulas at top-level operators. Latin text is hyphenated with plain TeX's English patterns (two letters before and three after the hyphen) through the Knuth–Plass line breaker; math and CJK text are not hyphenated. diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index fda602e..5604cd7 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -1267,6 +1267,27 @@ impl Unit { } /// Build a unit from a math atom using CMR10 metrics. + /// One vertical unit holding a display formula split into lines. + pub fn math_lines( + id: UnitId, + lines: &[crate::math::MathAtom], + font: &crate::cmr10::Cmr10Metrics, + ) -> Self { + let items = lines + .iter() + .map(|atom| { + let math_box = crate::math::layout_math(atom, font); + VerticalItem::Math { + atom: atom.clone(), + width: math_box.width, + height: math_box.height, + depth: math_box.depth, + } + }) + .collect(); + Self::vertical(id, items) + } + pub fn math( id: UnitId, atom: crate::math::MathAtom, @@ -7325,6 +7346,28 @@ b & 2 \\ assert!(!chunk_text[0].iter().any(|text| text == "F1")); } + #[test] + fn display_math_splits_at_operators() { + let atom = crate::math::parse_math("a + b + c + d + e + f + g + h + i + j"); + let font = Cmr10Metrics::default(); + let lines = crate::math::split_math_lines(&atom, &font, 60 * 65_536); + assert!(lines.len() > 1, "lines={}", lines.len()); + let atoms = |atom: &crate::math::MathAtom| match atom { + crate::math::MathAtom::Row(items) => items.len(), + _ => 1, + }; + let total: usize = lines.iter().map(atoms).sum(); + assert_eq!(total, atoms(&atom)); + for line in &lines { + let width = crate::math::layout_math(line, &font).width; + let single = match line { + crate::math::MathAtom::Row(items) => items.len() <= 1, + _ => true, + }; + assert!(single || width <= 60 * 65_536, "width={width}"); + } + } + #[test] fn checkpoint_round_trips_through_serde() { let engine = Engine::layout(&document()); diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index 51dc646..61b54d1 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -170,6 +170,36 @@ fn scaled(value: i64, factor: f64) -> i64 { (value as f64 * factor).round() as i64 } +/// Split a display formula into lines that fit `max_width`. +/// +/// TeX itself never breaks display math automatically; this mirrors the +/// explicit `\\split`/`align` behaviour by breaking after a top-level +/// binary or relation operator once the line would overflow. +pub fn split_math_lines(atom: &MathAtom, font: &Cmr10Metrics, max_width: i64) -> Vec { + let atoms = match atom { + MathAtom::Row(items) => items.clone(), + other => vec![other.clone()], + }; + if layout_math(atom, font).width <= max_width { + return vec![atom.clone()]; + } + let mut lines: Vec> = Vec::new(); + let mut current: Vec = Vec::new(); + for item in atoms { + let mut candidate = current.clone(); + candidate.push(item.clone()); + let candidate_width = layout_math(&MathAtom::Row(candidate.clone()), font).width; + if !current.is_empty() && candidate_width > max_width { + lines.push(std::mem::take(&mut current)); + } + current.push(item); + } + if !current.is_empty() { + lines.push(current); + } + lines.into_iter().map(MathAtom::Row).collect() +} + fn atom_class(atom: &MathAtom) -> MathClass { match atom { MathAtom::Symbol(character) => math_class(*character), diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 6faf136..d616d17 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`). 490 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 492 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 7d91321..0278bd8 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 CMR10 metrics, delimiter scaling, accents and a display-list painter; no CMEX size variants or TeX math spacing classes yet | +| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, 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); no CMEX size variants or TeX math spacing classes yet | | 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 331 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 490 tests (331 route-D unit, 14 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 332 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 492 tests (332 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 diff --git a/src/route_d.rs b/src/route_d.rs index bac3cde..b48f1b9 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -10,7 +10,7 @@ use std::fmt::Write as _; use std::sync::{Mutex, OnceLock}; use texrra_tex_core::cmr10::Cmr10Metrics; -use texrra_tex_core::math::parse_math; +use texrra_tex_core::math::{parse_math, split_math_lines}; use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_paper}; use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit}; @@ -925,11 +925,10 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do } } if paragraph.math { - let mut unit = Unit::math( - index as u64, - parse_math(¶graph.text), - &Cmr10Metrics::default(), - ); + let font = Cmr10Metrics::default(); + let atom = parse_math(¶graph.text); + let lines = split_math_lines(&atom, &font, 480 * SCALE); + let mut unit = Unit::math_lines(index as u64, &lines, &font); unit.space_before = paragraph.space_before; unit.space_stretch = paragraph.space_stretch; unit.space_shrink = paragraph.space_shrink; @@ -1066,6 +1065,26 @@ fn escape_json(value: &str) -> String { mod tests { use super::*; + #[test] + fn display_math_is_split_to_the_measure() { + let mut formula = String::from("$$"); + for index in 0..80 { + if index > 0 { + formula.push_str(" + "); + } + formula.push('x'); + } + formula.push_str(" = z$$"); + let (body, geometry) = geometry_and_body(&formula); + let paragraphs = paragraphs(&body).unwrap(); + let document = build_document(¶graphs, &geometry); + assert!( + document.units[0].items.len() > 1, + "items={}", + document.units[0].items.len() + ); + } + #[test] fn engine_template_keeps_paragraph_columns() { assert_eq!(engine_template("{|l|c|p{3cm}|}"), "lcp{3cm}");