1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#![deny(missing_docs)]

//! This crate turns (a subset of) latex into html, with syntax errors
//! reported using span elements.

/// A version of html_string suitable for export to C and python.
#[no_mangle]
pub extern "C" fn convert_html(s: *const std::os::raw::c_char) -> *const std::os::raw::c_char {
    if s.is_null() {
        return std::ptr::null();
    }
    let c_str = unsafe { std::ffi::CStr::from_ptr(s) };
    if let Ok(my_str) = c_str.to_str() {
        let output = html_string(my_str);
        std::ffi::CString::new(output).unwrap().into_raw()
    } else {
        std::ptr::null()
    }
}


/// Convert some LaTeX into an HTML `String`.
pub fn html_string(latex: &str) -> String {
    let mut s = String::with_capacity(latex.len());
    html(&mut s, latex).unwrap();
    s
}

/// Convert some LaTeX into HTML, and send the results to a `std::fmt::Write`.
pub fn html(fmt: &mut impl std::fmt::Write, mut latex: &str) -> Result<(),std::fmt::Error> {
    let math_environs = &["{equation}", "{align}"];
    loop {
        if latex.len() == 0 {
            return Ok(());
        }
        if let Some(i) = latex.find(|c| c == '\\' || c == '{' || c == '$') {
            fmt.write_str(&latex[..i])?;
            latex = &latex[i..];
            let c = latex.chars().next().unwrap();
            if c == '\\' {
                let name = macro_name(latex);
                latex = &latex[name.len()..];
                match name {
                    r"\emph" => {
                        let arg = argument(latex);
                        latex = &latex[arg.len()..];
                        if arg == "{" {
                            fmt.write_str(r#"<span class="error">\emph{</span>"#)?;
                        } else {
                            fmt.write_str("<em>")?;
                            html(fmt, arg)?;
                            fmt.write_str("</em>")?;
                        }
                    }
                    r"\it" => {
                        latex = finish_standalone_macro(latex);
                        fmt.write_str("<i>")?;
                        html(fmt, latex)?;
                        return fmt.write_str("</i>");
                    }
                    r"\ " => {
                        fmt.write_str(" ")?;
                    }
                    r"\%" => {
                        fmt.write_str("%")?;
                    }
                    r"\bf" => {
                        latex = finish_standalone_macro(latex);
                        fmt.write_str("<b>")?;
                        html(fmt, latex)?;
                        return fmt.write_str("</b>");
                    }
                    r"\sc" => {
                        latex = finish_standalone_macro(latex);
                        fmt.write_str(r#"<font style="font-variant: small-caps">"#)?;
                        html(fmt, latex)?;
                        return fmt.write_str("</font>");
                    }
                    r"\begin" => {
                        // We are looking at an environment...
                        let name = env_name(latex);
                        latex = &latex[name.len()..];
                        if name.chars().last() != Some('}') {
                            write!(fmt,r#"<span class="error">\begin{}</span>"#, name)?;
                        } else if math_environs.contains(&name) {
                            let env = end_env(name, latex);
                            latex = &latex[env.len()..];
                            if env == "" {
                                write!(fmt,r#"<span class="error">\begin{}</span>"#, name)?;
                            } else {
                                write!(fmt,r#"\begin{}{}"#, name, env)?;
                            }
                        }
                    }
                    _ => {
                        write!(fmt, r#"<span class="error">{}</span>"#, name)?;
                    }
                }
            } else if c == '$' {
                if let Some(i) = latex[1..].find('$') {
                    fmt.write_str(&latex[..i+2])?;
                    latex = &latex[i+2..];
                } else {
                    fmt.write_str(r#"<span class="error">$</span>"#)?;
                    latex = &latex[1..];
                }
            } else {
                let arg = argument(latex);
                latex = &latex[arg.len()..];
                if arg == "{" {
                    fmt.write_str(r#"<span class="error">{</span>"#)?;
                } else {
                    html(fmt, &arg[1..arg.len()-1])?;
                }
            }
        } else {
            return fmt.write_str(latex);
        }
    }
}

fn finish_standalone_macro(latex: &str) -> &str {
    if latex.len() == 0 {
        ""
    } else if latex.chars().next().unwrap() == ' ' {
        &latex[1..]
    } else {
        latex
    }
}

fn macro_name(latex: &str) -> &str {
    if let Some(i) = latex[1..].find(|c: char| !c.is_alphabetic()) {
        if i == 0 {
            &latex[..2]
        } else {
            &latex[..i+1]
        }
    } else {
        latex
    }
}

#[test]
fn test_macro_name() {
    assert_eq!(macro_name(r"\emph{foo"), r"\emph");
    assert_eq!(macro_name(r"\\ extra"), r"\\");
    assert_eq!(macro_name(r"\% extra"), r"\%");
}

fn env_name(latex: &str) -> &str {
    if let Some(i) = latex.find(|c: char| c == '}') {
        &latex[..i+1]
    } else if let Some(i) = latex.find(|c: char| c != '{' && !c.is_alphabetic()) {
        &latex[..i+1]
    } else {
        latex
    }
}

fn end_env<'a>(name: &str, latex: &'a str) -> &'a str {
    let end = format!(r"\end{}", name);
    if let Some(i) = latex.find(&end) {
        &latex[..i + end.len()]
    } else {
        ""
    }
}

fn argument(latex: &str) -> &str {
    if latex.len() == 0 {
        ""
    } else if latex.chars().next().unwrap().is_digit(10) {
        &latex[..1]
    } else if latex.chars().next().unwrap() == '{' {
        let mut n = 0;
        let mut arg = String::from("{");
        for c in latex[1..].chars() {
            arg.push(c);
            if c == '{' {
                n += 1
            } else if c == '}' {
                if n == 0 {
                    return &latex[..arg.len()]
                }
                n -= 1
            }
        }
        // we must have unbalanced parentheses
        &latex[..1]
    } else {
        &latex[..1]
    }
}

#[test]
fn test_argument() {
    assert_eq!(argument(r"{foo"), r"{");
    assert_eq!(argument(r"{foo}  "), r"{foo}");
}

#[test]
fn hello_world() {
    assert_eq!("hello world", &html_string("hello world"));
}
#[test]
fn emph_hello() {
    assert_eq!("<em>hello</em>", &html_string(r"\emph{hello}"));
}
#[test]
fn hello_it() {
    assert_eq!("hello good <i>world</i>", &html_string(r"hello {good \it world}"));
}
#[test]
fn inline_math() {
    assert_eq!(r"hello good $\cos^2x$ math", &html_string(r"hello good $\cos^2x$ math"));
}
#[test]
fn escape_space() {
    assert_eq!(r"hello<i> world</i>", &html_string(r"hello\it\ world"));
}
#[test]
fn escape_percent() {
    assert_eq!(r"50% full", &html_string(r"50\% full"));
}
#[test]
fn equation() {
    assert_eq!(r"
\begin{equation}
 y = x^2
\end{equation}
some more math
",
               &html_string(r"
\begin{equation}
 y = x^2
\end{equation}
some more math
"));
}