parseLatex and its options — the result tree, diagnostics, streaming, macros, extensions and the limits for untrusted input.
parseLatex turns a string into a ParseResult. It does not throw for bad
input: problems become error nodes in the tree and entries in diagnostics.
final result =parseLatex(r'\frac{a}{b} + \sqrt{x}');
print(result.hasErrors); // false
print(result.dump()); // the node tree, as an s-expression
ParseResult member
What it is
root
The top-level row of nodes. Every node carries its span in the source; Parse tree lists every node class.
diagnostics
Every problem found, warnings and errors.
errors, hasErrors
The errors only, and whether there are any.
incomplete
The input ended before something was finished — normal while text streams in.
idOf, pathTo, nodeById
Stable node ids, and the way back from an id to its node.
source, originalSpan
The normalised source the spans point into, and the map back to your string.
Spans are offsets into the normalised source: line endings become \n
and the text is put in Unicode NFC. For ASCII input without \r they are
offsets into your string; otherwise map them back with
result.originalSpan(span).
The full list, with defaults, is in the API reference below.
The ones you will reach for:
streaming — see above.
trust, trustCallback and the max… limits, timeBudget — for
input you do not control; see Errors and untrusted input.
throwOnError, strict, strictCallback — how mistakes and
non-strict input are reported; see Diagnostics.
macros, globalGroup — predefined macros, and whether top-level
definitions escape the formula; see Macros.
extensions, physics — the optional command sets (mhchem and
siunitx on, physics off); see Supported LaTeX.
colorIsTextColor — make \color take a body argument, like
\textcolor, as some older renderers did.
captionLabel — number \captions in tables ('Table').
ParseOptions.displayMode is not read by the parser: a source parses to the
same tree either way. Display style is a layout choice
(LayoutOptions.displayMode).
Never throws for bad input unless ParseOptions.throwOnError is set:
problems become error nodes plus ParseResult.diagnostics. Pass one
macros table to several calls to share \gdef/\newcommand
definitions between formulas; create it with newMacroTable.
Options that affect parsing. Layout options live elsewhere.
Constructor
Description
ParseOptions({…})
Creates parse options. Every default is safe for untrusted input.
ParseOptions: more
constParseOptions({
this.displayMode =false,
this.throwOnError =false,
this.strict =Strict.warn,
this.strictCallback,
this.trust =false,
this.trustCallback,
this.macros =const {},
this.globalGroup =false,
this.colorIsTextColor =false,
this.maxExpand =1000,
this.maxTokens =500000,
this.maxNesting =128,
this.maxNodes =100000,
this.maxSize =double.infinity,
this.timeBudget,
this.streaming =true,
this.extensions =LatexExtension.defaults,
this.captionLabel,
this.physics =constPhysicsOptions(),
})
Field
Type
Default
Description
displayMode
bool
false
Display math ($$…$$) rather than inline ($…$), as the caller means it. The parser does not read it: a source parses to the same tree either way, and display style is chosen at layout (LayoutOptions.displayMode).
throwOnError
bool
false
Throw LatexParseException on the first error instead of producing an error node. Off by default: the formula always renders.
strict
Strict
Strict.warn
How to treat non-strict input when strictCallback is null.
strictCallback
Strict Function(String code, String message)?
Per-case decision for non-strict input: receives the diagnostic code and message and returns the level to apply.
trust
bool
false
Whether untrusted commands (\href, \url, \includegraphics, \htmlClass…) are allowed when trustCallback is null.
trustCallback
bool Function(TrustContext context)?
Per-case decision for untrusted commands.
macros
Map<String, String>
const {}
Extra macros: name (with backslash) to replacement text. #1…#9 are arguments; the argument count is inferred from the highest #n.
globalGroup
bool
false
Whether definitions made with \def/\newcommand at top level escape the formula (see MacroTable for sharing across formulas).
colorIsTextColor
bool
false
Whether \color behaves like \textcolor (takes a body argument).
maxExpand
int
1000
Maximum number of macro expansions before giving up.
maxTokens
int
500000
Maximum number of tokens macro expansion may produce in one parse, all expansions together (TeX’s equivalent is its main memory). maxExpand counts expansions, not their size: a definition that doubles its argument (\def\a#1{\a{#1#1}}) or itself (\edef\b{\b\b}) grows exponentially in a few dozen expansions. Past the limit the parse stops with a maxTokens error, like the other limits.
maxNesting
int
128
Maximum depth of nested groups, arguments and environments.
maxNodes
int
100000
Maximum number of AST nodes.
maxSize
double
double.infinity
Largest dimension (in em) accepted for sizes such as \rule; larger values are clamped.
timeBudget
Duration?
Wall-clock budget for one parse. Null means unlimited.
streaming
bool
true
Treat unfinished input at the end of the source (unclosed groups, environments, \left, a half-typed command) as incomplete rather than as errors. Right for text that is still arriving.
extensions
Set<LatexExtension>
LatexExtension.defaults
Optional command sets to enable.
captionLabel
String?
When set, \caption numbers its tables as LaTeX does: “Table 1: …” with this word (“Table”, or a translation). Null (the default) leaves captions unnumbered, as fits a formula shown on its own.
physics
PhysicsOptions
const PhysicsOptions()
The physics package’s options, when LatexExtension.physics is on.
Member
Type
Description
strictFor(String code, String message)
Strict
The effective strict level for code.
isTrusted(TrustContext context)
bool
Whether context is trusted.
withStreaming(bool value)
ParseOptions
These options with streaming set to value (this object when it already is). The copy does not carry maxTokens over: it has the default.
operator ==(Object other)
bool
Equal when every option is (callbacks by identity), so options written inline in a build method still find cached parses.
The source, with the map back to the caller’s string.
root
RowNode
required
The formula.
diagnostics
List<Diagnostic>
required
Problems found, in source order of discovery.
tag
TagNode?
\tag of the formula (outside any environment), if any.
label
String?
\label of the formula, if any.
tagForm
TagForm?
mathtools’ \usetagform in force at the end of the formula: how its equation numbers, \tags and \eqrefs are drawn. Null: (1).
noNumber
bool
false
\notag / \nonumber was used outside any environment.
incomplete
bool
false
The input ended before something was finished (an unclosed group, environment or \left, a missing argument, a half-typed command). Normal while text is still streaming in.
Member
Type
Description
hasErrors
bool
Whether any diagnostic is an error.
errors
Iterable<Diagnostic>
The errors only.
dump()
String
The tree as an s-expression (see MathNode.dump).
idOf(MathNode node)
String
A stable identifier for node.
pathTo(String id)
List<MathNode>
The nodes from the root down to the node with id (see idOf), inclusive; empty when no node has that id.
nodeById(String id)
MathNode?
The node with id, or null.
originalSpan(SourceSpan span)
SourceSpan
Maps span (into the normalized source) back to the original string.
idOf: more
Ids are built from node kind and source position, so a node keeps its
id when more input is appended after it (streaming) and when the same
source is parsed again. Throws if node is not in this tree.
Optional command sets, enabled through ParseOptions.extensions.
Value
Description
mhchem
Chemistry: \ce, \pu (mhchem).
siunitx
Numbers and units: \num, \si, \SI, \qty, \unit, \ang, ranges and lists (a siunitx subset).
physics
Physics notation: \abs, \norm, \qty, \dv, \pdv, \expval, \mel, \comm, \vb, \grad… (physics package subset). Off by default: like the package, it redefines \div, \Re, \Im and (over siunitx) \qty. Its other commands work without it, wherever nothing else defines them (LatexCatalog.fallbacks).
Local definitions are undone at the end of the group that made them;
global ones (\gdef, \global) survive. Reuse one table across several
parses to share definitions between formulas.
Creates a table. builtins are consulted when no definition is set.
Member
Type
Description
extensions
Map<String, MacroDefinition>
Macros of the enabled extensions, consulted after definitions and before _builtins. Set by the parser from its options.
fallbacks
Map<String, MacroDefinition>
Common package commands (\abs, \sgn, \sfrac…), consulted last. They give a meaning to a name nothing else defines, but do not count as defined: \newcommand{\abs} defines it without a warning, as in a document that does not load the package. Set by the parser.
operator [](String name)
MacroDefinition?
The current meaning of name, or null.
has(String name)
bool
Whether name currently has a meaning.
hasOwn(String name)
bool
Whether name has a meaning other than a fallback’s.
definedNames
Iterable<String>
Names currently given a meaning by definitions (not builtins).
hasUserDefinition(String name)
bool
Whether name was defined by the user (not a builtin).