diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index e989946..b842b35 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -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 = 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); diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 078b1bf..a7ef6fe 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -191,3 +191,5 @@ empty paragraphs. `Unit::halign_from_source` parses `&` rows, `\\` separators, `\omit`, `\span`, `\multispan{n}` and `\hline` rule rows. +`Unit::halign_from_source_with_template` additionally accepts an `l`/`c`/`r` +column template. \ No newline at end of file