Skip to content
Talk to an engineerRequest access

Speech, LaTeX and hit testing

Read a formula aloud, write it back as normalised LaTeX, map a point on the layout back to the source, and list what the parser knows.

toSpeech reads a formula as text, for screen readers and text-to-speech. Short structures read naturally; larger ones announce their parts and end, so a listener can follow nesting.

final result = parseLatex(r'\frac{a+1}{b}');
print(toSpeech(result));
// the fraction with numerator a plus 1 and denominator b end fraction
print(toSpeech(result, verbosity: SpeechVerbosity.brief));
// a plus 1 over b
Parameter Values
language SpeechLanguage.english (default) and arabic. spanish, french, german, portuguese, bengali and hindi are drafts, not yet checked by a native reader.
verbosity SpeechVerbosity.brief, normal (default), verbose.

The Flutter widgets use it for their screen-reader label; see Interaction and accessibility.

toLatex writes a parsed formula back as LaTeX. The output lays out the same as the input, but the text may differ: spacing is normalised, x² becomes x^{2}, colours become #rrggbb. With ascii: true, Unicode characters typed directly are written as their commands.

print(toLatex(parseLatex(r'x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}')));
// x=\frac{-b\pm\sqrt{b^{2}-4ac}}{2a}
print(toLatex(parseLatex('α ≤ x²'), ascii: true));
// \alpha\le x^{2}

Every display item records the node that produced it. hitTestLayout(layout, x, y) returns the MathHit under a point (in em, in the layout’s coordinates), preferring the smallest item, or null over empty space; hit.info.span is the node’s position in the source.

  • selectionUnits(result, layout) lists the formula’s top-level nodes with their painted rectangles.
  • deepSelectionUnits(result, layout) lists every atom, inside fractions, scripts and groups too.
  • mathParts(result) gives the navigable tree of parts — a fraction’s numerator and denominator, a root’s radicand — that keyboard navigation and screen readers walk.

LatexCatalog.instance lists every name the parser accepts, grouped by the table that defines it — for galleries, completion lists and documentation. It reads the parser’s own tables, so it cannot drift from what parses.

final catalog = LatexCatalog.instance;
print(catalog.allCommands.contains(r'\frac')); // true
print(catalog.environments.contains('align')); // true
print(catalog.extension(LatexExtension.physics).contains(r'\dv')); // true

Commands that exist only inside their environment (\arrow in tikzcd, the bussproofs commands in prooftree) are not in allCommands.

Speaks a formula as text for screen readers and text-to-speech.

Short structures read naturally (“x squared”, “a over b”); larger ones announce their parts (“the fraction with numerator … and denominator …, end fraction”) so the listener can follow nesting.

String toSpeech(
ParseResult result, {
SpeechLanguage language = SpeechLanguage.english,
SpeechVerbosity verbosity = SpeechVerbosity.normal,
})

A language for spoken math.

Value Description
english English (ClearSpeak-like phrasing).
arabic Arabic (Modern Standard Arabic school phrasing).
spanish Spanish. DRAFT: not yet checked by a native reader.
french French. DRAFT: not yet checked by a native reader.
german German. DRAFT: not yet checked by a native reader.
portuguese Portuguese. DRAFT: not yet checked by a native reader.
bengali Bengali, words after what they govern (postpositions). DRAFT: not yet checked by a native reader.
hindi Hindi, words after what they govern (postpositions). DRAFT: not yet checked by a native reader.

How much structure speech announces.

Value Description
brief Shortest: structures read inline (“a plus b over c”), no ends announced. For listeners who know the formula’s shape.
normal Short structures read naturally, larger ones announce their parts and end (the default).
verbose Every fraction, root and group announces its parts and end, for listeners following unfamiliar or deeply nested formulas.

Writes a parsed formula back as LaTeX.

