diff --git a/README.md b/README.md index 0a782fd..4720857 100644 --- a/README.md +++ b/README.md @@ -385,7 +385,7 @@ paragraph (`p{...}`) columns are supported. `\multicolumn{n}{align}{...}` spans columns, `\cmidrule(r){a-b}` and `\cline{a-b}` draw partial rules over a column range, and spanning cells distribute their width over the covered natural columns; the resulting width matches the reference XeLaTeX output. -In route-D, `\halign`/`\calign` sources support `l`/`c`/`r`/`p{width}` cells, explicit `\tabskip`, `@{}`/`@{\hspace{...}}` column expressions, `\noalign{\vskip ...}` row glue, booktabs rule weights (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt) with `\cmidrule(lr){a-b}` trims and ranges, row-level page splitting that repeats the column widths, and longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) whose continuation chunks repeat the head rows and paint the foot block once. Figures honor `[htbp]` +In route-D, `\halign`/`\calign` sources support `l`/`c`/`r`/`p{width}` cells, explicit `\tabskip`, `@{}`/`@{\hspace{...}}` column expressions, `\noalign{\vskip ...}` row glue, booktabs rule weights (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt) with `\cmidrule(lr){a-b}` trims and ranges, row-level page splitting that repeats the column widths, longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) whose continuation chunks repeat the head rows and paint the foot block once, and LaTeX `tabular` sources mapped onto the same alignment path. Figures honor `[htbp]` placement hints (`[t]` is deferred to the top of the next page, `[b]` to the page bottom, `[p]` to a float page, `[h]` stays in the flow); tables honor `[t]` by deferring the caption and rows to the next page, `[b]` at the page diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index b2603e8..6faf136 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`). 488 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 490 workspace tests are green and no oracle fixture is ignored. Status after G1 (P0-P2): the paragraph model reproduces TeX's passes, @@ -60,7 +60,7 @@ table in [`TEX_CORE.md`](TEX_CORE.md) lists the evidence per milestone. Remaining gaps: -1. `\halign` handles spans/omit/templates, `p{width}` paragraph columns (wrapped cell text grows row heights and participates in row-level page splitting), explicit per-column `\tabskip` glue, page-sized row chunks that keep the table's column widths, and booktabs rule weights with partial `\cmidrule(lr){a-b}` spans, `@{}`/`@{\hspace{...}}` column expressions and `\noalign{\vskip ...}` row glue, longtable head/foot sections repeat the head rows on every page chunk and paint the foot block once, but not the full TeX column algorithm (`\valign` interleaving); +1. `\halign` handles spans/omit/templates, `p{width}` paragraph columns (wrapped cell text grows row heights and participates in row-level page splitting), explicit per-column `\tabskip` glue, page-sized row chunks that keep the table's column widths, and booktabs rule weights with partial `\cmidrule(lr){a-b}` spans, `@{}`/`@{\hspace{...}}` column expressions and `\noalign{\vskip ...}` row glue, longtable head/foot sections repeat the head rows on every page chunk and paint the foot block once, LaTeX `tabular` sources route through the same halign path, but not the full TeX column algorithm (`\valign` interleaving, nested tables); 2. math is a compact subset without the CM math fonts (`cmmi`, `cmsy`, `cmex`), display-math line breaking or `\mathchoice`-level styling; 3. text fonts are Liberation, not Computer Modern; Type1 fonts are not embeddable diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index db8f5a9..7d91321 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -130,7 +130,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`, `\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, bottom floats or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset, and `\mark{...}`/`\marks{...}` writes inside the routine are carried to the following page's mark list with their class; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets the pages the routine has not seen yet, even when the document raises insertion material; only a document that defers bottom floats keeps its initial goal, because the carried queue cannot be rebuilt after a retarget), `\ht255`, `\dp255` and `\wd255` expose the page box height, depth and width to the routine, and `\hsize` is readable (and assignable for the rest of the run) while `\wd255` tracks it; route-D sets `\hsize` from its 480pt text measure, insertion class registers `\count`/`\dimen`/`\skip` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments that outlive the routine (the paged builder runs the routine after each page, so an assigned `\dimen` or `\count` changes the insertion capacity and reservation of later pages); the configured `\skip` also reserves space above its class once per page in the paged builder, and a `\skip` assignment rebuilds the pages the routine has not seen yet with the new reservation, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine; `\vbadness` reports the badness of the break that produced the page and `\insertpenalties` the number of insertion items held over from it | -| 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; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, though `\valign` and full tabular parity remain open | +| 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; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), though `\valign`, nested tables and full tabular parity remain open | | 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 | | M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity | @@ -367,7 +367,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 331 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 488 tests (331 route-D unit, 7 route-D integration, 35 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 331 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 490 tests (331 route-D unit, 14 engine unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 v1 unit, 1 core unit), 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 c3578ae..bac3cde 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -139,6 +139,8 @@ struct PageGeometry { line_penalty: Option, adj_demerits: Option, space_factor_codes: Vec<(char, i64)>, + /// Captured `tabular` environments: (column spec, halign source). + tabular: Vec<(String, String)>, } /// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/ @@ -148,8 +150,31 @@ struct PageGeometry { fn strip_page_geometry(source: &str) -> (String, PageGeometry) { let mut geometry = PageGeometry::default(); let mut body = String::new(); + let mut tabular: Option<(String, String)> = None; for line in source.lines() { let trimmed = line.trim(); + if let Some((_, text)) = tabular.as_mut() { + if trimmed == "\\end{tabular}" { + let (template, text) = tabular.take().unwrap(); + geometry.tabular.push((template, text)); + } else { + if !text.is_empty() { + text.push('\n'); + } + text.push_str(trimmed); + } + continue; + } + if let Some(rest) = trimmed.strip_prefix("\\begin{tabular}") { + if let Some((template, _)) = braced(rest.trim_start()) { + body.push_str(&format!( + "\n\n\\texrratable{{{}}}\n\n", + geometry.tabular.len() + )); + tabular = Some((template.to_string(), String::new())); + } + continue; + } if let Some(value) = dimension_assignment(trimmed, "hoffset") { geometry.origin.h_offset = value; } else if let Some(value) = dimension_assignment(trimmed, "voffset") { @@ -233,9 +258,86 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { body.push('\n'); } } + if let Some((template, text)) = tabular { + geometry.tabular.push((template, text)); + } (body, geometry) } +fn braced(text: &str) -> Option<(&str, &str)> { + let mut depth = 0_i32; + for (index, character) in text.char_indices() { + match character { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + return Some((&text[1..index], &text[index + 1..])); + } + } + _ => {} + } + } + None +} + +fn engine_template(spec: &str) -> String { + let mut out = String::new(); + let mut characters = spec.chars().peekable(); + while let Some(character) = characters.next() { + match character { + 'l' | 'c' | 'r' => out.push(character), + 'p' | 'm' | 'b' => { + out.push('p'); + if characters.peek() == Some(&'{') { + let mut depth = 0_i32; + for inner in characters.by_ref() { + out.push(inner); + match inner { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + } + } + } + '|' | ' ' | '\t' => {} + '@' | '!' | '>' | '<' | '*' => { + if characters.peek() == Some(&'{') { + let mut depth = 0_i32; + for inner in characters.by_ref() { + match inner { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + } + } + } + _ => {} + } + } + if out.is_empty() { "l".to_string() } else { out } +} + +fn table_reference(text: &str) -> Option { + text.trim() + .strip_prefix("\\texrratable{")? + .strip_suffix('}')? + .parse() + .ok() +} + /// Strip geometry assignments from the whole source (preamble included) and /// return the LaTeX body with them removed. fn geometry_and_body(source: &str) -> (String, PageGeometry) { @@ -588,6 +690,24 @@ fn paragraphs(source: &str) -> Result, String> { let mut pending = (0_i64, 0_i64, 0_i64); let mut pending_break = false; for chunk in paragraphs { + if let Some(index) = table_reference(chunk) { + result.push(SourceParagraph { + text: format!("\\texrratable{{{index}}}"), + font: ParagraphFont::Roman, + line_height: 12, + math: false, + left_skip: 0, + centered: false, + right_aligned: false, + space_before: pending.0, + space_stretch: pending.1, + space_shrink: pending.2, + page_break: pending_break, + }); + pending = (0, 0, 0); + pending_break = false; + continue; + } if chunk == "\\newpage" || chunk == "\\clearpage" { pending_break = true; continue; @@ -789,6 +909,21 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do .iter() .enumerate() .map(|(index, paragraph)| { + if let Some(table) = table_reference(¶graph.text) { + if let Some((template, source)) = geometry.tabular.get(table) { + let mut unit = Unit::halign_from_source_with_template_and_tabskips( + index as u64, + &engine_template(template), + source, + 6 * SCALE, + Vec::new(), + ); + unit.space_before = paragraph.space_before; + unit.space_stretch = paragraph.space_stretch; + unit.space_shrink = paragraph.space_shrink; + return unit; + } + } if paragraph.math { let mut unit = Unit::math( index as u64, @@ -931,6 +1066,13 @@ fn escape_json(value: &str) -> String { mod tests { use super::*; + #[test] + fn engine_template_keeps_paragraph_columns() { + assert_eq!(engine_template("{|l|c|p{3cm}|}"), "lcp{3cm}"); + assert_eq!(engine_template("|p{2cm}|r|"), "p{2cm}r"); + assert_eq!(engine_template(""), "l"); + } + fn multi_page_source() -> String { let mut source = String::from("\\documentclass{article}\n\\begin{document}\n\n"); for index in 0..36 { diff --git a/tests/server.rs b/tests/server.rs index fbab1ac..c9b464a 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -595,6 +595,30 @@ fn route_d_renders_itemize_lists() { assert!(svg.contains(">•")); } +#[test] +fn route_d_renders_tabular_sources() { + let server = TestServer::start("route-d-tabular"); + let body = "\\begin{tabular}{|l|c|}\n\\hline\nAlpha & 1 \\\\\nBeta & 22 \\\\\n\\hline\n\\end{tabular}\n\nAfter the table."; + let response = server.request( + "POST", + "/api/route-d/preview", + body.as_bytes(), + "text/plain", + ); + assert_eq!(response.status, 200, "{}", response.text()); + let value: Value = serde_json::from_slice(&response.body).expect("route-D JSON"); + let pages = value["pages"].as_array().unwrap(); + let svg: String = pages + .iter() + .filter_map(|page| page["svg"].as_str()) + .collect::>() + .join("\n"); + assert!(svg.contains(">Alpha"), "{svg}"); + assert!(svg.contains(">22"), "{svg}"); + assert!(svg.contains(">A"), "{svg}"); + assert!(svg.contains(">f"), "{svg}"); +} + #[test] fn route_d_renders_enumerate_lists() { let server = TestServer::start("route-d-enumerate");