Repeat longtable heads on continuation pages

This commit is contained in:
gloamxun committed 2026-10-24 01:14:38 +08:00
1 parent 8c3e410ffc
commit 20011eadd3
4 files changed
+251 -5

No files matched your search

+1 -1
View File
@@ -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, 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, `\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]`
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
+246
View File
@@ -87,6 +87,15 @@ pub struct Halign {
/// Extra vertical glue after each row (TeX `\noalign{\vskip ...}`).
#[serde(default)]
pub row_gaps: Vec<i64>,
/// Leading rows repeated on the first page only (longtable `\endfirsthead`).
#[serde(default)]
pub first_head_len: usize,
/// Rows after the first head repeated on continuation pages (`\endhead`).
#[serde(default)]
pub head_len: usize,
/// Trailing rows painted only on the last page (`\endfoot`/`\endlastfoot`).
#[serde(default)]
pub foot_len: usize,
pub width: i64,
pub height: i64,
pub line_height: i64,
@@ -121,7 +130,137 @@ impl Halign {
///
/// Column widths are preserved so the fragments still line up when the
/// page builder places them on consecutive pages.
/// Split the table into page-sized row chunks, repeating longtable heads
/// and painting the foot block only on the last chunk.
pub fn split_for_height(&self, max_height: i64) -> Vec<Halign> {
if self.first_head_len > 0 || self.head_len > 0 || self.foot_len > 0 {
self.split_for_height_with_heads(max_height)
} else {
self.split_for_height_without_heads(max_height)
}
}
fn split_for_height_with_heads(&self, max_height: i64) -> Vec<Halign> {
let max_height = max_height.max(self.line_height);
let first_len = self.first_head_len.min(self.rows.len());
let head_len = self.head_len.min(self.rows.len().saturating_sub(first_len));
let body_start = first_len + head_len;
let foot_len = self
.foot_len
.min(self.rows.len().saturating_sub(body_start));
let body_end = self.rows.len() - foot_len;
let first_prefix: Vec<usize> = (0..first_len).collect();
let continuation_prefix: Vec<usize> = if first_len == 0 {
(0..head_len).collect()
} else {
(first_len..body_start).collect()
};
let height_of = |rows: &[usize]| -> i64 {
rows.iter()
.map(|&index| self.row_height(index) + self.row_gap(index))
.sum()
};
let foot_rows: Vec<usize> = (body_end..self.rows.len()).collect();
let foot_height = height_of(&foot_rows);
let mut chunks = Vec::new();
let mut cursor = body_start;
let mut first_chunk = true;
loop {
let prefix = if first_chunk {
&first_prefix
} else {
&continuation_prefix
};
let mut body_rows: Vec<usize> = Vec::new();
let mut height = height_of(prefix);
while cursor < body_end {
let row_height = self.row_height(cursor) + self.row_gap(cursor);
if !body_rows.is_empty() && height + row_height > max_height {
break;
}
body_rows.push(cursor);
height += row_height;
cursor += 1;
}
let last = cursor >= body_end;
let mut chunk_rows: Vec<usize> = Vec::new();
chunk_rows.extend(prefix.iter().copied());
chunk_rows.extend(body_rows.iter().copied());
if last && foot_len > 0 {
chunk_rows.extend(foot_rows.iter().copied());
height += foot_height;
}
let mut rules = Vec::new();
if let (Some(first), Some(last)) = (prefix.first(), prefix.last()) {
for rule in self
.rules
.iter()
.filter(|rule| rule.row >= *first && rule.row <= last + 1)
{
rules.push(HalignRule {
row: rule.row - first,
..*rule
});
}
}
if let (Some(first), Some(last)) = (body_rows.first(), body_rows.last()) {
let offset = prefix.len();
let lower = if prefix.is_empty() { *first } else { first + 1 };
for rule in self
.rules
.iter()
.filter(|rule| rule.row >= lower && rule.row <= last + 1)
{
rules.push(HalignRule {
row: offset + rule.row - first,
..*rule
});
}
}
if last {
if let (Some(first), Some(last)) = (foot_rows.first(), foot_rows.last()) {
let offset = prefix.len() + body_rows.len();
for rule in self
.rules
.iter()
.filter(|rule| rule.row > *first && rule.row <= last + 1)
{
rules.push(HalignRule {
row: offset + rule.row - first,
..*rule
});
}
}
}
chunks.push(Self {
rows: chunk_rows
.iter()
.map(|&index| self.rows[index].clone())
.collect(),
column_widths: self.column_widths.clone(),
column_wrap: self.column_wrap.clone(),
column_skips: self.column_skips.clone(),
rules,
row_gaps: chunk_rows
.iter()
.map(|&index| self.row_gap(index))
.collect(),
first_head_len: 0,
head_len: 0,
foot_len: 0,
width: self.width,
height,
line_height: self.line_height,
});
first_chunk = false;
if last {
break;
}
}
chunks
}
fn split_for_height_without_heads(&self, max_height: i64) -> Vec<Halign> {
if self.rows.is_empty() {
return vec![self.clone()];
}
@@ -143,6 +282,9 @@ impl Halign {
.get(start..index)
.map(<[_]>::to_vec)
.unwrap_or_default(),
first_head_len: 0,
head_len: 0,
foot_len: 0,
width: self.width,
height,
line_height: self.line_height,
@@ -163,6 +305,9 @@ impl Halign {
.get(start..)
.map(<[_]>::to_vec)
.unwrap_or_default(),
first_head_len: 0,
head_len: 0,
foot_len: 0,
width: self.width,
height,
line_height: self.line_height,
@@ -807,6 +952,9 @@ impl Unit {
column_skips,
rules: Vec::new(),
row_gaps: Vec::new(),
first_head_len: 0,
head_len: 0,
foot_len: 0,
width,
height: 0,
line_height,
@@ -867,6 +1015,9 @@ impl Unit {
let mut rules: Vec<HalignRule> = Vec::new();
let mut row_gaps: Vec<i64> = Vec::new();
let mut pending_gap = 0_i64;
let mut first_head_end: Option<usize> = None;
let mut head_end: Option<usize> = None;
let mut body_start: Option<usize> = None;
for raw_row in source.split(r"\\") {
if raw_row.trim().is_empty() {
continue;
@@ -886,6 +1037,19 @@ impl Unit {
}
}
}
if let Some(rest) = raw_row.strip_prefix(r"\endfirsthead") {
first_head_end = Some(rows.len());
raw_row = rest.trim();
} else if let Some(rest) = raw_row.strip_prefix(r"\endhead") {
head_end = Some(rows.len());
raw_row = rest.trim();
} else if let Some(rest) = raw_row.strip_prefix(r"\endlastfoot") {
body_start = Some(rows.len());
raw_row = rest.trim();
} else if let Some(rest) = raw_row.strip_prefix(r"\endfoot") {
head_end.get_or_insert(rows.len());
raw_row = rest.trim();
}
let mut rule = false;
if let Some(rest) = raw_row.strip_prefix(r"\hline") {
rule = true;
@@ -937,6 +1101,28 @@ impl Unit {
pending_gap = 0;
rows.push(HalignRow { cells, rule: false });
}
let first_len = first_head_end.unwrap_or(0);
let head_end = head_end.unwrap_or(first_len);
let body_start = body_start.unwrap_or(head_end);
let head_len = head_end.saturating_sub(first_len);
let foot_len = body_start.saturating_sub(head_end);
let body_len = rows.len().saturating_sub(body_start);
if foot_len > 0 {
let mut reordered = Vec::with_capacity(rows.len());
reordered.extend_from_slice(&rows[..head_end]);
reordered.extend_from_slice(&rows[body_start..]);
reordered.extend_from_slice(&rows[head_end..body_start]);
rows = reordered;
for rule in rules.iter_mut() {
if rule.row <= head_end {
// Head rows stay at the front.
} else if rule.row >= body_start {
rule.row -= foot_len;
} else {
rule.row += body_len;
}
}
}
let mut column_skips = tabskips;
if at_glue.iter().any(|value| value.is_some()) {
let default_gap = intercolumn.saturating_mul(65_536);
@@ -955,6 +1141,10 @@ impl Unit {
Self::halign_with_layout(id, rows, column_count, intercolumn, wraps, column_skips);
if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() {
halign.rules = rules;
halign.first_head_len = first_len.min(halign.rows.len());
halign.head_len = head_len.min(halign.rows.len() - halign.first_head_len);
halign.foot_len =
foot_len.min(halign.rows.len() - halign.first_head_len - halign.head_len);
if !row_gaps.is_empty() {
halign.row_gaps = row_gaps;
halign.height = (0..halign.rows.len())
@@ -7079,6 +7269,62 @@ b & 2 \\
assert_eq!(chunks[1].height, halign.row_height(1));
}
#[test]
fn longtable_heads_repeat_on_continuation_chunks() {
let source = "H1 & H2 \\\\\n\\endfirsthead\nH3 & H4 \\\\\n\\endhead\nF1 & F2 \\\\\n\\endfoot\nL1 & L2 \\\\\n\\endlastfoot\nb1 & x \\\\\nb2 & y \\\\\nb3 & z \\\\\nb4 & w \\\\\n";
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(), 8);
assert_eq!(halign.first_head_len, 1);
assert_eq!(halign.head_len, 1);
assert_eq!(halign.foot_len, 2);
let texts = |chunk: &Halign| -> Vec<String> {
chunk
.rows
.iter()
.flat_map(|row| row.cells.iter().map(|cell| cell.text.clone()))
.collect()
};
let all = texts(halign);
assert_eq!(&all[..4], ["H1", "H2", "H3", "H4"]);
assert_eq!(&all[12..16], ["F1", "F2", "L1", "L2"]);
let chunks = halign.split_for_height(halign.line_height * 2);
assert_eq!(chunks.len(), 4);
assert_eq!(chunks[0].rows[0].cells[0].text, "H1");
for chunk in &chunks[1..] {
assert_eq!(chunk.rows[0].cells[0].text, "H3");
}
let chunk_text: Vec<Vec<String>> = chunks.iter().map(texts).collect();
for body in ["b1", "b2", "b3", "b4"] {
assert_eq!(
chunk_text
.iter()
.filter(|texts| texts.iter().any(|text| text == body))
.count(),
1
);
}
assert_eq!(
chunk_text
.iter()
.filter(|texts| texts.iter().any(|text| text == "H1"))
.count(),
1
);
assert_eq!(
chunk_text
.iter()
.filter(|texts| texts.iter().any(|text| text == "H3"))
.count(),
3
);
assert!(chunk_text[3].iter().any(|text| text == "L1"));
assert!(!chunk_text[0].iter().any(|text| text == "F1"));
}
#[test]
fn checkpoint_round_trips_through_serde() {
let engine = Engine::layout(&document());
+2 -2
View File
@@ -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`). 487 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 488 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, but not the full TeX column algorithm (longtable repeated heads, `\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, but not the full TeX column algorithm (`\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
+2 -2
View File
@@ -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<n>{...}` 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<n>`/`\dimen<n>`/`\skip<n>` 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<n>` or `\count<n>` changes the insertion capacity and reservation of later pages); the configured `\skip<n>` also reserves space above its class once per page in the paged builder, and a `\skip<n>` 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; no longtable repeated heads, `\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), `@{}` / `@{\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 |
| 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 330 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 487 tests (330 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 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.
### M0 incremental demo