mathjson
Functions
parsePermalink
Parse a Latex string and return a corresponding MathJSON expression.
- latex: LatexString
- options:
- NumberFormattingOptions &
- ParseLatexOptions &
- onError: ErrorListener<ErrorCode>;
- → Expression
serializePermalink
Serialize a MathJSON expression as a Latex string.
- expr: Expression
- options:
- NumberFormattingOptions &
- SerializeLatexOptions &
- dictionary: Readonly<LatexDictionary>;
- onError: ErrorListener<ErrorCode>;
- → LatexString
interface ScannerPermalink
- applyInvisibleOperator
- applyOperator
- latexAfter
- latexBefore
- lookAhead
- match
- matchAny
- matchArguments
- matchBalancedExpression
- matchDecimalDigits
- matchExponent
- matchExpression
- matchNumber
- matchOptionalLatexArgument
- matchPrimary
- matchRequiredLatexArgument
- matchSign
- matchSignedInteger
- matchSupsub
- matchTabular
- matchWhile
- next
- skipSpace
interface ScannerapplyInvisibleOperatorPermalink
- lhs: Expression
- rhs: Expression
- → Expression
interface ScannerapplyOperatorPermalink
- op: string
- lhs: Expression
- rhs: Expression
- → [Expression, Expression]
interface ScannerlatexAfterPermalink
Return a latex string after the index
- → string
interface ScannerlatexBeforePermalink
Return a latex string before the index
- → string
interface ScannerlookAheadPermalink
Return an array of string corresponding to tokens ahead. The index is unchanged.
- → string[]
interface ScannermatchPermalink
If the next token matches the target advance and return true. Otherwise return false
- target: string
- → boolean
interface ScannermatchAnyPermalink
- targets: string[]
- → string
interface ScannermatchArgumentsPermalink
- kind:
- | ""
- | "group"
- | "implicit"
- → Expression[]
interface ScannermatchBalancedExpressionPermalink
- open: string
- close: string
- onError: ErrorListener<ErrorCode>
- → Expression
interface ScannermatchDecimalDigitsPermalink
- → string
interface ScannermatchExponentPermalink
- → string
interface ScannermatchExpressionPermalink
Parse an expression:
Stop when an operator of precedence less than minPrec
is encountered
minPrec
is 0 by default.
- minPrec: number
- → Expression
interface ScannermatchNumberPermalink
- → string
interface ScannermatchOptionalLatexArgumentPermalink
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
interface ScannermatchPrimaryPermalink
If not a primary, return null
and do not advance the index.
- minPrec: number
- → Expression
interface ScannermatchRequiredLatexArgumentPermalink
interface ScannermatchSignPermalink
If the next token matches a +
or -
sign, return it and advance the index. Otherwise return ''
and do not advance
- → string
interface ScannermatchSignedIntegerPermalink
- → string
interface ScannermatchSupsubPermalink
- lhs: Expression
- → Expression
interface ScannermatchTabularPermalink
interface ScannermatchWhilePermalink
- targets: string[]
- → string[]
interface ScannernextPermalink
Return the next token and advance the index
- → string
interface ScannerskipSpacePermalink
If there are any space, advance the index until a non-space is encountered
- → boolean
interface ScannerScanner.atEndPermalink
booleaninterface ScannerScanner.indexPermalink
numberinterface ScannerScanner.onErrorPermalink
ErrorListener<ErrorCode>interface ScannerScanner.optionsPermalink
Required<ParseLatexOptions>interface ScannerScanner.peekPermalink
stringReturn the next token, without advancing the index
interface SerializerPermalink
interface SerializerwrapShortPermalink
Add a group fence around the expression if it is short (not a function)
- expr: Expression
- → string
interface SerializerwrapStringPermalink
- s: string
- style:
- | "paren"
- | "leftright"
- | "big"
- | "none"
- → string
interface SerializerSerializer.levelPermalink
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.
interface SerializerSerializer.onErrorPermalink
ErrorListener<ErrorCode>interface SerializerSerializer.optionsPermalink
Required<SerializeLatexOptions>interface SerializerSerializer.serializePermalink
(expr: Expression): stringOutput a Latex string representing the expression
interface SerializerSerializer.wrapPermalink
(expr: Expression, prec?: number): stringAdd a group fence around the expression if it is an operator of precedence less than or equal to prec
.
class LatexSyntaxPermalink
For best performance when calling repeatedly Return a Latex dictionary suitable for the specified category, or 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 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 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.class LatexSyntaxnew LatexSyntaxPermalink
class LatexSyntaxparsePermalink
class LatexSyntaxserializePermalink
class LatexSyntaxgetDictionaryPermalink
"all"
for all categories ("arithmetic"
, "algebra"
, etc…).\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.options
argument of the constructor.
Types
LatexDictionaryPermalink
LatexDictionaryEntryPermalink
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
ornon
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 atrigger
- 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)
LatexStringPermalink
LatexTokenPermalink
- | 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]]
- when
- 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 (anunknown-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.
ParserFunctionPermalink
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.
SerializeLatexOptionsPermalink
- 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
SerializerFunctionPermalink
grok