Fill tabularx X columns from the target width

This commit is contained in:
gloamxun committed 2026-10-26 01:29:52 +08:00
1 parent 7ba66392ea
commit 20a2b1fa1f
4 files changed
+195 -26

No files matched your search

+190 -21
View File
@@ -223,7 +223,7 @@ struct PageGeometry {
/// Base font size from `\documentclass[11pt]`-style options.
base_font_size: Option<i64>,
/// Captured `tabular` environments: (column spec, halign source).
tabular: Vec<(String, String)>,
tabular: Vec<(String, String, Option<i64>)>,
/// `\title{...}` captured from the preamble.
title: Option<String>,
/// `\author{...}` captured from the preamble.
@@ -1104,13 +1104,13 @@ fn hypersetup_values(line: &str) -> Vec<(String, String)> {
fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
let mut geometry = PageGeometry::default();
let mut body = String::new();
let mut tabular: Option<(String, String, &'static str)> = None;
let mut tabular: Option<(String, String, &'static str, Option<i64>)> = None;
for line in source.lines() {
let trimmed = line.trim();
if let Some((_, text, environment)) = tabular.as_mut() {
if let Some((_, text, environment, _)) = tabular.as_mut() {
if trimmed == format!("\\end{{{environment}}}") {
let (template, text, _) = tabular.take().unwrap();
geometry.tabular.push((template, text));
let (template, text, _, target) = tabular.take().unwrap();
geometry.tabular.push((template, text, target));
} else {
if !text.is_empty() {
text.push('\n');
@@ -1120,7 +1120,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
continue;
}
let mut table_environment = None;
for environment in ["tabular", "longtable"] {
for environment in ["tabular", "longtable", "tabularx", "tabularx"] {
let begin = format!("\\begin{{{environment}}}");
if let Some(rest) = trimmed.strip_prefix(&begin) {
table_environment = Some((environment, rest));
@@ -1136,12 +1136,23 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
Some((_, tail)) => tail.trim_start(),
None => rest,
};
let (rest, target) = if environment == "tabularx" {
let Some((width, after)) = braced(rest) else {
continue;
};
match parse_dimension(width) {
Some(width) => (after.trim_start(), Some(width)),
None => continue,
}
} else {
(rest, None)
};
if let Some((template, _)) = braced(rest) {
if !body.ends_with('\n') {
body.push('\n');
}
body.push_str(&format!("\\texrratable{{{}}}\n", geometry.tabular.len()));
tabular = Some((template.to_string(), String::new(), environment));
tabular = Some((template.to_string(), String::new(), environment, target));
}
continue;
}
@@ -1521,8 +1532,8 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
body.push('\n');
}
}
if let Some((template, text, _)) = tabular {
geometry.tabular.push((template, text));
if let Some((template, text, _, target)) = tabular {
geometry.tabular.push((template, text, target));
}
(body, geometry)
}
@@ -1545,10 +1556,132 @@ fn braced(text: &str) -> Option<(&str, &str)> {
}
/// Build a captured `tabular` unit with the document's `\tabcolsep`.
fn tabular_unit(geometry: &PageGeometry, id: u64, template: &str, source: &str) -> Unit {
/// Replace `X` columns of a `tabularx` template with paragraph columns that
/// share the leftover width, so the table fills its declared target.
fn expand_tabular_template(template: &str, source: &str, target: Option<i64>) -> String {
let Some(target) = target else {
return template.to_string();
};
if !template.contains('X') {
return template.to_string();
}
let probe_template: String = template
.chars()
.map(|character| if character == 'X' { 'l' } else { character })
.collect();
let probe = Unit::halign_from_source_with_template_and_tabskips(
0,
&engine_template(&probe_template),
source,
6,
Vec::new(),
);
let Some(VerticalItem::Halign(halign)) = probe.items.first() else {
return template.to_string();
};
let mut flags = Vec::new();
let characters: Vec<char> = template.chars().collect();
let mut index = 0;
while index < characters.len() {
match characters[index] {
'l' | 'c' | 'r' => {
flags.push(false);
index += 1;
}
'X' => {
flags.push(true);
index += 1;
}
'p' | 'm' | 'b' => {
flags.push(false);
index += 1;
if characters.get(index) == Some(&'{') {
let mut depth = 0_i32;
while index < characters.len() {
let inner = characters[index];
index += 1;
match inner {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
}
}
}
_ => index += 1,
}
}
let x_count = flags.iter().filter(|expand| **expand).count();
if x_count == 0 {
return template.to_string();
}
let gaps = halign.column_widths.len().saturating_sub(1) as i64;
let fixed: i64 = halign
.column_widths
.iter()
.zip(flags.iter())
.filter(|(_, expand)| !**expand)
.map(|(width, _)| *width)
.sum();
let share = ((target - fixed - gaps * 6 * SCALE) / x_count as i64).max(SCALE);
let share = format!("p{{{:.4}pt}}", share as f64 / SCALE as f64);
let mut out = String::new();
let mut index = 0;
while index < characters.len() {
let character = characters[index];
match character {
'X' => {
out.push_str(&share);
index += 1;
}
'p' | 'm' | 'b' => {
out.push('p');
index += 1;
if characters.get(index) == Some(&'{') {
let mut depth = 0_i32;
while index < characters.len() {
let inner = characters[index];
out.push(inner);
index += 1;
match inner {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
}
}
}
_ => {
out.push(character);
index += 1;
}
}
}
out
}
fn tabular_unit(
geometry: &PageGeometry,
id: u64,
template: &str,
source: &str,
target: Option<i64>,
) -> Unit {
let template = expand_tabular_template(template, source, target);
let mut unit = Unit::halign_from_source_with_template_and_tabskips(
id,
&engine_template(template),
&engine_template(&template),
source,
6,
Vec::new(),
@@ -6249,8 +6382,9 @@ fn build_document_with_labels(
});
}
if let Some(table) = spec.table {
if let Some((template, source)) = geometry.tabular.get(table) {
let table_unit = tabular_unit(&geometry, index as u64, template, source);
if let Some((template, source, target)) = geometry.tabular.get(table) {
let table_unit =
tabular_unit(&geometry, index as u64, template, source, *target);
content.extend(table_unit.items);
}
}
@@ -6267,8 +6401,8 @@ fn build_document_with_labels(
return unit;
}
if let Some(table) = table_reference(&paragraph.text) {
if let Some((template, source)) = geometry.tabular.get(table) {
let mut unit = tabular_unit(&geometry, index as u64, template, source);
if let Some((template, source, target)) = geometry.tabular.get(table) {
let mut unit = tabular_unit(&geometry, index as u64, template, source, *target);
unit.space_before = paragraph.space_before;
unit.space_stretch = paragraph.space_stretch;
unit.space_shrink = paragraph.space_shrink;
@@ -6769,6 +6903,7 @@ const SUPPORTED_ENVIRONMENTS: &[&str] = &[
"verbatim",
"tabular",
"longtable",
"tabularx",
"displaymath",
"math",
"equation",
@@ -7584,7 +7719,6 @@ mod source_tests {
assert!(!json.contains("alignat"), "{json}");
}
#[test]
#[test]
fn operator_names_and_declared_operators_render() {
let source = r"\DeclareMathOperator{\Tr}{Tr}
@@ -7634,9 +7768,9 @@ x = 1 \\
y = 2
\end{eqnarray}\]
\begin{tabularx}{\textwidth}{lX}
\begin{wrapfigure}{r}{4cm}
a & b
\end{tabularx}
\end{wrapfigure}
\end{document}";
let json = preview_json(source).expect("preview");
assert!(
@@ -7644,7 +7778,7 @@ a & b
"{json}"
);
assert!(
json.contains("unsupported environment `tabularx`"),
json.contains("unsupported environment `wrapfigure`"),
"{json}"
);
assert!(!json.contains("unsupported environment `align`"), "{json}");
@@ -7665,8 +7799,6 @@ a & b
);
}
#[test]
#[test]
#[test]
fn headings_become_pdf_bookmarks() {
let pdf = pdf_bytes(
@@ -8085,6 +8217,43 @@ See \ref{fig:a} and \ref{tab:b}.";
assert!(!body.contains("tabular"), "environment leaked: {body}");
}
#[test]
fn tabularx_fills_its_target_width() {
let source =
"\\begin{tabularx}{200pt}{lX}\na & alpha beta gamma \\\\\nb & delta\n\\end{tabularx}";
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.tabular.len(), 1);
let template = &geometry.tabular[0].0;
assert_eq!(template, "lX");
assert!(geometry.tabular[0].2.is_some(), "target width missing");
assert!(body.contains("\\texrratable{0}"));
let blocks = paragraphs_with_geometry(
&body,
&PageGeometry::default().theorem_definitions,
0,
&geometry,
)
.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.clone()),
_ => None,
})
})
.expect("halign");
assert_eq!(halign.column_widths.len(), 2);
assert!(halign.column_widths[1] > halign.column_widths[0]);
let width = halign.width;
assert!(
(width - 200 * SCALE).abs() <= 2 * SCALE,
"width {width} not near 200pt"
);
}
#[test]
fn longtable_captures_its_body() {
let (body, geometry) =