Skip to content

Math Formula API

The math module provides registration and management of LaTeX formula rendering backends.

Module Overview

Export Type Responsibility
MathBackend Protocol Backend interface protocol
SVGFragment dataclass Render result (SVG content + dimensions)
QuickJaxBackend class Default backend (based on QuickJax / MathJax v4)
register_backend() function Register a custom backend
set_default_backend() function Set the default backend
get_backend() function Get a backend instance
get_default_backend_name() function Get the default backend name

Basic Usage

from latticesvg.math import get_backend

backend = get_backend()  # Default QuickJax
fragment = backend.render(r"E = mc^2", font_size=20, display=True)
print(fragment.width, fragment.height)
print(fragment.svg)  # SVG string fragment

Custom Backends

from latticesvg.math import register_backend, set_default_backend

class MyBackend:
    def render(self, latex: str, font_size: float, display: bool = True):
        # Return SVGFragment
        ...

register_backend("my_backend", MyBackend)
set_default_backend("my_backend")

Auto-generated API Docs

Backend Management

math

Math formula rendering — pluggable backend system.

Default backend: quickjax (in-process MathJax v4 via QuickJS).

Usage::

from latticesvg.math import get_backend

backend = get_backend()          # default QuickJax
frag = backend.render(r"E=mc^2", font_size=16)
MathBackend

Bases: Protocol

Abstract interface for math rendering backends.

render
render(latex: str, font_size: float) -> SVGFragment

Render latex at font_size and return an SVG fragment.

Source code in src/latticesvg/math/backend.py
def render(self, latex: str, font_size: float) -> SVGFragment:
    """Render *latex* at *font_size* and return an SVG fragment."""
    ...
available
available() -> bool

Return True if this backend's dependencies are satisfied.

Source code in src/latticesvg/math/backend.py
def available(self) -> bool:
    """Return ``True`` if this backend's dependencies are satisfied."""
    ...
SVGFragment dataclass
SVGFragment(svg_content: str, width: float, height: float, depth: float = 0.0)

Result of rendering a LaTeX expression to SVG.

svg_content instance-attribute
svg_content: str

Inner SVG markup (without outer <svg> wrapper).

width instance-attribute
width: float

Precise width in px.

height instance-attribute
height: float

Precise height in px.

depth class-attribute instance-attribute
depth: float = 0.0

Depth below baseline in px (for inline alignment).

QuickJaxBackend
QuickJaxBackend()

Render LaTeX math via QuickJax (in-process MathJax v4).

QuickJax runs MathJax inside an embedded QuickJS engine — no Node.js, no subprocess, no network. It is the recommended and default backend.

Source code in src/latticesvg/math/backend.py
def __init__(self) -> None:
    self._renderer = None
    self._cache: Dict[Tuple[str, float, bool], SVGFragment] = {}
register_backend
register_backend(name: str, cls: Type[MathBackend]) -> None

Register a math backend class under name.

Source code in src/latticesvg/math/__init__.py
def register_backend(name: str, cls: Type[MathBackend]) -> None:
    """Register a math backend class under *name*."""
    _backend_registry[name] = cls
    # Invalidate cached instance if the class changed
    _backend_instances.pop(name, None)
set_default_backend
set_default_backend(name: str) -> None

Set the global default math backend by name.

Source code in src/latticesvg/math/__init__.py
def set_default_backend(name: str) -> None:
    """Set the global default math backend by name."""
    global _default_backend_name
    _default_backend_name = name
get_default_backend_name
get_default_backend_name() -> str

Return the name of the current default backend.

Source code in src/latticesvg/math/__init__.py
def get_default_backend_name() -> str:
    """Return the name of the current default backend."""
    return _default_backend_name
get_backend
get_backend(name: Optional[str] = None) -> MathBackend

Return a (cached) backend instance.

PARAMETER DESCRIPTION
name

Backend name. None → use the global default.

TYPE: str or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If the requested backend is not registered.

RuntimeError

If the backend reports itself as unavailable.

Source code in src/latticesvg/math/__init__.py
def get_backend(name: Optional[str] = None) -> MathBackend:
    """Return a (cached) backend instance.

    Parameters
    ----------
    name : str or None
        Backend name.  ``None`` → use the global default.

    Raises
    ------
    ValueError
        If the requested backend is not registered.
    RuntimeError
        If the backend reports itself as unavailable.
    """
    if name is None:
        name = _default_backend_name

    if name in _backend_instances:
        return _backend_instances[name]

    cls = _backend_registry.get(name)
    if cls is None:
        raise ValueError(
            f"Unknown math backend {name!r}. "
            f"Registered: {list(_backend_registry)}"
        )

    inst = cls()
    if not inst.available():
        raise RuntimeError(
            f"Math backend {name!r} is not available. "
            f"Check its dependencies (pip install quickjax)."
        )
    _backend_instances[name] = inst
    return inst

QuickJax Backend

backend

Math backend protocol and QuickJax implementation.

SVGFragment dataclass
SVGFragment(svg_content: str, width: float, height: float, depth: float = 0.0)

Result of rendering a LaTeX expression to SVG.

svg_content instance-attribute
svg_content: str

Inner SVG markup (without outer <svg> wrapper).

width instance-attribute
width: float

Precise width in px.

height instance-attribute
height: float

Precise height in px.

depth class-attribute instance-attribute
depth: float = 0.0

Depth below baseline in px (for inline alignment).

MathBackend

Bases: Protocol

Abstract interface for math rendering backends.

render
render(latex: str, font_size: float) -> SVGFragment

Render latex at font_size and return an SVG fragment.

Source code in src/latticesvg/math/backend.py
def render(self, latex: str, font_size: float) -> SVGFragment:
    """Render *latex* at *font_size* and return an SVG fragment."""
    ...
available
available() -> bool

Return True if this backend's dependencies are satisfied.

Source code in src/latticesvg/math/backend.py
def available(self) -> bool:
    """Return ``True`` if this backend's dependencies are satisfied."""
    ...
QuickJaxBackend
QuickJaxBackend()

Render LaTeX math via QuickJax (in-process MathJax v4).

QuickJax runs MathJax inside an embedded QuickJS engine — no Node.js, no subprocess, no network. It is the recommended and default backend.

Source code in src/latticesvg/math/backend.py
def __init__(self) -> None:
    self._renderer = None
    self._cache: Dict[Tuple[str, float, bool], SVGFragment] = {}