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, caret stops, optional stable node identities, 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 AltBreakKind
- type AltCancelRole
- type AltColumn
- type AltColumnAlign
- type AltDescription
- type AltFlag
- type AltFontSize
- type AltFractionRole
- type AltFractionStyle
- type AltMathSize
- type AltNode
- type AltNodeKind
- type AltOverlayAlignment
- type AltPart
- type AltPartRole
- type AltPosition
- type AltRaiseDirection
- type AltRow
- type AltScriptRole
- type AltSizingKind
- type AltSpaceKind
- type AltSpaceWidth
- type AltTableRole
- type AltTag
- type AltVariant
- type Box
- type Break
- type BreakKind
- type CaretStop
- type Code
- type ColorPolicy
- type ColorPolicyMode
- type ColorRolePalette
- 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) LayoutContextWithOptions(ctx context.Context, expr *Expr, style Style, options LayoutOptions) (*Box, error)
- func (e *Engine) LayoutFormulaContext(ctx context.Context, formula *Formula, mode Mode, style Style) (*Box, error)
- func (e *Engine) LayoutFormulaContextWithOptions(ctx context.Context, formula *Formula, mode Mode, style Style, ...) (*Box, error)
- func (e *Engine) Limits() Limits
- type EquationLabel
- 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) Labels() []ir.EquationLabel
- func (e *Expr) Mode() Mode
- func (e *Expr) RootSnapshot() (*ir.Formula, error)
- func (e *Expr) Source() string
- type FaceUse
- type FontFace
- type FontOption
- type FontSet
- type FontSetConfig
- type FontUsage
- type Formula
- type Hit
- type HitKind
- type HitRange
- type Item
- type ItemKind
- type ItemRange
- type LayoutError
- type LayoutErrorKind
- type LayoutOptions
- type Limits
- type LineBox
- type Macro
- type MissingFallback
- type Mode
- type NodeID
- type Paint
- type ParseOptions
- type Path
- type PathTemplate
- type PixelGrid
- type Point
- type RGBA
- type Range
- type RecoveryMode
- type Rect
- type RenderRequest
- type RenderResult
- type Renderer
- type RendererOptions
- type Role
- type Segment
- type Severity
- type SnapAxis
- type Style
- type TagBox
- type Variation
- type VariationAxis
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 ColorPreserve = display.ColorPreserve ColorMapToRoles = display.ColorMapToRoles ColorAdjustContrast = display.ColorAdjustContrast DefaultMinContrast = display.DefaultMinContrast SnapNone = display.SnapNone SnapX = display.SnapX SnapY = display.SnapY 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 AltDescriptionVersion = display.AltDescriptionVersion AltKindRow = display.AltKindRow AltKindGlyph = display.AltKindGlyph AltKindText = display.AltKindText AltKindOperator = display.AltKindOperator AltKindSpace = display.AltKindSpace AltKindFraction = display.AltKindFraction AltKindRadical = display.AltKindRadical AltKindScripts = display.AltKindScripts AltKindFenced = display.AltKindFenced AltKindSizedDelimiter = display.AltKindSizedDelimiter AltKindAccent = display.AltKindAccent AltKindLine = display.AltKindLine AltKindCancel = display.AltKindCancel AltKindTable = display.AltKindTable AltKindMultiline = display.AltKindMultiline AltKindStyle = display.AltKindStyle AltKindOverlay = display.AltKindOverlay AltKindRaise = display.AltKindRaise AltKindColor = display.AltKindColor AltKindBox = display.AltKindBox AltKindPhantom = display.AltKindPhantom AltKindError = display.AltKindError AltKindPlaceholder = display.AltKindPlaceholder AltKindBreak = display.AltKindBreak AltKindAlignMarker = display.AltKindAlignMarker AltPartItem = display.AltPartItem AltPartBody = display.AltPartBody AltPartNumerator = display.AltPartNumerator AltPartDenominator = display.AltPartDenominator AltPartRadicand = display.AltPartRadicand AltPartIndex = display.AltPartIndex AltPartBase = display.AltPartBase AltPartTop = display.AltPartTop AltPartBottom = display.AltPartBottom AltPartTopLeft = display.AltPartTopLeft AltPartBottomLeft = display.AltPartBottomLeft AltPartTopRight = display.AltPartTopRight AltPartBottomRight = display.AltPartBottomRight AltPartOpen = display.AltPartOpen AltPartClose = display.AltPartClose AltPartContent = display.AltPartContent AltPartAccent = display.AltPartAccent AltVariantNormal = display.AltVariantNormal AltVariantItalic = display.AltVariantItalic AltVariantBold = display.AltVariantBold AltVariantBoldItalic = display.AltVariantBoldItalic AltVariantDoubleStruck = display.AltVariantDoubleStruck AltVariantScript = display.AltVariantScript AltVariantBoldScript = display.AltVariantBoldScript AltVariantFraktur = display.AltVariantFraktur AltVariantBoldFraktur = display.AltVariantBoldFraktur AltVariantSans = display.AltVariantSans AltVariantBoldSans = display.AltVariantBoldSans AltVariantMonospace = display.AltVariantMonospace AltFractionOrdinary = display.AltFractionOrdinary AltFractionBinomial = display.AltFractionBinomial AltFractionStacked = display.AltFractionStacked AltFractionVertical = display.AltFractionVertical AltFractionNoBar = display.AltFractionNoBar AltFractionSkewed = display.AltFractionSkewed AltFractionHorizontal = display.AltFractionHorizontal AltScriptOrdinary = display.AltScriptOrdinary AltScriptLimits = display.AltScriptLimits AltScriptOverlay = display.AltScriptOverlay AltScriptBraceLabel = display.AltScriptBraceLabel AltTableMatrix = display.AltTableMatrix AltTableArray = display.AltTableArray AltTableCases = display.AltTableCases AltTableVector = display.AltTableVector AltCancelStrike = display.AltCancelStrike AltCancelNegation = display.AltCancelNegation AltPositionAbove = display.AltPositionAbove AltPositionBelow = display.AltPositionBelow AltSpaceExplicit = display.AltSpaceExplicit AltSpaceInterword = display.AltSpaceInterword AltSpaceIgnored = display.AltSpaceIgnored AltSpaceWidthZero = display.AltSpaceWidthZero AltSpaceWidthThin = display.AltSpaceWidthThin AltSpaceWidthMedium = display.AltSpaceWidthMedium AltSpaceWidthThick = display.AltSpaceWidthThick AltSpaceWidthEn = display.AltSpaceWidthEn AltSpaceWidthQuad = display.AltSpaceWidthQuad AltSpaceWidthDoubleQuad = display.AltSpaceWidthDoubleQuad AltSpaceWidthNegativeThin = display.AltSpaceWidthNegativeThin AltSpaceWidthNegativeMedium = display.AltSpaceWidthNegativeMedium AltSpaceWidthNegativeThick = display.AltSpaceWidthNegativeThick AltSpaceWidthCustom = display.AltSpaceWidthCustom AltBreakRelation = display.AltBreakRelation AltBreakBinary = display.AltBreakBinary AltBreakExplicit = display.AltBreakExplicit AltSizingContent = display.AltSizingContent AltSizingRelative = display.AltSizingRelative AltSizingAbsolute = display.AltSizingAbsolute AltColumnCenter = display.AltColumnCenter AltColumnLeft = display.AltColumnLeft AltColumnRight = display.AltColumnRight AltSizeInherit = display.AltSizeInherit AltSizeDisplay = display.AltSizeDisplay AltSizeText = display.AltSizeText AltSizeScript = display.AltSizeScript AltSizeScriptScript = display.AltSizeScriptScript AltOverlayStart = display.AltOverlayStart AltOverlayCenter = display.AltOverlayCenter AltOverlayEnd = display.AltOverlayEnd AltRaiseUp = display.AltRaiseUp AltRaiseDown = display.AltRaiseDown AltRaiseZero = display.AltRaiseZero AltFlagBalanced = display.AltFlagBalanced AltFlagBar = display.AltFlagBar AltFlagWeak = display.AltFlagWeak AltFlagStretchy = display.AltFlagStretchy AltFlagNaturalFit = display.AltFlagNaturalFit AltFlagDotless = display.AltFlagDotless AltFlagExactFrameWidth = display.AltFlagExactFrameWidth AltFlagCross = display.AltFlagCross AltFlagInverted = display.AltFlagInverted AltFlagCentered = display.AltFlagCentered AltFlagCramped = display.AltFlagCramped AltFlagUncramped = display.AltFlagUncramped AltFlagFill = display.AltFlagFill AltFlagBorder = display.AltFlagBorder AltFlagPhantomWidth = display.AltFlagPhantomWidth AltFlagPhantomHeight = display.AltFlagPhantomHeight AltFlagPhantomDepth = display.AltFlagPhantomDepth )
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 CodeDuplicateLabel = source.CodeDuplicateLabel CodeUnresolvedReference = source.CodeUnresolvedReference CodeMissingGlyph = source.CodeMissingGlyph CodeInsufficientStretch = source.CodeInsufficientStretch 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 // ErrCannotSplit reports that an output Box cannot be split into // independent inline geometry. ErrCannotSplit = display.ErrCannotSplit )
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 ErrInvalidRecovery = errors.New("untie: invalid recovery mode")
ErrInvalidRecovery reports an unknown recovery mode.
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 AltBreakKind ¶ added in v0.4.0
type AltBreakKind = display.AltBreakKind
Limits, diagnostics, and output types are aliases of their owning packages.
type AltCancelRole ¶ added in v0.4.0
type AltCancelRole = display.AltCancelRole
Limits, diagnostics, and output types are aliases of their owning packages.
type AltColumn ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type AltColumnAlign ¶ added in v0.4.0
type AltColumnAlign = display.AltColumnAlign
Limits, diagnostics, and output types are aliases of their owning packages.
type AltDescription ¶ added in v0.4.0
type AltDescription = display.AltDescription
Limits, diagnostics, and output types are aliases of their owning packages.
Example ¶
package main
import (
"fmt"
"github.com/caelyreth/untie"
)
func main() {
expr := untie.ParseTeX(`\frac{n}{k}`, untie.Inline, untie.ParseOptions{})
description := expr.Alt().Description
if description == nil {
panic("missing structured accessibility description")
}
root := description.Root
fmt.Println(root.Kind)
fmt.Println(root.FractionRole)
for _, part := range root.Parts {
fmt.Println(part.Role, part.Node.Kind, part.Node.Text)
}
}
Output: fraction ordinary numerator glyph n denominator glyph k
type AltFlag ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type AltFontSize ¶ added in v0.4.0
type AltFontSize = display.AltFontSize
Limits, diagnostics, and output types are aliases of their owning packages.
type AltFractionRole ¶ added in v0.4.0
type AltFractionRole = display.AltFractionRole
Limits, diagnostics, and output types are aliases of their owning packages.
type AltFractionStyle ¶ added in v0.4.0
type AltFractionStyle = display.AltFractionStyle
Limits, diagnostics, and output types are aliases of their owning packages.
type AltMathSize ¶ added in v0.4.0
type AltMathSize = display.AltMathSize
Limits, diagnostics, and output types are aliases of their owning packages.
type AltNode ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type AltNodeKind ¶ added in v0.4.0
type AltNodeKind = display.AltNodeKind
Limits, diagnostics, and output types are aliases of their owning packages.
type AltOverlayAlignment ¶ added in v0.4.0
type AltOverlayAlignment = display.AltOverlayAlignment
Limits, diagnostics, and output types are aliases of their owning packages.
type AltPart ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type AltPartRole ¶ added in v0.4.0
type AltPartRole = display.AltPartRole
Limits, diagnostics, and output types are aliases of their owning packages.
type AltPosition ¶ added in v0.4.0
type AltPosition = display.AltPosition
Limits, diagnostics, and output types are aliases of their owning packages.
type AltRaiseDirection ¶ added in v0.4.0
type AltRaiseDirection = display.AltRaiseDirection
Limits, diagnostics, and output types are aliases of their owning packages.
type AltRow ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type AltScriptRole ¶ added in v0.4.0
type AltScriptRole = display.AltScriptRole
Limits, diagnostics, and output types are aliases of their owning packages.
type AltSizingKind ¶ added in v0.4.0
type AltSizingKind = display.AltSizingKind
Limits, diagnostics, and output types are aliases of their owning packages.
type AltSpaceKind ¶ added in v0.4.0
type AltSpaceKind = display.AltSpaceKind
Limits, diagnostics, and output types are aliases of their owning packages.
type AltSpaceWidth ¶ added in v0.4.0
type AltSpaceWidth = display.AltSpaceWidth
Limits, diagnostics, and output types are aliases of their owning packages.
type AltTableRole ¶ added in v0.4.0
type AltTableRole = display.AltTableRole
Limits, diagnostics, and output types are aliases of their owning packages.
type AltTag ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type AltVariant ¶ added in v0.4.0
type AltVariant = display.AltVariant
Limits, diagnostics, and output types are aliases of their owning packages.
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 CaretStop ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type ColorPolicy ¶ added in v0.4.0
type ColorPolicy = display.ColorPolicy
Limits, diagnostics, and output types are aliases of their owning packages.
type ColorPolicyMode ¶ added in v0.4.0
type ColorPolicyMode = display.ColorPolicyMode
Limits, diagnostics, and output types are aliases of their owning packages.
type ColorRolePalette ¶ added in v0.4.0
type ColorRolePalette = display.ColorRolePalette
Limits, diagnostics, and output types are aliases of their owning packages.
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) LayoutContextWithOptions ¶ added in v0.4.0
func (e *Engine) LayoutContextWithOptions( ctx context.Context, expr *Expr, style Style, options LayoutOptions, ) (*Box, error)
LayoutContextWithOptions lays out an expression with explicit recovery behavior.
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.
func (*Engine) LayoutFormulaContextWithOptions ¶ added in v0.4.0
func (e *Engine) LayoutFormulaContextWithOptions( ctx context.Context, formula *Formula, mode Mode, style Style, options LayoutOptions, ) (*Box, error)
LayoutFormulaContextWithOptions lays out canonical IR with explicit recovery behavior.
type EquationLabel ¶ added in v0.4.0
type EquationLabel = ir.EquationLabel
Limits, diagnostics, and output types are aliases of their owning packages.
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. TeX \label commands become formula-scoped metadata and \eqref resolves only through ParseOptions.References; there is no global document state, automatic numbering, or cross-formula lookup.
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, speech, and a structured localization tree 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 and its structured accessibility description 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) Labels ¶ added in v0.4.0
func (e *Expr) Labels() []ir.EquationLabel
Labels returns an independent copy of formula-scoped label metadata in source order.
func (*Expr) RootSnapshot ¶
RootSnapshot returns an independent, validated copy of the canonical IR.
type FaceUse ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
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.
func WithFontVariations ¶ added in v0.4.0
func WithFontVariations(variations ...Variation) FontOption
WithFontVariations sets OpenType design-variation coordinates for LoadMathFont. Omitted axes use the defaults declared by the font.
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 FontUsage ¶ added in v0.4.0
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 LayoutOptions ¶ added in v0.4.0
type LayoutOptions struct {
Recovery RecoveryMode
}
LayoutOptions controls one low-level Engine layout.
type MissingFallback ¶ added in v0.4.0
type MissingFallback = display.MissingFallback
Limits, diagnostics, and output types are aliases of their owning packages.
type NodeID ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type ParseOptions ¶
ParseOptions configure parsing. TeX macros and references are ignored by the Typst frontend. References maps decoded formula label names to host-supplied visible text used by TeX \eqref; values are not parsed as math. 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 PixelGrid ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type RecoveryMode ¶ added in v0.4.0
type RecoveryMode uint8
RecoveryMode controls whether layout may replace recoverable font failures with visible output.
The zero value is RecoveryVisible so editor-facing rendering remains useful while a formula is incomplete. RecoveryStrict is intended for conformance tests, validation tooling, and hosts that require a complete font match.
const ( // RecoveryVisible renders recoverable missing glyphs as error-colored // placeholder boxes and reports them through diagnostics. RecoveryVisible RecoveryMode = iota // RecoveryStrict reports recoverable font failures as layout errors. RecoveryStrict )
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 when layout succeeds or recoverable problems were rendered visibly. Diagnostics contain an independent snapshot of parse and layout problems and are returned with fatal 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
Recovery RecoveryMode
}
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 SnapAxis ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
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. A formula-level display tag populates Box.Tag and the associated LineBox.Tag. Source-row tags populate Box.Tags and use TagBox.Line instead. Constrained alignment reserves the applicable tag column before positioning the line. Inline layout ignores both MaxWidth and Align and rejects manual tags.
type Variation ¶ added in v0.4.0
Limits, diagnostics, and output types are aliases of their owning packages.
type VariationAxis ¶ added in v0.4.0
type VariationAxis = font.VariationAxis
Limits, diagnostics, and output types are aliases of their owning packages.
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. |
|
mathml
command
Command mathml converts TeX or Typst math to deterministic Presentation MathML.
|
Command mathml converts TeX or Typst math to deterministic Presentation MathML. |
|
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. |
|
Package identity defines opaque identities shared by canonical IR and display output.
|
Package identity defines opaque identities shared by canonical IR and display output. |
|
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. |
|
quality/upstreamfetch
command
Command upstreamfetch hydrates the raw upstream test inputs declared by the pinned source lock.
|
Command upstreamfetch hydrates the raw upstream test inputs declared by the pinned source lock. |
|
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 mathml converts between Untie canonical IR and Presentation MathML.
|
Package mathml converts between Untie canonical IR and Presentation MathML. |
|
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. |
|
Package stream renders append-only formula updates as stable display transitions.
|
Package stream renders append-only formula updates as stable display transitions. |