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