math-core 0.9.0


pip install math-core

  Latest version

Released: Oct 12, 2026

Project Links

Meta
Author: Thomas MK
Requires Python: >=3.10

Classifiers

Programming Language
  • Rust
  • Python :: Implementation :: CPython

License
  • OSI Approved :: MIT License

math-core

A Python library for converting LaTeX math expressions to MathML Core.

Overview

math-core converts LaTeX mathematical expressions into MathML Core, a streamlined subset of MathML that is supported by all major web browsers. It lets you render mathematical content on the web without requiring JavaScript libraries or polyfills.

Features

  • Convert LaTeX math expressions to MathML Core
  • Support for both inline and display (block) math
  • Define custom LaTeX macros for extended functionality
  • Global and local counter for numbered equations
  • Pretty-printing option for readable MathML output
  • Comprehensive error handling with descriptive error messages

Installation

pip install math-core

Quick Start

from math_core import LatexToMathML

# Create a converter instance
converter = LatexToMathML()

# Convert inline math
mathml = converter.convert_with_local_state("x^2 + y^2 = z^2", displaystyle=False)
print(mathml)
# Output: <math><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><msup><mi>y</mi><mn>2</mn></msup><mo>=</mo><msup><mi>z</mi><mn>2</mn></msup></math>

# Convert display math
mathml = converter.convert_with_local_state(r"\frac{1}{2}", displaystyle=True)
print(mathml)
# Output: <math display="block"><mfrac><mn>1</mn><mn>2</mn></mfrac></math>

Usage

Basic Usage

from math_core import LatexToMathML, LatexError

# Initialize converter
converter = LatexToMathML(pretty_print="always")

# Convert LaTeX to MathML
try:
    mathml = converter.convert_with_local_state(r"\sqrt{x^2 + 1}", displaystyle=False)
    print(mathml)
except LatexError as e:
    print(f"Conversion error: {e}")

Custom LaTeX Macros

Define custom macros to extend or modify LaTeX command behavior:

# Define custom macros
macros = {
    "d": r"\mathrm{d}",      # Differential d
    "R": r"\mathbb{R}",      # Real numbers
    "vec": r"\mathbf{#1}"    # Vector notation
}

converter = LatexToMathML(macros=macros)
mathml = converter.convert_with_local_state(r"\d x", displaystyle=False)

Numbered Equations with Global State

For documents with multiple numbered equations:

converter = LatexToMathML()

# First equation gets (1)
eq1 = converter.convert_with_global_state(
    r"\begin{align}E = mc^2\end{align}",
    displaystyle=True
)

# Second equation gets (2)
eq2 = converter.convert_with_global_state(
    r"\begin{align}F = ma\end{align}",
    displaystyle=True
)

# Reset counter when starting a new chapter/section
converter.reset_global_state()

# This equation gets (1) again
eq3 = converter.convert_with_global_state(
    r"\begin{align}p = mv\end{align}",
    displaystyle=True
)

Local Counter for Independent Numbering

Use local counters when equation numbers should restart within each conversion:

converter = LatexToMathML()

# Each conversion has independent numbering
doc1 = converter.convert_with_local_state(
    r"\begin{align}a &= b\\c &= d\end{align}",
    displaystyle=True
)  # Contains (1) and (2)

doc2 = converter.convert_with_local_state(
    r"\begin{align}x &= y\\z &= w\end{align}",
    displaystyle=True
)  # Also contains (1) and (2)

Converting a Whole Document at Once

convert_all converts a collection of snippets in one go, which is the only way to get forward references right: a snippet may refer to an equation which is only defined in a later snippet.

converter = LatexToMathML()

reference, equation = converter.convert_all([
    (r"\eqref{eq:euler}", False),
    (r"\begin{align}e^{i\pi} + 1 = 0\label{eq:euler}\end{align}", True),
])
# `reference` refers to equation (1), even though it comes first.

Each entry is a (latex, displaystyle) pair. Equation numbering restarts with every call to convert_all; the state of convert_with_global_state is neither used nor modified.

If any snippet fails to convert, LatexError is raised, unless the converter was created with continue_on_error=True, in which case an HTML snippet describing the error takes the place of that snippet's MathML.

API Reference

LatexToMathML

The main converter class.

