From cce656a407252ce658ba71db7b8b87a6502b6abc Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 24 Oct 2026 12:39:02 +0800 Subject: [PATCH] Lay out align and gather displays row by row --- README.md | 2 +- crates/texrra-tex-core/src/lib.rs | 46 +++++ crates/texrra-tex-core/src/math.rs | 207 ++++++++++++++++++++++ crates/texrra-tex-core/src/render.rs | 38 +++++ docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 6 +- src/route_d.rs | 247 +++++++++++++++++++++++++-- 7 files changed, 529 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 8fbf4c0..37e1cc0 100644 --- a/README.md +++ b/README.md @@ -467,7 +467,7 @@ from the font's MATH assembly parts. `\\left...\\right` target sizing follows the assignable TeX parameters `\\delimiterfactor` (default 901) and `\\delimitershortfall` (default 5pt), including local and global assignments. -In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. +In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Route-D integration can also be checked against a real TeX page: `cargo test -p texrra-tex-core --test route_d` includes `route_d_page_matches_pdftex_raster_geometry`, which renders the route-D PDF and a pdfTeX Letter page at the same scaled-point geometry, rasterizes both with `pdftoppm`, and compares ink line count plus left, right, and bottom edges. It is skipped when `pdflatex`/`pdftoppm` are unavailable. `route_d_multiline_bands_track_pdftex` extends that check to a wrapped paragraph: the pixel rows that carry ink form one band per TeX line, and every band top, bottom, left edge and (except for the last line, whose width follows the break point) right edge must land within a couple of pixels of the pdfTeX page. diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 047826b..939b821 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -6371,6 +6371,52 @@ mod tests { assert!(size > 655_360, "expected a larger glyph, got {size}"); } + #[test] + fn aligned_displays_share_their_alignment_points() { + let rows = vec![ + crate::math::AlignedRow::new( + vec![ + crate::math::MathAtom::Text("a".to_string()), + crate::math::MathAtom::Text("= b".to_string()), + ], + Some("(1)".to_string()), + ), + crate::math::AlignedRow::new( + vec![ + crate::math::MathAtom::Text("cc".to_string()), + crate::math::MathAtom::Text("= d".to_string()), + ], + Some("(2)".to_string()), + ), + ]; + let atom = crate::math::MathAtom::Aligned { + rows, + centered: false, + }; + 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 mut equals = Vec::new(); + let mut parens = Vec::new(); + for item in &list.items { + if let DisplayItem::Text { text, x, y, .. } = item { + if text == "=" { + equals.push((*x, *y)); + } else if text == "(" { + parens.push(*x); + } + } + } + assert_eq!(equals.len(), 2); + assert_eq!(equals[0].0, equals[1].0, "columns must share an x"); + assert!(equals[1].1 > equals[0].1, "rows must stack downward"); + assert_eq!(parens.len(), 2); + assert_eq!(parens[0], parens[1], "tags must share a right edge"); + } + #[test] fn middle_delimiters_paint_larger_than_the_base_glyph() { let atom = crate::math::parse_math( diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index 2f023cd..f05f01e 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -88,6 +88,11 @@ pub enum MathAtom { }, /// A `\middle` delimiter; TeX sizes it with the enclosing `\left`/`\right`. Middle(char), + /// Rows of an `align` (column-aligned) or `gather` (centred) display. + Aligned { + rows: Vec, + centered: bool, + }, StackLines(Vec), Stack { top: Box, @@ -116,6 +121,132 @@ pub enum MathAtom { }, } +/// One row of an `align`/`gather` display. +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct AlignedRow { + /// The cells between `&`; `gather` rows carry a single cell. + pub cells: Vec, + /// The equation number rendered at the row's right edge. + pub tag: Option, +} + +impl AlignedRow { + pub fn new(cells: Vec, tag: Option) -> Self { + Self { cells, tag } + } +} + +/// Geometry shared by the layout and painter of an `align`/`gather` display. +pub(crate) struct AlignedLayout { + pub boxes: Vec>, + pub column_widths: Vec, + pub column_starts: Vec, + pub tag_widths: Vec, + pub body_width: i64, + pub total_width: i64, + pub baselines: Vec, + pub first_height: i64, + pub height: i64, + pub depth: i64, +} + +pub(crate) fn layout_aligned( + rows: &[AlignedRow], + centered: bool, + font: &Cmr10Metrics, +) -> AlignedLayout { + if rows.is_empty() { + return AlignedLayout { + boxes: Vec::new(), + column_widths: Vec::new(), + column_starts: Vec::new(), + tag_widths: Vec::new(), + body_width: 0, + total_width: 0, + baselines: Vec::new(), + first_height: 0, + height: 0, + depth: 0, + }; + } + let boxes: Vec> = rows + .iter() + .map(|row| { + row.cells + .iter() + .map(|cell| layout_math(cell, font)) + .collect() + }) + .collect(); + let columns = boxes.iter().map(Vec::len).max().unwrap_or(0); + let mut column_widths = vec![0i64; columns]; + for row in &boxes { + for (index, cell) in row.iter().enumerate() { + column_widths[index] = column_widths[index].max(cell.width); + } + } + let mut column_starts = Vec::with_capacity(columns); + let mut pen = 0i64; + for width in &column_widths { + column_starts.push(pen); + pen += width; + } + let body_width = if centered { + boxes + .iter() + .flat_map(|row| row.iter()) + .map(|cell| cell.width) + .max() + .unwrap_or(0) + } else { + pen + }; + let tag_widths: Vec = rows + .iter() + .map(|row| { + row.tag + .as_ref() + .map(|tag| { + tag.chars() + .map(|character| Cmr10Metrics::Roman.width(character)) + .sum() + }) + .unwrap_or(0) + }) + .collect(); + let total_width = body_width.max(tag_widths.iter().copied().max().unwrap_or(0)); + let row_heights: Vec = boxes + .iter() + .map(|row| row.iter().map(|cell| cell.height).max().unwrap_or(0)) + .collect(); + let row_depths: Vec = boxes + .iter() + .map(|row| row.iter().map(|cell| cell.depth).max().unwrap_or(0)) + .collect(); + let mut baselines = vec![0i64; rows.len()]; + for index in 1..rows.len() { + let minimum = 12 * 65_536; + let touching = row_depths[index - 1] + row_heights[index] + 65_536; + baselines[index] = baselines[index - 1] + minimum.max(touching); + } + let first_height = row_heights.first().copied().unwrap_or(0); + let below = baselines.last().copied().unwrap_or(0) + row_depths.last().copied().unwrap_or(0); + let extent = first_height + below; + let axis = 2 * 65_536 + 32_768; + AlignedLayout { + boxes, + column_widths, + column_starts, + tag_widths, + body_width, + total_width, + baselines, + first_height, + height: extent / 2 + axis, + depth: (extent / 2 - axis).max(0), + } +} + fn fraction_bar_default() -> bool { true } @@ -579,6 +710,14 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { } } MathAtom::Middle(delimiter) => layout_math(&MathAtom::Symbol(*delimiter), font), + MathAtom::Aligned { rows, centered } => { + let layout = layout_aligned(rows, *centered, font); + MathBox { + width: layout.total_width, + height: layout.height, + depth: layout.depth, + } + } MathAtom::StackLines(rows) => { let boxes: Vec = rows.iter().map(|atom| layout_math(atom, font)).collect(); MathBox { @@ -1871,6 +2010,74 @@ mod tests { ); } + #[test] + fn aligned_rows_share_their_column_widths() { + let font = Cmr10Metrics::default(); + let rows = vec![ + AlignedRow::new( + vec![ + MathAtom::Text("a".to_string()), + MathAtom::Text("= x".to_string()), + ], + None, + ), + AlignedRow::new( + vec![ + MathAtom::Text("long".to_string()), + MathAtom::Text("= y".to_string()), + ], + None, + ), + ]; + let layout = layout_aligned(&rows, false, &font); + assert_eq!(layout.column_widths.len(), 2); + assert_eq!( + layout.column_widths[0], + layout_math(&MathAtom::Text("long".to_string()), &font).width + ); + assert_eq!(layout.body_width, layout.column_widths.iter().sum::()); + assert!(layout.baselines.len() == 2 && layout.baselines[1] > 0); + } + + #[test] + fn gather_rows_centre_their_cells() { + let font = Cmr10Metrics::default(); + let rows = vec![ + AlignedRow::new(vec![MathAtom::Text("a".to_string())], None), + AlignedRow::new(vec![MathAtom::Text("wide row".to_string())], None), + ]; + let layout = layout_aligned(&rows, true, &font); + assert_eq!( + layout.body_width, + layout_math(&MathAtom::Text("wide row".to_string()), &font).width + ); + assert_eq!(layout.column_widths.len(), 1); + } + + #[test] + fn aligned_rows_are_centred_on_the_math_axis() { + let font = Cmr10Metrics::default(); + let single = layout_math( + &MathAtom::Aligned { + rows: vec![AlignedRow::new(vec![MathAtom::Text("a".to_string())], None)], + centered: false, + }, + &font, + ); + let two = layout_math( + &MathAtom::Aligned { + rows: vec![ + AlignedRow::new(vec![MathAtom::Text("a".to_string())], None), + AlignedRow::new(vec![MathAtom::Text("b".to_string())], None), + ], + centered: false, + }, + &font, + ); + assert!(two.height > single.height); + assert!(two.depth > single.depth); + } + #[test] fn big_delimiters_allow_math_spaces() { let font = Cmr10Metrics::default(); diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 61da567..922455b 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -728,6 +728,44 @@ impl Page { cursor += width; } } + MathAtom::Aligned { rows, centered } => { + let layout = math::layout_aligned(rows, *centered, font); + let x0 = x + (layout.total_width - layout.body_width) / 2; + let first_baseline = baseline - layout.height + layout.first_height; + for (index, row) in rows.iter().enumerate() { + let row_baseline = first_baseline + layout.baselines[index]; + for (cell_index, cell) in row.cells.iter().enumerate() { + let cell_box = layout.boxes[index][cell_index]; + let cell_x = if *centered { + x0 + (layout.body_width - cell_box.width) / 2 + } else { + let start = layout.column_starts[cell_index]; + let width = layout.column_widths[cell_index]; + if cell_index % 2 == 0 { + x0 + start + width - cell_box.width + } else { + x0 + start + } + }; + Self::paint_math(cell, font, cell_x, row_baseline, size, list); + } + if let Some(tag) = &row.tag { + let tag_width = layout.tag_widths[index]; + let mut pen = x + layout.total_width - tag_width; + for character in tag.chars() { + let width = Cmr10Metrics::Roman.width(character); + list.push(DisplayItem::Text { + font: FontFace::Roman, + x: pen, + y: row_baseline, + size, + text: character.to_string(), + }); + pen += width; + } + } + } + } MathAtom::Tagged { body, tag } => { let body_box = math::layout_math(body, font); Self::paint_math(body, font, x, baseline, size, list); diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 65dc90a..01443a8 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`). 560 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 568 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 d756165..89159b4 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`, 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 and `\\mathcal` onto the cmsy10 calligraphic capitals; `\mathfrak` maps onto the bundled eufm10 Fraktur letters (embedded as Type1 outlines); infix fractions `\over`, `\atop`, `\choose`, `\brace`, `\brack` and their `withdelims` forms build fractions from the current row, with the bar only for the `\over` forms; `\middle` delimiters are sized with their enclosing `\left`/`\right` group and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size | +| 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 approximation of TeX's `\split` behaviour; `align`/`align*` displays share column widths and number each row, while `gather`/`gather*` centre every row); 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 and `\\mathcal` onto the cmsy10 calligraphic capitals; `\mathfrak` maps onto the bundled eufm10 Fraktur letters (embedded as Type1 outlines); infix fractions `\over`, `\atop`, `\choose`, `\brace`, `\brack` and their `withdelims` forms build fractions from the current row, with the bar only for the `\over` forms; `\middle` delimiters are sized with their enclosing `\left`/`\right` group and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size | | 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 | @@ -330,7 +330,7 @@ for a later overlaid slash. | M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing with default and custom `\sfcode`/`\frenchspacing`, explicit `\spaceskip`/`\xspaceskip`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfTeX oracle matrix 90-240pt plus register, geometry and vertical-glue fixtures | | M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for documents made of box/glue/penalty/mark vertical material (a unit may span pages), while in-text floats flow inline through the page builder; paged layouts replay edits from the edited page (insertions, bottom floats and interpreted `\output` force a full rebuild), and insertions are placed through the builder too; `\output` interpreted for a `\shipout`/`\ifdim`/`\ifnum` register subset over page globals and `\outputpenalty`/`\pageno`/`\deadcycles` | | M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter | -| M4 math | partial | atoms, scripts, fractions (including infix `\over`/`\atop`/`\choose`), roots, delimiters, accents, operators, classes, braces, boxed, negated, math alphabets (incl. `\mathcal`, `\mathbb` and `\mathfrak`); no math painter/shrink wrapping | +| M4 math | partial | atoms, scripts, fractions (including infix `\over`/`\atop`/`\choose`), roots, delimiters, accents, operators, classes, braces, boxed, negated, math alphabets (incl. `\mathcal`, `\mathbb` and `\mathfrak`), `align`/`gather` rows with per-row tags; no math painter/shrink wrapping | | M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style; route-D PDFs embed Knuth's Computer Modern Type1 programs (cmr10/cmbx10/cmti10/cmbxti10/cmtt10/cmss10) as `/Subtype /Type1` fonts with `/FontFile` (`Length1/2/3`), `/Encoding /Differences` and TFM `/Widths`, falling back per face to Liberation when the program does not encode every character | | M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; class/package execution absent | | M7 incremental integration | partial | route-D preview/PDF/edit endpoints plus opt-in `?engine=route-d` project preview, content-based page hashes and section/emphasis/display-math/itemize/enumerate/description/quote/center/flushright mapping; editor toggle in `texrra-web`; inline math pending | @@ -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, `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 381 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 560 tests (381 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 385 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 568 tests (385 route-D unit, 37 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 diff --git a/src/route_d.rs b/src/route_d.rs index bb3a9c6..37d6a81 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::{MathAtom, parse_math, split_math_lines}; +use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines}; use texrra_tex_core::pdf::{ PageOrigin, display_lists_to_pdf_with_cm_type1, display_lists_to_pdf_with_paper, }; @@ -650,6 +650,18 @@ struct SourceParagraph { /// Number of the equation environment this block came from. equation_number: Option, equation_tag: Option, + /// Rows of an `align`/`gather` environment. + equation_rows: Vec, + /// Whether the rows are centred (`gather`) rather than column-aligned. + align_centered: bool, +} + +/// One row of an `align`/`gather` environment. +#[derive(Clone, PartialEq, Eq)] +struct EquationRow { + text: String, + number: Option, + tag: Option, } /// Recognise an explicit vertical skip command standing alone between @@ -716,6 +728,8 @@ fn paragraphs(source: &str) -> Result, String> { page_break: pending_break, equation_number: None, equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, }); pending = (0, 0, 0); pending_break = false; @@ -755,11 +769,35 @@ fn command_body<'a>(text: &'a str, command: &str) -> Option<&'a str> { /// Assign equation numbers in source order and substitute label references. fn resolve_equation_numbers(blocks: &mut [SourceParagraph]) { let mut number = 0; - let mut labels: Vec<(String, u32)> = Vec::new(); + let mut labels: Vec<(String, String)> = Vec::new(); for block in blocks.iter_mut() { if !block.math { continue; } + if !block.equation_rows.is_empty() { + for row in block.equation_rows.iter_mut() { + if let Some(tag) = take_braced_argument(&mut row.text, "\\tag") { + row.tag = Some(tag); + row.number = None; + } + if row.text.contains("\\notag") || row.text.contains("\\nonumber") { + row.number = None; + } + row.text = row.text.replace("\\notag", "").replace("\\nonumber", ""); + let mut value = row.tag.clone(); + if row.number.is_some() { + number += 1; + row.number = Some(number); + value = Some(number.to_string()); + } + if let Some(value) = value { + for label in take_labels(&mut row.text) { + labels.push((label, value.clone())); + } + } + } + continue; + } if let Some(tag) = take_braced_argument(&mut block.text, "\\tag") { block.equation_tag = Some(tag); block.equation_number = None; @@ -773,16 +811,8 @@ fn resolve_equation_numbers(blocks: &mut [SourceParagraph]) { } number += 1; block.equation_number = Some(number); - loop { - let Some(start) = block.text.find("\\label{") else { - break; - }; - let Some(end) = block.text[start..].find('}') else { - break; - }; - let label = block.text[start + 7..start + end].trim().to_string(); - labels.push((label, number)); - block.text.replace_range(start..start + end + 1, ""); + for label in take_labels(&mut block.text) { + labels.push((label, number.to_string())); } } for block in blocks.iter_mut() { @@ -792,11 +822,33 @@ fn resolve_equation_numbers(blocks: &mut [SourceParagraph]) { block.text = block .text .replace(&eqref, &format!("({value})")) - .replace(&reference, &value.to_string()); + .replace(&reference, value); + for row in block.equation_rows.iter_mut() { + row.text = row + .text + .replace(&eqref, &format!("({value})")) + .replace(&reference, value); + } } } } +fn take_labels(text: &mut String) -> Vec { + let mut labels = Vec::new(); + loop { + let Some(start) = text.find("\\label{") else { + break; + }; + let Some(end) = text[start..].find('}') else { + break; + }; + let label = text[start + 7..start + end].trim().to_string(); + labels.push(label); + text.replace_range(start..start + end + 1, ""); + } + labels +} + fn parse_blocks_raw(raw: &str) -> Vec { for (environment, numbered) in [("itemize", false), ("enumerate", true)] { let begin = format!("\\begin{{{environment}}}"); @@ -833,6 +885,8 @@ fn parse_blocks_raw(raw: &str) -> Vec { page_break: false, equation_number: None, equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, } }) .collect(); @@ -860,6 +914,8 @@ fn parse_blocks_raw(raw: &str) -> Vec { page_break: false, equation_number: None, equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, }]; } } @@ -896,6 +952,8 @@ fn parse_blocks_raw(raw: &str) -> Vec { page_break: false, equation_number: None, equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, } }) .collect(); @@ -1217,6 +1275,47 @@ fn parse_runs( } fn parse_paragraph(raw: &str) -> SourceParagraph { + for (environment, starred, centered) in [ + ("align", false, false), + ("align*", true, false), + ("gather", false, true), + ("gather*", true, true), + ] { + let begin = format!("\\begin{{{environment}}}"); + let finish = format!("\\end{{{environment}}}"); + if let Some(inner) = raw + .strip_prefix(&begin) + .and_then(|text| text.strip_suffix(&finish)) + { + let rows: Vec = inner + .split("\\\\") + .map(str::trim) + .filter(|row| !row.is_empty()) + .map(|row| EquationRow { + text: row.to_string(), + number: if starred { None } else { Some(0) }, + tag: None, + }) + .collect(); + return SourceParagraph { + text: inner.trim().to_string(), + font: ParagraphFont::Roman, + line_height: 12, + math: true, + left_skip: 0, + centered: false, + right_aligned: false, + space_before: 0, + space_stretch: 0, + space_shrink: 0, + page_break: false, + equation_number: None, + equation_tag: None, + equation_rows: rows, + align_centered: centered, + }; + } + } if let Some((font, body)) = nfss_font(raw, ParagraphFont::Roman) { return SourceParagraph { text: body, @@ -1232,6 +1331,8 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { page_break: false, equation_number: None, equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, }; } if let Some(inner) = raw @@ -1252,6 +1353,8 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { page_break: false, equation_number: Some(0), equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, }; } if let Some(inner) = raw @@ -1272,6 +1375,8 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { page_break: false, equation_number: None, equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, }; } if let Some(math) = raw @@ -1296,6 +1401,8 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { page_break: false, equation_number: None, equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, }; } let candidates = [ @@ -1321,6 +1428,8 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { page_break: false, equation_number: None, equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, }; } } @@ -1338,9 +1447,23 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { page_break: false, equation_number: None, equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, } } +/// Wrap a row cell with empty Ord atoms so relation spacing shows up at the +/// column boundaries, the way amsmath aligns relation columns. +fn aligned_cell(source: &str) -> MathAtom { + let mut atoms = vec![MathAtom::Row(Vec::new())]; + match parse_math(source.trim()) { + MathAtom::Row(inner) => atoms.extend(inner), + other => atoms.push(other), + } + atoms.push(MathAtom::Row(Vec::new())); + MathAtom::Row(atoms) +} + fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document { let units = paragraphs .iter() @@ -1363,7 +1486,30 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do } if paragraph.math { let font = Cmr10Metrics::Math; - let atom = parse_math(¶graph.text); + let atom = if paragraph.equation_rows.is_empty() { + parse_math(¶graph.text) + } else { + let rows: Vec = paragraph + .equation_rows + .iter() + .map(|row| { + let cells: Vec = if paragraph.align_centered { + vec![aligned_cell(&row.text)] + } else { + row.text.split('&').map(aligned_cell).collect() + }; + let tag = row + .tag + .clone() + .or_else(|| row.number.map(|number| format!("({number})"))); + AlignedRow::new(cells, tag) + }) + .collect(); + MathAtom::Aligned { + rows, + centered: paragraph.align_centered, + } + }; let tag = paragraph.equation_tag.clone().or_else(|| { paragraph .equation_number @@ -1927,6 +2073,79 @@ d ); } + #[test] + fn align_rows_are_numbered_and_tagged() { + let source = r"\begin{align} +a &= b \\ +c &= d \tag{C} \\ +e &= f \notag \\ +g &= h +\end{align}"; + let blocks = paragraphs(source).expect("paragraphs"); + assert_eq!(blocks.len(), 1); + let rows = &blocks[0].equation_rows; + assert_eq!(rows.len(), 4); + let numbers: Vec> = rows.iter().map(|row| row.number).collect(); + assert_eq!(numbers, vec![Some(1), None, None, Some(2)]); + assert_eq!(rows[1].tag.as_deref(), Some("C")); + assert!(rows[0].text.contains('&'), "cells keep their separator"); + assert!( + rows.iter() + .all(|row| !row.text.contains("\\tag") && !row.text.contains("\\notag")), + "tag commands are stripped from the rows" + ); + } + + #[test] + fn align_labels_resolve_from_their_rows() { + let source = r"\begin{align} +a &= b \label{eq:a} \\ +c &= d +\end{align} + +See \eqref{eq:a}."; + let blocks = paragraphs(source).expect("paragraphs"); + assert_eq!(blocks[0].equation_rows[0].number, Some(1)); + let reference = blocks + .iter() + .find(|block| block.text.starts_with("See")) + .expect("reference paragraph"); + assert_eq!(reference.text, "See (1)."); + assert!( + !blocks[0].equation_rows[0].text.contains("\\label"), + "labels are stripped from aligned rows" + ); + } + + #[test] + fn gather_centres_its_single_cells() { + let source = r"\begin{gather*} +x \\ +y +\end{gather*}"; + let blocks = paragraphs(source).expect("paragraphs"); + assert!(blocks[0].align_centered); + assert_eq!(blocks[0].equation_rows.len(), 2); + assert!( + blocks[0] + .equation_rows + .iter() + .all(|row| !row.text.contains('&') && row.number.is_none()) + ); + } + + #[test] + fn align_displays_draw_each_row_with_its_number() { + let source = r"\begin{align} +a &= b \\ +c &= d +\end{align}"; + let json = preview_json(source).expect("preview"); + assert!(json.contains(">1"), "first row number: {json}"); + assert!(json.contains(">2"), "second row number: {json}"); + assert!(json.contains(">="), "relation glyph"); + } + #[test] fn numbered_equation_renders_its_tag() { let json = preview_json("\\begin{equation}\nx^2\n\\end{equation}").expect("preview");