1use super::*;
4
5#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
7pub struct LaTeX;
8impl Format for LaTeX {
9 fn mime() -> mime::Mime {
10 return "text/x-latex".parse().unwrap();
11 }
12 fn this_format() -> Self {
13 LaTeX
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!(LaTeX);
41display_floats_as!(LaTeX, r"$\times10^{", "}$", 3, Some("$10^{"));
42
43#[test]
44fn escaping() {
45 assert_eq!(&format_as!(LaTeX, ("&")).into_string(), r"\&");
46 assert_eq!(
47 &format_as!(LaTeX, ("hello &>this is cool")).into_string(),
48 r"hello \&>this is cool"
49 );
50 assert_eq!(
51 &format_as!(LaTeX, ("hello &>this is 'cool")).into_string(),
52 r"hello \&>this is 'cool"
53 );
54}
55#[test]
56fn floats() {
57 assert_eq!(&format_as!(LaTeX, 3.0).into_string(), "3");
58 assert_eq!(&format_as!(LaTeX, 3e5).into_string(), r"3$\times10^{5}$");
59 assert_eq!(&format_as!(LaTeX, 3e4).into_string(), "30000");
60}