Skip to content
Talk to an engineerRequest access

Finding math in text

MathScanner splits chat or Markdown text into text and formula segments — delimiters, prices, code, environments and streaming.

MathScanner finds formulas in text, like KaTeX’s auto-render, in pure Dart. MathText is built on it; use it directly when you render text yourself, for example in your own Markdown renderer. scan splits a string into TextSegments and MathSegments.

import 'package:val_latex/val_latex.dart';
void main() {
const scanner = MathScanner();
final segments = scanner.scan(r'Area $\pi r^2$ and $$x^2$$. It costs $5.');
for (final segment in segments) {
switch (segment) {
case TextSegment(:final text):
print('text: $text');
case MathSegment(:final tex, :final display):
print('${display ? 'display' : 'inline'} math: $tex');
}
}
}
text: Area
inline math: \pi r^2
text: and
display math: x^2
text: . It costs $5.
  • Delimiters are tried in the order given (MathDelimiter.standard: $$…$$, \[…\], \(…\), $…$, and \\[…\\], \\(…\\) for text whose backslashes were escaped twice). An inline formula must close before a blank line.
  • Prices stay text (Pandoc’s rule): the opening $ is followed by a non-space, the closing $ is preceded by a non-space and not followed by a digit. It costs $5 while $x$ is unknown finds x. \$ is a literal dollar sign. spacedDollars: true also accepts $ x + y $.
  • Environments (environments: true, the default): bare \begin{align}…\end{align} and the others in mathEnvironments are display math without delimiters.
  • Markdown (markdown: true, the default): code spans, fenced and indented code blocks and HTML comments are skipped, and display math opened in a block quote (> $$) drops the > markers from its later lines.
  • Streaming (streaming: true): a formula still open at the end of the text is returned as a MathSegment with complete: false, and a dangling opening delimiter is withheld. An open $ followed by a digit stays text until what follows is clearly math.

Each MathSegment has the tex between the delimiters (the whole \begin…\end for an environment), display, the open and close delimiters as written, complete, and its span in the input.

Finds formulas in text (like KaTeX’s auto-render, in pure Dart).

More about MathScanner
  • Delimiters are tried in the order given; a closing delimiter must come before a blank line for inline math.
  • \$ is a literal dollar sign; \\$ is a backslash and then a $ that may open math (an even run of backslashes escapes no $).
  • $ follows Pandoc’s rule so prices are not math: the opening $ must be followed by a non-space, the closing $ preceded by a non-space and not followed by a digit ($5 and $10 stays text). spacedDollars lifts the space rule.
  • Inline $…$ never contains a $ that could open a formula itself: such a $ (one followed by a non-space) ends the attempt, and the reader’s pairing wins. It costs $5 while $x$ is unknown finds x, not 5 while $x.
  • $a$$b$ is two formulas; a $$ that opens nothing ($$x$) is text, not a stray $ before an inline formula.
  • With markdown, code is skipped: code spans, fenced code blocks (``` and ~~~; an unclosed fence runs to the end, as in CommonMark), indented code blocks (4 spaces or a tab after a blank line, unless the paragraph before is a list item or indented, where the indent is list content) and HTML comments. Display math opened inside a block quote (> $$) drops the > markers from its later lines.
  • With streaming, a formula still open at the end of the text is returned as an incomplete MathSegment instead of as text, and a dangling opening delimiter is withheld rather than shown. An open $ followed by a digit stays text (a price) until what follows is clearly math: a command, ^, _, = or a brace. With markdown, a code span or HTML comment not yet closed hides the rest of the text as code until it closes.
Constructor Description
MathScanner({…}) Creates a scanner.
MathScanner: more
const MathScanner({
this.delimiters = MathDelimiter.standard,
this.environments = true,
this.markdown = true,
this.streaming = false,
this.spacedDollars = false,
})
Field Type Default Description
delimiters List<MathDelimiter> MathDelimiter.standard Delimiter pairs, tried in order at each position.
environments bool true Recognise \begin{equation}…\end{equation} and friends without delimiters.
markdown bool true Skip Markdown code (spans, fenced and indented blocks) and HTML comments; strip block-quote markers inside display math.
streaming bool false Treat text ending inside a formula as an incomplete formula.
spacedDollars bool false Accept spaces just inside $…$ ($ x + y $), as KaTeX’s auto-render does. Off by default: with it, $ 5 and $ is a formula, so prose with prices needs \$. Prices like $5 and $10 stay text either way (a closing $ is never followed by a digit).
Member Type Description
scan(String text) List<Segment> Splits text into text and math segments.

A pair of math delimiters.

Constructor Description
MathDelimiter(open, close, {required display}) Creates a delimiter pair.
Field Type Default Description
open String required Opening string.
close String required Closing string.
display bool required Whether the math is display math.
Member Type Description
static standard $$…$$, \[…\], \(…\), $…$: the delimiters KaTeX’s auto-render and most Markdown/LLM output use; and \\[…\\], \\(…\\), the same delimiters with their backslash doubled, as text that went through JSON escaping twice has them.
standard: more

Inside doubled delimiters every backslash run is halved when all of them have even length (\\frac is \frac); a single backslash anywhere means the inside was not escaped twice, and it is kept as written.

A piece of mixed text: plain text or a formula.

Field Type Default Description
span SourceSpan Where the segment is in the scanned string (delimiters included for math).

Plain text between formulas.

Constructor Description
TextSegment(span, text) Creates a text segment.
Field Type Default Description
text String required The text, with \$ unescaped to $.

A formula found in text.

Constructor Description
MathSegment(span, tex, {…}) Creates a math segment.
MathSegment: more
const MathSegment(
super.span,
this.tex, {
required this.display,
required this.open,
required this.close,
this.complete = true,
})
Field Type Default Description
tex String required The TeX source between the delimiters (for environments, the whole \begin…\end).
display bool required Display math ($$…$$, \[…\], environments) rather than inline.
open String required The opening delimiter as written.
close String required The closing delimiter (empty when complete is false).
complete bool true False when the text ended before the closing delimiter (streaming).

Environments recognised as display math without delimiters.

const Set<String> mathEnvironments = {
'equation', 'equation*', 'align', 'align*', 'alignat', 'alignat*', //
'gather', 'gather*', 'multline', 'multline*', 'flalign', 'flalign*',
'eqnarray', 'eqnarray*', 'xalignat', 'xalignat*', 'xxalignat', 'CD',
'displaymath', 'math',
// Math-only environments (amsmath, mathtools) that chat replies often
// write bare, without `$$` around them.
'aligned', 'alignedat', 'gathered', 'split', 'multlined', //
'array', 'darray', 'cases', 'cases*', 'dcases', 'dcases*', 'rcases',
'rcases*', 'drcases', 'drcases*', 'matrix', 'matrix*', 'pmatrix',
'pmatrix*', 'bmatrix', 'bmatrix*', 'Bmatrix', 'Bmatrix*', 'vmatrix',
'vmatrix*', 'Vmatrix', 'Vmatrix*', 'smallmatrix', 'smallmatrix*',
// Text tables, which chat replies often write bare.
'tabular', 'tabular*', 'tabularx', 'longtable', 'table', 'table*',
'subequations',
// Lists, likewise.
'itemize', 'enumerate', 'description',
};