Skip to main content

crisol_plot_core/
math_text.rs

1//! A small LaTeX subset for titles, labels, legends, and annotations.
2//!
3//! The renderer converts commands and scripts to Unicode text, so the same string is
4//! measured, painted, and exported without a math layout engine:
5//! `\alpha`, `^{2}`, `_{i}`, `\frac{a}{b}`, `\sqrt{x}`, `\pm`, `\times`, `\cdot`,
6//! `\infty`, `\degree`, and units.
7
8/// Convert a LaTeX subset to Unicode text.
9///
10/// ```
11/// # use crisol_plot_core::math_text::to_unicode_math;
12/// assert_eq!(to_unicode_math(r"$\alpha_{i}^{2}$"), "αᵢ²");
13/// assert_eq!(to_unicode_math(r"\frac{V}{s}"), "V/s");
14/// ```
15pub fn to_unicode_math(input: &str) -> String {
16    render(input, 0)
17}
18
19/// Deepest `{...}`/command nesting rendered; the renderer recurses.
20const MAX_DEPTH: usize = 32;
21
22fn render(input: &str, depth: usize) -> String {
23    if depth > MAX_DEPTH {
24        return String::new();
25    }
26    let mut out = String::with_capacity(input.len());
27    let mut chars = input.chars().peekable();
28    while let Some(character) = chars.next() {
29        match character {
30            '$' => {}
31            '\\' => {
32                let mut command = String::new();
33                while let Some(next) = chars.peek().copied() {
34                    if next.is_ascii_alphabetic() {
35                        command.push(next);
36                        chars.next();
37                    } else {
38                        break;
39                    }
40                }
41                if command.is_empty() {
42                    if let Some(next) = chars.next() {
43                        out.push(next);
44                    }
45                    continue;
46                }
47                match command.as_str() {
48                    "alpha" => out.push('α'),
49                    "beta" => out.push('β'),
50                    "gamma" => out.push('γ'),
51                    "delta" => out.push('δ'),
52                    "epsilon" => out.push('ε'),
53                    "zeta" => out.push('ζ'),
54                    "eta" => out.push('η'),
55                    "theta" => out.push('θ'),
56                    "iota" => out.push('ι'),
57                    "kappa" => out.push('κ'),
58                    "lambda" => out.push('λ'),
59                    "mu" => out.push('μ'),
60                    "nu" => out.push('ν'),
61                    "xi" => out.push('ξ'),
62                    "pi" => out.push('π'),
63                    "rho" => out.push('ρ'),
64                    "sigma" => out.push('σ'),
65                    "tau" => out.push('τ'),
66                    "upsilon" => out.push('υ'),
67                    "phi" => out.push('φ'),
68                    "chi" => out.push('χ'),
69                    "psi" => out.push('ψ'),
70                    "omega" => out.push('ω'),
71                    "Gamma" => out.push('Γ'),
72                    "Delta" => out.push('Δ'),
73                    "Theta" => out.push('Θ'),
74                    "Lambda" => out.push('Λ'),
75                    "Xi" => out.push('Ξ'),
76                    "Pi" => out.push('Π'),
77                    "Sigma" => out.push('Σ'),
78                    "Phi" => out.push('Φ'),
79                    "Psi" => out.push('Ψ'),
80                    "Omega" => out.push('Ω'),
81                    "pm" => out.push('±'),
82                    "mp" => out.push('∓'),
83                    "times" => out.push('×'),
84                    "cdot" => out.push('·'),
85                    "infty" => out.push('∞'),
86                    "degree" => out.push('°'),
87                    "sqrt" => {
88                        let group = group(&mut chars, depth + 1);
89                        out.push('√');
90                        out.push_str(&group);
91                    }
92                    "frac" => {
93                        let numerator = group(&mut chars, depth + 1);
94                        let denominator = group(&mut chars, depth + 1);
95                        out.push_str(&numerator);
96                        out.push('/');
97                        out.push_str(&denominator);
98                    }
99                    "text" | "mathrm" | "operatorname" => out.push_str(&group(&mut chars, depth + 1)),
100                    "si" => out.push_str(&group(&mut chars, depth + 1)),
101                    _ => out.push_str(&command),
102                }
103            }
104            '^' => out.push_str(&script(&mut chars, true, depth + 1)),
105            '_' => out.push_str(&script(&mut chars, false, depth + 1)),
106            '{' | '}' => {}
107            other => out.push(other),
108        }
109    }
110    out
111}
112
113fn group(chars: &mut std::iter::Peekable<std::str::Chars<'_>>, level: usize) -> String {
114    while chars.peek().is_some_and(|character| character.is_whitespace()) {
115        chars.next();
116    }
117    if chars.peek() == Some(&'{') {
118        chars.next();
119        let mut value = String::new();
120        let mut depth = 1;
121        for character in chars.by_ref() {
122            match character {
123                '{' => {
124                    depth += 1;
125                    value.push(character);
126                }
127                '}' => {
128                    depth -= 1;
129                    if depth == 0 {
130                        break;
131                    }
132                    value.push(character);
133                }
134                _ => value.push(character),
135            }
136        }
137        render(&value, level)
138    } else {
139        chars.next().map_or_else(String::new, |character| character.to_string())
140    }
141}
142
143fn script(chars: &mut std::iter::Peekable<std::str::Chars<'_>>, superscript: bool, depth: usize) -> String {
144    let raw = group(chars, depth);
145    raw.chars()
146        .map(|character| {
147            let map: &[(char, char)] = if superscript { &SUPERSCRIPT } else { &SUBSCRIPT };
148            map.iter()
149                .find(|(plain, _)| *plain == character)
150                .map_or(character, |(_, mapped)| *mapped)
151        })
152        .collect()
153}
154
155const SUPERSCRIPT: [(char, char); 36] = [
156    ('0', '⁰'),
157    ('1', '¹'),
158    ('2', '²'),
159    ('3', '³'),
160    ('4', '⁴'),
161    ('5', '⁵'),
162    ('6', '⁶'),
163    ('7', '⁷'),
164    ('8', '⁸'),
165    ('9', '⁹'),
166    ('+', '⁺'),
167    ('-', '⁻'),
168    ('=', '⁼'),
169    ('(', '⁽'),
170    (')', '⁾'),
171    ('a', 'ᵃ'),
172    ('b', 'ᵇ'),
173    ('c', 'ᶜ'),
174    ('d', 'ᵈ'),
175    ('e', 'ᵉ'),
176    ('f', 'ᶠ'),
177    ('g', 'ᵍ'),
178    ('h', 'ʰ'),
179    ('i', 'ⁱ'),
180    ('j', 'ʲ'),
181    ('k', 'ᵏ'),
182    ('l', 'ˡ'),
183    ('m', 'ᵐ'),
184    ('n', 'ⁿ'),
185    ('o', 'ᵒ'),
186    ('p', 'ᵖ'),
187    ('r', 'ʳ'),
188    ('s', 'ˢ'),
189    ('t', 'ᵗ'),
190    ('u', 'ᵘ'),
191    ('v', 'ᵛ'),
192];
193const SUBSCRIPT: [(char, char); 26] = [
194    ('0', '₀'),
195    ('1', '₁'),
196    ('2', '₂'),
197    ('3', '₃'),
198    ('4', '₄'),
199    ('5', '₅'),
200    ('6', '₆'),
201    ('7', '₇'),
202    ('8', '₈'),
203    ('9', '₉'),
204    ('+', '₊'),
205    ('-', '₋'),
206    ('=', '₌'),
207    ('(', '₍'),
208    (')', '₎'),
209    ('a', 'ₐ'),
210    ('e', 'ₑ'),
211    ('h', 'ₕ'),
212    ('i', 'ᵢ'),
213    ('j', 'ⱼ'),
214    ('k', 'ₖ'),
215    ('l', 'ₗ'),
216    ('m', 'ₘ'),
217    ('n', 'ₙ'),
218    ('o', 'ₒ'),
219    ('p', 'ₚ'),
220];
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn greek_scripts_and_fractions() {
228        assert_eq!(to_unicode_math(r"$\alpha_{i}^{2}$"), "αᵢ²");
229        assert_eq!(to_unicode_math(r"\frac{V}{s}"), "V/s");
230        assert_eq!(to_unicode_math(r"\sqrt{x}"), "√x");
231        assert_eq!(to_unicode_math(r"25\pm3\degree"), "25±3°");
232        assert_eq!(to_unicode_math(r"a \cdot b \times c"), "a · b × c");
233    }
234}
235
236#[cfg(test)]
237mod depth_tests {
238    #[test]
239    fn deeply_nested_math_does_not_overflow_the_stack() {
240        let input = format!("{}x{}", "\\frac{".repeat(10_000), "}{y}".repeat(10_000));
241        let output = super::to_unicode_math(&input);
242        assert!(output.len() < input.len());
243        let braces = format!("{}{}", "{".repeat(100_000), "}".repeat(100_000));
244        assert!(super::to_unicode_math(&braces).is_empty());
245    }
246}