Skip to main content

Module math

Module math 

Source
Expand description

Server-side LaTeX → MathML and Mermaid diagram passthrough.

Two post-processing steps that run against the HTML emitted by the Markdown pipeline:

  • convert_math (gated behind the math feature) walks the text of an HTML fragment, finds $$..$$ and $..$ spans, and replaces each one with a <math>...</math> element rendered via pulldown-latex. No client-side JavaScript is required — browsers render MathML natively.

  • rewrite_mermaid_blocks rewrites <pre><code class="language-mermaid">…</code></pre> blocks (the form comrak/mdx-gen emits for \u{60}\u{60}\u{60}mermaid fenced code) into <pre class="mermaid">…</pre> so the standard client-side mermaid.js bundle picks them up.

Both functions take a &str and return a fresh String. Each has a fast-path: if the input contains no $ (math) or no language-mermaid substring (diagrams), the input is returned unchanged with no allocation beyond the borrow check.

§Examples

Mermaid passthrough is always available:

use html_generator::math::rewrite_mermaid_blocks;

let html = r#"<pre><code class="language-mermaid">graph TD; A-->B</code></pre>"#;
let out = rewrite_mermaid_blocks(html);
// The block body is preserved verbatim — only the wrapping tag
// changes from `<pre><code class="language-mermaid">` to
// `<pre class="mermaid">` so client-side mermaid.js picks it up.
assert!(out.contains(r#"<pre class="mermaid">graph TD; A-->B</pre>"#));

Math is feature-gated. With the default math feature on:

use html_generator::math::convert_math;

let html = "<p>Energy: $$E = mc^2$$.</p>";
let out = convert_math(html);
assert!(out.contains("<math"));
assert!(out.contains("display=\"block\""));

§Error reporting

Both functions are infallible. pulldown-latex reports parse errors inline via a <merror style="border-color:#b22222">…</merror> element rather than failing the whole render — invalid LaTeX shows up visibly in the page, not as a 500 from the build, which is the right UX for content tooling.

Functions§

convert_math
Convert LaTeX math spans inside an HTML fragment to MathML.
rewrite_mermaid_blocks
Rewrite mermaid fenced blocks for client-side rendering.