diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 49bb025..fd41ab4 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -1523,6 +1523,7 @@ struct PagedOutput { dimens: [i64; 256], skips: [i64; 256], initial_dimens: Vec<(u8, i64)>, + initial_skips: Vec<(u8, i64)>, } impl PagedOutput { @@ -1531,12 +1532,14 @@ impl PagedOutput { let mut dimens = [0_i64; 256]; let mut skips = [0_i64; 256]; let mut initial_dimens = Vec::new(); + let mut initial_skips = Vec::new(); for class in &document.insertion_classes { let slot = class.number as usize; counts[slot] = i64::from(class.multiplier); dimens[slot] = class.max_height.unwrap_or(0); skips[slot] = class.skip.unwrap_or(document.insertion_skip); initial_dimens.push((class.number, dimens[slot])); + initial_skips.push((class.number, skips[slot])); } Self { program, @@ -1547,6 +1550,7 @@ impl PagedOutput { dimens, skips, initial_dimens, + initial_skips, } } @@ -1655,6 +1659,31 @@ fn output_insertion_limit(document: &Document, class: u8, routine: Option<&Paged fraction.min(absolute.max(0)) } +fn output_insertion_skip(document: &Document, class: u8, routine: Option<&PagedOutput>) -> i64 { + let initial = document + .insertion_classes + .iter() + .find(|entry| entry.number == class) + .and_then(|entry| entry.skip) + .unwrap_or(document.insertion_skip); + match routine { + Some(routine) => { + let slot = class as usize; + let known = routine + .initial_skips + .iter() + .find(|(number, _)| *number == class) + .map_or(initial, |(_, value)| *value); + if routine.skips[slot] == known { + initial + } else { + routine.skips[slot].max(0) + } + } + None => initial, + } +} + fn class_backstop(document: &Document, class: u8, fraction: i64) -> i64 { document .insertion_classes @@ -2249,7 +2278,7 @@ impl Engine { let insertion_skip: i64 = page .insertions .iter() - .map(|insertion| document.insertion_skip_for(insertion.class)) + .map(|insertion| output_insertion_skip(document, insertion.class, routine.as_ref())) .sum(); page.sources = sources; page.seal_in_place(); @@ -2276,11 +2305,21 @@ impl Engine { let has_bottom_float = nodes .iter() .any(|node| matches!(node, VerticalNode::BottomFloat { .. })); - if goal != builder.page_goal && !has_bottom_float { + let mut skips = builder.insertion_skips.clone(); + let mut skip_changed = false; + for (class, skip) in &mut skips { + let assigned = output_insertion_skip(document, *class, routine.as_ref()); + if assigned != *skip { + *skip = assigned; + skip_changed = true; + } + } + if (goal != builder.page_goal || skip_changed) && !has_bottom_float { let next_start = fragments .get(page_index + 1) .map_or(nodes.len(), |next| next.start); builder.set_page_goal(goal); + builder.insertion_skips = skips; fragments.truncate(page_index + 1); fragments.extend(builder.build_from(&nodes, next_start)); } @@ -2316,7 +2355,7 @@ impl Engine { let insertion_skip: i64 = page .insertions .iter() - .map(|insertion| document.insertion_skip_for(insertion.class)) + .map(|insertion| output_insertion_skip(document, insertion.class, routine.as_ref())) .sum(); page.seal_in_place(); let shipped = match routine.as_mut() { @@ -3342,6 +3381,46 @@ mod tests { assert_eq!(retargeted.layout.pages[0].insertions.len(), 1); } + #[test] + fn output_routine_can_assign_insertion_skip_for_later_pages() { + const PT: i64 = 65_536; + let build = |routine: Option<&str>| { + let mut units = Vec::new(); + for step in 0..4_u64 { + units.push(Unit::rule(step * 3, 100 * PT, 100 * PT)); + units.push(Unit::insertion( + step * 3 + 1, + 0, + 50 * PT, + vec![VerticalItem::Rule { + width: 100 * PT, + height: 50 * PT, + }], + )); + units.push(Unit::vskip(step * 3 + 2, 0)); + } + let mut document = Document::new(300 * PT, units); + document.insertion_classes = vec![InsertionClass { + number: 0, + fraction_percent: 100, + max_height: Some(300 * PT), + multiplier: 1000, + skip: None, + }]; + document.output_routine = routine.map(str::to_owned); + Engine::layout_paged(&document).expect("paged layout") + }; + + let base = build(None); + assert_eq!(base.layout.pages.len(), 2); + + // The routine assigns \skip0 after the first page; the remaining + // fragments are rebuilt with the larger reservation, so the second + // pair of units no longer fits on the second page. + let retargeted = build(Some(r#"\ifnum\pageno=1\skip0=40pt\fi\shipout\box255"#)); + assert_eq!(retargeted.layout.pages.len(), 3); + } + #[test] fn output_routine_can_change_vsize_for_later_pages() { let mut units = Vec::new(); diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index f50986f..37823ae 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`). 473 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 474 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -91,7 +91,7 @@ source-level `\hyphenation{...}` exceptions and `\parshape` measures, fragments are rebuilt from the next node index; insertion material is fine because class limits apply at assembly time), though a document that defers bottom floats keeps its initial goal; the paged builder runs the routine - page by page, so `\dimen` and `\count` assignments change the insertion limits and reservations of later pages; the configured `\skip` reserves space above its class once per page, while an output-routine `\skip` assignment still has no effect because the builder's parameters are fixed before the page loop; `\box255` content is not inspectable and the full `\output` machinery is still missing; + page by page, so `\dimen` and `\count` assignments change the insertion limits and reservations of later pages; the configured `\skip` reserves space above its class once per page, and an output-routine `\skip` assignment rebuilds the remaining pages with the new reservation, so later insertion material pays the assigned skip; `\box255` content is not inspectable and the full `\output` machinery is still missing; 4. `\halign` handles spans/omit/templates but not the full TeX column algorithm; 5. math is a compact subset without the CM math fonts (`cmmi`, `cmsy`, `cmex`), display-math line breaking or `\mathchoice`-level styling; diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 932c82c..d6611f9 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -129,7 +129,7 @@ and justification. | --- | --- | --- | | 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`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures | -| 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, bottom floats 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 the pages the routine has not seen yet, even when the document raises insertion material; only a document that defers bottom floats keeps its initial goal, because the carried queue cannot be rebuilt after a retarget), `\ht255`, `\dp255` and `\wd255` expose the page box height, depth and width to the routine, and `\hsize` is readable (and assignable for the rest of the run) while `\wd255` tracks it; route-D sets `\hsize` from its 480pt text measure, insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments that outlive the routine (the paged builder runs the routine after each page, so an assigned `\dimen` or `\count` changes the insertion capacity and reservation of later pages); the configured `\skip` also reserves space above its class once per page in the paged builder, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine; `\vbadness` reports the badness of the break that produced the page and `\insertpenalties` the number of insertion items held over from it | +| 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, bottom floats 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 the pages the routine has not seen yet, even when the document raises insertion material; only a document that defers bottom floats keeps its initial goal, because the carried queue cannot be rebuilt after a retarget), `\ht255`, `\dp255` and `\wd255` expose the page box height, depth and width to the routine, and `\hsize` is readable (and assignable for the rest of the run) while `\wd255` tracks it; route-D sets `\hsize` from its 480pt text measure, insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments that outlive the routine (the paged builder runs the routine after each page, so an assigned `\dimen` or `\count` changes the insertion capacity and reservation of later pages); the configured `\skip` also reserves space above its class once per page in the paged builder, and a `\skip` assignment rebuilds the pages the routine has not seen yet with the new reservation, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine; `\vbadness` reports the badness of the break that produced the page and `\insertpenalties` the number of insertion items held over from it | | 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 | | M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | @@ -367,7 +367,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 316 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 473 tests (316 route-D unit, 7 route-D integration, 35 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path. +The crate currently has 317 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 474 tests (317 route-D unit, 7 route-D integration, 35 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo