Support ragged-right paragraphs with an infinite rightskip

This commit is contained in:
gloamxun committed 2026-10-23 04:08:32 +08:00
1 parent f488dd3b6c
commit 448152cea4
7 files changed
+81 -10

No files matched your search

+1 -1
View File
@@ -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`. 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 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 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 page body through `pdf::PageOrigin`, leaving the sheet size unchanged, while
`Document::paper_width`/`paper_height` (`\paperwidth`/`\paperheight`, default US `Document::paper_width`/`paper_height` (`\paperwidth`/`\paperheight`, default US
Letter) set the MediaBox and the preview page box; the route-D endpoints read Letter) set the MediaBox and the preview page box; the route-D endpoints read
+60 -3
View File
@@ -116,6 +116,10 @@ pub struct ParagraphStyle {
pub centered: bool, pub centered: bool,
#[serde(default)] #[serde(default)]
pub right_aligned: bool, 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, pub par_indent: i64,
/// Extra stretch added to every line when TeX's emergency pass runs /// Extra stretch added to every line when TeX's emergency pass runs
/// (`\emergencystretch`). /// (`\emergencystretch`).
@@ -246,6 +250,7 @@ impl Default for ParagraphStyle {
lineskiplimit: 0, lineskiplimit: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
ragged_right: false,
par_indent: 0, par_indent: 0,
emergencystretch: 0, emergencystretch: 0,
pretolerance: 100, pretolerance: 100,
@@ -533,7 +538,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
}; };
let target = style.line_target(node.line); let target = style.line_target(node.line);
let stretch = stretch + extra_stretch; let stretch = stretch + extra_stretch;
let (ratio, badness) = if natural < target { let (mut ratio, mut badness) = if natural < target {
if stretch > 0 { if stretch > 0 {
let ratio = (target - natural) as f64 / stretch as f64; let ratio = (target - natural) as f64 / stretch as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64) (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 { } else {
(0.0, 0) (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 // TeX's default final line has \parfillskip's infinite
// stretch; without fil the last line is set like any other. // stretch; without fil the last line is set like any other.
let badness = if is_last && style.par_fillskip_fil && natural <= target { 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; 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(|| { let mut ranges = solution.unwrap_or_else(|| {
// TeX's final pass forces an overfull break only as a last resort. // TeX's final pass forces an overfull break only as a last resort.
// Emulate that choice: take the longest prefix that still satisfies // 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 { if overflow.is_none() && natural >= target {
overflow = Some(end_index); 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 0
} else if natural < target { } else if natural < target {
if stretch > 0 { if stretch > 0 {
@@ -717,6 +734,9 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
} else { } else {
10_000 10_000
}; };
if style.ragged_right && natural <= target {
badness = 0;
}
if badness <= style.tolerance { if badness <= style.tolerance {
feasible = Some(end_index); 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 // glue beyond its limits. A final line with a `fil` parfillskip only
// shrinks: the infinite stretch absorbs any shortfall, so only a // shrinks: the infinite stretch absorbs any shortfall, so only a
// line wider than the measure adjusts its finite glue. // 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 delta > 0 {
if !is_last || !style.par_fillskip_fil { if !is_last || !style.par_fillskip_fil {
let mut remaining = delta; 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] #[test]
fn words_break_at_glue_and_lines_are_justified() { fn words_break_at_glue_and_lines_are_justified() {
let style = ParagraphStyle { let style = ParagraphStyle {
+9
View File
@@ -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 /// `\hangindent`/`\hangafter` shift the affected lines and narrow their
/// measure exactly like pdfLaTeX. /// measure exactly like 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,
ragged_right: false,
hang_indent: 0, hang_indent: 0,
hang_after: 1, hang_after: 1,
par_shape: Vec::new(), par_shape: Vec::new(),
@@ -185,6 +186,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,
ragged_right: false,
hang_indent: 0, hang_indent: 0,
hang_after: 1, hang_after: 1,
par_shape: Vec::new(), par_shape: Vec::new(),
@@ -363,6 +365,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,
ragged_right: false,
hang_indent: 0, hang_indent: 0,
hang_after: 1, hang_after: 1,
par_shape: Vec::new(), par_shape: Vec::new(),
@@ -667,6 +670,7 @@ fn route_d_multiline_bands_track_pdftex() {
right_skip: 0, right_skip: 0,
centered: false, centered: false,
right_aligned: false, right_aligned: false,
ragged_right: false,
hang_indent: 0, hang_indent: 0,
hang_after: 1, hang_after: 1,
par_shape: Vec::new(), par_shape: Vec::new(),
+2 -2
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`). 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. fixture is ignored.
Known gaps, in dependency order: Known gaps, in dependency order:
@@ -59,7 +59,7 @@ Known gaps, in dependency order:
`\hangindent`/`\hangafter`/`\parshape` line geometry, `\parfillskip` `\hangindent`/`\hangafter`/`\parshape` line geometry, `\parfillskip`
with or without `fil`, default `\sfcode` sentence spacing, with or without `fil`, default `\sfcode` sentence spacing,
`\looseness`, and `\baselineskip`/`\lineskip`/`\parskip` interline `\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 yet generic `fil`/`fill` glue
orders or `\prevgraf`; orders or `\prevgraf`;
2. the default builder is still the scrolling builder with fraction 2. the default builder is still the scrolling builder with fraction
+4 -4
View File
@@ -115,7 +115,7 @@ and justification.
| Milestone | Content | Acceptance | | Milestone | Content | Acceptance |
| --- | --- | --- | | --- | --- | --- |
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 | | 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 | | 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 | | 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 | | 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 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-`). `\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 the requested count lies between one and nine lines away from the natural
count (the adjustment is reverted when no feasible layout exists). 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
@@ -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. 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 ### M0 incremental demo
@@ -375,7 +375,7 @@ deliberately open rather than approximated:
`\hyphenation` exceptions, `\hangindent`/`\parshape`, `\parfillskip` with `\hyphenation` exceptions, `\hangindent`/`\parshape`, `\parfillskip` with
or without `fil`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` or without `fil`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip`
interline glue, the default `\sfcode`/`\frenchspacing` sentence spacing, 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` - **M2**: the scrolling builder still drives `Document`; `page::PageBuilder`
implements TeX's candidate-breakpoint cost (badness + penalty, glue implements TeX's candidate-breakpoint cost (badness + penalty, glue
stretch/shrink, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it stretch/shrink, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it
+1
View File
@@ -409,6 +409,7 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
left_skip: paragraph.left_skip * SCALE, left_skip: paragraph.left_skip * SCALE,
centered: paragraph.centered, centered: paragraph.centered,
right_aligned: paragraph.right_aligned, right_aligned: paragraph.right_aligned,
ragged_right: false,
right_skip: 0, right_skip: 0,
hang_indent: 0, hang_indent: 0,
hang_after: 1, hang_after: 1,