Parse a Latex string and return a corresponding MathJSON expression.


Serialize a MathJSON expression as a Latex string.

interface Scanner

interface ScannerapplyInvisibleOperator

applyInvisibleOperator(lhs: Expression<T>, rhs: Expression<T>): Expression<T>
lhs: Expression<T>
rhs: Expression<T>

interface ScannerapplyOperator

applyOperator(op: string, lhs: Expression<T>, rhs: Expression<T>): [Expression<T>, Expression<T>]
op: string
lhs: Expression<T>
rhs: Expression<T>
[Expression<T>, Expression<T>]

interface ScannerlatexAfter

Return a latex string after the index

latexAfter(): string

interface ScannerlatexBefore

Return a latex string before the index

latexBefore(): string

interface ScannerlookAhead

Return an array of string corresponding to tokens ahead. The index is unchanged.

lookAhead(): string[]

interface Scannermatch

If the next token matches the target advance and return true. Otherwise return false

match(target: string): boolean
target: string

interface ScannermatchAny

matchAny(targets: string[]): string
targets: string[]

interface ScannermatchArguments

matchArguments(kind: "" | "group" | "implicit"): Expression<T>[]
  • | ""
  • | "group"
  • | "implicit"

interface ScannermatchBalancedExpression

matchBalancedExpression(open: string, close: string, onError?: ErrorListener<ErrorCode>): Expression<T>
open: string
close: string
onError: ErrorListener<ErrorCode>

interface ScannermatchDecimalDigits

matchDecimalDigits(): string

interface ScannermatchExponent

matchExponent(): string

interface ScannermatchExpression

Parse an expression:

::= | | |

Stop when an operator of precedence less than minPrec is encountered

minPrec is 0 by default.

matchExpression(minPrec?: number): Expression<T>
minPrec: number

interface ScannermatchNumber

matchNumber(): string

interface ScannermatchOptionalLatexArgument

If the next tokens correspond to an optional argument, enclosed with [ and ] return the content of the argument as an expression and advance the index past the closing ]. Otherwise, return null

matchOptionalLatexArgument(): Expression<T>

interface ScannermatchPrimary

:= ( | | | | ) ( | )*


::= | [‘,’ ]

If not a primary, return null and do not advance the index.

matchPrimary(minPrec?: number): Expression<T>
minPrec: number

interface ScannermatchRequiredLatexArgument

matchRequiredLatexArgument(): Expression<T>

interface ScannermatchSign

If the next token matches a + or - sign, return it and advance the index. Otherwise return '' and do not advance

matchSign(): string

interface ScannermatchSignedInteger

matchSignedInteger(): string

interface ScannermatchSupsub

matchSupsub(lhs: Expression<T>): Expression<T>
lhs: Expression<T>

interface ScannermatchTabular

matchTabular(): Expression<T>

interface ScannermatchWhile

matchWhile(targets: string[]): string[]
targets: string[]

interface Scannernext

Return the next token and advance the index

next(): string

interface ScannerskipSpace

If there are any space, advance the index until a non-space is encountered

skipSpace(): boolean

interface ScannerScanner.atEnd


interface ScannerScanner.index


interface ScannerScanner.onError


interface ScannerScanner.options


interface ScannerScanner.peek


Return the next token, without advancing the index

interface Serializer

interface SerializerwrapShort

Add a group fence around the expression if it is short (not a function)

wrapShort(expr: Expression<T>): string
expr: Expression<T>

interface SerializerwrapString

wrapString(s: string, style: "paren" | "leftright" | "big" | "none"): string
s: string
  • | "paren"
  • | "leftright"
  • | "big"
  • | "none"

interface SerializerSerializer.level


“depth” of the expression:

  • 0 for the root
  • 1 for the arguments of the root
  • 2 for the arguments of the arguments of the root
  • etc…

