Recursive AI

Getting started with onefont for Go

All onefont Go docs

Install onefont for Go, load a font, shape and measure text, shape mixed-direction text with font fallback, break lines, and unpack a web font.

onefont for Go parses fonts, shapes text with the font’s OpenType tables, and gives back glyphs, advances, offsets and clusters, plus bidi, line breaking and font fallback. Placing lines and drawing glyphs is up to you. Every sample on this page was compiled and run with Go 1.26.8 against recursiveai.org/go/onefont v1.1.1 from the Go module proxy; the output under each one is what it printed.

Install

onefont needs Go 1.24 or newer.

Terminal
mkdir font-start && cd font-start
go mod init example.com/font-start
go get recursiveai.org/go/onefont@v1.1.1

The import path is recursiveai.org/go/onefont and the package name is onefont. It has no dependencies outside the standard library, no cgo and no unsafe. The license is MIT or Apache-2.0, at your choice.

The samples are complete main.go files that read fonts from the current directory. They use Noto fonts (SIL Open Font License) from the noto-fonts repository at commit b963047, and a WOFF2 build of Noto Sans from the @fontsource/noto-sans 5.0.0 npm package. Pinned downloads keep the glyph IDs below the same:

Terminal
NOTO=https://raw.githubusercontent.com/googlefonts/noto-fonts/b96304716598bc0da16eb35512b5032eb452b4e5/hinted/ttf
for f in NotoSans NotoSansArabic NotoSansHebrew; do
  curl -LO $NOTO/$f/$f-Regular.ttf
done
curl -LO https://cdn.jsdelivr.net/npm/@fontsource/noto-sans@5.0.0/files/noto-sans-latin-400-normal.woff2

Load a font

Parse takes the bytes of a .ttf, .otf or .ttc file. The library opens no files itself.

GO
package main
 
import (
	"fmt"
	"log"
	"os"
 
	"recursiveai.org/go/onefont"
)
 
func main() {
	data, err := os.ReadFile("NotoSans-Regular.ttf")
	if err != nil {
		log.Fatal(err)
	}
	face, err := onefont.Parse(data)
	if err != nil {
		log.Fatal(err)
	}
	m := face.Metrics()
	fmt.Println(face.Family(), face.Subfamily(), "weight", m.Weight)
	fmt.Println(face.NumGlyphs(), "glyphs,", face.UnitsPerEm(), "units per em")
 
	// Metrics and advances are in font units. Scale by size / units per em.
	size := float32(16)
	lineHeight := float32(m.Ascender-m.Descender+m.LineGap) * size / float32(face.UnitsPerEm())
	fmt.Printf("line height at %v px: %.2f px\n", size, lineHeight)
 
	// The character map: glyph 0 means the font has no glyph for the character.
	for _, r := range []rune{'A', 'é', '€', 'א'} {
		g := face.GlyphIndex(r)
		fmt.Printf("%U %c  glyph %3d  advance %d\n", r, r, g, face.Advance(g))
	}
}
Text
Noto Sans Regular weight 400
3317 glyphs, 1000 units per em
line height at 16 px: 21.79 px
U+0041 A  glyph  36  advance 639
U+00E9 é  glyph 171  advance 564
U+20AC €  glyph 539  advance 572
U+05D0 א  glyph   0  advance 600
  • Metrics and advances are in font units. Multiply by size / UnitsPerEm() for pixels or points. The line height here is ascender minus descender plus line gap.
  • GlyphIndex maps a character through the font’s character map. Glyph 0 is the missing-glyph box: Noto Sans has no Hebrew letters.
  • Parse reads tables lazily and checks every offset. A damaged or unsupported file returns an error that wraps ErrInvalidFont or ErrUnsupportedFormat; match it with errors.Is. For a TrueType Collection, NumFaces counts the faces and Parse(data, onefont.WithFace(i)) picks one.

Shape text and measure it

Shape turns a string into positioned glyphs with the font’s own GSUB and GPOS tables: ligatures, kerning, contextual forms and the reordering complex scripts need. The script and direction come from the text.

GO
package main
 
import (
	"fmt"
	"log"
	"os"
 
	"recursiveai.org/go/onefont"
)
 
func load(name string) *onefont.Face {
	data, err := os.ReadFile(name)
	if err != nil {
		log.Fatal(err)
	}
	face, err := onefont.Parse(data)
	if err != nil {
		log.Fatal(err)
	}
	return face
}
 
func main() {
	latin := load("NotoSans-Regular.ttf")
	run, err := onefont.Shape("office", latin)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(run.Len(), "glyphs for 6 letters, script", run.Script, run.Direction)
	for _, g := range run.All() {
		fmt.Println("glyph", g.Glyph, "cluster", g.Cluster, "advance", g.AdvanceX)
	}
	size := float32(16)
	fmt.Printf("width at %v px: %.2f px\n", size, float32(run.Width())*size/float32(latin.UnitsPerEm()))
 
	arabic := load("NotoSansArabic-Regular.ttf")
	run, err = onefont.Shape("سلام", arabic)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(run.Len(), "glyphs, script", run.Script, run.Direction)
	for _, g := range run.All() {
		fmt.Println("glyph", g.Glyph, "cluster", g.Cluster, "advance", g.AdvanceX)
	}
}
Text
4 glyphs for 6 letters, script Latn ltr
glyph 82 cluster 0 advance 605
glyph 1969 cluster 1 advance 946
glyph 70 cluster 4 advance 480
glyph 72 cluster 5 advance 564
width at 16 px: 41.52 px
3 glyphs, script Arab rtl
glyph 769 cluster 6 advance 484
glyph 705 cluster 2 advance 599
glyph 1077 cluster 0 advance 784
  • Noto Sans draws “ffi” as one ligature glyph, so six letters become four glyphs. Clusters are byte offsets into the text: the ligature belongs to the cluster at byte 1.
  • Run.Width is the sum of the advances in font units; scale it the same way as the metrics to measure a string.
  • Arabic comes back right to left in visual order, as hb-shape prints it, with joining forms and the lam-alef ligature applied. Each Arabic letter is two bytes, so the clusters are 0, 2 and 6.
  • WithDirection, WithScript, WithLanguage and WithFeatures override what Shape infers. To shape many strings, keep a Shaper from NewShaper and a Run: once their buffers have grown, shaping allocates nothing.

