latex-rust 3.0.2

Pure-Rust LaTeX math renderer. Parse to AST, TeX-faithful layout on exact rationals, emit SVG, PNG, or egui shapes. No JavaScript, no webview, no runtime.
Documentation
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! `MathBox` tree → self-contained SVG 1.1.

use std::collections::HashMap;

use super::outline;
use crate::color::Color;
use crate::dim::Dim;
use crate::error::{Error, FontError};
use crate::font::MathFont;
use crate::layout::{layout_with_em_size_pt, BoxContent, MathBox, MathStyle};
use crate::parser::parse;

/// Options for [`render_svg`].
///
/// # Examples
///
/// ```
/// use latex_rust::{Color, Dim, SvgOptions};
///
/// let mut opt = SvgOptions::new();
/// opt.font_size_pt = Dim::from_i64(12);
/// opt.color = Color::rgb(0, 0, 0);
/// opt.display = false;
/// ```
#[derive(Clone, Debug)]
pub struct SvgOptions {
    /// Em size in points (SVG `width`/`height` use `pt`).
    pub font_size_pt: Dim,
    /// Default glyph fill.
    pub color: Color,
    /// When using [`latex_to_svg`], pick display vs text style.
    pub display: bool,
}

impl Default for SvgOptions {
    fn default() -> Self {
        Self {
            font_size_pt: Dim::from_i64(12),
            color: Color::rgb(0, 0, 0),
            display: false,
        }
    }
}