The output parses to a formula that lays out the same as the input (same glyphs, same positions); it is not always the same text (spacing is normalised, x² becomes x^{2}, colours become #rrggbb).

With ascii, Unicode math characters typed directly (≤, ∑, α) are written as their commands (\le, \sum, \alpha), for tools that only read ASCII TeX.

String toLatex(ParseResult result, {bool ascii = false})

Writes one node as LaTeX (see toLatex).

String nodeToLatex(MathNode node)

The item under (x, y) em, preferring the smallest one; null when the point is on empty space.

MathHit? hitTestLayout(
MathLayout layout,
double x,
double y, {
double slop = 0.05,
})

What is under a point of a formula.

Constructor Description
MathHit(item, info) Creates a hit.
Field Type Default Description
item DisplayItem required The painted item.
info ItemInfo required Its source span, node id, classes and link.

The painted extent of item, in em.

EmRect itemBounds(DisplayItem item)

An axis-aligned rectangle in em (x right, y down, origin on the formula’s baseline at its left edge).

Constructor Description
EmRect(left, top, right, bottom) Creates a rectangle.
Field Type Default Description
left double required Left edge.
top double required Top edge (negative above the baseline).
right double required Right edge.
bottom double required Bottom edge.
Member Type Description
width double Width.
height double Height.
contains(double x, double y, {double slop = 0}) bool Whether (x, y) is inside, with slop em of tolerance.
union(EmRect o) EmRect The smallest rectangle containing both.

The formula’s top-level nodes with their painted rectangles, in source order. Nodes that paint nothing (spaces, \label) are left out.

List<SelectionUnit> selectionUnits(ParseResult result, MathLayout layout)

Every atom of the formula in reading order, those inside fractions, scripts and groups too, with their painted rectangles: finer units for selecting than selectionUnits. Nodes that paint nothing are left out.

List<SelectionUnit> deepSelectionUnits(ParseResult result, MathLayout layout)

The source a selection of units from lo to hi (exclusive) stands for: when its ends sit in different groups, each end widens to the whole structure that holds it in their common group, so the source parses on its own.

SourceSpan selectedSpan(List<SelectionUnit> units, int lo, int hi)

One selectable piece of a formula: a top-level node and where it is painted.

Constructor Description
SelectionUnit(node, rect, {chain = const []}) Creates a unit.
Field Type Default Description
node MathNode required The node.
rect EmRect required Where it is painted (union of its items).
chain List<MathNode> const [] For deepSelectionUnits: the atoms enclosing node, outermost (a top-level node) first, ending with node itself; each is an atom of a row inside the one before.
Member Type Description
span SourceSpan Its source.

The formula’s top-level parts, each with its nested parts. Unbraced rows are flattened; a braced group of one node is that node; spaces and breaks are left out.

List<MathPart> mathParts(ParseResult result)

A navigable part of a formula: a node and the parts inside it (a fraction’s numerator and denominator, a root’s radicand, a row’s atoms), for screen-reader trees and keyboard navigation.

Constructor Description
MathPart(node, children) Creates a part.
Field Type Default Description
node MathNode required The node.
children List<MathPart> required The parts inside, in source order.
Member Type Description
span SourceSpan Its source.

A half-open range [start, end) of UTF-16 offsets into the parsed source.

More about SourceSpan

Offsets are into the normalized source (SourceText.text); use SourceText.originalSpan to map back to the caller’s string.

Constructor Description
SourceSpan(start, end) Creates a span from start (inclusive) to end (exclusive).
SourceSpan.empty(int offset) An empty span at offset.
SourceSpan.between(int a, int b) The span between two offsets in either order. Tokens produced by macros carry the macro call’s span, so an opening token can sit after its closing one.
Field Type Default Description
start int required First code unit covered.
end int required One past the last code unit covered.
Member Type Description
length int Number of code units covered.
isEmpty bool Whether the span covers nothing.
cover(SourceSpan other) SourceSpan The smallest span covering both this and other.
contains(int offset) bool Whether offset lies inside this span.
textOf(String source) String The covered text of source.

The source after normalization, with a map back to the original string.

More about SourceText

Normalization turns \r\n and lone \r into \n, so every line ending is one code unit, and puts the text in Unicode NFC (so é typed as e + a combining accent matches the precomposed letter). Spans point into text; originalSpan maps them back.

Constructor Description
SourceText(String original) Normalizes original.
Field Type Default Description
original String required The string as given by the caller.
text String The normalized string every span points into.
Member Type Description
originalOffset(int offset) int Maps an offset in text to the matching offset in original.
originalSpan(SourceSpan span) SourceSpan Maps a span in text to the matching span in original.

Every name val_latex understands, grouped by the table that defines it — for galleries, completion lists and documentation.

More about LatexCatalog

Read from the same tables the parser uses, so it cannot drift from what actually parses.

Member Type Description
static instance The catalog.
symbols Map<String, (String, AtomType)> Math symbol commands (\alpha, \le): the Unicode text and TeX atom class of each.
limitsOperators Set<String> Large operators that take limits above and below in display style.
namedOperators Map<String, bool> Named operators (\sin, \lim) and whether they take limits.
textSymbols Map<String, String> Text-mode symbol commands (\textdagger) and their text.
accents Iterable<String> Math accents (\hat, \widetilde, \overrightarrow).
textAccents Iterable<String> Text accents (\', \", \v), used inside \text{…}.
braces Iterable<String> Horizontal braces (\overbrace, \underbracket).
extensibleArrows Iterable<String> Extensible arrows (\xrightarrow).
commands Iterable<String> Commands the parser implements directly (\frac, \sqrt, \left, \mathbf, \boxed…).
infixCommands Iterable<String> Infix fraction commands (\over, \choose, \atop).
fontSwitches Iterable<String> Font switches (\rm, \bf, \itshape).
styleSwitches Iterable<String> Style switches (\displaystyle…).
sizeSwitches Iterable<String> Size switches (\tiny … \Huge).
structural Iterable<String> Commands handled inside other constructs (\right, \middle, \end, \\…), which have no meaning alone.
environments Iterable<String> Environments (matrix, align, CD…).
macros Iterable<String> Built-in macros (\pmod, \braket, \newcommand, \dots…).
fallbacks Iterable<String> Commands of common packages (\abs, \sfrac, \vv…) that apply wherever nothing else defines the name.
extension(LatexExtension extension) Iterable<String> The commands an optional extension adds.
colors Iterable<String> Named colours: CSS (red, teal) and xcolor’s dvipsnames (NavyBlue).
allCommands Set<String> Every command name above (not environments or colours), once.