Recursive AI

onefont for Go

All onefont Go docs

Pure-Go font parsing, OpenType text shaping, bidi, text segmentation and font fallback. Written from scratch for Go, with no cgo, no unsafe and nothing outside the standard library.

go get recursiveai.org/go/onefont

Requires Go 1.24 or newer. The import path is recursiveai.org/go/onefont and the package is onefont.

Quick start

Fonts come in as byte slices; the library opens no files and finds no system fonts. Errors are values you match with errors.Is.

Load a font and shape a string

GO
data, _ := os.ReadFile("NotoSans-Regular.ttf")
face, err := onefont.Parse(data)
if err != nil {
	log.Fatal(err)
}
run, err := onefont.Shape("Hello", face)
if err != nil {
	log.Fatal(err)
}
for i, g := range run.All() {
	fmt.Println(i, g.Glyph, g.Cluster, g.AdvanceX)
}

Glyph IDs, clusters (byte offsets into the text), advances and offsets come back in font units, in the visual order hb-shape prints them. Script and direction are taken from the text; options (WithDirection, WithScript, WithLanguage, WithFeatures) override them.

Mixed-direction text with font fallback

GO
chain := onefont.NewFallbackChain(latin, hebrew, emoji) // *Face or *Instance values
for sr, err := range onefont.ShapeText("abc אבג 123", chain) {
	if err != nil {
		log.Fatal(err)
	}
	// sr.Start and sr.End are byte offsets in the text, sr.Font indexes the
	// chain, sr.Level is the bidi level, sr.Run holds the glyphs.
	// Runs arrive in visual order, left to right.
	draw(sr)
}

ShapeText resolves bidi (UAX #9), picks a font per grapheme cluster, shapes every piece with its own font in its own direction and yields the pieces as they are displayed. See ExampleShaper_ShapeText.

Break lines

GO
for b := range onefont.LineBreaks(text) {
	fmt.Println(b.Pos, b.Mandatory) // a line may end before byte b.Pos
}
for line, forced := range onefont.Lines(text) {
	fmt.Printf("%q %v\n", line, forced)
}

See ExampleLineBreaks and ExampleLines. Graphemes, words and sentences work the same way (Graphemes, Words, Sentences and the …Breaks forms).

Glyph outlines

GO
path, err := face.GlyphPath(face.GlyphIndex('A'))
if err != nil {
	log.Fatal(err)
}
// Outlines are y up. Scale to 16 px per em and flip for a y-down canvas:
path.Transform(onefont.Scale(16/float32(face.UnitsPerEm()), -16/float32(face.UnitsPerEm())))
for seg := range path.All() {
	fmt.Println(seg.Kind, seg.Pts) // PathMove, PathLine, PathQuad, PathCubic, PathClose
}

See ExampleFace_GlyphPath, ExampleFace_Outline and ExampleScale.

Two layers

The happy path is built from the low-level API and uses nothing you cannot reach yourself. The low layer gives full access: Parse a Face, read its tables (Face.Table), look up glyphs, draw outlines into your own PathSink, make an Instance of a variable font, fill a reusable Run with a Shaper, resolve a Bidi, cut text with a Segmenter, split it over a FallbackChain. Keep a Shaper and a Run and shaping allocates nothing once their buffers have grown. The package documentation (go doc onefont) has the map of the API, the units and offsets rules and the concurrency table.

Features

  • Fonts: TrueType (glyf), OpenType CFF and CFF2, TrueType Collections; cmap (formats 0, 4, 6, 10, 12, 13 and 14 variation selectors), head, hhea, hmtx, OS/2, name, post, kern, GDEF, GSUB, GPOS; metrics, names, outlines into a small path sink (move, line, quad, cubic), bounds and affine transforms.
  • Variable fonts: fvar, avar, gvar, HVAR, MVAR, CFF2 blends and item variation stores; named instances; feature variations.
  • Shaping: GSUB lookups 1 to 8 and GPOS lookups 1 to 9 with every lookup flag, mark filtering sets, contextual and chained lookups and extension lookups; features and BCP 47 languages mapped to OpenType language systems; script itemisation. Shapers for Arabic (with Syriac and N'Ko), the Indic scripts, Khmer, Myanmar, Tibetan, the Universal Shaping Engine scripts, Thai and Lao, and Hangul.
  • Bidi: UAX #9 at Unicode 17.0.0: paragraph and explicit levels, isolates, brackets, line reordering (rules L1 and L2) and mirroring lookup.
  • Segmentation: UAX #14 line breaks (with the mandatory flag) and UAX #29 grapheme, word and sentence boundaries, default rules, Unicode 17.0.0. Line breaking also finds word boundaries in Thai, Lao, Khmer and Burmese text with built-in word lists (Segmenter.NoDictionary turns that off).
  • Fallback: a font per grapheme cluster over a chain of faces you supply, each run shaped with its own font's tables.
  • Unicode data: generated from the Unicode Character Database by tools/ucdgen (cd tools && go run ./ucdgen -check verifies the checked-in tables against the pinned source files); Unicode 17.0.0.

Limits and untrusted input

Fonts and text are treated as hostile. Nothing a font or a text contains makes a function panic or run without bound: every offset and count is checked against its table, outline and charstring interpreters bound their stack and nesting, composite glyphs detect cycles, variation data bounds its region and tuple counts, and shaping keeps work, nesting and growth budgets. A lookup that would exceed a budget stops being applied and the result is a valid run; a request whose result would outgrow the absolute growth limit, or a text over 1 GiB, returns an error that wraps ErrLimit. Other errors wrap ErrInvalidFont, ErrUnsupportedFormat, ErrFaceIndex, ErrGlyphID, ErrInvalidArgument or ErrNotFound. Library code opens no files, uses no network and runs no programs.

What it does not do

Rasterizing glyphs, running a hinting program, COLR painting, vertical layout and paragraph layout belong to the programs built on top. GlyphDescription and Hinting give a hinting interpreter the points, instructions and tables it needs. Parse reads plain fonts only; UnwrapWebFont unpacks WOFF and WOFF2 files first.

Conformance

onefont is tested against the Unicode conformance files and against the onefont conformance kit, a language-neutral suite of cases whose expectations come from the specifications and from HarfBuzz's output, shared by the onefont libraries for other languages.

SuiteCasesPassNot matched
Bidi (UAX #9: BidiTest, BidiCharacterTest)582,553582,5530
Segmentation (UAX #14, #29 conformance files and kit cases)25,06325,05211: dictionary line-breaking cases whose word lists differ from the reference's
Unicode properties4,8374,8370
Parse9229220
Fallback86860
Shape3,0373,0343: Tai Tham, which differ from the reference shaper

The Unicode conformance files are not stored here. To run them, set ONEFONT_CONFORMANCE_DIR to a directory holding BidiTest.txt, BidiCharacterTest.txt, GraphemeBreakTest.txt, WordBreakTest.txt, SentenceBreakTest.txt and LineBreakTest.txt from <https://www.unicode.org/Public/17.0.0/ucd/>; without it those tests are skipped. Fuzz targets cover the parsers, the shaper and the bidi, segmentation and fallback code (go test -fuzz).

Performance

Measured with bench/run.sh (method, inputs and fonts in bench/README.md) on an AMD Ryzen 9 7950X3D (32 threads), Linux, Go 1.26.8, GOMAXPROCS=1, alone on the machine (load average 1.0 to 1.4 for the whole run), 10 runs per row, medians. Before any row is timed, the libraries' outputs are checked to agree (glyphs, clusters, advances and offsets; outlines; runs; boundaries). The ratio is the other library's time divided by onefont's, so above 1 means onefont is faster. onefont allocates nothing per call in every steady-state row.

Rowonefontgolang.org/x/image/font/sfntgithub.com/go-text/typesetting
Parse a TrueType face365 ns9.2×828×
Parse a CFF face369 ns20×211×
Parse, then cmap, advance and one outline (TrueType / CFF)2.7 / 5.3 µs1.5× / 1.8×114× / 15×
cmap lookups of a text (TrueType / CFF)1.2 / 0.8 µs3.6× / 2.6×1.1× / 1.3×
Advances (TrueType / CFF)1.4 / 0.9 µs2.5× / 2.5×1.9× / 1.9×
Glyph outlines (TrueType / CFF)128 / 147 µs2.0× / 1.8×2.1× / 4.5×
Shaping a paragraphonefontgithub.com/go-text/typesetting/shaping
Latin109 µs1.12×
Arabic111 µs1.23×
Devanagari456 µs1.02×
Thai90 µs1.48×
CJK32 µs1.88×
Mixed scripts87 µs1.44×
Textonefontgolang.org/x/text/unicode/bidigithub.com/rivo/uniseg
Bidi (English / mixed / CJK)22 / 12 / 19 µs1.6× / 1.9× / 1.6×
Graphemes (4 texts)4.3–8.3 µs1.1×–3.1×
Line breaks (4 texts)8.3–18.5 µs1.3×–2.5×
Words (4 texts)5.3–10.3 µs1.5×–1.7×
Sentences (4 texts)3.1–6.0 µs2.8×–3.0×

Versions compared: golang.org/x/image v0.48.0, golang.org/x/text v0.44.0, github.com/go-text/typesetting v0.3.5, github.com/rivo/uniseg v0.4.7.

Licence

Licensed under either of the MIT licence (LICENSE-MIT) or the Apache License 2.0 (LICENSE-APACHE), at your option. Copyright Recursive AI, LLC.

The Unicode Character Database tables generated into this module are covered by the Unicode License v3. The word lists behind dictionary line breaking come from the ICU project's data files; their notices are in THIRD-PARTY-NOTICES.md.

The Brotli decoder's static dictionary (internal/brotli/dictionary.bin) is the one published in Appendix A of RFC 7932, generated by tools/brotligen. The Brotli format and dictionary are by Google and are published under the MIT licence (Copyright 2013 Google Inc.).