Skip to main content

Convert LaTeX math to MathML Core

Project description

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_counter("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_counter(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_counter(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_counter(r"\d x", displaystyle=False)

Numbered Equations with Global Counter

For documents with multiple numbered equations:

converter = LatexToMathML()

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

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

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

# This equation gets (1) again
eq3 = converter.convert_with_global_counter(
    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_counter(
    r"\begin{align}a &= b\\c &= d\end{align}",
    displaystyle=True
)  # Contains (1) and (2)

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

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.
  • 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.

Methods:

  • convert_with_global_counter(latex: str, displaystyle: bool) -> str | LatexError: Convert LaTeX to MathML using a global equation counter.
  • convert_with_local_counter(latex: str, displaystyle: bool) -> str | LatexError: Convert LaTeX to MathML using a local equation counter.
  • reset_global_counter() -> None: Reset the global 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_counter(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_counter(m.group(1), displaystyle=True),
        content,
    )

    # Replace inline math $...$
    content = re.sub(
        r"\$([^\$]+)\$",
        lambda m: converter.convert_with_local_counter(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_counter(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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

math_core-0.5.4-cp314-cp314t-musllinux_1_2_x86_64.whl (576.0 kB view details)

Uploaded CPython 3.14tmusllinux: musl 1.2+ x86-64

math_core-0.5.4-cp314-cp314t-musllinux_1_2_armv7l.whl (642.7 kB view details)

Uploaded CPython 3.14tmusllinux: musl 1.2+ ARMv7l

math_core-0.5.4-cp310-abi3-musllinux_1_2_x86_64.whl (581.5 kB view details)

Uploaded CPython 3.10+musllinux: musl 1.2+ x86-64

math_core-0.5.4-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (363.5 kB view details)

Uploaded CPython 3.10+manylinux: glibc 2.17+ ARM64

math_core-0.5.4-cp310-abi3-macosx_10_12_x86_64.whl (346.6 kB view details)

Uploaded CPython 3.10+macOS 10.12+ x86-64

File details

Details for the file math_core-0.5.4-cp314-cp314t-musllinux_1_2_x86_64.whl.

File metadata

  • Download URL: math_core-0.5.4-cp314-cp314t-musllinux_1_2_x86_64.whl
  • Upload date:
  • Size: 576.0 kB
  • Tags: CPython 3.14t, musllinux: musl 1.2+ x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for math_core-0.5.4-cp314-cp314t-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 f38aa2cac49d331dd735b8dfbc427b3202b6f7f1a4ebcc974baec5322abb701c
MD5 152a7c473cc4714daff3b9030c3d3354
BLAKE2b-256 c422c1b7e2bd89e4449af1fc60e564d59f642abade83533df1f5ae42346cd410

See more details on using hashes here.

File details

Details for the file math_core-0.5.4-cp314-cp314t-musllinux_1_2_armv7l.whl.

File metadata

  • Download URL: math_core-0.5.4-cp314-cp314t-musllinux_1_2_armv7l.whl
  • Upload date:
  • Size: 642.7 kB
  • Tags: CPython 3.14t, musllinux: musl 1.2+ ARMv7l
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for math_core-0.5.4-cp314-cp314t-musllinux_1_2_armv7l.whl
Algorithm Hash digest
SHA256 fa532ed45d740ee38cf6fd6a6356de04d8dbe99e96d7de3019fab851691a8354
MD5 823b41fe2010fb4ebcbedb6bf98e4fd2
BLAKE2b-256 04194cae28838ee1ce6f019689f50599c3d5ffd9fbf33dd500e77740f290046b

See more details on using hashes here.

File details

Details for the file math_core-0.5.4-cp310-abi3-musllinux_1_2_x86_64.whl.

File metadata

  • Download URL: math_core-0.5.4-cp310-abi3-musllinux_1_2_x86_64.whl
  • Upload date:
  • Size: 581.5 kB
  • Tags: CPython 3.10+, musllinux: musl 1.2+ x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for math_core-0.5.4-cp310-abi3-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 77578762a55680abd685a52486453f57c0a22854957802594d978cdcf72e3612
MD5 e333f8cd73a6a81676a8ebc575f86850
BLAKE2b-256 1e0b134e940395cb05bac9a761323c54059f2f65b8a0d038c7a81431b0d40c70

See more details on using hashes here.

File details

Details for the file math_core-0.5.4-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

  • Download URL: math_core-0.5.4-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
  • Upload date:
  • Size: 363.5 kB
  • Tags: CPython 3.10+, manylinux: glibc 2.17+ ARM64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for math_core-0.5.4-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 83877a95d9919c3043ebf7858a151bfb8e586fce6b92aebca98693a7d7308747
MD5 db6616d93e4d366f1c1c6642cb0818c5
BLAKE2b-256 df9c19f73be890519f634f71ae562b751d28768732eb71b31dbc0a579095d319

See more details on using hashes here.

File details

Details for the file math_core-0.5.4-cp310-abi3-macosx_10_12_x86_64.whl.

File metadata

  • Download URL: math_core-0.5.4-cp310-abi3-macosx_10_12_x86_64.whl
  • Upload date:
  • Size: 346.6 kB
  • Tags: CPython 3.10+, macOS 10.12+ x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for math_core-0.5.4-cp310-abi3-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 c40a9fa90ab6192c00d71e077c69dd7f47244c66fa05a6ffe4415c45500ea279
MD5 568103004265528de7e0ddbae03ffb86
BLAKE2b-256 053b575b41ae55c8853a67e1a9f47bd16f4c69b6f4fd68b40e73422c7ea7c163

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page