Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

asciimath2mathml

Convert AsciiMath strings to Presentation MathML markup with 100% specification coverage.

Overview

asciimath2mathml is a zero-dependency Python library (3.10+) that compiles AsciiMath mathematical notation into semantically accurate Presentation MathML. It is designed as a direct peer to latex2mathml, providing fast, stateless in-memory conversion and browser-based WebAssembly execution via Pyodide.

Features

  • Full AsciiMath Coverage — 100% of official AsciiMath symbols, operators, Greek letters, matrices, delimiters, accents, and structural constructs. See SYMBOL_REFERENCE.md for the complete mapping table.
  • Extended TeX Aliases — Unescaped TeX command names (times, div, infty, partial, implies, iff, subset, …) work natively alongside AsciiMath syntax.
  • Zero Runtime Dependencies — Pure Python standard library plus the Lark parser.
  • High Performance — Sub-millisecond cold parse; sub-microsecond cache hits via built-in LRU cache (512 entries by default, configurable).
  • Stateless Functional APIconvert() for strings, convert_to_element() for xml.etree.ElementTree integration.
  • Rich Error Diagnosticsstrict=True raises AsciiMathSyntaxError with .line, .column, .token, and .details; default mode wraps unparseable input in <mtext> rather than crashing.
  • Jupyter & IPython Nativeconvert() returns MathMLResult, a str subclass with _repr_html_() and _repr_mimebundle_() for zero-config notebook rendering.
  • CLI — Terminal commands asciimath2mathml and a2m, plus python -m asciimath2mathml.
  • PEP 561 Typed — Bundled py.typed marker; fully typed for Mypy and Pyright.

Installation

pip install asciimath2mathml

Quick Start

from asciimath2mathml import convert

# Inline formula (default)
result = convert("x^2 + y^2 = z^2")
# <math xmlns="http://www.w3.org/1998/Math/MathML"><mrow>…</mrow></math>

# Block display (centered, displaystyle)
result = convert("sum_(i=1)^n i^2", display="block")

Jupyter / IPython

In a notebook, convert() renders automatically — no display() call needed:

from asciimath2mathml import convert

convert("sum_(i=1)^n i^2 = (n(n+1)(2n+1))/6")
# ↑ renders as formatted math in the cell output

MathMLResult is a full str subclass; all string operations continue to work normally.

ElementTree API

from asciimath2mathml import convert_to_element

elem = convert_to_element("sqrt(x^2 + 1)")  # returns ET.Element
elem = convert_to_element("x^2", indent=2)  # pretty-printed
elem = convert_to_element("x^2", xmlns=None)  # omit namespace
elem = convert_to_element("x^2", parent=body)  # append to existing tree

Error Handling

By default, invalid input falls back to <mtext> rather than raising. Enable strict mode for validation workflows:

from asciimath2mathml import AsciiMathSyntaxError, convert_to_element

try:
    convert_to_element("x +\n)", strict=True)
except AsciiMathSyntaxError as err:
    print(err)  # Invalid AsciiMath syntax at line 2, col 1: 'x +\n)'
    print(err.line)  # 2
    print(err.column)  # 1
    print(err.token)  # ')'
    print(err.details)  # parser error description

Cache Control

from asciimath2mathml import configure_cache, clear_cache, get_cache_info

get_cache_info()  # CacheInfo(hits=…, misses=…, maxsize=512, currsize=…)
clear_cache()  # flush all cached entries
configure_cache(1024)  # change capacity
configure_cache(None)  # unbounded
configure_cache(0)  # disable caching

Command-Line Interface

asciimath2mathml "x^2 + y^2 = z^2"       # inline
asciimath2mathml -b "sum_(i=1)^n i^2"    # block display
asciimath2mathml -p "x^2"                # pretty-print
asciimath2mathml -f formula.txt          # read from file
echo "sqrt(a^2 + b^2)" | asciimath2mathml  # read from stdin
asciimath2mathml -s "x^"                # strict mode (exits 1 on error)
asciimath2mathml --no-xmlns "x^2"       # omit xmlns attribute
asciimath2mathml -o out.xml "x^2"       # write to file
Flag Description
formula AsciiMath formula string (positional)
-f / --file FILE Read formula from file
-b / --block Block display mode (displaystyle="true")
-p / --pretty Pretty-print output with indentation
-s / --strict Raise on syntax error (exit code 1)
--no-xmlns Omit xmlns attribute from <math>
-o / --output FILE Write output to file (default: stdout)
-v / --version Show version and exit

