mathjson

Functions

Parse a Latex string and return a corresponding MathJSON expression.

Serialize a MathJSON expression as a Latex string.

applyInvisibleOperator(lhs: Expression, rhs: Expression): Expression
lhs: Expression
rhs: Expression
Expression

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

Return a latex string after the index

latexAfter(): string
string

Return a latex string before the index

latexBefore(): string
string

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

string[]

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

match(target: string): boolean
target: string
boolean

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

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

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

matchDecimalDigits(): string
string

matchExponent(): string
string

Parse an expression:

::= |||

Stop when an operator of precedence less than minPrec is encountered

minPrec is 0 by default.

matchExpression(minPrec?: number): Expression
minPrec: number
Expression

matchNumber(): string
string

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
Expression

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

:=

::= |[‘,’]

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

matchPrimary(minPrec?: number): Expression
minPrec: number
Expression

matchRequiredLatexArgument(): Expression
Expression

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

matchSign(): string
string

matchSignedInteger(): string
string

matchSupsub(lhs: Expression): Expression
lhs: Expression
Expression

matchTabular(): Expression
Expression

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

Return the next token and advance the index

next(): string
string

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

skipSpace(): boolean
boolean

boolean

number

ErrorListener<ErrorCode>

Required<ParseLatexOptions>

string

Return the next token, without advancing the index

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

wrapShort(expr: Expression): string
expr: Expression
string

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

number

“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.

ErrorListener<ErrorCode>

Required<SerializeLatexOptions>

(expr: Expression): string

Output a Latex string representing the expression

(expr: Expression, prec?: number): string

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

For best performance when calling repeatedly parse() or serialize(), create an instance of LatexSyntax and call its methods. The constructor of LatexSyntax will compile and optimize the dictionary so that calls of the parse() and serialize() methods will bypass that step. By contrast invoking the parse() and serialize() functions will compile the dictionary each time they are called.

parse(latex: string): Expression
latex: string
Expression

serialize(expr: Expression): string
expr: Expression
string

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 token \pi 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?: "algebra" | "arithmetic" | "calculus" | "collections" | "complex" | "combinatorics" | "core" | "dimensions" | "domains" | "inequalities" | "intervals" | "linear-algebra" | "logic" | "numeric" | "other" | "physics" | "polynomials" | "relations" | "rounding" | "statistics" | "symbols" | "transcendentals" | "trigonometry" | "units" | "all"): readonly LatexDictionaryEntry[]
domain:
• | "algebra"
• | "arithmetic"
• | "calculus"
• | "collections"
• | "complex"
• | "combinatorics"
• | "core"
• | "dimensions"
• | "domains"
• | "inequalities"
• | "intervals"
• | "linear-algebra"
• | "logic"
• | "numeric"
• | "other"
• | "physics"
• | "polynomials"
• | "relations"
• | "rounding"
• | "statistics"
• | "symbols"
• | "transcendentals"
• | "trigonometry"
• | "units"
• | "all"

Types

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

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| ParserFunction;

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

• | string
• | "<{>"
• | "<}>"
• | ""
• | "<$>" • | "<$$>" NumberFormattingOptionsPermalink 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; ParseLatexOptionsPermalink 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). Example: By default, f(x) is parsed as [“multiply”, “f”, “x”]. After…  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 promoteUnknwonSymbols 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 scanner.next() 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 whose 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.

The second element is the resulting expression.

(lhs: Expression| "null", scanner: Scanner, minPrec: number): [lhs: Expression| "null", result: Expression| "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

Documentation built with grok