display_as/
mathlatex.rs

1//! Format as LaTeX math mode
2
3use super::*;
4
5/// Format as LaTeX math mode.
6#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
7pub struct Math;
8impl Format for Math {
9    fn mime() -> mime::Mime {
10        return "text/x-latex".parse().unwrap();
11    }
12    fn this_format() -> Self {
13        Math
14    }
15    fn escape(f: &mut Formatter, mut s: &str) -> Result<(), Error> {
16        let badstuff = "&{}#%\\~$_^";
17        while let Some(idx) = s.find(|c| badstuff.contains(c)) {
18            let (first, rest) = s.split_at(idx);
19            let (badchar, tail) = rest.split_at(1);
20            f.write_str(first)?;
21            f.write_str(match badchar {
22                "&" => r"\&",
23                "{" => r"\{",
24                "}" => r"\}",
25                "#" => r"\#",
26                "%" => r"\%",
27                "\\" => r"\textbackslash{}",
28                "~" => r"\textasciitilde{}",
29                "$" => r"\$",
30                "_" => r"\_",
31                "^" => r"\^",
32                _ => unreachable!(),
33            })?;
34            s = tail;
35        }
36        f.write_str(s)
37    }
38}
39
40display_integers_as!(Math);
41display_floats_as!(Math, r"\times10^{", "}", 3, Some("10^{"));
42
43#[test]
44fn escaping() {
45    assert_eq!(&format_as!(Math, ("&")).into_string(), r"\&");
46    assert_eq!(
47        &format_as!(Math, ("hello &>this is cool")).into_string(),
48        r"hello \&>this is cool"
49    );
50    assert_eq!(
51        &format_as!(Math, ("hello &>this is 'cool")).into_string(),
52        r"hello \&>this is 'cool"
53    );
54}
55#[test]
56fn floats() {
57    assert_eq!(&format_as!(Math, 3.0).into_string(), "3");
58    assert_eq!(&format_as!(Math, 3e5).into_string(), r"3\times10^{5}");
59    assert_eq!(&format_as!(Math, 1e5).into_string(), r"10^{5}");
60    assert_eq!(&format_as!(Math, 3e4).into_string(), "30000");
61}