Symbols

All supported AsciiMath tokens, their TeX aliases, and the corresponding MathML output are documented in SYMBOL_REFERENCE.md.

Quick category overview:

Category Examples
Arithmetic & relational + - * / = != <= >= ~~ -=
Logic & set theory and or not AA EE in sub nn uu
Greek letters alpha beta gamma … omega Gamma Delta …
Arrows -> <- <-> => <=> uarr darr
Big operators sum prod int oint lim nnn uuu
Fractions & roots a/b frac(a)(b) sqrt(x) root(n)(x)
Scripts a^b a_b a_b^c f' f''
Matrices [[a,b],[c,d]] ((a,b),(c,d))
Delimiters & accents `
Font styles bb(x) bbb(x) rm(x) sf(x) cc(x) tt(x)
Higher-order overset underset ubrace cancel color

API Reference

convert(asciimath_string, *, display="inline") → MathMLResult

Converts an AsciiMath string to serialized MathML. Results are LRU-cached.

  • display: "inline" (default) or "block" (wraps in <mstyle displaystyle="true">)
  • Returns MathMLResult, a str subclass with Jupyter rich-display hooks.

convert_to_element(asciimath_string, *, display="inline", parent=None, strict=False, indent=None, xmlns="http://www.w3.org/1998/Math/MathML") → ET.Element

Converts an AsciiMath string to an xml.etree.ElementTree.Element.

  • parent: append the <math> element to an existing element
  • strict: raise AsciiMathSyntaxError instead of falling back to <mtext>
  • indent: pretty-print with indent spaces per level
  • xmlns: namespace URI on <math>, or None/"" to omit

MathMLResult(str)

str subclass returned by convert(). Implements _repr_html_() and _repr_mimebundle_() for Jupyter/IPython rendering.

Exceptions

Exception When raised
AsciiMathError Base class for all library exceptions
AsciiMathSyntaxError strict=True and input fails to parse; carries .line, .column, .token, .details

Cache functions

Function Description
configure_cache(maxsize) Set LRU cache capacity (int, None for unbounded, 0 to disable)
clear_cache() Flush all cached entries (also convert.cache_clear())
get_cache_info() Return CacheInfo(hits, misses, maxsize, currsize) (also convert.cache_info())

__version__

import asciimath2mathml

print(asciimath2mathml.__version__)  # e.g. "0.3.0b1"

Resolved dynamically via importlib.metadata; falls back to "0.3.0b1.dev0" in uninstalled checkouts.

Development

python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest tests/ -v --cov=asciimath2mathml

See CONTRIBUTING.md for contribution guidelines and SYMBOL_REFERENCE.md for the full symbol inventory.

License

MIT

Release files for asciimath2mathml 0.3.0b1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for asciimath2mathml 0.3.0b1
File Size Uploaded
asciimath2mathml-0.3.0b1.tar.gz 40.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for asciimath2mathml 0.3.0b1
File Interpreter ABI Platform
asciimath2mathml-0.3.0b1-py3-none-any.whl Python 3 none any Details

Total release size: 60.8 kB

Release files / asciimath2mathml-0.3.0b1.tar.gz

Download URL asciimath2mathml-0.3.0b1.tar.gz
Size 40.4 kB
Tags Source
SHA-256 checksum
How to use checksums
5ab3f8f71d302968ccfaa48680aca86dc985f2398ce07a60e23af9feb700d22d
BLAKE2b-256 checksum
How to use checksums
949b5276aed5247b3e1e0b20882a299488c63f8eed1da667a12e291f5caee583
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 11, 2026.

Transparency log

Release files / asciimath2mathml-0.3.0b1-py3-none-any.whl

Download URL asciimath2mathml-0.3.0b1-py3-none-any.whl
Size 20.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4d7ea68aa573f4548d481075f17713b057ed3c6ac5baba7fed402140c19f359d
BLAKE2b-256 checksum
How to use checksums
34d6f124a23a27b6e9f24a747697871eb7a4d08238534f94bf98ce52e6de5dd7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 11, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.3.0b1 This release

2 release files

0.2.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page