Report diagnostics and lay out cases environments

This commit is contained in:
gloamxun committed 2026-10-26 00:35:08 +08:00
1 parent a28e8926c7
commit 971190df26
6 files changed
+281 -10

No files matched your search

+231
View File
@@ -88,6 +88,10 @@ pub enum MathAtom {
},
/// A `\middle` delimiter; TeX sizes it with the enclosing `\left`/`\right`.
Middle(char),
/// A `cases` environment: each row holds the cells split on `&`.
Cases {
rows: Vec<Vec<MathAtom>>,
},
/// Rows of an `align` (column-aligned) or `gather` (centred) display.
Aligned {
rows: Vec<AlignedRow>,
@@ -536,6 +540,200 @@ pub fn italic_correction(atom: &MathAtom, font: &Cmr10Metrics) -> i64 {
}
}
/// Geometry shared by the layout and painter of a `cases` environment.
pub(crate) struct CasesLayout {
pub boxes: Vec<Vec<MathBox>>,
pub column_widths: Vec<i64>,
pub column_starts: Vec<i64>,
pub baselines: Vec<i64>,
pub first_height: i64,
pub brace: (i64, i64, i64),
pub width: i64,
pub height: i64,
pub depth: i64,
}
/// Lay out the rows of a `cases` environment and the brace beside them.
pub(crate) fn cases_layout(rows: &[Vec<MathAtom>], font: &Cmr10Metrics) -> CasesLayout {
let boxes: Vec<Vec<MathBox>> = rows
.iter()
.map(|row| row.iter().map(|cell| layout_math(cell, font)).collect())
.collect();
let columns = boxes.iter().map(|row| row.len()).max().unwrap_or(0);
let mut column_widths = vec![0_i64; columns];
for row in &boxes {
for (column, cell) in row.iter().enumerate() {
column_widths[column] = column_widths[column].max(cell.width);
}
}
let gap = 655_360;
let mut column_starts = vec![0_i64; columns];
let mut cursor = 0_i64;
for (column, width) in column_widths.iter().enumerate() {
column_starts[column] = cursor;
cursor += *width + if column + 1 < columns { gap } else { 0 };
}
let body_width = cursor;
let row_heights: Vec<i64> = boxes
.iter()
.map(|row| row.iter().map(|cell| cell.height).max().unwrap_or(0))
.collect();
let row_depths: Vec<i64> = boxes
.iter()
.map(|row| row.iter().map(|cell| cell.depth).max().unwrap_or(0))
.collect();
let mut baselines = vec![0_i64; boxes.len()];
for index in 1..boxes.len() {
let advance = (row_depths[index - 1] + row_heights[index] + 2 * 65_536).max(655_360);
baselines[index] = baselines[index - 1] + advance;
}
let first_height = row_heights.first().copied().unwrap_or(0);
let last_baseline = baselines.last().copied().unwrap_or(0);
let last_depth = row_depths.last().copied().unwrap_or(0);
let extent = first_height + last_baseline + last_depth;
let axis = 2 * 65_536 + 32_768;
let brace = select_delimiter(*font, '{', extent);
CasesLayout {
boxes,
column_widths,
column_starts,
baselines,
first_height,
brace,
width: brace.0 + 3 * 65_536 + body_width,
height: (extent / 2 + axis).max(brace.1),
depth: (extent / 2 - axis).max(0).max(brace.2),
}
}
/// Read the body of `\begin{name}` up to its matching `\end{name}`.
fn read_environment(chars: &[char], index: usize, name: &str) -> Option<(String, usize)> {
let pattern: Vec<char> = format!("\\end{{{name}}}").chars().collect();
let mut cursor = index;
let mut depth = 0_i32;
while cursor < chars.len() {
match chars[cursor] {
'{' => depth += 1,
'}' => depth -= 1,
_ => {}
}
if depth == 0
&& cursor + pattern.len() <= chars.len()
&& chars[cursor..cursor + pattern.len()] == pattern[..]
{
let inner: String = chars[index..cursor].iter().collect();
return Some((inner, cursor + pattern.len()));
}
cursor += 1;
}
None
}
/// Split an environment body into rows on `\\` and cells on `&`.
pub(crate) fn split_environment_rows(inner: &str) -> Vec<Vec<String>> {
fn cells(row: &str) -> Vec<String> {
let mut cells = Vec::new();
let mut cell = String::new();
let mut depth = 0_i32;
for character in row.chars() {
match character {
'{' => {
depth += 1;
cell.push(character);
}
'}' => {
depth -= 1;
cell.push(character);
}
'&' if depth == 0 => {
cells.push(cell.trim().to_string());
cell.clear();
}
_ => cell.push(character),
}
}
cells.push(cell.trim().to_string());
cells
}
let mut rows = Vec::new();
let mut row = String::new();
let mut depth = 0_i32;
let mut characters = inner.chars().peekable();
while let Some(character) = characters.next() {
match character {
'{' => {
depth += 1;
row.push(character);
}
'}' => {
depth -= 1;
row.push(character);
}
'\\' if depth == 0 => {
if characters.peek() == Some(&'\\') {
characters.next();
rows.push(cells(&row));
row.clear();
} else {
row.push(character);
}
}
_ => row.push(character),
}
}
let last = cells(&row);
if !(last.len() == 1 && last[0].is_empty()) {
rows.push(last);
}
rows
}
/// Parse a `\begin{env}...\end{env}` math environment.
fn math_environment(chars: &[char], index: usize) -> Option<(MathAtom, usize)> {
let mut cursor = index;
while chars.get(cursor) == Some(&'\u{0}') {
cursor += 1;
}
if chars.get(cursor) != Some(&'{') {
return None;
}
cursor += 1;
let mut name = String::new();
while let Some(&character) = chars.get(cursor) {
if character == '}' {
break;
}
name.push(character);
cursor += 1;
}
if chars.get(cursor) != Some(&'}') {
return None;
}
cursor += 1;
let (inner, end) = read_environment(chars, cursor, &name)?;
match name.as_str() {
"cases" => {
let rows = split_environment_rows(&inner)
.into_iter()
.map(|row| {
row.into_iter()
.map(|cell| {
if cell.is_empty() {
MathAtom::Row(Vec::new())
} else {
parse_math(&cell)
}
})
.collect()
})
.collect();
Some((MathAtom::Cases { rows }, end))
}
_ => None,
}
}
pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
match atom {
MathAtom::Symbol(character) => {
@@ -627,6 +825,14 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
depth: body_box.depth.max(left_box.2).max(right_box.2),
}
}
MathAtom::Cases { rows } => {
let layout = cases_layout(rows, font);
MathBox {
width: layout.width,
height: layout.height,
depth: layout.depth,
}
}
MathAtom::Accent { base, .. } => {
let base_box = layout_math(base, font);
MathBox {
@@ -1475,6 +1681,10 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
}
parse_atom(chars, after)
}
"begin" => match math_environment(chars, next) {
Some((atom, after)) => (atom, after),
None => (MathAtom::Symbol('?'), next),
},
"frac" | "tfrac" | "dfrac" | "cfrac" => {
let (numerator, after) = parse_atom(chars, next);
let (denominator, after) = parse_atom(chars, after);
@@ -2273,6 +2483,27 @@ mod tests {
assert!(two.depth > single.depth);
}
#[test]
fn cases_environment_lays_out_its_rows() {
let atom = parse_math("\\begin{cases} x & x>0 \\\\ 0 & \\text{else} \\end{cases}");
let atom = match atom {
MathAtom::Row(atoms) => atoms
.into_iter()
.find(|atom| matches!(atom, MathAtom::Cases { .. }))
.expect("cases atom in the row"),
other => other,
};
let MathAtom::Cases { rows } = atom else {
panic!("expected a cases atom");
};
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].len(), 2);
assert_eq!(rows[1].len(), 2);
let box_ = layout_math(&MathAtom::Cases { rows }, &Cmr10Metrics::default());
assert!(box_.width > 3 * 65_536);
assert!(box_.height > 0);
}
#[test]
fn big_delimiters_allow_math_spaces() {
let font = Cmr10Metrics::default();