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
+145 -25

No files matched your search

+88 -17
View File
@@ -119,6 +119,10 @@ pub struct ParagraphStyle {
pub centered: bool, pub centered: bool,
#[serde(default)] #[serde(default)]
pub right_aligned: bool, 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 /// Ragged-right setting (`\raggedright`): lines keep their natural width
/// and the missing space is absorbed by an infinite `\rightskip`. /// and the missing space is absorbed by an infinite `\rightskip`.
#[serde(default)] #[serde(default)]
@@ -253,6 +257,7 @@ impl Default for ParagraphStyle {
lineskiplimit: 0, lineskiplimit: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
looseness: 0,
ragged_right: false, ragged_right: false,
par_indent: 0, par_indent: 0,
emergencystretch: 0, emergencystretch: 0,
@@ -440,9 +445,14 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
struct Candidate { struct Candidate {
cost: i64, cost: i64,
previous: usize, previous: usize,
previous_index: usize,
previous_state: usize, previous_state: usize,
line: 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 count = breakpoints.len();
let mut solution: Option<Vec<(usize, usize)>> = None; let mut solution: Option<Vec<(usize, usize)>> = None;
// TeX's emergency pass only exists when \emergencystretch is positive. // 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. // State = fitness * 2 + whether the previous line was hyphenated.
// A candidate also records its zero-based line number so that // A candidate also records its zero-based line number so that
// \parshape and \hangindent can give each line its own measure. // \parshape and \hangindent can give each line its own measure.
let mut best: Vec<[Option<Candidate>; 8]> = vec![[None; 8]; count]; let mut best: Vec<[Vec<Candidate>; 8]> = (0..count)
best[0][2] = Some(Candidate { .map(|_| std::array::from_fn(|_| Vec::new()))
.collect();
best[0][2].push(Candidate {
cost: 0, cost: 0,
previous: 0, previous: 0,
previous_index: 0,
previous_state: 2, previous_state: 2,
line: 0, line: 0,
}); });
@@ -543,11 +556,11 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
}; };
} }
for previous_state in 0..8 { for previous_state in 0..8 {
let Some(node) = best[start_index][previous_state] else { let previous_bucket = best[start_index][previous_state].clone();
continue; for (previous_index, node) in previous_bucket.into_iter().enumerate() {
};
let target = style.line_target(node.line); let target = style.line_target(node.line);
let infinite_order = (1..4).rev().find(|order| stretch_by_order[*order] > 0); let infinite_order =
(1..4).rev().find(|order| stretch_by_order[*order] > 0);
let stretch = stretch + extra_stretch; let stretch = stretch + extra_stretch;
let (mut ratio, mut badness) = if natural < target { let (mut ratio, mut badness) = if natural < target {
if infinite_order.is_some() { if infinite_order.is_some() {
@@ -582,8 +595,9 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
badness badness
}; };
// A line that cannot fit even after shrinking its glue is // A line that cannot fit even after shrinking its glue is
// overfull. TeX only admits such lines in the emergency // overfull. TeX rejects such lines in every ordinary pass,
// pass, no matter how large \tolerance is. // regardless of \tolerance, and only admits them in the
// final/emergency pass.
let overfull = natural > target && natural - target > shrink; let overfull = natural > target && natural - target > shrink;
if overfull && pass != 2 { if overfull && pass != 2 {
continue; continue;
@@ -600,7 +614,8 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} else { } else {
3 3
}; };
let fitness = if natural < target && stretch == 0 && infinite_order.is_none() { let fitness =
if natural < target && stretch == 0 && infinite_order.is_none() {
3 3
} else { } else {
fitness fitness
@@ -626,30 +641,63 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} }
let cost = node.cost.saturating_add(demerits); let cost = node.cost.saturating_add(demerits);
let line = node.line + 1; let line = node.line + 1;
let entry = &mut best[end_index][state]; let bucket = &mut best[end_index][state];
if entry.map_or(true, |current| cost < current.cost) { if let Some(current) = bucket.iter_mut().find(|entry| entry.line == line) {
*entry = Some(Candidate { if cost < current.cost {
*current = Candidate {
cost, cost,
previous: start_index, previous: start_index,
previous_index,
previous_state,
line,
};
}
} else {
bucket.push(Candidate {
cost,
previous: start_index,
previous_index,
previous_state, previous_state,
line, line,
}); });
bucket.sort_unstable_by_key(|candidate| candidate.cost);
bucket.truncate(CANDIDATES_PER_STATE);
}
} }
} }
} }
} }
let final_index = count - 1; let final_index = count - 1;
let winner = (0..8) let mut finals: Vec<(i64, usize, usize, usize)> = Vec::new();
.filter_map(|state| best[final_index][state].map(|node| (node.cost, state))) for state in 0..8 {
.min(); for (index, node) in best[final_index][state].iter().enumerate() {
if let Some((_, mut state)) = winner { 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 ranges = Vec::new();
let mut end_index = final_index; let mut end_index = final_index;
while end_index > 0 { 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])); ranges.push((breakpoints[node.previous], breakpoints[end_index]));
end_index = node.previous; end_index = node.previous;
state = node.previous_state; state = node.previous_state;
index = node.previous_index;
} }
solution = Some(ranges); solution = Some(ranges);
break; break;
@@ -2058,4 +2106,27 @@ mod tests {
assert_eq!(fil, 0, "\\hfil must stay at its natural width"); assert_eq!(fil, 0, "\\hfil must stay at its natural width");
assert!(fill > 0, "\\hfill must absorb the whole page set"); 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");
}
} }
+31
View File
@@ -151,6 +151,7 @@ fn route_d_lines_with(
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
looseness: 0,
par_indent: 0, par_indent: 0,
line_height: 12 * PT, line_height: 12 * PT,
..ParagraphStyle::default() ..ParagraphStyle::default()
@@ -537,6 +538,36 @@ fn par_shape_matches_pdftex() {
); );
} }
/// TeX `\\looseness` asks for a different final line count when such a
/// break is feasible within `\\tolerance`; pdfLaTeX is the reference. When
/// the requested count is infeasible TeX still prints a different (alternative
/// optimum) paragraph; route-D keeps the ordinary optimum there, which is
/// covered by the unit tests rather than this oracle.
#[test]
fn looseness_matches_pdftex() {
let width = 120;
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";
for looseness in [0_i64, 1] {
let prefix = format!("\\tolerance=10000 \\pretolerance=10000 \\looseness={looseness} ");
let Some(reference) = pdftex_lines(&paragraph_fixture_with(text, width, &prefix)) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(text, f64::from(width), |style| {
style.tolerance = 10_000;
style.pretolerance = 10_000;
style.looseness = looseness;
});
assert_eq!(
ours.len(),
reference.len(),
"looseness {looseness} line count"
);
assert_lines_match(&format!("looseness {looseness}"), &ours, &reference);
}
}
/// Sentence punctuation changes the space factor, so the interword glue and /// Sentence punctuation changes the space factor, so the interword glue and
/// the resulting line breaks must match pdfLaTeX. /// the resulting line breaks must match pdfLaTeX.
#[test] #[test]
+4
View File
@@ -16,6 +16,7 @@ fn body_style() -> ParagraphStyle {
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
looseness: 0,
ragged_right: false, ragged_right: false,
hang_indent: 0, hang_indent: 0,
hang_after: 1, hang_after: 1,
@@ -186,6 +187,7 @@ fn route_d_page_matches_pdftex_raster_geometry() {
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
looseness: 0,
ragged_right: false, ragged_right: false,
hang_indent: 0, hang_indent: 0,
hang_after: 1, hang_after: 1,
@@ -365,6 +367,7 @@ fn route_d_two_pages_match_pdftex_raster_geometry() {
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
looseness: 0,
ragged_right: false, ragged_right: false,
hang_indent: 0, hang_indent: 0,
hang_after: 1, hang_after: 1,
@@ -670,6 +673,7 @@ fn route_d_multiline_bands_track_pdftex() {
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
looseness: 0,
ragged_right: false, ragged_right: false,
hang_indent: 0, hang_indent: 0,
hang_after: 1, hang_after: 1,
+5 -3
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`). 424 workspace tests are green and no oracle PDF opt-in with `?engine=route-d`). 426 workspace tests are green and no oracle
fixture is ignored. fixture is ignored.
Known gaps, in dependency order: Known gaps, in dependency order:
@@ -219,8 +219,10 @@ is added from 2000, and `\frenchspacing` switches it off; a 150pt punctuated
oracle fixture matches pdfLaTeX's line breaks and word positions. oracle fixture matches pdfLaTeX's line breaks and word positions.
`\looseness` adjusts the final line count inside TeX's `[1,9]` window and is `\looseness` adjusts the final line count inside TeX's `[1,9]` window and is
reverted when no feasible layout exists; 120pt and 200pt fixtures require one reverted when no feasible layout exists; a 120pt fixture requires one extra
extra line and match pdfLaTeX exactly. line and matches pdfLaTeX exactly. When the requested count is infeasible
TeX's own output picks an alternative optimum that route-D does not
reproduce; the infeasible case is covered by unit tests.
Interline spacing follows TeX: the first baseline sits at the paragraph's Interline spacing follows TeX: the first baseline sits at the paragraph's
ascent, each later baseline advances by `\baselineskip` when the resulting gap ascent, each later baseline advances by `\baselineskip` when the resulting gap
+2 -4
View File
@@ -140,9 +140,7 @@ and justification.
a zero code leaves the running factor unchanged, as in TeX. Explicit a zero code leaves the running factor unchanged, as in TeX. Explicit
`\spaceskip`/`\xspaceskip` replace the font glue, and hyphenation applies `\spaceskip`/`\xspaceskip` replace the font glue, and hyphenation applies
to a word's letter core so trailing punctuation does not suppress the to a word's letter core so trailing punctuation does not suppress the
pattern lookup (pdfTeX breaks `epsilon:` as `ep-`). `ParagraphStyle::ragged_right` models `\raggedright`: lines keep their natural width and fill greedily, because the infinite `fil` in `\rightskip` leaves no reason to stretch. `\looseness` shifts the paragraph by whole lines when pattern lookup (pdfTeX breaks `epsilon:` as `ep-`). `ParagraphStyle::ragged_right` models `\raggedright`: lines keep their natural width and fill greedily, because the infinite `fil` in `\rightskip` leaves no reason to stretch. `\looseness` asks for the natural line count shifted by up to nine lines (TeX's `[1,9]` window); the shift is kept only while a feasible layout exists at that count. When the requested count is infeasible pdfLaTeX can still emit a different alternative optimum; route-D keeps the ordinary optimum there, which the unit tests pin.
the requested count lies between one and nine lines away from the natural
count (the adjustment is reverted when no feasible layout exists).
Interline glue follows TeX: each baseline advances by `\baselineskip` when Interline glue follows TeX: each baseline advances by `\baselineskip` when
the resulting gap clears `\lineskiplimit`, otherwise by `\lineskip`; the resulting gap clears `\lineskiplimit`, otherwise by `\lineskip`;
`\parskip` is appended between paragraph units in the vertical list. When a `\parskip` is appended between paragraph units in the vertical list. When a
@@ -346,7 +344,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 288 unit tests plus seven route-D integration tests and twenty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 424 tests (288 route-D unit, 7 route-D integration, 24 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 3 binary units), with none ignored. v1 remains the live server path. The crate currently has 289 unit tests plus seven route-D integration tests and twenty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 426 tests (289 route-D unit, 7 route-D integration, 25 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 3 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo ### M0 incremental demo
+15 -1
View File
@@ -114,6 +114,7 @@ struct PageGeometry {
right_skip: Option<i64>, right_skip: Option<i64>,
tolerance: Option<i64>, tolerance: Option<i64>,
pretolerance: Option<i64>, pretolerance: Option<i64>,
looseness: Option<i64>,
emergency_stretch: Option<i64>, emergency_stretch: Option<i64>,
hang_indent: Option<i64>, hang_indent: Option<i64>,
hang_after: Option<i64>, hang_after: Option<i64>,
@@ -159,6 +160,8 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
geometry.tolerance = Some(value); geometry.tolerance = Some(value);
} else if let Some(value) = integer_assignment(trimmed, "pretolerance") { } else if let Some(value) = integer_assignment(trimmed, "pretolerance") {
geometry.pretolerance = Some(value); geometry.pretolerance = Some(value);
} else if let Some(value) = signed_integer_assignment(trimmed, "looseness") {
geometry.looseness = Some(value.clamp(-9, 9));
} else if let Some(value) = dimension_assignment(trimmed, "hangindent") { } else if let Some(value) = dimension_assignment(trimmed, "hangindent") {
geometry.hang_indent = Some(value); geometry.hang_indent = Some(value);
} else if let Some(value) = integer_assignment(trimmed, "hangafter") { } else if let Some(value) = integer_assignment(trimmed, "hangafter") {
@@ -256,6 +259,14 @@ fn integer_assignment(line: &str, name: &str) -> Option<i64> {
.map(|value| value.clamp(0, 10_000)) .map(|value| value.clamp(0, 10_000))
} }
/// Read a signed integer assignment such as `\\looseness=-1`.
fn signed_integer_assignment(line: &str, name: &str) -> Option<i64> {
let rest = line.strip_prefix('\\')?;
let rest = rest.strip_prefix(name)?;
let rest = rest.trim_start().strip_prefix('=')?;
rest.trim().parse::<i64>().ok()
}
fn dimension_assignment(line: &str, name: &str) -> Option<i64> { fn dimension_assignment(line: &str, name: &str) -> Option<i64> {
let rest = line.strip_prefix('\\')?; let rest = line.strip_prefix('\\')?;
let rest = rest.strip_prefix(name)?; let rest = rest.strip_prefix(name)?;
@@ -541,6 +552,7 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
left_skip: paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0), left_skip: paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0),
centered: paragraph.centered, centered: paragraph.centered,
right_aligned: paragraph.right_aligned, right_aligned: paragraph.right_aligned,
looseness: geometry.looseness.unwrap_or(0),
ragged_right: false, ragged_right: false,
right_skip: geometry.right_skip.unwrap_or(0), right_skip: geometry.right_skip.unwrap_or(0),
hang_indent: geometry.hang_indent.unwrap_or(0), hang_indent: geometry.hang_indent.unwrap_or(0),
@@ -725,13 +737,14 @@ mod source_tests {
#[test] #[test]
fn reads_hang_registers_from_the_preamble() { fn reads_hang_registers_from_the_preamble() {
let (body, geometry) = geometry_and_body( let (body, geometry) = geometry_and_body(
"\\hangindent=20pt\n\\hangafter=1\n\\tolerance=1000\n\\pretolerance=50\n\\spaceskip=6pt plus 1pt minus 0.5pt\n\\frenchspacing\n\nword word", "\\hangindent=20pt\n\\hangafter=1\n\\tolerance=1000\n\\pretolerance=50\n\\looseness=-1\n\\spaceskip=6pt plus 1pt minus 0.5pt\n\\frenchspacing\n\nword word",
); );
assert_eq!(geometry.hang_indent, Some(20 * 65_536)); assert_eq!(geometry.hang_indent, Some(20 * 65_536));
assert_eq!(geometry.hang_after, Some(1)); assert_eq!(geometry.hang_after, Some(1));
let pt = 65_536; let pt = 65_536;
assert_eq!(geometry.tolerance, Some(1000)); assert_eq!(geometry.tolerance, Some(1000));
assert_eq!(geometry.pretolerance, Some(50)); assert_eq!(geometry.pretolerance, Some(50));
assert_eq!(geometry.looseness, Some(-1));
assert_eq!(geometry.space_skip, Some((6 * pt, pt, pt / 2))); assert_eq!(geometry.space_skip, Some((6 * pt, pt, pt / 2)));
assert_eq!(geometry.french_spacing, Some(true)); assert_eq!(geometry.french_spacing, Some(true));
let paragraphs = paragraphs(&body).expect("paragraphs"); let paragraphs = paragraphs(&body).expect("paragraphs");
@@ -742,6 +755,7 @@ mod source_tests {
assert_eq!(style.hang_after, 1); assert_eq!(style.hang_after, 1);
assert_eq!(style.tolerance, 1000); assert_eq!(style.tolerance, 1000);
assert_eq!(style.pretolerance, 50); assert_eq!(style.pretolerance, 50);
assert_eq!(style.looseness, -1);
assert_eq!(style.space_skip, Some((6 * pt, pt, pt / 2))); assert_eq!(style.space_skip, Some((6 * pt, pt, pt / 2)));
assert!(style.frenchspacing); assert!(style.frenchspacing);
} }