From a6397fcfef1e7ee251bcd0aabb4db9a6e1bc9fb4 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 13:46:32 +0800 Subject: [PATCH] Honour TeX looseness when an alternative line count exists --- crates/texrra-tex-core/src/paragraph.rs | 253 +++++++++++++++--------- crates/texrra-tex-core/tests/oracle.rs | 31 +++ crates/texrra-tex-core/tests/route_d.rs | 4 + docs/ROUTE_D_PLAN.md | 8 +- docs/TEX_CORE.md | 6 +- src/route_d.rs | 16 +- 6 files changed, 219 insertions(+), 99 deletions(-) diff --git a/crates/texrra-tex-core/src/paragraph.rs b/crates/texrra-tex-core/src/paragraph.rs index f0523b7..6fcf01c 100755 --- a/crates/texrra-tex-core/src/paragraph.rs +++ b/crates/texrra-tex-core/src/paragraph.rs @@ -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> = 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; 8]> = vec![[None; 8]; count]; - best[0][2] = Some(Candidate { + let mut best: Vec<[Vec; 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"); + } } diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index 3453354..adaa1ae 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -151,6 +151,7 @@ fn route_d_lines_with( right_skip: 0, centered: false, right_aligned: false, + looseness: 0, par_indent: 0, line_height: 12 * PT, ..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(¶graph_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 /// the resulting line breaks must match pdfLaTeX. #[test] diff --git a/crates/texrra-tex-core/tests/route_d.rs b/crates/texrra-tex-core/tests/route_d.rs index 3176f5b..499a57f 100755 --- a/crates/texrra-tex-core/tests/route_d.rs +++ b/crates/texrra-tex-core/tests/route_d.rs @@ -16,6 +16,7 @@ fn body_style() -> ParagraphStyle { right_skip: 0, centered: false, right_aligned: false, + looseness: 0, ragged_right: false, hang_indent: 0, hang_after: 1, @@ -186,6 +187,7 @@ fn route_d_page_matches_pdftex_raster_geometry() { right_skip: 0, centered: false, right_aligned: false, + looseness: 0, ragged_right: false, hang_indent: 0, hang_after: 1, @@ -365,6 +367,7 @@ fn route_d_two_pages_match_pdftex_raster_geometry() { right_skip: 0, centered: false, right_aligned: false, + looseness: 0, ragged_right: false, hang_indent: 0, hang_after: 1, @@ -670,6 +673,7 @@ fn route_d_multiline_bands_track_pdftex() { right_skip: 0, centered: false, right_aligned: false, + looseness: 0, ragged_right: false, hang_indent: 0, hang_after: 1, diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index b87d591..8e78800 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -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`). 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. 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. `\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 -extra line and match pdfLaTeX exactly. +reverted when no feasible layout exists; a 120pt fixture requires one extra +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 ascent, each later baseline advances by `\baselineskip` when the resulting gap diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 553858a..d24f017 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -140,9 +140,7 @@ and justification. a zero code leaves the running factor unchanged, as in TeX. Explicit `\spaceskip`/`\xspaceskip` replace the font glue, and hyphenation applies 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 - the requested count lies between one and nine lines away from the natural - count (the adjustment is reverted when no feasible layout exists). + 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. Interline glue follows TeX: each baseline advances by `\baselineskip` when the resulting gap clears `\lineskiplimit`, otherwise by `\lineskip`; `\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. -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 diff --git a/src/route_d.rs b/src/route_d.rs index 786b3a7..092e7da 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -114,6 +114,7 @@ struct PageGeometry { right_skip: Option, tolerance: Option, pretolerance: Option, + looseness: Option, emergency_stretch: Option, hang_indent: Option, hang_after: Option, @@ -159,6 +160,8 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { geometry.tolerance = Some(value); } else if let Some(value) = integer_assignment(trimmed, "pretolerance") { 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") { geometry.hang_indent = Some(value); } else if let Some(value) = integer_assignment(trimmed, "hangafter") { @@ -256,6 +259,14 @@ fn integer_assignment(line: &str, name: &str) -> Option { .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 { + let rest = line.strip_prefix('\\')?; + let rest = rest.strip_prefix(name)?; + let rest = rest.trim_start().strip_prefix('=')?; + rest.trim().parse::().ok() +} + fn dimension_assignment(line: &str, name: &str) -> Option { let rest = line.strip_prefix('\\')?; 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), centered: paragraph.centered, right_aligned: paragraph.right_aligned, + looseness: geometry.looseness.unwrap_or(0), ragged_right: false, right_skip: geometry.right_skip.unwrap_or(0), hang_indent: geometry.hang_indent.unwrap_or(0), @@ -725,13 +737,14 @@ mod source_tests { #[test] fn reads_hang_registers_from_the_preamble() { 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_after, Some(1)); let pt = 65_536; assert_eq!(geometry.tolerance, Some(1000)); 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.french_spacing, Some(true)); let paragraphs = paragraphs(&body).expect("paragraphs"); @@ -742,6 +755,7 @@ mod source_tests { assert_eq!(style.hang_after, 1); assert_eq!(style.tolerance, 1000); assert_eq!(style.pretolerance, 50); + assert_eq!(style.looseness, -1); assert_eq!(style.space_skip, Some((6 * pt, pt, pt / 2))); assert!(style.frenchspacing); }