# onefont Go docs, all pages (onefont-go 1.1.1)
Every page of https://recursiveai.org/onefont/go/docs/ and https://recursiveai.org/onefont/go/cookbook/ as markdown, getting started first. Index: https://recursiveai.org/onefont/go/llms.txt
# Getting started with onefont for Go
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.
```sh
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:
```sh
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](https://recursiveai.org/onefont/go/docs/overview/): the README, with the full feature list, conformance results and benchmarks.
- [Changelog](https://recursiveai.org/onefont/go/docs/changelog/): what changed in 1.1.0 and 1.1.1.
- [Package documentation](https://pkg.go.dev/recursiveai.org/go/onefont) on pkg.go.dev, with a runnable example for each feature.
# onefont for Go
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.
| Suite | Cases | Pass | Not matched |
|---|---:|---:|---|
| Bidi (UAX #9: BidiTest, BidiCharacterTest) | 582,553 | 582,553 | 0 |
| Segmentation (UAX #14, #29 conformance files and kit cases) | 25,063 | 25,052 | 11: dictionary line-breaking cases whose word lists differ from the reference's |
| Unicode properties | 4,837 | 4,837 | 0 |
| Parse | 922 | 922 | 0 |
| Fallback | 86 | 86 | 0 |
| Shape | 3,037 | 3,034 | 3: 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
; 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](https://github.com/recursive-ai-oss/onefont-go/blob/2a9a35cbfcd2e359c0178abdf2e0beaef4a7213f/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.
| Row | onefont | golang.org/x/image/font/sfnt | github.com/go-text/typesetting |
|---|---:|---:|---:|
| Parse a TrueType face | 365 ns | 9.2× | 828× |
| Parse a CFF face | 369 ns | 20× | 211× |
| Parse, then cmap, advance and one outline (TrueType / CFF) | 2.7 / 5.3 µs | 1.5× / 1.8× | 114× / 15× |
| cmap lookups of a text (TrueType / CFF) | 1.2 / 0.8 µs | 3.6× / 2.6× | 1.1× / 1.3× |
| Advances (TrueType / CFF) | 1.4 / 0.9 µs | 2.5× / 2.5× | 1.9× / 1.9× |
| Glyph outlines (TrueType / CFF) | 128 / 147 µs | 2.0× / 1.8× | 2.1× / 4.5× |
| Shaping a paragraph | onefont | github.com/go-text/typesetting/shaping |
|---|---:|---:|
| Latin | 109 µs | 1.12× |
| Arabic | 111 µs | 1.23× |
| Devanagari | 456 µs | 1.02× |
| Thai | 90 µs | 1.48× |
| CJK | 32 µs | 1.88× |
| Mixed scripts | 87 µs | 1.44× |
| Text | onefont | golang.org/x/text/unicode/bidi | github.com/rivo/uniseg |
|---|---:|---:|---:|
| Bidi (English / mixed / CJK) | 22 / 12 / 19 µs | 1.6× / 1.9× / 1.6× | |
| Graphemes (4 texts) | 4.3–8.3 µs | | 1.1×–3.1× |
| Line breaks (4 texts) | 8.3–18.5 µs | | 1.3×–2.5× |
| Words (4 texts) | 5.3–10.3 µs | | 1.5×–1.7× |
| Sentences (4 texts) | 3.1–6.0 µs | | 2.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](https://github.com/recursive-ai-oss/onefont-go/tree/2a9a35cbfcd2e359c0178abdf2e0beaef4a7213f/LICENSE-MIT)) or the Apache License 2.0
([LICENSE-APACHE](https://github.com/recursive-ai-oss/onefont-go/tree/2a9a35cbfcd2e359c0178abdf2e0beaef4a7213f/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](https://github.com/recursive-ai-oss/onefont-go/blob/2a9a35cbfcd2e359c0178abdf2e0beaef4a7213f/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.).
# Changelog
All notable changes are listed here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project
follows [Semantic Versioning](https://semver.org/).
## [1.1.1] - 2026-12-03
### Fixed
- **Tatweel:** a run made only of Common characters that Arabic text uses
(the tatweel U+0640, the Arabic comma) is shaped as Arabic when no script is
given and none is carried, so a span of tatweels gets its initial, medial and
final forms. `hb-shape` leaves such a run without a script; browsers give it
the script of the text around it.
- **Faces without a GPOS table place combining marks.** Each mark is placed
from the glyph boxes by its combining class (above, below, attached, left,
centre and right, double marks, Hebrew points, Arabic and Syriac vowel
signs), and marks stacked on one base rise over each other, matching
`hb-shape`. A mark with no class keeps its place but gives up its advance.
Faces with a GPOS table, and the Indic, Universal Shaping Engine, Khmer,
Myanmar, Thai, Lao, Tibetan, Hangul, N'Ko and Mongolian shapers, are
unchanged.
- In a face without GDEF glyph classes only nonspacing marks lose their
advance; spacing and enclosing marks (Mc, Me) keep it, as `hb-shape` does.
- The deprecated combining marks U+0340, U+0341, U+0343 and U+0344 are shaped
as the plain marks they are equivalent to, even when the face maps them, and
a base with marks after it is decomposed and recomposed even when the face
maps the base itself (a Greek question mark before a mark, say).
## [1.1.0] - 2026-12-03
### Added
- **Web fonts:** `UnwrapWebFont` unpacks WOFF 1.0 and WOFF 2.0 files (including
WOFF2 collections and the `glyf`, `loca` and `hmtx` transforms) to a plain
font for `Parse`; `IsWebFont` tells the two apart and `WithMaxFontSize`
bounds the unpacked size (default 64 MiB). The Brotli decoder it needs is
our own, in the standard library only, with the RFC 7932 dictionary.
- **Hinting data:** `Face.GlyphDescription` and `Instance.GlyphDescription`
give a glyph's points, contour ends, instructions and composite components,
and `Face.Hinting` the `fpgm`, `prep`, `cvt `, `gasp` and `maxp` data a
TrueType interpreter needs.
- **Shaping:** `WithGraphemeClusters` makes clusters whole UAX #29 grapheme
clusters (conjuncts included, GB9c); `WithFeatureRanges`, `FeatureRange` and
`ParseFeatureRange` limit a feature to part of the text (`liga[3:5]`).
- **Fallback:** `FallbackChain.WithEmojiPresentation` sends emoji sequences
(variation selector 16, keycaps, ZWJ sequences, modifiers, flags) to the
first colour font that covers them.
- **Dictionary line breaking:** `Segmenter.AppendLineBreaks` allows a break
between the words of a run of Thai, Lao, Khmer or Burmese letters, which
UAX #14 leaves to a dictionary, as browsers do. The words come from list
tables built into the library (generated by `tools/dictgen` from ICU's
dictionary data files; sources and notices in `THIRD-PARTY-NOTICES.md`,
about 1.1 MiB of tables). Text outside the lists stays together up to the
next word. `Segmenter.NoDictionary` restores the rules of UAX #14 alone.
### Changed
- Line breaking for Thai, Lao, Khmer and Burmese now uses the built-in word
lists by default, so `LineBreaks` and `Lines` return breaks between the words
of such a run where 1.0.0 returned none. `Segmenter.NoDictionary` restores
the rules of UAX #14 alone.
### Fixed
- The tatweel (U+0640) takes its joining forms like a dual-joining letter, so
a leading, trailing or medial tatweel joins its neighbours.
- Hebrew points the font has no glyph for no longer add their advance width.
- A font with no space glyph no longer shows default-ignorable characters
(variation selectors, joiners, soft hyphens) as `.notdef` boxes: they leave
no glyph, as in HarfBuzz.
- A cluster with the text variation selector (U+FE0E) never counts as an
emoji sequence, wherever the selector stands.
## [1.0.0] - 2026-12-02
First release.
### Added
- **Fonts:** `Parse` over the caller's bytes (lazy, bounds-checked tables) for
TrueType, OpenType CFF, CFF2 and TrueType Collections (`WithFace`,
`NumFaces`); `cmap` lookup including variation selectors; `head`, `hhea`,
`hmtx`, `OS/2`, `name` and `post` metrics and names; legacy `kern`.
- **Outlines:** `Face.Outline` into a `PathSink`, `Face.GlyphPath` into a
`Path`, glyph bounds, `Affine` transforms with `Scale`, `Translate` and `Mul`.
- **Variable fonts:** `fvar`, `avar`, `gvar`, `HVAR`, `MVAR` and CFF2 variation
data through `Instance`, `InstanceAt`, `InstanceNamed` and `Normalize`; axes
and named instances.
- **Shaping:** `Shape` and the reusable `Shaper` with GSUB lookups 1 to 8 and
GPOS lookups 1 to 9, all lookup flags, feature variations, features
(`ParseFeature`), languages, scripts and directions; shapers for Arabic,
Syriac, N'Ko, the Indic scripts, Khmer, Myanmar, Tibetan, the Universal
Shaping Engine scripts, Thai, Lao and Hangul; `Shaper.ShapeRuns` for runs cut
by the caller; glyph origins (`WithOrigins`); pair kerning (`Kerning`).
- **Bidi:** `Bidi` implementing UAX #9 at Unicode 17.0.0 with levels, runs,
visual order and mirroring lookup (`BidiMirror`).
- **Segmentation:** `Segmenter` and iterators for UAX #14 line breaks and
UAX #29 grapheme, word and sentence boundaries at Unicode 17.0.0, plus
`IsEastAsianWide`, `IsSyllableScript` and `JoiningTypeOf`.
- **Fallback:** `FallbackChain`, `FontRuns` and `ShapeText`, which resolves
bidi, chooses a font per grapheme cluster and shapes every piece in visual
order.
- **Robustness:** bounded work, nesting and growth in shaping, charstrings,
composite glyphs and variation data; errors that wrap `ErrInvalidFont`,
`ErrUnsupportedFormat`, `ErrFaceIndex`, `ErrGlyphID`, `ErrLimit`,
`ErrInvalidArgument` and `ErrNotFound`; fuzz targets for the parsers, the
shaper and the Unicode algorithms.
- **Documentation:** package documentation, a runnable `Example` for each
feature, and benchmarks against other Go packages in `bench/`.
# Measure text width in Go with a font
**onefont-go** is a free, open-source font and text-shaping library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onefont) · [GitHub](https://github.com/recursive-ai-oss/onefont-go) · [Docs](https://recursiveai.org/onefont/go/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/go/cookbook/measure-shaped-text-width/measure-shaped-text-width.zip)
In the sample font, `AV` is narrower than `A` and `V` measured separately: shaping applies the font’s kerning, which brings the letters closer together.
```shell
go get recursiveai.org/go/onefont
```
Requires Go 1.24+.
```go
package main
import (
"fmt"
"os"
"recursiveai.org/go/onefont"
)
func main() {
face := loadFont()
run, err := onefont.Shape("AV", face)
if err != nil {
panic(err)
}
px := 16.0 * float64(run.Width()) /
float64(face.UnitsPerEm())
fmt.Printf("AV: %.2f px\n", px)
}
func loadFont() *onefont.Face {
data, err := os.ReadFile(
"NotoSans-Subset-Regular.ttf",
)
if err != nil {
panic(err)
}
face, err := onefont.Parse(data)
if err != nil {
panic(err)
}
return face
}
```
```text
AV: 19.18 px
```
That’s the distance the pen advances when it draws `AV`. If the font file is missing or can’t be parsed, the example stops at the error instead of reporting a width.
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onefont`, then `go run .`; or unzip [the example](https://recursiveai.org/onefont/go/cookbook/measure-shaped-text-width/measure-shaped-text-width.zip) and `go run .`.
If you paste the code, put `NotoSans-Subset-Regular.ttf` from the zip next to `main.go`, or use a different `.ttf` that contains `A` and `V` and change the filename in `loadFont`.
## Variations
**Measure at 32 px.** Replace the `px` calculation. With the same font and text, this prints `AV: 38.37 px`.
```go
px := 32.0 * float64(run.Width()) /
float64(face.UnitsPerEm())
```
## Related recipes
- [Set a variable font axis in Go](https://recursiveai.org/onefont/go/cookbook/instantiate-variable-font-axis/)
- [Split mixed RTL and LTR text into bidi runs in Go](https://recursiveai.org/onefont/go/cookbook/resolve-bidirectional-text-runs/)
## The short answer
Parse the exact font you plan to draw with. Call `onefont.Shape` and multiply `run.Width()` by the font size in pixels divided by `face.UnitsPerEm()`. `Width()` already sums the horizontal advances from shaping, in font units. It does not return pixels or the width of a box around the visible outline.
## How do you calculate text width in pixels from a font size?
A font defines its shapes and spacing on its own grid. `UnitsPerEm()` tells you how many units on that grid correspond to one em. At a font size of 16 px, one em spans 16 px; the conversion is `16 × run width ÷ units per em`. Keep that calculation in floating point and round only if a later step needs whole pixels. The example’s two decimal places are for display, not how the width is stored.
## What is kerning, and why does it affect text width?
Kerning changes the spacing between a pair of glyphs. Shaping can also replace multiple input characters with one glyph, such as a ligature, or position marks relative to a base letter. The result depends on the text and on what the font supports. It’s not enough to multiply a character count by an average width or to add the advances of individually mapped letters. Shape the same text, font, and features you’ll use to draw it. For a line that mixes directions or needs several fonts, use `ShapeText` with a font fallback chain; measure each returned run with its own font’s units per em before adding the pixel widths.
## Is advance width the same as the visible width of the text?
No. Advance answers “where should the next run start?” A space can advance the pen without painting anything, and an outline can stick out beyond its advance. For a tight crop around the ink, use glyph bounds instead: position each glyph’s bounds at its pen position plus the offsets from shaping, then take their union. The [OpenType horizontal metrics specification](https://learn.microsoft.com/en-us/typography/opentype/spec/hmtx) distinguishes advance width from side bearings.
# Convert a glyph outline to an SVG path in Go
**onefont-go** is a free, open-source font and text-shaping library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onefont) · [GitHub](https://github.com/recursive-ai-oss/onefont-go) · [Docs](https://recursiveai.org/onefont/go/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/go/cookbook/export-glyph-outline-as-svg-path/export-glyph-outline-as-svg-path.zip)
Read the glyph with `GlyphPath` and negate y for SVG.
```shell
go get recursiveai.org/go/onefont
```
Requires Go 1.24+.
```go
package main
import (
"fmt"
"os"
"recursiveai.org/go/onefont"
)
func main() {
face := loadFont()
glyph := face.GlyphIndex('L')
if glyph == 0 {
panic("glyph not in font")
}
path, err := face.GlyphPath(glyph)
if err != nil {
panic(err)
}
// M, L, Q, C, Z in PathSegmentKind order.
points := [...]int{1, 1, 2, 3, 0}
for seg := range path.All() {
fmt.Printf("%c", "MLQCZ"[seg.Kind])
n := points[seg.Kind]
for _, p := range seg.Pts[:n] {
fmt.Printf(" %g %g", p.X, 0-p.Y)
}
fmt.Println()
}
}
func loadFont() *onefont.Face {
data, err := os.ReadFile(
"NotoSans-Subset-Regular.ttf",
)
if err != nil {
panic(err)
}
face, err := onefont.Parse(data)
if err != nil {
panic(err)
}
return face
}
```
```text
M 97 0
L 97 -714
L 187 -714
L 187 -80
L 499 -80
L 499 0
Z
```
If the font doesn’t map the letter, the example stops instead of drawing the font’s missing glyph. If reading the outline fails, discard the path: it can be incomplete.
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onefont`, then `go run .`; or unzip [the example](https://recursiveai.org/onefont/go/cookbook/export-glyph-outline-as-svg-path/export-glyph-outline-as-svg-path.zip) and `go run .`.
If you paste the code, put `NotoSans-Subset-Regular.ttf` from the zip next to `main.go`, or use a different `.ttf` that contains `L` and change the filename in `loadFont`.
## Variations
**Export a glyph with curves.** Swap `L` for `C` in the example. TrueType outlines give `Q` (quadratic) curves, as in this example, while OpenType fonts with CFF outlines give `C` (cubic) curves.
```go
glyph := face.GlyphIndex('C')
```
**Display the `L` as a standalone SVG.** Paste the output into `d` and give the SVG a `viewBox` that includes the negative y coordinates. Save this as `letter.svg` and open it in a browser.
```svg
```
## Related recipes
- [Measure text width in Go with a font](https://recursiveai.org/onefont/go/cookbook/measure-shaped-text-width/)
- [Set a variable font axis in Go](https://recursiveai.org/onefont/go/cookbook/instantiate-variable-font-axis/)
## The short answer
Look up the character’s glyph ID with `GlyphIndex`, then call `GlyphPath`. Write an absolute SVG command for each segment: `M` for move, `L` for line, `Q` for a quadratic curve, `C` for a cubic curve, and `Z` to close. For every endpoint and control point, keep x and negate y. The output is geometry in font units, not an image or an embedded font.
## How do you generate SVG path data from a font glyph?
The segment kind tells you how many coordinate pairs to write. Moves and lines have one pair. A TrueType quadratic curve has a control point followed by the endpoint. A CFF cubic curve has two controls followed by the endpoint. The uppercase commands in the [SVG path specification](https://www.w3.org/TR/SVG2/paths.html#PathData) use absolute positions, so you can write the points directly after flipping y. Keep every new `M` and closing `Z`: a glyph can contain multiple contours, including contours that form holes. A space may return an empty path without returning an error.
## Why is my SVG glyph upside down or clipped?
Font outlines normally put the baseline at y = 0 and use positive y above it. In SVG, positive y points down in the [initial coordinate system](https://www.w3.org/TR/SVG2/coords.html#InitialCoordinateSystem). After the flip, the top of this `L` is at −714. A view box starting at y = 0 would miss the part above the baseline, so the standalone example starts at −750. Those bounds fit this sample; choose new bounds when you export a different glyph. To compute a box from `GlyphBounds`, flip the y range as well: the new minimum y is the negative of the font’s maximum y.
## Can you convert text to SVG paths the same way?
For a string, shape it first and export the glyph IDs the shaper returns. Mapping letters one by one can miss ligatures and contextual forms. Place each outline using the pen advance and offsets from the shaped run; then convert the positioned points to SVG coordinates. Paths no longer carry the original text for selection, search, or assistive technology, so keep the text separately where that matters.
# Set a variable font axis in Go
**onefont-go** is a free, open-source font and text-shaping library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onefont) · [GitHub](https://github.com/recursive-ai-oss/onefont-go) · [Docs](https://recursiveai.org/onefont/go/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/go/cookbook/instantiate-variable-font-axis/instantiate-variable-font-axis.zip)
Set `wght` to 900 with `Face.Instance`, then read `A`’s advance width: the horizontal space the glyph takes.
```shell
go get recursiveai.org/go/onefont
```
Requires Go 1.24+.
```go
package main
import (
"fmt"
"os"
"recursiveai.org/go/onefont"
)
func main() {
face := loadFont()
instance, err := face.Instance(
onefont.Variation{
Tag: onefont.MakeTag("wght"),
Value: 900,
},
)
if err != nil {
panic(err)
}
glyph := instance.GlyphIndex('A')
fmt.Println("Default A:",
face.Advance(glyph))
fmt.Println("wght 900 A:",
instance.Advance(glyph))
}
func loadFont() *onefont.Face {
data, err := os.ReadFile("RobotoFlex.ttf")
if err != nil {
panic(err)
}
face, err := onefont.Parse(data)
if err != nil {
panic(err)
}
return face
}
```
```text
Default A: 1280
wght 900 A: 1452
```
If the font has no variation axes, `Instance` returns the default design rather than an error. Check `face.Axes()` if you need to require a specific axis.
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onefont`, then `go run .`; or unzip [the example](https://recursiveai.org/onefont/go/cookbook/instantiate-variable-font-axis/instantiate-variable-font-axis.zip) and `go run .`.
If you paste the code, put `RobotoFlex.ttf` from the zip next to `main.go`, or use a different variable `.ttf` with a `wght` axis and change the filename in `loadFont`.
## Variations
**Set the width axis instead.** Replace the `face.Instance` call, keeping the error check. Change the second output label to `wdth 75 A:`. The advance at this width is `1216` font units.
```go
instance, err := face.Instance(
onefont.Variation{
Tag: onefont.MakeTag("wdth"),
Value: 75,
},
)
```
## Related recipes
- [Measure text width in Go with a font](https://recursiveai.org/onefont/go/cookbook/measure-shaped-text-width/)
- [Convert a glyph outline to an SVG path in Go](https://recursiveai.org/onefont/go/cookbook/export-glyph-outline-as-svg-path/)
## The short answer
Call `face.Instance` with a `Variation` containing the four-letter axis tag and a coordinate. For example, `wght` at 900 sets the weight axis of the returned instance; it does not modify the original face. Read the new design’s metric with `instance.Advance(glyph)`. This returns an instance for measuring and shaping, not a new TTF file.
## What is a variable weight font?
A variable weight font can provide intermediate designs between its light and heavy extremes. `wght` is the [registered OpenType axis for weight](https://learn.microsoft.com/en-us/typography/opentype/spec/dvaraxistag_wght). The value is a design coordinate, not a percentage of boldness. A heavier design can also change letter spacing: in the bundled Roboto Flex file, `A` advances 1280 font units at the default design and 1452 at `wght` 900. That difference is specific to this font and glyph. Don’t assume every heavier glyph will get wider.
## How do you find a variable font’s axis ranges?
Read `face.Axes()` for the tag and the `Min`, `Default`, and `Max` values for each axis. Use them to decide which controls to offer and what ranges they accept. `Instance` clamps a supplied coordinate to the font’s range, and each axis you omit keeps its default. An unknown tag won’t change the font, so check that a tag is present before accepting it from a user. `instance.Variations()` reports the effective coordinates after clamping. Those are more useful to show in an interface than the raw numbers you requested.
## Does setting font weight change how text is measured?
It can. The example reads the advance of one glyph, the distance from its origin to the next pen position. For a word, pass the instance instead of the face to `onefont.Shape`, use the shaped run’s width, and convert from font units at your chosen size. Use the same instance for drawing the glyph outlines. Otherwise you can measure a word at the new weight and accidentally draw it with the original advances or outlines.
# Split mixed RTL and LTR text into bidi runs in Go
**onefont-go** is a free, open-source font and text-shaping library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onefont) · [GitHub](https://github.com/recursive-ai-oss/onefont-go) · [Docs](https://recursiveai.org/onefont/go/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/go/cookbook/resolve-bidirectional-text-runs/resolve-bidirectional-text-runs.zip)
Call `ResolveBidi`, then read `Runs` in display order.
```shell
go get recursiveai.org/go/onefont
```
Requires Go 1.24+. No font needed.
```go
package main
import (
"fmt"
"recursiveai.org/go/onefont"
)
func main() {
text := "abc אבג 123"
bidi := onefont.ResolveBidi(
text, onefont.DirectionAuto,
)
for run := range bidi.Runs(0, len(text)) {
fmt.Printf("%q RTL=%t\n",
text[run.Start:run.End], run.RTL())
}
}
```
```text
"abc " RTL=false
"123" RTL=false
"אבג " RTL=true
```
The string is stored as `abc`, then Hebrew, then `123`; the browser reorders it on screen.
The number run appears before the Hebrew run in visual order, and it still reads left to right. The printed Hebrew substring itself is unchanged.
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onefont`, then `go run .`; or unzip [the example](https://recursiveai.org/onefont/go/cookbook/resolve-bidirectional-text-runs/resolve-bidirectional-text-runs.zip) and `go run .`.
## Variations
**Use a right-to-left paragraph base.** Replace the `ResolveBidi` call. This moves `abc` to the rightmost run; the digits still form a left-to-right run.
```go
bidi := onefont.ResolveBidi(
text, onefont.DirectionRTL,
)
```
```text
"123" RTL=false
" אבג " RTL=true
"abc" RTL=false
```
## Related recipes
- [Measure text width in Go with a font](https://recursiveai.org/onefont/go/cookbook/measure-shaped-text-width/)
- [Go font and shaping quickstart](https://recursiveai.org/onefont/go/docs/getting-started/)
## The short answer
Call `ResolveBidi` with the original string and a base direction. Iterate `bidi.Runs(0, len(text))` for one line in visual order, from its left edge to its right edge. `run.Start` and `run.End` are byte offsets in the original Go string, so `text[run.Start:run.End]` gives you the original substring. Call `run.RTL()` to decide how that piece reads.
## What is bidirectional text?
Bidirectional text combines material that reads right to left, such as Hebrew or Arabic, with material that reads left to right, such as Latin words or numbers. A split at spaces or at every script change doesn’t resolve the direction of spaces, punctuation, or digits. The [Unicode Bidirectional Algorithm](https://www.unicode.org/reports/tr9/) assigns embedding levels to resolve those cases. With `DirectionAuto`, the first strong directional character sets the paragraph base for this example. Specify `DirectionLTR` or `DirectionRTL` when a document already gives you the base direction.
## What is the difference between logical and visual order in bidi text?
Logical order is the order in which characters are stored; visual order is how they are placed on a line. The sample prints its runs in visual order, but each slice is still in logical order. That’s why the Hebrew substring isn’t printed as reversed text. Hand that original slice and its direction to the shaper instead of reversing bytes or runes yourself. Reversing bytes can break UTF-8, and reversing runes can separate a combining mark from its base.
## How do you handle bidi runs when text wraps?
Resolve the paragraph as a whole, then pass each actual line’s start and end byte offsets to `Runs`. The line routine applies the bidi rules for those bounds, so the same paragraph can produce different runs depending on where it wraps. `ResolveBidi` doesn’t choose line breaks or turn characters into glyphs. If the next step is to shape a line with font fallback, `ShapeText` combines bidi resolution with font selection and shaping for the text you pass it.
# Decompress WOFF2 to a font file in Go
**onefont-go** is a free, open-source font and text-shaping library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onefont) · [GitHub](https://github.com/recursive-ai-oss/onefont-go) · [Docs](https://recursiveai.org/onefont/go/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/go/cookbook/decompress-woff2-to-sfnt/decompress-woff2-to-sfnt.zip)
Use `UnwrapWebFont` to recover the font inside a WOFF2 file; the first four bytes of the unpacked font tell you whether it’s TTF, OTF, or TTC. The zip includes a Noto Sans web font.
```shell
go get recursiveai.org/go/onefont
```
```go
package main
import (
"fmt"
"log"
"os"
"recursiveai.org/go/onefont"
)
func main() {
input := "NotoSans-Subset-Regular.woff2"
data, err := os.ReadFile(input)
if err != nil {
log.Fatal(err)
}
font, err := onefont.UnwrapWebFont(data,
onefont.WithMaxFontSize(8<<20))
if err != nil {
log.Fatal(err)
}
var ext string
switch string(font[:4]) {
case "\x00\x01\x00\x00", "true":
ext = ".ttf"
case "OTTO":
ext = ".otf"
case "ttcf":
ext = ".ttc"
default:
log.Fatalf("unknown SFNT flavor: %x", font[:4])
}
output := "unpacked" + ext
err = os.WriteFile(output, font, 0644)
if err != nil {
log.Fatal(err)
}
fmt.Println("Wrote", output)
}
```
```text
Wrote unpacked.ttf
```
`UnwrapWebFont` returns an error for damaged input or a font that exceeds the unpacked-size limit. The program writes no file in either case.
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onefont`, then `go run .`; or unzip [the example](https://recursiveai.org/onefont/go/cookbook/decompress-woff2-to-sfnt/decompress-woff2-to-sfnt.zip) and `go run .`.
Requires Go 1.24 or later.
## Variations
**Unpack a CFF web font.** Use an input that contains CFF outlines, such as [the pinned `cff.woff2` example](https://raw.githubusercontent.com/recursive-ai-oss/onefont-go/2a9a35cbfcd2e359c0178abdf2e0beaef4a7213f/testdata/webfont/cff.woff2). Save the raw file beside `main.go` and change the input:
```go
input := "cff.woff2"
```
```text
Wrote unpacked.otf
```
**Unpack a collection.** Download [the pinned `collection.woff2` example](https://raw.githubusercontent.com/recursive-ai-oss/onefont-go/2a9a35cbfcd2e359c0178abdf2e0beaef4a7213f/testdata/webfont/collection.woff2) the same way:
```go
input := "collection.woff2"
```
```text
Wrote unpacked.ttc
```
## Related recipes
- [Inspect an unpacked font in Go](https://recursiveai.org/onefont/go/docs/getting-started/#load-a-font)
## The short answer
Call `onefont.UnwrapWebFont` on the file’s bytes, then write the returned slice as a font file. Choose `.ttf`, `.otf`, or `.ttc` from the signature of the *unpacked* font. The `.woff2` suffix only tells you about the wrapper.
## Can you convert WOFF2 to TTF?
Yes, if the web font wraps a font with TrueType outlines. The [OpenType file specification](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#table-directory) gives `00 01 00 00` as the sfnt version for those outlines. The sample has that signature, so the program writes `unpacked.ttf`. An sfnt is a font container built from named tables; the program checks its first four bytes rather than looking for a family name or a filename extension.
Unwrapping is not an outline conversion. If the source is a web subset with only the characters needed by a site, the output is still that subset. A `.ttf` extension will not restore missing characters, weights, or tables. And the output need not be byte-for-byte identical to the font before compression: onefont-go reverses WOFF2 table transforms and recomputes the table checksums. It skips the wrapper’s optional metadata and private data.
## How can I convert a WOFF2 file to OTF?
Use the same call. An unpacked `OTTO` signature means the OpenType font contains CFF or CFF2 outlines; give it the `.otf` extension. If you get `ttcf` instead, keep the result as a `.ttc` collection. It can hold multiple faces, not just one. If a downstream tool accepts only TrueType outlines, changing the extension of an `OTTO` result will not make it compatible.
## How can I convert a WOFF2 file without using a web service?
`UnwrapWebFont` runs locally. It also accepts WOFF 1.0. Use `IsWebFont` if one code path needs to handle both already-unpacked and wrapped fonts: it checks the signature only, not whether the remaining data is valid. When you only want to inspect or shape a face, pass the unpacked bytes to `Parse` without writing a copy first.
A compressed file can be small even when the unpacked tables are large. The example sets an 8 MiB output limit with `WithMaxFontSize`; omitting it uses the library’s 64 MiB default. If a known font needs a higher limit than your application chose, raise it for that input rather than inferring an output limit from the file size.
# Find Thai line break opportunities in Go
**onefont-go** is a free, open-source font and text-shaping library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onefont) · [GitHub](https://github.com/recursive-ai-oss/onefont-go) · [Docs](https://recursiveai.org/onefont/go/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/go/cookbook/find-thai-line-breaks/find-thai-line-breaks.zip)
Use `AppendLineBreaks` to find Thai wrap points where there are no spaces. It finds candidates, not the lines that fit.
```shell
go get recursiveai.org/go/onefont
```
```go
package main
import (
"fmt"
"recursiveai.org/go/onefont"
)
func main() {
text := "สวัสดีครับผมชื่อสมชาย"
var segmenter onefont.Segmenter
start := 0
breaks := segmenter.AppendLineBreaks(nil, text)
for _, b := range breaks {
fmt.Printf("%d %s\n", b.Pos, text[start:b.Pos])
start = b.Pos
}
}
```
```text
18 สวัสดี
30 ครับ
36 ผม
48 ชื่อ
63 สมชาย
```
Each line shows a candidate end byte and the text since the previous candidate. These are **not** the lines a layout engine would draw.
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onefont`, then `go run .`; or unzip [the example](https://recursiveai.org/onefont/go/cookbook/find-thai-line-breaks/find-thai-line-breaks.zip) and `go run .`.
Requires Go 1.24 or later.
## Variations
**Compare with Unicode’s rules alone.** Replace the declaration of `segmenter` to turn the dictionary off:
```go
segmenter := onefont.Segmenter{NoDictionary: true}
```
```text
63 สวัสดีครับผมชื่อสมชาย
```
## Related recipes
- [Iterate Unicode grapheme clusters in Go](https://recursiveai.org/onefont/go/cookbook/split-string-into-grapheme-clusters/)
- [Choose an emoji fallback font in Go](https://recursiveai.org/onefont/go/cookbook/shape-text-with-emoji-fallback/)
## The short answer
Use a zero-value `onefont.Segmenter` and call `AppendLineBreaks(nil, text)`. The built-in dictionary adds break opportunities inside Thai letter runs. `Pos` is a UTF-8 byte offset that you can use to slice the original Go string. No font or target width is needed to find these opportunities.
## How do you break Thai text without spaces?
Don’t split on spaces or after a fixed number of runes. In `สวัสดีครับผมชื่อสมชาย`, the first internal opportunity is after `สวัสดี`, at byte 18. A width-independent split on spaces would find no internal breaks. [Unicode’s line-breaking algorithm](https://www.unicode.org/reports/tr14/#SA) leaves this kind of letter run to language-specific analysis. onefont-go matches against its built-in word lists for Thai, Lao, Khmer and Burmese.
The dictionary may not contain every name or term in your text. An unmatched stretch stays together until the next word the dictionary recognizes. The result is a set of allowed break positions, not a general-purpose Thai tokenizer. `NoDictionary` switches off only dictionary line breaking, not the other Unicode line-breaking rules or the grapheme iterator.
## How do you wrap Thai text to fit a width?
Find the opportunities first, then use your font and size to measure candidate lines. For a simple greedy wrap, start from the beginning of the line and keep the last legal end that fits. At a mandatory break, end the line even if there is room. `Pos` includes the point after a hard break such as a newline; separate that separator from the text you draw.
The width check needs shaped advances, not bytes or a count of dictionary words. Shape the text you intend to draw; with a fixed font, scale the resulting advance from font units to pixels using the font’s units per em. If no candidate fits the line, decide whether your application will allow overflow or use a separate emergency-break policy. A grapheme boundary won’t cut a combining sequence in half, but that does not make it a normal Thai line-break opportunity.
The last candidate is normally the end of the paragraph, not a request to insert a newline. Check `Mandatory` rather than treating every returned offset as a forced line end. If you need to keep the same segmenter for several paragraphs, reuse it in one goroutine or use a separate one for each concurrent worker.
# Choose an emoji fallback font in Go
**onefont-go** is a free, open-source font and text-shaping library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onefont) · [GitHub](https://github.com/recursive-ai-oss/onefont-go) · [Docs](https://recursiveai.org/onefont/go/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/go/cookbook/shape-text-with-emoji-fallback/shape-text-with-emoji-fallback.zip)
Use `WithEmojiPresentation` to prefer a color face for keycaps and other emoji sequences. Both sample fonts are in the zip.
```shell
go get recursiveai.org/go/onefont
```
```go
package main
import (
"fmt"
"log"
"os"
"recursiveai.org/go/onefont"
)
func main() {
textFont := load("NotoSans-Subset-Regular.ttf")
emojiFont := load("Noto-Emoji-Keycap.ttf")
chain := onefont.NewFallbackChain(textFont, emojiFont).
WithEmojiPresentation()
text := "1\uFE0E 1\uFE0F\u20E3"
for run, err := range onefont.ShapeText(text, chain) {
if err != nil {
log.Fatal(err)
}
fmt.Printf("bytes %d:%d, font %d, %d glyphs\n",
run.Start, run.End, run.Font, run.Run.Len())
}
}
func load(path string) *onefont.Face {
data, err := os.ReadFile(path)
if err != nil {
log.Fatal(err)
}
face, err := onefont.Parse(data)
if err != nil {
log.Fatal(err)
}
return face
}
```
```text
bytes 0:5, font 0, 3 glyphs
bytes 5:12, font 1, 1 glyphs
```
`1\uFE0E` asks for text presentation. `1\uFE0F\u20E3` is an emoji keycap; the latter uses font 1, the emoji face. The space stays with font 0.
Paste the code above into `main.go`, put both `.ttf` files from the zip next to it, run `go mod init example` and `go get recursiveai.org/go/onefont`, then `go run .`; or unzip [the example](https://recursiveai.org/onefont/go/cookbook/shape-text-with-emoji-fallback/shape-text-with-emoji-fallback.zip) and `go run .`.
Requires Go 1.24 or later.
## Variations
**Use first covering font instead.** Drop `WithEmojiPresentation` from the chain declaration:
```go
chain := onefont.NewFallbackChain(textFont, emojiFont)
```
```text
bytes 0:12, font 0, 6 glyphs
```
## Related recipes
- [Iterate Unicode grapheme clusters in Go](https://recursiveai.org/onefont/go/cookbook/split-string-into-grapheme-clusters/)
- [Apply an OpenType feature to a range in Go](https://recursiveai.org/onefont/go/cookbook/apply-opentype-feature-to-text-range/)
## The short answer
Load your primary text face and a color emoji face. Pass them in that order to `NewFallbackChain`, then call `WithEmojiPresentation()` on the chain and pass the result to `ShapeText`. The runs report a font index as well as glyphs. In the sample, both faces have a glyph for `1`, but the presentation request makes the keycap use the second face.
## How do I change the emoji font without changing the text font?
Keep your preferred text face first and put your emoji face after it. Without the presentation option, the first font that covers the first code point in each grapheme cluster wins. For emoji sequences recognized by `WithEmojiPresentation`, onefont-go instead looks for the first covering face that has a `CBDT`, `COLR`, `sbix`, or `SVG ` table. If no such face covers the base, choice falls back to the normal order.
This lets you change the emoji face without putting it ahead of your text face for ordinary text. For example, moving the emoji face to the front simply to fix keycaps can also change the face used for plain digits. The option returns a new chain; pass that chain, not the original, to `ShapeText`.
## How do I force text or emoji presentation?
The [Unicode emoji standard](https://www.unicode.org/reports/tr51/#Emoji_Variation_Sequences) defines U+FE0E (VS15) for text presentation and U+FE0F (VS16) for emoji presentation. onefont-go uses its ordinary order for a cluster with VS15. It prefers a color face for a cluster with VS16 or a recognized emoji sequence such as a keycap or a flag made from two regional indicators. A standalone emoji without a selector follows ordinary font order in this release. A selector is therefore a request used in font choice, not a guarantee that a specific font or glyph will appear.
## Why does an emoji still show separate glyphs or no color?
Font choice and drawing are different. The fallback chain tests coverage of the cluster’s first code point, not whether the entire sequence maps to a single glyph in that font. A color table also doesn’t guarantee that the chosen glyph has color data. Use fonts that contain the sequences you expect and a renderer that supports the chosen font’s color format. `ShapeText` provides the glyphs and positions; it doesn’t rasterize them. If you retain glyphs after advancing its iterator, copy them: the run storage is reused.
# Apply an OpenType feature to a range in Go
**onefont-go** is a free, open-source font and text-shaping library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onefont) · [GitHub](https://github.com/recursive-ai-oss/onefont-go) · [Docs](https://recursiveai.org/onefont/go/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/go/cookbook/apply-opentype-feature-to-text-range/apply-opentype-feature-to-text-range.zip)
Pass `-liga[3:5]` to `ParseFeatureRange` to turn off the `fi` ligature over those bytes only. The zip includes the sample font.
```shell
go get recursiveai.org/go/onefont
```
```go
package main
import (
"fmt"
"log"
"os"
"recursiveai.org/go/onefont"
)
func main() {
text := "é fi fi"
feature, err := onefont.ParseFeatureRange("-liga[3:5]")
if err != nil {
log.Fatal(err)
}
data, err := os.ReadFile("NotoSans-Subset-Regular.ttf")
if err != nil {
log.Fatal(err)
}
face, err := onefont.Parse(data)
if err != nil {
log.Fatal(err)
}
run, err := onefont.Shape(text, face,
onefont.WithFeatureRanges(feature))
if err != nil {
log.Fatal(err)
}
for _, glyph := range run.All() {
fmt.Printf("byte %d: glyph %d\n",
glyph.Cluster, glyph.Glyph)
}
}
```
```text
byte 0: glyph 169
byte 2: glyph 1
byte 3: glyph 71
byte 4: glyph 74
byte 5: glyph 1
byte 6: glyph 339
```
Offsets are UTF-8 bytes: `é` takes two bytes, so the first `fi` spans `[3:5]` (byte 5 is excluded).
The first `fi` yields separate glyphs at bytes 3 and 4. The second yields one glyph at byte 6. Glyph IDs are specific to this font.
Paste the code above into `main.go`, put `NotoSans-Subset-Regular.ttf` from the zip next to it, run `go mod init example` and `go get recursiveai.org/go/onefont`, then `go run .`; or unzip [the example](https://recursiveai.org/onefont/go/cookbook/apply-opentype-feature-to-text-range/apply-opentype-feature-to-text-range.zip) and `go run .`.
Requires Go 1.24 or later.
## Variations
**Disable the second ligature instead.** Change the range in the sample:
```go
feature, err := onefont.ParseFeatureRange("-liga[6:8]")
```
```text
byte 0: glyph 169
byte 2: glyph 1
byte 3: glyph 339
byte 5: glyph 1
byte 6: glyph 71
byte 7: glyph 74
```
## Related recipes
- [Choose an emoji fallback font in Go](https://recursiveai.org/onefont/go/cookbook/shape-text-with-emoji-fallback/)
- [Iterate Unicode grapheme clusters in Go](https://recursiveai.org/onefont/go/cookbook/split-string-into-grapheme-clusters/)
## The short answer
Parse a setting like `-liga[3:5]` with `onefont.ParseFeatureRange` and pass it to `onefont.Shape` through `onefont.WithFeatureRanges`. The interval is start-inclusive and end-exclusive, in UTF-8 **bytes**. The feature is off inside that range; it keeps its normal value elsewhere.
## What is an OpenType feature?
An OpenType feature is a font rule for substituting or positioning glyphs. The [registered OpenType feature tags](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist) include `liga` for standard ligatures and `kern` for kerning, which adjusts spacing between glyphs. Turning off `liga` changes the glyphs the shaper returns. It doesn’t edit the Go string or replace its letters with the Unicode ligature character. If your font lacks the feature, the shaper ignores the setting; the same range applied to another font need not give the same glyph count.
## How do I use OpenType features on just part of a string?
In `é fi fi`, `é` takes two UTF-8 bytes. The first space is at byte 2, so the first `fi` spans `[3:5]`. The second `fi` starts at byte 6. If your selection comes from a rune or character index, convert it to a byte offset before building the range. For text selected by a user, choose boundaries that don’t cut through a grapheme cluster. If you are composing the text from known pieces, the byte length of the preceding text is the start, and adding the byte length of the selected piece gives the end.
A range can override a whole-run `WithFeatures` setting as well as a script default. Outside the range, the whole-run or default setting still applies. If ranges for the same tag overlap, the last setting wins. An empty or reversed range matches no glyphs. When shaping with `ShapeRuns` or `ShapeText`, count these offsets from the whole string you passed in, even if the shaper splits it into several runs. Recalculate the range if the source string changes before the call.
# Iterate Unicode grapheme clusters in Go
**onefont-go** is a free, open-source font and text-shaping library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onefont) · [GitHub](https://github.com/recursive-ai-oss/onefont-go) · [Docs](https://recursiveai.org/onefont/go/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/go/cookbook/split-string-into-grapheme-clusters/split-string-into-grapheme-clusters.zip)
Range over `onefont.Graphemes` to keep a letter with its combining accent or an emoji sequence together.
```shell
go get recursiveai.org/go/onefont
```
```go
package main
import (
"fmt"
"unicode/utf8"
"recursiveai.org/go/onefont"
)
func main() {
text := "e\u0301👨👩👧x"
for cluster := range onefont.Graphemes(text) {
runes := utf8.RuneCountInString(cluster)
fmt.Printf("%s: %d\n", cluster, runes)
}
}
```
The number after each cluster is its rune count, not its byte length.
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onefont`, then `go run .`; or unzip [the example](https://recursiveai.org/onefont/go/cookbook/split-string-into-grapheme-clusters/split-string-into-grapheme-clusters.zip) and `go run .`.
Requires Go 1.24 or later.
```text
é: 2
👨👩👧: 5
x: 1
```
## Variations
**Keep byte offsets.** Remove the `unicode/utf8` import and replace the loop in `main`:
```go
start := 0
for end := range onefont.GraphemeBreaks(text) {
fmt.Printf("%d:%d %s\n", start, end, text[start:end])
start = end
}
```
```text
0:3 é
3:21 👨👩👧
21:22 x
```
## Related recipes
- [Find Thai line break opportunities in Go](https://recursiveai.org/onefont/go/cookbook/find-thai-line-breaks/)
- [Choose an emoji fallback font in Go](https://recursiveai.org/onefont/go/cookbook/shape-text-with-emoji-fallback/)
## The short answer
Range over `onefont.Graphemes(text)` to get substrings containing one extended grapheme cluster each. Use `onefont.GraphemeBreaks(text)` when you need byte offsets into the original string, for example to place a caret or delete the last cluster without leaving part of it behind.
## What is the difference between runes and grapheme clusters in Go?
[`range` on a Go string](https://go.dev/ref/spec#For_range) decodes one UTF-8 code point at a time and yields its byte index and rune. That is useful when the code point is the unit you need. For cursor movement or character limits in a text field, it can split what a reader sees as one unit. In the sample, `e` and U+0301 (combining acute accent) are separate runes. The family emoji is three pictographs joined by two zero-width joiners. Each sequence is one cluster, even though neither is one rune.
A cluster is also not a glyph or a unit of display width. The shape a font draws can depend on its rules and on surrounding text. Count clusters to enforce a text length expressed in perceived characters, not to decide how many clusters fit on a line.
## How do I slice a Go string without breaking accents or emoji?
Use the end of a cluster from `GraphemeBreaks` as the slice boundary. Its first return value for the sample is `3`, so `text[:3]` includes the base letter *and* the accent. The next boundary is `21`; `text[3:21]` is the complete emoji sequence. Keep the previous offset (starting at zero) if you need both ends. Don’t use a count of clusters as a byte index, and don’t subtract one from an exclusive end: that can leave a partial UTF-8 encoding.
The iterator follows the [default extended grapheme cluster rules in Unicode UAX #29](https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries). onefont-go v1.1.1 uses Unicode 17.0.0. It does not normalize text: precomposed `é` and `e` followed by the combining accent can both be one cluster while remaining different strings. For nonempty input the last boundary is `len(text)`, and there’s no boundary at zero; empty input yields none.