diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index f2a2f77..4fa04fe 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -221,6 +221,46 @@ fn delimiter_width(delimiter: char, font: &Cmr10Metrics) -> i64 { /// TeX grows delimiters with the enclosed formula; this is a simple 1x-3x /// approximation of that rule. +/// Pick the delimiter glyph TeX would use for a body of `delta` extent. +/// +/// The ordinary glyph is used while it is tall enough; otherwise the smallest +/// CMEX size variant whose extent covers the requirement wins, and oversized +/// bodies scale the largest variant further. +pub(crate) fn select_delimiter(font: Cmr10Metrics, delimiter: char, delta: i64) -> (i64, i64, i64) { + if delimiter == '.' { + return (0, 0, 0); + } + let base = ( + font.width(delimiter), + font.height(delimiter), + font.depth(delimiter), + ); + let need = ((delta * 901) / 1000).max(delta - 5 * 65_536).max(0); + if base.1 + base.2 >= need && base.1 + base.2 > 0 { + return base; + } + for size in 1..=4 { + if let Some(metrics) = cmex_delimiter(delimiter, size) { + if metrics.1 + metrics.2 >= need { + return metrics; + } + } + } + if let Some(metrics) = cmex_delimiter(delimiter, 4) { + let extent = metrics.1 + metrics.2; + if extent > 0 && need > extent { + let factor = need as f64 / extent as f64; + return ( + (metrics.0 as f64 * factor) as i64, + (metrics.1 as f64 * factor) as i64, + (metrics.2 as f64 * factor) as i64, + ); + } + return metrics; + } + base +} + pub fn delimiter_scale(body: &MathBox) -> f64 { let extent = (body.height + body.depth) as f64 / 65_536.0; (extent / 9.0).clamp(1.0, 3.0) @@ -309,13 +349,13 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { }, MathAtom::Delimited { left, right, body } => { let body_box = layout_math(body, font); - let scale = delimiter_scale(&body_box); + let delta = body_box.height + body_box.depth; + let left_box = select_delimiter(*font, *left, delta); + let right_box = select_delimiter(*font, *right, delta); MathBox { - width: ((delimiter_width(*left, font) + delimiter_width(*right, font)) as f64 - * scale) as i64 - + body_box.width, - height: body_box.height + (2 * 65_536) * scale as i64, - depth: body_box.depth + (2 * 65_536) * scale as i64, + width: left_box.0 + body_box.width + right_box.0, + height: body_box.height.max(left_box.1).max(right_box.1), + depth: body_box.depth.max(left_box.2).max(right_box.2), } } MathAtom::Accent { base, .. } => { @@ -1892,3 +1932,47 @@ mod cmex_size_tests { assert!(bigg.height > big.height); } } + +#[cfg(test)] +mod delimiter_selection_tests { + use super::*; + use crate::cmr10::{Cmr10Metrics, cmex_delimiter}; + + #[test] + fn selector_keeps_the_ordinary_glyph_for_small_bodies() { + let font = Cmr10Metrics::Math; + let small = select_delimiter(font, '(', 7 * 65_536); + assert_eq!(small.0, font.width('(')); + assert_eq!(small.1, font.height('(')); + assert_eq!(small.2, font.depth('(')); + let empty = select_delimiter(font, '.', 30 * 65_536); + assert_eq!(empty, (0, 0, 0)); + } + + #[test] + fn selector_grows_to_cmex_variants_for_tall_bodies() { + let font = Cmr10Metrics::Math; + let tall = select_delimiter(font, '(', 30 * 65_536); + let bigg_bigg = cmex_delimiter('(', 4).expect("cmex Bigg paren"); + assert_eq!(tall, bigg_bigg); + let medium = select_delimiter(font, '(', 15 * 65_536); + let mut matched = false; + for size in 1..=4 { + if let Some(metrics) = cmex_delimiter('(', size) { + if metrics == medium { + matched = true; + } + } + } + assert!(matched, "medium selection {medium:?} is not a cmex variant"); + } + + #[test] + fn delimited_layout_uses_selected_delimiters() { + let font = Cmr10Metrics::Math; + let plain = layout_math(&parse_math(r"\left(a\right)"), &font); + let tall = layout_math(&parse_math(r"\left(\frac{a}{b}\right)"), &font); + assert!(tall.height + tall.depth > plain.height + plain.depth); + assert!(tall.width > plain.width); + } +} diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index cfe2f54..407e3eb 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -762,26 +762,40 @@ impl Page { } MathAtom::Delimited { left, right, body } => { let body_box = math::layout_math(body, font); - let scale = math::delimiter_scale(&body_box); - let delimiter_size = (size as f64 * scale) as i64; - let left_width = (font.width(*left) as f64 * scale) as i64; - let delimiter_shift = ((delimiter_size - size) as f64 * 0.35) as i64; + let delta = body_box.height + body_box.depth; + let left_box = math::select_delimiter(*font, *left, delta); + let right_box = math::select_delimiter(*font, *right, delta); + let left_width = left_box.0; + let base_extent = |delimiter: char| font.height(delimiter) + font.depth(delimiter); + let scaled_size = |extent: (i64, i64, i64), delimiter: char| -> (i64, i64) { + let base = base_extent(delimiter); + let scale = if base > 0 { + (extent.1 + extent.2) as f64 / base as f64 + } else { + 1.0 + }; + let glyph_size = (size as f64 * scale) as i64; + let shift = ((glyph_size - size) as f64 * 0.35) as i64; + (glyph_size, shift) + }; if *left != '.' { + let (left_size, left_shift) = scaled_size(left_box, *left); list.push(DisplayItem::Text { font: FontFace::Roman, x, - y: baseline + delimiter_shift, - size: delimiter_size, + y: baseline + left_shift, + size: left_size, text: left.to_string(), }); } Self::paint_math(body, font, x + left_width, baseline, size, list); if *right != '.' { + let (right_size, right_shift) = scaled_size(right_box, *right); list.push(DisplayItem::Text { font: FontFace::Roman, x: x + left_width + body_box.width, - y: baseline + delimiter_shift, - size: delimiter_size, + y: baseline + right_shift, + size: right_size, text: right.to_string(), }); } diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index c43a89e..9960e62 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`). 499 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 502 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 00c3740..021138a 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`), 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); 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`; no full 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 339 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 499 tests (339 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 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. ### M0 incremental demo