diff --git a/README.md b/README.md index 4e56840..210a124 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) 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 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 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 6750cd9..0300a9a 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -1727,6 +1727,9 @@ impl Engine { let mut page_penalties = Vec::new(); let mut page_depths = Vec::new(); let mut page_stretches = Vec::new(); + let mut page_fil_stretches = Vec::new(); + let mut page_fill_stretches = Vec::new(); + let mut page_filll_stretches = Vec::new(); let mut page_shrinks = Vec::new(); let mut held: BTreeMap> = BTreeMap::new(); let fragments = builder.build(&nodes); @@ -1798,6 +1801,9 @@ impl Engine { page_penalties.push(fragment.penalty); page_depths.push(fragment.depth); page_stretches.push(fragment.stretch); + page_fil_stretches.push(fragment.stretches[1]); + page_fill_stretches.push(fragment.stretches[2]); + page_filll_stretches.push(fragment.stretches[3]); page_shrinks.push(fragment.shrink); } @@ -1824,6 +1830,9 @@ impl Engine { page_penalties.push(0); page_depths.push(0); page_stretches.push(0); + page_fil_stretches.push(0); + page_fill_stretches.push(0); + page_filll_stretches.push(0); page_shrinks.push(0); } if let Some(source) = &document.output_routine { @@ -1836,6 +1845,9 @@ impl Engine { page_total, page_depth: page_depths.get(index).copied().unwrap_or(0), page_stretch: page_stretches.get(index).copied().unwrap_or(0), + page_fil_stretch: page_fil_stretches.get(index).copied().unwrap_or(0), + page_fill_stretch: page_fill_stretches.get(index).copied().unwrap_or(0), + page_filll_stretch: page_filll_stretches.get(index).copied().unwrap_or(0), page_shrink: page_shrinks.get(index).copied().unwrap_or(0), vsize: document.page_goal, top_skip: document.top_skip, @@ -5216,6 +5228,34 @@ mod tests { assert_eq!(widths, vec![20, 80], "only the fil glue stretches"); } + #[test] + fn output_routine_sees_fill_stretch_orders() { + let mut document = Document::new(200, Vec::new()); + document.units = vec![ + Unit::rule(0, 10, 40), + Unit::vertical( + 1, + vec![VerticalItem::StretchGlue(VerticalGlue::with_order( + 20, + 4 * 65_536, + 0, + 2, + ))], + ), + Unit::penalty(2, -10_000), + Unit::rule(3, 10, 40), + ]; + document.output_routine = Some(r"\ifdim\pagefillstretch>3pt\shipout\box255\fi".to_owned()); + let engine = Engine::layout_paged(&document).expect("paged"); + assert_eq!(engine.pages().len(), 1); + assert!( + engine.pages()[0] + .items + .iter() + .any(|item| matches!(item, VerticalItem::Rule { .. })) + ); + } + #[test] fn interpreted_output_sees_the_break_penalty() { let mut document = Document::new(100, Vec::new()); diff --git a/crates/texrra-tex-core/src/output.rs b/crates/texrra-tex-core/src/output.rs index c8c0aad..e1a759f 100644 --- a/crates/texrra-tex-core/src/output.rs +++ b/crates/texrra-tex-core/src/output.rs @@ -20,6 +20,12 @@ pub struct OutputContext { pub page_depth: i64, /// TeX `\pagestretch`: stretch of the vertical glue so far. pub page_stretch: i64, + /// TeX `\pagefilstretch`: stretch of `\vfil` glue on the page. + pub page_fil_stretch: i64, + /// TeX `\pagefillstretch`: stretch of `\vfill` glue on the page. + pub page_fill_stretch: i64, + /// TeX `\pagefilllstretch`: stretch of `\vfilll` glue on the page. + pub page_filll_stretch: i64, /// TeX `\pageshrink`: shrink of the vertical glue so far. pub page_shrink: i64, /// TeX `\vsize`: the configured page height. @@ -105,6 +111,9 @@ enum Register { PageTotal, PageDepth, PageStretch, + PageFilStretch, + PageFillStretch, + PageFilllStretch, PageShrink, Vsize, TopSkip, @@ -120,6 +129,9 @@ impl Dimension { Register::PageTotal => context.page_total, Register::PageDepth => context.page_depth, Register::PageStretch => context.page_stretch, + Register::PageFilStretch => context.page_fil_stretch, + Register::PageFillStretch => context.page_fill_stretch, + Register::PageFilllStretch => context.page_filll_stretch, Register::PageShrink => context.page_shrink, Register::Vsize => context.vsize, Register::TopSkip => context.top_skip, @@ -488,6 +500,9 @@ fn parse_dimension(tokens: &[Token], index: &mut usize) -> Result Register::PageTotal, "pagedepth" => Register::PageDepth, "pagestretch" => Register::PageStretch, + "pagefilstretch" => Register::PageFilStretch, + "pagefillstretch" => Register::PageFillStretch, + "pagefilllstretch" => Register::PageFilllStretch, "pageshrink" => Register::PageShrink, "vsize" => Register::Vsize, "topskip" => Register::TopSkip, @@ -578,6 +593,9 @@ mod tests { page_total, page_depth: 0, page_stretch: 0, + page_fil_stretch: 0, + page_fill_stretch: 0, + page_filll_stretch: 0, page_shrink: 0, vsize: 612 * 65_536, top_skip: 10 * 65_536, @@ -609,6 +627,25 @@ mod tests { assert_eq!(shrink.shipout_count(&context(0)).unwrap(), 0); } + #[test] + fn fill_stretch_registers_are_visible() { + let program = OutputProgram::parse(r"\ifdim\pagefilstretch>9pt\shipout\box255\fi").unwrap(); + let mut context = context(0); + context.page_fil_stretch = 10 * 65_536; + assert_eq!(program.shipout_count(&context).unwrap(), 1); + assert_eq!(program.shipout_count(&self::context(0)).unwrap(), 0); + + let fill = OutputProgram::parse(r"\ifdim\pagefillstretch>4pt\shipout\box255\fi").unwrap(); + let mut context = self::context(0); + context.page_fill_stretch = 5 * 65_536; + assert_eq!(fill.shipout_count(&context).unwrap(), 1); + + let filll = OutputProgram::parse(r"\ifdim\pagefilllstretch>4pt\shipout\box255\fi").unwrap(); + let mut context = self::context(0); + context.page_filll_stretch = 5 * 65_536; + assert_eq!(filll.shipout_count(&context).unwrap(), 1); + } + #[test] fn page_depth_register_is_visible() { let program = OutputProgram::parse(r"\ifdim\pagedepth>4pt\shipout\box255\fi").unwrap(); diff --git a/crates/texrra-tex-core/src/page.rs b/crates/texrra-tex-core/src/page.rs index 458cd8e..018d8a5 100644 --- a/crates/texrra-tex-core/src/page.rs +++ b/crates/texrra-tex-core/src/page.rs @@ -112,6 +112,9 @@ pub struct PageFragment { pub stretch_order: u8, /// Total shrink of the vertical glue on the page. pub shrink: i64, + /// Stretch of each glue order: index 0 is normal, 1 is `\vfil`, 2 is + /// `\vfill` and 3 is `\vfilll`. + pub stretches: [i64; 4], /// Signed glue-setting amount applied to the page: positive stretch to /// fill the goal, negative shrink to fit it (zero when ragged). pub set: i64, @@ -283,6 +286,7 @@ impl PageBuilder { badness, 0, bottom, + order_stretches(&nodes[start..end]), self.insertion_space(nodes, start, end, held), ); return Some(( @@ -323,6 +327,7 @@ impl PageBuilder { badness, 0, bottom, + order_stretches(&nodes[start..end]), self.insertion_space(nodes, start, end, held), ); return Some(( @@ -372,6 +377,7 @@ impl PageBuilder { badness + *penalty, *penalty, bottom, + order_stretches(&nodes[start..end]), self.insertion_space(nodes, start, end, held), ); return Some(( @@ -434,6 +440,7 @@ impl PageBuilder { best.cost, best.penalty, best.bottom, + order_stretches(&nodes[start..best.end]), self.insertion_space(nodes, start, best.end, held), ); Some(( @@ -570,6 +577,7 @@ impl PageBuilder { cost: i64, penalty: i64, bottom: i64, + stretches: [i64; 4], insertions: Vec, ) -> PageFragment { let reserved: i64 = insertions.iter().map(|space| space.height).sum(); @@ -597,6 +605,7 @@ impl PageBuilder { stretch, stretch_order, shrink, + stretches, set, insertions, } @@ -625,6 +634,17 @@ impl PageBuilder { } } +fn order_stretches(nodes: &[VerticalNode]) -> [i64; 4] { + let mut stretches = [0_i64; 4]; + for node in nodes { + if let VerticalNode::Glue(glue) = node { + let order = usize::from(glue.order.min(3)); + stretches[order] += glue.stretch.max(0); + } + } + stretches +} + fn effective_stretch(stretch_orders: &[i64; 4]) -> (i64, u8) { for (order, stretch) in stretch_orders.iter().enumerate().rev() { if *stretch > 0 { @@ -727,6 +747,21 @@ mod tests { assert_eq!(pages[0].shrink, 5); } + #[test] + fn fragments_record_stretch_by_glue_order() { + let builder = PageBuilder::new(200); + let nodes = vec![ + box_(50, 0), + VerticalNode::Glue(VerticalGlue::with_order(0, 20, 0, 0)), + VerticalNode::Glue(VerticalGlue::with_order(0, 10, 0, 1)), + VerticalNode::Glue(VerticalGlue::with_order(0, 5, 0, 2)), + box_(50, 0), + ]; + let pages = builder.build(&nodes); + assert_eq!(pages.len(), 1); + assert_eq!(pages[0].stretches, [20, 10, 5, 0]); + } + #[test] fn forced_penalty_breaks_the_page() { let builder = PageBuilder::new(100); diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index d7edd16..2bb2055 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`). 383 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 386 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -242,7 +242,7 @@ Scope: - TeX page builder: candidate breakpoints, cost = badness + penalty, page goal recomputation as insertions arrive, `\pagegoal`, `\pagetotal`, `\pagedepth`, `\pagestretch`, `\pageshrink`, - `\pagestretch`, `\pagefilstretch`, `\pagefillstretch`, `\pagefilllstretch`, + `\pagestretch`, `\pagefilstretch`, `\pagefillstretch`, `\pagefilllstretch` (per-order stretch is recorded on every page fragment), `\pageshrink`, `\pagedepth`; - marks: `\mark`, `\botmark`, `\firstmark`, `\topmark`, `\marks` (marks are collected per page; `Engine::top_mark`/`first_mark`/`bot_mark` now carry the diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index fa84853..28924f2 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -116,7 +116,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` 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 (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` 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 (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` 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, `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 | | M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | @@ -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 259 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 383 tests (259 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 259 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 386 tests (262 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