formula

package
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package formula lays out mathematical formulas written in LaTeX or MathML and returns them as vector graphics: a BDF object of filled and stroked paths, which any renderer of BDF objects draws — into an image (raster/imagebdf), on an Ebitengine screen (raster/ebitenginebdf), or on a browser's canvas as the page of a document (@bdfkit/render).

ts, _ := formula.New(nil)
f := formula.ParseTeX(`x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}`)
obj := ts.Layout(f, formula.Style{Size: 24, Display: true}).Object()
img, _ := imagebdf.Object(obj, 2, nil)

Formulas are laid out the way TeX and MathML Core lay them out, with the parameters and the glyph variants of the OpenType MATH table of a formula font: script sizes and shifts, fraction and radical gaps, the spacing between atoms, large operators, and delimiters, radicals and accents that grow. It is the engine that the converters of this module lay the formulas of Word, PowerPoint, Excel, HTML, EPUB, Markdown and draw.io documents out with. The formula font is STIX Two Math, which the package embeds, unless Options name another.

STIX Two Math is licensed under the SIL Open Font License 1.1 (fonts/OFL.txt; Copyright 2001-2021 The STIX Fonts Project Authors, with Reserved Font Name "TM Math"). A program that imports this package holds the font; fonts/README.md says where the file comes from.

Example

A formula drawn into an image, on the baseline of a line of text.

package main

import (
	"fmt"
	"image"
	"image/color"
	"image/draw"

	"github.com/shibukawa/bdf"
	"github.com/shibukawa/bdf/image/formula"
	"github.com/shibukawa/bdf/raster/imagebdf"
)

func main() {
	ts, err := formula.New(nil)
	if err != nil {
		panic(err)
	}
	f := formula.ParseTeX(`x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}`)
	l := ts.Layout(f, formula.Style{Size: 24, Display: true, Color: bdf.RGB(0, 0, 0)})
	obj := l.Object()

	img, err := imagebdf.Object(obj, 2, nil)
	if err != nil {
		panic(err)
	}
	dst := image.NewRGBA(image.Rect(0, 0, 480, 200))
	draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
	x, y := 20, 100 // where the baseline starts
	b := img.Bounds()
	draw.Draw(dst, b.Add(image.Pt(x, y)), img, b.Min, draw.Over)

	fmt.Println(f.Text())
	fmt.Println(b.Min.Y < 0, b.Max.Y > 0)
}
Output:
x=(−b±√(b^2−4ac))/(2a)
true true

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Formula

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

Formula is a formula read from LaTeX or MathML.

func ParseMathML

func ParseMathML(src string) (*Formula, error)

ParseMathML reads the first math element of src (presentation MathML, as HTML holds it).

func ParseTeX

func ParseTeX(src string) *Formula

ParseTeX reads a formula written in LaTeX's math mode (without the $ or \[ \] around it), with the commands of amsmath and amssymb that MathJax and KaTeX pages use. It does not fail: what it does not know it keeps as text.

func (*Formula) Display

func (f *Formula) Display() bool

Display reports whether the formula asks for display style (a MathML math element with display="block").

func (*Formula) Text

func (f *Formula) Text() string

Text returns the formula in a linear notation, such as "x=(−b±√(b^2−4ac))/(2a)": what a screen reader, a search or a copy takes for the formula.

type Layout

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

Layout is a formula laid out. Its origin is the left end of its baseline and y grows downwards, in the units of Style.Size.

func (*Layout) Depth

func (l *Layout) Depth() float64

Depth is how far the formula reaches below its baseline.

func (*Layout) Document

func (l *Layout) Document(margin float64) *bdf.Document

Document returns a document of one page that holds the formula with a margin around it: what a browser draws on a canvas with @bdfkit/render or shows with the viewer, and what raster/imagebdf draws as a page. The page carries the formula in linear notation (Text) as its text, for search, copy and screen readers.

Example

A formula served as a document of one page, for a browser to draw.

package main

import (
	"bytes"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/shibukawa/bdf"
	"github.com/shibukawa/bdf/image/formula"
)

func main() {
	ts, err := formula.New(nil)
	if err != nil {
		panic(err)
	}
	handler := func(w http.ResponseWriter, r *http.Request) {
		l := ts.Layout(formula.ParseTeX(r.URL.Query().Get("tex")), formula.Style{Size: 20, Display: true})
		w.Header().Set("Content-Type", "application/octet-stream")
		l.Document(8).WriteSingle(w)
	}
	rec := httptest.NewRecorder()
	handler(rec, httptest.NewRequest("GET", `/formula?tex=e^{i\pi}%2B1=0`, nil))
	r, err := bdf.OpenSingle(bytes.NewReader(rec.Body.Bytes()), int64(rec.Body.Len()))
	if err != nil {
		panic(err)
	}
	doc, err := r.ToDocument()
	if err != nil {
		panic(err)
	}
	st, _ := doc.SearchText()
	fmt.Println(len(doc.Views[0].Pages), st.Views[0].Pages[0].Text)
}
Output:
1 e^(iπ)+1=0

func (*Layout) Draw

func (l *Layout) Draw(o *bdf.Object, x, y float64)

Draw draws the formula into o with the left end of its baseline at (x, y), as paths (see Object). It leaves the fill and stroke styles of o as the formula set them.

func (*Layout) Height

func (l *Layout) Height() float64

Height is how far the formula reaches above its baseline.

func (*Layout) Ink

func (l *Layout) Ink() bdf.Rect

Ink returns the extent of what the formula draws, which may reach past its width, height and depth (italic overhangs, accents).

func (*Layout) Object

func (l *Layout) Object() *bdf.Object

Object returns the formula as an object of paths: the outlines of its glyphs, the rules of its fractions and radicals, and the lines of its enclosures. The origin of the object is the left end of the baseline and its bounding box is what the formula draws (Ink). The object refers to no font and no other part, so it is drawn as it is (imagebdf.Object, ebitenginebdf.Compile) or added to a document.

func (*Layout) Text

func (l *Layout) Text() string

Text returns the formula in a linear notation (see Formula.Text).

func (*Layout) Width

func (l *Layout) Width() float64

Width is the advance of the formula: where what follows it on the line starts.

type Options

type Options struct {
	// Math is the formula font, a TrueType or OpenType font with a MATH
	// table (STIX Two Math, Latin Modern Math, Cambria Math …). nil is
	// the embedded STIX Two Math.
	Math []byte
	// Text are fonts for the characters the formula font lacks, such as
	// East Asian text in \text{…}, tried in order.
	Text [][]byte
}

Options are the fonts of a Typesetter.

type Style

type Style struct {
	// Size is the font size in the units of the result (12 when it is 0).
	Size float64
	// Display sets the formula in display style, as on a line of its own:
	// larger operators with their limits above and below, taller
	// fractions. A formula that asks for it (Formula.Display) gets it
	// too.
	Display bool
	// Color is the color of the formula where it sets none itself (\color);
	// black when it is 0.
	Color bdf.Color
	Bold  bool
}

Style is how a formula is set.

type Typesetter

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

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

func New

func New(opts *Options) (*Typesetter, error)

New returns a typesetter. A nil opts lays formulas out with the embedded formula font alone.

func (*Typesetter) Layout

func (t *Typesetter) Layout(f *Formula, st Style) *Layout

Layout lays a formula out.

Jump to

Keyboard shortcuts

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