diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index f3ebaaa..bd4d58e 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -14,6 +14,7 @@ pub enum MathAtom { radicand: Box, degree: Option>, }, + 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(); diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 1dc2e99..8958747 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -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