package font
Import Path
github.com/go-text/typesetting/font (on go.dev)
Dependency Relation
imports 16 packages, and imported by 5 packages
Involved Source Files
aat_layout_kern_kerx.go
aat_layout_morx.go
bitmaps.go
cache.go
cmap.go
cmap_arabic_pua_table.go
cmap_cache.go
color.go
Package font provides an high level API to access
Opentype font properties.
See packages [opentype] and [opentype/tables] for a lower level, more detailled API.
glyphs.go
metadata.go
metrics.go
os2.go
ot_layout.go
post.go
renderer.go
svg.go
variations.go
Package-Level Type Names (total 57)
AATStateTable supports both regular and extended AAT state machines
Class tables.AATLookup
GetClass return the class for the given glyph, with the correct default value.
GetEntry return the entry for the given state and class,
and handle invalid values (by returning an empty entry).
Aspect stores the properties that specify which font in a family to use:
style, weight, and stretchiness.
Stretch Stretch
Style Style
Weight Weight
SetDefaults replace unspecified values by the default values: StyleNormal, WeightNormal, StretchNormal
BitmapFormat identifies the format on the glyph
raw data. Across the various font files, many formats
may be encountered : black and white bitmaps, PNG, TIFF, JPG.
const BlackAndWhite
const JPG
const PNG
const TIFF
BitmapSize expose the size of bitmap glyphs.
One font may contain several sizes.
Height uint16
Width uint16
XPpem uint16
YPpem uint16
func (*Font).BitmapSizes() []BitmapSize
Cmap stores a compact representation of a cmap,
offering both on-demand rune lookup and full rune range.
It is conceptually equivalent to a map[rune]GID, but is often
implemented more efficiently.
Iter returns a new iterator over the cmap
Multiple iterators may be used over the same cmap
The returned interface is garanted not to be nil.
Lookup avoid the construction of a map and provides
an alternative when only few runes need to be fetched.
It returns a default value and false when no glyph is provided.
func ProcessCmap(cmap tables.Cmap, os2FontPage tables.FontPage) (Cmap, UnicodeVariations, error)
CmapIter is an iterator over a Cmap.
Char must be called only when `Next` has returned `true`
Next returns true if the iterator still has data to yield
CmapIter : github.com/apache/arrow-go/v18/arrow/compute/exec.ArrayIter[bool]
func Cmap.Iter() CmapIter
CmapRuneRanger is implemented by cmaps whose coverage is defined in terms
of rune ranges
RuneRanges returns a list of (start, end) rune pairs, both included.
`dst` is an optional buffer used to reduce allocations
CPAL is the 'CPAL' table,
with [numPalettes]x[numPaletteEntries] colors.
CPAL[0] is the default palette
Description provides font metadata.
Aspect Aspect
Family string
func Describe(ld *ot.Loader, buffer []byte) (Description, []byte)
func (*Font).Describe() Description
Face is a font with user-provided settings.
Contrary to the [*Font] objects, Faces are NOT safe for concurrent use.
A Face caches glyph extents and rune to glyph mapping, and should be reused when possible.
Also note that an empty [Face] is invalid : the [NewFace] constructor is required to properly init caches.
Font *Font
Font.Ankr tables.Ankr
// color glyphs, optional
// color glyphs, optional
Cmap is the 'cmap' table
Font.Feat tables.Feat
// An absent table has a nil GlyphClassDef
// An absent table has a nil slice of lookups
// An absent table has a nil slice of lookups
Font.Kern Kernx
Font.Kerx Kernx
Font.Ltag tables.Ltag
Font.Morx Morx
// optional
Font.Trak tables.Trak
BitmapSizes returns the size of bitmap glyphs present in the font.
Coords return a read-only slice of the current variable coordinates, expressed in normalized units.
It is empty for non variable fonts.
Describe provides access to family and aspect.
See also the package level function [Describe],
which is more efficient if you only need the font
metadata.
FontHExtents returns the extents of the font for horizontal text, or false
it not available, in font units.
FontVExtents is the same as `FontHExtents`, but for vertical text.
( Face) GetGlyphContourPoint(glyph GID, pointIndex uint16) (x, y int32, ok bool)
GlyphData returns the glyph content for [gid], or nil if
not found.
See also the various GlyphDataXXX methods, for more control
on the types of glyphs loaded.
GlyphDataBitmap looks for glyph data in the 'sbix', 'CBDT', 'EBDT' and 'BDAT' tables.
GlyphDataColor looks for glyph data in the 'COLR' table.
GlyphDataOutline looks for glyph data in 'glyf', 'CFF ' and 'CFF2' tables.
It is a bit faster than calling [Face.GlyphData] and may be used for instance
when rendering colored glyphs (from the 'COLR' table).
GlyphDataSVG looks for glyph data in the 'SVG ' table.
(*Face) GlyphExtents(glyph GID) (GlyphExtents, bool)
( Face) GlyphHOrigin(GID) (x, y int32, found bool)
GlyphName returns the name of the given glyph, or an empty
string if the glyph is invalid or has no name.
(*Face) GlyphVOrigin(glyph GID) (x, y float32)
HasVerticalMetrics returns true if a the 'vmtx' table is present.
If not, client should avoid calls to [VerticalAdvance], which will returns a
defaut value.
(*Face) HorizontalAdvance(gid GID) float32
IsMonospace returns 'true' if the font is monospace,
by inspecting the horizontal advances of its glyphs.
LineMetric returns the metric identified by `metric` (in fonts units).
NominalGlyph returns the glyph used to represent the given rune,
or false if not found.
Note that it only looks into the cmap, without taking account substitutions
nor variation selectors.
NormalizeVariations normalize the given design-space coordinates. The minimum and maximum
values for the axis are mapped to the interval [-1,1], with the default
axis value mapped to 0.
Any additional scaling defined in the face's `avar` table is also
applied, as described at https://docs.microsoft.com/en-us/typography/opentype/spec/avar.
This method panics if `coords` has not the correct length, that is the number of axis inf 'fvar'.
Ppem returns the horizontal and vertical pixels-per-em (ppem), used to select bitmap sizes.
SetCoords applies a list of variation coordinates, expressed in normalized units.
Use [NormalizeVariations] to convert from design (user) space units.
SetPpem applies horizontal and vertical pixels-per-em (ppem).
SetVariations applies a list of font-variation settings to a font,
defaulting to the values given in the `fvar` table.
Note that passing an empty slice will instead remove the coordinates.
Upem returns the units per em of the font file.
This value is only relevant for scalable fonts.
VariationGlyph retrieves the glyph ID for a specified Unicode code point
followed by a specified Variation Selector code point, or false if not found
(*Face) VerticalAdvance(gid GID) float32
func NewFace(font *Font) *Face
func ParseTTC(file Resource) ([]*Face, error)
func ParseTTF(file Resource) (*Face, error)
func github.com/go-text/typesetting/shaping.Fontmap.ResolveFace(r rune) *Face
func github.com/go-text/typesetting/shaping.FontmapScript.ResolveFace(r rune) *Face
func github.com/go-text/typesetting/shaping.SplitByFontGlyphs(input shaping.Input, availableFaces []*Face) []shaping.Input
Feature tables.Feature
// [lookupIndexCount] Array of indices into the LookupList — zero-based (first lookup is LookupListIndex = 0)
Tag Tag
Font represents one Opentype font file (or one sub font of a collection).
It is an educated view of the underlying font file, optimized for quick access
to information required by text layout engines.
All its methods are read-only and a [*Font] object is thus safe for concurrent use.
Ankr tables.Ankr
// color glyphs, optional
// color glyphs, optional
Cmap is the 'cmap' table
Feat tables.Feat
// An absent table has a nil GlyphClassDef
// An absent table has a nil slice of lookups
// An absent table has a nil slice of lookups
Kern Kernx
Kerx Kernx
Ltag tables.Ltag
Morx Morx
// optional
Trak tables.Trak
BitmapSizes returns the size of bitmap glyphs present in the font.
Describe provides access to family and aspect.
See also the package level function [Describe],
which is more efficient if you only need the font
metadata.
(*Font) GetGlyphContourPoint(glyph GID, pointIndex uint16) (x, y int32, ok bool)
(*Font) GlyphHOrigin(GID) (x, y int32, found bool)
GlyphName returns the name of the given glyph, or an empty
string if the glyph is invalid or has no name.
HasVerticalMetrics returns true if a the 'vmtx' table is present.
If not, client should avoid calls to [VerticalAdvance], which will returns a
defaut value.
IsMonospace returns 'true' if the font is monospace,
by inspecting the horizontal advances of its glyphs.
NominalGlyph returns the glyph used to represent the given rune,
or false if not found.
Note that it only looks into the cmap, without taking account substitutions
nor variation selectors.
NormalizeVariations normalize the given design-space coordinates. The minimum and maximum
values for the axis are mapped to the interval [-1,1], with the default
axis value mapped to 0.
Any additional scaling defined in the face's `avar` table is also
applied, as described at https://docs.microsoft.com/en-us/typography/opentype/spec/avar.
This method panics if `coords` has not the correct length, that is the number of axis inf 'fvar'.
Upem returns the units per em of the font file.
This value is only relevant for scalable fonts.
VariationGlyph retrieves the glyph ID for a specified Unicode code point
followed by a specified Variation Selector code point, or false if not found
func NewFont(ld *ot.Loader) (*Font, error)
func NewFace(font *Font) *Face
FontExtents exposes font-wide extent values, measured in font units.
Note that typically ascender is positive and descender negative in coordinate systems that grow up.
// Typographic ascender.
// Typographic descender.
// Suggested line spacing gap.
func (*Face).FontHExtents() (FontExtents, bool)
func (*Face).FontVExtents() (FontExtents, bool)
func github.com/go-text/typesetting/harfbuzz.(*Font).ExtentsForDirection(direction harfbuzz.Direction) FontExtents
FontID represents an identifier of a font (possibly in a collection),
and an optional variable instance.
// The filename or identifier of the font file.
The index of the face in a collection. It is always 0 for
single font files.
For variable fonts, stores 1 + the instance index.
It is set to 0 to ignore variations, or for non variable fonts.
GID is used to identify glyphs in a font.
It is mostly internal to the font and should not be confused with
Unicode code points.
Note that, despite Opentype font files using uint16, we choose to use uint32,
to allow room for future extension.
The actual image content, whose interpretation depends
on the Format field.
Format BitmapFormat
// number of columns and rows
Outline may be specified to be drawn with bitmap
// number of columns and rows
GlyphBitmap : GlyphData
func (*Face).GlyphDataBitmap(gid gID) (GlyphBitmap, bool)
GlyphColor describe a colored glyph, as found in
COLR tables
Paint tables.PaintTable
GlyphColor : GlyphData
func (*Face).GlyphDataColor(gid gID) (GlyphColor, bool)
GlyphData describe how to draw a glyph.
It is either an GlyphOutline, GlyphSVG or GlyphBitmap.
GlyphBitmap
GlyphColor
GlyphOutline
GlyphSVG
func (*Face).GlyphData(gid GID) GlyphData
GlyphExtents exposes extent values, measured in font units.
Note that height is negative in coordinate systems that grow up.
GlyphOutline exposes the path to draw for
vector glyph.
Coordinates are expressed in fonts units.
Segments []Segment
Sideways updates the coordinates of the outline by applying
a 90° clockwise rotation, and adding [yOffset] afterwards.
When used for vertical text, pass
-Glyph.YOffset, converted in font units, as [yOffset]
(a positive value to lift the glyph up).
GlyphOutline : GlyphData
func (*Face).GlyphDataOutline(gid gID) (GlyphOutline, bool)
GlyphSVG is an SVG description for the glyph,
as found in Opentype SVG table.
According to the specification, a fallback outline
should be specified for each SVG glyphs
The SVG image content, decompressed if needed.
The actual glyph description is an SVG element
with id="glyph<GID>" (as in id="glyph12"),
and several glyphs may share the same Source
GlyphSVG : GlyphData
func (*Face).GlyphDataSVG(gid gID) (GlyphSVG, bool)
Layout Layout
Layout.FeatureVariations []tables.FeatureVariationRecord
Layout.Features []Feature
Layout.Scripts []Script
Lookups []GPOSLookup
FindFeatureIndex fetches the index for a given feature tag in the GSUB or GPOS table.
Returns false if not found
FindScript looks for [script] and return its index into the Scripts slice,
or -1 if the tag is not found.
FindVariationIndex returns the first feature variation matching
the specified variation coordinates, as an index in the
`FeatureVariations` field.
It returns `-1` if not found.
LookupOptions LookupOptions
Lookup qualifiers.
Index (base 0) into GDEF mark glyph sets structure,
meaningfull only if UseMarkFilteringSet is set.
Subtables []tables.GPOSLookup
Props returns a 32-bit integer where the lower 16-bit is `Flag` and
the higher 16-bit is `MarkFilteringSet` if the lookup uses one.
Layout Layout
Layout.FeatureVariations []tables.FeatureVariationRecord
Layout.Features []Feature
Layout.Scripts []Script
Lookups []GSUBLookup
FindFeatureIndex fetches the index for a given feature tag in the GSUB or GPOS table.
Returns false if not found
FindScript looks for [script] and return its index into the Scripts slice,
or -1 if the tag is not found.
FindVariationIndex returns the first feature variation matching
the specified variation coordinates, as an index in the
`FeatureVariations` field.
It returns `-1` if not found.
LookupOptions LookupOptions
Lookup qualifiers.
Index (base 0) into GDEF mark glyph sets structure,
meaningfull only if UseMarkFilteringSet is set.
Subtables []tables.GSUBLookup
Props returns a 32-bit integer where the lower 16-bit is `Flag` and
the higher 16-bit is `MarkFilteringSet` if the lookup uses one.
( Kern0) KernPair(left, right GID) int16
Kern0 : SimpleKerns
Machine AATStateTable
// After successful parsing, may be safely indexed by AATStateEntry.AsKernxIndex() from `Machine`
// indexed by Left + Right
// Offset from beginning of this subtable to the start of the kerning array.
// Offset from beginning of this subtable to the left-hand offset table.
// Offset from beginning of this subtable to right-hand offset table.
( Kern2) KernPair(left, right GID) int16
Kern2 : SimpleKerns
KernIndex []uint8
Kernings []int16
LeftClass []uint8
RightClass []uint8
// The number of right-hand classes.
( Kern3) KernPair(left, right GID) int16
Kern3 : SimpleKerns
Anchors tables.KerxAnchors
Machine AATStateTable
ActionType returns 0, 1 or 2 .
Column tables.AatLookupMixed
with rowCount * columnCount
for tuples the values are estParseKerx (Not yet run).the first element of the tuple
// Values are pre-multiplied by `columnCount`
( Kern6) KernPair(left, right GID) int16
Kern6 : SimpleKerns
KernSubtable represents a 'kern' or 'kerx' subtable.
Data interface{isKernSubtable()}
IsExtended is [true] for AAT `kerx` subtables, false for 'kern' subtables
0 for scalar values
IsBackwards returns true if state-table based should process the glyphs backwards.
IsCrossStream returns true if the subtable has cross-stream kerning values.
IsHorizontal returns true if the subtable has horizontal kerning values.
IsVariation returns true if the subtable has variation kerning values.
Kernx represents a 'kern' or 'kerx' kerning table.
It supports both Microsoft and Apple formats.
shared between GSUB and GPOS
FeatureVariations []tables.FeatureVariationRecord
Features []Feature
Scripts []Script
FindFeatureIndex fetches the index for a given feature tag in the GSUB or GPOS table.
Returns false if not found
FindScript looks for [script] and return its index into the Scripts slice,
or -1 if the tag is not found.
FindVariationIndex returns the first feature variation matching
the specified variation coordinates, as an index in the
`FeatureVariations` field.
It returns `-1` if not found.
LineMetric identifies one metric about the font.
func (*Face).LineMetric(metric LineMetric) float32
const CapHeight
const StrikethroughPosition
const StrikethroughThickness
const SubscriptEmXOffset
const SubscriptEmYOffset
const SubscriptEmYSize
const SuperscriptEmXOffset
const SuperscriptEmYSize
const UnderlinePosition
const UnderlineThickness
const XHeight
Lookup qualifiers.
Index (base 0) into GDEF mark glyph sets structure,
meaningfull only if UseMarkFilteringSet is set.
Props returns a 32-bit integer where the lower 16-bit is `Flag` and
the higher 16-bit is `MarkFilteringSet` if the lookup uses one.
type Morx ([])
After successul parsing, this array may be safely
indexed by the indexes and counts from Machine entries.
Machine AATStateTable
The lookup value is interpreted as a GlyphIndex
// high byte of the coverage flag
Data interface{isMorxSubtable()}
// Mask identifying which subtable this is.
Resource is a combination of io.Reader, io.Seeker and io.ReaderAt.
This interface is satisfied by most things that you'd want
to parse, for example *os.File, io.SectionReader or *bytes.Reader.
Script tables.Script
// Offset to default LangSys table, from beginning of Script table — may be NULL
// same length as langSysRecords
// [langSysCount] Array of LangSysRecords, listed alphabetically by LangSys tag
Tag Tag
FindLanguage looks for [language] and return its index into the [LangSys] slice,
or -1 if the tag is not found.
GetLangSys return the language at [index]. It [index] is out of range (for example with 0xFFFF),
it returns [DefaultLangSys] (which may be empty)
type SegmentPoint = ot.SegmentPoint (struct)
SimpleKerns store a compact form of the kerning values,
which is restricted to (one direction) kerning pairs.
It is only implemented by [Kern0], [Kern2], [Kern3] and [Kern6],
where [Kern1] and [Kern4] requires a state machine to be interpreted.
KernPair return the kern value for the given pair, or zero.
The value is expressed in glyph units and
is negative when glyphs should be closer.
Kern0
Kern2
Kern3
Kern6
Stretch is the width of a font as an approximate fraction of the normal width.
Widths range from 0.5 to 2.0 inclusive, with 1.0 as the normal width.
const StretchCondensed
const StretchExpanded
const StretchExtraCondensed
const StretchExtraExpanded
const StretchNormal
const StretchSemiCondensed
const StretchSemiExpanded
const StretchUltraCondensed
const StretchUltraExpanded
Style (also called slant) allows italic or oblique faces to be selected.
const StyleItalic
const StyleNormal
Tag represents an open-type name.
These are technically uint32's, but are usually
displayed in ASCII as they are all acronyms.
See https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6.html#Overview
GetGlyphVariant returns the glyph index to used to [r] combined with [selector],
with one of the tri-state flags [VariantNotFound, VariantUseDefault, VariantFound]
func ProcessCmap(cmap tables.Cmap, os2FontPage tables.FontPage) (Cmap, UnicodeVariations, error)
VarCoord stores font variation coordinates,
which are real numbers in [-1;1], stored as fixed 2.14 integer.
Variation defines a value for a wanted variation axis.
// Variation-axis identifier tag
// In design units
func github.com/go-text/typesetting/harfbuzz.ParseVariation(s string) (Variation, error)
func (*Face).SetVariations(variations []Variation)
Weight is the degree of blackness or stroke thickness of a font.
This value ranges from 100.0 to 900.0, with 400.0 as normal.
const WeightBlack
const WeightBold
const WeightExtraBold
const WeightExtraLight
const WeightLight
const WeightMedium
const WeightNormal
const WeightSemibold
const WeightThin
Package-Level Functions (total 8)
Describe provides access to family and aspect.
'buffer' may be provided to reduce allocations.
It provides an efficient API, loading only the mininum
tables required. See also the method [Font.Describe]
if you already have loaded the font.
LoadHeadTable loads the 'head' or the 'bhed' table.
If a 'bhed' Apple table is present, it replaces the 'head' one.
[buffer] may be provided to reduce allocations; the returned [tables.Head] is guaranteed
not to retain any reference on [buffer].
If [buffer] is nil or has not enough capacity, a new slice is allocated (and returned).
NewFace wraps [font] and initializes glyph caches.
NewFont loads all the font tables, sanitizing them.
An error is returned only when required tables 'cmap', 'head', 'maxp' are invalid (or missing).
More control on errors is available by using package [tables].
NormalizeFamily removes spaces and lower the given string.
ParseTTC parse an Opentype font file, with support for collections.
Single font files are supported, returning a slice with length 1.
ParseTTF parse an Opentype font file (.otf, .ttf).
See ParseTTC for support for collections.
ProcessCmap sanitize the given 'cmap' subtable, and select the best encoding
when several subtables are given.
When present, the variation selectors are returned.
[os2FontPage] is used for legacy arabic fonts.
The returned values are copied from the input 'cmap', meaning they do not
retain any reference on the input storage.
Package-Level Constants (total 40)
The [GlyphBitmap.Data] slice stores a black or white (0/1)
bit image, whose length L satisfies
L * 8 >= [GlyphBitmap.Width] * [GlyphBitmap.Height]
const CapHeight LineMetric = 9
EmptyGlyph represents an invisible glyph, which should not be drawn,
but whose advance and offsets should still be accounted for when rendering.
The [GlyphBitmap.Data] slice stores a JPG encoded image
The [GlyphBitmap.Data] slice stores a PNG encoded image
Condensed width (75%).
Expanded width (125%).
Extra-condensed width (62.5%).
Extra-expanded width (150%).
Normal width (100%).
Semi-condensed width (87.5%).
Semi-expanded width (112.5%).
Ultra-condensed width (50%), the narrowest possible.
Ultra-expanded width (200%), the widest possible.
Distance above the baseline of the top of the strikethrough.
Suggested thickness to draw for the strikethrough.
A form that is generally cursive in nature or slanted.
This groups what is usually called Italic or Oblique.
A face that is neither italic not obliqued.
const SubscriptEmXOffset LineMetric = 8 const SubscriptEmYOffset LineMetric = 7 const SubscriptEmYSize LineMetric = 6 const SuperscriptEmXOffset LineMetric = 5 const SuperscriptEmYSize LineMetric = 4
The [GlyphBitmap.Data] slice stores a TIFF encoded image
Distance above the baseline of the top of the underline.
Since most fonts have underline positions beneath the baseline, this value is typically negative.
Suggested thickness to draw for the underline.
const UseMarkFilteringSet = 16
VariantFound is returned when the font has a variant for the glyph and selector.
VariantNotFound is returned when the font does not have a glyph for
the given rune and selector.
VariantUseDefault is returned when the regular glyph should be used (ignoring the selector).
Black weight (900), the thickest value.
Bold weight (700).
Extra-bold weight (800).
Extra light weight (200).
Light weight (300).
Medium weight (500, higher than normal).
Normal (400).
Semibold weight (600).
Thin weight (100), the thinnest value.
const XHeight LineMetric = 10
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |