mathlayout

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package equation lays out mathematical formulas and draws them into BDF objects, for every converter whose documents hold formulas: Office Math (OMML) in Word documents, MathML in HTML pages, and LaTeX in Markdown.

The three notations are read into one tree (the shape of presentation MathML: rows of tokens, fractions, radicals, scripts, limits, tables), which is laid out the way TeX and MathML Core lay formulas out, with the parameters and glyph variants of the OpenType MATH table of a formula font (STIX Two Math, Cambria Math, Latin Modern Math …): script sizes and shifts, fraction and radical gaps, the spacing between atoms, large operators, and delimiters, radicals and accents that grow from larger variants and assemblies of parts. Glyphs no character maps to are drawn through private use characters of the embedded font subset (fontset.Set.GlyphRune). Without a formula font, formulas are laid out with the text font and default parameters, and delimiters are scaled.

A laid out formula is drawn into a child object that its host places with an ALT_TEXT carrying the formula in a linear notation, such as "x=(−b±√(b^2−4ac))/(2a)", which text extraction, search and copy use.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsFunctionName

func IsFunctionName(s string) bool

IsFunctionName reports whether s names a function (sin, log, lim …) that is set upright.

func Linear

func Linear(n Node) string

Linear writes a formula in a linear notation close to the one Office calls linear format (UnicodeMath): x^2, x_(i+1), (a+b)/(c+d), √(x+1), √(n&x), ∑_(i=1)^n x_i. It is the text that extraction, search and copy see for the formula.

func ParseColor

func ParseColor(s string) (bdf.Color, bool)

ParseColor reads a color: a name, #rgb, #rrggbb or rgb(r, g, b).

func XHeight

func XHeight(fc *Face) float64

XHeight returns the height of the x of a face in em (0 when it has none).

Types

type Align

type Align uint8

Align is a horizontal alignment.

const (
	Center Align = iota
	Left
	Right
)

type Atom

type Atom struct {
	Kind    Kind
	Text    string
	Variant Variant
	Class   Class
	// Font is the family of a Text atom drawn in a text font instead of
	// the formula font ("" draws it in the formula font when that has its
	// characters).
	Font string

	// Operator properties. Stretchy operators grow to the height of their
	// row (vertical ones) or the width of what they are over or under
	// (horizontal ones); Symmetric ones grow evenly around the math axis.
	Stretchy, Symmetric bool
	LargeOp             bool // drawn larger in display style
	MovableLimits       bool // limits go to the side outside display style
	Accent              bool // an accent over or under its base
	// Shortfall grows delimiters as TeX's \left and \right do (not quite
	// to the full height of what they enclose).
	Shortfall bool
	// MinSize is a size (em) the operator grows to at least, as \big and
	// \Bigg ask for.
	MinSize float64
	// Spaced sets the space before and after an operator to LSpace and
	// RSpace (em) instead of the space of its class.
	Spaced         bool
	LSpace, RSpace float64
}

Atom is a token: identifiers, numbers, operators and text.

func NewOp

func NewOp(s string) *Atom

NewOp returns an operator token with the properties the operator dictionary gives it (stretchy delimiters, large operators, accents).

type Bar

type Bar struct {
	Kid   Node
	Under bool
}

Bar draws a rule over (or under) what it holds (\overline, OMML bar).

type Box

type Box struct {
	W, H, D float64
	// Italic is the italic correction of a box that ends in a slanted
	// glyph: where a superscript goes past its width.
	Italic float64
	// contains filtered or unexported fields
}

Box is a laid out formula or part of one: its width, its height above and depth below the baseline (points), and what it draws, relative to the left end of its baseline (y grows downwards).

func (*Box) Depth

func (b *Box) Depth() float64

func (*Box) Height

func (b *Box) Height() float64

func (*Box) Ink

func (b *Box) Ink() bdf.Rect

Ink returns the extent of what b draws relative to its origin (y grows downwards), which may reach past its box (italic overhangs, accents).

func (*Box) Items

func (b *Box) Items() []Item

Items returns what b draws, in drawing order.

func (*Box) Width

func (b *Box) Width() float64

Width, Height and Depth are the box's dimensions in points.

type Class

type Class uint8

Class is a TeX atom class, which sets the spacing between atoms.

const (
	ClassAuto Class = iota // from the token (operators: the operator dictionary)
	Ord
	LargeOp // a large operator or a function name
	Bin
	Rel
	Open
	Close
	Punct
	Inner
	None // no spacing around it
)

type Enclose

type Enclose struct {
	Kid                      Node
	Top, Bottom, Left, Right bool
	Round, Circle            bool
	StrikeH, StrikeV         bool
	StrikeUp, StrikeDown     bool // lower left to upper right, upper left to lower right
}

Enclose draws lines around or across what it holds (menclose, OMML borderBox, \boxed, \cancel).

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine lays formulas out with one set of fonts. It is not safe for concurrent use.

func New

func New(f Fonts) *Engine

New returns an engine that lays formulas out with f.

func (*Engine) HasMathFont

func (e *Engine) HasMathFont() bool

HasMathFont reports whether formulas are laid out with a formula font.

func (*Engine) Layout

func (e *Engine) Layout(n Node, st Style) *Box

Layout lays a formula out.

func (*Engine) XHeight

func (e *Engine) XHeight() float64

XHeight returns the height of the formula font's x in em (0 without a formula font).

type Face

type Face struct {
	Loaded *fontdb.Loaded // nil when no font file is available
	// Host is what the host of the engine knows the face by (the font it
	// draws text with); the engine does not look at it.
	Host any
}

Face is a font that formulas are laid out with.

type Fonts

type Fonts struct {
	// Math is the formula font, a font with a MATH table (see
	// fontdb.DB.ResolveMath); nil without one.
	Math *Face
	// Text returns the face that draws r in a text font: for characters
	// the formula font lacks (East Asian text) and for text asked in a
	// family (family "" is the text around the formula). It is also what
	// formulas are drawn with when no formula font is available.
	Text func(family string, r rune, bold, italic bool) *Face
	// Advance returns the advance of r in em in a face, for a host that
	// keeps the characters it draws (to embed a subset of the font). nil
	// measures with the font.
	Advance func(f *Face, r rune) float64
	// GlyphRune returns the character that a host draws glyph g of a face
	// with, for the glyphs no character maps to (the larger variants and
	// the parts of delimiters): hosts that draw formulas as text give
	// them private use characters. nil keeps such glyphs by their index
	// only (Item.Glyph).
	GlyphRune func(f *Face, g uint16) (rune, bool)
	// Warn receives problems, such as a missing formula font.
	Warn func(msg string)
}

Fonts are what formulas are laid out with.

type Frac

type Frac struct {
	Num, Den           Node
	Kind               FracKind
	NoBar              bool    // a stack without a rule
	Thickness          float64 // the rule in em; 0 for the font's
	NumAlign, DenAlign Align
}

Frac is a fraction (mfrac, \frac, \binom's stack, OMML f).

type FracKind

type FracKind uint8

FracKind is how a fraction is drawn.

const (
	FracStacked FracKind = iota // numerator over denominator
	FracSkewed                  // numerator raised, a slash, denominator lowered
	FracLinear                  // numerator, slash, denominator on the baseline
)

type Item

type Item struct {
	Kind ItemKind
	// X and Y are where a glyph's baseline starts, the top left corner of
	// a rule, and the origin of a stroke's path.
	X, Y  float64
	Color bdf.Color

	// a glyph
	Face *Face
	// Glyph is the glyph in the face; HasGlyph is false for a character
	// the face lacks, which a host draws with a font of its own.
	Glyph    uint16
	HasGlyph bool
	Size     float64 // the font size
	// Text is the character that draws the glyph: the character itself,
	// or the one Fonts.GlyphRune gave a glyph no character maps to (then
	// Alt is the character the glyph is a form of).
	Text, Alt string
	Advance   float64
	// ScaleX and ScaleY stretch a glyph that is grown without a formula
	// font (1 otherwise).
	ScaleX, ScaleY float64

	// W and H are the size of a rule; W is the line width of a stroke.
	W, H float64
	Path *bdf.Path // of a stroke
}

Item is something a laid out formula draws, relative to the left end of its baseline (y grows downwards, points).

type ItemKind

type ItemKind uint8

ItemKind is what an Item draws.

const (
	ItemGlyph  ItemKind = iota // a glyph (or, without a formula font, a character) of a face
	ItemRule                   // a filled rectangle: a fraction bar, the rule of a radical
	ItemStroke                 // a stroked path: an enclosure, a strike, a delimiter drawn without a formula font
)

type Kind

type Kind uint8

Kind is the kind of a token.

const (
	Ident  Kind = iota // a variable or function name (mi)
	Number             // mn
	Op                 // an operator, relation, delimiter or punctuation (mo)
	Text               // text (mtext, \text{}, Office's normal text)
)

type Node

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

Node is a node of a formula.

func ParseMathML

func ParseMathML(n *html.Node) (formula Node, display bool)

ParseMathML reads a MathML math element as golang.org/x/net/html parses it (presentation MathML, with the deprecated elements pages still use: mfenced, mstyle's attributes). display reports display="block". Of the elements nested deeper than maxDepth, the tokens are read, in a row.

func ParseTeX

func ParseTeX(src string) Node

ParseTeX reads a formula written in LaTeX's math mode, with the commands of amsmath and amssymb that Markdown documents and MathJax and KaTeX pages use. What it does not know it keeps as text. Groups and arguments nested deeper than maxDepth are read without their braces and commands.

type OMML

type OMML struct {
	// NaryLim and IntLim are where the limits of n-ary operators and of
	// integrals go when an operator does not say: "undOvr" or "subSup"
	// (m:mathPr's naryLim and intLim; "" for Word's defaults).
	NaryLim, IntLim string
	// RunStyle reads the formatting of the runs of Office Math in DrawingML
	// text (PowerPoint, Excel), whose a:rPr inherits from its text body:
	// the style to set a run in (nil for none), and its font and weight
	// for normal text. The runs of Word documents have a w:rPr, which the
	// reader reads itself.
	RunStyle func(rPr *xmltree.Node) (style *Styled, font string, bold, italic bool)
	// contains filtered or unexported fields
}

OMML is what reading Office Math needs to know about its document.

func (*OMML) ParseOMML

func (o *OMML) ParseOMML(n *xmltree.Node) Node

ParseOMML reads an Office Math zone (m:oMath) or any of its arguments.

func (*OMML) ParseOMMLPara

func (o *OMML) ParseOMMLPara(n *xmltree.Node) (lines []Node, jc string)

ParseOMMLPara reads a display math paragraph (m:oMathPara): the formula on each of its lines, and their justification ("left", "right" or "center").

type Phantom

type Phantom struct {
	Kid                          Node
	Show                         bool
	ZeroWidth, ZeroAsc, ZeroDesc bool
}

Phantom lays out what it holds without drawing it (Show false), or draws it without some of its dimensions (\smash, OMML phant).

type Radical

type Radical struct {
	Base, Degree Node
}

Radical is a square root (Degree nil) or a root of another degree.

type Row

type Row struct {
	Kids []Node
	// Class is how the row spaces from its neighbors; ClassAuto makes it
	// an ordinary atom.
	Class Class
}

Row is a sequence of nodes laid out side by side (mrow, a TeX group). Its vertically stretchy operators grow to the height of the rest.

type Scripts

type Scripts struct {
	Base           Node
	Sub, Sup       Node
	PreSub, PreSup Node
}

Scripts is a base with subscripts and superscripts after it and before it (msub, msup, msubsup, mmultiscripts; nil for none).

type Space

type Space struct {
	Width float64
}

Space is horizontal space (negative: backwards), in em.

type Style

type Style struct {
	Size    float64 // font size in points
	Display bool    // display style: a formula on a line of its own
	Color   bdf.Color
	Bold    bool
}

Style is how a whole formula is set.

type Styled

type Styled struct {
	Kid Node
	// Display sets display (1) or inline (2) style.
	Display int8
	// Level sets the script level (1+level: 1 is display/text size, 2
	// script, 3 script-script); LevelUp makes it one smaller.
	Level   int8
	LevelUp bool
	Color   *bdf.Color
	Size    float64 // font size in points
	// Base is the font size in points of text outside scripts (Office's
	// run size, which scripts are reduced from).
	Base    float64
	Scale   float64 // font size factor
	Variant Variant
	// Bold draws the text and operators bold where the font has bold
	// forms (Office's bold runs).
	Bold bool
}

Styled changes the style of what it holds; zero fields leave it as it is.

type Table

type Table struct {
	Rows     [][]Node
	ColAlign []Align // per column, the last repeated; nil centers
	// Aligned lays the columns out in pairs, the first of a pair aligned
	// right and the second left, without space between them (LaTeX's
	// aligned, Office's equation arrays).
	Aligned bool
	RowGap  float64 // em between rows; 0 for the default
	ColGap  float64 // em between columns; 0 for the default
	// Display sets the cells in display style (equation arrays).
	Display bool
}

Table is a matrix, the rows of an array of equations, or cases.

type UnderOver

type UnderOver struct {
	Base                    Node
	Under, Over             Node
	AccentUnder, AccentOver bool
}

UnderOver is a base with something under and over it (limits, accents, braces).

type Variant

type Variant uint8

Variant is a math variant: the style of the letters and digits of a token, drawn with the Mathematical Alphanumeric Symbols.

const (
	VarAuto Variant = iota // italic for single-letter identifiers, else normal
	VarNormal
	VarItalic
	VarBold
	VarBoldItalic
	VarDoubleStruck
	VarScript
	VarBoldScript
	VarFraktur
	VarBoldFraktur
	VarSansSerif
	VarSansSerifBold
	VarSansSerifItalic
	VarSansSerifBoldItalic
	VarMonospace
)

Jump to

Keyboard shortcuts

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