From c3e75bd244d8325dd1e8b146e5d56a2508f649bd Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 24 Oct 2026 01:03:53 +0800 Subject: [PATCH] Draw booktabs rules with their own weights and spans --- README.md | 2 +- crates/texrra-tex-core/src/lib.rs | 246 ++++++++++++++++++++++++++- crates/texrra-tex-core/src/render.rs | 18 ++ docs/ROUTE_D_PLAN.md | 4 +- docs/TEX_CORE.md | 4 +- 5 files changed, 267 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index b018e08..926c0c6 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. -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`, 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 6eead73..0145733 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -50,6 +50,25 @@ pub struct HalignRow { pub rule: bool, } +/// A horizontal rule at a `\halign` row boundary. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct HalignRule { + /// Boundary the rule sits above; `rows.len()` paints below the table. + pub row: usize, + /// First covered column. + pub start: usize, + /// Last covered column (inclusive). + pub end: usize, + /// Thickness in scaled points (booktabs heavy/light rule widths). + pub width: i64, + /// Space trimmed from the left edge (`\cmidrule(lr)`). + #[serde(default)] + pub trim_left: i64, + /// Space trimmed from the right edge (`\cmidrule(lr)`). + #[serde(default)] + pub trim_right: i64, +} + /// A laid-out `\halign` table: natural column widths plus row rules. #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Halign { @@ -62,6 +81,9 @@ pub struct Halign { /// the uniform intercolumn spacing derived from `width`. #[serde(default)] pub column_skips: Vec, + /// Painted rules (booktabs heavy/light rules and partial `\cmidrule`s). + #[serde(default)] + pub rules: Vec, pub width: i64, pub height: i64, pub line_height: i64, @@ -112,6 +134,7 @@ impl Halign { column_widths: self.column_widths.clone(), column_wrap: self.column_wrap.clone(), column_skips: self.column_skips.clone(), + rules: self.rules_for_chunk(start, index), width: self.width, height, line_height: self.line_height, @@ -126,6 +149,7 @@ impl Halign { column_widths: self.column_widths.clone(), column_wrap: self.column_wrap.clone(), column_skips: self.column_skips.clone(), + rules: self.rules_for_chunk(start, self.rows.len()), width: self.width, height, line_height: self.line_height, @@ -239,6 +263,44 @@ impl Halign { self.column_skips.get(boundary).copied().unwrap_or(0) } } + + /// Rules that belong to the page chunk covering rows `start..end`. + fn rules_for_chunk(&self, start: usize, end: usize) -> Vec { + self.rules + .iter() + .filter_map(|rule| { + let belongs = + (rule.row > start && rule.row <= end) || (start == 0 && rule.row == 0); + if belongs { + Some(HalignRule { + row: rule.row - start, + ..*rule + }) + } else { + None + } + }) + .collect() + } + + /// Left edge of a column (including all gaps before it). + fn column_offset(&self, column: usize) -> i64 { + let column = column.min(self.column_widths.len()); + self.column_widths[..column].iter().sum::() + + (0..column) + .map(|boundary| self.gap_width(boundary)) + .sum::() + } + + /// Horizontal rectangle of one rule: `(x, width)`. + pub fn rule_rect(&self, rule: &HalignRule) -> (i64, i64) { + let last = self.column_widths.len().saturating_sub(1); + let start = rule.start.min(last); + let end = rule.end.min(last).max(start); + let x = self.column_offset(start) + rule.trim_left; + let right = (self.column_offset(end + 1) - rule.trim_right).min(self.width); + (x, (right - x).max(65_536)) + } } /// Natural width of a run of text at the illustrative 10pt metrics. @@ -322,6 +384,79 @@ fn parse_tex_dimension(spec: &str) -> Option { Some((value * points_per_unit * 65_536.0).round() as i64) } +/// Strip booktabs rule commands from a row, recording their spans. +fn take_booktabs_rules(raw: &str, row: usize, columns: usize) -> (String, Vec) { + let mut rules = Vec::new(); + let mut remaining = raw.trim(); + loop { + let trimmed = remaining.trim_start(); + let end = columns.saturating_sub(1); + let (width, rest) = if let Some(rest) = trimmed.strip_prefix(r"\toprule") { + (Some(52_429), rest) + } else if let Some(rest) = trimmed.strip_prefix(r"\bottomrule") { + (Some(52_429), rest) + } else if let Some(rest) = trimmed.strip_prefix(r"\midrule") { + (Some(32_768), rest) + } else { + (None, trimmed) + }; + if let Some(width) = width { + rules.push(HalignRule { + row, + start: 0, + end, + width, + trim_left: 0, + trim_right: 0, + }); + remaining = rest.trim_start(); + continue; + } + if let Some(rest) = trimmed.strip_prefix(r"\cmidrule") { + let mut rest = rest.trim_start(); + let mut trim_left = 0_i64; + let mut trim_right = 0_i64; + if let Some(after_open) = rest.strip_prefix('(') { + if let Some((options, tail)) = after_open.split_once(')') { + if options.contains('l') { + trim_left = 4 * 65_536; + } + if options.contains('r') { + trim_right = 4 * 65_536; + } + rest = tail.trim_start(); + } + } + if let Some(body) = rest.strip_prefix('{') { + if let Some((span, tail)) = body.split_once('}') { + let (left, right) = span.split_once('-').unwrap_or((span, span)); + let start = left.trim().parse::().unwrap_or(1).saturating_sub(1); + let end = right + .trim() + .parse::() + .unwrap_or(columns) + .saturating_sub(1) + .min(columns.saturating_sub(1)); + if start <= end { + rules.push(HalignRule { + row, + start, + end, + width: 32_768, + trim_left, + trim_right, + }); + } + remaining = tail.trim_start(); + continue; + } + } + } + break; + } + (remaining.to_owned(), rules) +} + /// Parse an alignment template into per-column alignment and wrap widths. fn parse_column_template(template: &str) -> (Vec, Vec>) { let mut alignments = Vec::new(); @@ -536,6 +671,7 @@ impl Unit { column_widths, column_wrap: wraps, column_skips, + rules: Vec::new(), width, height: 0, line_height, @@ -592,11 +728,15 @@ impl Unit { let (alignments, wraps) = parse_column_template(template); let column_count = alignments.len().max(1); let mut rows = Vec::new(); + let mut rules: Vec = Vec::new(); for raw_row in source.split(r"\\") { if raw_row.trim().is_empty() { continue; } - let mut raw_row = raw_row.trim(); + let (rule_text, collected) = + take_booktabs_rules(raw_row.trim(), rows.len(), column_count); + rules.extend(collected); + let mut raw_row = rule_text.trim(); if let Some(rest) = raw_row.strip_prefix(r"\noalign") { let rest = rest.trim_start(); if let Some(body) = rest.strip_prefix('{') { @@ -651,7 +791,14 @@ impl Unit { } rows.push(HalignRow { cells, rule: false }); } - Self::halign_with_layout(id, rows, column_count, intercolumn, wraps, tabskips) + let mut unit = + Self::halign_with_layout(id, rows, column_count, intercolumn, wraps, tabskips); + if !rules.is_empty() { + if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() { + halign.rules = rules; + } + } + unit } /// A running mark item, recorded on the page where it is shipped out. @@ -6593,6 +6740,101 @@ cc & d\n", ); } + #[test] + fn booktabs_rules_carry_widths_and_partial_spans() { + let source = r"\toprule +Name & Value \\ +\midrule +a & 1 \\ +\cmidrule(lr){1-1} +b & 2 \\ +\bottomrule +"; + let unit = Unit::halign_from_source_with_template(1, "ll", source, 0); + let VerticalItem::Halign(halign) = &unit.items[0] else { + panic!("expected halign"); + }; + assert_eq!(halign.rows.len(), 3); + assert_eq!(halign.rules.len(), 4); + assert_eq!( + halign.rules[0], + HalignRule { + row: 0, + start: 0, + end: 1, + width: 52_429, + trim_left: 0, + trim_right: 0, + } + ); + assert_eq!(halign.rules[1].row, 1); + assert_eq!(halign.rules[1].width, 32_768); + assert_eq!(halign.rules[2].row, 2); + assert_eq!(halign.rules[2].start, 0); + assert_eq!(halign.rules[2].end, 0); + assert_eq!(halign.rules[2].trim_left, 4 * 65_536); + assert_eq!(halign.rules[2].trim_right, 4 * 65_536); + assert_eq!(halign.rules[3].row, 3); + assert_eq!(halign.rules[3].width, 52_429); + let (x, width) = halign.rule_rect(&halign.rules[2]); + assert_eq!(x, 4 * 65_536); + assert_eq!(width, halign.column_widths[0] - 8 * 65_536); + let list = halign.display_list(); + let painted: Vec<(i64, i64, i64)> = list + .items + .iter() + .filter_map(|item| match item { + DisplayItem::Rule { x, y, width, .. } => Some((*x, *y, *width)), + _ => None, + }) + .collect(); + assert_eq!(painted.len(), 4); + assert!( + painted + .iter() + .any(|(_, _, width)| *width < halign.width / 2) + ); + assert!(painted.iter().any(|(_, y, _)| *y == halign.height)); + } + + #[test] + fn booktabs_rules_follow_page_chunks() { + let mut source = String::from( + r"\toprule +", + ); + for index in 0..20 { + source.push_str(&format!("row{index} & value{index} \\\\\n")); + } + source.push_str( + r"\bottomrule +", + ); + let unit = Unit::halign_from_source_with_template(1, "ll", &source, 0); + let VerticalItem::Halign(halign) = &unit.items[0] else { + panic!("expected halign"); + }; + assert_eq!(halign.rules.len(), 2); + let chunks = halign.split_for_height(halign.line_height * 3); + assert!(chunks.len() >= 2); + assert!( + chunks[0] + .rules + .iter() + .any(|rule| rule.row == 0 && rule.width == 52_429) + ); + let last = chunks.last().unwrap(); + assert!( + last.rules + .iter() + .any(|rule| rule.row == last.rows.len() && rule.width == 52_429) + ); + assert_eq!( + chunks.iter().map(|chunk| chunk.rows.len()).sum::(), + 20 + ); + } + #[test] fn checkpoint_round_trips_through_serde() { let engine = Engine::layout(&document()); diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 7d2364e..6fa9bb3 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -273,6 +273,15 @@ impl Halign { }; let mut y = 0_i64; for (row_index, row) in self.rows.iter().enumerate() { + for rule in self.rules.iter().filter(|rule| rule.row == row_index) { + let (x, width) = self.rule_rect(rule); + list.push(DisplayItem::Rule { + x, + y, + width, + height: rule.width, + }); + } if row.rule { let height = 26_214; // 0.4pt in scaled points. list.push(DisplayItem::Rule { @@ -319,6 +328,15 @@ impl Halign { } y += row_height; } + for rule in self.rules.iter().filter(|rule| rule.row == self.rows.len()) { + let (x, width) = self.rule_rect(rule); + list.push(DisplayItem::Rule { + x, + y, + width, + height: rule.width, + }); + } list } } diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 8bbf4be..e0a5277 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`). 481 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 483 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 and page-sized row chunks that keep the table's column widths, but not the full TeX column algorithm (booktabs/longtable, `\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, but not the full TeX column algorithm (longtable repeated heads, `\valign` interleaving, `@{}` preamble expressions); 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 94ef570..376098c 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, and explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks; no booktabs/longtable, `\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); no longtable repeated heads, `@{}` preamble expressions, `\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 324 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 481 tests (324 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 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. ### M0 incremental demo