mathpix-markdown-it

repository·master·Indexed 20 days ago

https://github.com/mathpix/mathpix-markdown-it

An open-source TypeScript implementation of the Mathpix Markdown specification, a STEM-focused superset of Markdown. It enables the rendering of complex mathematical equations, chemistry diagrams, and scientific tables in web applications using MathJax v3 for SVG math rendering and markdown-it for standard Markdown parsing. The library provides React components (MathpixMarkdown, MathpixLoader) and the MathpixMarkdownModel for manual rendering, HTML conversion, and styling.

Tokens
74.8K
Snippets
234
Records
302
Agent score
69%

What's inside mathpix-markdown-it

  1. What is mathpix-markdown-it?

    master

    The mathpix-markdown-it library is an open-source TypeScript implementation of the Mathpix Markdown specification. It is built upon two core libraries:

    • MathJax v3: Used for rendering mathematical equations as SVGs.
    • markdown-it: Used for the underlying standard Markdown parsing.
  2. What is Mathpix Markdown?

    master

    Mathpix Markdown (MMD) is a superset of Markdown designed for the STEM community. It extends standard Markdown with syntax for advanced equations, complex tables, chemistry diagrams, and academic publication elements (like abstracts and author lists). It is backward compatible with standard Markdown.

    Key features include:

    • Equation Support: LaTeX-based math via MathJax, including numbering and referencing.
    • Tables: LaTeX tabular syntax for complex and nested scientific tables.
    • Chemistry: Support for SMILES markup for chemistry diagrams.
    • Academic Elements: Support for abstracts, author lists, linkable sections, and figure referencing.
    • Advanced Figures: Enhanced image syntax for controlling width, height, and alignment.
  3. Explore available icon types in mathpix-markdown-it

    master

    The mathpix-markdown-it ecosystem supports several categories of icons that can be used within the markdown rendering process. These include:

    • Unicode icons: Standard Unicode character-based icons.
    • Squared icons: Icons presented within squared containers.
    • Emoji icons: Standard emoji characters.
    • fa-icons: Font Awesome icons.
    • Color icons: Specialized color-based icon sets.

    For a full visual reference of the specific characters and names available, consult the project's icon documentation tables.

  4. Use non-numbered block math in Mathpix Markdown

    master

    For standalone mathematical equations that do not require numbering, use one of the following delimiters:

    • $$...$$
    • \[...\]
    • \begin{equation*}...\end{equation*}
    • \begin{align*}...\end{align*}
    $$
    x = \frac { - b \pm \sqrt { b ^ { 2 } - 4 a c } } { 2 a }
    $$
    
    \begin{equation*}
    l ( \theta ) = \sum _ { i = 1 } ^ { m } \log p ( x , \theta )
    \end{equation*}
  5. Understand the performance characteristics of footnote rules

    master

    The parser uses a per-state position cache and per-line token guards to optimize footnote processing (\footnote, \footnotetext, and \blfootnotetext).

    Performance Notes:

    • Optimization: The parser performs an $O(|src|)$ sweep once per parse to cache positions. Subsequent checks for footnote keywords at block starts are $O(1)$.
    • Code Fencing: The position cache does not exclude code-fenced regions. If \footnote literals exist inside fenced code blocks, the parser still performs a scan, though the block-rule will eventually bail on those matches to ensure output correctness.
    • Pathological Cases: Significant performance degradation (quadratic blow-up) can occur in very large documents (>1 MB) containing many long tabular blocks that lack empty-line separators between them.
  6. Use advanced LaTeX math environments (split, gather)

    master

    Mathpix Markdown supports specialized LaTeX environments for complex equation layouts:

    • \begin{split}...\end{split}: Used to split a single equation into multiple lines. Use & for alignment points and \\ for new lines. If you need the split equation to be numbered, wrap it in a \begin{equation}...\end{equation} block.
    • \begin{gather}...\end{gather}: Displays a set of consecutive equations that do not require specific alignment.
    • \begin{gather*}...\end{gather*}: Same as gather, but without equation numbering.
    \begin{split}
    a& =b+c-d\\
    & \quad +e-f\\
    & =g+h\\
    & =i
    \end{split}
    
    \begin{gather}
    a_1=b_1+c_1\\
    a_2=b_2+c_2-d_2+e_2
    \end{gather}
  7. Use vertical-align brackets in LaTeX tabular syntax

    master

    You can control the vertical alignment of cells within a \begin{tabular} block by adding an optional positional bracket [t], [c], or [b] immediately after the command. This bracket sets the default vertical alignment for all l, c, r, and S columns in that table.

    Mapping:

    • \begin{tabular}[t]{...}: Sets default vAlign to 'top'.
    • \begin{tabular}[c]{...}: Sets default vAlign to 'middle'.
    • \begin{tabular}[b]{...}: Sets default vAlign to 'bottom'.

    Precedence (Highest to Lowest):

    1. Per-column specifiers (m, p, b).
    2. Explicit bracket ([t], [c], [b]).
    3. The defaultCellVerticalAlign option.
    4. Browser default (middle).

    Cell-level Inference: If a cell contains a nested \begin{tabular}[pos], the outer <td> will inherit that vertical alignment. This allows nested tables to drive the alignment of the parent cell.

    % Top-aligned columns
    \begin{tabular}[t]{|l|l|l|}
      Cell 1 & Cell 2 & Cell 3 \\
    \end{tabular}
    
    % Bottom-aligned columns
    \begin{tabular}[b]{|l|l|l|}
      Cell 1 & Cell 2 & Cell 3 \\
    \end{tabular}
  8. How literal dollar signs are rendered in mathescape listings

    master

    When using [mathescape=true] within an lstlisting environment, you can render literal dollar signs ($) by escaping them with backslashes. The parser follows a specific rule for dropping backslashes to ensure the $ is treated as text rather than a math delimiter:

    • \$ $\rightarrow$ $ (one backslash dropped, results in a literal dollar)
    • \\$ $\rightarrow$ \$ (two backslashes dropped, results in a single backslash and a literal dollar)
    • \\\$ $\rightarrow$ \\$ (three backslashes dropped, results in two backslashes and a literal dollar)

    Important Notes:

    • Bare $: A single $ without preceding backslashes still toggles math mode (e.g., $x$ renders as math).
    • Scope: This behavior applies only to listings where mathescape=true. In plain lstlisting environments or standard code fences (```), the $ is treated as verbatim text and is not affected by these escaping rules.
    • Other Delimiters: Handling for \( / \[ / \\( / \\[ remains unchanged.
    /* Example of desired behavior in [mathescape=true] listings */
    \$x\$    // Renders as: $x$
    \\$conf_a\\$ // Renders as: \$conf_a\$
    \\\$    // Renders as: \$
    $x$      // Renders as: math mode x
  9. Enable math accessibility with speech-rule-engine (SRE)

    master

    By default, math output is not accessible to screen readers. To enable accessibility, you must provide a speech-rule-engine (SRE) instance in the accessibility.sre option. This adds assistive-mml to the mjx-container, allowing screen readers to interpret math (e.g., reading $x^y$ as "x Superscript y").

    Browser Usage (Synchronous)

    Import loadSre from mathpix-markdown-it/lib/sre/sre-browser and pass its result to the options object.

    Node.js Usage (Asynchronous)

    Import loadSreAsync from mathpix-markdown-it/lib/sre/sre-node and await its result before calling markdownToHTML.

    // Browser Example
    import { MathpixMarkdownModel } from "mathpix-markdown-it";
    import { loadSre } from "mathpix-markdown-it/lib/sre/sre-browser";
    
    const html = MathpixMarkdownModel.markdownToHTML("$x^y$", {
        accessibility: {
          sre: loadSre()
        },
    });
    
    // Node.js Example
    const { MathpixMarkdownModel } = require('mathpix-markdown-it');
    const { loadSreAsync } = require('mathpix-markdown-it/lib/sre/sre-node');
    
    (async() => {
      const html = MathpixMarkdownModel.markdownToHTML("$x^y$", {
        accessibility: {
          sre: await loadSreAsync()
        },
      });
    })();
  10. How the two-hook cleanup scheme works

    master

    The library uses a core-ruler mechanism to manage the lifecycle of parse-only data (like tabular caches and math dedup caches) to prevent them from being retained during the render phase.

    1. reset_tabular_state: A hook registered before('normalize') that clears module-level tabular state at the start of every md.parse(). This is defensive and ensures a clean slate even if a previous parse failed.
    2. cleanup_tabular_state: A hook pushed to the end of the core pipeline that drops parse-only caches such as subTabular, mathTable, extractedCodeBlocks, diagboxTable, and the column-style intern cache. These are cleared because they are no longer needed once the parse is complete and are not read during the render phase.
  11. How codeText and clipboard copying work for mathescape listings

    master

    For lstlisting environments with mathescape=true, the project maintains a math-aware plain-text version of the content in token.meta.codeText. This ensures that when a user uses the 'copy-to-clipboard' feature or renders a listing inside a table cell, the copied text matches the rendered visual display.

    Data Contract for token.meta.codeText:

    • Literal Un-escaping: Escaped characters (like \$) are stored as their un-escaped literal form ($).
    • Math Preservation: Math fragments use token.inputLatex to preserve original delimiters and any \$ sequences inside the math, while maintaining whitespace and newlines.
    • Fallback: If codeText is not available (as in plain listings), systems fall back to token.content (the raw source).