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
+5074 -56

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
+72 -22
View File
@@ -363,8 +363,10 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
}
}
let mut ranges = solution.unwrap_or_else(|| {
// TeX's fallback when no feasible break exists: fill each line up to
// the first break at or past the measure, then continue.
// TeX's final pass forces an overfull break only as a last resort.
// 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 start_index = 0;
while start_index + 1 < count {
@@ -374,7 +376,8 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} else {
0
};
let mut chosen = count - 1;
let mut feasible = None;
let mut overflow = None;
for end_index in start_index + 1..count {
let start = breakpoints[start_index];
let end = breakpoints[end_index];
@@ -382,37 +385,72 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
continue;
}
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() {
let last_item = start + offset + 1 == end;
match item {
HorizontalItem::Box(box_item) => natural += box_item.width,
HorizontalItem::Glue { width, .. } => {
if start + offset + 1 != end {
natural += *width;
HorizontalItem::Box(box_item) => {
natural += box_item.width;
has_box = true;
}
HorizontalItem::Glue {
width,
stretch: stretch_amount,
shrink: shrink_amount,
} => {
if last_item {
continue;
}
natural += *width;
stretch += *stretch_amount;
shrink += *shrink_amount;
}
HorizontalItem::Penalty { .. } => {}
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
if start + offset + 1 == end {
natural += *pre_break_width;
natural += if last_item {
*pre_break_width
} else {
natural += *no_break_width;
}
*no_break_width
};
}
}
}
if natural >= target {
chosen = end_index;
break;
if !has_box {
continue;
}
if overflow.is_none() && natural >= target {
overflow = Some(end_index);
}
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]));
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
});
@@ -479,10 +517,11 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
}
let is_last = line_index + 1 == line_count;
if !is_last {
// TeX clamps the glue set ratio to the available stretch or
// shrink; an overfull line stays overfull instead of pulling its
// glue past the declared shrink.
let delta = (target - natural).clamp(-shrink, 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 {
let mut remaining = delta;
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.
pub fn text_items_with_font(
text: &str,
@@ -565,7 +611,9 @@ pub fn text_items_with_font(
font: &crate::cmr10::Cmr10Metrics,
) -> Vec<HorizontalItem> {
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();
// 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
@@ -631,10 +679,12 @@ pub fn text_items_with_font(
italic: font.italic(character),
}));
let boundary = character_index + 1;
// TeX's defaults for American English are \lefthyphenmin=2 and
// \righthyphenmin=3.
if !ligated
&& points.contains(&boundary)
&& boundary >= 2
&& boundary + 2 <= word.chars().count()
&& boundary + 3 <= word.chars().count()
{
items.push(HorizontalItem::Discretionary {
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() {
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
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`). 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.
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
pdfLaTeX.
Status (P0 committed, P1 in progress): the oracle harness found and fixed two
real defects — the TFM lig/kern reader kept the last instruction for a shared
key instead of the first (`k` + `a` picked up `w`'s kern), and justification
squeezed overfull lines past their declared shrink. Both are fixed and the
150pt fixture now matches pdfLaTeX word for word.
Status (continued): the breaker now reproduces TeX's passes and demerits.
Pass 0 uses `\pretolerance` without hyphenation, pass 1 `\tolerance` with it,
and a third pass with `\tolerance=10000` plus `\emergencystretch` runs only when
that register is positive. With zero emergencystretch TeX gives up and fills
each line to the first break at or past the measure, which is exactly the
overfull fallback implemented here. Demerits combine line penalty, badness,
break penalties and adjacent fitness changes, and the final line keeps its
natural width. Both oracle fixtures now pass, so TeX's emergency choices are
reproduced rather than approximated.
Status (P0 committed, P1 in progress): the oracle harness found and fixed
four real defects: the TFM lig/kern reader kept the last instruction for a
shared key (`k` + `a` picked up `w`'s kern), justification squeezed overfull
lines past their declared shrink while clamping legal stretch, the vendored
plain-TeX hyphenation patterns disagreed with pdfLaTeX (`kappa`, `lambda`),
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.
Still open: explicit `\tolerance`/`\pretolerance` overrides, flagged
(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
correction, kern pairs, ff/fi/fl/ffi/ffl ligatures and the fontdimen glue
parameters), hyphenates with the plain-TeX en-US patterns, and reproduces
TeX's paragraph breaker: pass 0 uses `\pretolerance` without hyphenation,
pass 1 uses `\tolerance`, and a third pass with `\tolerance=10000` runs only
when `\emergencystretch` is positive. With zero emergencystretch TeX gives up
and fills each line to the first break at or past the measure, which leaves
the familiar overfull boxes; the same fallback runs here. Justification clamps
the glue set ratio to the declared stretch and shrink, so an overfull line
stays overfull exactly as in TeX instead of being squeezed into the measure.
parameters), hyphenates with TeX Live's `hyph-en-us` patterns and exceptions
(`\lefthyphenmin=2`, `\righthyphenmin=3`), and reproduces TeX's paragraph
breaker: pass 0 uses `\pretolerance` without hyphenation, pass 1 uses
`\tolerance`, and a third pass with `\tolerance=10000` runs only when
`\emergencystretch` is positive. With zero emergencystretch TeX's final pass
keeps `\tolerance` and forces overfull breaks through artificial demerits;
the fallback here mirrors that choice by taking the longest prefix within
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
match the oracle word for word and within 0.05pt horizontally. The 150pt
fixture exercises the overfull fallback, the 180pt fixture the ordinary
pass-1 solution. `route_d_multiline_bands_track_pdftex` rasterizes the same
`tests/oracle.rs` compares a matrix of measures (100, 120, 150, 180, 200 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. `route_d_multiline_bands_track_pdftex` rasterizes the same
paragraph in both engines and compares ink bands, covering baseline placement
and justification.
@@ -92,7 +96,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, 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 |
| 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 |
@@ -103,10 +107,14 @@ and justification.
## Current limits
- The M1 paragraph builder parses CMR10 TFM metrics (widths, height/depth,
italic correction, kern pairs, ligatures), applies plain-TeX hyphenation and
runs TeX's tolerance passes with demerits. Remaining gaps are explicit
`\tolerance`/`\pretolerance` overrides, hyphenated-break penalties and
`\parfillskip` variants.
italic correction, kern pairs, ligatures), applies TeX Live's en-US
hyphenation patterns and runs TeX's tolerance passes with demerits. Remaining
gaps are explicit `\tolerance`/`\pretolerance` overrides (the defaults and
`\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
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 |
| --- | --- | --- |
| 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 |
| 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 |