From c2ba59906c073fecaf52a6f5c7ca23d203342fa8 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 12:28:09 +0800 Subject: [PATCH] Read insertion class registers in the output routine --- crates/texrra-tex-core/src/lib.rs | 39 ++++++++++ crates/texrra-tex-core/src/output.rs | 105 ++++++++++++++++++++++++++- docs/TEX_CORE.md | 4 +- 3 files changed, 145 insertions(+), 3 deletions(-) diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index ef201b6..592d584 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -1873,6 +1873,15 @@ impl Engine { let mut shipped = Vec::new(); for (index, page) in pages.into_iter().enumerate() { let page_total: i64 = page.items.iter().map(item_height).sum(); + let mut insertion_counts = [1000_i64; 256]; + let mut insertion_dimens = [0_i64; 256]; + let mut insertion_skips = [0_i64; 256]; + for class in &document.insertion_classes { + let slot = class.number as usize; + insertion_counts[slot] = i64::from(class.multiplier); + insertion_dimens[slot] = class.max_height.unwrap_or(0); + insertion_skips[slot] = class.skip.unwrap_or(document.insertion_skip); + } let context = output::OutputContext { page_goal: page_goals.get(index).copied().unwrap_or(document.page_goal), page_total, @@ -1886,6 +1895,9 @@ impl Engine { top_skip: document.top_skip, max_depth: document.max_depth, output_penalty: page_penalties.get(index).copied().unwrap_or(0), + insertion_counts, + insertion_dimens, + insertion_skips, pageno: index as i64 + 1, deadcycles: 0, }; @@ -5389,6 +5401,33 @@ mod tests { assert_eq!(engine.pages().len(), 1); } + #[test] + fn output_routine_reads_insertion_registers() { + let mut document = Document::new(100, vec![Unit::rule(0, 10, 40)]); + document.insertion_classes = vec![InsertionClass { + number: 1, + fraction_percent: 100, + max_height: Some(7 * 65_536), + skip: Some(3 * 65_536), + multiplier: 2000, + }]; + + document.output_routine = + Some(r"\ifnum\count1=2000\shipout\box255\else\relax\fi".to_owned()); + let engine = Engine::layout_paged(&document).expect("paged"); + assert_eq!(engine.pages().len(), 1); + + document.output_routine = + Some(r"\ifdim\dimen1>6pt\shipout\box255\else\relax\fi".to_owned()); + let engine = Engine::layout_paged(&document).expect("paged"); + assert_eq!(engine.pages().len(), 1); + + document.output_routine = + Some(r"\ifnum\count1=1000\shipout\box255\else\relax\fi".to_owned()); + let engine = Engine::layout_paged(&document).expect("paged"); + assert_eq!(engine.pages().len(), 0); + } + #[test] fn interpreted_output_can_ship_only_odd_pages() { let mut document = Document::new(100, Vec::new()); diff --git a/crates/texrra-tex-core/src/output.rs b/crates/texrra-tex-core/src/output.rs index e1a759f..8a7a71e 100644 --- a/crates/texrra-tex-core/src/output.rs +++ b/crates/texrra-tex-core/src/output.rs @@ -10,7 +10,7 @@ use std::fmt; /// Page registers visible to the output routine. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct OutputContext { /// TeX `\pagegoal`: the goal the current page was built for. pub page_goal: i64, @@ -40,6 +40,37 @@ pub struct OutputContext { pub pageno: i64, /// TeX `\deadcycles`: output routines since the last shipout. pub deadcycles: i64, + /// TeX `\count` for insertion class `n`: the insertion multiplier. + pub insertion_counts: [i64; 256], + /// TeX `\dimen` for insertion class `n`: the class' maximum size. + pub insertion_dimens: [i64; 256], + /// TeX `\skip` for insertion class `n`. + pub insertion_skips: [i64; 256], +} + +impl Default for OutputContext { + fn default() -> Self { + Self { + page_goal: 0, + page_total: 0, + page_depth: 0, + page_stretch: 0, + page_fil_stretch: 0, + page_fill_stretch: 0, + page_filll_stretch: 0, + page_shrink: 0, + vsize: 0, + top_skip: 0, + max_depth: 0, + output_penalty: 0, + pageno: 0, + deadcycles: 0, + // TeX's default insertion multiplier is 1000. + insertion_counts: [1000; 256], + insertion_dimens: [0; 256], + insertion_skips: [0; 256], + } + } } /// A parsed `\output` program. @@ -118,6 +149,8 @@ enum Register { Vsize, TopSkip, MaxDepth, + InsertionDimen(u8), + InsertionSkip(u8), } impl Dimension { @@ -136,6 +169,8 @@ impl Dimension { Register::Vsize => context.vsize, Register::TopSkip => context.top_skip, Register::MaxDepth => context.max_depth, + Register::InsertionDimen(class) => context.insertion_dimens[class as usize], + Register::InsertionSkip(class) => context.insertion_skips[class as usize], }, } } @@ -152,6 +187,7 @@ enum IntegerRegister { PageNo, DeadCycles, OutputPenalty, + InsertionCount(u8), } impl Integer { @@ -162,6 +198,7 @@ impl Integer { IntegerRegister::PageNo => context.pageno, IntegerRegister::DeadCycles => context.deadcycles, IntegerRegister::OutputPenalty => context.output_penalty, + IntegerRegister::InsertionCount(class) => context.insertion_counts[class as usize], }, } } @@ -468,6 +505,18 @@ fn parse_integer(tokens: &[Token], index: &mut usize) -> Result "pageno" => IntegerRegister::PageNo, "deadcycles" => IntegerRegister::DeadCycles, "outputpenalty" => IntegerRegister::OutputPenalty, + "count" => { + *index += 1; + if matches!( + tokens.get(*index), + Some(Token::Number { value, unit: None }) if value.round() as i64 == 0 + ) { + *index += 1; + return Ok(Integer::Register(IntegerRegister::PageNo)); + } + let class = parse_insertion_class(tokens, index, "\\count", false)?; + return Ok(Integer::Register(IntegerRegister::InsertionCount(class))); + } other => return Err(format!("unsupported integer register `\\{other}`")), }; *index += 1; @@ -507,6 +556,16 @@ fn parse_dimension(tokens: &[Token], index: &mut usize) -> Result Register::Vsize, "topskip" => Register::TopSkip, "maxdepth" => Register::MaxDepth, + "dimen" => { + *index += 1; + let class = parse_insertion_class(tokens, index, "\\dimen", true)?; + return Ok(Dimension::Register(Register::InsertionDimen(class))); + } + "skip" => { + *index += 1; + let class = parse_insertion_class(tokens, index, "\\skip", true)?; + return Ok(Dimension::Register(Register::InsertionSkip(class))); + } other => return Err(format!("unsupported page register `\\{other}`")), }; *index += 1; @@ -517,6 +576,28 @@ fn parse_dimension(tokens: &[Token], index: &mut usize) -> Result Result { + match tokens.get(*index) { + Some(Token::Number { value, unit: None }) => { + let class = value.round() as i64; + let lowest = if allow_zero { 0 } else { 1 }; + if !(lowest..=255).contains(&class) { + return Err(format!( + "`{command}` needs an insertion class number between {lowest} and 255" + )); + } + *index += 1; + Ok(class as u8) + } + _ => Err(format!("`{command}` needs an insertion class number")), + } +} + fn execute(ops: &[Op], context: &OutputContext, shipped: &mut usize) -> Result<(), String> { for op in ops { match op { @@ -603,6 +684,7 @@ mod tests { output_penalty: 0, pageno: 1, deadcycles: 0, + ..OutputContext::default() } } @@ -655,6 +737,27 @@ mod tests { assert_eq!(program.shipout_count(&context(0)).unwrap(), 0); } + #[test] + fn insertion_registers_are_visible() { + let mut context = context(0); + context.insertion_counts[1] = 2000; + context.insertion_dimens[1] = 7 * 65_536; + context.insertion_skips[1] = 3 * 65_536; + + let count = OutputProgram::parse(r"\ifnum\count1=2000\shipout\box255\fi").unwrap(); + assert_eq!(count.shipout_count(&context).unwrap(), 1); + assert_eq!(count.shipout_count(&self::context(0)).unwrap(), 0); + + let dimen = OutputProgram::parse(r"\ifdim\dimen1>6pt\shipout\box255\fi").unwrap(); + assert_eq!(dimen.shipout_count(&context).unwrap(), 1); + + let skip = OutputProgram::parse(r"\ifdim\skip1<4pt\shipout\box255\fi").unwrap(); + assert_eq!(skip.shipout_count(&context).unwrap(), 1); + + let pageno = OutputProgram::parse(r"\ifnum\count0=1\shipout\box255\fi").unwrap(); + assert_eq!(pageno.shipout_count(&context).unwrap(), 1); + } + #[test] fn conditional_ships_only_large_pages() { let program = OutputProgram::parse(r"\ifdim\pagetotal>50pt\shipout\box255\fi").unwrap(); diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index c4ca68c..f61749a 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -116,7 +116,7 @@ and justification. | --- | --- | --- | | M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 | | M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode` and vertical-glue fixtures; generic fil glue and `\prevgraf` next | -| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep` and a `\bottomfraction` cap) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers, `PageFragment::penalty` carries the break penalty, and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine | +| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep` and a `\bottomfraction` cap) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers, insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`), `PageFragment::penalty` carries the break penalty, and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine | | M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; no booktabs/longtable parity yet | | M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; no CMEX size variants or TeX math spacing classes yet | | M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | @@ -346,7 +346,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 267 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 391 tests (267 route-D unit, 7 route-D integration, 17 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 269 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 393 tests (269 route-D unit, 7 route-D integration, 17 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo