From 448152cea46ba49f7f934c5119a58767d2977c1b Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 04:08:32 +0800 Subject: [PATCH] Support ragged-right paragraphs with an infinite rightskip --- README.md | 2 +- crates/texrra-tex-core/src/paragraph.rs | 63 +++++++++++++++++++++++-- crates/texrra-tex-core/tests/oracle.rs | 9 ++++ crates/texrra-tex-core/tests/route_d.rs | 4 ++ docs/ROUTE_D_PLAN.md | 4 +- docs/TEX_CORE.md | 8 ++-- src/route_d.rs | 1 + 7 files changed, 81 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 344269e..4af07ad 100644 --- a/README.md +++ b/README.md @@ -589,7 +589,7 @@ execution, service and incrementality targets) is in The first M7 service integration is available as `POST /api/route-d/preview`, with PDF export at `POST /api/route-d/pdf`. It accepts blank-line-separated source with a small `\section`/`\textbf`/`\emph`/display-math/list subset, lays it out with the route-D page builder, and returns the v1-compatible preview shape plus per-page hashes and -SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, the breaker follows TeX's `\pretolerance`/`\tolerance`/`\emergencystretch` passes with demerits (falling back to TeX's overfull fill when no feasible break exists), and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. Non-final lines bake their justification into the glue widths, so the PDF and the SVG preview are flush to the measure instead of showing natural spaces. Interline spacing follows TeX (`\baselineskip` unless `\lineskiplimit` forces `\lineskip`), and `Document::par_skip` adds `\parskip` between paragraph units. `page::PageBuilder` selects page breaks by TeX's badness-plus-penalty cost, including glue setting, `\topskip` and `Document::max_depth` (`\maxdepth`), and breaks ties toward the page closest to the goal; `Engine::layout_paged` exposes it for documents whose units are single vertical items; insertion classes are placed through the same builder, with per-class limits and held-over material, while the scrolling builder remains the default until bottom/in-text floats gain a paged equivalent; paged layouts replay edits from the edited page, falling back to a full rebuild when insertions or an `\output` routine are present. `Document::output_routine` runs an interpreted `\output` program (`\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum` and `\ifodd` over page registers; `\pageno`, `\outputpenalty` and `\deadcycles` are readable, and each page fragment records the penalty that broke it) over those paged fragments, so a routine can drop pages it does not ship, or ship only the pages it wants based on the break penalty or page number. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. `Document::h_offset` and `v_offset` (`\hoffset`/`\voffset`) shift the exported +SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, the breaker follows TeX's `\pretolerance`/`\tolerance`/`\emergencystretch` passes with demerits (falling back to TeX's overfull fill when no feasible break exists), and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. Non-final lines bake their justification into the glue widths, so the PDF and the SVG preview are flush to the measure instead of showing natural spaces; with `\raggedright` (`ParagraphStyle::ragged_right`) lines keep their natural widths and fill greedily, because `\rightskip` carries an infinite `fil`. Interline spacing follows TeX (`\baselineskip` unless `\lineskiplimit` forces `\lineskip`), and `Document::par_skip` adds `\parskip` between paragraph units. `page::PageBuilder` selects page breaks by TeX's badness-plus-penalty cost, including glue setting, `\topskip` and `Document::max_depth` (`\maxdepth`), and breaks ties toward the page closest to the goal; `Engine::layout_paged` exposes it for documents whose units are single vertical items; insertion classes are placed through the same builder, with per-class limits and held-over material, while the scrolling builder remains the default until bottom/in-text floats gain a paged equivalent; paged layouts replay edits from the edited page, falling back to a full rebuild when insertions or an `\output` routine are present. `Document::output_routine` runs an interpreted `\output` program (`\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum` and `\ifodd` over page registers; `\pageno`, `\outputpenalty` and `\deadcycles` are readable, and each page fragment records the penalty that broke it) over those paged fragments, so a routine can drop pages it does not ship, or ship only the pages it wants based on the break penalty or page number. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. `Document::h_offset` and `v_offset` (`\hoffset`/`\voffset`) shift the exported page body through `pdf::PageOrigin`, leaving the sheet size unchanged, while `Document::paper_width`/`paper_height` (`\paperwidth`/`\paperheight`, default US Letter) set the MediaBox and the preview page box; the route-D endpoints read diff --git a/crates/texrra-tex-core/src/paragraph.rs b/crates/texrra-tex-core/src/paragraph.rs index f861e8f..c148bfc 100755 --- a/crates/texrra-tex-core/src/paragraph.rs +++ b/crates/texrra-tex-core/src/paragraph.rs @@ -116,6 +116,10 @@ pub struct ParagraphStyle { pub centered: bool, #[serde(default)] pub right_aligned: bool, + /// Ragged-right setting (`\raggedright`): lines keep their natural width + /// and the missing space is absorbed by an infinite `\rightskip`. + #[serde(default)] + pub ragged_right: bool, pub par_indent: i64, /// Extra stretch added to every line when TeX's emergency pass runs /// (`\emergencystretch`). @@ -246,6 +250,7 @@ impl Default for ParagraphStyle { lineskiplimit: 0, centered: false, right_aligned: false, + ragged_right: false, par_indent: 0, emergencystretch: 0, pretolerance: 100, @@ -533,7 +538,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra }; let target = style.line_target(node.line); let stretch = stretch + extra_stretch; - let (ratio, badness) = if natural < target { + let (mut ratio, mut 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) @@ -550,6 +555,12 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra } 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 { @@ -631,6 +642,12 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra break; } } + // With an infinite `fil` in `\rightskip` every line that fits has zero + // badness, so TeX fills each line greedily; the demerits search would + // instead pick the shortest first line among the equal-cost solutions. + if style.ragged_right { + solution = None; + } let mut ranges = solution.unwrap_or_else(|| { // TeX's final pass forces an overfull break only as a last resort. // Emulate that choice: take the longest prefix that still satisfies @@ -700,7 +717,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra if overflow.is_none() && natural >= target { overflow = Some(end_index); } - let badness = if final_line && style.par_fillskip_fil && natural <= target { + let mut badness = if final_line && style.par_fillskip_fil && natural <= target { 0 } else if natural < target { if stretch > 0 { @@ -717,6 +734,9 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra } else { 10_000 }; + if style.ragged_right && natural <= target { + badness = 0; + } if badness <= style.tolerance { feasible = Some(end_index); } @@ -814,7 +834,11 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra // glue beyond its limits. A final line with a `fil` parfillskip only // shrinks: the infinite stretch absorbs any shortfall, so only a // line wider than the measure adjusts its finite glue. - let delta = (target - natural).max(-shrink); + let delta = if style.ragged_right { + (target - natural).min(0).max(-shrink) + } else { + (target - natural).max(-shrink) + }; if delta > 0 { if !is_last || !style.par_fillskip_fil { let mut remaining = delta; @@ -1217,6 +1241,39 @@ mod tests { ); } + #[test] + fn ragged_right_leaves_lines_at_their_natural_width() { + let width = |line: &[HorizontalItem]| -> i64 { + line.iter() + .map(|item| match item { + HorizontalItem::Box(box_item) => box_item.width, + HorizontalItem::Glue { width, .. } => *width, + HorizontalItem::Penalty { width, .. } => *width, + HorizontalItem::Discretionary { .. } => 0, + }) + .sum() + }; + let style = |ragged_right: bool| ParagraphStyle { + line_width: 200, + par_fillskip_fil: false, + ragged_right, + ..ParagraphStyle::default() + }; + let justified = layout_paragraph("alpha beta", &style(false)); + let ragged = layout_paragraph("alpha beta", &style(true)); + assert_eq!(justified.lines.len(), 1); + assert_eq!( + width(&justified.lines[0]), + 200, + "justified line fills the measure" + ); + assert_eq!( + width(&ragged.lines[0]), + 94, + "ragged line keeps its natural width" + ); + } + #[test] fn words_break_at_glue_and_lines_are_justified() { let style = ParagraphStyle { diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index 0762978..8f79df8 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -384,6 +384,15 @@ fn hyphen_penalty_inhibits_hyphenation() { }); } +/// `\raggedright` leaves an infinite `fil` in `\rightskip`, so lines stop at +/// their natural widths instead of stretching to the measure. +#[test] +fn ragged_right_matches_pdftex() { + compare_fixture_with(WORDS, 150, "\\raggedright ", |style| { + style.ragged_right = true; + }); +} + /// `\hangindent`/`\hangafter` shift the affected lines and narrow their /// measure exactly like pdfLaTeX. #[test] diff --git a/crates/texrra-tex-core/tests/route_d.rs b/crates/texrra-tex-core/tests/route_d.rs index 4081a36..3176f5b 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, + ragged_right: false, hang_indent: 0, hang_after: 1, par_shape: Vec::new(), @@ -185,6 +186,7 @@ fn route_d_page_matches_pdftex_raster_geometry() { right_skip: 0, centered: false, right_aligned: false, + ragged_right: false, hang_indent: 0, hang_after: 1, par_shape: Vec::new(), @@ -363,6 +365,7 @@ fn route_d_two_pages_match_pdftex_raster_geometry() { right_skip: 0, centered: false, right_aligned: false, + ragged_right: false, hang_indent: 0, hang_after: 1, par_shape: Vec::new(), @@ -667,6 +670,7 @@ fn route_d_multiline_bands_track_pdftex() { right_skip: 0, centered: false, right_aligned: false, + ragged_right: false, hang_indent: 0, hang_after: 1, par_shape: Vec::new(), diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 4799e42..dbe678c 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`). 377 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 379 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -59,7 +59,7 @@ 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`, but not + glue), custom `\sfcode` overrides, explicit `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip` fil), but not yet generic `fil`/`fill` glue orders or `\prevgraf`; 2. the default builder is still the scrolling builder with fraction diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 43026b8..0022cba 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`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode` 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` and vertical-glue fixtures; generic fil glue and `\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, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep` and a `\bottomfraction` cap) 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 registers and `PageFragment::penalty` carries the break penalty | | 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 | @@ -140,7 +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-`). `\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` 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). Interline glue follows TeX: each baseline advances by `\baselineskip` when @@ -342,7 +342,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 254 unit tests plus seven route-D integration tests and sixteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 377 tests (254 route-D unit, 7 route-D integration, 16 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 255 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 379 tests (255 route-D unit, 7 route-D integration, 17 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -375,7 +375,7 @@ deliberately open rather than approximated: `\hyphenation` exceptions, `\hangindent`/`\parshape`, `\parfillskip` with or without `fil`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, the default `\sfcode`/`\frenchspacing` sentence spacing, - and explicit `\spaceskip`/`\xspaceskip` are modelled. + explicit `\spaceskip`/`\xspaceskip`, and `\raggedright` (infinite `\rightskip` fil) are modelled. - **M2**: the scrolling builder still drives `Document`; `page::PageBuilder` implements TeX's candidate-breakpoint cost (badness + penalty, glue stretch/shrink, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it diff --git a/src/route_d.rs b/src/route_d.rs index e85ac54..5f18353 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -409,6 +409,7 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document { left_skip: paragraph.left_skip * SCALE, centered: paragraph.centered, right_aligned: paragraph.right_aligned, + ragged_right: false, right_skip: 0, hang_indent: 0, hang_after: 1,