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
#![forbid(unsafe_code)]
#![deny(missing_docs)]
pub mod error;
pub use error::{Error, Result};
pub mod opts;
pub use opts::{Opts, OptsBuilder, OutputType};
mod js_engine;
use js_engine::{Engine, JsEngine, JsValue};
pub const KATEX_VERSION: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/KATEX-VERSION"));
const JS_SRC: &str = concat!(
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/js/node-hack.js")),
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/vendor/katex.min.js")),
include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/vendor/contrib/mhchem.min.js"
)),
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/js/post-node-hack.js")),
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/js/entry.js")),
);
thread_local! {
static KATEX: Result<Engine> = init_katex();
}
fn init_katex<E>() -> Result<E>
where
E: JsEngine,
{
let engine = E::new()?;
engine.eval(JS_SRC)?;
Ok(engine)
}
#[inline]
fn render_inner<E>(engine: &E, input: &str, opts: impl AsRef<Opts>) -> Result<String>
where
E: JsEngine,
{
use core::iter;
let input = engine.create_string_value(input.to_owned())?;
let opts = opts.as_ref().to_js_value(engine)?;
let args = iter::once(input).chain(iter::once(opts));
let result = engine.call_function("katexRenderToString", args)?;
result.into_string()
}
pub fn render_with_opts(input: &str, opts: impl AsRef<Opts>) -> Result<String> {
KATEX.with(|engine| {
engine
.as_ref()
.map_err(|e| e.clone())
.and_then(|engine| render_inner(engine, input, opts))
})
}
#[inline]
pub fn render(input: &str) -> Result<String> {
render_with_opts(input, Opts::default())
}
#[cfg(test)]
mod tests;