From e632db02cf1da575753fdd0dd7bc96a5419edc79 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 12:15:27 +0800 Subject: [PATCH] Start held-over insertions with splittopskip --- README.md | 2 +- crates/texrra-tex-core/src/lib.rs | 68 +++++++++++++++++++++++++++++++ docs/ROUTE_D_PLAN.md | 5 ++- docs/TEX_CORE.md | 4 +- 4 files changed, 74 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 210a124..217be4d 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; 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 with TeX orders (normal/`\vfil`/`\vfill`/`\vfilll`), `\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 and how much stretch each glue order carries, so `\pagefilstretch`, `\pagefillstretch` and `\pagefilllstretch` are readable) 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 with TeX orders (normal/`\vfil`/`\vfill`/`\vfilll`), `\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, held-over material and `Document::split_top_skip` (`\splittopskip`, default 10pt) at the top of each continuation, 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 and how much stretch each glue order carries, so `\pagefilstretch`, `\pagefillstretch` and `\pagefilllstretch` are readable) 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/lib.rs b/crates/texrra-tex-core/src/lib.rs index f9268ad..63067ec 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -630,6 +630,10 @@ pub struct Document { /// first insertion class on a page. Zero by default for compatibility. #[serde(default)] pub insertion_skip: i64, + /// TeX's `\splittopskip`: glue placed at the top of insertion material + /// carried over to the next page. Defaults to 10pt. + #[serde(default = "default_split_top_skip")] + pub split_top_skip: i64, /// TeX floatsep: vertical space between two floats of the same placement /// on one page. Defaults to 12pt. #[serde(default = "default_float_sep")] @@ -673,6 +677,10 @@ fn default_float_sep() -> i64 { 12 * 65_536 } +fn default_split_top_skip() -> i64 { + 10 * 65_536 +} + fn default_text_float_sep() -> i64 { 20 * 65_536 } @@ -724,6 +732,7 @@ impl Document { total_number: default_total_number(), insertion_classes: Vec::new(), insertion_skip: 0, + split_top_skip: default_split_top_skip(), float_sep: default_float_sep(), text_float_sep: default_text_float_sep(), in_text_sep: default_in_text_sep(), @@ -920,6 +929,27 @@ fn item_height(item: &VerticalItem) -> i64 { /// Returns `(accepted, remainder, reserved_height)`. A single item larger than /// the capacity is still accepted alone: TeX only splits insertion material at /// item boundaries. +/// TeX starts a split insertion's continuation with `\splittopskip`. Only add +/// the glue when the class capacity can also hold the first content item; +/// otherwise a class with no remaining capacity would accept the glue forever +/// and never make progress. +fn held_insertion_material( + document: &Document, + capacity: i64, + mut material: Vec, +) -> Vec { + let split = document.split_top_skip.max(0); + let first = material + .iter() + .map(item_height) + .find(|height| *height > 0) + .unwrap_or(0); + if !material.is_empty() && split > 0 && capacity >= split.saturating_add(first) { + material.insert(0, VerticalItem::Glue(split)); + } + material +} + fn take_insertion_prefix( document: &Document, class: u8, @@ -1748,6 +1778,7 @@ impl Engine { let material = held.remove(&class).unwrap_or_default(); let limit = document.insertion_class_limit(class); let capacity = (limit - used.get(&class).copied().unwrap_or(0)).max(0); + let material = held_insertion_material(document, capacity, material); let (accepted, remainder, reserved) = take_insertion_prefix(document, class, material, capacity); attach_insertion(&mut insertions, &mut used, class, accepted, reserved); @@ -1819,6 +1850,7 @@ impl Engine { for class in classes { let material = held.remove(&class).unwrap_or_default(); let limit = document.insertion_class_limit(class); + let material = held_insertion_material(document, limit, material); let (accepted, remainder, reserved) = take_insertion_prefix(document, class, material, limit); attach_insertion(&mut insertions, &mut used, class, accepted, reserved); @@ -3373,6 +3405,42 @@ mod tests { assert_eq!(engine.pages().len(), 2); } + #[test] + fn held_over_insertions_start_with_split_top_skip() { + let scale = 65_536; + let mut document = Document::new( + 200 * scale, + vec![Unit::insertion( + 1, + 0, + 120 * scale, + vec![ + VerticalItem::Rule { + width: 0, + height: 60 * scale, + }, + VerticalItem::Rule { + width: 0, + height: 60 * scale, + }, + ], + )], + ); + document.split_top_skip = 20 * scale; + document.insertion_classes = vec![InsertionClass { + number: 0, + fraction_percent: 50, + max_height: None, + skip: None, + multiplier: 1000, + }]; + let engine = Engine::layout_paged(&document).expect("paged"); + assert_eq!(engine.pages().len(), 2); + let second = &engine.pages()[1].insertions[0]; + assert_eq!(second.items.first(), Some(&VerticalItem::Glue(20 * scale))); + assert_eq!(second.height, 80 * scale); + } + #[test] fn insertion_skip_reserves_space_before_the_first_insertion() { let insertion = || { diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 2f2aa8c..ef36432 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`). 387 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 388 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -248,7 +248,8 @@ Scope: collected per page; `Engine::top_mark`/`first_mark`/`bot_mark` now carry the TeX register semantics, `\marks` remains open); - insertions: `\insert` with `\count`, `\dimen`, `\skip` per class, split - insertions, held-over material, `\footins` defaults (the three registers are + insertions, held-over material with `\splittopskip` leading each + continuation, `\footins` defaults (the three registers are now modelled by `InsertionClass::multiplier`, `max_height` and `skip`, and the fitting head stays on the anchor page with the tail held over; TeX's register arithmetic remains); diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index c8ac287..163b3b7 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -336,7 +336,7 @@ M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments. -M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the candidate closest to the page goal wins, so an overfull page takes the least overfull break. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` dimension assignments from the source and apply them. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward (documents with insertions or an interpreted `\output` routine still fall back to a full rebuild, because held-over material and dropped pages move page boundaries). The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: three page fixtures (single-line paragraphs, `\parskip=6pt`, and multi-line paragraphs split across pages) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. +M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the candidate closest to the page goal wins, so an overfull page takes the least overfull break. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` dimension assignments from the source and apply them. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward (documents with insertions or an interpreted `\output` routine still fall back to a full rebuild, because held-over material and dropped pages move page boundaries). The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: three page fixtures (single-line paragraphs, `\parskip=6pt`, and multi-line paragraphs split across pages) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row heights and cell text widths to scaled points; the painter uses 10pt glyphs in 12pt rows. Rules and spans are painted; tall tables split at row boundaries (`Halign::split_for_height`) with column widths preserved. @@ -344,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 263 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 387 tests (263 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. +The crate currently has 264 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 388 tests (264 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