Match TeX hyphenation and justification semantics

This commit is contained in:
texrra committed 2026-10-23 01:00:45 +08:00
1 parent ac134b3c4e
commit 4fbc43f5ff
6 files changed
+5073 -55

No files matched your search

@@ -0,0 +1,14 @@
as-so-ciate
as-so-ciates
dec-li-na-tion
oblig-a-tory
phil-an-thropic
present
presents
project
projects
reci-procity
re-cog-ni-zance
ref-or-ma-tion
ret-ri-bu-tion
ta-ble
File diff suppressed because it is too large. Load diff
+71 -21
View File
@@ -363,8 +363,10 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} }
} }
let mut ranges = solution.unwrap_or_else(|| { let mut ranges = solution.unwrap_or_else(|| {
// TeX's fallback when no feasible break exists: fill each line up to // TeX's final pass forces an overfull break only as a last resort.
// the first break at or past the measure, then continue. // Emulate that choice: take the longest prefix that still satisfies
// \tolerance, and fall back to the first prefix that overflows the
// measure when no feasible line exists.
let mut greedy = Vec::new(); let mut greedy = Vec::new();
let mut start_index = 0; let mut start_index = 0;
while start_index + 1 < count { while start_index + 1 < count {
@@ -374,7 +376,8 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} else { } else {
0 0
}; };
let mut chosen = count - 1; let mut feasible = None;
let mut overflow = None;
for end_index in start_index + 1..count { for end_index in start_index + 1..count {
let start = breakpoints[start_index]; let start = breakpoints[start_index];
let end = breakpoints[end_index]; let end = breakpoints[end_index];
@@ -382,37 +385,72 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
continue; continue;
} }
let mut natural = 0_i64; let mut natural = 0_i64;
let mut stretch = 0_i64;
let mut shrink = 0_i64;
let mut has_box = false;
for (offset, item) in items[start..end].iter().enumerate() { for (offset, item) in items[start..end].iter().enumerate() {
let last_item = start + offset + 1 == end;
match item { match item {
HorizontalItem::Box(box_item) => natural += box_item.width, HorizontalItem::Box(box_item) => {
HorizontalItem::Glue { width, .. } => { natural += box_item.width;
if start + offset + 1 != end { has_box = true;
natural += *width;
} }
HorizontalItem::Glue {
width,
stretch: stretch_amount,
shrink: shrink_amount,
} => {
if last_item {
continue;
}
natural += *width;
stretch += *stretch_amount;
shrink += *shrink_amount;
} }
HorizontalItem::Penalty { .. } => {} HorizontalItem::Penalty { .. } => {}
HorizontalItem::Discretionary { HorizontalItem::Discretionary {
pre_break_width, pre_break_width,
no_break_width, no_break_width,
} => { } => {
if start + offset + 1 == end { natural += if last_item {
natural += *pre_break_width; *pre_break_width
} else { } else {
natural += *no_break_width; *no_break_width
};
} }
} }
} }
if !has_box {
continue;
} }
if natural >= target { if overflow.is_none() && natural >= target {
chosen = end_index; overflow = Some(end_index);
break; }
let badness = if end == items.len() && natural <= target {
0
} else if natural < target {
if stretch > 0 {
(100.0 * ((target - natural) as f64 / stretch as f64).powi(3))
.round()
.min(10_000.0) as i64
} else {
10_000
}
} else if shrink > 0 {
(100.0 * ((natural - target) as f64 / shrink as f64).powi(3))
.round()
.min(10_000.0) as i64
} else {
10_000
};
if badness <= TOLERANCE {
feasible = Some(end_index);
} }
} }
let chosen = feasible.or(overflow).unwrap_or(count - 1);
greedy.push((breakpoints[start_index], breakpoints[chosen])); greedy.push((breakpoints[start_index], breakpoints[chosen]));
start_index = chosen; start_index = chosen;
} }
// The DP path produces ranges from the end backwards; build the
// fallback the same way so the single reverse below applies to both.
greedy.reverse(); greedy.reverse();
greedy greedy
}); });
@@ -479,10 +517,11 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} }
let is_last = line_index + 1 == line_count; let is_last = line_index + 1 == line_count;
if !is_last { if !is_last {
// TeX clamps the glue set ratio to the available stretch or // TeX can stretch normal glue past its nominal stretch (badness
// shrink; an overfull line stays overfull instead of pulling its // simply exceeds 100), but it never shrinks past the declared
// glue past the declared shrink. // shrink: an overfull line keeps its overflow instead of pulling
let delta = (target - natural).clamp(-shrink, stretch); // glue beyond its limits.
let delta = (target - natural).max(-shrink);
if delta > 0 && stretch > 0 { if delta > 0 && stretch > 0 {
let mut remaining = delta; let mut remaining = delta;
for item in &mut line { for item in &mut line {
@@ -558,6 +597,13 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} }
} }
/// TeX Live's American English hyphenation patterns (`hyph-en-us`, 2005),
/// which are what pdfLaTeX loads for `\language` 0 with the `english` option.
/// The vendored plain-TeX patterns differ (for example `kappa`), so route-D
/// uses the same data as the reference implementation.
const HYPHENATION_PATTERNS: &str = include_str!("../assets/hyph-en-us-patterns.txt");
const HYPHENATION_EXCEPTIONS: &str = include_str!("../assets/hyph-en-us-exceptions.txt");
/// Convert text using TFM character widths and fontdimen glue parameters. /// Convert text using TFM character widths and fontdimen glue parameters.
pub fn text_items_with_font( pub fn text_items_with_font(
text: &str, text: &str,
@@ -565,7 +611,9 @@ pub fn text_items_with_font(
font: &crate::cmr10::Cmr10Metrics, font: &crate::cmr10::Cmr10Metrics,
) -> Vec<HorizontalItem> { ) -> Vec<HorizontalItem> {
let mut items = Vec::new(); let mut items = Vec::new();
let hyphenator = hyphenate::Hyphenator::plain_tex_en_us(); let mut hyphenator = hyphenate::Hyphenator::default();
hyphenator.load_patterns(HYPHENATION_PATTERNS);
hyphenator.insert_exceptions(HYPHENATION_EXCEPTIONS);
let caser = hyphenate::AsciiLowerCaser::default(); let caser = hyphenate::AsciiLowerCaser::default();
// TeX's text fonts turn runs of hyphens into en/em dashes. cmr10's TFM // TeX's text fonts turn runs of hyphens into en/em dashes. cmr10's TFM
// does not carry these ligatures, so apply the same mapping before // does not carry these ligatures, so apply the same mapping before
@@ -631,10 +679,12 @@ pub fn text_items_with_font(
italic: font.italic(character), italic: font.italic(character),
})); }));
let boundary = character_index + 1; let boundary = character_index + 1;
// TeX's defaults for American English are \lefthyphenmin=2 and
// \righthyphenmin=3.
if !ligated if !ligated
&& points.contains(&boundary) && points.contains(&boundary)
&& boundary >= 2 && boundary >= 2
&& boundary + 2 <= word.chars().count() && boundary + 3 <= word.chars().count()
{ {
items.push(HorizontalItem::Discretionary { items.push(HorizontalItem::Discretionary {
pre_break_width: font.width('-'), pre_break_width: font.width('-'),
+10
View File
@@ -261,3 +261,13 @@ fn paragraph_breaks_match_pdftex_at_150pt() {
fn paragraph_breaks_match_pdftex_at_180pt() { 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
/// breaks, 150pt needs TeX's final-pass overfull box, and 180/200/240pt are
/// ordinary tolerance solutions.
#[test]
fn paragraph_breaks_match_pdftex_across_measures() {
for width in [100u32, 120, 150, 180, 200, 240] {
compare_fixture(WORDS, width);
}
}
+14 -16
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`). 285 workspace tests are green and no oracle PDF opt-in with `?engine=route-d`). 286 workspace tests are green and no oracle
fixture is ignored. fixture is ignored.
Known gaps, in dependency order: Known gaps, in dependency order:
@@ -154,21 +154,19 @@ Acceptance: 30 fixtures covering widths, indents, hyphenation, overfull and
underfull lines; line break positions and overfull boxes identical to underfull lines; line break positions and overfull boxes identical to
pdfLaTeX. pdfLaTeX.
Status (P0 committed, P1 in progress): the oracle harness found and fixed two Status (P0 committed, P1 in progress): the oracle harness found and fixed
real defects — the TFM lig/kern reader kept the last instruction for a shared four real defects: the TFM lig/kern reader kept the last instruction for a
key instead of the first (`k` + `a` picked up `w`'s kern), and justification shared key (`k` + `a` picked up `w`'s kern), justification squeezed overfull
squeezed overfull lines past their declared shrink. Both are fixed and the lines past their declared shrink while clamping legal stretch, the vendored
150pt fixture now matches pdfLaTeX word for word. plain-TeX hyphenation patterns disagreed with pdfLaTeX (`kappa`, `lambda`),
and the final-pass fallback did not model TeX's artificial demerits. The
Status (continued): the breaker now reproduces TeX's passes and demerits. breaker now uses TeX Live's `hyph-en-us` patterns and exceptions with
Pass 0 uses `\pretolerance` without hyphenation, pass 1 `\tolerance` with it, `\lefthyphenmin=2`/`\righthyphenmin=3`, stretches normal glue past its
and a third pass with `\tolerance=10000` plus `\emergencystretch` runs only when nominal stretch while clamping shrink at the declared limit, and falls back to
that register is positive. With zero emergencystretch TeX gives up and fills the longest prefix within `\tolerance` or the first overflowing prefix. The
each line to the first break at or past the measure, which is exactly the oracle compares 100, 120, 150, 180, 200 and 240pt and all six match pdfLaTeX
overfull fallback implemented here. Demerits combine line penalty, badness, word for word within 0.05pt; the narrow measures exercise hyphenated and
break penalties and adjacent fitness changes, and the final line keeps its overfull breaks.
natural width. Both oracle fixtures now pass, so TeX's emergency choices are
reproduced rather than approximated.
Still open: explicit `\tolerance`/`\pretolerance` overrides, flagged Still open: explicit `\tolerance`/`\pretolerance` overrides, flagged
(hyphenated) demerits, `\parfillskip` variants, `\hangindent`/`\parshape`, (hyphenated) demerits, `\parfillskip` variants, `\hangindent`/`\parshape`,
+26 -18
View File
@@ -61,19 +61,23 @@ class execution are still ahead.
M1 reads real CMR10 TFM metrics at runtime (advances, height/depth, italic M1 reads real CMR10 TFM metrics at runtime (advances, height/depth, italic
correction, kern pairs, ff/fi/fl/ffi/ffl ligatures and the fontdimen glue correction, kern pairs, ff/fi/fl/ffi/ffl ligatures and the fontdimen glue
parameters), hyphenates with the plain-TeX en-US patterns, and reproduces parameters), hyphenates with TeX Live's `hyph-en-us` patterns and exceptions
TeX's paragraph breaker: pass 0 uses `\pretolerance` without hyphenation, (`\lefthyphenmin=2`, `\righthyphenmin=3`), and reproduces TeX's paragraph
pass 1 uses `\tolerance`, and a third pass with `\tolerance=10000` runs only breaker: pass 0 uses `\pretolerance` without hyphenation, pass 1 uses
when `\emergencystretch` is positive. With zero emergencystretch TeX gives up `\tolerance`, and a third pass with `\tolerance=10000` runs only when
and fills each line to the first break at or past the measure, which leaves `\emergencystretch` is positive. With zero emergencystretch TeX's final pass
the familiar overfull boxes; the same fallback runs here. Justification clamps keeps `\tolerance` and forces overfull breaks through artificial demerits;
the glue set ratio to the declared stretch and shrink, so an overfull line the fallback here mirrors that choice by taking the longest prefix within
stays overfull exactly as in TeX instead of being squeezed into the measure. tolerance and otherwise the first prefix that overflows. Justification
stretches normal glue past its nominal stretch (badness simply exceeds 100)
and clamps shrink at the declared limit, so overfull lines stay overfull
exactly as in TeX.
`tests/oracle.rs` checks the 150pt and 180pt fixtures against pdfLaTeX: both `tests/oracle.rs` compares a matrix of measures (100, 120, 150, 180, 200 and
match the oracle word for word and within 0.05pt horizontally. The 150pt 240pt) against pdfLaTeX: every fixture matches word for word and within 0.05pt
fixture exercises the overfull fallback, the 180pt fixture the ordinary horizontally. The narrow measures exercise hyphenated and overfull breaks,
pass-1 solution. `route_d_multiline_bands_track_pdftex` rasterizes the same 150pt the final-pass overfull box, and 180-240pt ordinary tolerance
solutions. `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.
@@ -92,7 +96,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, hyphenation, TeX demerits and tolerance passes, pdfLaTeX oracles at 150pt and 180pt; explicit tolerance registers and more fixtures 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, pdfLaTeX oracle matrix 100-240pt; explicit tolerance registers, `\looseness`, `\parshape` and more fixtures 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; interpreted `\output`, float pages 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; interpreted `\output`, float pages 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 |
@@ -103,10 +107,14 @@ and justification.
## Current limits ## Current limits
- The M1 paragraph builder parses CMR10 TFM metrics (widths, height/depth, - The M1 paragraph builder parses CMR10 TFM metrics (widths, height/depth,
italic correction, kern pairs, ligatures), applies plain-TeX hyphenation and italic correction, kern pairs, ligatures), applies TeX Live's en-US
runs TeX's tolerance passes with demerits. Remaining gaps are explicit hyphenation patterns and runs TeX's tolerance passes with demerits. Remaining
`\tolerance`/`\pretolerance` overrides, hyphenated-break penalties and gaps are explicit `\tolerance`/`\pretolerance` overrides (the defaults and
`\parfillskip` variants. `\emergencystretch` are modelled), `\hyphenpenalty`/`\exhyphenpenalty`,
`\looseness`, `\parshape` and `\parfillskip` variants.
The pdfLaTeX oracle pins six measures (100-240pt) and all match; no oracle
fixture is ignored.
The pdfLaTeX oracle currently pins two measures (150pt and 180pt). The earlier The pdfLaTeX oracle currently pins two measures (150pt and 180pt). The earlier
multi-width table was produced by the old single-cost breaker and is no longer multi-width table was produced by the old single-cost breaker and is no longer
@@ -237,7 +245,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, hyphenation, TeX demerits and tolerance passes, pdfTeX 150pt/180pt oracles | | M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, pdfTeX oracle matrix 100-240pt |
| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; 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; 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 |