Mixed-direction text and font fallback

ShapeText resolves bidi (UAX #9), picks a font for each grapheme cluster from a FallbackChain, and shapes each piece with its own font in its own direction.

GO
package main
 
import (
	"fmt"
	"log"
	"os"
 
	"recursiveai.org/go/onefont"
)
 
func load(name string) *onefont.Face {
	data, err := os.ReadFile(name)
	if err != nil {
		log.Fatal(err)
	}
	face, err := onefont.Parse(data)
	if err != nil {
		log.Fatal(err)
	}
	return face
}
 
func main() {
	chain := onefont.NewFallbackChain(load("NotoSans-Regular.ttf"), load("NotoSansHebrew-Regular.ttf"))
	text := "Hello שלום 123"
	for sr, err := range onefont.ShapeText(text, chain) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%q  font %d  level %d  %d glyphs\n", text[sr.Start:sr.End], sr.Font, sr.Level, sr.Run.Len())
	}
}
Text
"Hello "  font 0  level 0  6 glyphs
"123"  font 0  level 2  3 glyphs
" "  font 0  level 1  1 glyphs
"שלום"  font 1  level 1  4 glyphs
  • The pieces arrive in the order they are displayed, left to right. The Hebrew word and the number after it form a right-to-left run, so “123” is drawn before “שלום”.
  • Font is the index in the chain: Noto Sans has no Hebrew, so those letters go to font 1. Level is the bidi level, odd for right to left.
  • sr.Run is reused between iterations, so copy what you keep.

Break lines

Lines yields the pieces of text between line break opportunities (UAX #14), each with the spaces that stay on its line, and whether it ends in a forced break. LineBreaks gives the same positions as byte offsets.

GO
package main
 
import (
	"fmt"
 
	"recursiveai.org/go/onefont"
)
 
func main() {
	for line, forced := range onefont.Lines("Two lines.\nThe second wraps here.") {
		fmt.Printf("%q %v\n", line, forced)
	}
 
	// Thai has no spaces between words. Since 1.1 a dictionary finds the word breaks.
	thai := "ภาษาไทยไม่มีช่องว่าง"
	var s onefont.Segmenter
	fmt.Println(pieces(thai, s.AppendLineBreaks(nil, thai)))
	s.NoDictionary = true // the rules of UAX #14 alone, as in 1.0
	fmt.Println(pieces(thai, s.AppendLineBreaks(nil, thai)))
}
 
func pieces(text string, breaks []onefont.LineBreak) []string {
	var out []string
	prev := 0
	for _, b := range breaks {
		out = append(out, text[prev:b.Pos])
		prev = b.Pos
	}
	return out
}
Text
"Two " false
"lines.\n" true
"The " false
"second " false
"wraps " false
"here." false
[ภาษา ไทย ไม่มี ช่อง ว่าง]
[ภาษาไทยไม่มีช่องว่าง]
  • A line may end after any piece. To wrap a paragraph, shape the pieces, add their widths and end the line at the last piece that fits.
  • Thai, Lao, Khmer and Burmese are written without spaces between words. Since 1.1, line breaking finds the words with lists built into the library, as browsers do. Setting Segmenter.NoDictionary gives the rules of UAX #14 alone, which allow no break inside the run.
  • Graphemes, Words and Sentences work the same way (UAX #29), with …Breaks forms that yield offsets.

Unpack a web font

New in 1.1: UnwrapWebFont turns a WOFF or WOFF2 file into a plain font for Parse.

GO
package main
 
import (
	"fmt"
	"log"
	"os"
 
	"recursiveai.org/go/onefont"
)
 
func main() {
	data, err := os.ReadFile("noto-sans-latin-400-normal.woff2")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("web font:", onefont.IsWebFont(data), len(data), "bytes")
	if onefont.IsWebFont(data) {
		data, err = onefont.UnwrapWebFont(data)
		if err != nil {
			log.Fatal(err)
		}
	}
	face, err := onefont.Parse(data)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(data), "bytes unpacked:", face.Family(), face.NumGlyphs(), "glyphs")
}
Text
web font: true 14256 bytes
31200 bytes unpacked: Noto Sans 333 glyphs
  • IsWebFont tells a web font from a plain one. WithMaxFontSize bounds the unpacked size; the default is 64 MiB.
  • The Brotli decoder WOFF2 needs is part of the module and uses only the standard library.

Drawing the text

onefont stops at glyphs and positions. Face.GlyphPath returns a glyph’s outline as move, line, quadratic and cubic segments in font units (y up), and Face.Outline draws it into your own PathSink; scale it with onefont.Scale and fill it with the rasterizer of your choice.

Where next

  • Overview: the README, with the full feature list, conformance results and benchmarks.
  • Changelog: what changed in 1.1.0 and 1.1.1.
  • Package documentation on pkg.go.dev, with a runnable example for each feature.