Constructor parameters:

  • pretty_print (str, optional): A string indicating whether to pretty print the MathML output. Options are “never”, “always”, or “auto”. “auto” means that all block equations will be pretty printed. Default: “never”.
  • macros (dict[str, str], optional): Dictionary of LaTeX macros for custom commands.
  • xml_namespace (bool, optional): A boolean indicating whether to include xmlns="http://www.w3.org/1998/Math/MathML" in the <math> tag. Default: False.
  • continue_on_error (bool, optional): A boolean indicating whether to raise an exception for conversion errors. If conversion fails and this is True, an HTML snippet describing the error will be returned, instead of raising LatexError. Default: False.
  • ignore_unknown_commands (bool, optional): A boolean indicating whether to ignore unknown LaTeX commands. If True, unknown commands be rendered as red text and the conversion will continue. Default: False.
  • annotation (bool, optional): A boolean indicating whether to include the original LaTeX as an annotation in the MathML output. Default: False.
  • allow_unreliable_rendering (bool, optional): A boolean indicating whether to enable commands whose MathML Core output is rendered unreliably across browsers, such as \widetilde, \widecheck and \utilde. If False, these commands are treated as unknown. Default: False.
  • global_group (bool, optional): A boolean indicating whether to run the conversion in the global group. If True, commands defined with \newcommand stay defined for subsequent calls to convert_with_global_state; if False, such definitions are local to the snippet which contains them. Default: False.
  • fancy_error (bool, optional): A boolean indicating whether to render errors as rich Ariadne diagnostic reports. If True (the default), the LatexError message contains a formatted diagnostic with source spans. Set to False to use compact plain-text messages instead.
  • unicode_substitution (str, optional): A string indicating whether to substitute certain character combinations with a single Unicode symbol. Options are “conventional” and “never”. With “conventional”, commands like \coloneqq are rendered with a dedicated Unicode symbol (≔) wherever the LaTeX package unicode-math would substitute; with “never”, they are rendered as a combination of more basic symbols (: and =), which is more faithful to the LaTeX output. Default: “conventional”.
  • max_expansions (int, optional): The number of custom command expansions allowed in one snippet, after which the conversion gives up. The limit exists because a macro may expand to itself, directly or indirectly. Default: 1000.
  • id_prefix (str, optional): Added to the beginning of every id and anchor reference in the output. Use this to avoid conflicts when embedding the output. The prefix is not URL escaped. Default: "".

Methods:

  • convert_with_global_state(latex: str, displaystyle: bool) -> str: Convert LaTeX to MathML using global state. May raise LatexError.
  • convert_with_local_state(latex: str, displaystyle: bool) -> str: Convert LaTeX to MathML using local state. May raise LatexError.
  • convert_all(snippets: list[tuple[str, bool]]) -> list[str]: Convert all snippets of a document at once, resolving forward references between them. Each snippet is a (latex, displaystyle) pair. Uses a fresh state for the batch, independent of the global state. May raise LatexError.
  • reset_global_state() -> None: Reset the global state (e.g., set the equation counter to zero).

LatexError

Exception raised when LaTeX parsing or conversion fails.

from math_core import LatexToMathML, LatexError

converter = LatexToMathML()
try:
    result = converter.convert_with_local_state(r"\invalid")
except LatexError as e
    print(f"Conversion failed: {e}")

Use Cases

Static Site Generators

Integrate math-core into your static site generator to convert LaTeX in Markdown files:

import re
from math_core import LatexToMathML

converter = LatexToMathML(pretty_print="auto")

def process_math(content):
    # Replace display math $$...$$; do this first to avoid conflicts with inline math delimiters
    content = re.sub(
        r"\$\$([^\$]+)\$\$",
        lambda m: converter.convert_with_local_state(m.group(1), displaystyle=True),
        content,
    )

    # Replace inline math $...$
    content = re.sub(
        r"\$([^\$]+)\$",
        lambda m: converter.convert_with_local_state(m.group(1), displaystyle=False),
        content,
    )

    return content

Web Applications

Generate MathML on the server side:

from flask import Flask, render_template_string
from math_core import LatexToMathML, LatexError

app = Flask(__name__)
converter = LatexToMathML()

@app.route("/equation/<latex>")
def render_equation(latex):
    try:
        mathml = converter.convert_with_local_state(latex, displaystyle=True)
        return render_template_string(
            "<html><body>{{ mathml|safe }}</body></html>", mathml=mathml
        )
    except LatexError:
        return "Invalid equation", 400

Why MathML Core?

MathML Core is a carefully selected subset of MathML 4 that focuses on essential mathematical notation while ensuring consistent rendering across browsers. Unlike full MathML or JavaScript-based solutions:

  • Native browser support: No JavaScript required
  • Accessibility: Better screen reader support
  • Performance: Faster rendering than JS solutions
  • SEO-friendly: Search engines can index mathematical content
  • Future-proof: Part of web standards with ongoing browser support

Browser Support

Firefox currently has the most complete support for MathML Core, with Chrome close behind. Safari has the least support and some rendering issues exist when using MathML Core, but it is improving with each release.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Wheel compatibility matrix

Platform CPython >=3.10 (abi3) CPython (additional flags: t) 3.14
macosx_10_12_x86_64
macosx_11_0_arm64
manylinux2014_aarch64
manylinux2014_x86_64
manylinux_2_17_aarch64
manylinux_2_17_x86_64
musllinux_1_2_aarch64
musllinux_1_2_armv7l
musllinux_1_2_i686
musllinux_1_2_x86_64
win_amd64
win_arm64

Files in release

Extras:
Dependencies: