API Reference

API Reference

Complete reference of the exported types and functions in the ot package (github.com/boxesandglue/textshape/ot).

Font Loading

ParseFont

func ParseFont(data []byte, index int) (*Font, error)

Parses an OpenType font from raw bytes. Supports TrueType (.ttf), OpenType (.otf), TrueType Collections (.ttc), and DFONTs. Use index = 0 for single-font files.

Font Methods

Method Returns Description
NumGlyphs() int Number of glyphs in the font
HasTable(tag Tag) bool Check if a table exists
TableData(tag Tag) []byte, error Get raw table data
HasGlyph(cp Codepoint) bool Check if a codepoint has a glyph
HasGlyphNames() bool Check if glyph names are available
GetGlyphName(glyph GlyphID) string Get name for a glyph ID
GetGlyphFromName(name string) GlyphID, bool Get glyph ID from name

Face (Font Metrics)

NewFace

func NewFace(font *Font) (*Face, error)

Creates a Face with parsed metric tables (OS/2, hhea, head, etc.).

Face Methods

Method Returns Description
Upem() uint16 Units per em
Ascender() int16 Typographic ascender
Descender() int16 Typographic descender (negative)
CapHeight() int16 Capital letter height
XHeight() int16 Lowercase x height
LineGap() int16 Recommended line gap
BBox() int16 × 4 Font bounding box (xMin, yMin, xMax, yMax)
IsFixedPitch() bool Monospace font
IsItalic() bool Italic font
ItalicAngle() int32 Italic angle
WeightClass() uint16 CSS weight class (100–900)
PostscriptName() string PostScript name
FamilyName() string Font family name
IsCFF() bool CFF/CFF2 outlines (vs TrueType)
HasVariations() bool Is a variable font
VariationAxes() []AxisInfo List of variation axes
FindVariationAxis(tag Tag) AxisInfo, bool Find axis by tag
NamedInstances() []NamedInstance Predefined variation instances
HorizontalAdvance(glyph GlyphID) float32 Glyph advance
GetHExtents() FontExtents Horizontal font extents
Cmap() *Cmap Character-to-glyph mapping table
GlyphOutline(glyph GlyphID) GlyphOutline, bool Extract glyph path segments (TrueType and CFF)

Shaper

NewShaper / NewShaperFromFace

func NewShaper(font *Font) (*Shaper, error)
func NewShaperFromFace(face *Face) (*Shaper, error)

Creates a shaper. NewShaper creates a Face internally. NewShaperFromFace reuses an existing one.

Shaping

Method Description
Shape(buf *Buffer, features []Feature) Shape text in the buffer. Pass nil for default features.
ShapeString(text string) ([]GlyphID, []GlyphPos) Convenience: shape a string with auto-detected direction and default features

Features

Method Description
SetDefaultFeatures(features []Feature) Set features used when Shape receives nil
GetDefaultFeatures() []Feature Get current default features

Variable Fonts

Method Description
HasVariations() bool Whether the font has variation axes
SetVariations(variations []Variation) Set multiple axis values (resets unspecified to defaults)
SetVariation(tag Tag, value float32) Set a single axis value
SetNamedInstance(index int) Apply a named instance
DesignCoords() []float32 Current user-space axis coordinates
NormalizedCoords() []float32 Normalized axis coordinates [-1, 1]

Synthetic Bold/Slant

Method Description
SetSyntheticBold(x, y float32, inPlace bool) Set embolden strength in em-units
SyntheticBold() (x, y float32, inPlace bool) Get current bold parameters
SetSyntheticSlant(slant float32) Set shear factor
SyntheticSlant() float32 Get current slant value

Font Access

Method Description
Font() *Font Get the underlying font
HasGSUB() bool GSUB table available
HasGPOS() bool GPOS table available
HasGDEF() bool GDEF table available
HasHmtx() bool Horizontal metrics available
GDEF() *GDEF Get GDEF table (may be nil)
GetGlyphHAdvanceVar(glyph GlyphID) uint16 Horizontal advance with variation deltas
GetGlyphVOrigin(glyph GlyphID) (x, y int16) Vertical origin for a glyph

Buffer

NewBuffer

func NewBuffer() *Buffer

Creates an empty buffer.

Fields

Field Type Description
Info []GlyphInfo Glyph information (input/output)
Pos []GlyphPos Glyph positions (output)
Direction Direction Text direction
Flags BufferFlags Shaping behavior flags
Script Tag ISO 15924 script tag
Language Tag OpenType language tag
LanguageCandidates []Tag Multiple language candidates
PreContext []Codepoint Surrounding context before text
PostContext []Codepoint Surrounding context after text
ClusterLevel int Cluster merging mode (0–3)
NotFoundVSGlyph int Glyph for missing variation selectors (-1 = remove)

Methods

Method Description
AddString(s string) Add UTF-8 text
AddCodepoints(codepoints []Codepoint) Add Unicode codepoints
GuessSegmentProperties() Auto-detect direction, script, language
SetDirection(dir Direction) Set text direction
Len() int Number of glyphs
Clear() Remove glyphs, keep properties
Reset() Remove glyphs and reset all properties
Reverse() Reverse glyph order
ReverseRange(start, end int) Reverse a range
GlyphIDs() []GlyphID Extract glyph IDs
MergeClusters(start, end int) Merge cluster values in range
AllocateLigID() uint8 Get unique ligature ID

