Reproduce TeX paragraph breaking with tolerance passes and demerits

- replace the single-tolerance DP with pass 0 (pretolerance, no hyphenation),
  pass 1 (tolerance, hyphenation) and an optional emergency pass
- add emergencystretch to ParagraphStyle; the emergency pass only runs when it
  is positive, otherwise TeX's overfull fallback applies and each line fills to
  the first break at or past the measure
- compute badness and fitness classes like TeX and fold them with penalties
  into demerits, ignoring the trailing forced penalty on the final line
- keep forward order in the greedy fallback
- enable the 180pt pdfLaTeX oracle fixture and add an emergencystretch test
- give route-D extraction tests scaled body styles so fixed-cell
  ParagraphStyle defaults no longer mix raw units with TFM advances
- document the passes, oracle results and remaining P1 gaps
This commit is contained in:
gloamxun committed 2026-10-23 00:50:57 +08:00
1 parent 03aa1c5110
commit ac134b3c4e
8 files changed
+331 -164

No files matched your search

+243 -87
View File
@@ -48,6 +48,10 @@ pub struct ParagraphStyle {
#[serde(default)]
pub right_aligned: bool,
pub par_indent: i64,
/// Extra stretch added to every line when TeX's emergency pass runs
/// (`\emergencystretch`).
#[serde(default)]
pub emergencystretch: i64,
pub line_height: i64,
pub char_width: i64,
pub space_width: i64,
@@ -64,6 +68,7 @@ impl Default for ParagraphStyle {
centered: false,
right_aligned: false,
par_indent: 0,
emergencystretch: 0,
line_height: 12,
char_width: 10,
space_width: 4,
@@ -181,104 +186,236 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
}
breakpoints.dedup();
// TeX's line breaker: demerits over badness, break penalties and fitness
// changes. Pass 0 uses \pretolerance without hyphenation, pass 1 uses
// \tolerance, and the emergency pass only exists when \emergencystretch is
// positive. With zero emergencystretch TeX gives up and falls back to
// filling each line up to the first break at or past the measure, which is
// what produces the familiar overfull boxes.
#[derive(Clone, Copy)]
struct Candidate {
cost: i64,
previous: usize,
previous_fitness: usize,
}
const PRETOLERANCE: i64 = 100;
const TOLERANCE: i64 = 200;
const LINE_PENALTY: i64 = 10;
const ADJ_DEMERITS: i64 = 10_000;
let count = breakpoints.len();
let mut best = vec![i64::MAX; count];
let mut previous = vec![0_usize; count];
best[0] = 0;
for end_index in 1..count {
let end = breakpoints[end_index];
for start_index in 0..end_index {
let start = breakpoints[start_index];
if best[start_index] == i64::MAX || start >= end {
let mut solution: Option<Vec<(usize, usize)>> = None;
let passes = if style.emergencystretch > 0 { 3 } else { 2 };
for pass in 0..passes {
let limit = match pass {
0 => PRETOLERANCE,
1 => TOLERANCE,
_ => 10_000,
};
let extra_stretch = if pass == 2 { style.emergencystretch } else { 0 };
let mut best: Vec<[Option<Candidate>; 4]> = vec![[None; 4]; count];
best[0][1] = Some(Candidate {
cost: 0,
previous: 0,
previous_fitness: 1,
});
for end_index in 1..count {
let end = breakpoints[end_index];
let is_last = end == items.len();
if pass == 0 && matches!(items[end - 1], HorizontalItem::Discretionary { .. }) {
continue;
}
let line = &items[start..end];
let mut natural = 0_i64;
let mut stretch = 0_i64;
let mut shrink = 0_i64;
let mut has_box = false;
let mut trailing_penalty = 0_i64;
for (offset, item) in line.iter().enumerate() {
match item {
HorizontalItem::Box(box_item) => {
natural += box_item.width;
has_box = true;
}
HorizontalItem::Glue {
width,
stretch: stretch_amount,
shrink: shrink_amount,
} => {
natural += *width;
stretch += *stretch_amount;
shrink += *shrink_amount;
}
HorizontalItem::Penalty { penalty, .. } => {
trailing_penalty = *penalty;
}
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
if start + offset + 1 == end {
natural += *pre_break_width;
} else {
natural += *no_break_width;
for start_index in 0..end_index {
let start = breakpoints[start_index];
if start >= end {
continue;
}
let mut natural = 0_i64;
let mut stretch = 0_i64;
let mut shrink = 0_i64;
let mut has_box = false;
let mut trailing_penalty = 0_i64;
for (offset, item) in items[start..end].iter().enumerate() {
match item {
HorizontalItem::Box(box_item) => {
natural += box_item.width;
has_box = true;
}
HorizontalItem::Glue {
width,
stretch: stretch_amount,
shrink: shrink_amount,
} => {
// A break at glue discards that glue: the line ends
// before it, exactly as TeX's line breaker does.
if start + offset + 1 == end {
continue;
}
natural += *width;
stretch += *stretch_amount;
shrink += *shrink_amount;
}
HorizontalItem::Penalty { penalty, .. } => trailing_penalty = *penalty,
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
if start + offset + 1 == end {
natural += *pre_break_width;
} else {
natural += *no_break_width;
}
}
}
}
if !has_box {
continue;
}
if is_last {
trailing_penalty = 0;
}
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
- if start_index == 0 {
style.par_indent
} else {
0
};
let stretch = stretch + extra_stretch;
let (ratio, badness) = if natural < target {
if stretch > 0 {
let ratio = (target - natural) as f64 / stretch as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else if natural > target {
if shrink > 0 {
let ratio = (natural - target) as f64 / shrink as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else {
(0.0, 0)
};
// TeX's final line has \parfillskip's infinite stretch.
let badness = if is_last && natural <= target {
0
} else {
badness
};
if badness > limit {
continue;
}
let fitness = if ratio < -0.5 {
0
} else if ratio <= 0.5 {
1
} else if ratio <= 1.0 {
2
} else {
3
};
let fitness = if natural < target && stretch == 0 {
3
} else {
fitness
};
for previous_fitness in 0..4 {
let Some(node) = best[start_index][previous_fitness] else {
continue;
};
let mut demerits = (LINE_PENALTY + badness).pow(2);
if trailing_penalty >= 0 {
demerits = demerits.saturating_add(trailing_penalty.pow(2));
} else {
demerits = demerits.saturating_sub(trailing_penalty.pow(2));
}
if (fitness as i64 - previous_fitness as i64).abs() > 1 {
demerits = demerits.saturating_add(ADJ_DEMERITS);
}
let cost = node.cost.saturating_add(demerits);
let entry = &mut best[end_index][fitness];
if entry.map_or(true, |current| cost < current.cost) {
*entry = Some(Candidate {
cost,
previous: start_index,
previous_fitness,
});
}
}
}
if !has_box {
continue;
}
let final_index = count - 1;
let winner = (0..4)
.filter_map(|fitness| best[final_index][fitness].map(|node| (node.cost, fitness)))
.min();
if let Some((_, mut fitness)) = winner {
let mut ranges = Vec::new();
let mut end_index = final_index;
while end_index > 0 {
let node = best[end_index][fitness].expect("chosen line");
ranges.push((breakpoints[node.previous], breakpoints[end_index]));
end_index = node.previous;
fitness = node.previous_fitness;
}
solution = Some(ranges);
break;
}
}
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.
let mut greedy = Vec::new();
let mut start_index = 0;
while start_index + 1 < count {
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
- if start_index == 0 {
style.par_indent
} else {
0
};
let is_last = end == items.len();
if !is_last && natural * 2 < target {
continue;
}
let (ratio, overfull) = if natural <= target {
if is_last || stretch == 0 {
(0.0, false)
} else {
((target - natural) as f64 / stretch as f64, false)
let mut chosen = count - 1;
for end_index in start_index + 1..count {
let start = breakpoints[start_index];
let end = breakpoints[end_index];
if start >= end {
continue;
}
let mut natural = 0_i64;
for (offset, item) in items[start..end].iter().enumerate() {
match item {
HorizontalItem::Box(box_item) => natural += box_item.width,
HorizontalItem::Glue { width, .. } => {
if start + offset + 1 != end {
natural += *width;
}
}
HorizontalItem::Penalty { .. } => {}
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
if start + offset + 1 == end {
natural += *pre_break_width;
} else {
natural += *no_break_width;
}
}
}
}
if natural >= target {
chosen = end_index;
break;
}
} else if shrink == 0 {
((natural - target) as f64, true)
} else {
let ratio = (natural - target) as f64 / shrink as f64;
(ratio, ratio > 1.0)
};
let badness = (100.0 * ratio.abs().powi(3)).min(10_000.0) as i64;
let overfull_penalty = if overfull { 100_000 } else { 0 };
let penalty = if is_last {
0
} else if trailing_penalty >= 0 {
trailing_penalty.min(10_000)
} else {
-(trailing_penalty)
};
let cost = badness
.saturating_mul(badness)
.saturating_add(overfull_penalty)
.saturating_add(penalty);
if cost < best[end_index] {
best[end_index] = cost;
previous[end_index] = start_index;
}
greedy.push((breakpoints[start_index], breakpoints[chosen]));
start_index = chosen;
}
}
let mut ranges = Vec::new();
let mut end_index = count - 1;
while end_index > 0 {
let start_index = previous[end_index].min(end_index - 1);
ranges.push((breakpoints[start_index], breakpoints[end_index]));
end_index = start_index;
}
// 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
});
ranges.reverse();
let mut lines = Vec::with_capacity(ranges.len());
let mut max_width = 0;
@@ -554,6 +691,7 @@ mod tests {
let style = ParagraphStyle {
line_width: 150 * 65_536,
par_indent: 0,
emergencystretch: 0,
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
@@ -655,19 +793,18 @@ mod tests {
&style,
&font,
);
let mut words: Vec<usize> = paragraph
// TeX produces four lines at this measure: 7, 8, 9 and 1 words.
let words: Vec<usize> = paragraph
.lines
.iter()
.map(|line| {
line.iter()
.filter(|item| matches!(item, HorizontalItem::Glue { .. }))
.count()
+ 1
})
.collect();
if let Some(last) = words.last_mut() {
*last += 1;
}
assert_eq!(words, vec![7, 7, 8]);
assert_eq!(words, vec![7, 8, 9, 1]);
}
#[test]
@@ -695,11 +832,30 @@ mod tests {
assert_eq!(counts, vec![30, 25]);
}
#[test]
fn emergencystretch_enables_the_emergency_pass() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 150 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
let plain = layout_paragraph_with_font(text, &style, &font);
assert_eq!(plain.line_count(), 2);
let emergency = ParagraphStyle {
emergencystretch: 10 * 65_536,
..style
};
let paragraph = layout_paragraph_with_font(text, &emergency, &font);
assert_eq!(paragraph.line_count(), 3);
}
#[test]
fn hyphenation_inserts_discretionary_breaks() {
let font = crate::cmr10::Cmr10Metrics::default();
let style = ParagraphStyle {
line_width: 3_000_000,
line_width: 2_000_000,
..ParagraphStyle::default()
};
let items = text_items_with_font("hyphenation", &style, &font);