texmath

package
v0.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 16 Imported by: 2 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package texmath lays out mathematical formulas with the OpenType MATH table of a font, by the rules of TeX Appendix G. It is the port of github.com/go-tex/math at the commit 6a6d2729, and a fork of it (D78).

A formula is a tree of nodes, such as Atom, Scripts and Fraction. Parse reads TeX math and returns its tree:

tree, err := texmath.Parse(`\frac{a}{b}`)

A program can also build a tree itself, for example from MathML. Layout lays out a tree with a face that has a MATH table, such as STIX Two Math of the package texmath/stixtwomath, at a size and in a style. LayoutTeX parses and lays out in one call:

f, err := stixtwomath.Font()
...
box, err := texmath.LayoutTeX(`\frac{a}{b}`, font.NewFace(f), 16, texmath.Display)

The result is a Box: its width, its height above the baseline, its depth below it, and its items. An item is a glyph of a face, a filled rectangle, or a filled path, such as the head of an arrow. Each length is in the unit of the size, such as pixels or points, and y grows down. Box.Draw fills the items into an okage Pixmap. Box.Path gives the outline of every item as one path, and Box.ItemPath the outline of one item, for a writer of SVG. They read the outlines from the faces of the items, and need no FontDatabase.

An error of Parse is a *SyntaxError. It wraps okage.ErrTeXMathSyntax, and also okage.ErrTeXMathUnknownCommand for an unknown command, whose name is in its field Command. Layout gives okage.ErrMathNoMathTable for a face without a MATH table. A formula past a limit gives okage.ErrMathLimit. The limits are:

  • The depth of nesting is at most 100 levels (WithMaxDepth). Each step of the recursion of the parser is a level: a list, an atom, a command, an argument, and the scripts of a nucleus. A tree of the parser is at most twice as deep as its levels, and the layout allows twice the depth, with a level for each node that holds other nodes. A StyleChange takes no level. On TinyGo for wasip1, a goroutine has a stack of 64 KiB that does not grow, and Parse takes at most 27 KiB of it for the deepest formula.
  • The parser makes at most 100,000 nodes (WithMaxNodes). A box has at most 1,000,000 items.
  • The macros of \def expand at most 100,000 times, the budget of the source (WithMaxExpansions). The source and its expansion have at most 1,048,576 tokens.
  • A length of \rule, \raisebox, \mkern, \mskip or \genfrac is at most 16,384 pt, em or ex, or 16,384 em in mu. A factor of \scalebox is a finite number of at most 100. The size of Layout is a positive finite number.

Text, colors and the KaTeX commands

The additions of phase 26 of D78 give the commands that the labels of Mermaid use and that the source does not have.

\text, \textrm, \textbf, \textit, \textsf, \texttt, \textup, \textmd, \textnormal and \emph set their argument as text, a TextRun, with its spaces. Each one changes one part of the text style in force, as in LaTeX: \textbf in \textit is bold italic. WithTextFace gives the four faces of the roman family, and WithTextFamily the faces of the sans-serif and the monospace families. The layout shapes a run with typesetting/shaping, so the ligatures and the kerning of the face apply, and a character that the face has no glyph for takes the math face. A style without a face takes the math alphabet of that style from the math face: the upright, bold, italic or bold italic letters and digits, and the sans-serif or the monospace ones. Its other characters, the spaces among them, are the glyphs of the math face. So without a text face, \text sets the upright glyphs of the math face, as the source does.

\color sets the color of the rest of its group, and \textcolor of its argument, with a name of CSS, such as red, or a number such as #228B22, as KaTeX reads them. \colorbox, \fcolorbox and \fbox set text on a background, in a frame, or both.

\cancel, \bcancel and \xcancel draw a line across their argument, as KaTeX does. \phase draws the angle mark of electrical engineering around its argument, a line under it and a slanted line at its left, as KaTeX does. \tag and \tag* set the label of an equation a quad after the formula, as TeX sets an equation number. With WithLineWidth, the label is at the right margin of the line, and the formula is centered in it. \hline draws a rule between the rows of array and of the matrices, and \hdashline a dashed rule. \cfrac sets a continued fraction in display style, and \cfrac[l] and \cfrac[r] set its numerator at the left or the right. \kern and \hspace give a space of any length, and \llap, \rlap and \clap, with \mathllap, \mathrlap and \mathclap, set their argument with no width. \scriptscriptstyle, \dddot and \ddddot work. \newcommand, \renewcommand and \providecommand define a macro in the formula, as \def does, and the first parameter can have a default value. The macros of KaTeX that stand for a symbol, a font or an operator, such as \R, \N, \Z, \reals, \larr and \bold, are known unless the formula defines the name.

\overbrace and \underbrace draw the brace of the face, U+23DE or U+23DF, grown to the width of their argument with the horizontal variants and the horizontal assembly of the MATH table, and set their labels over and under it. \widehat, \widetilde and \widecheck take the widest horizontal variant of their combining mark that is not wider than their argument, as TeX does. \middle grows as its \left and \right do. \smash removes the height and the depth of its argument, \smash[t] the height only, and \smash[b] the depth only. The size commands, from \tiny to \Huge, set the rest of their group at a factor of the size of Layout, from 0.5 to 2.488, as LaTeX and KaTeX do.

On 2026-11-25 the maintainers asked for the rest of the commands of KaTeX (D95). The symbols, the operators and the macros of KaTeX all parse, with the accents and the symbols of text, such as \text{\'{a}} and \ss. The arrows, the harpoons and the line segments go over or under a base, as \underrightarrow. \overgroup, \undergroup, \utilde and \Overrightarrow grow a character of the face, and \overbracket and \underbracket a square bracket. \sideset sets scripts at the left and the right of a large operator. \vcenter, \angl, \sout, \smallint, \above, \brace, \brack, \verb, \url and the extensible arrows of two shafts work, and align, alignat, gather, equation and rcases are environments. \href and the commands of HTML set their body without the link, and \includegraphics is an empty space of the size of the image. A \\ outside an environment makes no line break.

The layout uses three more parts of the MATH table, and an option turns each one off for a comparison with the source. The italic correction of a glyph, such as the italic f, moves a superscript to the right, moves the limits of an operator apart, and follows the glyph in a list, as TeX Appendix G says (WithItalicCorrection). Box.Italic gives the correction of the last glyph. The top accent attachment puts an accent, which is the combining mark of the face, over the attachment point of a glyph (WithAccentAttachment). The math kerning of the corners of two glyphs moves a script into the shape of its nucleus, such as the subscript of an italic V (WithMathKern).

On 2026-11-26 ivy asked for six changes, which follow TeX where the source and the MATH table do not (D103). \ldots, \dots, \mathellipsis, \cdots and the dots of amsmath are three dots of the class Punct in an atom of the class Inner, as fontmath.ltx and amsmath set them, so 1,\ldots,n has the width of TeX. \dots sets the dots at the center before a binary operator, a relation or a large operator. The primes of x' are at the size of x, after it, and the scripts attach to the primes. A superscript of \prime only is primes. An accent over one character takes its scripts as TeX Appendix G, rule 12, says, so the subscript of \hat y_i is where the subscript of y_i is. The drop of a subscript under a nucleus that is not one character, SubscriptBaselineDropMin, is at the size of the script. WithMathConstant sets a constant of the MATH table, and WithSubSupShiftDown gives a subscript with a superscript the shift sub2 of TeX. The cells of aligned, alignedat, split and gathered, and of the environments of KaTeX that take their layout, are in display style.

Three commits of go-tex/math of 2026-11-28 are ported:

  • A glyph of a script is the alternate of the feature ssty of the face. The style Script takes the first alternate, and the style ScriptScript takes the second one. So a letter of a script has the width that the face draws for that size.
  • The delimiters of \binom, \choose and \genfrac reach delim1 of TeX in display style and delim2 in the other styles. These are 2.39 em and 1.01 em, whatever the fraction holds.
  • A group of one character of the class Ord, such as {x}, is that character before its scripts, as math_group of TeX says. So {x}^2 is x^2.

The commands that KaTeX parses and Parse does not are in test/texmath/katex_parse.txt, with their reasons.

Differences from go-tex/math

The parser makes a tree and lays nothing out, and the layout makes items and not SVG text. The source lays out each command as it parses it. The layout reads exact font units with typesetting, scaled by a size that is a float64. It imports typesetting/shaping to shape the runs of a text face. The source asks go-opentype for a face at a whole number of pixels, which rounds each value, and takes the ink of a glyph from the points of an outline of lines. The hook of \xhookrightarrow is a filled outline, so that Box.Path holds every item. The source strokes it.

The port also fixes these faults of the source. The files and the lines are those of the source. First the faults of the parser:

  • parse.go:39 drops every space, also in \text, so \text{if } b sets "ifb". The text of \text is a TextRun that keeps its spaces, as TeX does: TeX skips the white space after a control word and after a comment only. In \text, an apostrophe is a character and not a prime (parse.go:80), and ~, \ , \%, \&, \#, \_, \$, \{ and \} are text.
  • parse.go:39 sets a carriage return as a character. It is white space.
  • parse.go:254, parse.go:499 and parse.go:526 recurse with no limit on the depth. The depth is limited.
  • The source has no limit on the nodes. The nodes are limited.
  • macro.go:59 copies the rest of the input at each expansion, in quadratic time, and nothing limits the tokens that an expansion makes. The expansion is a stack, and the tokens are limited.
  • parse.go:145 scans for the \fi of each \ifmmode and recurses into the true branch, in quadratic time for nested conditionals. One pass with a stack gives the same result.
  • mukern.go:79 reads each part of the glue of \mskip with glue of its own, so a run of "plus" parts recurses with no bound. A part of the glue has no glue.
  • scalebox.go:62 and scalebox.go:84 take NaN and Inf from strconv.ParseFloat into the SVG text, and rule.go:94, mukern.go:43 and parse.go:794 take any finite length. These are limits now.
  • exat.go:22 converts a size of 2^47 points or more to an integer out of range, and exat.go:37 loops once for each point of a negative size. exAt returns 1.5 for a large size before the conversion, and stops the loop when \vfuzz is 0, which gives the same value.
  • parse.go:325 drops \limits, \nolimits and \displaylimits, and a script after them then attaches to an empty atom after the operator. They now set where the scripts of the operator go.
  • parse.go:802 sets the style 3 of \genfrac in script style. It is scriptscript, as in TeX.
  • parse.go:1066 adds an empty row after a \\ before \end. As in LaTeX and KaTeX, it starts no row.
  • parse.go:599 sets \middle at one size, 1.8 em, parse.go:699 keeps the extent of \smash, parse.go:329 ignores the size commands such as \large, and parse.go:660 draws \overbrace and \underbrace as a rule. The additions above replace each one.
  • mathchoice.go:45 parses the chosen branch of \mathchoice only, so a fault in another branch is not reported. Each branch is parsed, because the style is not known before the layout.
  • parse.go:316 and parse.go:411 set the denominator of \over, and the fraction, in the style of a style command before \over. As in TeX, the style command sets only the part of the numerator after it.

Then the faults of the layout:

  • math.go:163, math.go:191 and parse.go:323 set a script at the script size of the size in force, so a script of a script is 70% of a script, and each level is smaller again. TeX has three sizes: the text size, and the script and scriptscript sizes of ScriptPercentScaleDown and ScriptScriptPercentScaleDown. \displaystyle and \textstyle go back to the text size.
  • math.go:163 drops every space between atoms in a script, and math.go:191 keeps every space in a fraction in text style, whose parts are at the script size. In script and scriptscript style, TeX keeps only the thin spaces next to an Op.
  • math.go:443 sets a Bin as an Ord only at the start of a list and after a Bin, Op, Rel, Open or Punct. As in TeX, it is an Ord also before a Rel, a Close or a Punct, and at the end of a list.
  • parse.go:1001 and mukern.go:33 make each space, such as \, or \mkern, an Ord atom, so \int\mkern-6mu\int took two thin spaces. A space is not an atom, as a kern or glue of TeX.
  • math.go:475 and math.go:485 place a superscript and a subscript each on its own, with SuperscriptShiftUp, SuperscriptBaselineDropMax and SubscriptShiftDown only. The scripts follow Appendix G, rule 18, with SuperscriptBottomMin, SubscriptBaselineDropMin, SubscriptTopMax, SubSuperscriptGapMin, SuperscriptBottomMaxWithSubscript and SpaceAfterScript. The drops of the baselines apply to a nucleus that is a box, and not to one glyph of a character, as rule 18a and the OpenType specification say.
  • math.go:477 and math.go:487 count only the height of a superscript and the depth of a subscript, so ^1 had no depth and _2 no height.
  • math.go:512 and math.go:517 place a limit by UpperLimitGapMin and LowerLimitGapMin only. Its baseline is also at least UpperLimitBaselineRiseMin over the operator, or LowerLimitBaselineDropMin under it.
  • math.go:553 and math.go:555 place the numerator and the denominator by the gaps only. Their baselines are also at least FractionNumeratorShiftUp and FractionDenominatorShiftDown from the baseline, or the constants of display style.
  • math.go:570 places the parts of \atop and \binom with the gaps of a fraction and the thickness of the rule. They take StackTopShiftUp, StackBottomShiftDown and StackGapMin, as Appendix G, rule 15c, says.
  • math.go:887 puts all the excess of a radical sign that is taller than the body below the body. As Appendix G, rule 11, says, half of the excess opens the gap over the body.
  • parse.go:1007 sets a large operator on the baseline, so the variant of display style hung from it. A large operator is centered on the math axis, as Appendix G, rule 13, says.
  • math.go:1083 grows the delimiters of \left, \right and the matrices to the whole height around the axis, so a delimiter was often a size too large. They cover 901/1000 of it and miss at most 0.5 em, with the \delimiterfactor and \delimitershortfall of plain.tex.
  • parse.go:581 draws the shaft and the heads of \xrightarrow at the size and on the axis of the script style of its labels, so the arrow sat under the math axis. They are those of the style in force.
  • math.go:660 leaves the hook of \xhookrightarrow out of the depth.
  • parse.go:935 and parse.go:1044 set the rows of \substack and the cells of smallmatrix one style down from the style in force. They are in script style, as \scriptstyle in the templates of amsmath sets.
  • parse.go:983 draws the null delimiter of \big. as the glyph .notdef, and math.go:933 draws .notdef for a delimiter without a glyph. Both are empty boxes.
  • math.go:1038 stacks the parts of an assembly from the last one up. The OpenType specification lists the parts from the bottom to the top, so the top part was at the bottom, and a tall parenthesis was upside down. The first part is at the bottom.
  • parse.go:1702 sets each accent with the spacing accent, such as U+02C6, centered on the advance of its nucleus, and \vec with a combining mark of no advance, so the arrow was too far to the left. An accent is the combining mark of the face, at its attachment point.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Accent

type Accent struct {
	Base    Node
	Accent  rune
	Stretch bool
}

Accent sets an accent over Base, such as \hat. Stretch grows it to the width of Base with the horizontal variants and the horizontal assembly of the MATH table, as \widehat. The source does not stretch an accent.

type Align

type Align uint8

Align is the horizontal alignment of a column of an Array.

const (
	AlignCenter Align = iota
	AlignLeft
	AlignRight
)

The alignments of a column.

type Angl added in v0.21.0

type Angl struct{ Body Node }

Angl is \angl: Body under a line, with a line at its right, the angle of the actuarial notation, as KaTeX draws it. Its class is Ord.

type Array

type Array struct {
	Kind        ArrayKind
	Rows        [][]Node
	Align       []Align // per column, centered when short
	VRules      []int   // the column gaps, 0 to the column count, with a vertical rule
	HRules      []int   // the row gaps, 0 to the row count, with a horizontal rule, as \hline
	HDashed     []bool  // for each rule of HRules, whether it is dashed, as \hdashline
	Open, Close rune    // the delimiters of pmatrix and its kin, 0 for none
	Stretch     float64 // \arraystretch, 0 for 1
}

Array is a grid of cells: the matrix environments, cases, array, aligned, gathered, smallmatrix and \substack, and the mtable of MathML. A row can be shorter than the others.

type ArrayKind

type ArrayKind uint8

ArrayKind is the kind of an Array. It sets the space between the rows and the columns.

const (
	ArrayMatrix      ArrayKind = iota // matrix, pmatrix and its kin, and cases
	ArrayArray                        // array, with a column specification
	ArrayAligned                      // aligned and split
	ArrayGathered                     // gathered
	ArraySmallMatrix                  // smallmatrix, with its cells in script style
	ArraySubstack                     // \substack, with its rows in script style
)

The kinds of an Array.

type Atom

type Atom struct {
	Class   Class
	Text    string
	Variant Variant
	Body    Node
	Large   bool   // an operator that grows in display style, such as \sum
	Limits  Limits // where the scripts of an operator go
}

Atom is a nucleus with a class. Text holds its characters, which the layout maps through Variant to the glyphs of the math face, as one unit with no space inside, such as "sin". Body holds a nucleus that is a formula, such as {a+b}, when Text is empty. An Atom with no Text and no Body is an empty atom of its class.

type Bar

type Bar struct {
	Base  Node
	Under bool
}

Bar is \overline or \underline.

type Box

type Box struct {
	Width  float64 // the advance width
	Height float64 // the extent above the baseline
	Depth  float64 // the extent below the baseline
	Italic float64 // the italic correction of the last glyph, which Width includes (WithItalicCorrection)
	Items  []Item
}

Box is a formula laid out. Its origin is the left end of its baseline, and y grows down, as in okage. Every length is in the unit of the size of the layout.

func Layout

func Layout(n Node, face *font.Face, size float64, style Style, opts ...Option) (*Box, error)

Layout lays out n with face, which must have a MATH table, at size, in style. The size is in any unit, such as pixels or points, and every length of the result is in that unit. A length of n in pt counts one point as one unit of the size, as the source does. Layout reads face, which is not safe for concurrent use, so a caller gives each goroutine its own face.

A face without a MATH table gives okage.ErrMathNoMathTable. A size that is not a positive finite number, and a tree past a limit, give an error that wraps okage.ErrMathLimit. The limits are those of Parse: WithMaxDepth for the depth of the tree, and at most 1,000,000 items in the box. A style past ScriptScript is ScriptScript.

func LayoutTeX

func LayoutTeX(tex string, face *font.Face, size float64, style Style, opts ...Option) (*Box, error)

LayoutTeX parses tex and lays out its tree, for a caller that has TeX only. It is RenderSVGMetrics and RenderDisplaySVGMetrics of the source, with items in place of SVG text. An error of Parse is a *SyntaxError.

func (*Box) Draw

func (b *Box) Draw(p *okage.Pixmap, t okage.Transform, paint *okage.Paint)

Draw fills each item into p, moved by t. paint gives the anti-aliasing and the blend mode, and the color of each item replaces its shader. paint is not changed.

func (*Box) ItemPath

func (b *Box) ItemPath(i int) *okage.Path

ItemPath returns the outline of the item i, for a caller that colors each item, such as a writer of SVG for a formula with colors. It returns nil when the item draws nothing or i is out of range.

func (*Box) Path

func (b *Box) Path() *okage.Path

Path returns the outline of every item as one path, in the unit of the size, with the baseline at y = 0. It reads the outlines from the faces of the items, and needs no FontDatabase. It returns nil for a box that draws nothing.

The path is filled with the nonzero rule. A rule and the head of an arrow go clockwise on the screen, as the outer contours of a CFF font do, so an arrow head adds to the shaft under it.

type Boxed

type Boxed struct {
	Body       Node
	Background *okage.Color
	Border     *okage.Color
	NoFrame    bool
}

Boxed is \boxed, \fbox, \colorbox and \fcolorbox: Body in a frame, on a background, or both. Background is nil for no background. Border is the color of the frame, nil for the color in force. NoFrame leaves the frame out, as \colorbox does.

type Brace

type Brace struct {
	Base  Node
	Under bool
	Rune  rune
}

Brace is \overbrace or \underbrace: a horizontal curly brace over or under Base, which grows to its width. Its class is Op. The Base of a Scripts that is a Brace takes its scripts as labels over and under the brace in each style, as limits, so \overbrace{x}^{n} sets n over the brace. The source draws a rule in place of the brace. Rune is the character of the brace, such as U+23B4 for \overbracket. It is the curly brace U+23DE or U+23DF when it is 0.

type Cancel

type Cancel struct {
	Body     Node
	Up, Down bool
	Strike   bool
}

Cancel draws a line across Body, as \cancel, \bcancel and \xcancel. Up is the line from the bottom left to the top right corner, and Down the line from the top left to the bottom right corner. Strike is the horizontal line of \sout, half the height of the letter x over the baseline. The class of a Cancel is the class of its Body.

type Choice

type Choice struct {
	Display, Text, Script, ScriptScript List
}

Choice is \mathchoice: the layout sets the branch of the style in force. An empty branch makes no atom at all, so it does not change the space between its neighbors.

type Class

type Class uint8

Class is the class of an atom. It sets the space between two atoms, by the table of TeX Appendix G.

const (
	Ord Class = iota
	Op
	Bin
	Rel
	Open
	Close
	Punct
	Inner
)

The eight classes of TeX.

type Color

type Color struct {
	Color okage.Color
	Body  Node
}

Color draws Body in a color, as \color and \textcolor. When a Color is an item of a List, the items of its Body, or Body itself when it is not a List, join that list for the space between atoms, as for a StyleChange.

type Delimited

type Delimited struct {
	Open, Close rune // 0 for the null delimiter "."
	Body        Node
}

Delimited is \left and \right: Body between two delimiters that grow to its height and depth around the math axis.

type Delimiter

type Delimiter struct {
	Rune   rune
	Class  Class
	Size   float64 // the height in em, centered on the math axis. 0 is the natural glyph on the baseline
	Middle bool    // \middle
}

Delimiter is one delimiter of a fixed size, such as \big(, or a delimiter of \middle. A delimiter of \middle in the Body of a Delimited, as an item of its List, grows as the delimiters of the Delimited do. Outside a Delimited, it takes its Size.

type Family

type Family uint8

Family is the family of the face of a TextRun.

const (
	FamilyRoman Family = iota // \text and \textrm
	FamilySans                // \textsf
	FamilyMono                // \texttt
)

The families of text.

type Fraction

type Fraction struct {
	Num, Den    Node
	NoRule      bool  // \atop, \binom, and \genfrac with a thickness of zero
	Open, Close rune  // the delimiters of \binom and \genfrac, 0 for none
	NumAlign    Align // the place of a narrower Num over Den: \cfrac[l] and \cfrac[r]
}

Fraction is \frac, \over, \atop, \binom and \genfrac. \dfrac and \tfrac are a StyleChange around a Fraction.

type Item

type Item struct {
	Kind      ItemKind
	Face      *font.Face      // ItemGlyph
	Glyph     font.GID        // ItemGlyph
	Size      float64         // ItemGlyph: the em size of the glyph
	X, Y      float64         // the origin of a glyph or a path, or the top left corner of a rule
	W, H      float64         // ItemRule
	Path      *okage.Path     // ItemPath, relative to X and Y
	Text      string          // ItemGlyph: the characters of the glyph, for a text layer. Empty on a part of an assembly after the first
	Color     okage.Color     // the color of the fill
	Transform okage.Transform // applied after X and Y. The identity, except under \scalebox and \reflectbox
}

Item is one thing that a Box draws.

type ItemKind

type ItemKind uint8

ItemKind is the kind of an Item.

const (
	ItemGlyph ItemKind = iota // one glyph of a face
	ItemRule                  // a filled rectangle
	ItemPath                  // a filled path, such as the head of an arrow
)

The kinds of an Item.

type Lap

type Lap struct {
	Body Node
	Side LapSide
}

Lap is Body with a width of zero, so that it overhangs to the right, as \lefteqn and \rlap, to the left, as \llap, or to both sides, as \clap.

type LapSide

type LapSide uint8

LapSide is the side that the Body of a Lap overhangs.

const (
	LapRight  LapSide = iota // \rlap and \lefteqn
	LapLeft                  // \llap
	LapCenter                // \clap
)

The sides of a Lap.

type Length

type Length struct {
	Value float64
	Unit  Unit
}

Length is a TeX length. Pt and the other absolute units count one point as one unit of the size of the layout, as the source does. The parser converts in, pc, cm, mm, bp, dd, cc and sp to Pt.

type Limits

type Limits uint8

Limits says where the scripts of an operator go.

const (
	LimitsAuto  Limits = iota // above and below in display style only
	LimitsAbove               // \limits
	LimitsSide                // \nolimits, and an operator such as \int or \sin
)

The places of the scripts of an operator.

type List

type List []Node

List is a row of nodes on one baseline. The empty List is valid.

The class of a List, as a part of a formula, is the class of its only item when it has one item, and Ord in the other cases. As in TeX, a Bin item at the start or at the end of a list, after a Bin, Op, Rel, Open or Punct item, or before a Rel, Close or Punct item, is set as an Ord. A Space is not an atom: it takes no part in these rules or in the space between atoms.

func Parse

func Parse(tex string, opts ...Option) (List, error)

Parse reads TeX math, such as `\frac{a}{b}`, and returns its tree. An unknown command is an error that names it. Parse lays nothing out, so it needs no font. An error of Parse is a *SyntaxError.

type Negate

type Negate struct{ Body Node }

Negate is \not: a slash over Body. The class of a Negate is the class of its Body.

type Node

type Node interface {
	// contains filtered or unexported methods
}

Node is one node of a formula. Each type of this file, other than the enumerations, is a Node.

type Option

type Option func(*config)

Option changes a limit of Parse, or a setting of the layout.

func WithAccentAttachment

func WithAccentAttachment(on bool) Option

WithAccentAttachment turns the top accent attachment of the MATH table on or off. It is on by default, as phase 26 of D78 adds it. The layout then sets an accent with the combining mark of the face, such as U+0302 for \hat, and puts the attachment point of the mark over the attachment point of a nucleus of one glyph, such as an italic letter. A glyph without an attachment point has it in the middle of its advance, and a mark with no advance in the middle of its ink. Off, the layout centers the spacing accent, such as U+02C6, on the advance of the nucleus, as the source. A stretched accent, such as \widehat, always takes the horizontal variants of the combining mark.

func WithColor

func WithColor(c okage.Color) Option

WithColor sets the color of each item outside a Color node. The default is opaque black. The source has no such setting: its SVG text fills with currentColor.

func WithItalicCorrection

func WithItalicCorrection(on bool) Option

WithItalicCorrection turns the italic correction of the MATH table on or off. It is on by default, as phase 26 of D78 adds it. The layout then sets a superscript of a character that the MATH table gives an italic correction, such as f or the integral sign, to the right by that correction, sets the upper limit of an operator half of it to the right and the lower limit half of it to the left, puts the correction after such a character in a list, and gives the correction of the last glyph in Box.Italic, as TeX Appendix G, rules 13a, 17 and 18, and the OpenType specification say. The width of a list includes the italic correction of a character at its end, as in TeX and KaTeX, and Box.Italic gives it, so that a caller that sets a script or a slanted letter after the box can take it off. Off, the layout uses no italic correction, as the source.

func WithLineWidth added in v0.21.0

func WithLineWidth(w float64) Option

WithLineWidth sets the width of the line of a formula, in the unit of the size of the layout. A formula with \tag then has the width of the line, with the body centered and the label at the right margin. A width of 0 or less, the default, sets the label a quad after the body. The other formulas do not change (D95).

func WithLogger

func WithLogger(lg *slog.Logger) Option

WithLogger sets the logger of the layout. It logs, once for each layout, a character that has no glyph in the face, at the level Warn (D20). The source has no logger, and sets such a character as an empty box.

func WithMathConstant added in v0.23.0

func WithMathConstant(c font.MathConstant, v float32) Option

WithMathConstant sets the constant c of the MATH table to v, in the units of the font, in place of the value of the face. The face does not change. A caller can give a math font the shifts of TeX with it, such as sub1 of Computer Modern for SubscriptShiftDown (D103).

func WithMathKern

func WithMathKern(on bool) Option

WithMathKern turns the math kerning of the MATH table on or off. It is on by default, as phase 26 of D78 adds it. The layout then moves a script of a nucleus of one glyph by the kerns of the corners of the two glyphs that face each other, at two heights, as the OpenType specification says. The smaller sum of the two heights moves the script. Off, the layout uses no math kerning, as the source.

func WithMaxDepth

func WithMaxDepth(n int) Option

WithMaxDepth sets the largest depth of nesting of groups, arguments and environments. Each step of the recursion of the parser is one level: a list, an atom, a command, an argument, and the scripts of a nucleus. So x in {{x}} is six levels deep: the outer list, two groups with their lists, and x. The default is 100. A value below 1 keeps the default.

func WithMaxExpansions

func WithMaxExpansions(n int) Option

WithMaxExpansions sets the budget of macro expansions. The default is 100,000, the budget of the source. When the budget is spent, a macro is left as it is, and the parser reports it as an unknown command. A value below 0 keeps the default.

func WithMaxNodes

func WithMaxNodes(n int) Option

WithMaxNodes sets the largest number of nodes of a tree that Parse makes. The default is 100,000. A value below 1 keeps the default.

func WithSubSupShiftDown added in v0.23.0

func WithSubSupShiftDown(v float32) Option

WithSubSupShiftDown sets the least shift down of a subscript that has a superscript, in the units of the font. It is sub2 of TeX, where SubscriptShiftDown is sub1. The MATH table has one shift for both, and without this option a subscript takes SubscriptShiftDown in both cases (D103).

func WithTextFace

func WithTextFace(regular, bold, italic, boldItalic *font.Face) Option

WithTextFace sets the faces of the roman family of text, for \text and a TextRun: the regular, the bold, the italic and the bold italic face. A nil face is not set. The layout shapes a run of text with typesetting/shaping, so the ligatures and the kerning of the face apply. A style whose face is not set takes the glyphs of the math alphabets of the math face, as the layout does with no text face at all: the upright, bold, italic and bold italic letters and digits, and the other characters of the math face. The source has no text face.

func WithTextFamily

func WithTextFamily(f Family, regular, bold, italic, boldItalic *font.Face) Option

WithTextFamily sets the faces of the family f of text, as WithTextFace does for the roman family: \textsf takes FamilySans, and \texttt FamilyMono. A style whose face is not set takes the sans-serif or the monospace alphabet of the math face. An unknown family is ignored.

type OverArrow

type OverArrow struct {
	Base        Node
	Left, Right bool // the ends that carry a head
	Under       bool
	Harpoon     bool
	Segment     bool
}

OverArrow is an arrow over Base that spans its width: \overrightarrow, \overleftarrow, \overleftrightarrow and \vv. Under sets it under Base, as \underrightarrow. Harpoon draws the upper half of each head, as \overrightharpoon. Segment draws a short vertical bar at each end that is asked for in place of a head, as \overlinesegment.

type OverUnder

type OverUnder struct {
	Base        Node
	Over, Under Node // nil when absent
	Class       Class
}

OverUnder sets Over above and Under below Base, centered: \overset, \underset, \stackrel and \buildrel, and the munder and mover of MathML. Over and Under are set in script style.

type Overlay

type Overlay struct{ Rows []OverlayRow }

Overlay is \ooalign: each row is set on the same baseline, over the others. The box is as wide as the widest row that is not hidden on both sides.

type OverlayRow

type OverlayRow struct {
	Body                Node
	HideLeft, HideRight bool
}

OverlayRow is one row of an Overlay. A row with \hidewidth on both sides is centered, and a row with \hidewidth on the left only is set at the right.

type Phantom

type Phantom struct {
	Body                 Node
	Horizontal, Vertical bool // keep the width, keep the height and the depth
}

Phantom keeps the size of Body and draws nothing: \phantom keeps the width, the height and the depth, \hphantom the width only, \vphantom and \mathstrut the height and the depth only.

type Phase added in v0.20.0

type Phase struct{ Body Node }

Phase is \phase: Body with the angle mark of electrical engineering, a line under Body and a slanted line at its left, as KaTeX draws it. Its class is Ord.

type Radical

type Radical struct {
	Body   Node
	Degree Node // nil for a square root
}

Radical is \sqrt, with an optional degree.

type Raise

type Raise struct {
	Body                Node
	Lift                Length
	Height, Depth       Length
	HasHeight, HasDepth bool
}

Raise is \raisebox{Lift}[Height][Depth]{Body}: Body moved up by Lift. A Height or a Depth replaces the extent of the moved box when its flag is set.

type Rule

type Rule struct {
	Width, Height, Lift Length
}

Rule is \rule[Lift]{Width}{Height}: a filled rectangle whose bottom edge is Lift above the baseline. A rule with a width or a height that is not positive draws nothing and keeps its size, as a strut.

type Scale

type Scale struct {
	Body Node
	X, Y float64
}

Scale is \scalebox and \reflectbox: Body scaled by X and Y around the left end of its baseline. A negative X mirrors Body, and the box keeps it to the right of the origin. A negative Y swaps the height and the depth. The class of a Scale is the class of its Body.

type Scripts

type Scripts struct {
	Base     Node
	Sup, Sub Node // nil when absent
	Primes   int
}

Scripts attaches a superscript, a subscript and primes to Base. Base is never nil. The parser gives the empty List for a script with no nucleus, such as ^1.

type Sideset added in v0.21.0

type Sideset struct {
	Base               Node
	LeftSup, LeftSub   Node // nil when absent
	RightSup, RightSub Node // nil when absent
}

Sideset is \sideset: the scripts of Left at the left of Base, and the scripts of Right at its right. Base is a large operator, which takes its own scripts as limits.

type SizeChange

type SizeChange struct {
	Factor float64
	Body   Node
}

SizeChange sets Body at Factor times the size of the layout, as the size commands \tiny to \Huge, from 0.5 for \tiny to 2.488 for \Huge. The factor is of the size that Layout gets, so a size command in another one does not multiply. A SizeChange is one atom, with the class of its Body.

type Space

type Space struct{ Width Length }

Space is a horizontal space, such as \quad or \,, or a negative one. In a List, it is not an atom, as a kern or glue of TeX.

type Stretch added in v0.21.0

type Stretch struct {
	Base  Node
	Rune  rune
	Under bool
}

Stretch is a character that grows to the width of Base over or under it, with the horizontal variants and the horizontal assembly of the MATH table: \overgroup, \undergroup, \utilde and \Overrightarrow. Its class is Ord.

type Style

type Style uint8

Style is one of the four styles of TeX. The source has no cramped style, and the port has none either.

const (
	Display Style = iota
	Text
	Script
	ScriptScript
)

The four styles of TeX.

type StyleChange

type StyleChange struct {
	Style Style
	Body  Node
}

StyleChange sets Body in Style, as \displaystyle or \scriptstyle. When a StyleChange is an item of a List, the items of its Body, or Body itself when it is not a List, join that list for the space between atoms, as a style command does in TeX. The parser gives each style command the rest of its group, up to the next style command, as a Body. \dfrac is a StyleChange whose Body is a Fraction.

type SyntaxError

type SyntaxError struct {
	// Pos is the byte offset of the fault in the TeX source. A fault at the
	// end of the source has the length of the source.
	Pos int

	// Msg says what is wrong, with the words of go-tex/math.
	Msg string

	// Command is the unknown command, such as `\foo`, or the unknown
	// environment, such as `\begin{foo}`. It is empty for the other faults.
	Command string
	// contains filtered or unexported fields
}

SyntaxError is the error of Parse. It wraps okage.ErrTeXMathSyntax for TeX math that the parser cannot read. For an unknown command or environment, it also wraps okage.ErrTeXMathUnknownCommand, and Command names it. For a formula past a limit, it wraps okage.ErrMathLimit only.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

Error returns the message, such as `parsing tex math: unknown command \foo`.

func (*SyntaxError) Unwrap

func (e *SyntaxError) Unwrap() []error

Unwrap returns the sentinel errors of the fault.

type Tag

type Tag struct {
	Body, Label Node
}

Tag is \tag: Body with the label of an equation at its right, a quad away, as TeX sets an equation number. Label holds the parentheses of \tag, and none for \tag*. With WithLineWidth, the label is at the right margin of the line, and Body is centered in the line.

type TextRun

type TextRun struct {
	Text         string
	Bold, Italic bool
	Family       Family
}

TextRun is text in a text face, as \text and the mtext of MathML. Its spaces are kept. The layout shapes it with the face that WithTextFace or WithTextFamily gives for its family and its style. Without such a face, it takes the math alphabet of its style from the math face, such as the bold letters for Bold, and the other characters of the math face, a space among them. The source sets \text with the upright glyphs of the math face.

type Unit

type Unit uint8

Unit is the unit of a Length.

const (
	Em Unit = iota // the size of the layout
	Ex             // the height of the letter x of the math face
	Mu             // 1/18 em
	Pt             // one unit of the size of the layout, as the source counts it
)

The units of a Length.

type VCenter added in v0.21.0

type VCenter struct{ Body Node }

VCenter is \vcenter: Body centered on the math axis.

type Variant

type Variant uint8

Variant is a math alphabet: the block of Mathematical Alphanumeric Symbols that a Latin letter or a digit maps to. The other characters do not change.

const (
	Italic              Variant = iota // the default of a letter
	Upright                            // \mathrm, an operator name and a symbol
	Bold                               // \mathbf
	BoldItalic                         // \boldsymbol, \mathbfit
	DoubleStruck                       // \mathbb
	Calligraphic                       // \mathcal and \mathscr
	Fraktur                            // \mathfrak
	SansSerif                          // \mathsf
	SansSerifItalic                    // \mathsfit
	SansSerifBoldItalic                // \mathsfbfit
	Monospace                          // \mathtt
	SansSerifBold                      // the bold sans-serif style of text without a face for it
)

The math alphabets.

type XArrow

type XArrow struct {
	Arrow       rune
	Over, Under Node // Under is nil when absent
}

XArrow is an arrow that grows to the width of its labels, such as \xrightarrow[Under]{Over}. Arrow is the character that the command names, such as '→' for \xrightarrow and '↪' for \xhookrightarrow. Its class is Rel, and its labels are set in script style.

Directories

Path Synopsis
Package stixtwomath holds the font STIX Two Math, which has an OpenType MATH table, for the math layout of texmath (D78).
Package stixtwomath holds the font STIX Two Math, which has an OpenType MATH table, for the math layout of texmath (D78).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL