Documentation
¶
Overview ¶
Package untie renders TeX and Typst math into a UI-independent display list using host-supplied OpenType MATH fonts.
Parse and ParseTypst produce immutable expressions. NewEngine prepares a caller-owned, concurrency-safe layout environment. NewRenderer is the recommended host facade: it combines parsing, layout, and optional bounded expression caching while retaining one prepared engine. Package-level Layout and LayoutContext use a bounded process-wide engine cache.
Layout output is a flattened display.Box containing glyph outlines, rules, source hits, and deterministic diagnostics. The render package provides a framework-neutral drawing protocol and fitting helpers. The optional encode/svg and encode/raster packages serialize the same display contract without coupling the core to a UI framework.
Index ¶
- Constants
- Variables
- func ClearLayoutEngineCache()
- func Version() string
- type Align
- type Alt
- type Box
- type Break
- type BreakKind
- type Code
- type Diagnostic
- type Dialect
- type Engine
- func (e *Engine) FontKeySHA256() [32]byte
- func (e *Engine) Layout(expr *Expr, style Style) (*Box, error)
- func (e *Engine) LayoutContext(ctx context.Context, expr *Expr, style Style) (*Box, error)
- func (e *Engine) LayoutFormulaContext(ctx context.Context, formula *Formula, mode Mode, style Style) (*Box, error)
- func (e *Engine) Limits() Limits
- type EquationTag
- type Expr
- func Parse(src string, dialect Dialect, mode Mode, opts ParseOptions) *Expr
- func ParseContext(ctx context.Context, src string, dialect Dialect, mode Mode, opts ParseOptions) (*Expr, error)
- func ParseTeX(src string, mode Mode, opts ParseOptions) *Expr
- func ParseTypst(src string, mode Mode, opts ParseOptions) *Expr
- func (e *Expr) Alt() Alt
- func (e *Expr) AltContext(ctx context.Context) (Alt, error)
- func (e *Expr) Diagnostics() []Diagnostic
- func (e *Expr) Dialect() Dialect
- func (e *Expr) HasErrors() bool
- func (e *Expr) Key() uint64
- func (e *Expr) Mode() Mode
- func (e *Expr) RootSnapshot() (*ir.Formula, error)
- func (e *Expr) Source() string
- type FontFace
- type FontOption
- type FontSet
- type FontSetConfig
- type Formula
- type Hit
- type HitKind
- type HitRange
- type Item
- type ItemKind
- type ItemRange
- type LayoutError
- type LayoutErrorKind
- type Limits
- type LineBox
- type Macro
- type Mode
- type Paint
- type ParseOptions
- type Path
- type PathTemplate
- type Point
- type RGBA
- type Range
- type Rect
- type RenderRequest
- type RenderResult
- type Renderer
- type RendererOptions
- type Role
- type Segment
- type Severity
- type Style
- type TagBox
Examples ¶
Constants ¶
const ( Inline = ir.Inline Display = ir.Display )
const ( SeverityError = source.SeverityError SeverityWarning = source.SeverityWarning SeverityInfo = source.SeverityInfo ItemGlyphPath = display.ItemGlyphPath ItemRule = display.ItemRule ItemGlyphRef = display.ItemGlyphRef SegMoveTo = geometry.SegMoveTo SegLineTo = geometry.SegLineTo SegQuadTo = geometry.SegQuadTo SegCubeTo = geometry.SegCubeTo SegClose = geometry.SegClose RoleInk = display.RoleInk RoleError = display.RoleError RolePlaceholder = display.RolePlaceholder HitAtom = display.HitAtom HitGroup = display.HitGroup HitScript = display.HitScript HitFractionNumerator = display.HitFractionNumerator HitFractionDenominator = display.HitFractionDenominator HitRadical = display.HitRadical HitFence = display.HitFence HitTableCell = display.HitTableCell HitRow = display.HitRow HitOther = display.HitOther BreakRelation = display.BreakRelation BreakBinary = display.BreakBinary BreakExplicit = display.BreakExplicit AlignStart = display.AlignStart AlignCenter = display.AlignCenter AlignEnd = display.AlignEnd FormulaTagLine = display.FormulaTagLine )
const ( CodeSyntax = source.CodeSyntax CodeUnknownCommand = source.CodeUnknownCommand CodeUnknownSymbol = source.CodeUnknownSymbol CodeMissingArgument = source.CodeMissingArgument CodeUnclosedGroup = source.CodeUnclosedGroup CodeUnexpectedToken = source.CodeUnexpectedToken CodeUnsupported = source.CodeUnsupported CodeInvalidValue = source.CodeInvalidValue CodeInvalidEnvironment = source.CodeInvalidEnvironment CodeUnknownVariable = source.CodeUnknownVariable CodeMissingGlyph = source.CodeMissingGlyph CodeTextUnsupported = source.CodeTextUnsupported CodeLimitExceeded = source.CodeLimitExceeded CodeCanceled = source.CodeCanceled CodeInternal = source.CodeInternal CodeDeprecated = source.CodeDeprecated )
Variables ¶
var ( // ErrInvalidExpr reports a nil expression. ErrInvalidExpr = errors.New("untie: nil expression") // ErrAltInvalidRoot reports malformed alternative-text input. ErrAltInvalidRoot = internalalt.ErrInvalidRoot // ErrAltLimitExceeded reports an alternative-text traversal or output limit. ErrAltLimitExceeded = internalalt.ErrLimitExceeded // ErrAltUnsupportedNode reports an IR node that alternative text cannot explain. ErrAltUnsupportedNode = internalalt.ErrUnsupportedNode )
var ( // ErrInvalidInput reports malformed input at the public layout boundary. ErrInvalidInput = internallayout.ErrInvalidInput // ErrMissingGlyph reports that the configured font set cannot supply a // glyph required by the expression. ErrMissingGlyph = internallayout.ErrMissingGlyph // ErrUnsupported reports a recognized construct that this release cannot // render. ErrUnsupported = internallayout.ErrUnsupported // ErrInsufficientStretch reports that the font cannot stretch a delimiter // or accent far enough for the requested construction. ErrInsufficientStretch = internallayout.ErrInsufficientStretch // ErrLimit reports that a configured parse, layout, or output limit was // exceeded. ErrLimit = internallayout.ErrLimit )
var ( // ErrInvalidContext reports a nil context. ErrInvalidContext = errors.New("untie: nil context") // ErrInvalidFonts reports a missing or unusable prepared font set. ErrInvalidFonts = errors.New("untie: invalid font set") // ErrInvalidStyle reports an invalid host layout style. ErrInvalidStyle = errors.New("untie: invalid layout style") // ErrInvalidEngine reports a nil or unusable prepared layout engine. ErrInvalidEngine = errors.New("untie: invalid layout engine") )
var ( // ErrInvalidRenderer reports a nil renderer, invalid default dialect, or // unusable renderer construction input. ErrInvalidRenderer = errors.New("untie: invalid renderer") )
Functions ¶
func ClearLayoutEngineCache ¶
func ClearLayoutEngineCache()
ClearLayoutEngineCache drops every prepared Engine retained by the package-level layout convenience functions. Explicitly owned Engines from NewEngine are unaffected. An in-flight convenience build may still finish, but it will not be inserted after the clear.
Types ¶
type Box ¶
Limits, diagnostics, and output types are aliases of their owning packages.
func Layout ¶
Layout lays out an expression with a background context and the bounded process-wide Engine cache. It reports preparation, cancellation, and layout errors rather than returning a misleading empty result.
func LayoutContext ¶
LayoutContext is a convenience wrapper that reuses a bounded eight-entry process-wide cache of prepared Engines. The cache is keyed by library version, the full FontSet revision, and effective resource limits. Layout results are not cached; callers receive an independent Box for every call.
Use NewEngine when the host needs explicit ownership of prepared resources.
type Diagnostic ¶
type Diagnostic = source.Diagnostic
Limits, diagnostics, and output types are aliases of their owning packages.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is a prepared, concurrency-safe layout environment owned by the caller. Reuse it for repeated layouts with the same FontSet and Limits.
An Engine retains its FontSet and is GC-managed; neither value needs a Close call. Use LoadMathFont or LoadFontSet and NewEngine once during application setup, then retain the Engine for the lifetime of the font configuration.
Example (DisplayLines) ¶
package main
import (
"fmt"
"os"
"github.com/caelyreth/untie"
)
func main() {
fontBytes, err := os.ReadFile("testdata/upstream/fonts/NewCMMath-Book.otf")
if err != nil {
panic(err)
}
fonts, err := untie.LoadFontSet(untie.FontSetConfig{
Math: untie.FontFace{Bytes: fontBytes, ID: "NewCMMath-Book"},
})
if err != nil {
panic(err)
}
engine, err := untie.NewEngine(fonts, untie.Limits{})
if err != nil {
panic(err)
}
expr := untie.ParseTeX(`a+b+c+d`, untie.Display, untie.ParseOptions{})
box, err := engine.Layout(expr, untie.Style{Size: 24, MaxWidth: 60})
if err != nil {
panic(err)
}
allValid := box.Validate() == nil
fmt.Println("wrapped:", len(box.Lines) > 1)
fmt.Println("lines valid:", allValid)
fmt.Println("first baseline:", displayLineBaseline(box.Lines[0]))
fmt.Println("first offset nonnegative:", box.Lines[0].OffsetX >= 0)
}
func displayLineBaseline(line untie.LineBox) float32 {
return line.Baseline
}
Output: wrapped: true lines valid: true first baseline: 0 first offset nonnegative: true
Example (LayoutAtTwoSizes) ¶
package main
import (
"bytes"
"fmt"
"os"
"github.com/caelyreth/untie"
)
func main() {
fontBytes, err := os.ReadFile("testdata/upstream/fonts/NewCMMath-Book.otf")
if err != nil {
panic(err)
}
fonts, err := untie.LoadFontSet(untie.FontSetConfig{
Math: untie.FontFace{Bytes: fontBytes, ID: "NewCMMath-Book"},
})
if err != nil {
panic(err)
}
engine, err := untie.NewEngine(fonts, untie.Limits{})
if err != nil {
panic(err)
}
expr := untie.ParseTeX(`\frac{x+1}{2}`, untie.Inline, untie.ParseOptions{})
small, err := engine.Layout(expr, untie.Style{Size: 12, GenerateAlt: true})
if err != nil {
panic(err)
}
before, err := small.MarshalCanonical()
if err != nil {
panic(err)
}
large, err := engine.Layout(expr, untie.Style{Size: 24, GenerateAlt: true})
if err != nil {
panic(err)
}
after, err := small.MarshalCanonical()
if err != nil {
panic(err)
}
fmt.Println("small valid:", small.Validate() == nil)
fmt.Println("large valid:", large.Validate() == nil)
fmt.Println("scales up:", large.Width > small.Width)
fmt.Println("alt present:", small.Alt.Text != "" && small.Alt.Speech != "")
fmt.Println("first box unchanged:", bytes.Equal(before, after))
}
Output: small valid: true large valid: true scales up: true alt present: true first box unchanged: true
func NewEngine ¶
NewEngine prepares an Engine for repeated layouts.
Prefer this API when the application owns the font/cache lifecycle. The package-level Layout and LayoutContext convenience functions use a separate bounded process-wide cache.
func (*Engine) FontKeySHA256 ¶
FontKeySHA256 returns the collision-resistant identity of the prepared font set used by the Engine.
func (*Engine) LayoutContext ¶
LayoutContext lays out an expression with cancellation and resource limits. Style.Features is snapshotted for the duration of the call; the caller may reuse or modify its slice after LayoutContext returns. Box.Alt is generated under the per-field stricter intersection of Engine and expression limits, so it may be a bounded fallback that differs from Expr.Alt.
func (*Engine) LayoutFormulaContext ¶
func (e *Engine) LayoutFormulaContext(ctx context.Context, formula *Formula, mode Mode, style Style) (*Box, error)
LayoutFormulaContext lays out canonical IR with cancellation and the Engine's configured resource limits. Unlike Expr, formula must be immutable for the duration of the call and may be shared after it returns.
This is the advanced boundary for hosts that cache canonical IR or produce it through another validated frontend. Parsed expressions should use LayoutContext so parser-validated structure can be reused.
type EquationTag ¶
type EquationTag = ir.EquationTag
Limits, diagnostics, and output types are aliases of their owning packages.
type Expr ¶
type Expr struct {
// contains filtered or unexported fields
}
Expr is an immutable parsed formula.
func Parse ¶
func Parse(src string, dialect Dialect, mode Mode, opts ParseOptions) *Expr
Parse parses source into an expression. Malformed source produces diagnostics and a drawable fallback tree rather than an ordinary error. Links are text-only: the visible body is rendered with its source spans preserved, the destination is discarded, and a warning is reported only after the link arguments validate. TeX URL groups preserve raw URL characters and balanced braces; Typst link destinations are limited to non-empty strings in the bounded evaluator. Labels, references, and document-level link resolution are outside this API.
func ParseContext ¶
func ParseContext( ctx context.Context, src string, dialect Dialect, mode Mode, opts ParseOptions, ) (*Expr, error)
ParseContext parses source with context cancellation. Cancellation is checked before parser dispatch and again before the expression is returned. Parser work already in progress is bounded by opts.Limits rather than interrupted at arbitrary points. A canceled call returns a nil expression and ctx.Err.
Parse options are snapshotted before parsing. The caller may reuse or mutate its macro map and limits after ParseContext returns.
func ParseTeX ¶
func ParseTeX(src string, mode Mode, opts ParseOptions) *Expr
ParseTeX is a dialect-specific convenience wrapper.
Example ¶
package main
import (
"fmt"
"github.com/caelyreth/untie"
)
func main() {
expr := untie.ParseTeX(`x^2+\frac{1}{2}`, untie.Display, untie.ParseOptions{})
fmt.Println(expr.Source())
fmt.Println(len(expr.Diagnostics()))
}
Output: x^2+\frac{1}{2} 0
func ParseTypst ¶
func ParseTypst(src string, mode Mode, opts ParseOptions) *Expr
ParseTypst is a dialect-specific convenience wrapper.
func (*Expr) Alt ¶
Alt returns deterministic plain text and speech derived from the neutral IR. If generation cannot complete, it returns a bounded, validated fallback. Use AltContext to observe the error.
func (*Expr) AltContext ¶
AltContext returns alternative text with cooperative cancellation.
Nil contexts and cancellation return a zero Alt. Non-context failures return a bounded, validated visible fallback together with an error. Unsupported nested nodes may return partially generated output containing visible markers. Use ErrAltInvalidRoot, ErrAltLimitExceeded, and ErrAltUnsupportedNode to classify those errors.
func (*Expr) Diagnostics ¶
func (e *Expr) Diagnostics() []Diagnostic
Diagnostics returns an independent copy of parse diagnostics.
func (*Expr) HasErrors ¶
HasErrors reports whether parsing produced at least one error-severity diagnostic. The expression remains drawable whether this returns true or false.
func (*Expr) RootSnapshot ¶
RootSnapshot returns an independent, validated copy of the canonical IR.
type FontOption ¶
type FontOption = font.FontOption
Limits, diagnostics, and output types are aliases of their owning packages.
func WithFontID ¶
func WithFontID(id string) FontOption
WithFontID sets an explicit face ID for LoadMathFont.
func WithFontIndex ¶
func WithFontIndex(index int) FontOption
WithFontIndex selects a TTC face for LoadMathFont.
type FontSet ¶
Limits, diagnostics, and output types are aliases of their owning packages.
func LoadFontSet ¶
func LoadFontSet(config FontSetConfig) (*FontSet, error)
LoadFontSet prepares one or more host-supplied faces for repeated layout. Empty face IDs are derived deterministically.
func LoadMathFont ¶
func LoadMathFont(data []byte, opts ...FontOption) (*FontSet, error)
LoadMathFont prepares one math face. Use WithFontID and WithFontIndex when the host needs explicit identity or a TTC face index.
type FontSetConfig ¶
type FontSetConfig = font.FontSetConfig
Limits, diagnostics, and output types are aliases of their owning packages.
type LayoutError ¶
type LayoutError struct {
Kind LayoutErrorKind
Range source.Range
Err error
}
LayoutError is a structured public layout failure.
Kind is stable for programmatic classification. Range identifies the originating canonical IR node when one can be attributed; otherwise it is source.Detached(). Err preserves the underlying cause and can be inspected with errors.Is or errors.As.
func (*LayoutError) Error ¶
func (e *LayoutError) Error() string
Error returns the classification, source location, and underlying cause.
func (*LayoutError) Unwrap ¶
func (e *LayoutError) Unwrap() error
Unwrap returns the underlying layout cause.
type LayoutErrorKind ¶
type LayoutErrorKind string
LayoutErrorKind is the stable machine-readable classification of a layout failure. Kinds may be added over time, but existing meanings remain stable.
const ( // LayoutErrorInvalidInput reports malformed canonical layout input or an // invalid output invariant. LayoutErrorInvalidInput LayoutErrorKind = "invalid-input" // LayoutErrorMissingGlyph reports unavailable glyph data. LayoutErrorMissingGlyph LayoutErrorKind = "missing-glyph" // LayoutErrorUnsupported reports a recognized but unsupported construct. LayoutErrorUnsupported LayoutErrorKind = "unsupported" // LayoutErrorInsufficientStretch reports a delimiter or accent that the // configured font cannot stretch far enough. LayoutErrorInsufficientStretch LayoutErrorKind = "insufficient-stretch" // LayoutErrorLimit reports an exceeded resource limit. LayoutErrorLimit LayoutErrorKind = "limit" )
type ParseOptions ¶
ParseOptions configure parsing. TeX macros are ignored by the Typst frontend. Typst preamble/code definitions are intentionally unsupported; hosts must expand them before calling Parse.
type PathTemplate ¶
type PathTemplate = display.PathTemplate
Limits, diagnostics, and output types are aliases of their owning packages.
type RenderRequest ¶
type RenderRequest struct {
Dialect Dialect
Mode Mode
Style display.Style
Parse ParseOptions
}
RenderRequest selects one source-to-display-list operation.
A zero Dialect uses RendererOptions.DefaultDialect. A zero Mode means Inline. A fully zero Style uses RendererOptions.DefaultStyle; otherwise a zero Size or nil Features field inherits the configured default. Parse options are snapshotted before parsing, and their limits are intersected with RendererOptions.Limits.
type RenderResult ¶
RenderResult is one render attempt.
Box is non-nil only when layout succeeds. Diagnostics contain an independent snapshot of recoverable parse diagnostics and are returned with layout errors when parsing completed. Alt is populated only when the effective style requests alternative-text generation.
type Renderer ¶
type Renderer struct {
// contains filtered or unexported fields
}
Renderer is a caller-owned, concurrency-safe high-level parse-and-layout facade. It retains one prepared Engine for the lifetime of the renderer and may be shared by concurrent rendering workers.
Parsed expressions may be reused through a bounded LRU cache. Every successful Render call performs layout and returns a new Box.
func NewRenderer ¶
func NewRenderer(fonts *FontSet, opts RendererOptions) (*Renderer, error)
NewRenderer prepares a reusable renderer and its Engine.
Engine preparation happens once here. The renderer inherits the engine's concurrency and resource-limit guarantees.
func (*Renderer) Render ¶
func (r *Renderer) Render( ctx context.Context, src string, request RenderRequest, ) (*RenderResult, error)
Render parses, lays out, and optionally generates alternative text for one formula.
Recoverable source problems do not fail the call. When layout fails after parsing, Render returns a non-nil result containing diagnostics alongside the error. Context cancellation returns nil when observed before parsing and a diagnostic-bearing result when observed during layout.
type RendererOptions ¶
type RendererOptions struct {
Limits source.Limits
DefaultDialect Dialect
DefaultStyle display.Style
CacheEntries int
}
RendererOptions configure a reusable high-level renderer.
Limits are shared by parsing, layout, and alternative-text generation. DefaultDialect selects the dialect when RenderRequest.Dialect is TeX's zero value; a zero DefaultDialect means TeX. DefaultStyle is used when RenderRequest.Style is the zero value, with a zero Size defaulting to 16. CacheEntries bounds the parsed-expression cache; zero or a negative value disables it. Returned display boxes are never cached.
type Style ¶
Style is a display.Style layout request. Display layout with a positive MaxWidth emits Box.Lines in a MaxWidth-wide alignment frame. Align positions each line within that frame. Box.Items and Box.Hits are the sole drawable storage; LineBox and TagBox ranges select parent-frame records and must not be translated again. Single-line display tags populate Box.Tag and the associated LineBox.Tag. Constrained alignment reserves the tag width before positioning the line. Inline layout ignores both MaxWidth and Align and rejects manual tags.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
contrib
|
|
|
mygo
module
|
|
|
Package display defines the immutable output contract for UI hosts.
|
Package display defines the immutable output contract for UI hosts. |
|
encode
|
|
|
raster
Package raster renders display boxes to RGBA images and PNG streams with a pure-Go antialiased vector rasterizer.
|
Package raster renders display boxes to RGBA images and PNG streams with a pure-Go antialiased vector rasterizer. |
|
svg
Package svg encodes a display.Box as a standalone SVG document.
|
Package svg encodes a display.Box as a standalone SVG document. |
|
examples
|
|
|
internal/example
Package example provides shared command-line setup for the exporter examples.
|
Package example provides shared command-line setup for the exporter examples. |
|
png
command
Command png renders one formula as an antialiased PNG image.
|
Command png renders one formula as an antialiased PNG image. |
|
svg
command
Command svg renders one formula as a standalone SVG document.
|
Command svg renders one formula as a standalone SVG document. |
|
Package font defines host-supplied font inputs and parsed font sets.
|
Package font defines host-supplied font inputs and parsed font sets. |
|
Package fontsource loads caller-supplied font files from an io/fs filesystem.
|
Package fontsource loads caller-supplied font files from an io/fs filesystem. |
|
Package geometry defines deterministic geometric primitives.
|
Package geometry defines deterministic geometric primitives. |
|
internal
|
|
|
alt
Package alt derives deterministic plain text and speech from Untie's neutral math IR.
|
Package alt derives deterministic plain text and speech from Untie's neutral math IR. |
|
engine
Package engine connects parsed IR, parsed fonts, and the layout engine.
|
Package engine connects parsed IR, parsed fonts, and the layout engine. |
|
irarena
Package irarena allocates immutable IR nodes for a single frontend parse.
|
Package irarena allocates immutable IR nodes for a single frontend parse. |
|
layout
Package layout turns the neutral math IR into a deterministic display list.
|
Package layout turns the neutral math IR into a deterministic display list. |
|
mathdata
Package mathdata provides immutable, generated mathematical metadata shared by Untie's TeX and Typst frontends and by the font layer.
|
Package mathdata provides immutable, generated mathematical metadata shared by Untie's TeX and Typst frontends and by the font layer. |
|
mathdata/gen
command
Command gen generates Untie's checked-in math metadata.
|
Command gen generates Untie's checked-in math metadata. |
|
quality
Package quality contains repository-wide architecture, corpus, and compatibility verification.
|
Package quality contains repository-wide architecture, corpus, and compatibility verification. |
|
quality/conformance
Package conformance reports frontend behavior against pinned formula corpora.
|
Package conformance reports frontend behavior against pinned formula corpora. |
|
quality/crosscheck
Package crosscheck verifies that the TeX and Typst frontends lower the pinned paired corpus to equivalent semantic IR and render equal output.
|
Package crosscheck verifies that the TeX and Typst frontends lower the pinned paired corpus to equivalent semantic IR and render equal output. |
|
quality/daily
Package daily evaluates the product-priority daily-STEM formula corpus.
|
Package daily evaluates the product-priority daily-STEM formula corpus. |
|
quality/fixture
Package fixture decodes and validates the immutable upstream fixtures used by Untie's conformance tests.
|
Package fixture decodes and validates the immutable upstream fixtures used by Untie's conformance tests. |
|
tex
Package tex implements the TeX math frontend.
|
Package tex implements the TeX math frontend. |
|
typst
Package typst implements the Typst math frontend.
|
Package typst implements the Typst math frontend. |
|
Package ir defines Untie's language-neutral math tree.
|
Package ir defines Untie's language-neutral math tree. |
|
Package render provides a small, framework-neutral drawing protocol over display.Box.
|
Package render provides a small, framework-neutral drawing protocol over display.Box. |
|
Package source defines source locations, diagnostics, and resource limits.
|
Package source defines source locations, diagnostics, and resource limits. |