Skip to content
Talk to an engineerRequest access

Parsing

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

\gdef (or globalGroup: true) into one table from newMacroTable(), and pass that table to every parseLatex call that should see the definitions:

final macros = newMacroTable();
parseLatex(r'\gdef\RR{\mathbb{R}}', macros: macros);
final result = parseLatex(r'f \colon \RR^n \to \RR', macros: macros);
print(result.hasErrors); // false

Parses LaTeX math source.

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.

ParseResult parseLatex(
String source, {
ParseOptions options = const ParseOptions(),
MacroTable? macros,
})

A macro table preloaded with the built-in macros, for sharing definitions across parseLatex calls.

MacroTable newMacroTable()

Options that affect parsing. Layout options live elsewhere.

Constructor Description
ParseOptions({…}) Creates parse options. Every default is safe for untrusted input.
ParseOptions: more
const ParseOptions({
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 = const PhysicsOptions(),
})
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 outcome of parsing one formula.

Constructor Description
ParseResult({…}) Creates a result.
ParseResult: more
ParseResult({
required this.source,
required this.root,
required this.diagnostics,
this.tag,
this.label,
this.noNumber = false,
this.incomplete = false,
this.tagForm,
})
Field Type Default Description
source SourceText required 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.

mathtools’ \newtagform{name}[format]{left}{right}.

Constructor Description
TagForm(name, left, right, {format}) Creates a tag form.
Field Type Default Description
name String required Its name.
left RowNode required Text before the number.
right RowNode required Text after the number.
format String? The text font command applied to the number (\textbf), if any.

A problem found while parsing.

Constructor Description
Diagnostic({…}) Creates a diagnostic.
Diagnostic: more
const Diagnostic({
required this.code,
required this.message,
required this.span,
this.severity = Severity.error,
})
Field Type Default Description
code String required Stable machine-readable identifier, e.g. undefinedControlSequence.
message String required Human-readable description.
span SourceSpan required Where in the normalized source the problem is.
severity Severity Severity.error How serious it is.
Member Type Description
format(String source) String The message with a caret excerpt of source under the span.

How serious a Diagnostic is.

Value Description
warning Input LaTeX would reject but we accept (non-strict behaviour).
error Input that could not be understood; an error node marks the spot.

Thrown by parseLatex only when ParseOptions.throwOnError is set.

Constructor Description
LatexParseException(diagnostic) Creates an exception for diagnostic.
Field Type Default Description
diagnostic Diagnostic required The first error found.

What to do with input LaTeX would reject but we can still handle.

Value Description
ignore Accept silently.
warn Accept and record a warning diagnostic.
error Treat as an error.

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).
Member Type Description
static defaults = {mhchem, siunitx} The extensions enabled by default.

The physics package’s options (\usepackage[…]{physics}), for ParseOptions.physics.

Constructor Description
PhysicsOptions({trig = true, italicDiff = false, arrowDel = false}) Creates options; the defaults are the package’s.
Field Type Default Description
trig bool true trig (default) / notrig: \sin, \cos… take automatically sized brackets (\sin(x), \sin[2](x)).
italicDiff bool false italicdiff / uprightdiff (default): the differential d of \dd, \dv, \pdv… is italic.
arrowDel bool false arrowdel / bolddel (default): \grad, \div, \curl use an arrowed rather than a bold nabla.

A request to use a feature gated by ParseOptions.trust.

Constructor Description
TrustContext({required command, url, protocol, span}) Creates a trust request.
Field Type Default Description
command String required The command asking, e.g. \href.
url String? The URL involved, if any.
protocol String? The URL’s protocol in lower case (https, mailto, _relative).
span SourceSpan? Where the command is.

Macro definitions with TeX group scoping.

More about MacroTable

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.

Constructor Description
MacroTable([Map<String, MacroDefinition>? builtins]) 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).
set(String name, MacroDefinition? definition, {…}) void Sets name to definition (null undefines it).
state(String key) Object? The value of state key (a register, a counter…), or null when it was never set.
setState(String key, Object? value, {bool global = false}) void Sets state key to value (null removes it), until the end of the current group unless global.
hasState bool Whether any state was ever set: lets callers skip state lookups on formulas that use none.
beginGroup() void Opens a group.
endGroup() void Closes the innermost group, undoing its local definitions.
endAllGroups() void Closes every open group.
depth int Number of open groups.
set: more
void set(String name, MacroDefinition? definition, {bool global = false})