From 9744e148091221bb8b9c1773514b7c4b76446a52 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 20 Oct 2026 12:44:24 +0800 Subject: [PATCH] Lay out natural-width halign tables --- crates/texrra-tex-core/src/lib.rs | 172 ++++++++++++++++++++++++++++++ docs/TEX_CORE.md | 4 +- 2 files changed, 175 insertions(+), 1 deletion(-) diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 43a1433..e9053c1 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -18,6 +18,36 @@ pub struct VerticalBox { pub height: i64, } +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum CellAlignment { + Left, + Center, + Right, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct HalignCell { + pub text: String, + pub span: usize, + pub alignment: CellAlignment, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct HalignRow { + pub cells: Vec, + pub rule: bool, +} + +/// A laid-out `\halign` table: natural column widths plus row rules. +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct Halign { + pub rows: Vec, + pub column_widths: Vec, + pub width: i64, + pub height: i64, + pub line_height: i64, +} + #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum VerticalItem { Box(VerticalBox), @@ -26,6 +56,7 @@ pub enum VerticalItem { Insertion(Insertion), Mark(Mark), Float(Float), + Halign(Halign), } /// Vertical material reserved at the bottom of a page (footnotes etc.). @@ -65,6 +96,67 @@ pub struct Unit { } impl Unit { + /// Build a simple `\halign` table with natural column widths. + pub fn halign(id: UnitId, rows: Vec, column_count: usize, intercolumn: i64) -> Self { + let mut column_widths = vec![0_i64; column_count]; + 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 width: i64 = cell + .text + .chars() + .map(|character| if character.is_whitespace() { 4 } else { 10 }) + .sum(); + if let Some(slot) = column_widths.get_mut(column) { + *slot = (*slot).max(width); + } + } + column += span; + } + } + 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 available: i64 = column_widths[column..column + span] + .iter() + .copied() + .sum::() + + gaps; + let needed: i64 = cell.text.chars().count() as i64 * 10; + let extra = (needed - available).max(0); + for offset in 0..span { + column_widths[column + offset] += extra / span as i64; + } + } + column += span; + } + } + let gaps = intercolumn * column_count.saturating_sub(1) as i64; + let width = column_widths.iter().sum::() + gaps; + let line_height = 12; + let rule_height = 26_214; // 0.4pt + let height = rows + .iter() + .map(|row| if row.rule { rule_height } else { line_height }) + .sum(); + Self { + id, + source: "halign".to_owned(), + items: vec![VerticalItem::Halign(Halign { + rows, + column_widths, + width, + height, + line_height, + })], + } + } + /// M1 paragraph builder: box/glue/penalty item stream with a /// Knuth-Plass-style word-level line breaker. pub fn paragraph(id: UnitId, source: impl Into) -> Self { @@ -267,6 +359,20 @@ impl Engine { } current.items.push(item.clone()); } + VerticalItem::Halign(halign) => { + if current.items.is_empty() && top_float_height(¤t) == 0 { + used = document.top_skip.max(halign.height); + } else if used + halign.height + > document.page_goal - insertion_height - bottom_float_height(¤t) + { + pages.push(std::mem::replace(&mut current, Page::empty())); + used = document.top_skip.max(halign.height); + insertion_height = 0; + } else { + used += halign.height; + } + current.items.push(item.clone()); + } VerticalItem::Glue(amount) => { if !current.items.is_empty() { used += amount; @@ -390,6 +496,7 @@ impl Engine { VerticalItem::Insertion(insertion) => insertion.height, VerticalItem::Mark(_) => 0, VerticalItem::Float(float) => float.height, + VerticalItem::Halign(halign) => halign.height, }) .sum(); if checkpoint.used + edited_height > next.page_goal && !checkpoint.page_items.is_empty() { @@ -438,6 +545,20 @@ impl Engine { } current.items.push(item.clone()); } + VerticalItem::Halign(halign) => { + if current.items.is_empty() && top_float_height(¤t) == 0 { + used = next.top_skip.max(halign.height); + } else if used + halign.height + > next.page_goal - insertion_height - bottom_float_height(¤t) + { + pages.push(std::mem::replace(&mut current, Page::empty())); + used = next.top_skip.max(halign.height); + insertion_height = 0; + } else { + used += halign.height; + } + current.items.push(item.clone()); + } VerticalItem::Glue(amount) => { if !current.items.is_empty() { used += amount; @@ -760,6 +881,57 @@ mod tests { assert_eq!(engine.layout.pages[1].items.len(), 1); } + #[test] + fn halign_computes_natural_column_widths() { + let rows = vec![ + HalignRow { + cells: vec![ + HalignCell { + text: "A".to_owned(), + span: 1, + alignment: CellAlignment::Left, + }, + HalignCell { + text: "B".to_owned(), + span: 1, + alignment: CellAlignment::Left, + }, + ], + rule: false, + }, + HalignRow { + cells: vec![ + HalignCell { + text: "longword".to_owned(), + span: 1, + alignment: CellAlignment::Left, + }, + HalignCell { + text: "C".to_owned(), + span: 1, + alignment: CellAlignment::Right, + }, + ], + rule: true, + }, + HalignRow { + cells: vec![HalignCell { + text: "TOTAL".to_owned(), + span: 2, + alignment: CellAlignment::Center, + }], + rule: false, + }, + ]; + let unit = Unit::halign(0, rows, 2, 20); + let VerticalItem::Halign(halign) = &unit.items[0] else { + panic!("expected a halign item"); + }; + assert_eq!(halign.column_widths, vec![80, 10]); + assert_eq!(halign.width, 110); + assert_eq!(halign.height, 12 + 26_214 + 12); + } + #[test] fn checkpoint_round_trips_through_serde() { let engine = Engine::layout(&document()); diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 57d1a57..6260b68 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -72,7 +72,7 @@ next paragraph milestones. | 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, pdfTeX fixture and minimum line fill; hyphenation next | | 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; interpreted `\output`, float pages next | -| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | table width/rules match reference | +| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: `Halign` model with natural column widths, spans and rule rows; no `\omit`/`\span` token parsing or PDF painting yet | | M4 | math lists, scripts, fractions, radicals, accents, delimiters | arXiv formulas render without overlap | | M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | | M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity | @@ -101,6 +101,8 @@ overfull ratio 4.11, badness 6942. TeX rejects the underfull candidate under its tolerance but still emits the moderately overfull 5-word line. Reproducing this needs a two-pass tolerance algorithm with an emergency overfull pass, not a single cost function. +- `Unit::halign` lays out natural column widths, multi-column spans and rule + rows as a `VerticalItem::Halign`; it is not yet painted by the v2 PDF path. - Page breaking handles vertical boxes/glue, `Document::top_skip` and forced vertical penalties (`penalty <= -10000`); positive penalties are recorded but not yet part of page badness. `VerticalItem::Insertion` material is