diff --git a/README.md b/README.md index 926c0c6..dc09377 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`, booktabs rule weights (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt) with `\cmidrule(lr){a-b}` trims and ranges, and row-level page splitting that repeats the column widths. Multi-page table headers are not implemented. Figures honor `[htbp]` +In route-D, `\halign`/`\calign` sources support `l`/`c`/`r`/`p{width}` cells, explicit `\tabskip`, `@{}`/`@{\hspace{...}}` column expressions, booktabs rule weights (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt) with `\cmidrule(lr){a-b}` trims and ranges, and row-level page splitting that repeats the column widths. Multi-page table headers are not implemented. 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/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 0145733..23a3c73 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -457,6 +457,78 @@ fn take_booktabs_rules(raw: &str, row: usize, columns: usize) -> (String, Vec Vec> { + let mut columns = 0_usize; + let mut overrides: Vec<(usize, Option)> = Vec::new(); + let mut characters = template.chars().peekable(); + while let Some(character) = characters.next() { + match character { + 'l' | 'L' | 'c' | 'C' | 'r' | 'R' => columns += 1, + 'p' | 'P' => { + columns += 1; + if characters.peek() == Some(&'{') { + characters.next(); + for inner in characters.by_ref() { + if inner == '}' { + break; + } + } + } + } + '@' => { + let mut value = Some(0_i64); + if characters.peek() == Some(&'{') { + characters.next(); + let mut spec = String::new(); + let mut depth = 0_usize; + for inner in characters.by_ref() { + match inner { + '{' => { + depth += 1; + spec.push('{'); + } + '}' => { + if depth == 0 { + break; + } + depth -= 1; + spec.push('}'); + } + other => spec.push(other), + } + } + let spec = spec.trim(); + if !spec.is_empty() { + value = parse_at_glue(spec); + } + } + overrides.push((columns, value)); + } + _ => {} + } + } + let mut glue = vec![None; columns + 1]; + for (boundary, value) in overrides { + if let Some(slot) = glue.get_mut(boundary) { + *slot = value; + } + } + glue +} + +/// Parse the body of an `@{\hspace{...}}` column expression. +fn parse_at_glue(spec: &str) -> Option { + let spec = spec.trim(); + let rest = spec + .strip_prefix(r"\hspace") + .or_else(|| spec.strip_prefix(r"\hskip"))?; + let rest = rest.trim_start(); + let rest = rest.strip_prefix('*').unwrap_or(rest).trim_start(); + let body = rest.strip_prefix('{')?.split_once('}')?.0; + parse_tex_dimension(body) +} + /// Parse an alignment template into per-column alignment and wrap widths. fn parse_column_template(template: &str) -> (Vec, Vec>) { let mut alignments = Vec::new(); @@ -492,7 +564,25 @@ fn parse_column_template(template: &str) -> (Vec, Vec alignments.push(CellAlignment::Left); wraps.push(wrap); } - '|' | '@' | ' ' => {} + '|' | ' ' => {} + '@' => { + if characters.peek() == Some(&'{') { + characters.next(); + let mut depth = 0_usize; + for inner in characters.by_ref() { + match inner { + '{' => depth += 1, + '}' => { + if depth == 0 { + break; + } + depth -= 1; + } + _ => {} + } + } + } + } _ => { alignments.push(CellAlignment::Left); wraps.push(None); @@ -635,12 +725,24 @@ impl Unit { column += span; } } + let span_gaps = |column: usize, span: usize| -> i64 { + if column_skips.is_empty() { + intercolumn * (span.saturating_sub(1) as i64) + } else { + column_skips + .iter() + .skip(column) + .take(span.saturating_sub(1)) + .copied() + .sum() + } + }; for row in &rows { let mut column = 0_usize; for cell in &row.cells { let span = cell.span.max(1).min(column_count.saturating_sub(column)); if span > 1 { - let gaps = intercolumn * (span.saturating_sub(1) as i64); + let gaps = span_gaps(column, span); let available: i64 = column_widths[column..column + span] .iter() .copied() @@ -727,6 +829,7 @@ impl Unit { ) -> Self { let (alignments, wraps) = parse_column_template(template); let column_count = alignments.len().max(1); + let at_glue = parse_at_glues(template); let mut rows = Vec::new(); let mut rules: Vec = Vec::new(); for raw_row in source.split(r"\\") { @@ -791,8 +894,22 @@ impl Unit { } rows.push(HalignRow { cells, rule: false }); } + let mut column_skips = tabskips; + if at_glue.iter().any(|value| value.is_some()) { + let default_gap = intercolumn.saturating_mul(65_536); + let mut merged = vec![default_gap; column_count.saturating_sub(1)]; + for (slot, width) in merged.iter_mut().zip(column_skips.iter()) { + *slot = *width; + } + for boundary in 1..column_count { + if let Some(Some(width)) = at_glue.get(boundary).copied() { + merged[boundary - 1] = width; + } + } + column_skips = merged; + } let mut unit = - Self::halign_with_layout(id, rows, column_count, intercolumn, wraps, tabskips); + Self::halign_with_layout(id, rows, column_count, intercolumn, wraps, column_skips); if !rules.is_empty() { if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() { halign.rules = rules; @@ -6835,6 +6952,41 @@ b & 2 \\ ); } + #[test] + fn at_expressions_override_column_gaps() { + let unit = Unit::halign_from_source_with_template(1, "l@{}c", "aa & bb \\\\", 20); + let VerticalItem::Halign(halign) = &unit.items[0] else { + panic!("expected halign"); + }; + assert_eq!(halign.column_skips, vec![0]); + assert_eq!(halign.width, halign.column_widths.iter().sum::()); + assert_eq!(halign.column_offset(1), halign.column_widths[0]); + + let unit = + Unit::halign_from_source_with_template(1, r"l@{\hspace{5pt}}c", "aa & bb \\\\", 20); + let VerticalItem::Halign(halign) = &unit.items[0] else { + panic!("expected halign"); + }; + assert_eq!(halign.column_skips, vec![5 * 65_536]); + assert_eq!( + halign.column_offset(1), + halign.column_widths[0] + 5 * 65_536 + ); + } + + #[test] + fn plain_templates_keep_uniform_gaps() { + let unit = Unit::halign_from_source_with_template(1, "lc", "aa & bb \\\\", 20); + let VerticalItem::Halign(halign) = &unit.items[0] else { + panic!("expected halign"); + }; + assert!(halign.column_skips.is_empty()); + assert_eq!( + halign.column_offset(1), + halign.column_widths[0] + 20 * 65_536 + ); + } + #[test] fn checkpoint_round_trips_through_serde() { let engine = Engine::layout(&document()); diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index e0a5277..9c3e629 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`). 483 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 485 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, but not the full TeX column algorithm (longtable repeated heads, `\valign` interleaving, `@{}` preamble expressions); +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 and `@{}`/`@{\hspace{...}}` column expressions, but not the full TeX column algorithm (longtable repeated heads, `\valign` interleaving); 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 376098c..edd15a6 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); no longtable repeated heads, `@{}` preamble expressions, `\valign` or full tabular parity yet | +| 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), and `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue; no longtable repeated heads, `\valign` or full tabular 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 | | 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 326 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 483 tests (326 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 328 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 485 tests (328 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. ### M0 incremental demo