diff --git a/README.md b/README.md index c82084a..528c964 100644 --- a/README.md +++ b/README.md @@ -475,6 +475,7 @@ Route-D float placement mirrors TeX fractions: - `Document::top_number`, `bottom_number` and `total_number` default to TeX's 2, 1 and 12; they cap top floats, bottom floats and all floats on one page. - `Document::float_sep` defaults to 12pt (`\floatsep`); stacked top floats or stacked bottom floats reserve that gap between each other, in full layout and after `Engine::edit`. - `Document::text_float_sep` defaults to 20pt (`\textfloatsep`); a page that carries both floats and body text reserves one such gap between them. `Page::display_list_with_layout(page_goal, text_float_sep)` mirrors that in rendered output, while `display_list_with_goal` keeps the historic no-gap behaviour for callers without document settings. +- A `[t]` float that appears while a page is already filling joins the top of that same page (TeX's `\@toplist`): its height plus `\textfloatsep` is charged to that page, so the body stops earlier; only a page break before the float moves it forward. - Floats that start a page sit at the top margin: float material does not consume `\topskip`; only body text does. - `FloatPlacement::Here` keeps an `[h]` float in the body flow: `Document::in_text_sep` (TeX `\intextsep`, default 12pt) separates it from the surrounding text, the float moves to the next page when it does not fit, and it counts against `\totalnumber`. `Page::display_list_with_layout` paints the float at the same flow position the page builder reserved. - `Engine::edit` applies the float fractions, number limits and separations, so incremental layout matches full layout. diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 4af45ae..df79090 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -6450,7 +6450,7 @@ mod tests { } #[test] - fn paged_layout_defers_a_late_top_float() { + fn paged_layout_puts_a_late_top_float_on_its_own_page() { let mut document = Document::new( 100, vec![ @@ -6461,10 +6461,11 @@ mod tests { ); document.text_float_sep = 0; let layout = Engine::layout_paged(&document).expect("a late float still builds"); - assert_eq!(layout.pages().len(), 2); - assert!(layout.pages()[0].floats.is_empty()); - assert_eq!(layout.pages()[1].floats.len(), 1); - assert_eq!(layout.pages()[1].items.len(), 1); + // TeX installs the float at the top of the page it is seen on, so the + // float and both rules share one page. + assert_eq!(layout.pages().len(), 1); + assert_eq!(layout.pages()[0].floats.len(), 1); + assert_eq!(layout.pages()[0].items.len(), 2); } #[test] diff --git a/crates/texrra-tex-core/src/page.rs b/crates/texrra-tex-core/src/page.rs index 33daba0..d0706ba 100644 --- a/crates/texrra-tex-core/src/page.rs +++ b/crates/texrra-tex-core/src/page.rs @@ -323,13 +323,11 @@ impl PageBuilder { height: float_height, } => { if height > 0 - && (has_body - || top_count >= self.top_number - || float_total >= self.total_number) + && (top_count >= self.top_number || float_total >= self.total_number) { - // TeX never places a top float below body material, - // nor above the `\topnumber`/`\totalnumber` limits: - // the float starts the next page instead. + // TeX never puts more top floats on one page than + // `\topnumber`/`\totalnumber` allow: the float starts + // the next page instead. let end = index.max(start); let badness = self.badness(height, reserved, stretch, shrink, stretch_order); @@ -354,7 +352,21 @@ impl PageBuilder { self.insertion_overflow(nodes, start, end, held), )); } - height += (*float_height).max(0); + // TeX installs a `[t]` float at the top of the page it is + // seen on, pushing the body down by its height plus + // `\textfloatsep` (or `\floatsep` between stacked + // floats). Only a page that breaks before the float moves + // it to the next page. + if height > 0 { + height += (*float_height).max(0) + + if has_float { + self.float_sep.max(0) + } else { + self.text_float_sep.max(0) + }; + } else { + height += (*float_height).max(0); + } has_float = true; top_count += 1; float_total += 1; diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index 5dc31cd..28f24b0 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -10,7 +10,7 @@ use std::process::Command; use std::sync::atomic::{AtomicU64, Ordering}; use texrra_tex_core::paragraph::{HorizontalItem, ParagraphStyle}; -use texrra_tex_core::{Document, Engine, Unit, VerticalItem, layout_paragraph}; +use texrra_tex_core::{Document, Engine, FloatPlacement, Unit, VerticalItem, layout_paragraph}; /// Scaled points per TeX point. const PT: i64 = 65_536; @@ -935,6 +935,71 @@ fn pages_split_paragraphs_like_pdftex() { } } +/// A `[t]` float deferred to the next page top reserves its height plus +/// `\textfloatsep`; body breaks must stay in step with pdfLaTeX. +#[test] +fn top_floats_reserve_page_space_like_pdftex() { + let paragraphs: Vec = (0..80) + .map(|index| format!("p{index} alpha beta gamma")) + .collect(); + let float_at = 9_usize; + let mut body = String::new(); + for (index, paragraph) in paragraphs.iter().enumerate() { + body.push_str(paragraph); + body.push_str("\\par\n"); + if index == float_at { + body.push_str("\\begin{figure}[t]\\rule{100pt}{50pt}\\end{figure}\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 style = ParagraphStyle { + line_width: 345 * PT, + par_indent: 15 * PT, + line_height: 12 * PT, + ..ParagraphStyle::default() + }; + let mut units = Vec::new(); + let mut next_id = 1_u64; + for (index, paragraph) in paragraphs.iter().enumerate() { + units.push(Unit::paragraph_with_style( + next_id, + paragraph.clone(), + style.clone(), + )); + next_id += 1; + if index == float_at { + units.push(Unit::float(next_id, FloatPlacement::Top, 100 * PT, 50 * PT)); + next_id += 1; + } + } + let mut document = Document::new(550 * PT, units); + document.top_skip = 12 * PT; + document.text_float_sep = 20 * PT; + let engine = Engine::layout_paged(&document).expect("top floats are page-buildable"); + let ours: Vec = engine.pages().iter().map(page_alnum_text).collect(); + assert_eq!( + ours.len(), + reference.len(), + "route-D produced {} pages, pdfLaTeX {}", + ours.len(), + reference.len() + ); + for (index, (ours, reference)) in ours.iter().zip(&reference).enumerate() { + assert_eq!(ours, reference, "body text on page {}", index + 1); + } +} + /// `\footnotetext` raises insertion material that is reserved at the page /// bottom. With slack on each page, the body breaks and per-page body text /// must stay in step with pdfLaTeX even though the note text is not compared. diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 253175a..90547fa 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`). 451 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 452 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -306,13 +306,14 @@ 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: eight page fixtures are wired (single-line paragraphs, `\parskip=6pt` +Progress: nine page fixtures are wired (single-line paragraphs, `\parskip=6pt` spacing, multi-line paragraphs split across pages, a 300pt `\textheight`, a 30pt `\topskip`, `\newpage` forced breaks, stretchy `\vskip` glue between -paragraphs, and `\footnotetext` insertions reserved at the page bottom); each +paragraphs, `\footnotetext` insertions reserved at the page bottom, and a +`[t]` float that reserves its height plus `\textfloatsep` on its own page); each asserts the same page count and the same per-page body text as pdfLaTeX, with -footnote text excluded from the body comparison. Floats are the remaining -page-fixture gap because route-D's source mapping does not raise them yet. +footnote text excluded from the body comparison. Route-D's source mapping still +does not raise LaTeX floats, so the float fixture drives `Engine` directly. ### P3 — `\halign` / `\valign` (L2) diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index ffda98a..3c9092a 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -351,9 +351,9 @@ 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 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 +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. A `[t]` float seen while a page is already being filled is installed at the top of that same page, exactly as TeX's `\@toplist` does: the page height gains the float plus one `\textfloatsep` (or `\floatsep` between stacked floats), so the body stops earlier instead of the float waiting for the next page; only a break before the float moves it forward. `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; 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: eight page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, a 30pt `\topskip`, a forced `\newpage`, stretchy `\vskip` glue between paragraphs, and footnotes raised with `\footnotetext`) 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: nine page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, a 30pt `\topskip`, a forced `\newpage`, stretchy `\vskip` glue between paragraphs, footnotes raised with `\footnotetext`, and a `[t]` float that reserves its height plus `\textfloatsep` on the page it appears) 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. @@ -361,7 +361,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 298 unit tests plus seven route-D integration tests and thirty-one oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 451 tests (298 route-D unit, 7 route-D integration, 31 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path. +The crate currently has 298 unit tests plus seven route-D integration tests and thirty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 452 tests (298 route-D unit, 7 route-D integration, 32 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo