Lay out nested tables inside their cell
Nested tabulars were flattened to a text summary before the outer halign
parsed them, so the inner rows never existed as a table. Keep them instead:
strip_page_geometry replaces each nested block with a \texrranested{index}
token and stores the source on the geometry, and tabular_unit resolves the
token into a recursively built inner table attached to the cell. Cell text is
cleared, column widths and row height take the inner table's metrics, and page
splitting remaps nested row indices when it chunks rows.
Halign gains a nested list, refresh_measurements, nested-aware row_height and a
painting branch that translates the inner display list to the cell position at
the row's alignment. The old flattening pass stays as a dead-code fallback.
The nested-table test now checks one stored source, the placeholder token, one
attached 2x2 table in cell (0, 1), an empty outer cell and inner "a"/"d"
painted in the preview SVG.
This commit is contained in:
1 parent
371f05baaa
commit
81da180ab7
3 files changed
+205
-23
No files matched your search
@@ -178,6 +178,9 @@ pub struct Halign {
|
||||
pub width: i64,
|
||||
pub height: i64,
|
||||
pub line_height: i64,
|
||||
/// Nested tables painted inside a cell: (row, cell, table).
|
||||
#[serde(default)]
|
||||
pub nested: Vec<(usize, usize, Halign)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -336,6 +339,7 @@ impl Halign {
|
||||
foot_len: 0,
|
||||
margin: self.margin,
|
||||
multirow: Vec::new(),
|
||||
nested: self.nested_for_rows(&chunk_rows),
|
||||
width: self.width,
|
||||
height,
|
||||
line_height: self.line_height,
|
||||
@@ -376,6 +380,7 @@ impl Halign {
|
||||
foot_len: 0,
|
||||
margin: self.margin,
|
||||
multirow: Vec::new(),
|
||||
nested: self.nested_for_rows(&(start..index).collect::<Vec<_>>()),
|
||||
width: self.width,
|
||||
height,
|
||||
line_height: self.line_height,
|
||||
@@ -402,6 +407,7 @@ impl Halign {
|
||||
foot_len: 0,
|
||||
margin: self.margin,
|
||||
multirow: Vec::new(),
|
||||
nested: self.nested_for_rows(&(start..self.rows.len()).collect::<Vec<_>>()),
|
||||
width: self.width,
|
||||
height,
|
||||
line_height: self.line_height,
|
||||
@@ -409,6 +415,18 @@ impl Halign {
|
||||
chunks
|
||||
}
|
||||
|
||||
fn nested_for_rows(&self, indices: &[usize]) -> Vec<(usize, usize, Halign)> {
|
||||
let mut nested = Vec::new();
|
||||
for (new_row, old_row) in indices.iter().copied().enumerate() {
|
||||
for (row, cell, table) in &self.nested {
|
||||
if *row == old_row {
|
||||
nested.push((new_row, *cell, table.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
nested
|
||||
}
|
||||
|
||||
/// Column index of `cell_index` inside `row`.
|
||||
fn cell_column(&self, row: &HalignRow, cell_index: usize) -> usize {
|
||||
row.cells[..cell_index.min(row.cells.len())]
|
||||
@@ -530,18 +548,77 @@ impl Halign {
|
||||
if row.rule {
|
||||
return 26_214;
|
||||
}
|
||||
let lines = (0..row.cells.len())
|
||||
.map(|index| {
|
||||
if self.cell_row_span(row_index, index) > 1 {
|
||||
1
|
||||
} else {
|
||||
self.cell_lines(row_index, index).len()
|
||||
let mut height = self.line_height
|
||||
* (0..row.cells.len())
|
||||
.map(|index| {
|
||||
if self.cell_row_span(row_index, index) > 1 {
|
||||
1
|
||||
} else {
|
||||
self.cell_lines(row_index, index).len()
|
||||
}
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(1)
|
||||
.max(1) as i64;
|
||||
for (row, _, table) in &self.nested {
|
||||
if *row == row_index {
|
||||
height = height.max(table.height);
|
||||
}
|
||||
}
|
||||
height
|
||||
}
|
||||
|
||||
/// Recompute widths and height after nested tables are attached.
|
||||
pub fn refresh_measurements(&mut self) {
|
||||
let column_count = self.column_widths.len();
|
||||
let mut widths = vec![0_i64; column_count];
|
||||
for row in &self.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 = crate::text_width(&cell.text);
|
||||
if let Some(slot) = widths.get_mut(column) {
|
||||
*slot = (*slot).max(width);
|
||||
}
|
||||
}
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(1)
|
||||
.max(1);
|
||||
self.line_height * lines as i64
|
||||
column += span;
|
||||
}
|
||||
}
|
||||
for (row_index, row) in self.rows.iter().enumerate() {
|
||||
let mut column = 0_usize;
|
||||
for (cell_index, cell) in row.cells.iter().enumerate() {
|
||||
let span = cell.span.max(1).min(column_count.saturating_sub(column));
|
||||
if let Some((_, _, table)) = self
|
||||
.nested
|
||||
.iter()
|
||||
.find(|(row, cell, _)| *row == row_index && *cell == cell_index)
|
||||
{
|
||||
if span == 1 {
|
||||
if let Some(slot) = widths.get_mut(column) {
|
||||
*slot = (*slot).max(table.width);
|
||||
}
|
||||
}
|
||||
}
|
||||
column += span;
|
||||
}
|
||||
}
|
||||
let gaps: i64 = if self.column_skips.is_empty() {
|
||||
if column_count > 1 {
|
||||
let old_gap = (self.width - self.column_widths.iter().sum::<i64>())
|
||||
/ (column_count as i64 - 1);
|
||||
old_gap.max(0) * (column_count as i64 - 1)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
} else {
|
||||
self.column_skips.iter().copied().sum()
|
||||
};
|
||||
self.column_widths = widths;
|
||||
self.width = self.column_widths.iter().sum::<i64>() + gaps;
|
||||
self.height = (0..self.rows.len())
|
||||
.map(|index| self.row_height(index) + self.row_gap(index))
|
||||
.sum();
|
||||
}
|
||||
|
||||
/// Uniform intercolumn spacing derived from the table width.
|
||||
@@ -1172,6 +1249,7 @@ impl Unit {
|
||||
foot_len: 0,
|
||||
margin: 0,
|
||||
multirow: Vec::new(),
|
||||
nested: Vec::new(),
|
||||
width,
|
||||
height: 0,
|
||||
line_height,
|
||||
|
||||
+4
-3
@@ -553,9 +553,10 @@ are:
|
||||
as empty text.
|
||||
- **Tables**: `\multirow` centres over its rows, `array` column modifiers
|
||||
`>{}`/`<{}` and the outer `\tabcolsep` margins are parsed. A nested
|
||||
`tabular` no longer terminates the outer capture: its rows and cells are
|
||||
flattened into one text run inside the cell (`a b ; c d`), so the outer
|
||||
structure survives, while true nested-table layout and `\valign` remain
|
||||
`tabular` is attached to its outer cell as a real inner table: column widths
|
||||
and row heights account for it, the inner table is painted at the cell
|
||||
position, and page splitting remaps its row index. Images inside a nested
|
||||
table are not merged into the outer display list, and `\valign` remains
|
||||
unmodelled.
|
||||
- **Fonts**: the twelve Computer Modern faces and four math faces are embedded
|
||||
as Type1 with per-glyph Liberation fallback. Greek math commands now map to
|
||||
|
||||
+112
-9
@@ -229,6 +229,8 @@ struct PageGeometry {
|
||||
head_rule_width: Option<i64>,
|
||||
/// Frozen `\sbox`/`\savebox` metrics: name -> (width, height, depth), sp.
|
||||
savebox_dimensions: Vec<(String, (i64, i64, i64))>,
|
||||
/// Nested `tabular` sources referenced by `\texrranested{index}` tokens.
|
||||
nested_tables: Vec<String>,
|
||||
head_sep: Option<i64>,
|
||||
head_height: Option<i64>,
|
||||
foot_skip: Option<i64>,
|
||||
@@ -2351,7 +2353,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
}
|
||||
}
|
||||
let (template, text, _, target, _) = tabular.take().unwrap();
|
||||
let text = flatten_nested_tables(&text);
|
||||
let text = protect_nested_tables(&text, &mut geometry.nested_tables);
|
||||
geometry
|
||||
.tabular
|
||||
.push((template, expand_multirow(&text), target));
|
||||
@@ -3038,7 +3040,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
}
|
||||
}
|
||||
if let Some((template, text, _, target, _)) = tabular {
|
||||
let text = flatten_nested_tables(&text);
|
||||
let text = protect_nested_tables(&text, &mut geometry.nested_tables);
|
||||
geometry
|
||||
.tabular
|
||||
.push((template, expand_multirow(&text), target));
|
||||
@@ -3063,9 +3065,52 @@ fn braced(text: &str) -> Option<(&str, &str)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Replace nested `tabular` environments with a flattened text summary so the
|
||||
/// outer table keeps its cell structure. True nested-table layout is still
|
||||
/// open; this keeps the inner commands from breaking the outer parse.
|
||||
/// Replace nested `tabular` blocks with `\texrranested{index}` tokens and
|
||||
/// store their sources on the geometry for `tabular_unit` to resolve.
|
||||
fn protect_nested_tables(source: &str, nested_tables: &mut Vec<String>) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = source;
|
||||
while let Some(position) = rest.find("\\begin{tabular") {
|
||||
out.push_str(&rest[..position]);
|
||||
let after = &rest[position..];
|
||||
let Some(end) = nested_table_end(after) else {
|
||||
out.push_str(after);
|
||||
return out;
|
||||
};
|
||||
let block = &after[..end];
|
||||
let index = nested_tables.len();
|
||||
nested_tables.push(block.to_string());
|
||||
out.push_str(&format!("\\texrranested{{{index}}}"));
|
||||
rest = &after[end..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// Split a full `\begin{tabular}...\end{tabular}` block into its column spec
|
||||
/// and body rows.
|
||||
fn nested_table_parts(block: &str) -> Option<(&str, &str)> {
|
||||
let open_end = block.find('}')?;
|
||||
let environment = block.get("\\begin{".len()..open_end)?;
|
||||
let mut rest = block[open_end + 1..].trim_start();
|
||||
if let Some(stripped) = rest.strip_prefix('[')
|
||||
&& let Some((_, tail)) = stripped.split_once(']')
|
||||
{
|
||||
rest = tail.trim_start();
|
||||
}
|
||||
if (environment == "tabularx" || environment == "tabular*")
|
||||
&& let Some((_, used)) = braced_group(rest)
|
||||
{
|
||||
rest = rest[used..].trim_start();
|
||||
}
|
||||
let (spec, used) = braced_group(rest)?;
|
||||
let body = &rest[used..];
|
||||
let body_end = body.rfind("\\end{tabular")?;
|
||||
Some((spec, body[..body_end].trim()))
|
||||
}
|
||||
|
||||
/// Flatten nested `tabular` environments to a text summary (fallback).
|
||||
#[allow(dead_code)]
|
||||
fn flatten_nested_tables(source: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = source;
|
||||
@@ -3472,9 +3517,51 @@ fn tabular_unit(
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() {
|
||||
resolve_nested_tables(halign, geometry, id);
|
||||
}
|
||||
unit
|
||||
}
|
||||
|
||||
fn resolve_nested_tables(halign: &mut texrra_tex_core::Halign, geometry: &PageGeometry, id: u64) {
|
||||
let mut placements = Vec::new();
|
||||
for (row_index, row) in halign.rows.iter().enumerate() {
|
||||
for (cell_index, cell) in row.cells.iter().enumerate() {
|
||||
if let Some(rest) = cell.text.trim().strip_prefix("\\texrranested{")
|
||||
&& let Some((index, _)) = rest.split_once('}')
|
||||
&& let Ok(index) = index.trim().parse::<usize>()
|
||||
{
|
||||
placements.push((row_index, cell_index, index));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (row, cell, index) in placements {
|
||||
let Some(source) = geometry.nested_tables.get(index).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let Some((template, body)) = nested_table_parts(&source) else {
|
||||
continue;
|
||||
};
|
||||
let template = template.to_string();
|
||||
let body = body.to_string();
|
||||
let inner = tabular_unit(geometry, id, &template, &body, None);
|
||||
let Some(VerticalItem::Halign(table)) = inner.items.first().cloned() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(cell) = halign
|
||||
.rows
|
||||
.get_mut(row)
|
||||
.and_then(|line| line.cells.get_mut(cell))
|
||||
{
|
||||
cell.text.clear();
|
||||
}
|
||||
halign.nested.push((row, cell, table));
|
||||
}
|
||||
if !halign.nested.is_empty() {
|
||||
halign.refresh_measurements();
|
||||
}
|
||||
}
|
||||
|
||||
fn engine_template(spec: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut characters = spec.chars().peekable();
|
||||
@@ -15280,8 +15367,10 @@ left & right \\
|
||||
\end{tabular}";
|
||||
let (body, geometry) = geometry_and_body(source);
|
||||
assert_eq!(geometry.tabular.len(), 1, "outer table captured once");
|
||||
assert_eq!(geometry.nested_tables.len(), 1, "nested table stored once");
|
||||
let (template, text, _) = &geometry.tabular[0];
|
||||
assert_eq!(template, "ll");
|
||||
assert!(text.contains("\\texrranested{0}"), "{text}");
|
||||
assert!(!text.contains("begin{tabular}"), "{text}");
|
||||
let blocks = paragraphs(&body).expect("paragraphs");
|
||||
let document = build_document(&blocks, &geometry);
|
||||
@@ -15297,11 +15386,25 @@ left & right \\
|
||||
.expect("halign");
|
||||
assert_eq!(halign.column_widths.len(), 2);
|
||||
assert_eq!(halign.rows.len(), 2);
|
||||
assert!(
|
||||
halign.rows[0].cells[1].text.contains("a b ; c d"),
|
||||
"nested content flattened as {:?}",
|
||||
halign.rows[0].cells[1].text
|
||||
assert_eq!(halign.nested.len(), 1, "nested table attached");
|
||||
let (row, cell, table) = &halign.nested[0];
|
||||
assert_eq!((*row, *cell), (0, 1));
|
||||
assert_eq!(table.rows.len(), 2);
|
||||
assert_eq!(table.column_widths.len(), 2);
|
||||
assert!(halign.rows[0].cells[1].text.is_empty());
|
||||
let cells: String = table
|
||||
.rows
|
||||
.iter()
|
||||
.flat_map(|row| row.cells.iter().map(|cell| cell.text.clone()))
|
||||
.collect();
|
||||
assert!(cells.contains('a') && cells.contains('d'), "{cells}");
|
||||
let document_source = format!(
|
||||
"\\documentclass{{article}}\n\\begin{{document}}\n\n{source}\n\nAfter.\n\n\\end{{document}}\n"
|
||||
);
|
||||
let json = preview_json(&document_source).expect("preview");
|
||||
let value: serde_json::Value = serde_json::from_str(&json).expect("JSON");
|
||||
let svg = value["pages"][0]["svg"].as_str().expect("svg");
|
||||
assert!(svg.contains("a") && svg.contains("d"), "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user