Add upright text atoms inside math

This commit is contained in:
gloamxun committed 2026-10-20 12:59:45 +08:00
1 parent ebab0eca05
commit 053468875e
2 files changed
+49

No files matched your search

+47
View File
@@ -14,6 +14,7 @@ pub enum MathAtom {
radicand: Box<MathAtom>,
degree: Option<Box<MathAtom>>,
},
Text(String),
Delimited {
left: char,
right: char,
@@ -165,6 +166,20 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
depth: boxed.depth,
}
}
MathAtom::Text(text) => MathBox {
width: text
.chars()
.map(|character| {
if character == ' ' {
font.space()
} else {
font.width(character)
}
})
.sum(),
height: 6 * 65_536,
depth: 2 * 65_536,
},
MathAtom::Delimited { left, right, body } => {
let body_box = layout_math(body, font);
MathBox {
@@ -386,6 +401,21 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
let delimiter = chars.get(next).copied().unwrap_or('|');
(MathAtom::Symbol(delimiter), next + 1)
}
"text" | "mathrm" => {
let mut after = next;
if chars.get(after) == Some(&'{') {
after += 1;
}
let start = after;
while after < chars.len() && chars[after] != '}' {
after += 1;
}
let text: String = chars[start..after].iter().collect();
if after < chars.len() {
after += 1;
}
(MathAtom::Text(text), after)
}
"left" => {
let left = chars.get(next).copied().unwrap_or('(');
let (body, after) = parse_sequence(chars, next + 1, false, true);
@@ -477,6 +507,23 @@ mod tests {
assert!(indexed.height > plain.height);
}
#[test]
fn math_text_uses_upright_character_widths() {
let font = Cmr10Metrics::default();
let atom = parse_math("\\text{PSNR}");
let MathAtom::Row(atoms) = &atom else {
panic!("expected a row");
};
let MathAtom::Text(text) = &atoms[0] else {
panic!("expected a text atom");
};
assert_eq!(text, "PSNR");
let text_box = layout_math(&atom, &font);
let symbol = layout_math(&parse_math("P"), &font);
assert!(text_box.width > symbol.width);
assert!(text_box.height > 0);
}
#[test]
fn middle_delimiter_adds_a_symbol() {
let font = Cmr10Metrics::default();
+2
View File
@@ -110,6 +110,8 @@ a single cost function.
- `MathAtom::Accent { accent, base }` parses `\hat`, `\widehat`,
`\tilde`, `\widetilde`, `\bar`, `\overline` and `\vec`; it adds
accent height without changing the base width.
- `MathAtom::Text(String)` parses `\text{...}` and `\mathrm{...}`;
widths use upright CMR glyphs and spaces use the font space width.
- `MathAtom::Delimited { left, right, body }` and `\left...\right`
parsing grow the delimiter box with the body height/depth.
- `MathClass` and TeX's 0/3/4/5mu inter-atom table add spacing for