From 6305f059ac1b530f3a6979667e54443e32c4f443 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 02:45:11 +0800 Subject: [PATCH] Shrink overfull final lines and widen the oracle matrix --- README.md | 2 +- crates/texrra-tex-core/src/paragraph.rs | 89 ++++++++++++++++--------- crates/texrra-tex-core/tests/oracle.rs | 26 ++++++-- docs/ROUTE_D_PLAN.md | 11 ++- docs/TEX_CORE.md | 20 +++--- 5 files changed, 98 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 26da42f..0efe07e 100644 --- a/README.md +++ b/README.md @@ -576,7 +576,7 @@ boxes/glue, a simple page builder, serializable checkpoints and a page-local edit demo. M1 adds the horizontal box/glue/penalty model, an item-stream Knuth-Plass-style paragraph builder, CMR10 metrics extracted from `cmr10.tfm`, and a matching pdfTeX line-break fixture. Paragraphs are split at line boundaries when they cross a page, and the pdfLaTeX oracle covers the -100-240pt measure matrix plus register, `\hangindent`/`\parshape`, +90-240pt measure matrix plus register, `\hangindent`/`\parshape`, `\parfillskip`, sentence-spacing with custom `\sfcode`, `\spaceskip`/`\xspaceskip`, `\looseness` and vertical-glue fixtures. Overflowing insertion material is split at item boundaries, with the tail held over to the diff --git a/crates/texrra-tex-core/src/paragraph.rs b/crates/texrra-tex-core/src/paragraph.rs index 6883eeb..b736235 100755 --- a/crates/texrra-tex-core/src/paragraph.rs +++ b/crates/texrra-tex-core/src/paragraph.rs @@ -799,15 +799,17 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra } else { 0 }; - if !is_last || !style.par_fillskip_fil { - natural += fillskip; - stretch += fillskip_stretch; - // TeX can stretch normal glue past its nominal stretch (badness - // simply exceeds 100), but it never shrinks past the declared - // shrink: an overfull line keeps its overflow instead of pulling - // glue beyond its limits. - let delta = (target - natural).max(-shrink); - if delta > 0 && stretch > 0 { + natural += fillskip; + stretch += fillskip_stretch; + // TeX can stretch normal glue past its nominal stretch (badness + // simply exceeds 100), but it never shrinks past the declared + // shrink: an overfull line keeps its overflow instead of pulling + // glue beyond its limits. A final line with a `fil` parfillskip only + // shrinks: the infinite stretch absorbs any shortfall, so only a + // line wider than the measure adjusts its finite glue. + let delta = (target - natural).max(-shrink); + if delta > 0 { + if !is_last || !style.par_fillskip_fil { let mut remaining = delta; for item in &mut line { if let HorizontalItem::Glue { @@ -830,30 +832,30 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra { *width += remaining; } - } else if delta < 0 && shrink > 0 { - let mut remaining = delta; - for item in &mut line { - if let HorizontalItem::Glue { - width, - shrink: shrink_amount, - .. - } = item - && *shrink_amount > 0 - { - let share = delta * *shrink_amount / shrink; - *width += share; - remaining -= share; - } - } - if remaining != 0 - && let Some(HorizontalItem::Glue { width, .. }) = line - .iter_mut() - .rev() - .find(|item| matches!(item, HorizontalItem::Glue { .. })) + } + } else if delta < 0 { + let mut remaining = delta; + for item in &mut line { + if let HorizontalItem::Glue { + width, + shrink: shrink_amount, + .. + } = item + && *shrink_amount > 0 { - *width += remaining; + let share = delta * *shrink_amount / shrink; + *width += share; + remaining -= share; } } + if remaining != 0 + && let Some(HorizontalItem::Glue { width, .. }) = line + .iter_mut() + .rev() + .find(|item| matches!(item, HorizontalItem::Glue { .. })) + { + *width += remaining; + } } let width: i64 = line .iter() @@ -1181,6 +1183,33 @@ mod tests { ); } + #[test] + fn overfull_final_line_shrinks_its_glue() { + let font = crate::cmr10::Cmr10Metrics::Roman; + let style = ParagraphStyle { + line_width: 23 * 65_536, + par_indent: 0, + emergencystretch: 0, + line_height: 12 * 65_536, + ..ParagraphStyle::default() + }; + let paragraph = layout_paragraph_with_font("aa bb", &style, &font); + assert_eq!(paragraph.line_count(), 1); + let glue = paragraph.lines[0].iter().find_map(|item| match item { + HorizontalItem::Glue { width, .. } => Some(*width), + _ => None, + }); + let glue = glue.expect("the final line must keep its interword glue"); + assert!( + glue < font.space(), + "an overfull final line must shrink its glue" + ); + assert!( + glue >= font.space() - font.shrink(), + "the final line must not shrink past the declared shrink" + ); + } + #[test] fn words_break_at_glue_and_lines_are_justified() { let style = ParagraphStyle { diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index 8bab6cf..2a9488f 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -406,12 +406,30 @@ fn paragraph_breaks_match_pdftex_at_180pt() { compare_fixture(WORDS, 180); } -/// Several measures in one run: 100/120pt exercise hyphenated and overfull -/// breaks, 150pt needs TeX's final-pass overfull box, and 180/200/240pt are -/// ordinary tolerance solutions. +/// Several measures in one run: 90/100/110/120pt exercise hyphenated and +/// overfull breaks, 130/150/160pt need TeX's final-pass overfull box, and +/// 180/200/220/240pt are ordinary tolerance solutions. #[test] fn paragraph_breaks_match_pdftex_across_measures() { - for width in [100u32, 120, 150, 180, 200, 240] { + for width in [90u32, 100, 110, 120, 130, 150, 160, 180, 200, 220, 240] { compare_fixture(WORDS, width); } } + +/// `\emergencystretch` gives the final pass extra stretch, so TeX can avoid +/// an overfull line and break the paragraph into more lines. +#[test] +fn emergencystretch_matches_pdftex() { + compare_fixture_with(WORDS, 150, "\\emergencystretch=10pt ", |style| { + style.emergencystretch = 10 * 65_536; + }); +} + +/// `\leftskip` narrows the measure and shifts every line, so line starts and +/// breaks must match pdfLaTeX. +#[test] +fn leftskip_matches_pdftex() { + compare_fixture_with(WORDS, 150, "\\leftskip=20pt ", |style| { + style.left_skip = 20 * 65_536; + }); +} diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 0c7bc40..df6e12b 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`). 319 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 333 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -176,10 +176,9 @@ and the final-pass fallback did not model TeX's artificial demerits. The breaker now uses TeX Live's `hyph-en-us` patterns and exceptions with `\lefthyphenmin=2`/`\righthyphenmin=3`, stretches normal glue past its nominal stretch while clamping shrink at the declared limit, and falls back to -the longest prefix within `\tolerance` or the first overflowing prefix. The -oracle compares 100, 120, 150, 180, 200 and 240pt and all six match pdfLaTeX -word for word within 0.05pt; the narrow measures exercise hyphenated and -overfull breaks. Register fixtures pin `\pretolerance=10000` (pass 0 stops +the longest prefix within `\tolerance` or the first overflowing prefix. The oracle compares an eleven-measure matrix (90-240pt) and all fixtures match +pdfLaTeX word for word within 0.05pt; the narrow measures exercise hyphenated +and overfull breaks, and a final line held at its declared shrink limit. Register fixtures pin `\pretolerance=10000` (pass 0 stops before hyphenation) and `\hyphenpenalty=10000` (hyphenation illegal, first-fit overfull lines). @@ -222,7 +221,7 @@ top of a page (see `Paragraph::split_at`). Still open: generic `fil`/`fill` glue orders, `\prevgraf`, explicit `\vskip` classes (`\smallskip` and friends), -double/final hyphen demerit oracle fixtures, and more width fixtures. +double/final hyphen demerit oracle fixtures. ### P2 — Vertical list, page builder, `\output` (L2) diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index fb521b6..11618ea 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -80,11 +80,11 @@ fields mirroring `\pretolerance`, `\tolerance`, `\hyphenpenalty` and plus document-level `\hyphenation` exceptions; `\hyphenpenalty` at 10000 or more disables hyphenation and switches the fallback to a first-fit scan. -`tests/oracle.rs` compares a matrix of measures (100, 120, 150, 180, 200 and +`tests/oracle.rs` compares a matrix of measures (90, 100, 110, 120, 130, 150, 160, 180, 200, 220 and 240pt) against pdfLaTeX: every fixture matches word for word and within 0.05pt -horizontally. The narrow measures exercise hyphenated and overfull breaks, -150pt the final-pass overfull box, and 180-240pt ordinary tolerance -solutions. Two further fixtures pin register behaviour at 120pt: +horizontally. The narrowest measures exercise hyphenated and overfull breaks (including a +final line held at its declared shrink limit), 130-160pt the final-pass +overfull box, and 180-240pt ordinary tolerance solutions. Two further fixtures pin register behaviour at 120pt: `\pretolerance=10000` stops before hyphenation and `\hyphenpenalty=10000` inhibits it, leaving the overfull first-fit lines TeX produces. A 120pt fixture with `\hangindent=20pt \hangafter=1` checks every line origin @@ -94,7 +94,9 @@ justified like any other line (the default `0pt plus 1fil` leaves it short). Two 150pt fixtures pin explicit interword glue: `\spaceskip` replaces the font glue (width kept, stretch/shrink following the space factor) and `\xspaceskip` is used verbatim once the factor reaches 2000; neither adds -`\fontdimen7`. `route_d_multiline_bands_track_pdftex` rasterizes the same +`\fontdimen7`. A 150pt fixture pins `\emergencystretch=10pt` (three lines instead of an +overfull pair) and another pins `\leftskip=20pt` (narrowed measure and +shifted origins). `route_d_multiline_bands_track_pdftex` rasterizes the same paragraph in both engines and compares ink bands, covering baseline placement and justification. @@ -113,7 +115,7 @@ and justification. | Milestone | Content | Acceptance | | --- | --- | --- | | M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 | -| 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`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 100-240pt plus register, geometry, `\sfcode` and vertical-glue fixtures; generic fil glue and `\prevgraf` next | +| 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`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode` and vertical-glue fixtures; generic fil glue and `\prevgraf` next | | 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, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, while the scrolling builder remains the default; interpreted `\output` next | | 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; no booktabs/longtable parity 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; no CMEX size variants or TeX math spacing classes yet | @@ -151,7 +153,7 @@ and justification. Remaining gaps are generic `fil`/`fill` glue orders outside `\parfillskip` and `\prevgraf`. -The pdfLaTeX oracle pins the 100-240pt measure matrix plus `\hangindent`, +The pdfLaTeX oracle pins the 90-240pt measure matrix plus `\hangindent`, `\parfillskip`, sentence-spacing and `\looseness` fixtures; all match and no oracle fixture is ignored. @@ -289,7 +291,7 @@ for a later overlaid slash. | Milestone | State | Notes | | --- | --- | --- | | M0 checkpoint engine | done | page list, page hashes, snapshot/restore, edit replay | -| 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 100-240pt plus register, geometry and vertical-glue fixtures | +| 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 floats, insertions and incremental replay still use the scrolling path; interpreted `\output` absent | | M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter | | M4 math | partial | atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping | @@ -327,7 +329,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 206 unit tests plus seven route-D integration tests and eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 319 tests (206 route-D unit, 7 route-D integration, 8 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 215 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 333 tests (215 route-D unit, 7 route-D integration, 13 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo