diff --git a/crates/texrra-tex-core/src/paragraph.rs b/crates/texrra-tex-core/src/paragraph.rs index 24a51f7..f0523b7 100755 --- a/crates/texrra-tex-core/src/paragraph.rs +++ b/crates/texrra-tex-core/src/paragraph.rs @@ -20,6 +20,9 @@ pub enum HorizontalItem { width: i64, stretch: i64, shrink: i64, + /// TeX glue order: 0 normal, 1 fil, 2 fill, 3 filll. + #[serde(default)] + order: u8, }, Penalty { width: i64, @@ -364,6 +367,7 @@ pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec { width: style.space_width, stretch: style.space_stretch, shrink: style.space_shrink, + order: 0, }); } } else { @@ -477,6 +481,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra let mut natural = 0_i64; let mut stretch = 0_i64; let mut shrink = 0_i64; + let mut stretch_by_order = [0_i64; 4]; let mut has_box = false; let mut trailing_penalty = 0_i64; for (offset, item) in items[start..end].iter().enumerate() { @@ -489,13 +494,18 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra width, stretch: stretch_amount, shrink: shrink_amount, + order, + .. } => { if start + offset + 1 == end { continue; } natural += *width; - stretch += *stretch_amount; shrink += *shrink_amount; + match *order { + 0 => stretch += *stretch_amount, + order => stretch_by_order[order as usize] += *stretch_amount, + } } HorizontalItem::Penalty { penalty, .. } => trailing_penalty = *penalty, HorizontalItem::Discretionary { @@ -537,9 +547,12 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra 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 stretch > 0 { + 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 { @@ -587,7 +600,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra } else { 3 }; - let fitness = if natural < target && stretch == 0 { + let fitness = if natural < target && stretch == 0 && infinite_order.is_none() { 3 } else { fitness @@ -673,6 +686,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra let mut natural = 0_i64; let mut stretch = 0_i64; let mut shrink = 0_i64; + let mut stretch_by_order = [0_i64; 4]; let mut has_box = false; for (offset, item) in items[start..end].iter().enumerate() { let last_item = start + offset + 1 == end; @@ -685,13 +699,18 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra width, stretch: stretch_amount, shrink: shrink_amount, + order, + .. } => { if last_item { continue; } natural += *width; - stretch += *stretch_amount; shrink += *shrink_amount; + match *order { + 0 => stretch += *stretch_amount, + order => stretch_by_order[order as usize] += *stretch_amount, + } } HorizontalItem::Penalty { .. } => {} HorizontalItem::Discretionary { @@ -717,10 +736,13 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra if overflow.is_none() && natural >= target { overflow = Some(end_index); } + let infinite_order = (1..4).rev().find(|order| stretch_by_order[*order] > 0); let mut badness = if final_line && style.par_fillskip_fil && natural <= target { 0 } else if natural < target { - if stretch > 0 { + if infinite_order.is_some() { + 0 + } else if stretch > 0 { (100.0 * ((target - natural) as f64 / stretch as f64).powi(3)) .round() .min(10_000.0) as i64 @@ -799,6 +821,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra // glue, so the shipped line (and therefore the PDF) is flush. let target = style.line_target(line_index); let (mut natural, mut stretch, mut shrink) = (0_i64, 0_i64, 0_i64); + let mut stretch_by_order = [0_i64; 4]; for item in &line { match item { HorizontalItem::Box(box_item) => natural += box_item.width, @@ -806,10 +829,15 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra width, stretch: stretch_amount, shrink: shrink_amount, + order, + .. } => { natural += *width; - stretch += *stretch_amount; shrink += *shrink_amount; + match *order { + 0 => stretch += *stretch_amount, + order => stretch_by_order[order as usize] += *stretch_amount, + } } HorizontalItem::Penalty { width, .. } => natural += *width, HorizontalItem::Discretionary { .. } => {} @@ -839,18 +867,28 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra } else { (target - natural).max(-shrink) }; + let infinite_order = (1..4).rev().find(|order| stretch_by_order[*order] > 0); + let chosen_order = infinite_order.unwrap_or(0); + let chosen_stretch = if chosen_order == 0 { + stretch + } else { + stretch_by_order[chosen_order as usize] + }; if delta > 0 { - if !is_last || !style.par_fillskip_fil { + if !is_last || !style.par_fillskip_fil || infinite_order.is_some() { let mut remaining = delta; for item in &mut line { if let HorizontalItem::Glue { width, stretch: stretch_amount, + order, .. } = item + && *order == chosen_order as u8 && *stretch_amount > 0 + && chosen_stretch > 0 { - let share = delta * *stretch_amount / stretch; + let share = delta * *stretch_amount / chosen_stretch; *width += share; remaining -= share; } @@ -987,8 +1025,9 @@ pub fn text_items_with_font( // `\sfcode`; it scales the next interword glue (and adds `\fontdimen7` // once it reaches 2000). let mut space_factor = 1000_i64; + let mut after_control_word = false; for (word_index, word) in words.iter().enumerate() { - if word_index > 0 { + if word_index > 0 && !after_control_word { let factor = space_factor.max(1000); // TeX's `\spaceskip`/`\xspaceskip` replace the font's interword // glue; the space factor still scales stretch and shrink, and @@ -1020,11 +1059,25 @@ pub fn text_items_with_font( width, stretch, shrink, + order: 0, }); // TeX never kerns across interword glue. previous_box = None; previous_character = None; } + if matches!(*word, "\\hfill" | "\\hfil") { + items.push(HorizontalItem::Glue { + width: 0, + stretch: 1, + shrink: 0, + order: if *word == "\\hfill" { 2 } else { 1 }, + }); + previous_box = None; + previous_character = None; + after_control_word = true; + continue; + } + after_control_word = false; let original: Vec = word.chars().collect(); // TeX hyphenates the letter run of a word: leading or trailing // punctuation stays on the word and does not suppress the pattern @@ -1795,6 +1848,7 @@ mod tests { width, stretch, shrink, + .. } => Some((*width, *stretch, *shrink)), _ => None, }) @@ -1858,6 +1912,7 @@ mod tests { width, stretch, shrink, + .. } => Some((*width, *stretch, *shrink)), _ => None, }) @@ -1883,6 +1938,7 @@ mod tests { width, stretch, shrink, + .. } => Some((*width, *stretch, *shrink)), _ => None, }) @@ -1930,6 +1986,7 @@ mod tests { width, stretch, shrink, + .. } => Some((*width, *stretch, *shrink)), _ => None, }) @@ -1938,4 +1995,67 @@ mod tests { assert_eq!(stretch, font.stretch()); assert_eq!(shrink, font.shrink()); } + + #[test] + fn hfill_absorbs_the_line_stretch() { + let font = crate::cmr10::Cmr10Metrics::Roman; + let style = ParagraphStyle { + line_width: 200 * 65_536, + par_indent: 0, + line_height: 12 * 65_536, + ..ParagraphStyle::default() + }; + let paragraph = layout_paragraph_with_font("A \\hfill B", &style, &font); + assert_eq!(paragraph.lines.len(), 1); + let line = ¶graph.lines[0]; + let fill = line + .iter() + .filter(|item| matches!(item, HorizontalItem::Glue { order: 2, .. })) + .count(); + assert_eq!(fill, 1, "\\hfill should be one fill-order glue"); + let width: i64 = line + .iter() + .map(|item| match item { + HorizontalItem::Box(box_) => box_.width, + HorizontalItem::Glue { width, .. } => *width, + HorizontalItem::Penalty { width, .. } => *width, + HorizontalItem::Discretionary { .. } => 0, + }) + .sum(); + assert_eq!(width, 200 * 65_536); + } + + #[test] + fn fill_glue_wins_over_fil() { + let font = crate::cmr10::Cmr10Metrics::Roman; + let style = ParagraphStyle { + line_width: 300 * 65_536, + par_indent: 0, + line_height: 12 * 65_536, + ..ParagraphStyle::default() + }; + let paragraph = layout_paragraph_with_font("A \\hfil B \\hfill C", &style, &font); + assert_eq!(paragraph.lines.len(), 1); + let line = ¶graph.lines[0]; + let fil: i64 = line + .iter() + .filter_map(|item| match item { + HorizontalItem::Glue { + width, order: 1, .. + } => Some(*width), + _ => None, + }) + .sum(); + let fill: i64 = line + .iter() + .filter_map(|item| match item { + HorizontalItem::Glue { + width, order: 2, .. + } => Some(*width), + _ => None, + }) + .sum(); + assert_eq!(fil, 0, "\\hfil must stay at its natural width"); + assert!(fill > 0, "\\hfill must absorb the whole page set"); + } } diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index 401ae4a..3453354 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -795,3 +795,13 @@ fn leftskip_matches_pdftex() { style.left_skip = 20 * 65_536; }); } + +#[test] +fn hfill_matches_pdftex() { + compare_fixture_with("alpha \\hfill beta", 150, "", |_| {}); +} + +#[test] +fn hfill_and_hfil_match_pdftex() { + compare_fixture_with("alpha \\hfil beta \\hfill gamma", 150, "", |_| {}); +} diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 301c512..96a5483 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`). 413 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 417 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -59,9 +59,9 @@ Known gaps, in dependency order: `\hangindent`/`\hangafter`/`\parshape` line geometry, `\parfillskip` with or without `fil`, default `\sfcode` sentence spacing, `\looseness`, and `\baselineskip`/`\lineskip`/`\parskip` interline - glue), custom `\sfcode` overrides, explicit `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip` fil), but not -yet generic `fil`/`fill` glue - orders or `\prevgraf`; + glue), custom `\sfcode` overrides, explicit `\spaceskip`/`\xspaceskip`, + `\raggedright` (infinite `\rightskip` fil), and explicit + `\hfil`/`\hfill` glue orders, but not yet `\prevgraf`; 2. the default builder is still the scrolling builder with fraction policies, now with line-level paragraph splits; `page::PageBuilder` implements the candidate-breakpoint cost model (badness + penalty, glue @@ -228,7 +228,7 @@ not fit is split at line boundaries: the next fragment continues on the next page without a `\parskip`, and a single unsplittable line may overflow at the top of a page (see `Paragraph::split_at`). -Still open: generic `fil`/`fill` glue orders, `\prevgraf`, explicit +Still open: `\prevgraf`, explicit `\vskip` classes (`\smallskip` and friends), double/final hyphen demerit oracle fixtures. The breaker now rejects overfull lines outside the emergency pass, exactly like TeX, so `\tolerance` cannot diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 7f3fc45..57afc3c 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -115,7 +115,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, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip` and vertical-glue fixtures; generic fil glue and `\prevgraf` 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, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders and vertical-glue fixtures; `\prevgraf` 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; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets later pages when the document has no insertions or floats), insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments for the duration of the routine, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `PageFragment::penalty` carries the break penalty, and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine | | 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 | @@ -346,7 +346,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 282 unit tests plus seven route-D integration tests and twenty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 413 tests (282 route-D unit, 7 route-D integration, 22 oracle, 71 v1 integration, 24 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 284 unit tests plus seven route-D integration tests and twenty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 417 tests (284 route-D unit, 7 route-D integration, 24 oracle, 71 v1 integration, 24 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo