diff --git a/README.md b/README.md index b1e494a..fba9890 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 floats and incremental replay gain paged equivalents. `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. 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; the route-D PDF endpoint reads leading `\hoffset`/`\voffset` dimension assignments from the submitted source. Page marks collected by `\mark` are exposed through diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index db366aa..899a270 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -11,7 +11,7 @@ pub mod tfm; pub use cmr10::Cmr10Metrics; use std::collections::BTreeMap; -use page::{InsertionLimit, PageBuilder, VerticalGlue, VerticalNode}; +use page::{InsertionLimit, PageBuilder, PageFragment, VerticalGlue, VerticalNode}; pub use paragraph::{ HorizontalBox, HorizontalItem, Paragraph, ParagraphFont, ParagraphStyle, layout_items, layout_paragraph, layout_paragraph_with_font, text_items, text_items_with_font, @@ -1190,6 +1190,10 @@ pub struct Layout { pub recomputed_pages: usize, /// Page indices whose sealed hash changed in the last edit. pub changed_pages: Vec, + /// Node index that starts each page of a paged layout. Empty when the + /// layout came from the scrolling builder or cannot be replayed partially. + #[serde(default)] + pub paged_page_nodes: Vec, } impl Layout { @@ -1590,6 +1594,7 @@ impl Engine { checkpoints, recomputed_pages: 0, changed_pages: (0..pages_len).collect(), + paged_page_nodes: Vec::new(), }, } } @@ -1659,27 +1664,15 @@ impl Engine { /// because their placement belongs to the incremental builder for now. pub fn layout_paged(document: &Document) -> Option { let (nodes, owners, node_items) = document_nodes(document)?; - let builder = PageBuilder { - page_goal: document.page_goal, - top_skip: document.top_skip, - max_depth: document.max_depth, - insertion_limits: document - .insertion_classes - .iter() - .map(|class| InsertionLimit { - class: class.number, - height: document.insertion_class_limit(class.number), - }) - .collect(), - text_float_sep: document.text_float_sep.max(0), - }; + let builder = Self::paged_builder(document); let mut pages = Vec::new(); let mut page_penalties = Vec::new(); let mut page_depths = Vec::new(); let mut page_stretches = Vec::new(); let mut page_shrinks = Vec::new(); let mut held: BTreeMap> = BTreeMap::new(); - for fragment in builder.build(&nodes) { + let fragments = builder.build(&nodes); + for fragment in &fragments { let mut items = Vec::new(); let mut marks = Vec::new(); let mut floats = Vec::new(); @@ -1792,6 +1785,12 @@ impl Engine { } pages = shipped; } + let paged_page_nodes = + if document.output_routine.is_none() && pages.len() == fragments.len() { + fragments.iter().map(|fragment| fragment.start).collect() + } else { + Vec::new() + }; let count = pages.len(); Some(Self { layout: Layout { @@ -1799,6 +1798,7 @@ impl Engine { checkpoints: Vec::new(), recomputed_pages: 0, changed_pages: (0..count).collect(), + paged_page_nodes, }, }) } @@ -1824,6 +1824,118 @@ impl Engine { self.layout = layout; } + fn paged_builder(document: &Document) -> PageBuilder { + PageBuilder { + page_goal: document.page_goal, + top_skip: document.top_skip, + max_depth: document.max_depth, + insertion_limits: document + .insertion_classes + .iter() + .map(|class| InsertionLimit { + class: class.number, + height: document.insertion_class_limit(class.number), + }) + .collect(), + text_float_sep: document.text_float_sep.max(0), + } + } + + /// Materialize page fragments without insertion hold-over. + fn paged_pages( + document: &Document, + owners: &[usize], + node_items: &[VerticalItem], + fragments: &[PageFragment], + ) -> Vec { + fragments + .iter() + .map(|fragment| { + let mut page = Page::empty(); + for index in fragment.start..fragment.end { + match &node_items[index] { + VerticalItem::Mark(mark) => page.marks.push(mark.clone()), + VerticalItem::Float(float) => page.floats.push(float.clone()), + item => page.items.push(item.clone()), + } + let unit = &document.units[owners[index]]; + if page.sources.last().map(|(id, _)| *id) != Some(unit.id) { + page.sources.push((unit.id, source_hash(&unit.source))); + } + } + page.seal_in_place(); + page + }) + .collect() + } + + /// Replay a paged layout from the page that contains `unit_index`. + /// + /// Earlier pages keep their sealed content. Documents with insertions or + /// an interpreted output routine fall back to a full rebuild: held-over + /// material can add pages that have no node start to replay from. + fn relayout_paged_incremental(&mut self, document: &Document, unit_index: usize) -> bool { + let starts = self.layout.paged_page_nodes.clone(); + if starts.is_empty() || document.output_routine.is_some() { + return false; + } + if document.units.iter().any(|unit| { + unit.items + .iter() + .any(|item| matches!(item, VerticalItem::Insertion(_))) + }) { + return false; + } + let Some((nodes, owners, node_items)) = document_nodes(document) else { + return false; + }; + let Some(mut first_node) = owners.iter().position(|owner| *owner >= unit_index) else { + return false; + }; + // The parser owns the synthetic par-skip glue by the paragraph that + // follows it, so that glue sits at the end of the previous page. Start + // replaying at the unit's first real item instead. + while first_node < nodes.len() + && owners[first_node] == unit_index + && matches!(node_items[first_node], VerticalItem::Glue(_)) + && !matches!( + document.units[unit_index].items.first(), + Some(VerticalItem::Glue(_)) + ) + { + first_node += 1; + } + let page_index = starts + .iter() + .rposition(|start| *start <= first_node) + .unwrap_or(0); + let start_node = starts[page_index]; + let fragments = Self::paged_builder(document).build_from(&nodes, start_node); + let rebuilt = Self::paged_pages(document, &owners, &node_items, &fragments); + let previous = std::mem::take(&mut self.layout.pages); + let prefix = page_index.min(previous.len()); + let mut pages: Vec = previous[..prefix].to_vec(); + pages.extend(rebuilt); + let changed_pages = (prefix..pages.len()) + .filter(|index| { + previous + .get(*index) + .is_none_or(|old| old.hash != pages[*index].hash) + }) + .collect(); + let recomputed_pages = pages.len() - prefix; + let mut paged_page_nodes: Vec = starts[..page_index.min(starts.len())].to_vec(); + paged_page_nodes.extend(fragments.iter().map(|fragment| fragment.start)); + self.layout = Layout { + pages, + checkpoints: Vec::new(), + recomputed_pages, + changed_pages, + paged_page_nodes, + }; + true + } + pub fn edit(&mut self, document: &Document, unit_id: UnitId, source: impl Into) { let Some(unit_index) = document.units.iter().position(|unit| unit.id == unit_id) else { self.layout = Self::layout(document).layout; @@ -1847,7 +1959,9 @@ impl Engine { .unwrap_or(ParagraphFont::Roman); next.units[unit_index] = Unit::paragraph_with_style_and_face(unit_id, source, style, font); if self.layout.checkpoints.is_empty() { - self.replace_with_paged(&next); + if !self.relayout_paged_incremental(&next, unit_index) { + self.replace_with_paged(&next); + } return; } self.relayout_from(&next, unit_index); @@ -2278,6 +2392,7 @@ impl Engine { checkpoints, recomputed_pages: rebuilt, changed_pages, + paged_page_nodes: Vec::new(), }; } } @@ -5355,7 +5470,71 @@ mod tests { let first = engine.pages()[0].hash; engine.edit(&document, 3, "epsilon zeta"); assert_eq!(engine.pages()[0].hash, first); - assert!(engine.changed_pages().contains(&1)); - assert_eq!(engine.recomputed_pages(), engine.pages().len()); + assert_eq!(engine.changed_pages(), &[1]); + assert_eq!(engine.recomputed_pages(), 1); + } + + #[test] + fn paged_edit_keeps_untouched_pages() { + let style = ParagraphStyle { + line_width: 200 * 65_536, + line_height: 12 * 65_536, + ..ParagraphStyle::default() + }; + let paragraph = |id, text: &str| { + Unit::paragraph_with_style_and_face(id, text, style.clone(), ParagraphFont::Roman) + }; + let mut document = Document::new( + 16 * 65_536, + vec![ + paragraph(1, "alpha beta"), + paragraph(2, "gamma delta"), + paragraph(3, "epsilon zeta"), + ], + ); + document.par_skip = 65_536; + let mut engine = Engine::layout_paged(&document).expect("paragraphs are page-buildable"); + assert_eq!(engine.pages().len(), 3); + let first = engine.pages()[0].hash; + let second = engine.pages()[1].hash; + engine.edit(&document, 3, "eta theta iota"); + assert_eq!(engine.pages()[0].hash, first); + assert_eq!(engine.pages()[1].hash, second); + assert_eq!(engine.changed_pages(), &[2]); + assert_eq!(engine.recomputed_pages(), 1); + } + + #[test] + fn paged_edit_falls_back_when_insertions_are_present() { + let style = ParagraphStyle { + line_width: 200 * 65_536, + line_height: 12 * 65_536, + ..ParagraphStyle::default() + }; + let document = Document::new( + 16 * 65_536, + vec![ + Unit::paragraph_with_style_and_face( + 1, + "alpha beta", + style.clone(), + ParagraphFont::Roman, + ), + Unit::insertion( + 2, + 0, + 65_536, + vec![VerticalItem::Rule { + width: 10, + height: 65_536, + }], + ), + Unit::paragraph_with_style_and_face(3, "gamma delta", style, ParagraphFont::Roman), + ], + ); + let mut engine = Engine::layout_paged(&document).expect("insertions are page-buildable"); + let pages = engine.pages().len(); + engine.edit(&document, 3, "epsilon zeta"); + assert_eq!(engine.recomputed_pages(), pages); } } diff --git a/crates/texrra-tex-core/src/page.rs b/crates/texrra-tex-core/src/page.rs index 34688fb..e63e3e5 100644 --- a/crates/texrra-tex-core/src/page.rs +++ b/crates/texrra-tex-core/src/page.rs @@ -155,6 +155,26 @@ impl PageBuilder { pages } + /// Build pages starting at a node that begins a page. + /// + /// Insertion material is not carried over here: the incremental replay in + /// `Engine` refuses documents that raise insertions, because held-over + /// material can add pages that have no node start of their own. + pub fn build_from(&self, nodes: &[VerticalNode], start: usize) -> Vec { + let mut pages = Vec::new(); + let mut next = self.skip_leading(nodes, start); + while next < nodes.len() { + let Some((fragment, after, _)) = self.best_fragment(nodes, next, &BTreeMap::new()) + else { + break; + }; + let after = after.max(next + 1); + pages.push(fragment); + next = self.skip_leading(nodes, after); + } + pages + } + fn skip_leading(&self, nodes: &[VerticalNode], mut index: usize) -> usize { while index < nodes.len() { match nodes[index] { diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index ee11ad1..a839803 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`). 358 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 367 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -262,7 +262,8 @@ marks) and chooses each page at the cheapest feasible breakpoint, scoring badness from the page goal and accumulated glue, adding the break penalty, and applying `\topskip` to the first box and `\maxdepth` to the page depth. Seven unit tests cover overfull avoidance, exact glue filling, forced penalties, -penalty-driven earlier breaks, `\topskip`, `\maxdepth` and marks. +penalty-driven earlier breaks, `\topskip`, `\maxdepth`, marks, insertion +limits and top-float placement. `Engine::layout_paged` now feeds it every document whose units are single vertical items (`Document::max_depth` supplies `\maxdepth`) and materialises the chosen fragments as hashed pages; ties go to the breakpoint closest to the page @@ -273,9 +274,13 @@ with `pdftotext -bbox`, and the PDF endpoint reads leading `\hoffset`/`\voffset` dimension assignments from the source. Insertion classes are placed by the paged builder with their limits and held-over material, and top floats are placed at the head of a fragment with `\textfloatsep` reserved above the body; -bottom/in-text floats and checkpoint replay still fall back to the scrolling -builder, which stays the default until it has a paged equivalent. Next: port those paths and paper margins, then extend the `\output` -interpreter past the shipout/ifdim/ifnum/ifodd/ifcase subset. +bottom/in-text floats still fall back to the scrolling builder, which stays +the default until it has a paged equivalent. Paged layouts also record the +node index starting each page, so `Engine::edit` reuses the sealed prefix and +rebuilds only the pages from the edited unit onward; insertions and interpreted +`\output` keep the full-rebuild fallback. Next: port bottom/in-text floats and +paper margins, then extend the `\output` interpreter past the +shipout/ifdim/ifnum/ifodd/ifcase subset. Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks); page counts identical and first/last baselines within 1pt of pdfLaTeX. diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index d3a8654..72a62a6 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`, `\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 floats and insertion classes on that path, while the scrolling builder remains the default for bottom/in-text floats and edit replay; `\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 floats and insertion classes on that path, while the scrolling builder remains the default for bottom/in-text floats; 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 | | M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | @@ -302,7 +302,7 @@ for a later overlaid slash. | --- | --- | --- | | M0 checkpoint engine | done | page list, page hashes, snapshot/restore, edit replay | | M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing with default and custom `\sfcode`/`\frenchspacing`, explicit `\spaceskip`/`\xspaceskip`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfTeX oracle matrix 90-240pt plus register, geometry and vertical-glue fixtures | -| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for documents made of box/glue/penalty/mark vertical material (a unit may span pages), while floats and incremental replay still use the scrolling path, insertions are placed through the builder too; `\output` interpreted for a `\shipout`/`\ifdim`/`\ifnum` register subset over page globals and `\outputpenalty`/`\pageno`/`\deadcycles` | +| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for documents made of box/glue/penalty/mark vertical material (a unit may span pages), while bottom/in-text floats still use the scrolling path; paged layouts replay edits from the edited page (insertions and interpreted `\output` force a full rebuild), and insertions are placed through the builder too; `\output` interpreted for a `\shipout`/`\ifdim`/`\ifnum` register subset over page globals and `\outputpenalty`/`\pageno`/`\deadcycles` | | M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter | | M4 math | partial | atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping | | M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style | @@ -331,7 +331,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 eight unit tests, and 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_origin` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and the route-D PDF endpoint strips leading `\hoffset`/`\voffset` dimension assignments from the source and applies 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. Floats and the incremental checkpoint replay still use the scrolling builder, which remains the default until those pieces have a paged equivalent. 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); `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_origin` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and the route-D PDF endpoint strips leading `\hoffset`/`\voffset` dimension assignments from the source and applies 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. 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). Bottom/in-text floats and the scrolling builder's float path remain 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. @@ -339,7 +339,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 244 unit tests plus seven route-D integration tests and sixteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 365 tests (244 route-D unit, 7 route-D integration, 16 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 246 unit tests plus seven route-D integration tests and sixteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 367 tests (246 route-D unit, 7 route-D integration, 16 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -376,8 +376,9 @@ deliberately open rather than approximated: - **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 - for simple documents, but floats and incremental replay need a paged - equivalent before it can become the default; paper margins remain open, and + for simple documents; paged edits replay from the edited page, but bottom + and in-text floats need a paged equivalent before it can become the default; + paper margins remain open, and the `\output` interpreter only covers the shipout/ifdim/ifnum/ifodd/ifcase subset (explicit `\hoffset`/`\voffset` offsets are applied by the PDF writer). - **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. only used text faces embed Liberation Serif/Mono as Type0/Identity-H; each face is subset to the glyphs actually used (composite components included, glyph IDs retained); FontFile2 and ToUnicode streams use Flate compression; the ToUnicode CMap follows the used characters; ff/fi/fl/ffi/ffl ligatures come from TFM, and CMR10 italic corrections are applied at line ends; full NFSS family switching is not implemented.