This allows for variation of the Latex serialized based on the depth of the expression, for example using \Bigl( for the top level, and \bigl( or ( for others.

interface SerializerSerializer.onError


interface SerializerSerializer.options


interface SerializerSerializer.serialize

(expr: Expression<T>): string

Output a Latex string representing the expression

interface SerializerSerializer.wrap

(expr: Expression<T>, prec?: number): string

Add a group fence around the expression if it is an operator of precedence less than or equal to prec.

class LatexSyntax

To customize the parsing and serializing of Latex syntax, create a LatexSyntax instance.

class LatexSyntaxnew LatexSyntax

class LatexSyntaxparse

parse(latex: string): Expression<T>
latex: string

class LatexSyntaxserialize

serialize(expr: Expression<T>): string
expr: Expression<T>

class LatexSyntaxgetDictionary

Return a Latex dictionary suitable for the specified category, or "all" for all categories ("arithmetic", "algebra", etc…).

A Latex dictionary is needed to translate between Latex and MathJSON.

Each entry in the dictionary indicate how a Latex token (or string of tokens) should be parsed into a MathJSON expression.

For example an entry can define that the \pi Latex token should map to the symbol "Pi", or that the token - should map to the function ["Negate",...] when in a prefix position and to the function ["Subtract", ...] when in an infix position.

Furthermore, the information in each dictionary entry is used to serialize the Latex string corresponding to a MathJSON expression.

Use the value returned by this function to the options argument of the constructor.

getDictionary(domain?: DictionaryCategory | "all"): readonly LatexDictionaryEntry<any>[]
readonly LatexDictionaryEntry<any>[]



<T extends number> = LatexDictionaryEntry<T>[]


Maps a string of Latex tokens to a function or symbol and vice-versa.

<T extends number> =
arguments: "group" | "implicit" | "";

If trigger is `‘symbol’``. Indicate if this symbol can be followed by arguments. The presence of arguments will indicate that the arguments should be applied to the symbol. Otherwise, the invisible operator is applied to the symbol and the arguments.

If arguments is "group":

“f(x)” -> ["f", "x"] “f x” -> ["multiply", "f", "x"]

If arguments is "":

“f(x)” -> ["multiply", "f", ["group", "x"]] “f x” -> ["multiply", "f", "x"]

If arguments is "group/primary" and the symbol is followed either by a group or by a primary (prefix + symbol + subsupfix + postfix). Used for trig functions. i.e. \sin x vs \sin(x):

“f(x)” -> ["f", "x"] “f x” -> ["f", "x"]

associativity: "right" | "left" | "non" | "both";

If trigger is `‘infix’``

  • both: a + b + c -> +(a, b, c)
  • left: a / b / c -> /(/(a, b), c)
  • right: a = b = c -> =(a, =(b, c))
  • non: a < b < c -> syntax error
  • a both-associative operator has an unlimited number of arguments
  • a left, right or non associative operator has at most two arguments
closeFence: LatexToken | LatexToken[];
name: string;

Map a function or symbol name to this record.

Each record should have at least a name or a trigger

optionalLatexArg: number;

If trigger is `‘symbol’``.

If a Latex command (i.e. the trigger starts with \, e.g. \sqrt) indicates the number of optional arguments expected (indicate with square brackets).

For example, for the \sqrt command, 1: \sqrt[3]{x}

parse: Expression<T> | ParserFunction<T>;

A function that returns an expression, or an expression

precedence: number;

If trigger is `‘infix’``

requiredLatexArg: number;

If trigger is `‘symbol’``.

If a Latex command (i.e. the trigger starts with \, e.g. \frac) indicates the number of required arguments expected (indicated with curly braces).

For example, for the \frac command, 2: \frac{1}{n}

separator: LatexString;

If trigger is `‘matchfix’``.

serialize: SerializerFunction<T> | LatexString;

The Latex to serialize.

trigger: LatexToken | {environment: string; infix: LatexToken | LatexToken[]; matchfix: LatexToken | LatexToken[]; postfix: LatexToken | LatexToken[]; prefix: LatexToken | LatexToken[]; subfix: LatexToken | LatexToken[]; superfix: LatexToken | LatexToken[]; symbol: LatexToken | LatexToken[]};

Map one or more latex tokens to this record.

As a shortcut, if the trigger is a LatexToken, it is assumed to be a symbol.

There can be multiple entries (for example ‘+’ is both an infix and a prefix)




  • | string
  • | "<{>"
  • | "<}>"
  • | ""
  • | "<$>"
  • | "<$$>"


beginExponentMarker: string;
beginRepeatingDigits: string;
decimalMarker: string;

A string representing the decimal marker, the string separating the whole portion of a number from the fractional portion, i.e. the ‘.’ in ‘3.1415’.

Default: "."

endExponentMarker: string;
endRepeatingDigits: string;
exponentProduct: string;
groupSeparator: string;

A string representing the separator between groups of digits, used to improve readability of numbers with lots of digits.

Default: ","

imaginaryNumber: string;
negativeInfinity: string;
notANumber: string;
notation: "engineering" | "auto" | "scientific";
positiveInfinity: string;
precision: number;
truncationMarker: string;


idempotentCommands: LatexToken[];

When one these commands is encountered, its argument is parsed, as if the command was not present.

Useful for some presentational commands such as \left, \bigl, etc…

ignoreCommands: LatexToken[];

When one of these commands is encountered, it is skipped.

Useful for purely presentational commands such as \displaystyle

invisibleOperator: string;

If a symbol follows a number, consider them separated by this invisible operator.

Default: "Multiply"

invisiblePlusOperator: string;

If this setting is not empty, when a number is immediately followed by a fraction, assume that the fraction should be added to the number, that is that there is an invisible plus operator between the two.

For example with 2\frac{3}{4}:

  • when invisiblePlusOperator is "add" : ["add", 2, ["divide", 3, 4]]
  • when invisiblePlusOperator is "": ["multiply", 2, ["divide", 3, 4]]
parseArgumentsOfUnknownLatexCommands: boolean;

When an unknown latex command is encountered, attempt to parse any arguments it may have.

For example, \foo{x+1} would produce ['\foo', ['add', 'x', 1]] if this property is true, ['latex', '\foo', '<{>', 'x', '+', 1, '<{>'] otherwise.

parseNumbers: boolean;

When a number is encountered, parse it.

Otherwise, return each token making up the number (minus sign, digits, decimal separator, etc…)

preserveLatex: boolean;

If true, the expression will be decorated with the Latex fragments corresponding to each elements of the expression

promoteUnknownFunctions: RegExp;

When a token is encountered at a position that could match a function call, and it is followed by an apply function operator (typically, parentheses), consider them to a be a function if the string of tokens match this regular expression.

While this is a convenient shortcut, it is recommended to more explicitly define custom functions by providing an entry for them in a function dictionary (providing additional information about their arguments, etc…) and in a Latex translation dictonary (indicating what Latex markup corresponds to the function).


By default, f(x) is parsed as [“multiply”, “f”, “x”].


     promoteUnknownFunctions = /^[fg]$/

f(x) is parsed as [“f”, “x”]

promoteUnknownSymbols: RegExp;

When a token is encountered at a position where a symbol could be parsed, if the token matches promoteUnknownSymbols it will be accepted as a symbol (an unknown-symbol error will still be triggered so that the caller can be notified). Otherwise, the symbol is rejected.

skipSpace: boolean;

If true, ignore space characters.


Custom parser function.

It is triggered by a latex fragment (the latex argument). When invoked, the scanner points right after that latex fragment. The scanner should be moved, by calling for every consumed token.

If it was in an infix or postfix context, lhs will represent the left-hand side argument. In a prefix or matchfix context, lhs is null.

The function should return a tuple:

  • Its first element is an unprocessed left-hand side, if any. If the left-hand-side has been consumed (for example if this was a valid infix operator), the first element of the tuple should be null.

  • Its second element is the resulting expression.

<T extends number> = (lhs: Expression<T> | "null", scanner: Scanner<T>, minPrec: number): [lhs: Expression<T> | "null", result: Expression<T> | "null"]


invisibleMultiply: LatexString;

Latex string used to render an invisible multiply, e.g. in ‘2x’. Leave it empty to join the adjacent terms, or use \cdot to insert a \cdot operator between them, i.e. 2\cdot x.

Empty by default.

invisiblePlus: LatexString;

Latex string used for an invisible plus, e.g. in ‘1 3/4’. Leave it empty to join the main number and the fraction, i.e. render it as 1\frac{3}{4}, or use + to insert a + operator between them, i.e. 1+\frac{3}{4}

Empty by default.

multiply: LatexString;

Latex string used for an explicit multiply operator,

Default: \times


<T extends number> = (serializer: Serializer<T>, expr: T | Expression<T>): string
Documentation built with grok