Honour TeX looseness when an alternative line count exists

This commit is contained in:
gloamxun committed 2026-10-23 13:46:32 +08:00
1 parent 96cd98f833
commit a6397fcfef
6 files changed
+219 -99

No files matched your search

+162 -91
View File
@@ -119,6 +119,10 @@ pub struct ParagraphStyle {
pub centered: bool,
#[serde(default)]
pub right_aligned: bool,
/// TeX `\looseness`: shift the final line count by this many lines (an
/// alternative is only taken when it is feasible, as in TeX).
#[serde(default)]
pub looseness: i64,
/// Ragged-right setting (`\raggedright`): lines keep their natural width
/// and the missing space is absorbed by an infinite `\rightskip`.
#[serde(default)]
@@ -253,6 +257,7 @@ impl Default for ParagraphStyle {
lineskiplimit: 0,
centered: false,
right_aligned: false,
looseness: 0,
ragged_right: false,
par_indent: 0,
emergencystretch: 0,
@@ -440,9 +445,14 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
struct Candidate {
cost: i64,
previous: usize,
previous_index: usize,
previous_state: usize,
line: usize,
}
/// TeX keeps one active node per fitness class, but \looseness needs
/// alternative line counts to survive pruning; keep the cheapest few
/// candidates per class, deduplicated by line count.
const CANDIDATES_PER_STATE: usize = 6;
let count = breakpoints.len();
let mut solution: Option<Vec<(usize, usize)>> = None;
// TeX's emergency pass only exists when \emergencystretch is positive.
@@ -459,10 +469,13 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
// State = fitness * 2 + whether the previous line was hyphenated.
// A candidate also records its zero-based line number so that
// \parshape and \hangindent can give each line its own measure.
let mut best: Vec<[Option<Candidate>; 8]> = vec![[None; 8]; count];
best[0][2] = Some(Candidate {
let mut best: Vec<[Vec<Candidate>; 8]> = (0..count)
.map(|_| std::array::from_fn(|_| Vec::new()))
.collect();
best[0][2].push(Candidate {
cost: 0,
previous: 0,
previous_index: 0,
previous_state: 2,
line: 0,
});
@@ -543,113 +556,148 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
};
}
for previous_state in 0..8 {
let Some(node) = best[start_index][previous_state] else {
continue;
};
let target = style.line_target(node.line);
let infinite_order = (1..4).rev().find(|order| stretch_by_order[*order] > 0);
let stretch = stretch + extra_stretch;
let (mut ratio, mut badness) = if natural < target {
if infinite_order.is_some() {
let previous_bucket = best[start_index][previous_state].clone();
for (previous_index, node) in previous_bucket.into_iter().enumerate() {
let target = style.line_target(node.line);
let infinite_order =
(1..4).rev().find(|order| stretch_by_order[*order] > 0);
let stretch = stretch + extra_stretch;
let (mut ratio, mut badness) = if natural < target {
if infinite_order.is_some() {
(0.0, 0)
} else 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)
} else 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)
};
// \raggedright puts an infinite `fil` in \rightskip, so
// any line that fits has zero badness and natural glue.
if style.ragged_right && natural <= target {
ratio = 0.0;
badness = 0;
}
// TeX's default final line has \parfillskip's infinite
// stretch; without fil the last line is set like any other.
let badness = if is_last && style.par_fillskip_fil && natural <= target {
0
} else {
(1.0, 10_000)
badness
};
// A line that cannot fit even after shrinking its glue is
// overfull. TeX rejects such lines in every ordinary pass,
// regardless of \tolerance, and only admits them in the
// final/emergency pass.
let overfull = natural > target && natural - target > shrink;
if overfull && pass != 2 {
continue;
}
} 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)
if badness > limit {
continue;
}
let fitness = if ratio < -0.5 {
0
} else if ratio <= 0.5 {
1
} else if ratio <= 1.0 {
2
} else {
(1.0, 10_000)
3
};
let fitness =
if natural < target && stretch == 0 && infinite_order.is_none() {
3
} else {
fitness
};
let state = fitness * 2 + usize::from(hyphen_break);
let previous_fitness = previous_state / 2;
let mut demerits = (style.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));
}
} else {
(0.0, 0)
};
// \raggedright puts an infinite `fil` in \rightskip, so
// any line that fits has zero badness and natural glue.
if style.ragged_right && natural <= target {
ratio = 0.0;
badness = 0;
}
// TeX's default final line has \parfillskip's infinite
// stretch; without fil the last line is set like any other.
let badness = if is_last && style.par_fillskip_fil && natural <= target {
0
} else {
badness
};
// A line that cannot fit even after shrinking its glue is
// overfull. TeX only admits such lines in the emergency
// pass, no matter how large \tolerance is.
let overfull = natural > target && natural - target > shrink;
if overfull && pass != 2 {
continue;
}
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 && infinite_order.is_none() {
3
} else {
fitness
};
let state = fitness * 2 + usize::from(hyphen_break);
let previous_fitness = previous_state / 2;
let mut demerits = (style.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(style.adj_demerits);
}
if hyphen_break {
if previous_state % 2 == 1 {
demerits = demerits.saturating_add(style.double_hyphen_demerits);
if (fitness as i64 - previous_fitness as i64).abs() > 1 {
demerits = demerits.saturating_add(style.adj_demerits);
}
if end_index + 1 == count - 1 {
demerits = demerits.saturating_add(style.final_hyphen_demerits);
if hyphen_break {
if previous_state % 2 == 1 {
demerits = demerits.saturating_add(style.double_hyphen_demerits);
}
if end_index + 1 == count - 1 {
demerits = demerits.saturating_add(style.final_hyphen_demerits);
}
}
let cost = node.cost.saturating_add(demerits);
let line = node.line + 1;
let bucket = &mut best[end_index][state];
if let Some(current) = bucket.iter_mut().find(|entry| entry.line == line) {
if cost < current.cost {
*current = Candidate {
cost,
previous: start_index,
previous_index,
previous_state,
line,
};
}
} else {
bucket.push(Candidate {
cost,
previous: start_index,
previous_index,
previous_state,
line,
});
bucket.sort_unstable_by_key(|candidate| candidate.cost);
bucket.truncate(CANDIDATES_PER_STATE);
}
}
let cost = node.cost.saturating_add(demerits);
let line = node.line + 1;
let entry = &mut best[end_index][state];
if entry.map_or(true, |current| cost < current.cost) {
*entry = Some(Candidate {
cost,
previous: start_index,
previous_state,
line,
});
}
}
}
}
let final_index = count - 1;
let winner = (0..8)
.filter_map(|state| best[final_index][state].map(|node| (node.cost, state)))
.min();
if let Some((_, mut state)) = winner {
let mut finals: Vec<(i64, usize, usize, usize)> = Vec::new();
for state in 0..8 {
for (index, node) in best[final_index][state].iter().enumerate() {
finals.push((node.cost, node.line, state, index));
}
}
finals.sort_unstable();
if let Some(&(_, best_line, _, _)) = finals.first() {
// TeX's looseness asks for `best + looseness` lines; if that count
// has no feasible solution the ordinary optimum is used.
let looseness = style.looseness.clamp(-9, 9);
let target = (best_line as i64 + looseness).max(0) as usize;
let chosen = if looseness == 0 {
finals[0]
} else {
finals
.iter()
.copied()
.find(|entry| entry.1 == target)
.unwrap_or(finals[0])
};
let (_, _, mut state, mut index) = chosen;
let mut ranges = Vec::new();
let mut end_index = final_index;
while end_index > 0 {
let node = best[end_index][state].expect("chosen line");
let node = best[end_index][state][index];
ranges.push((breakpoints[node.previous], breakpoints[end_index]));
end_index = node.previous;
state = node.previous_state;
index = node.previous_index;
}
solution = Some(ranges);
break;
@@ -2058,4 +2106,27 @@ mod tests {
assert_eq!(fil, 0, "\\hfil must stay at its natural width");
assert!(fill > 0, "\\hfill must absorb the whole page set");
}
#[test]
fn looseness_shifts_the_line_count_when_feasible() {
let font = crate::cmr10::Cmr10Metrics::default();
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa \
lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega";
let base = ParagraphStyle {
line_width: 120 * 65_536,
par_indent: 0,
tolerance: 10_000,
pretolerance: 10_000,
..ParagraphStyle::default()
};
let measured = |looseness: i64| {
let mut style = base.clone();
style.looseness = looseness;
layout_paragraph_with_font(text, &style, &font).lines.len()
};
assert_eq!(measured(0), 5, "default optimum");
// A four-line setting would need an overfull line, which TeX refuses
// outside the final pass, so the optimum is kept.
assert_eq!(measured(-1), 5, "infeasible tighter paragraph");
assert_eq!(measured(1), 6, "looser paragraph");
}
}