From 7a42ddc1bf72ddee6d610c27ab50f0d22dc6baad Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 13:18:21 +0800 Subject: [PATCH] Expose prevgraf to the output routine --- crates/texrra-tex-core/src/lib.rs | 38 ++++++++++++++++++++++++++++ crates/texrra-tex-core/src/output.rs | 23 +++++++++++++++++ docs/ROUTE_D_PLAN.md | 9 ++++--- docs/TEX_CORE.md | 4 +-- 4 files changed, 68 insertions(+), 6 deletions(-) diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 886f2e0..24a22a6 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -920,6 +920,19 @@ fn item_height(item: &VerticalItem) -> i64 { } } +/// TeX `\prevgraf` for a finished page: the line count of the last paragraph +/// broken on it. +fn page_prev_graf(page: &Page) -> i64 { + page.items + .iter() + .rev() + .find_map(|item| match item { + VerticalItem::Paragraph(paragraph) => Some(paragraph.lines.len() as i64), + _ => None, + }) + .unwrap_or(0) +} + /// Take the longest prefix of `items` whose reserved height fits `capacity`. /// /// Returns `(accepted, remainder, reserved_height)`. A single item larger than @@ -1923,6 +1936,7 @@ impl Engine { insertion_skips, pageno, deadcycles, + prev_graf: page_prev_graf(&page), }; let shipped_now = program.shipout_count(&mut context).ok()?; pageno = context.pageno.wrapping_add(1); @@ -2097,6 +2111,7 @@ impl Engine { insertion_counts: [1000; 256], insertion_dimens: [0; 256], insertion_skips: [0; 256], + prev_graf: page_prev_graf(&page), pageno, deadcycles, }; @@ -5849,6 +5864,29 @@ mod tests { ); } + #[test] + fn page_prev_graf_counts_the_last_paragraph_lines() { + let style = ParagraphStyle { + line_width: 60 * 65_536, + par_indent: 0, + ..ParagraphStyle::default() + }; + let paragraph = layout_paragraph_with_font( + "alpha beta gamma delta epsilon zeta eta theta", + &style, + &Cmr10Metrics::Roman, + ); + let lines = paragraph.lines.len() as i64; + assert!(lines > 1, "fixture should wrap, got {lines} lines"); + + let mut page = Page::empty(); + page.items.push(VerticalItem::Paragraph(paragraph)); + assert_eq!(page_prev_graf(&page), lines); + + let empty = Page::empty(); + assert_eq!(page_prev_graf(&empty), 0); + } + #[test] fn output_routine_sees_the_page_depth() { let math = Unit { diff --git a/crates/texrra-tex-core/src/output.rs b/crates/texrra-tex-core/src/output.rs index 27b070a..c68a1df 100644 --- a/crates/texrra-tex-core/src/output.rs +++ b/crates/texrra-tex-core/src/output.rs @@ -42,6 +42,8 @@ pub struct OutputContext { pub pageno: i64, /// TeX `\deadcycles`: output routines since the last shipout. pub deadcycles: i64, + /// TeX `\prevgraf`: lines in the paragraph most recently broken. + pub prev_graf: 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. @@ -67,6 +69,7 @@ impl Default for OutputContext { output_penalty: 0, pageno: 0, deadcycles: 0, + prev_graf: 0, // TeX's default insertion multiplier is 1000. insertion_counts: [1000; 256], insertion_dimens: [0; 256], @@ -223,6 +226,7 @@ enum IntegerRegister { PageNo, DeadCycles, OutputPenalty, + PrevGraf, InsertionCount(u8), } @@ -234,6 +238,7 @@ impl Integer { IntegerRegister::PageNo => context.pageno, IntegerRegister::DeadCycles => context.deadcycles, IntegerRegister::OutputPenalty => context.output_penalty, + IntegerRegister::PrevGraf => context.prev_graf, IntegerRegister::InsertionCount(class) => context.insertion_counts[class as usize], }, } @@ -581,6 +586,7 @@ fn parse_integer(tokens: &[Token], index: &mut usize) -> Result "pageno" => IntegerRegister::PageNo, "deadcycles" => IntegerRegister::DeadCycles, "outputpenalty" => IntegerRegister::OutputPenalty, + "prevgraf" => IntegerRegister::PrevGraf, "count" => { *index += 1; if matches!( @@ -741,6 +747,7 @@ fn execute(ops: &[Op], context: &mut OutputContext, shipped: &mut usize) -> Resu IntegerRegister::PageNo => context.pageno = value, IntegerRegister::DeadCycles => context.deadcycles = value, IntegerRegister::OutputPenalty => context.output_penalty = value, + IntegerRegister::PrevGraf => context.prev_graf = value, IntegerRegister::InsertionCount(class) => { context.insertion_counts[*class as usize] = value; } @@ -786,6 +793,7 @@ mod tests { output_penalty: 0, pageno: 1, deadcycles: 0, + prev_graf: 0, ..OutputContext::default() } } @@ -852,6 +860,21 @@ mod tests { assert!(!plain.assigns_vsize()); } + #[test] + fn output_routine_sees_prevgraf() { + let mut context = context(0); + context.prev_graf = 4; + let program = OutputProgram::parse(r"\ifnum\prevgraf=4\pageno=9\fi").unwrap(); + assert_eq!(program.shipout_count(&mut context).unwrap(), 0); + assert_eq!(context.pageno, 9); + + let copy = OutputProgram::parse(r"\pageno=\prevgraf").unwrap(); + let mut context = self::context(0); + context.prev_graf = 6; + copy.shipout_count(&mut context).unwrap(); + assert_eq!(context.pageno, 6); + } + #[test] fn output_routine_can_assign_registers() { let mut context = context(0); diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 96a5483..a8af961 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`). 417 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 419 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -60,8 +60,9 @@ Known gaps, in dependency order: with or without `fil`, default `\sfcode` sentence spacing, `\looseness`, and `\baselineskip`/`\lineskip`/`\parskip` interline glue), custom `\sfcode` overrides, explicit `\spaceskip`/`\xspaceskip`, - `\raggedright` (infinite `\rightskip` fil), and explicit - `\hfil`/`\hfill` glue orders, but not yet `\prevgraf`; + `\raggedright` (infinite `\rightskip` fil), explicit + `\hfil`/`\hfill` glue orders, and `\prevgraf` visibility in the output + routine; 2. the default builder is still the scrolling builder with fraction policies, now with line-level paragraph splits; `page::PageBuilder` implements the candidate-breakpoint cost model (badness + penalty, glue @@ -228,7 +229,7 @@ not fit is split at line boundaries: the next fragment continues on the next page without a `\parskip`, and a single unsplittable line may overflow at the top of a page (see `Paragraph::split_at`). -Still open: `\prevgraf`, explicit +Still open: explicit `\vskip` classes (`\smallskip` and friends), double/final hyphen demerit oracle fixtures. The breaker now rejects overfull lines outside the emergency pass, exactly like TeX, so `\tolerance` cannot diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 57afc3c..2050c92 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -115,7 +115,7 @@ and justification. | Milestone | Content | Acceptance | | --- | --- | --- | | 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`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders and vertical-glue fixtures; `\prevgraf` next | +| 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`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures | | 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`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) 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 and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets later pages when the document has no insertions or floats), insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments for the duration of the routine, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `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 | @@ -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 284 unit tests plus seven route-D integration tests and twenty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 417 tests (284 route-D unit, 7 route-D integration, 24 oracle, 71 v1 integration, 24 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 286 unit tests plus seven route-D integration tests and twenty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 419 tests (286 route-D unit, 7 route-D integration, 24 oracle, 71 v1 integration, 24 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo