Layout
Lay a parsed formula out with TeX's rules — the display list, sizes in em, layout options, line breaking, fonts and layout in a background isolate.
layoutFormula lays a ParseResult out and returns a MathLayout;
renderLatex parses and lays out in one step.
final layout = renderLatex( r'\sum_{k=1}^{n} k = \frac{n(n+1)}{2}', layoutOptions: const LayoutOptions(displayMode: true),);
print(layout.width); // emprint(layout.height + layout.depth); // emAll sizes are in em: multiply by the font size for pixels. x grows to the right and y downwards, with the origin on the baseline at the formula’s left edge.
MathLayout member |
What it is |
|---|---|
width |
Width, in em. |
height, depth |
Extent above and below the baseline, in em. |
items |
The display list: glyphs, rules, lines, paths and text runs, each positioned in em, with the source span of the node that made it where it has one. Display list lists every item class. |
lineCount |
How many lines the formula was broken into. |
equationNumbers |
Equation numbers, for the renderer to place at the margin. |
rtl |
Whether the math was laid out right to left. |
Fonts and text
Section titled “Fonts and text”layoutFormula, prepareFormula and renderLatex take:
font— the math font, by defaultMathFont.latinModern.fallbackFonts— fonts tried, in order, for symbols the math font lacks; after them the bundled STIX Two Math, then the symbol is shaped as text or drawn as a box (LayoutOptions.missingGlyphs).shaper— theTextShaperthat measures text runs (\text{…}and characters no math font has). Without Flutter the default,FallbackTextShaper, measures them from the math fonts’ own glyphs: right for Latin, Greek and Cyrillic, an estimate for scripts the fonts lack. In Flutter,mathShaperFor(MathTextFonts.latinModern)is the shaper the widgets use, backed by Flutter’s text engine.
Line breaking
Section titled “Line breaking”With LayoutOptions.maxWidth (in em), a long formula breaks into lines: in
display style before relations and operators, inline after them (TeX’s
rule). To lay a formula out at several widths, prepare it once;
layoutAt(width) re-runs only the line breaker.
final prepared = prepareFormula( parseLatex( r'(a+b)^3 = (a+b)(a+b)^2 = (a+b)(a^2 + 2ab + b^2) ' r'= a^3 + 3a^2 b + 3a b^2 + b^3', ), options: const LayoutOptions(displayMode: true),);
for (final width in [40.0, 20.0, 10.0]) { print('$width em: ${prepared.layoutAt(width).lineCount} lines');}// 40.0 em: 1 lines// 20.0 em: 3 lines// 10.0 em: 5 lineslayoutFormulaSegments splits an inline formula into pieces at its TeX
break points, for placing in a wrapping paragraph one piece at a time —
MathText uses it.
In the background
Section titled “In the background”layoutInBackground(source) parses and lays out in a long-lived worker
isolate and returns a Future<MathLayout>. It uses the bundled Latin Modern
Math and the pure-Dart shaper, so \text{…} widths are estimates; math
glyphs are exact. On the web, which has no isolates, it lays out right away.
stopBackgroundLayout() stops the worker; the next call starts a new one.
final layout = await layoutInBackground(r'\frac{a}{b}');API reference
Section titled “API reference”renderLatex()
Section titled “renderLatex()”Parses and lays out source in one step.
Display style comes from LayoutOptions.displayMode in
layoutOptions; the parse does not depend on it.
MathLayout renderLatex( String source, { ParseOptions parseOptions = const ParseOptions(), LayoutOptions layoutOptions = const LayoutOptions(), MathFont? font, TextShaper? shaper, MacroTable? macros, List<MathFont> fallbackFonts = const [],})layoutFormula()
Section titled “layoutFormula()”Lays out a parsed formula.
font defaults to the bundled Latin Modern Math; shaper measures text
runs and defaults to a FallbackTextShaper over font.
Symbols the math font lacks are taken from fallbackFonts (in
order), then from the bundled STIX Two Math (MathFont.stixTwo), then
shaped as text, or drawn as a missing-glyph box
(LayoutOptions.missingGlyphs).
MathLayout layoutFormula( ParseResult result, { LayoutOptions options = const LayoutOptions(), MathFont? font, TextShaper? shaper, List<MathFont> fallbackFonts = const [],})prepareFormula()
Section titled “prepareFormula()”Prepares result for layout at several widths (see PreparedFormula);
LayoutOptions.maxWidth is ignored in favour of layoutAt’s width.
PreparedFormula prepareFormula( ParseResult result, { LayoutOptions options = const LayoutOptions(), MathFont? font, TextShaper? shaper, List<MathFont> fallbackFonts = const [],})PreparedFormula
Section titled “PreparedFormula”A formula laid out once, ready to be broken to any width: layoutAt
re-runs only the line breaker (a widget resizing, a window dragged).
| Member | Type | Description |
|---|---|---|
layoutAt(double? maxWidth) |
MathLayout |
The layout at maxWidth em (null: unbounded). |
layoutFormulaSegments()
Section titled “layoutFormulaSegments()”Splits an inline formula into pieces at its TeX break points (after
binary operators and relations, at \allowbreak, at spaces in
\text), for placing in a wrapping paragraph one piece at a time.
With maxWidth (the paragraph’s line width, in em) the pieces are
weighed as TeX weighs breaks: they always end at relations, at +,
− and the other operators only within a piece wider than half the
line, and inside brackets only within one wider than the line.
List<MathLayout> layoutFormulaSegments( ParseResult result, { LayoutOptions options = const LayoutOptions(), MathFont? font, TextShaper? shaper, List<MathFont> fallbackFonts = const [], double? maxWidth,})layoutInBackground()
Section titled “layoutInBackground()”Parses and lays out source away from the calling isolate: on native
platforms in a long-lived worker isolate (the font is parsed there
once), on the web synchronously (no isolates there).
Text runs are measured by the pure-Dart shaper in the worker, so
\text{…} widths are estimates; math glyphs are exact. Layouts use the
bundled Latin Modern Math.
Future<MathLayout> layoutInBackground( String source, { ParseOptions parseOptions = const ParseOptions(), LayoutOptions layoutOptions = const LayoutOptions(),})stopBackgroundLayout()
Section titled “stopBackgroundLayout()”Stops the worker isolate (a new one starts on the next call).
void stopBackgroundLayout()encodeLayout()
Section titled “encodeLayout()”A layout as plain lists and numbers (fonts by name), cheap to send
between isolates; decodeLayout rebuilds it with the receiver’s fonts,
so painters keep their per-font glyph caches.
List<Object?> encodeLayout(MathLayout layout)decodeLayout()
Section titled “decodeLayout()”Rebuilds a layout from encodeLayout; fonts resolves font names (a
name not found falls back to the first font).
MathLayout decodeLayout(List<Object?> data, List<MathFont> fonts)LayoutOptions
Section titled “LayoutOptions”Options that affect layout.
| Constructor | Description |
|---|---|
LayoutOptions({…}) |
Creates layout options. |
LayoutOptions: more
const LayoutOptions({ this.displayMode = false, this.errorColor = const LatexColor(0xFFCC0000), this.minRuleThickness = 0, this.fleqn = false, this.leqno = false, this.firstEquationNumber = 1, this.labels = const {}, this.incomplete = IncompleteStyle.hide, this.placeholderColor = const LatexColor(0x66888888), this.mathDirection = MathDirection.ltr, this.digits = DigitStyle.western, this.operatorNames = const {}, this.maxWidth, this.lineBreaking = LineBreaking.auto, this.continuationIndent = 2, this.alignContinuation = true, this.showEmptyGroups = false, this.repeatOperator = false, this.textDirection = TextRunDirection.auto, this.classScales = const {}, this.scriptSizeGlyphs = true, this.missingGlyphs = MissingGlyphs.shape, this.kashida = true, this.recordBreakPoints = false,})| Field | Type | Default | Description |
|---|---|---|---|
displayMode |
bool |
false |
Display style ($$…$$) rather than text style ($…$). |
errorColor |
LatexColor |
const LatexColor(0xFFCC0000) |
Colour of error nodes. |
minRuleThickness |
double |
0 |
Minimum thickness of rules (fraction bars, radicals, table lines), in em; thinner rules are thickened so they stay visible. |
fleqn |
bool |
false |
Display equations aligned left instead of centred. |
leqno |
bool |
false |
Equation numbers on the left. |
firstEquationNumber |
int |
1 |
Number given to the first automatically numbered row. |
labels |
Map<String, String> |
const {} |
Resolved \label → number text, for \ref / \eqref. |
incomplete |
IncompleteStyle |
IncompleteStyle.hide |
How incomplete input is drawn. |
placeholderColor |
LatexColor |
const LatexColor(0x66888888) |
Colour of incomplete placeholders. |
mathDirection |
MathDirection |
MathDirection.ltr |
Direction of the math (Arabic notation uses MathDirection.rtl). |
digits |
DigitStyle |
DigitStyle.western |
How numbers are written. |
operatorNames |
Map<String, String> |
const {} |
Replacement names for named operators, e.g. arabicOperatorNames. Keys are commands (\sin); values are shaped as text. |
maxWidth |
double? |
Available width in em. When set, long formulas break into lines (see lineBreaking); a formula that cannot break stays wider. |
|
lineBreaking |
LineBreaking |
LineBreaking.auto |
Line-breaking policy. |
continuationIndent |
double |
2 |
Indent of continuation lines, in em, when they are not aligned at a relation. |
alignContinuation |
bool |
true |
Align continuation lines at the first relation (=) of the first line, as in hand-set display math. |
showEmptyGroups |
bool |
false |
Draws empty groups (\frac{}{}, x^{}) as placeholder boxes, for editors where they are slots waiting for input. |
repeatOperator |
bool |
false |
When a line breaks before a binary operator or relation (display line breaking), also show it at the end of the line before — the convention in some countries (Russia, for one). |
textDirection |
TextRunDirection |
TextRunDirection.auto |
Base direction of text runs. Math itself stays left to right unless mathDirection says otherwise. |
classScales |
Map<String, double> |
const {} |
Size factors for parts marked \htmlClass{name}{…}, by class name (a theme’s “sizes per class”): {'small': 0.8}. |
scriptSizeGlyphs |
bool |
true |
Use the font’s script-size glyph designs (ssty) in scripts, as TeX does with cmr7/cmr5. Off matches KaTeX, which scales text-size glyphs. |
missingGlyphs |
MissingGlyphs |
MissingGlyphs.shape |
What symbols missing from every math font become. |
kashida |
bool |
true |
Stretch Arabic operator names (operatorNames) with kashida (ـ) to span wide limits, as Arabic notation does (نهـــا). |
recordBreakPoints |
bool |
false |
Record where the formula could break (MathLayout.breakPoints), for debug overlays. |
| Member | Type | Description |
|---|---|---|
copyWith({…}) |
LayoutOptions |
A copy with the given fields replaced (null keeps the current value). |
copyWith: more
LayoutOptions copyWith({ bool? displayMode, LatexColor? errorColor, double? minRuleThickness, bool? fleqn, bool? leqno, int? firstEquationNumber, Map<String, String>? labels, IncompleteStyle? incomplete, LatexColor? placeholderColor, MathDirection? mathDirection, DigitStyle? digits, Map<String, String>? operatorNames, double? maxWidth, LineBreaking? lineBreaking, double? continuationIndent, bool? alignContinuation, bool? showEmptyGroups, bool? repeatOperator, TextRunDirection? textDirection, Map<String, double>? classScales, bool? scriptSizeGlyphs, MissingGlyphs? missingGlyphs, bool? kashida, bool? recordBreakPoints,})MathLayout
Section titled “MathLayout”A laid-out formula.
| Constructor | Description |
|---|---|
MathLayout(box, {…}) |
Creates a layout. |
MathLayout: more
const MathLayout( this.box, { this.equationNumbers = const [], this.rtl = false, this.lineCount = 1, this.breakPoints = const [], this.lineSpans = const [],})| Field | Type | Default | Description |
|---|---|---|---|
box |
Box |
required |
The formula. Lengths are in em of the base font size. |
equationNumbers |
List<EquationNumber> |
const [] |
Equation numbers to place at the right (or left, with leqno) margin of display equations. |
rtl |
bool |
false |
Laid out right to left: renderers put equation numbers on the left (on the right with leqno). |
lineCount |
int |
1 |
Number of lines after line breaking. |
breakPoints |
List<double> |
const [] |
Where the formula could break (x in em on its single line), when LayoutOptions.recordBreakPoints asked for them. |
lineSpans |
List<SourceSpan> |
const [] |
The source each line covers, after line breaking (empty when the formula was not broken). |
| Member | Type | Description |
|---|---|---|
leqno |
bool |
Whether the formula puts its equation numbers at the left margin (\leqno), as a renderer’s leqno option does for all. |
width |
double |
Width. |
height |
double |
Height above the baseline. |
depth |
double |
Depth below the baseline. |
items |
List<DisplayItem> |
Items to paint. |
EquationNumber
Section titled “EquationNumber”An equation number placed by the renderer at the margin.
| Constructor | Description |
|---|---|
EquationNumber(box, baseline, {left = false}) |
Creates an equation number. |
| Field | Type | Default | Description |
|---|---|---|---|
left |
bool |
false |
Asked for at the left margin (plain TeX’s \leqno), whatever the renderer’s default side. |
box |
Box |
required |
The number, e.g. (3). |
baseline |
double |
required |
Its baseline, relative to the formula’s baseline (y down). |
LineBreaking
Section titled “LineBreaking”Where a formula may break across lines.
| Value | Description |
|---|---|
auto |
Display math: display; inline math: tex. |
tex |
TeX’s rule: after binary operators and relations. |
display |
Display style: before binary operators and relations, so each continuation line starts with its operator; also inside \left…\right and at spaces in \text. |
none |
Never break. |
IncompleteStyle
Section titled “IncompleteStyle”How an incomplete (still streaming) part of a formula is shown.
| Value | Description |
|---|---|
hide |
Not shown: takes no space. |
placeholder |
A small grey placeholder box. |
show |
What has been typed so far (\fra), in the placeholder colour; a missing argument shows nothing. |
MathDirection
Section titled “MathDirection”Reading direction of the math itself.
| Value | Description |
|---|---|
ltr |
Left to right (the default, also inside right-to-left text). |
rtl |
Right to left, for Arabic mathematical notation: the formula is mirrored, directional symbols (brackets, radicals, ∑, ∫, arrows, <) are drawn mirrored, numbers and text keep their own direction. |
DigitStyle
Section titled “DigitStyle”How numbers are written.
| Value | Description |
|---|---|
western |
0123456789. |
arabicIndic |
٠١٢٣٤٥٦٧٨٩ (Arabic-Indic), with ٫ and ٬ as separators. |
persian |
۰۱۲۳۴۵۶۷۸۹ (Extended Arabic-Indic, Persian and Urdu), with ٫ and ٬. |
arabicOperatorNames
Section titled “arabicOperatorNames”Arabic names for common operators, as used in Arabic-language school
mathematics (Mashriq conventions). Have a native reader check them for
your audience; pass your own table to LayoutOptions.operatorNames.
const Map<String, String> arabicOperatorNames = { r'\sin': 'جا', r'\cos': 'جتا', r'\tan': 'ظا', r'\cot': 'ظتا', r'\sec': 'قا', r'\csc': 'قتا', r'\lim': 'نها', r'\log': 'لو',};TextRunDirection
Section titled “TextRunDirection”Base direction of text runs (\text{…}) — how neutral characters
and mixed-direction words inside a run are ordered.
| Value | Description |
|---|---|
auto |
Each run from its first strong character (so (1) stays (1) in right-to-left math); in Math widgets with left-to-right math, the surrounding Directionality. |
ltr |
Left to right. |
rtl |
Right to left. |
MissingGlyphs
Section titled “MissingGlyphs”What a symbol no math font has becomes.
| Value | Description |
|---|---|
shape |
A text run (the host’s text engine may find it in a system font). |
box |
A visible outlined box, for symbols in math blocks. |
TextShaper
Section titled “TextShaper”Measures text runs (\text{…}, non-math characters).
More about TextShaper
The core cannot shape complex scripts (Arabic joining, Indic
conjuncts). Flutter supplies a shaper backed by its text engine; the
default FallbackTextShaper measures from the math font.
| Member | Type | Description |
|---|---|---|
shape(String text, TextFont font) |
ShapedText |
Measures text in font at size 1 (em). |
ShapedText
Section titled “ShapedText”The measured size of a text run, in em of the run’s own size.
| Constructor | Description |
|---|---|
ShapedText({…}) |
Creates a result. |
ShapedText: more
const ShapedText({ required this.width, required this.ascent, required this.descent, this.glyphs, this.complete = true,})| Field | Type | Default | Description |
|---|---|---|---|
width |
double |
required |
Advance width. |
ascent |
double |
required |
Height above the baseline. |
descent |
double |
required |
Depth below the baseline (positive). |
glyphs |
List<DisplayItem>? |
What renderers without a text engine draw (relative to the run origin, size 1): glyphs, and for colour fonts fills and images; null when the host text engine will draw the run. | |
complete |
bool |
true |
False when some characters could not be shaped and width is an estimate. |
FallbackTextShaper
Section titled “FallbackTextShaper”A pure-Dart shaper using the math font’s own glyphs, one per grapheme.
More about FallbackTextShaper
Right for Latin and Greek text in the math font. A character the math font lacks is taken from the bundled STIX Two Math (Cyrillic, IPA, more accented Latin, superscript digits, vulgar fractions), a few symbols neither font has are drawn (✔, ✘, ❌…), and an accented letter neither font has is drawn as its base letter with the accent over it. Default- ignorable characters (variation selectors, joiners, bidi controls, the soft hyphen) take no room. What is still missing gets an estimated width and marks the result incomplete (no glyphs: the renderer’s own text engine draws the run).
| Constructor | Description |
|---|---|
FallbackTextShaper(font) |
Creates a shaper using font. |
| Field | Type | Default | Description |
|---|---|---|---|
font |
MathFont |
required |
The font. |
| Member | Type | Description |
|---|---|---|
canDraw(int cp) |
bool |
Whether cp can be drawn on its own (by a font or as a drawn symbol), or takes no room. |
isRtlText()
Section titled “isRtlText()”Whether text reads right to left: its first strong character is
Hebrew, Arabic, Syriac, Thaana, N’Ko or another right-to-left script
(UAX #9 rule P2).
bool isRtlText(String text)isDefaultIgnorable()
Section titled “isDefaultIgnorable()”Whether cp is drawn as nothing: a default-ignorable code point
(variation selectors, zero-width space and joiners, bidi controls, the
invisible operators U+2061–U+2064, the byte order mark, tags), the
soft hyphen, or a line or paragraph separator.
bool isDefaultIgnorable(int cp)lineBreaks()
Section titled “lineBreaks()”Break opportunities inside text (never at 0; the end of the text is
always a break and is not listed).
List<LineBreakOpportunity> lineBreaks(String text)lineBreakClass()
Section titled “lineBreakClass()”The Line_Break class of cp (a name such as AL, ID, SP).
String lineBreakClass(int cp)LineBreakOpportunity
Section titled “LineBreakOpportunity”A place where a line may (or must) break: before the code unit at
offset.
| Constructor | Description |
|---|---|
LineBreakOpportunity(offset, {mandatory = false}) |
Creates an opportunity. |
| Field | Type | Default | Description |
|---|---|---|---|
offset |
int |
required |
UTF-16 offset of the first character of the next line. |
mandatory |
bool |
false |
A hard break (line feed, paragraph separator…). |