From a2a2eafab57bf0704cea83ef5615847f88874a9e Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 03:04:58 +0800 Subject: [PATCH] Read output penalty and page number in the output routine --- README.md | 2 +- crates/texrra-tex-core/src/lib.rs | 34 ++++- crates/texrra-tex-core/src/output.rs | 203 +++++++++++++++++++++++---- crates/texrra-tex-core/src/page.rs | 21 ++- docs/ROUTE_D_PLAN.md | 18 +-- docs/TEX_CORE.md | 12 +- 6 files changed, 243 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 4d7ceb2..19635d9 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` and `\ifdim` over page registers) over those paged fragments, so a routine can drop pages it does not ship. 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 floats and incremental replay gain paged equivalents. `Document::output_routine` runs an interpreted `\output` program (`\shipout\box255`, `\relax`, `\message`, `\ifdim` and `\ifnum` 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 f3525db..c5e40f1 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -1649,6 +1649,7 @@ impl Engine { .collect(), }; let mut pages = Vec::new(); + let mut page_penalties = Vec::new(); let mut held: BTreeMap> = BTreeMap::new(); for fragment in builder.build(&nodes) { let mut items = Vec::new(); @@ -1705,6 +1706,7 @@ impl Engine { page.sources = sources; page.seal_in_place(); pages.push(page); + page_penalties.push(fragment.penalty); } // Insertion material that did not fit its class limit on the page where @@ -1727,11 +1729,12 @@ impl Engine { page.insertions = insertions.into_values().collect(); page.seal_in_place(); pages.push(page); + page_penalties.push(0); } if let Some(source) = &document.output_routine { let program = output::OutputProgram::parse(source).ok()?; let mut shipped = Vec::new(); - for page in pages { + for (index, page) in pages.into_iter().enumerate() { let page_total: i64 = page.items.iter().map(item_height).sum(); let context = output::OutputContext { page_goal: document.page_goal, @@ -1739,6 +1742,9 @@ impl Engine { vsize: document.page_goal, top_skip: document.top_skip, max_depth: document.max_depth, + output_penalty: page_penalties.get(index).copied().unwrap_or(0), + pageno: index as i64 + 1, + deadcycles: 0, }; if program.shipout_count(&context).ok()? > 0 { shipped.push(page); @@ -4864,6 +4870,32 @@ mod tests { assert!(engine.pages().iter().all(|page| page.hash != 0)); } + #[test] + fn interpreted_output_sees_the_break_penalty() { + let mut document = Document::new(100, Vec::new()); + document.output_routine = Some(r"\ifnum\outputpenalty<-9999\shipout\box255\fi".to_owned()); + document.units = vec![ + Unit::rule(0, 10, 40), + Unit::penalty(1, -10_000), + Unit::rule(2, 10, 40), + ]; + let engine = Engine::layout_paged(&document).expect("paged layout"); + assert_eq!(engine.pages().len(), 1); + } + + #[test] + fn interpreted_output_reads_the_page_number() { + let mut document = Document::new(100, Vec::new()); + document.output_routine = Some(r"\ifnum\pageno>1\shipout\box255\fi".to_owned()); + document.units = vec![ + Unit::rule(0, 10, 40), + Unit::penalty(1, -10_000), + Unit::rule(2, 10, 40), + ]; + let engine = Engine::layout_paged(&document).expect("paged layout"); + assert_eq!(engine.pages().len(), 1); + } + #[test] fn paged_layout_expands_vertical_units() { let document = Document::new( diff --git a/crates/texrra-tex-core/src/output.rs b/crates/texrra-tex-core/src/output.rs index 2a1a270..f7a825a 100644 --- a/crates/texrra-tex-core/src/output.rs +++ b/crates/texrra-tex-core/src/output.rs @@ -21,6 +21,12 @@ pub struct OutputContext { pub top_skip: i64, /// TeX `\maxdepth`. pub max_depth: i64, + /// TeX `\outputpenalty`: the penalty at which the page broke. + pub output_penalty: i64, + /// One-based number of the page being considered. + pub pageno: i64, + /// TeX `\deadcycles`: output routines since the last shipout. + pub deadcycles: i64, } /// A parsed `\output` program. @@ -61,6 +67,13 @@ enum Op { then_ops: Vec, else_ops: Vec, }, + IfNum { + left: Integer, + relation: Relation, + right: Integer, + then_ops: Vec, + else_ops: Vec, + }, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -93,6 +106,32 @@ impl Dimension { } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Integer { + Constant(i64), + Register(IntegerRegister), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum IntegerRegister { + PageNo, + DeadCycles, + OutputPenalty, +} + +impl Integer { + fn resolve(self, context: &OutputContext) -> i64 { + match self { + Self::Constant(value) => value, + Self::Register(register) => match register { + IntegerRegister::PageNo => context.pageno, + IntegerRegister::DeadCycles => context.deadcycles, + IntegerRegister::OutputPenalty => context.output_penalty, + }, + } + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Relation { Less, @@ -161,29 +200,14 @@ fn lex(source: &str) -> Result, String> { index += 1; } _ if character.is_ascii_digit() || character == '.' => { - let start = index; - while index < chars.len() && chars[index].is_ascii_digit() { - index += 1; - } - if index < chars.len() && chars[index] == '.' { - index += 1; - while index < chars.len() && chars[index].is_ascii_digit() { - index += 1; - } - } - let number: String = chars[start..index].iter().collect(); - let value: f64 = number - .parse() - .map_err(|_| format!("invalid number `{number}`"))?; - while index < chars.len() && chars[index].is_ascii_whitespace() { - index += 1; - } - let unit_start = index; - while index < chars.len() && chars[index].is_ascii_alphabetic() { - index += 1; - } - let unit = (unit_start < index).then(|| chars[unit_start..index].iter().collect()); - tokens.push(Token::Number { value, unit }); + tokens.push(lex_number(&chars, &mut index, false)?); + } + '-' if chars + .get(index + 1) + .is_some_and(|next| next.is_ascii_digit() || *next == '.') => + { + index += 1; + tokens.push(lex_number(&chars, &mut index, true)?); } other => return Err(format!("unexpected character `{other}`")), } @@ -191,6 +215,35 @@ fn lex(source: &str) -> Result, String> { Ok(tokens) } +fn lex_number(chars: &[char], index: &mut usize, negative: bool) -> Result { + let start = *index; + while *index < chars.len() && chars[*index].is_ascii_digit() { + *index += 1; + } + if *index < chars.len() && chars[*index] == '.' { + *index += 1; + while *index < chars.len() && chars[*index].is_ascii_digit() { + *index += 1; + } + } + let number: String = chars[start..*index].iter().collect(); + let value: f64 = number + .parse() + .map_err(|_| format!("invalid number `{number}`"))?; + while *index < chars.len() && chars[*index].is_ascii_whitespace() { + *index += 1; + } + let unit_start = *index; + while *index < chars.len() && chars[*index].is_ascii_alphabetic() { + *index += 1; + } + let unit = (unit_start < *index).then(|| chars[unit_start..*index].iter().collect()); + Ok(Token::Number { + value: if negative { -value } else { value }, + unit, + }) +} + fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result, String> { let mut ops = Vec::new(); while *index < tokens.len() { @@ -251,13 +304,7 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result< "ifdim" => { *index += 1; let left = parse_dimension(tokens, index)?; - let relation = match tokens.get(*index) { - Some(Token::Relation('<')) => Relation::Less, - Some(Token::Relation('>')) => Relation::Greater, - Some(Token::Relation('=')) => Relation::Equal, - _ => return Err("\\ifdim expects <, > or =".to_owned()), - }; - *index += 1; + let relation = parse_relation(tokens, index, "ifdim")?; let right = parse_dimension(tokens, index)?; let then_ops = parse_sequence(tokens, index, &["else", "fi"])?; let mut else_ops = Vec::new(); @@ -279,6 +326,31 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result< else_ops, }); } + "ifnum" => { + *index += 1; + let left = parse_integer(tokens, index)?; + let relation = parse_relation(tokens, index, "ifnum")?; + let right = parse_integer(tokens, index)?; + let then_ops = parse_sequence(tokens, index, &["else", "fi"])?; + let mut else_ops = Vec::new(); + if let Some(Token::Command(name)) = tokens.get(*index) + && name == "else" + { + *index += 1; + else_ops = parse_sequence(tokens, index, &["fi"])?; + } + match tokens.get(*index) { + Some(Token::Command(name)) if name == "fi" => *index += 1, + _ => return Err("\\ifnum is missing \\fi".to_owned()), + } + ops.push(Op::IfNum { + left, + relation, + right, + then_ops, + else_ops, + }); + } other => return Err(format!("unsupported \\output command `\\{other}`")), }, token => return Err(format!("unexpected token {token:?}")), @@ -291,6 +363,38 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result< } } +fn parse_relation(tokens: &[Token], index: &mut usize, command: &str) -> Result { + let relation = match tokens.get(*index) { + Some(Token::Relation('<')) => Relation::Less, + Some(Token::Relation('>')) => Relation::Greater, + Some(Token::Relation('=')) => Relation::Equal, + _ => return Err(format!("\\{command} expects <, > or =")), + }; + *index += 1; + Ok(relation) +} + +fn parse_integer(tokens: &[Token], index: &mut usize) -> Result { + let integer = match tokens.get(*index) { + Some(Token::Number { value, unit: None }) => { + *index += 1; + Integer::Constant(value.round() as i64) + } + Some(Token::Command(name)) => { + let register = match name.as_str() { + "pageno" => IntegerRegister::PageNo, + "deadcycles" => IntegerRegister::DeadCycles, + "outputpenalty" => IntegerRegister::OutputPenalty, + other => return Err(format!("unsupported integer register `\\{other}`")), + }; + *index += 1; + Integer::Register(register) + } + _ => return Err("expected an integer or integer register".to_owned()), + }; + Ok(integer) +} + fn parse_dimension(tokens: &[Token], index: &mut usize) -> Result { let dimension = match tokens.get(*index) { Some(Token::Number { value, unit }) => { @@ -345,6 +449,22 @@ fn execute(ops: &[Op], context: &OutputContext, shipped: &mut usize) -> Result<( }; execute(if taken { then_ops } else { else_ops }, context, shipped)?; } + Op::IfNum { + left, + relation, + right, + then_ops, + else_ops, + } => { + let left = left.resolve(context); + let right = right.resolve(context); + let taken = match relation { + Relation::Less => left < right, + Relation::Greater => left > right, + Relation::Equal => left == right, + }; + execute(if taken { then_ops } else { else_ops }, context, shipped)?; + } } } Ok(()) @@ -361,6 +481,9 @@ mod tests { vsize: 612 * 65_536, top_skip: 10 * 65_536, max_depth: 0, + output_penalty: 0, + pageno: 1, + deadcycles: 0, } } @@ -397,6 +520,26 @@ mod tests { assert_eq!(program.shipout_count(&small_page).unwrap(), 1); } + #[test] + fn ifnum_reads_page_and_penalty_registers() { + let program = OutputProgram::parse(r"\ifnum\pageno>1\shipout\box255\fi").unwrap(); + let mut context = context(0); + assert_eq!(program.shipout_count(&context).unwrap(), 0); + context.pageno = 2; + assert_eq!(program.shipout_count(&context).unwrap(), 1); + } + + #[test] + fn ifnum_reads_negative_output_penalty() { + let program = + OutputProgram::parse(r"\ifnum\outputpenalty<-9999\shipout\box255\fi").unwrap(); + let context = context(0); + assert_eq!(program.shipout_count(&context).unwrap(), 0); + let mut forced = context; + forced.output_penalty = -10_000; + assert_eq!(program.shipout_count(&forced).unwrap(), 1); + } + #[test] fn unsupported_commands_and_unbalanced_conditionals_are_errors() { assert!(OutputProgram::parse(r"\vbox{}").is_err()); diff --git a/crates/texrra-tex-core/src/page.rs b/crates/texrra-tex-core/src/page.rs index 07c973b..39cc529 100644 --- a/crates/texrra-tex-core/src/page.rs +++ b/crates/texrra-tex-core/src/page.rs @@ -70,6 +70,9 @@ pub struct PageFragment { pub end: usize, /// TeX's page cost for the breakpoint: badness plus penalty. pub cost: i64, + /// Penalty that produced this break: a forced penalty value, the chosen + /// candidate's penalty, or zero for the final page. + pub penalty: i64, /// Badness of the page height against the page goal. pub badness: i64, /// Height of the page box after glue setting. @@ -89,6 +92,7 @@ struct Candidate { depth: i64, shrink: i64, reserved: i64, + penalty: i64, end: usize, next: usize, } @@ -198,7 +202,8 @@ impl PageBuilder { height, depth, badness, - badness + penalty, + badness + *penalty, + *penalty, self.insertion_space(nodes, start, end, held), ); return Some(( @@ -239,6 +244,7 @@ impl PageBuilder { best.depth, best.badness, best.cost, + best.penalty, self.insertion_space(nodes, start, best.end, held), ); Some(( @@ -311,6 +317,7 @@ impl PageBuilder { let badness = self.badness(height, reserved, stretch, shrink); Candidate { cost: badness + penalty, + penalty, badness, height, depth, @@ -352,12 +359,14 @@ impl PageBuilder { depth: i64, badness: i64, cost: i64, + penalty: i64, insertions: Vec, ) -> PageFragment { PageFragment { start, end, cost, + penalty, badness, height, depth, @@ -400,6 +409,16 @@ mod tests { VerticalNode::Glue(VerticalGlue::new(width, stretch, shrink)) } + #[test] + fn forced_penalty_breaks_record_the_penalty() { + let builder = PageBuilder::new(100); + let nodes = vec![box_(20, 0), VerticalNode::Penalty(-10_000), box_(20, 0)]; + let pages = builder.build(&nodes); + assert_eq!(pages.len(), 2); + assert_eq!(pages[0].penalty, -10_000); + assert_eq!(pages[1].penalty, 0); + } + #[test] fn breaks_before_the_page_overflows() { let builder = PageBuilder::new(100); diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 2f34282..496d8e1 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`). 344 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 349 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -69,10 +69,12 @@ yet generic `fil`/`fill` glue documents made of box/glue/penalty/mark units and insertion classes (per-class limits with held-over material), but floats and incremental checkpoint replay still use the scrolling builder, and the interpreted - `\output` subset handles `\shipout`/`\ifdim` only; + `\output` subset handles `\shipout`, `\ifdim` and `\ifnum` over page + registers such as `\pageno`, `\outputpenalty` and `\deadcycles`; 3. `\insert` classes model `\count`/`\dimen`/`\skip` but are not TeX registers addressed by number; the interpreted output routine covers page - shipping and `\ifdim` comparisons but not the full `\output` machinery; + shipping and `\ifdim`/`\ifnum` comparisons but not the full `\output` + machinery; 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; @@ -242,9 +244,9 @@ Scope: 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); -- output: `\output` as an interpreted token list (`\shipout\box255`, `\ifdim` - over page registers landed), `\outputpenalty`, `\deadcycles`, page display - list assembly; +- output: `\output` as an interpreted token list (`\shipout\box255`, `\ifdim`, + `\ifnum`, `\outputpenalty`, `\pageno` and `\deadcycles` landed), page + display list assembly; - floats: TeX-compatible policy module used by the default output routine (top/bottom fractions and counts already exist). @@ -266,7 +268,7 @@ dimension assignments from the source. Insertion classes are placed by the paged builder with their limits and held-over material; 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 subset. +interpreter past the shipout/ifdim/ifnum subset. Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks); page counts identical and first/last baselines within 1pt of pdfLaTeX. @@ -409,7 +411,7 @@ Acceptance: corpus green or explicitly listed; CI documented. | goal | phases | deliverable | | --- | --- | --- | -| G1 (current) | P0, P1, P2 | TeX-exact paragraphs, vertical list, page builder, interpreted `\output` (shipout/ifdim subset landed) | +| G1 (current) | P0, P1, P2 | TeX-exact paragraphs, vertical list, page builder, interpreted `\output` (shipout/ifdim/ifnum subset landed) | | G2 | P3, P4 | tables and math at L2/L3 | | G3 | P5 | Computer Modern fonts, NFSS, pixel parity for text/math | | G4 | P6 | class execution (article, journal) | diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 2e790d9..f79afc7 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, while the scrolling builder remains the default; `\output` is interpreted for a `\shipout`/`\ifdim` subset | +| 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, while the scrolling builder remains the default; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum` 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 | @@ -295,7 +295,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` register subset | +| 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` | | 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 | @@ -324,7 +324,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 seven unit tests. `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` and `\ifdim` over page registers), 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. +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` and `\ifnum` 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. 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. @@ -332,7 +332,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 226 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 344 tests (226 route-D unit, 7 route-D integration, 13 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 231 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 349 tests (231 route-D unit, 7 route-D integration, 13 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 @@ -371,11 +371,11 @@ deliberately open rather than approximated: 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 - the `\output` interpreter only covers the shipout/ifdim subset (explicit + the `\output` interpreter only covers the shipout/ifdim/ifnum 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. - **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and - math limit policies are only partially modeled; `OutputRoutine::wants_break` can force a page break between units, and insertion material is stacked by class from the page bottom; `Document::output_routine` is interpreted per page by `output::OutputProgram` for the shipout/ifdim subset, while `OutputRoutine` remains the Rust hook. + math limit policies are only partially modeled; `OutputRoutine::wants_break` can force a page break between units, and insertion material is stacked by class from the page bottom; `Document::output_routine` is interpreted per page by `output::OutputProgram` for the shipout/ifdim/ifnum subset (with `\pageno`, `\outputpenalty`, `\deadcycles`), while `OutputRoutine` remains the Rust hook. - Page hashes cover rendered items/insertions/marks/floats, not source-dependency metadata, so replaying an earlier page cannot change its hash merely by re-attaching source hashes.