Keep nested tabulars inside their outer table

The table capture ended at the first \end{tabular}, so a nested table inside a
cell closed the outer table early and the remaining inner rows leaked into the
document. Track the nesting depth of \begin{tabular}/\end{tabular} and only
close the outer environment at depth zero.

Nested blocks are flattened before the outer halign parses them: inner rows are
split on \\ and cells on &, rule commands and \multicolumn/\multirow wrappers
are stripped, and the text is joined as "a b ; c d" inside the outer cell. The
outer structure, column count and row count survive; true nested-table layout
and \valign remain open.

A regression test wraps a 2x2 tabular in a 2-column outer table and checks one
captured table, two columns, two rows and the flattened inner text.
This commit is contained in:
gloamxun committed 2026-10-26 23:56:43 +08:00
1 parent 4b28d65006
commit def93b6cf5
3 files changed
+236 -15

No files matched your search

+229 -11
View File
@@ -2141,25 +2141,35 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
.replace("\\end{table*}", "\\end{table}");
let mut geometry = PageGeometry::default();
let mut body = String::new();
let mut tabular: Option<(String, String, &'static str, Option<i64>)> = None;
let mut tabular: Option<(String, String, &'static str, Option<i64>, usize)> = None;
for line in source.lines() {
let trimmed = line.trim();
if let Some((_, text, environment, _)) = tabular.as_mut() {
if let Some((_, text, environment, _, depth)) = tabular.as_mut() {
let end = format!("\\end{{{environment}}}");
let closed = trimmed.strip_suffix(&end);
if let Some(prefix) = closed {
let prefix = prefix.trim();
if !prefix.is_empty() {
if !text.is_empty() {
text.push('\n');
let begins = trimmed.matches("\\begin{tabular").count();
let ends = trimmed.matches("\\end{tabular").count();
if closed.is_some() && *depth == 0 && begins == 0 {
if let Some(prefix) = closed {
let prefix = prefix.trim();
if !prefix.is_empty() {
if !text.is_empty() {
text.push('\n');
}
text.push_str(prefix);
}
text.push_str(prefix);
}
let (template, text, _, target) = tabular.take().unwrap();
let (template, text, _, target, _) = tabular.take().unwrap();
let text = flatten_nested_tables(&text);
geometry
.tabular
.push((template, expand_multirow(&text), target));
} else {
if begins > ends {
*depth += begins - ends;
} else {
*depth = depth.saturating_sub(ends - begins);
}
if !text.is_empty() {
text.push('\n');
}
@@ -2200,7 +2210,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
body.push('\n');
}
body.push_str(&format!("\\texrratable{{{}}}\n", geometry.tabular.len()));
tabular = Some((template.to_string(), String::new(), environment, target));
tabular = Some((template.to_string(), String::new(), environment, target, 0));
}
continue;
}
@@ -2830,7 +2840,8 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
body.push('\n');
}
}
if let Some((template, text, _, target)) = tabular {
if let Some((template, text, _, target, _)) = tabular {
let text = flatten_nested_tables(&text);
geometry
.tabular
.push((template, expand_multirow(&text), target));
@@ -2855,6 +2866,181 @@ 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.
fn flatten_nested_tables(source: &str) -> 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];
out.push_str(&flatten_nested_block(block));
rest = &after[end..];
}
out.push_str(rest);
out
}
/// Return the byte offset just past the matching `\end{tabular}`.
fn nested_table_end(text: &str) -> Option<usize> {
let begin = "\\begin{tabular";
let end = "\\end{tabular}";
let mut depth = 0_i64;
let mut cursor = 0;
while cursor < text.len() {
let next_begin = text[cursor..].find(begin).map(|offset| cursor + offset);
let next_end = text[cursor..].find(end).map(|offset| cursor + offset);
match (next_begin, next_end) {
(Some(begin_at), Some(end_at)) if begin_at < end_at => {
depth += 1;
cursor = begin_at + begin.len();
}
(_, Some(end_at)) => {
depth -= 1;
cursor = end_at + end.len();
if depth <= 0 {
return Some(cursor);
}
}
(Some(begin_at), None) => {
depth += 1;
cursor = begin_at + begin.len();
}
(None, None) => return None,
}
}
None
}
fn flatten_nested_block(block: &str) -> String {
let Some(open_end) = block.find('}') else {
return String::new();
};
let environment = block.get("\\begin{".len()..open_end).unwrap_or("");
let body_end = block.rfind("\\end{tabular").unwrap_or(block.len());
let mut rest = block[open_end + 1..body_end].trim_start();
if let Some(stripped) = rest.strip_prefix('[')
&& let Some((_, tail)) = stripped.split_once(']')
{
rest = tail.trim_start();
}
if environment == "tabularx" || environment == "tabular*" {
if let Some((_, used)) = braced_group(rest) {
rest = rest[used..].trim_start();
}
}
let Some((_spec, used)) = braced_group(rest) else {
return String::new();
};
let body = &rest[used..];
let rows: Vec<String> = split_top_level(body, "\\\\")
.into_iter()
.map(|row| {
let row = strip_table_rules(&row);
let cells: Vec<String> = split_top_level(&row, "&")
.into_iter()
.map(|cell| flatten_nested_cell(&cell))
.filter(|cell| !cell.is_empty())
.collect();
cells.join(" ")
})
.filter(|row| !row.is_empty())
.collect();
rows.join(" ; ")
}
fn flatten_nested_cell(cell: &str) -> String {
let mut text = cell.to_string();
for command in ["\\multicolumn", "\\multirow"] {
while let Some(position) = text.find(command) {
let after = &text[position + command.len()..];
let mut rest = after.trim_start();
let mut argument = String::new();
for _ in 0..3 {
if let Some((group, used)) = braced_group(rest) {
argument = group.to_string();
rest = rest[used..].trim_start();
} else {
break;
}
}
if argument.is_empty() {
break;
}
text = format!("{}{}{}", &text[..position], argument, rest);
}
}
let text = flatten_nested_tables(&text);
let text = strip_table_rules(&text);
let text = scrub_title_metadata(&text);
let text = strip_noop_commands(&text);
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn split_top_level(text: &str, separator: &str) -> Vec<String> {
let mut parts = Vec::new();
let mut current = String::new();
let mut depth = 0_i64;
let mut chars = text.char_indices().peekable();
while let Some((index, character)) = chars.next() {
if character == '{' {
depth += 1;
} else if character == '}' {
depth -= 1;
}
if depth == 0 && text[index..].starts_with(separator) {
parts.push(std::mem::take(&mut current));
for _ in 1..separator.len() {
chars.next();
}
continue;
}
current.push(character);
}
parts.push(current);
parts
}
fn strip_table_rules(text: &str) -> String {
let mut out = text.to_string();
for command in [
"\\hline",
"\\toprule",
"\\midrule",
"\\bottomrule",
"\\addlinespace",
"\\cmidrule",
"\\cline",
"\\noalign",
] {
while let Some(position) = out.find(command) {
let after = &out[position + command.len()..];
let mut rest = after.trim_start();
if let Some(inner) = rest.strip_prefix('(') {
if let Some(close) = inner.find(')') {
rest = inner[close + 1..].trim_start();
}
}
if let Some(stripped) = rest.strip_prefix('[')
&& let Some((_, tail)) = stripped.split_once(']')
{
rest = tail.trim_start();
}
if let Some((_, used)) = braced_group(rest) {
rest = &rest[used..];
}
out = format!("{}{}", &out[..position], rest);
}
}
out
}
/// Build a captured `tabular` unit with the document's `\tabcolsep`.
/// Replace `X` columns of a `tabularx` template with paragraph columns that
@@ -14482,6 +14668,38 @@ A definition.
assert!(!text.contains('?'), "{text}");
}
#[test]
fn nested_tables_keep_the_outer_structure() {
let source = r"\begin{tabular}{ll}
outer & \begin{tabular}{cc}a & b\\ c & d\end{tabular} \\
left & right \\
\end{tabular}";
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.tabular.len(), 1, "outer table captured once");
let (template, text, _) = &geometry.tabular[0];
assert_eq!(template, "ll");
assert!(!text.contains("begin{tabular}"), "{text}");
let blocks = paragraphs(&body).expect("paragraphs");
let document = build_document(&blocks, &geometry);
let halign = document
.units
.iter()
.find_map(|unit| {
unit.items.iter().find_map(|item| match item {
VerticalItem::Halign(halign) => Some(halign),
_ => None,
})
})
.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
);
}
#[test]
fn savebox_dimensions_are_frozen_and_readable() {
let source = "\\newsavebox{\\b}\n\\sbox{\\b}{abc}\n\nX\\hspace{\\wd\\b}Y";