impl SvgOptions {
    /// 12 pt, black fill, text style.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

/// Parse, lay out, and render `latex` to a self-contained SVG document.
///
/// Glyphs are `<path>` elements from STIX Two Math outlines. Rules are `<rect>`.
///
/// # Arguments
///
/// * `latex` — math source (see [`crate::parse()`]).
/// * `font` — face used for layout and outlines.
/// * `options` — em size, default fill, and display vs text style.
///
/// # Returns
///
/// An SVG 1.1 document string.
///
/// # Errors
///
/// * [`Error::Parse`] — tokenizer or parser rejected `latex`.
/// * [`Error::Font`] — a required glyph is missing.
/// * [`Error::Unsupported`] — construct this renderer will not invent.
///
/// # Examples
///
/// ```
/// use latex_rust::{latex_to_svg, MathFont, SvgOptions};
///
/// let font = MathFont::stix_two_math().unwrap();
/// let svg = latex_to_svg(r"\frac{1}{2}", &font, &SvgOptions::new()).unwrap();
/// assert!(svg.contains("<svg"));
/// ```
pub fn latex_to_svg(latex: &str, font: &MathFont, options: &SvgOptions) -> Result<String, Error> {
    let ast = parse(latex)?;
    let style = if options.display {
        MathStyle::Display
    } else {
        MathStyle::Text
    };
    let tree = layout_with_em_size_pt(&ast, font, style, &options.font_size_pt)?;
    render_svg(&tree, font, options)
}

/// Render a laid-out [`MathBox`] to a self-contained SVG document.
///
/// # Arguments
///
/// * `tree` — box model from [`crate::layout()`].
/// * `font` — face that supplied the glyph ids on `tree`.
/// * `options` — em size and default fill (`display` is ignored here).
///
/// # Returns
///
/// An SVG 1.1 document string.
///
/// # Errors
///
/// * [`Error::Font`] — outline missing for a glyph id on `tree`.
/// * [`Error::Unsupported`] — a box the SVG backend cannot emit.
///
/// # Examples
///
/// ```
/// use latex_rust::{layout, parse, render_svg, MathFont, MathStyle, SvgOptions};
///
/// let ast = parse(r"x").unwrap();
/// let font = MathFont::stix_two_math().unwrap();
/// let tree = layout(&ast, &font, MathStyle::Text).unwrap();
/// let svg = render_svg(&tree, &font, &SvgOptions::new()).unwrap();
/// assert!(svg.contains("<path"));
/// ```
pub fn render_svg(tree: &MathBox, font: &MathFont, options: &SvgOptions) -> Result<String, Error> {
    let em_pt = options.font_size_pt.clone();
    let fu_pt = &em_pt / &Dim::from_i64(i64::from(font.units_per_em()));
    let svg_w = &tree.width * &em_pt;
    let svg_h = (&tree.height + &tree.depth) * &em_pt;
    let baseline = &tree.height * &em_pt;
    let mut cache: HashMap<u16, String> = HashMap::new();
    let mut body = String::new();
    emit(
        tree,
        font,
        &em_pt,
        &fu_pt,
        &Dim::zero(),
        &baseline,
        options.color,
        &mut cache,
        &mut body,
    )?;
    let mut out = String::from(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
    out.push('\n');
    out.push_str(&format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="{}pt" height="{}pt" viewBox="0 0 {} {}">"#,
        svg_w.to_svg_string(),
        svg_h.to_svg_string(),
        svg_w.to_svg_string(),
        svg_h.to_svg_string()
    ));
    out.push('\n');
    out.push_str(r#"<g fill=""#);
    out.push_str(&options.color.css_hex());
    out.push_str("\">\n");
    out.push_str(&body);
    out.push_str("</g>\n</svg>\n");
    Ok(out)
}

enum SvgTask<'a> {
    Draw {
        bx: &'a MathBox,
        origin_x: Dim,
        parent_baseline: Dim,
        fill: Color,
    },
    CloseGroup,
}

#[allow(clippy::too_many_arguments)]
fn emit(
    bx: &MathBox,
    font: &MathFont,
    em_pt: &Dim,
    fu_pt: &Dim,
    origin_x: &Dim,
    parent_baseline: &Dim,
    fill: Color,
    cache: &mut HashMap<u16, String>,
    out: &mut String,
) -> Result<(), Error> {
    let mut stack = vec![SvgTask::Draw {
        bx,
        origin_x: origin_x.clone(),
        parent_baseline: parent_baseline.clone(),
        fill,
    }];
    while let Some(task) = stack.pop() {
        match task {
            SvgTask::CloseGroup => out.push_str("</g>\n"),
            SvgTask::Draw {
                bx,
                origin_x,
                parent_baseline,
                fill,
            } => emit_one(
                bx,
                font,
                em_pt,
                fu_pt,
                &origin_x,
                &parent_baseline,
                fill,
                cache,
                out,
                &mut stack,
            )?,
        }
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn emit_one<'a>(
    bx: &'a MathBox,
    font: &MathFont,
    em_pt: &Dim,
    fu_pt: &Dim,
    origin_x: &Dim,
    parent_baseline: &Dim,
    fill: Color,
    cache: &mut HashMap<u16, String>,
    out: &mut String,
    stack: &mut Vec<SvgTask<'a>>,
) -> Result<(), Error> {
    let baseline = parent_baseline - &(bx.shift.clone() * em_pt);
    match &bx.content {
        BoxContent::Empty | BoxContent::Kern(_) => Ok(()),
        BoxContent::Glyph {
            ch,
            glyph_id,
            scale,
        } => {
            let d = if let Some(s) = cache.get(glyph_id) {
                s.clone()
            } else {
                let s = outline::glyph_path_d(font, *glyph_id)?;
                if s.is_empty() {
                    return Err(FontError::MissingGlyph { ch: *ch }.into());
                }
                cache.insert(*glyph_id, s.clone());
                s
            };
            let k = fu_pt * scale;
            let sx = k.to_svg_string();
            let nsx = (-k).to_svg_string();
            out.push_str(&format!(
                r#"<path d="{d}" transform="translate({} {}) scale({sx} {nsx})"/>"#,
                origin_x.to_svg_string(),
                baseline.to_svg_string(),
            ));
            out.push('\n');
            Ok(())
        }
        BoxContent::Rule => {
            let w = &bx.width * em_pt;
            let h_ink = (&bx.height + &bx.depth) * em_pt;
            if w.is_zero() || h_ink.is_zero() {
                return Ok(());
            }
            let y = &baseline - &(bx.height.clone() * em_pt);
            out.push_str(&format!(
                r#"<rect x="{}" y="{}" width="{}" height="{}"/>"#,
                origin_x.to_svg_string(),
                y.to_svg_string(),
                w.to_svg_string(),
                h_ink.to_svg_string()
            ));
            out.push('\n');
            Ok(())
        }
        BoxContent::HList(kids) => {
            let mut x = origin_x.clone();
            let mut placed = Vec::with_capacity(kids.len());
            for k in kids {
                placed.push((k, x.clone()));
                x = &x + &(k.width.clone() * em_pt);
            }
            for (k, x) in placed.into_iter().rev() {
                stack.push(SvgTask::Draw {
                    bx: k,
                    origin_x: x,
                    parent_baseline: baseline.clone(),
                    fill,
                });
            }
            Ok(())
        }
        BoxContent::VList(kids) => {
            if kids.is_empty() {
                return Ok(());
            }
            let mut placed = Vec::with_capacity(kids.len());
            placed.push((&kids[0], baseline.clone()));
            let mut y_below = kids[0].depth.clone() * em_pt;
            for k in kids.iter().skip(1) {
                let child_base = &baseline + &y_below + &(k.height.clone() * em_pt);
                placed.push((k, child_base));
                y_below = &y_below + &((&k.height + &k.depth) * em_pt);
            }
            for (k, child_base) in placed.into_iter().rev() {
                stack.push(SvgTask::Draw {
                    bx: k,
                    origin_x: origin_x.clone(),
                    parent_baseline: child_base,
                    fill,
                });
            }
            Ok(())
        }
        BoxContent::Overlap(kids) => {
            for k in kids.iter().rev() {
                stack.push(SvgTask::Draw {
                    bx: k,
                    origin_x: origin_x.clone(),
                    parent_baseline: baseline.clone(),
                    fill,
                });
            }
            Ok(())
        }
        BoxContent::Color(c, inner) => {
            out.push_str(&format!(
                r#"<g fill="{hex}" stroke="{hex}">"#,
                hex = c.css_hex()
            ));
            out.push('\n');
            stack.push(SvgTask::CloseGroup);
            stack.push(SvgTask::Draw {
                bx: inner,
                origin_x: origin_x.clone(),
                parent_baseline: baseline,
                fill: *c,
            });
            Ok(())
        }
        BoxContent::BackColor(c, inner) => {
            let w = &bx.width * em_pt;
            let h_ink = (&bx.height + &bx.depth) * em_pt;
            let y = &baseline - &(bx.height.clone() * em_pt);
            out.push_str(&format!(
                r#"<rect x="{}" y="{}" width="{}" height="{}" fill="{}"/>"#,
                origin_x.to_svg_string(),
                y.to_svg_string(),
                w.to_svg_string(),
                h_ink.to_svg_string(),
                c.css_hex()
            ));
            out.push('\n');
            stack.push(SvgTask::Draw {
                bx: inner,
                origin_x: origin_x.clone(),
                parent_baseline: baseline,
                fill,
            });
            Ok(())
        }
        BoxContent::Line {
            x1,
            y1,
            x2,
            y2,
            thickness,
        } => {
            let x1p = origin_x + &(x1.clone() * em_pt);
            let y1p = &baseline - &(y1.clone() * em_pt);
            let x2p = origin_x + &(x2.clone() * em_pt);
            let y2p = &baseline - &(y2.clone() * em_pt);
            let sw = thickness.clone() * em_pt;
            out.push_str(&format!(
                r#"<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="{}" stroke-width="{}"/>"#,
                x1p.to_svg_string(),
                y1p.to_svg_string(),
                x2p.to_svg_string(),
                y2p.to_svg_string(),
                fill.css_hex(),
                sw.to_svg_string(),
            ));
            out.push('\n');
            Ok(())
        }
        BoxContent::Frame {
            thickness,
            stroke,
            inner,
        } => {
            let w = &bx.width * em_pt;
            let h_ink = (&bx.height + &bx.depth) * em_pt;
            let t = thickness.clone() * em_pt;
            let half = &t / &Dim::from_i64(2);
            let x = origin_x + &half;
            let y = &(&baseline - &(bx.height.clone() * em_pt)) + &half;
            let rw = (&w - &t).max(&Dim::zero());
            let rh = (&h_ink - &t).max(&Dim::zero());
            let stroke_css = stroke.unwrap_or(fill).css_hex();
            if !rw.is_zero() && !rh.is_zero() {
                out.push_str(&format!(
                    r#"<rect x="{}" y="{}" width="{}" height="{}" fill="none" stroke="{}" stroke-width="{}"/>"#,
                    x.to_svg_string(),
                    y.to_svg_string(),
                    rw.to_svg_string(),
                    rh.to_svg_string(),
                    stroke_css,
                    t.to_svg_string(),
                ));
                out.push('\n');
            }
            stack.push(SvgTask::Draw {
                bx: inner,
                origin_x: origin_x.clone(),
                parent_baseline: baseline,
                fill,
            });
            Ok(())
        }
    }
}