Parse scripts, fractions and roots into math atoms

This commit is contained in:
gloamxun committed 2026-10-20 12:53:14 +08:00
1 parent cd6baba53f
commit b6d55e63dc
2 files changed
+145

No files matched your search

+143
View File
@@ -9,6 +9,8 @@ use crate::cmr10::Cmr10Metrics;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MathAtom {
Symbol(char),
Row(Vec<MathAtom>),
Sqrt(Box<MathAtom>),
Script {
base: Box<MathAtom>,
sub: Option<Box<MathAtom>>,
@@ -61,6 +63,30 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
height: 7 * 65_536,
depth: 2 * 65_536,
},
MathAtom::Row(atoms) => {
let mut width = 0;
let mut height = 0;
let mut depth = 0;
for atom in atoms {
let boxed = layout_math(atom, font);
width += boxed.width;
height = height.max(boxed.height);
depth = depth.max(boxed.depth);
}
MathBox {
width,
height,
depth,
}
}
MathAtom::Sqrt(atom) => {
let boxed = layout_math(atom, font);
MathBox {
width: boxed.width + 4 * 65_536,
height: boxed.height + 2 * 65_536,
depth: boxed.depth,
}
}
MathAtom::Script { base, sub, sup } => {
let base_box = layout_math(base, font);
let sub_box = sub.as_deref().map(|atom| layout_math(atom, font));
@@ -101,6 +127,104 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
}
}
/// Parse a small TeX math subset into a [`MathAtom`] row.
///
/// Supported: plain symbols, `{}` groups, `_`/`^` scripts, `\frac{a}{b}` and
/// `\sqrt{x}`. Whitespace is ignored. Unknown control words become `?` so a
/// later M4 parser can replace them.
pub fn parse_math(input: &str) -> MathAtom {
let chars: Vec<char> = input.chars().filter(|ch| !ch.is_whitespace()).collect();
let (atom, _) = parse_sequence(&chars, 0, false);
atom
}
fn parse_sequence(chars: &[char], mut index: usize, stop_at_brace: bool) -> (MathAtom, usize) {
let mut atoms = Vec::new();
while index < chars.len() {
if stop_at_brace && chars[index] == '}' {
break;
}
let (mut atom, mut next) = parse_atom(chars, index);
let mut sub = None;
let mut sup = None;
loop {
if next < chars.len() && chars[next] == '_' && sub.is_none() {
let (script, after) = parse_script(chars, next + 1);
sub = Some(Box::new(script));
next = after;
} else if next < chars.len() && chars[next] == '^' && sup.is_none() {
let (script, after) = parse_script(chars, next + 1);
sup = Some(Box::new(script));
next = after;
} else {
break;
}
}
if sub.is_some() || sup.is_some() {
atom = MathAtom::Script {
base: Box::new(atom),
sub,
sup,
};
}
atoms.push(atom);
index = next;
}
(MathAtom::Row(atoms), index)
}
fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
let Some(&character) = chars.get(index) else {
return (MathAtom::Row(Vec::new()), index);
};
if character == '{' {
let (atom, next) = parse_sequence(chars, index + 1, true);
let next = if chars.get(next) == Some(&'}') {
next + 1
} else {
next
};
return (atom, next);
}
if character == '\\' {
let mut next = index + 1;
let mut command = String::new();
while let Some(&ch) = chars.get(next) {
if ch.is_ascii_alphabetic() {
command.push(ch);
next += 1;
} else {
break;
}
}
return match command.as_str() {
"frac" => {
let (numerator, after) = parse_atom(chars, next);
let (denominator, after) = parse_atom(chars, after);
(MathAtom::fraction(numerator, denominator), after)
}
"sqrt" => {
let (radicand, after) = parse_atom(chars, next);
(MathAtom::Sqrt(Box::new(radicand)), after)
}
_ => (MathAtom::Symbol('?'), next),
};
}
(MathAtom::Symbol(character), index + 1)
}
fn parse_script(chars: &[char], index: usize) -> (MathAtom, usize) {
if chars.get(index) == Some(&'{') {
parse_atom(chars, index)
} else if chars.get(index) == Some(&'\\') {
parse_atom(chars, index)
} else if let Some(&character) = chars.get(index) {
(MathAtom::Symbol(character), index + 1)
} else {
(MathAtom::Row(Vec::new()), index)
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -143,4 +267,23 @@ mod tests {
assert!(fraction.height > numerator.height);
assert!(fraction.depth > 0);
}
#[test]
fn parse_script_attaches_to_the_previous_atom() {
let atom = parse_math("x^2");
let MathAtom::Row(atoms) = atom else {
panic!("expected a row");
};
assert!(matches!(&atoms[0], MathAtom::Script { sup: Some(_), .. }));
}
#[test]
fn parse_fraction_and_sqrt() {
let atom = parse_math("\\frac{a}{b} + \\sqrt{x}");
let MathAtom::Row(atoms) = atom else {
panic!("expected a row");
};
assert!(matches!(&atoms[0], MathAtom::Fraction { .. }));
assert!(matches!(&atoms[2], MathAtom::Sqrt(_)));
}
}
+2
View File
@@ -104,6 +104,8 @@ overfull ratio 4.11, badness 6942. TeX rejects the underfull candidate under
its tolerance but still emits the moderately overfull 5-word line. Reproducing
this needs a two-pass tolerance algorithm with an emergency overfull pass, not
a single cost function.
- `parse_math` converts a small TeX math subset (symbols, `{}` groups,
`_`/`^` scripts, `\frac`, `\sqrt`) into `MathAtom::Row`.
- `MathAtom::{Symbol, Script, Fraction}` and `layout_math` produce
`MathBox { width, height, depth }`; `Unit::math` turns an atom into a
vertical box. Parsing TeX math tokens and painting remain future M4 work.