diff --git a/README.md b/README.md index dc6ec25..4d7ceb2 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. 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` 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 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 3199b53..f3525db 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -1,5 +1,6 @@ pub mod cmr10; pub mod math; +pub mod output; pub mod page; pub mod paragraph; pub mod pdf; @@ -623,6 +624,10 @@ pub struct Document { /// Extra vertical displacement of the page origin (`\voffset`). #[serde(default)] pub v_offset: i64, + /// TeX `\output` token list, interpreted by [`output::OutputProgram`]. + /// `None` ships every page the builder produces. + #[serde(default)] + pub output_routine: Option, } fn default_text_fraction() -> u8 { @@ -683,6 +688,7 @@ impl Document { par_skip: 0, h_offset: 0, v_offset: 0, + output_routine: None, } } @@ -1722,6 +1728,24 @@ impl Engine { page.seal_in_place(); pages.push(page); } + if let Some(source) = &document.output_routine { + let program = output::OutputProgram::parse(source).ok()?; + let mut shipped = Vec::new(); + for page in pages { + let page_total: i64 = page.items.iter().map(item_height).sum(); + let context = output::OutputContext { + page_goal: document.page_goal, + page_total, + vsize: document.page_goal, + top_skip: document.top_skip, + max_depth: document.max_depth, + }; + if program.shipout_count(&context).ok()? > 0 { + shipped.push(page); + } + } + pages = shipped; + } let count = pages.len(); Some(Self { layout: Layout { @@ -5039,6 +5063,48 @@ mod tests { assert!(layout.pages()[1].items.is_empty()); } + #[test] + fn interpreted_output_can_drop_pages() { + let mut document = Document::new( + 100, + vec![ + Unit::rule(1, 80, 40), + Unit::penalty(2, -10_000), + Unit::rule(3, 80, 80), + ], + ); + document.output_routine = Some(r"\ifdim\pagetotal>50\shipout\box255\fi".to_owned()); + let layout = Engine::layout_paged(&document).expect("output routine is page-buildable"); + assert_eq!(layout.pages().len(), 1); + assert_eq!(layout.pages()[0].items.len(), 1); + match &layout.pages()[0].items[0] { + VerticalItem::Rule { height, .. } => assert_eq!(*height, 80), + other => panic!("unexpected item {other:?}"), + } + } + + #[test] + fn interpreted_output_ships_every_page_when_asked_to() { + let mut document = Document::new( + 100, + vec![ + Unit::rule(1, 80, 40), + Unit::penalty(2, -10_000), + Unit::rule(3, 80, 80), + ], + ); + document.output_routine = Some(r"\shipout\box255".to_owned()); + let layout = Engine::layout_paged(&document).expect("output routine is page-buildable"); + assert_eq!(layout.pages().len(), 2); + } + + #[test] + fn invalid_output_routines_fall_back_to_the_scrolling_builder() { + let mut document = Document::new(100, vec![Unit::rule(1, 80, 40)]); + document.output_routine = Some(r"\vbox{}".to_owned()); + assert!(Engine::layout_paged(&document).is_none()); + } + #[test] fn paged_layout_edit_relayouts_and_reports_changes() { let style = ParagraphStyle { diff --git a/crates/texrra-tex-core/src/output.rs b/crates/texrra-tex-core/src/output.rs new file mode 100644 index 0000000..2a1a270 --- /dev/null +++ b/crates/texrra-tex-core/src/output.rs @@ -0,0 +1,406 @@ +//! A small interpreter for TeX's `\output` token list. +//! +//! Only the subset that decides *which* page box leaves the page builder is +//! supported today: `\shipout\box255`, `\relax`, `\message{...}` and +//! `\ifdim` comparisons over the page registers `\pagegoal`, `\pagetotal`, +//! `\vsize`, `\topskip` and `\maxdepth`. Anything else is a parse error, which +//! makes `Engine::layout_paged` fall back to the scrolling builder. + +use std::fmt; + +/// Page registers visible to the output routine. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OutputContext { + /// TeX `\pagegoal`: the goal the current page was built for. + pub page_goal: i64, + /// TeX `\pagetotal`: the height accumulated on the current page. + pub page_total: i64, + /// TeX `\vsize`: the configured page height. + pub vsize: i64, + /// TeX `\topskip`. + pub top_skip: i64, + /// TeX `\maxdepth`. + pub max_depth: i64, +} + +/// A parsed `\output` program. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OutputProgram { + ops: Vec, +} + +impl OutputProgram { + pub fn parse(source: &str) -> Result { + let tokens = lex(source)?; + let mut index = 0; + let ops = parse_sequence(&tokens, &mut index, &[])?; + if index != tokens.len() { + return Err(format!("unexpected token {:?}", tokens[index])); + } + Ok(Self { ops }) + } + + /// Execute the program for one page and return how many times it called + /// `\shipout`. + pub fn shipout_count(&self, context: &OutputContext) -> Result { + let mut shipped = 0; + execute(&self.ops, context, &mut shipped)?; + Ok(shipped) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Op { + Shipout, + Relax, + Message(String), + IfDim { + left: Dimension, + relation: Relation, + right: Dimension, + then_ops: Vec, + else_ops: Vec, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Dimension { + Constant(i64), + Register(Register), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Register { + PageGoal, + PageTotal, + Vsize, + TopSkip, + MaxDepth, +} + +impl Dimension { + fn resolve(self, context: &OutputContext) -> i64 { + match self { + Self::Constant(value) => value, + Self::Register(register) => match register { + Register::PageGoal => context.page_goal, + Register::PageTotal => context.page_total, + Register::Vsize => context.vsize, + Register::TopSkip => context.top_skip, + Register::MaxDepth => context.max_depth, + }, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Relation { + Less, + Greater, + Equal, +} + +#[derive(Clone, Debug, PartialEq)] +enum Token { + Command(String), + Number { value: f64, unit: Option }, + Open, + Close, + Relation(char), +} + +impl fmt::Display for Token { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Command(name) => write!(formatter, "\\{name}"), + Self::Number { value, unit } => match unit { + Some(unit) => write!(formatter, "{value}{unit}"), + None => write!(formatter, "{value}"), + }, + Self::Open => write!(formatter, "{{"), + Self::Close => write!(formatter, "}}"), + Self::Relation(relation) => write!(formatter, "{relation}"), + } + } +} + +fn lex(source: &str) -> Result, String> { + let chars: Vec = source.chars().collect(); + let mut tokens = Vec::new(); + let mut index = 0; + while index < chars.len() { + let character = chars[index]; + match character { + ' ' | '\t' | '\n' | '\r' => index += 1, + '%' => { + while index < chars.len() && chars[index] != '\n' { + index += 1; + } + } + '\\' => { + index += 1; + let start = index; + while index < chars.len() && chars[index].is_ascii_alphabetic() { + index += 1; + } + if start == index { + return Err("expected a control sequence after `\\`".to_owned()); + } + tokens.push(Token::Command(chars[start..index].iter().collect())); + } + '{' => { + tokens.push(Token::Open); + index += 1; + } + '}' => { + tokens.push(Token::Close); + index += 1; + } + '<' | '>' | '=' => { + tokens.push(Token::Relation(character)); + 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 }); + } + other => return Err(format!("unexpected character `{other}`")), + } + } + Ok(tokens) +} + +fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result, String> { + let mut ops = Vec::new(); + while *index < tokens.len() { + if let Token::Command(name) = &tokens[*index] + && stop.contains(&name.as_str()) + { + return Ok(ops); + } + match &tokens[*index] { + Token::Command(name) => match name.as_str() { + "shipout" => { + *index += 1; + let boxed = match tokens.get(*index) { + Some(Token::Command(box_command)) if box_command == "box" => { + *index += 1; + match tokens.get(*index) { + Some(Token::Number { value, unit: None }) + if (*value - 255.0).abs() < f64::EPSILON => + { + *index += 1; + true + } + _ => false, + } + } + _ => false, + }; + if !boxed { + return Err("\\shipout expects \\box255".to_owned()); + } + ops.push(Op::Shipout); + } + "relax" => { + *index += 1; + ops.push(Op::Relax); + } + "message" => { + *index += 1; + if !matches!(tokens.get(*index), Some(Token::Open)) { + return Err("\\message expects a braced argument".to_owned()); + } + *index += 1; + let mut text = String::new(); + while *index < tokens.len() { + match &tokens[*index] { + Token::Close => { + *index += 1; + break; + } + token => { + text.push_str(&token.to_string()); + *index += 1; + } + } + } + ops.push(Op::Message(text)); + } + "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 right = parse_dimension(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("\\ifdim is missing \\fi".to_owned()), + } + ops.push(Op::IfDim { + left, + relation, + right, + then_ops, + else_ops, + }); + } + other => return Err(format!("unsupported \\output command `\\{other}`")), + }, + token => return Err(format!("unexpected token {token:?}")), + } + } + if stop.is_empty() { + Ok(ops) + } else { + Err(format!("expected one of {stop:?}")) + } +} + +fn parse_dimension(tokens: &[Token], index: &mut usize) -> Result { + let dimension = match tokens.get(*index) { + Some(Token::Number { value, unit }) => { + let factor = match unit.as_deref() { + None | Some("sp") => 1.0, + Some("pt") => 65_536.0, + Some("bp") => 65_782.0, + Some("in") => 4_736_286.0, + Some("cm") => 1_864_680.0, + Some("mm") => 186_468.0, + Some("pc") => 786_432.0, + Some(other) => return Err(format!("unsupported unit `{other}`")), + }; + *index += 1; + Dimension::Constant((value * factor).round() as i64) + } + Some(Token::Command(name)) => { + let register = match name.as_str() { + "pagegoal" => Register::PageGoal, + "pagetotal" => Register::PageTotal, + "vsize" => Register::Vsize, + "topskip" => Register::TopSkip, + "maxdepth" => Register::MaxDepth, + other => return Err(format!("unsupported page register `\\{other}`")), + }; + *index += 1; + Dimension::Register(register) + } + _ => return Err("expected a dimension or page register".to_owned()), + }; + Ok(dimension) +} + +fn execute(ops: &[Op], context: &OutputContext, shipped: &mut usize) -> Result<(), String> { + for op in ops { + match op { + Op::Shipout => *shipped += 1, + Op::Relax | Op::Message(_) => {} + Op::IfDim { + 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(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn context(page_total: i64) -> OutputContext { + OutputContext { + page_goal: 612 * 65_536, + page_total, + vsize: 612 * 65_536, + top_skip: 10 * 65_536, + max_depth: 0, + } + } + + #[test] + fn ships_the_page_box() { + let program = OutputProgram::parse(r"\shipout\box255").unwrap(); + assert_eq!(program.shipout_count(&context(0)).unwrap(), 1); + } + + #[test] + fn conditional_ships_only_large_pages() { + let program = OutputProgram::parse(r"\ifdim\pagetotal>50pt\shipout\box255\fi").unwrap(); + assert_eq!(program.shipout_count(&context(40 * 65_536)).unwrap(), 0); + assert_eq!(program.shipout_count(&context(60 * 65_536)).unwrap(), 1); + } + + #[test] + fn else_branch_ships_small_pages() { + let program = + OutputProgram::parse(r"\ifdim\pagetotal>50pt\shipout\box255\else\shipout\box255\fi") + .unwrap(); + let mut small = context(40 * 65_536); + small.page_total = 40 * 65_536; + assert_eq!(program.shipout_count(&small).unwrap(), 1); + assert_eq!(program.shipout_count(&context(70 * 65_536)).unwrap(), 1); + } + + #[test] + fn page_goal_register_is_visible() { + let program = OutputProgram::parse(r"\ifdim\pagegoal<600pt\shipout\box255\fi").unwrap(); + assert_eq!(program.shipout_count(&context(0)).unwrap(), 0); + let mut small_page = context(0); + small_page.page_goal = 500 * 65_536; + assert_eq!(program.shipout_count(&small_page).unwrap(), 1); + } + + #[test] + fn unsupported_commands_and_unbalanced_conditionals_are_errors() { + assert!(OutputProgram::parse(r"\vbox{}").is_err()); + assert!(OutputProgram::parse(r"\ifdim\pagetotal>1pt\shipout\box255").is_err()); + assert!(OutputProgram::parse(r"\shipout").is_err()); + } +} diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 2380ed8..2f34282 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`). 336 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 344 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -68,11 +68,11 @@ yet generic `fil`/`fill` glue setting, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it for 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 an interpreted - `\output` is absent; + checkpoint replay still use the scrolling builder, and the interpreted + `\output` subset handles `\shipout`/`\ifdim` only; 3. `\insert` classes model `\count`/`\dimen`/`\skip` but are not TeX - registers addressed by number, and there is still no interpreted output - routine; + registers addressed by number; the interpreted output routine covers page + shipping and `\ifdim` 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,8 +242,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, `\box255`, `\shipout`, - `\outputpenalty`, `\deadcycles`, page display list assembly; +- output: `\output` as an interpreted token list (`\shipout\box255`, `\ifdim` + over page registers landed), `\outputpenalty`, `\deadcycles`, page display + list assembly; - floats: TeX-compatible policy module used by the default output routine (top/bottom fractions and counts already exist). @@ -264,8 +265,8 @@ 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; 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, then paper margins and the interpreted -`\output`. +it has a paged equivalent. Next: port those paths and paper margins, then extend the `\output` +interpreter past the shipout/ifdim subset. Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks); page counts identical and first/last baselines within 1pt of pdfLaTeX. @@ -408,7 +409,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` | +| G1 (current) | P0, P1, P2 | TeX-exact paragraphs, vertical list, page builder, interpreted `\output` (shipout/ifdim 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 00f2500..2e790d9 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; interpreted `\output` 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 | | 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 | @@ -237,8 +237,11 @@ oracle fixture is ignored. attached to `Page::insertions` and reserves height from the page goal. `VerticalItem::Mark` material is collected into `Page::marks` and included in the page hash. `OutputRoutine::shipout` runs before sealing and may - mutate each page; this models the `\output` stage in Rust rather than as - an interpreted token list, and cannot yet change page goals. Top `Float` + mutate each page; this models the `\output` stage in Rust. The interpreted + subset lives in `output::OutputProgram` (`Document::output_routine`), which + understands `\shipout\box255`, `\relax`, `\message{...}` and `\ifdim` / + `\else` / `\fi` over the page registers `\pagegoal`, `\pagetotal`, `\vsize`, + `\topskip` and `\maxdepth`; it cannot yet change page goals. Top `Float` material is deferred to the next page when it arrives late; bottom floats reserve height on the current page and must satisfy `Document.text_fraction_percent` (default 50%); a page holding only floats @@ -292,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; interpreted `\output` absent | +| 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 | | 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 | @@ -321,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. 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 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. 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. @@ -329,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 218 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 336 tests (218 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 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. ### M0 incremental demo @@ -367,12 +370,12 @@ deliberately open rather than approximated: 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 and an interpreted - `\output` remain open (explicit + equivalent before it can become the default; paper margins remain open, and + the `\output` interpreter only covers the shipout/ifdim 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; `\output` is still Rust code rather than interpreted tokens. + 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. - 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.