diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 29951ca..7345e77 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -601,6 +601,9 @@ fn default_insertion_multiplier() -> u32 { pub struct Document { pub units: Vec, pub page_goal: i64, + /// Unit indices that start on a fresh page (TeX `\newpage` forced breaks). + #[serde(default)] + pub page_breaks: Vec, /// TeX `\paperwidth`: width of the output page. #[serde(default = "default_paper_width")] pub paper_width: i64, @@ -744,6 +747,7 @@ impl Document { Self { units, page_goal, + page_breaks: Vec::new(), paper_width: default_paper_width(), paper_height: default_paper_height(), top_skip: 0, @@ -865,6 +869,11 @@ fn document_nodes( let mut items = Vec::new(); let mut previous_paragraph = false; for (index, unit) in document.units.iter().enumerate() { + if document.page_breaks.binary_search(&index).is_ok() { + nodes.push(VerticalNode::Penalty(-10_000)); + owners.push(index); + items.push(VerticalItem::Penalty(-10_000)); + } if unit.space_before > 0 { nodes.push(VerticalNode::Glue(VerticalGlue::new( unit.space_before, @@ -1373,6 +1382,13 @@ impl Engine { used = document.top_skip; insertion_height = 0; } + if document.page_breaks.binary_search(&unit_index).is_ok() && !current.items.is_empty() + { + output.shipout(&mut current, pages.len() + 1); + pages.push(std::mem::replace(&mut current, Page::empty())); + used = document.top_skip; + insertion_height = 0; + } checkpoints.push(Checkpoint { unit_index, page_index: pages.len(), @@ -2417,10 +2433,11 @@ impl Engine { .sum(); // A paragraph is rebuilt line by line, so it may fill the remaining // space of the checkpoint page instead of being pushed to a new one. - let splits = matches!( - next.units[start_index].items.first(), - Some(VerticalItem::Paragraph(_)) - ); + let splits = next.page_breaks.binary_search(&start_index).is_ok() + || matches!( + next.units[start_index].items.first(), + Some(VerticalItem::Paragraph(_)) + ); if !splits && checkpoint.used + edited_height > next.page_goal && !checkpoint.page_items.is_empty() @@ -2444,6 +2461,11 @@ impl Engine { let mut checkpoints = self.layout.checkpoints[..start_index].to_vec(); for (index, unit) in next.units.iter().enumerate().skip(start_index) { + if next.page_breaks.binary_search(&index).is_ok() && !current.items.is_empty() { + pages.push(std::mem::replace(&mut current, Page::empty())); + used = next.top_skip; + insertion_height = 0; + } checkpoints.push(Checkpoint { unit_index: index, page_index: pages.len(), diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index 7bb4795..8ebd82e 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -291,16 +291,26 @@ fn route_pages_text_with( top_skip_pt: i64, ) -> Vec { let mut units = Vec::new(); - for (index, text) in paragraphs.iter().enumerate() { + let mut page_breaks = Vec::new(); + for text in paragraphs { + if text.trim() == "\\newpage" || text.trim() == "\\clearpage" { + page_breaks.push(units.len()); + continue; + } let style = ParagraphStyle { line_width: 345 * PT, par_indent: 15 * PT, line_height: 12 * PT, ..ParagraphStyle::default() }; - units.push(Unit::paragraph_with_style(index as u64 + 1, text, style)); + units.push(Unit::paragraph_with_style( + units.len() as u64 + 1, + text, + style, + )); } let mut document = Document::new(page_goal_pt * PT, units); + document.page_breaks = page_breaks; document.top_skip = top_skip_pt * PT; document.par_skip = par_skip * PT; document.text_float_sep = 0; @@ -659,6 +669,33 @@ fn explicit_sfcode_matches_pdftex() { }); } +/// `\newpage` forces the next paragraph onto a fresh page; page texts and +/// page count must match pdfLaTeX. +#[test] +fn newpage_matches_pdftex_page_breaks() { + let paragraphs = vec![ + "alpha beta gamma delta".to_string(), + "\\newpage".to_string(), + "epsilon zeta eta theta".to_string(), + ]; + let body = "alpha beta gamma delta\n\n\\newpage\n\nepsilon zeta eta theta\\par\n"; + let source = format!( + "\\documentclass[10pt]{{article}}\n\ + \\pdfpagewidth=612bp \\pdfpageheight=792bp\n\ + \\pagestyle{{empty}}\n\ + \\begin{{document}}\n\ + \\hsize=345pt \\parindent=15pt \\parskip=0pt \\topskip=12pt \\vsize=550pt\n\ + {body}\\end{{document}}\n" + ); + let Some(reference) = pdftex_pages(&source) else { + eprintln!("skipping: pdflatex/pdftotext are not installed"); + return; + }; + let ours = route_pages_text(¶graphs, 0); + assert_eq!(ours.len(), reference.len(), "newpage page count"); + assert_eq!(ours, reference, "newpage page text"); +} + #[test] fn pages_break_like_pdftex_for_single_line_paragraphs() { let paragraphs: Vec = (0..100) diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index d183d6d..c5de7e7 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`). 442 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 445 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -301,8 +301,9 @@ interpreter past the shipout/ifdim/ifnum/ifodd/ifcase subset. Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks); page counts identical and first/last baselines within 1pt of pdfLaTeX. -Progress: three page fixtures are wired (single-line paragraphs, `\parskip=6pt` -spacing, and multi-line paragraphs split across pages); each asserts the same +Progress: four page fixtures are wired (single-line paragraphs, `\parskip=6pt` +spacing, multi-line paragraphs split across pages, and `\newpage` forced +breaks); each asserts the same page count and the same per-page text as pdfLaTeX. ### P3 — `\halign` / `\valign` (L2) diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 193b74e..bbf9006 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -347,7 +347,7 @@ M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` be M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item); `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. A standalone `\smallskip`, `\medskip`, `\bigskip` or `\vskip` line between paragraphs becomes the following unit's `space_before` glue, carrying TeX's width plus its `plus`/`minus` parts (`\smallskip` is 3pt plus 1pt minus 1pt, and so on). Both page builders reserve it, the paged builder gets a real breakpoint with the glue's stretch and shrink, and edits preserve all three components; the command no longer leaks into the paragraph text. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and preview pages apply the same offsets to their display list so the editor and -PDF agree. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance`, `\pretolerance`, `\hangindent`/`\hangafter`, `\spaceskip`/`\xspaceskip` and `\frenchspacing` into the paragraph styles; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty`, `\deadcycles` and `\maxdeadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: five page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, and a 30pt `\topskip`) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. +PDF agree. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance`, `\pretolerance`, `\hangindent`/`\hangafter`, `\spaceskip`/`\xspaceskip` and `\frenchspacing` into the paragraph styles; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty`, `\deadcycles` and `\maxdeadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; Route-D sources map a standalone `\newpage` or `\clearpage` onto `Document::page_breaks`, so the next paragraph starts on a fresh page (the paged builder turns each break into a `-10000` penalty node); for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: five page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, and a 30pt `\topskip`) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row heights and cell text widths to scaled points; the painter uses 10pt glyphs in 12pt rows. Rules and spans are painted; tall tables split at row boundaries (`Halign::split_for_height`) with column widths preserved. @@ -355,7 +355,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 296 unit tests plus seven route-D integration tests and twenty-seven oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 442 tests (296 route-D unit, 7 route-D integration, 27 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 11 binary units), with none ignored. v1 remains the live server path. +The crate currently has 296 unit tests plus seven route-D integration tests and twenty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 445 tests (296 route-D unit, 7 route-D integration, 28 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 12 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo diff --git a/src/route_d.rs b/src/route_d.rs index df18583..ed1aa48 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -504,6 +504,8 @@ pub fn edit_json(source: &str, unit: usize) -> Result { #[derive(Clone, PartialEq, Eq)] struct SourceParagraph { text: String, + /// TeX `\newpage` before this paragraph. + page_break: bool, centered: bool, right_aligned: bool, font: ParagraphFont, @@ -562,7 +564,12 @@ fn paragraphs(source: &str) -> Result, String> { } let mut result = Vec::new(); let mut pending = (0_i64, 0_i64, 0_i64); + let mut pending_break = false; for chunk in paragraphs { + if chunk == "\\newpage" || chunk == "\\clearpage" { + pending_break = true; + continue; + } if let Some(skip) = vertical_skip(chunk) { pending.0 += skip.0; pending.1 += skip.1; @@ -574,6 +581,8 @@ fn paragraphs(source: &str) -> Result, String> { first.space_before += pending.0; first.space_stretch += pending.1; first.space_shrink += pending.2; + first.page_break = pending_break; + pending_break = false; pending = (0, 0, 0); } result.extend(blocks); @@ -620,6 +629,7 @@ fn parse_blocks(raw: &str) -> Vec { space_before: 0, space_stretch: 0, space_shrink: 0, + page_break: false, } }) .collect(); @@ -644,6 +654,7 @@ fn parse_blocks(raw: &str) -> Vec { space_before: 0, space_stretch: 0, space_shrink: 0, + page_break: false, }]; } } @@ -677,6 +688,7 @@ fn parse_blocks(raw: &str) -> Vec { space_before: 0, space_stretch: 0, space_shrink: 0, + page_break: false, } }) .collect(); @@ -710,6 +722,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { space_before: 0, space_stretch: 0, space_shrink: 0, + page_break: false, }; } let candidates = [ @@ -730,6 +743,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { space_before: 0, space_stretch: 0, space_shrink: 0, + page_break: false, }; } } @@ -744,6 +758,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { space_before: 0, space_stretch: 0, space_shrink: 0, + page_break: false, } } @@ -823,7 +838,14 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do unit }) .collect(); - Document::new(700 * SCALE, units) + let mut document = Document::new(700 * SCALE, units); + document.page_breaks = paragraphs + .iter() + .enumerate() + .filter(|(_, paragraph)| paragraph.page_break) + .map(|(index, _)| index) + .collect(); + document } fn render_json(document: &Document, engine: &Engine, edit: Option<(&[usize], usize)>) -> String { @@ -1158,4 +1180,17 @@ mod source_tests { assert_eq!(document.units[3].space_stretch, 2 * SCALE); assert_eq!(document.units[3].space_shrink, SCALE); } + #[test] + fn newpage_starts_a_new_page() { + let source = "Alpha beta gamma delta.\n\n\\newpage\n\nEpsilon zeta eta theta."; + let parsed = paragraphs(source).expect("paragraphs"); + assert_eq!(parsed.len(), 2); + assert!(!parsed[0].page_break); + assert!(parsed[1].page_break); + let document = build_document(&parsed, &PageGeometry::default()); + assert_eq!(document.page_breaks, vec![1]); + let engine = Engine::layout(&document); + assert_eq!(engine.pages().len(), 2); + assert!(engine.pages()[0].items.len() >= 1); + } }