Shrink overfull final lines and widen the oracle matrix

This commit is contained in:
gloamxun committed 2026-10-23 02:45:11 +08:00
1 parent bcd3b6fa66
commit 6305f059ac
5 files changed
+98 -50

No files matched your search

+1 -1
View File
@@ -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 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 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 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`, `\parfillskip`, sentence-spacing with custom `\sfcode`,
`\spaceskip`/`\xspaceskip`, `\looseness` and vertical-glue fixtures. Overflowing `\spaceskip`/`\xspaceskip`, `\looseness` and vertical-glue fixtures. Overflowing
insertion material is split at item boundaries, with the tail held over to the insertion material is split at item boundaries, with the tail held over to the
+59 -30
View File
@@ -799,15 +799,17 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} else { } else {
0 0
}; };
if !is_last || !style.par_fillskip_fil { natural += fillskip;
natural += fillskip; stretch += fillskip_stretch;
stretch += fillskip_stretch; // TeX can stretch normal glue past its nominal stretch (badness
// TeX can stretch normal glue past its nominal stretch (badness // simply exceeds 100), but it never shrinks past the declared
// simply exceeds 100), but it never shrinks past the declared // shrink: an overfull line keeps its overflow instead of pulling
// shrink: an overfull line keeps its overflow instead of pulling // glue beyond its limits. A final line with a `fil` parfillskip only
// glue beyond its limits. // shrinks: the infinite stretch absorbs any shortfall, so only a
let delta = (target - natural).max(-shrink); // line wider than the measure adjusts its finite glue.
if delta > 0 && stretch > 0 { let delta = (target - natural).max(-shrink);
if delta > 0 {
if !is_last || !style.par_fillskip_fil {
let mut remaining = delta; let mut remaining = delta;
for item in &mut line { for item in &mut line {
if let HorizontalItem::Glue { if let HorizontalItem::Glue {
@@ -830,30 +832,30 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
{ {
*width += remaining; *width += remaining;
} }
} else if delta < 0 && shrink > 0 { }
let mut remaining = delta; } else if delta < 0 {
for item in &mut line { let mut remaining = delta;
if let HorizontalItem::Glue { for item in &mut line {
width, if let HorizontalItem::Glue {
shrink: shrink_amount, width,
.. shrink: shrink_amount,
} = item ..
&& *shrink_amount > 0 } = 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 { .. }))
{ {
*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 let width: i64 = line
.iter() .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] #[test]
fn words_break_at_glue_and_lines_are_justified() { fn words_break_at_glue_and_lines_are_justified() {
let style = ParagraphStyle { let style = ParagraphStyle {
+22 -4
View File
@@ -406,12 +406,30 @@ fn paragraph_breaks_match_pdftex_at_180pt() {
compare_fixture(WORDS, 180); compare_fixture(WORDS, 180);
} }
/// Several measures in one run: 100/120pt exercise hyphenated and overfull /// Several measures in one run: 90/100/110/120pt exercise hyphenated and
/// breaks, 150pt needs TeX's final-pass overfull box, and 180/200/240pt are /// overfull breaks, 130/150/160pt need TeX's final-pass overfull box, and
/// ordinary tolerance solutions. /// 180/200/220/240pt are ordinary tolerance solutions.
#[test] #[test]
fn paragraph_breaks_match_pdftex_across_measures() { 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); 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;
});
}
+5 -6
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the 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 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. fixture is ignored.
Known gaps, in dependency order: 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 breaker now uses TeX Live's `hyph-en-us` patterns and exceptions with
`\lefthyphenmin=2`/`\righthyphenmin=3`, stretches normal glue past its `\lefthyphenmin=2`/`\righthyphenmin=3`, stretches normal glue past its
nominal stretch while clamping shrink at the declared limit, and falls back to nominal stretch while clamping shrink at the declared limit, and falls back to
the longest prefix within `\tolerance` or the first overflowing prefix. The the longest prefix within `\tolerance` or the first overflowing prefix. The oracle compares an eleven-measure matrix (90-240pt) and all fixtures match
oracle compares 100, 120, 150, 180, 200 and 240pt and all six match pdfLaTeX pdfLaTeX word for word within 0.05pt; the narrow measures exercise hyphenated
word for word within 0.05pt; the narrow measures exercise hyphenated and and overfull breaks, and a final line held at its declared shrink limit. Register fixtures pin `\pretolerance=10000` (pass 0 stops
overfull breaks. Register fixtures pin `\pretolerance=10000` (pass 0 stops
before hyphenation) and `\hyphenpenalty=10000` (hyphenation illegal, first-fit before hyphenation) and `\hyphenpenalty=10000` (hyphenation illegal, first-fit
overfull lines). overfull lines).
@@ -222,7 +221,7 @@ top of a page (see `Paragraph::split_at`).
Still open: generic `fil`/`fill` glue orders, `\prevgraf`, explicit Still open: generic `fil`/`fill` glue orders, `\prevgraf`, explicit
`\vskip` classes (`\smallskip` and friends), `\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) ### P2 — Vertical list, page builder, `\output` (L2)
+11 -9
View File
@@ -80,11 +80,11 @@ fields mirroring `\pretolerance`, `\tolerance`, `\hyphenpenalty` and
plus document-level `\hyphenation` exceptions; `\hyphenpenalty` at 10000 or plus document-level `\hyphenation` exceptions; `\hyphenpenalty` at 10000 or
more disables hyphenation and switches the fallback to a first-fit scan. 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 240pt) against pdfLaTeX: every fixture matches word for word and within 0.05pt
horizontally. The narrow measures exercise hyphenated and overfull breaks, horizontally. The narrowest measures exercise hyphenated and overfull breaks (including a
150pt the final-pass overfull box, and 180-240pt ordinary tolerance final line held at its declared shrink limit), 130-160pt the final-pass
solutions. Two further fixtures pin register behaviour at 120pt: overfull box, and 180-240pt ordinary tolerance solutions. Two further fixtures pin register behaviour at 120pt:
`\pretolerance=10000` stops before hyphenation and `\hyphenpenalty=10000` `\pretolerance=10000` stops before hyphenation and `\hyphenpenalty=10000`
inhibits it, leaving the overfull first-fit lines TeX produces. A 120pt inhibits it, leaving the overfull first-fit lines TeX produces. A 120pt
fixture with `\hangindent=20pt \hangafter=1` checks every line origin 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 Two 150pt fixtures pin explicit interword glue: `\spaceskip` replaces the
font glue (width kept, stretch/shrink following the space factor) and font glue (width kept, stretch/shrink following the space factor) and
`\xspaceskip` is used verbatim once the factor reaches 2000; neither adds `\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 paragraph in both engines and compares ink bands, covering baseline placement
and justification. and justification.
@@ -113,7 +115,7 @@ and justification.
| Milestone | Content | Acceptance | | Milestone | Content | Acceptance |
| --- | --- | --- | | --- | --- | --- |
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 | | 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 | | 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 | | 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 | | 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 Remaining gaps are generic `fil`/`fill` glue orders outside
`\parfillskip` and `\prevgraf`. `\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 `\parfillskip`, sentence-spacing and `\looseness` fixtures; all match and no
oracle fixture is ignored. oracle fixture is ignored.
@@ -289,7 +291,7 @@ for a later overlaid slash.
| Milestone | State | Notes | | Milestone | State | Notes |
| --- | --- | --- | | --- | --- | --- |
| M0 checkpoint engine | done | page list, page hashes, snapshot/restore, edit replay | | 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 | | 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 | | 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 | | 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. 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 ### M0 incremental demo