Skip to content

Commit f1bcfbd

Browse files
committed
render latex math to mathml
1 parent 4a4414b commit f1bcfbd

4 files changed

Lines changed: 43 additions & 0 deletions

File tree

‎Cargo.lock‎

Lines changed: 10 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,4 @@ toml = "0.8.19"
2525
syntect = { version = "5", default-features = false, features = [
2626
"default-fancy",
2727
] }
28+
pulldown-latex = "0.7"

‎src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@ fn read_source_files(current: &Path, prefix: &Path) -> Result<Vec<RawFile>> {
187187
fn to_html(markdown: &str, highlighter: &markdown::Highlighter) -> Result<String> {
188188
let events = markdown::to_events(markdown)?;
189189
let events = highlighter.highlight_code(events)?;
190+
let events = markdown::render_math(events)?;
190191
let mut content = String::new();
191192
pulldown_cmark::html::push_html(&mut content, events.into_iter());
192193
Ok(content)

‎src/markdown.rs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,3 +254,34 @@ impl Highlighter {
254254
Ok(new_events)
255255
}
256256
}
257+
258+
pub fn render_math(events: Vec<Event>) -> Result<Vec<Event>> {
259+
use pulldown_latex::{config::DisplayMode, Parser, RenderConfig, Storage};
260+
261+
let mut storage = Storage::new();
262+
263+
let mut latex_as_html = |latex_math: &str, display_mode| {
264+
storage.reset();
265+
let parser = Parser::new(latex_math, &storage);
266+
let config = RenderConfig {
267+
display_mode,
268+
..Default::default()
269+
};
270+
let mut mathml = String::new();
271+
pulldown_latex::push_mathml(&mut mathml, parser, config)?;
272+
Ok::<String, anyhow::Error>(mathml)
273+
};
274+
275+
events
276+
.into_iter()
277+
.map(|e| match e {
278+
Event::InlineMath(m) => Ok(Event::InlineHtml(
279+
latex_as_html(&m, DisplayMode::Inline)?.into(),
280+
)),
281+
Event::DisplayMath(m) => Ok(Event::InlineHtml(
282+
latex_as_html(&m, DisplayMode::Block)?.into(),
283+
)),
284+
e => Ok(e),
285+
})
286+
.collect::<Result<_>>()
287+
}

0 commit comments

Comments
 (0)