GlyphInfo

Information about a shaped glyph.

Field Type Description
Codepoint Codepoint Original Unicode codepoint
GlyphID GlyphID Glyph index in the font
Cluster int Cluster index (maps to input text position)

Classification Methods

Method Returns Description
IsBaseGlyph() bool Base glyph (letter, digit, …)
IsMark() bool Combining mark
IsLigature() bool Result of ligature substitution
IsLigated() bool Was substituted by a ligature
IsMultiplied() bool Part of multiple substitution
GetLigID() uint8 Ligature ID
GetLigComp() uint8 Component index in ligature
GetLigNumComps() int Number of components

GlyphPos

Positioning information for a shaped glyph. All values are in font units.

Field Type Description
XAdvance int16 Horizontal advance
YAdvance int16 Vertical advance
XOffset int16 Horizontal offset from current position
YOffset int16 Vertical offset from current position

Feature

type Feature struct {
    Tag   Tag
    Value uint32
    Start uint
    End   uint
}

Constructors

Function Description
NewFeature(tag Tag, value uint32) Feature Feature with specific value, global range
NewFeatureOn(tag Tag) Feature Enable feature globally
NewFeatureOff(tag Tag) Feature Disable feature globally
FeatureFromString(s string) (Feature, bool) Parse from string (e.g., "smcp", "-liga", "kern[3:5]=0")
ParseFeatures(s string) []Feature Parse comma-separated list
DefaultFeatures() []Feature Default feature set (kern, liga, calt, mark, …)

Methods

Method Description
IsGlobal() bool Applies to entire buffer
String() string Format as string

Glyph Outlines

Types for representing glyph vector paths. See Glyph Outlines for usage.

SegmentOp

type SegmentOp uint8

const (
    SegmentMoveTo SegmentOp = iota  // Start new contour
    SegmentLineTo                    // Straight line
    SegmentQuadTo                    // Quadratic Bezier (TrueType)
    SegmentCubeTo                    // Cubic Bezier (CFF/OpenType)
)

OutlinePoint

type OutlinePoint struct{ X, Y float32 }

A 2D point in font units.

Segment

type Segment struct {
    Op   SegmentOp
    Args [3]OutlinePoint  // Number of used entries depends on Op
}
Op Args used
SegmentMoveTo [0] = point
SegmentLineTo [0] = endpoint
SegmentQuadTo [0] = control, [1] = endpoint
SegmentCubeTo [0] = ctrl1, [1] = ctrl2, [2] = endpoint

GlyphOutline

type GlyphOutline struct {
    Segments []Segment
}

Returned by Face.GlyphOutline(gid). Contains the complete path of a glyph, including all contours. Composite glyphs are resolved recursively with transforms applied.

Basic Types

Tag

type Tag uint32

4-byte OpenType tag. Create with MakeTag(a, b, c, d byte). Convert to string with tag.String().

wght := ot.MakeTag('w', 'g', 'h', 't')
fmt.Println(wght.String()) // "wght"

Direction

type Direction int

const (
    DirectionLTR Direction = 4  // Left-to-Right
    DirectionRTL Direction = 5  // Right-to-Left
    DirectionTTB Direction = 6  // Top-to-Bottom
    DirectionBTT Direction = 7  // Bottom-to-Top
)
Method Description
IsValid() bool Is a valid direction
IsHorizontal() bool LTR or RTL
IsVertical() bool TTB or BTT
IsForward() bool LTR or TTB
IsBackward() bool RTL or BTT
Reverse() Direction Opposite direction

GlyphID / Codepoint

type GlyphID = uint16    // Glyph index in the font
type Codepoint = uint32  // Unicode codepoint

Variation

type Variation struct {
    Tag   Tag     // Axis tag (e.g., 'wght')
    Value float32 // Axis value
}

AxisInfo

type AxisInfo struct {
    Index        int
    Tag          Tag
    MinValue     float32
    DefaultValue float32
    MaxValue     float32
}

NamedInstance

type NamedInstance struct {
    Index             int
    SubfamilyNameID   uint16
    PostScriptNameID  uint16
    Coords            []float32
}

Buffer Flags

const (
    BufferFlagDefault                    BufferFlags = 0
    BufferFlagBOT                        BufferFlags = ...  // Beginning of text
    BufferFlagEOT                        BufferFlags = ...  // End of text
    BufferFlagPreserveDefaultIgnorables  BufferFlags = ...  // Keep ZWJ/ZWNJ visible
    BufferFlagRemoveDefaultIgnorables    BufferFlags = ...  // Remove ZWJ/ZWNJ
    BufferFlagDoNotInsertDottedCircle    BufferFlags = ...  // No dotted circle
)

Common Table Tags

Constant Table
TagCmap Character-to-glyph mapping
TagGlyf TrueType glyph outlines
TagGDEF Glyph Definition
TagGSUB Glyph Substitution
TagGPOS Glyph Positioning
TagFvar Font Variations
TagKernTable Kerning (legacy)