Draw booktabs rules with their own weights and spans

This commit is contained in:
gloamxun committed 2026-10-24 01:03:53 +08:00
1 parent d0ffeea94b
commit c3e75bd244
5 files changed
+267 -7

No files matched your search

+244 -2
View File
@@ -50,6 +50,25 @@ pub struct HalignRow {
pub rule: bool,
}
/// A horizontal rule at a `\halign` row boundary.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct HalignRule {
/// Boundary the rule sits above; `rows.len()` paints below the table.
pub row: usize,
/// First covered column.
pub start: usize,
/// Last covered column (inclusive).
pub end: usize,
/// Thickness in scaled points (booktabs heavy/light rule widths).
pub width: i64,
/// Space trimmed from the left edge (`\cmidrule(lr)`).
#[serde(default)]
pub trim_left: i64,
/// Space trimmed from the right edge (`\cmidrule(lr)`).
#[serde(default)]
pub trim_right: i64,
}
/// A laid-out `\halign` table: natural column widths plus row rules.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Halign {
@@ -62,6 +81,9 @@ pub struct Halign {
/// the uniform intercolumn spacing derived from `width`.
#[serde(default)]
pub column_skips: Vec<i64>,
/// Painted rules (booktabs heavy/light rules and partial `\cmidrule`s).
#[serde(default)]
pub rules: Vec<HalignRule>,
pub width: i64,
pub height: i64,
pub line_height: i64,
@@ -112,6 +134,7 @@ impl Halign {
column_widths: self.column_widths.clone(),
column_wrap: self.column_wrap.clone(),
column_skips: self.column_skips.clone(),
rules: self.rules_for_chunk(start, index),
width: self.width,
height,
line_height: self.line_height,
@@ -126,6 +149,7 @@ impl Halign {
column_widths: self.column_widths.clone(),
column_wrap: self.column_wrap.clone(),
column_skips: self.column_skips.clone(),
rules: self.rules_for_chunk(start, self.rows.len()),
width: self.width,
height,
line_height: self.line_height,
@@ -239,6 +263,44 @@ impl Halign {
self.column_skips.get(boundary).copied().unwrap_or(0)
}
}
/// Rules that belong to the page chunk covering rows `start..end`.
fn rules_for_chunk(&self, start: usize, end: usize) -> Vec<HalignRule> {
self.rules
.iter()
.filter_map(|rule| {
let belongs =
(rule.row > start && rule.row <= end) || (start == 0 && rule.row == 0);
if belongs {
Some(HalignRule {
row: rule.row - start,
..*rule
})
} else {
None
}
})
.collect()
}
/// Left edge of a column (including all gaps before it).
fn column_offset(&self, column: usize) -> i64 {
let column = column.min(self.column_widths.len());
self.column_widths[..column].iter().sum::<i64>()
+ (0..column)
.map(|boundary| self.gap_width(boundary))
.sum::<i64>()
}
/// Horizontal rectangle of one rule: `(x, width)`.
pub fn rule_rect(&self, rule: &HalignRule) -> (i64, i64) {
let last = self.column_widths.len().saturating_sub(1);
let start = rule.start.min(last);
let end = rule.end.min(last).max(start);
let x = self.column_offset(start) + rule.trim_left;
let right = (self.column_offset(end + 1) - rule.trim_right).min(self.width);
(x, (right - x).max(65_536))
}
}
/// Natural width of a run of text at the illustrative 10pt metrics.
@@ -322,6 +384,79 @@ fn parse_tex_dimension(spec: &str) -> Option<i64> {
Some((value * points_per_unit * 65_536.0).round() as i64)
}
/// Strip booktabs rule commands from a row, recording their spans.
fn take_booktabs_rules(raw: &str, row: usize, columns: usize) -> (String, Vec<HalignRule>) {
let mut rules = Vec::new();
let mut remaining = raw.trim();
loop {
let trimmed = remaining.trim_start();
let end = columns.saturating_sub(1);
let (width, rest) = if let Some(rest) = trimmed.strip_prefix(r"\toprule") {
(Some(52_429), rest)
} else if let Some(rest) = trimmed.strip_prefix(r"\bottomrule") {
(Some(52_429), rest)
} else if let Some(rest) = trimmed.strip_prefix(r"\midrule") {
(Some(32_768), rest)
} else {
(None, trimmed)
};
if let Some(width) = width {
rules.push(HalignRule {
row,
start: 0,
end,
width,
trim_left: 0,
trim_right: 0,
});
remaining = rest.trim_start();
continue;
}
if let Some(rest) = trimmed.strip_prefix(r"\cmidrule") {
let mut rest = rest.trim_start();
let mut trim_left = 0_i64;
let mut trim_right = 0_i64;
if let Some(after_open) = rest.strip_prefix('(') {
if let Some((options, tail)) = after_open.split_once(')') {
if options.contains('l') {
trim_left = 4 * 65_536;
}
if options.contains('r') {
trim_right = 4 * 65_536;
}
rest = tail.trim_start();
}
}
if let Some(body) = rest.strip_prefix('{') {
if let Some((span, tail)) = body.split_once('}') {
let (left, right) = span.split_once('-').unwrap_or((span, span));
let start = left.trim().parse::<usize>().unwrap_or(1).saturating_sub(1);
let end = right
.trim()
.parse::<usize>()
.unwrap_or(columns)
.saturating_sub(1)
.min(columns.saturating_sub(1));
if start <= end {
rules.push(HalignRule {
row,
start,
end,
width: 32_768,
trim_left,
trim_right,
});
}
remaining = tail.trim_start();
continue;
}
}
}
break;
}
(remaining.to_owned(), rules)
}
/// Parse an alignment template into per-column alignment and wrap widths.
fn parse_column_template(template: &str) -> (Vec<CellAlignment>, Vec<Option<i64>>) {
let mut alignments = Vec::new();
@@ -536,6 +671,7 @@ impl Unit {
column_widths,
column_wrap: wraps,
column_skips,
rules: Vec::new(),
width,
height: 0,
line_height,
@@ -592,11 +728,15 @@ impl Unit {
let (alignments, wraps) = parse_column_template(template);
let column_count = alignments.len().max(1);
let mut rows = Vec::new();
let mut rules: Vec<HalignRule> = Vec::new();
for raw_row in source.split(r"\\") {
if raw_row.trim().is_empty() {
continue;
}
let mut raw_row = raw_row.trim();
let (rule_text, collected) =
take_booktabs_rules(raw_row.trim(), rows.len(), column_count);
rules.extend(collected);
let mut raw_row = rule_text.trim();
if let Some(rest) = raw_row.strip_prefix(r"\noalign") {
let rest = rest.trim_start();
if let Some(body) = rest.strip_prefix('{') {
@@ -651,7 +791,14 @@ impl Unit {
}
rows.push(HalignRow { cells, rule: false });
}
Self::halign_with_layout(id, rows, column_count, intercolumn, wraps, tabskips)
let mut unit =
Self::halign_with_layout(id, rows, column_count, intercolumn, wraps, tabskips);
if !rules.is_empty() {
if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() {
halign.rules = rules;
}
}
unit
}
/// A running mark item, recorded on the page where it is shipped out.
@@ -6593,6 +6740,101 @@ cc & d\n",
);
}
#[test]
fn booktabs_rules_carry_widths_and_partial_spans() {
let source = r"\toprule
Name & Value \\
\midrule
a & 1 \\
\cmidrule(lr){1-1}
b & 2 \\
\bottomrule
";
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(), 3);
assert_eq!(halign.rules.len(), 4);
assert_eq!(
halign.rules[0],
HalignRule {
row: 0,
start: 0,
end: 1,
width: 52_429,
trim_left: 0,
trim_right: 0,
}
);
assert_eq!(halign.rules[1].row, 1);
assert_eq!(halign.rules[1].width, 32_768);
assert_eq!(halign.rules[2].row, 2);
assert_eq!(halign.rules[2].start, 0);
assert_eq!(halign.rules[2].end, 0);
assert_eq!(halign.rules[2].trim_left, 4 * 65_536);
assert_eq!(halign.rules[2].trim_right, 4 * 65_536);
assert_eq!(halign.rules[3].row, 3);
assert_eq!(halign.rules[3].width, 52_429);
let (x, width) = halign.rule_rect(&halign.rules[2]);
assert_eq!(x, 4 * 65_536);
assert_eq!(width, halign.column_widths[0] - 8 * 65_536);
let list = halign.display_list();
let painted: Vec<(i64, i64, i64)> = list
.items
.iter()
.filter_map(|item| match item {
DisplayItem::Rule { x, y, width, .. } => Some((*x, *y, *width)),
_ => None,
})
.collect();
assert_eq!(painted.len(), 4);
assert!(
painted
.iter()
.any(|(_, _, width)| *width < halign.width / 2)
);
assert!(painted.iter().any(|(_, y, _)| *y == halign.height));
}
#[test]
fn booktabs_rules_follow_page_chunks() {
let mut source = String::from(
r"\toprule
",
);
for index in 0..20 {
source.push_str(&format!("row{index} & value{index} \\\\\n"));
}
source.push_str(
r"\bottomrule
",
);
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.rules.len(), 2);
let chunks = halign.split_for_height(halign.line_height * 3);
assert!(chunks.len() >= 2);
assert!(
chunks[0]
.rules
.iter()
.any(|rule| rule.row == 0 && rule.width == 52_429)
);
let last = chunks.last().unwrap();
assert!(
last.rules
.iter()
.any(|rule| rule.row == last.rows.len() && rule.width == 52_429)
);
assert_eq!(
chunks.iter().map(|chunk| chunk.rows.len()).sum::<usize>(),
20
);
}
#[test]
fn checkpoint_round_trips_through_serde() {
let engine = Engine::layout(&document());
+18
View File
@@ -273,6 +273,15 @@ impl Halign {
};
let mut y = 0_i64;
for (row_index, row) in self.rows.iter().enumerate() {
for rule in self.rules.iter().filter(|rule| rule.row == row_index) {
let (x, width) = self.rule_rect(rule);
list.push(DisplayItem::Rule {
x,
y,
width,
height: rule.width,
});
}
if row.rule {
let height = 26_214; // 0.4pt in scaled points.
list.push(DisplayItem::Rule {
@@ -319,6 +328,15 @@ impl Halign {
}
y += row_height;
}
for rule in self.rules.iter().filter(|rule| rule.row == self.rows.len()) {
let (x, width) = self.rule_rect(rule);
list.push(DisplayItem::Rule {
x,
y,
width,
height: rule.width,
});
}
list
}
}