Metadata-Version: 2.5
Name: asciimath2mathml
Version: 0.3.0b1
Summary: Convert AsciiMath strings to MathML markup
Author: asciimath2mathml contributors
License: MIT
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: lark>=1.1.0
Provides-Extra: dev
Requires-Dist: hypothesis>=6.100; extra == 'dev'
Requires-Dist: mypy; extra == 'dev'
Requires-Dist: pre-commit; extra == 'dev'
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: pytest-cov; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Description-Content-Type: text/markdown

# 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](https://asciimath.org/) 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`](./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](https://github.com/lark-parser/lark) parser.
- **High Performance** — Sub-millisecond cold parse; sub-microsecond cache hits via built-in LRU cache (512 entries by default, configurable).
- **Stateless Functional API** — `convert()` for strings, `convert_to_element()` for `xml.etree.ElementTree` integration.
- **Rich Error Diagnostics** — `strict=True` raises `AsciiMathSyntaxError` with `.line`, `.column`, `.token`, and `.details`; default mode wraps unparseable input in `<mtext>` rather than crashing.
- **Jupyter & IPython Native** — `convert()` 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

```bash
pip install asciimath2mathml
```

## Quick Start

```python
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:

```python
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

```python
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:

```python
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

```python
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

```bash
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`](./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 | `|x|  ||x||  |__x__|  hat x  bar x  vec x` |
| 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__`

```python
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

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

See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for contribution guidelines and [`SYMBOL_REFERENCE.md`](./SYMBOL_REFERENCE.md) for the full symbol inventory.

## License

MIT
