latex2mathml

repository·master·Indexed 42 days ago

https://github.com/roniemartinez/latex2mathml

A pure Python library for converting LaTeX mathematical notation into MathML (Mathematical Markup Language). Version 3.81.1 provides a programmatic API via the Converter class and top-level functions, as well as a command-line interface for converting text, files, or standard input. It includes features for handling custom macros, Unicode symbol lookup, and a structured Node tree for parsing LaTeX data.

Tokens
3.2K
Snippets
15
Records
16
Agent score
54%

What's inside latex2mathml

  1. Define custom macros for walk()

    master

    You can provide custom macro definitions to the walk function to handle non-standard LaTeX commands. The macros dictionary expects the following format:

    { "command_name": ( [list_of_tokens], number_of_arguments ) }

    • command_name: The exact string of the command (e.g., "\\mycmd").
    • list_of_tokens: The sequence of tokens that the command expands into.
    • number_of_arguments: The integer count of arguments the macro accepts (used with #1, #2, etc., in the token list).
    from latex2mathml import walker
    
    # Define a macro \hello{text} that expands to \text{hello text}
    custom_macros = {
        "\\hello": (["\\text", "hello"], 1)
    }
    
    # Note: If the macro uses arguments like #1, the expansion logic handles substitution
    # Example: macro for \swap{a}{b} -> a b
    swap_macros = {
        "\\swap": (["#1", "#2"], 2)
    }
    
    tree = walker.walk(r"\hello{world}", macros=swap_macros)
  2. Convert LaTeX to MathML in Python

    master

    To convert LaTeX strings to MathML programmatically, import latex2mathml.converter and use the convert() function. Pass your LaTeX string as the input argument to receive the MathML output.

    import latex2mathml.converter
    
    latex_input = "<your_latex_string>"
    mathml_output = latex2mathml.converter.convert(latex_input)
  3. Reference the latex2mathml CLI options

    master

    The following options are available when using the latex2mathml command-line tool:

    Options:

    • -h, --help: Show this help message and exit
    • -V, --version: Show version
    • -b, --block: Display block

    Required Arguments:

    • -t TEXT, --text TEXT: Provide the LaTeX text directly
    • -f FILE, --file FILE: Provide a file containing LaTeX
    • -s, --stdin: Read LaTeX from standard input
  4. Use the latex2mathml command-line interface

    master

    The latex2mathml CLI allows you to convert LaTeX to MathML from the terminal using text, files, or standard input (stdin).

    # View help information
    latex2mathml -h
    
    # Example usage (based on available flags)
    latex2mathml -t "\alpha"
    latex2mathml -f input.tex
    latex2mathml -s
  5. Parse and load the symbol dictionary with parse_symbols()

    master

    The parse_symbols() function reads the unimathsymbols.txt file to build a mapping between LaTeX commands and Unicode hex strings. It handles various formats including direct LaTeX commands, Unicode math equivalents, and additional aliases defined in the symbol file. It also applies a set of hardcoded manual overrides for specific LaTeX commands (e.g., \And, \Box, \dots).

    from latex2mathml.symbols_parser import parse_symbols
    
    symbols_map = parse_symbols()
    # symbols_map is a dict[str, str] where keys are LaTeX commands and values are Unicode hex strings
  6. Traverse LaTeX data into a Node tree with walk()

    master

    The walk function is the primary entry point for converting a LaTeX string into a structured tree of Node objects. It tokenizes the input and recursively builds a hierarchy representing the mathematical structure.

    Parameters

    • data (str): The raw LaTeX string to be parsed.
    • display (str): The display mode. Use "block" for display-style math (e.g., for summations/products with limits) or "inline" for text-style math. Defaults to "inline".
    • macros (dict, optional): A dictionary mapping macro names to their definitions. A definition is a tuple containing a list of tokens (list[str]) and the number of arguments (int).

    Returns

    • list[Node]: A list of Node objects representing the top-level elements of the parsed LaTeX.
    from latex2mathml import walker
    
    latex_input = r"\sum_{i=1}^{n} i"
    # Parse as block math to ensure limits are handled correctly
    node_tree = walker.walk(latex_input, display="block")
    
    for node in node_tree:
        print(node.token)
  7. Convert LaTeX to MathML using top-level functions

    master

    For simple use cases, you can use the standalone convert and convert_to_element functions. These functions instantiate a Converter internally with default settings.

    • convert(latex, xmlns, display, parent): Returns a MathML string.
    • convert_to_element(latex, xmlns, display, parent): Returns an XML Element.
    from latex2mathml import convert, convert_to_element
    
    # Quick conversion to string
    result = convert(r"x^2")
    
    # Quick conversion to Element
    element = convert_to_element(r"x^2", display="block")
  8. Handle LaTeX conversion errors with custom exceptions

    master

    The latex2mathml library raises specific exceptions when encountering malformed LaTeX or unsupported syntax during the conversion process. You can catch these exceptions to handle errors gracefully in your application.

    Commonly encountered exceptions include:

    • NumeratorNotFoundError: Raised when a numerator is expected but not found.
    • DenominatorNotFoundError: Raised when a denominator is expected but not found.
    • ExtraLeftOrMissingRightError: Raised due to unbalanced parentheses or braces.
    • MissingSuperScriptOrSubscriptError: Raised when superscript or subscript syntax is incomplete.
    • DoubleSubscriptsError / DoubleSuperscriptsError: Raised when multiple subscripts or superscripts are applied to the same base incorrectly.
    • NoAvailableTokensError: Raised when the parser runs out of tokens unexpectedly.
    • InvalidStyleForGenfracError: Raised when an invalid style is provided for the rac or ext related commands.
    • MissingEndError: Raised when a command that requires an end delimiter is not closed.
    • InvalidAlignmentError: Raised for incorrect alignment syntax.
    • InvalidWidthError: Raised for invalid width specifications.
    • LimitsMustFollowMathOperatorError: Raised when limits are not correctly placed after a math operator.
    try:
        # Attempt LaTeX to MathML conversion
        result = latex2mathml.converter.convert(invalid_latex_string)
    except (NumeratorNotFoundError, DenominatorNotFoundError, ExtraLeftOrMissingRightError) as e:
        print(f"Conversion error: {e}")
  9. Convert a LaTeX symbol to its Unicode representation with convert_symbol()

    master

    Use convert_symbol(symbol: str) to look up the Unicode hex string for a given LaTeX symbol. The function searches a pre-loaded dictionary of symbols. If the symbol is not found, it returns None.

    from latex2mathml.symbols_parser import convert_symbol
    
    unicode_hex = convert_symbol(r"\alpha")
    if unicode_hex:
        print(f"Unicode hex: {unicode_hex}")
    else:
        print("Symbol not found")
  10. Convert LaTeX to MathML using the Converter class

    master

    The Converter class is the primary interface for converting LaTeX strings into MathML. You can initialize it with a specific MathML namespace and display mode.

    Initialization

    • xmlns: The MathML namespace (defaults to http://www.w3.org/1998/Math/MathML).
    • display: The display mode, either 'inline' or 'block' (defaults to 'inline').

    Methods

    • convert(latex: str, parent: Optional[Element] = None) -> str: Converts the LaTeX string and returns the MathML as an unescaped string.
    • convert_to_element(latex: str, parent: Optional[Element] = None) -> Element: Converts the LaTeX string and returns an xml.etree.ElementTree.Element object.
    • reset(): Resets the internal equation_counter and macros dictionary.
    from latex2mathml.converter import Converter
    
    # Initialize converter
    converter = Converter(display="block")
    
    # Convert LaTeX to a MathML string
    mathml_string = converter.convert(r"\alpha + \beta")
    print(mathml_string)
    
    # Convert LaTeX to an XML Element
    element = converter.convert_to_element(r"\sum_{i=1}^{n} i")