Apply halign column templates
This commit is contained in:
1 parent
7250f7f5ca
commit
a00a2d5148
2 files changed
+37
-3
No files matched your search
@@ -209,14 +209,33 @@ impl Unit {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a small TeX-like halign body (`&`, `\\`, `\omit`, `\span`,
|
||||
/// `\multispan{n}`) into a laid-out unit.
|
||||
/// Parse a small TeX-like halign body with an `l`/`c`/`r` column template.
|
||||
pub fn halign_from_source(
|
||||
id: UnitId,
|
||||
source: &str,
|
||||
column_count: usize,
|
||||
intercolumn: i64,
|
||||
) -> Self {
|
||||
let template = "l".repeat(column_count.max(1));
|
||||
Self::halign_from_source_with_template(id, &template, source, intercolumn)
|
||||
}
|
||||
|
||||
/// Parse an `l`/`c`/`r` column template plus a halign body.
|
||||
pub fn halign_from_source_with_template(
|
||||
id: UnitId,
|
||||
template: &str,
|
||||
source: &str,
|
||||
intercolumn: i64,
|
||||
) -> Self {
|
||||
let alignments: Vec<CellAlignment> = template
|
||||
.chars()
|
||||
.map(|character| match character {
|
||||
'c' => CellAlignment::Center,
|
||||
'r' => CellAlignment::Right,
|
||||
_ => CellAlignment::Left,
|
||||
})
|
||||
.collect();
|
||||
let column_count = alignments.len().max(1);
|
||||
let mut rows = Vec::new();
|
||||
for raw_row in source.split(r"\\") {
|
||||
if raw_row.trim().is_empty() {
|
||||
@@ -257,10 +276,14 @@ impl Unit {
|
||||
if let Some(rest) = text.strip_prefix(r"\omit") {
|
||||
text = rest.trim().to_owned();
|
||||
}
|
||||
let column: usize = cells.iter().map(|cell: &HalignCell| cell.span.max(1)).sum();
|
||||
cells.push(HalignCell {
|
||||
text,
|
||||
span,
|
||||
alignment: CellAlignment::Left,
|
||||
alignment: alignments
|
||||
.get(column)
|
||||
.copied()
|
||||
.unwrap_or(CellAlignment::Left),
|
||||
});
|
||||
}
|
||||
rows.push(HalignRow { cells, rule: false });
|
||||
@@ -1151,6 +1174,15 @@ mod tests {
|
||||
assert_eq!(halign.cell_box(2, 0), Some((30, 110)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halign_template_centers_and_right_aligns_cells() {
|
||||
let unit = Unit::halign_from_source_with_template(1, "lcr", r"A & B & C", 10);
|
||||
let VerticalItem::Halign(halign) = &unit.items[0] else {
|
||||
panic!("expected halign");
|
||||
};
|
||||
assert_eq!(halign.rows[0].cells[1].alignment, CellAlignment::Center);
|
||||
assert_eq!(halign.rows[0].cells[2].alignment, CellAlignment::Right);
|
||||
}
|
||||
#[test]
|
||||
fn halign_source_parses_hline_rules() {
|
||||
let unit = Unit::halign_from_source(1, r"A & B \\ \hline C & D", 2, 10);
|
||||
|
||||
Reference in new issue
Block a user