untie

package module
v0.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: Apache-2.0, MIT Imports: 20 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Untie

Untie is a pure-Go math renderer for TeX and Typst. It parses both input languages into one language-neutral representation, lays formulas out with a host-supplied OpenType MATH font, and returns a UI-independent display list of glyph paths, rules, source hits, and accessibility text.

Properties

  • one renderer for TeX and Typst math;
  • pure Go with CGO_ENABLED=0;
  • no browser, DOM, GPU, platform text, or system-font dependency;
  • deterministic layout and output;
  • recoverable parsing with source diagnostics;
  • core color policies for authored-color preservation, semantic mapping, and contrast correction;
  • structured text-face and missing-fallback reporting;
  • optional conservative pixel-grid snapping for thin rules and stems;
  • source-mapped hit regions, caret stops, and explicit stable node IDs;
  • OpenType MATH metrics, glyph outlines, variants, and assemblies;
  • reusable rendering with bounded caches;
  • inline and display layout, line breaking, equation tags, and overflow bounds;
  • formula-scoped labels and host-resolved equation references;
  • deterministic text, speech, and structured localization alternatives for accessibility;
  • deterministic Presentation MathML export and a bounded strict importer;
  • bounded mhchem-style \ce and \pu support without a chemistry database;
  • optional SVG and PNG output.

Use

NewRenderer is the main API for applications. Load the font once, keep the renderer, and call Render whenever the source or style changes.

import (
	"context"
	"os"

	"github.com/caelyreth/untie"
	"github.com/caelyreth/untie/render"
)

fontBytes, err := os.ReadFile("NewCMMath-Book.otf")
if err != nil {
	return err
}
fonts, err := untie.LoadMathFont(fontBytes)
if err != nil {
	return err
}
math, err := untie.NewRenderer(fonts, untie.RendererOptions{
	DefaultStyle: untie.Style{Size: 24},
	CacheEntries: 128,
})
if err != nil {
	return err
}

result, err := math.Render(context.Background(), `x^2+\frac{1}{2}`, untie.RenderRequest{
	Mode: untie.Display,
})
if err != nil {
	// Recoverable parse diagnostics may still be present in result.
	return err
}

err = render.Walk(result.Box, func(command render.Command) error {
	switch command.Kind {
	case render.CommandPath:
		// Paint command.Path using command.At, command.Em, and command.Paint.
	case render.CommandRule:
		// Fill command.Rect with command.Paint.
	}
	return nil
})

The renderer caches immutable parsed expressions when CacheEntries is positive. It never reuses returned boxes, so each successful Render produces an independent display list.

For ready-made output, use encode/svg or encode/raster. SVG supports deterministic vector export; the raster package provides antialiased RGBA and PNG output without cgo.

Use mathml for Presentation MathML interchange. Export covers every canonical IR node family. Import is intentionally limited to a documented strict subset with structured diagnostics for unsupported input.

Lower-Level API

Use NewEngine when you need explicit engine ownership, direct canonical-IR layout, or a custom parse/layout pipeline. It exposes the same layout core as Renderer, without the convenience facade.

engine, err := untie.NewEngine(fonts, untie.Limits{})
if err != nil {
	return err
}
expr := untie.ParseTeX(`\sum_{i=1}^{n} i^2`, untie.Display, untie.ParseOptions{})
box, err := engine.Layout(expr, untie.Style{Size: 24})

See Getting Started for the complete integration pipeline and Rendering for the drawing contract.

MyGo

The optional contrib/mygo adapter renders directly to MyGo elements and plugs into Markdown math:

math, err := untiemygo.New(fonts, untiemygo.Options{
	Dialect:      untie.TeX,
	CacheEntries: 128,
})
if err != nil {
	return err
}

ui.Column(c).Children(func() {
	math.Element(c, source, untie.Display).FillWidth()
})

BindMarkdown adds $...$, $$...$$, \(...\), and \[...\] support to a MyGo Markdown view. See the MyGo integration guide for direct elements, Markdown binding, and existing-box drawing.

Documentation

Release

v0.4.2 is the latest published release. Untie remains pre-1.0 while its API stability tiers are validated through real integrations. Release notes are generated from Conventional Commits and published in GitHub Releases; see Release Process for the maintainer workflow.

License

Copyright 2026 Yu (Caelyreth).

Untie is dual-licensed under either:

You may choose either license at your option.

The SPDX expression for original project material is MIT OR Apache-2.0.

Third-party material remains under its own license; see Third-Party Licenses.

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

Examples

Constants

View Source
const (
	Inline  = ir.Inline
	Display = ir.Display
)
View Source
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
)
View Source
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

View Source
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
)
View Source
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
)
View Source
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")
)
View Source
var ErrInvalidRecovery = errors.New("untie: invalid recovery mode")

ErrInvalidRecovery reports an unknown recovery mode.

View Source
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.

func Version

func Version() string

Version returns the library and layout revision used in cache contracts.

Types

type Align

type Align = display.Align

Limits, diagnostics, and output types are aliases of their owning packages.

type Alt

type Alt = display.Alt

Limits, diagnostics, and output types are aliases of their owning packages.

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

type AltColumn = display.AltColumn

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

type AltFlag = display.AltFlag

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

type AltNode = display.AltNode

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

type AltPart = display.AltPart

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

type AltRow = display.AltRow

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

type AltTag = display.AltTag

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

type Box = display.Box

Limits, diagnostics, and output types are aliases of their owning packages.

func Layout

func Layout(expr *Expr, fonts *FontSet, style Style) (*Box, error)

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

func LayoutContext(ctx context.Context, expr *Expr, fonts *FontSet, style Style) (*Box, error)

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 Break

type Break = display.Break

Limits, diagnostics, and output types are aliases of their owning packages.

type BreakKind

type BreakKind = display.BreakKind

Limits, diagnostics, and output types are aliases of their owning packages.

type CaretStop added in v0.4.0

type CaretStop = display.CaretStop

Limits, diagnostics, and output types are aliases of their owning packages.

type Code

type Code = source.Code

Code is a stable diagnostic identifier.

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 Dialect

type Dialect uint8

Dialect selects the input math language.

const (
	TeX Dialect = iota
	Typst
)

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

func NewEngine(fonts *FontSet, limits Limits) (prepared *Engine, err error)

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

func (e *Engine) FontKeySHA256() [32]byte

FontKeySHA256 returns the collision-resistant identity of the prepared font set used by the Engine.

func (*Engine) Layout

func (e *Engine) Layout(expr *Expr, style Style) (*Box, error)

Layout lays out an expression with a background context.

func (*Engine) LayoutContext

func (e *Engine) LayoutContext(ctx context.Context, expr *Expr, style Style) (*Box, error)

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.

func (*Engine) Limits

func (e *Engine) Limits() Limits

Limits returns the effective resource limits used by the Engine.

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

func (e *Expr) Alt() 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

func (e *Expr) AltContext(ctx context.Context) (Alt, error)

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) Dialect

func (e *Expr) Dialect() Dialect

Dialect returns the source dialect.

func (*Expr) HasErrors

func (e *Expr) HasErrors() bool

HasErrors reports whether parsing produced at least one error-severity diagnostic. The expression remains drawable whether this returns true or false.

func (*Expr) Key

func (e *Expr) Key() uint64

Key returns a stable convenience cache key for the parsed expression.

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) Mode

func (e *Expr) Mode() Mode

Mode returns the root math mode.

func (*Expr) RootSnapshot

func (e *Expr) RootSnapshot() (*ir.Formula, error)

RootSnapshot returns an independent, validated copy of the canonical IR.

func (*Expr) Source

func (e *Expr) Source() string

Source returns the original source.

type FaceUse added in v0.4.0

type FaceUse = display.FaceUse

Limits, diagnostics, and output types are aliases of their owning packages.

type FontFace

type FontFace = font.FontFace

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

type FontSet = font.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

type FontUsage = display.FontUsage

Limits, diagnostics, and output types are aliases of their owning packages.

type Formula

type Formula = ir.Formula

Limits, diagnostics, and output types are aliases of their owning packages.

type Hit

type Hit = display.Hit

Limits, diagnostics, and output types are aliases of their owning packages.

type HitKind

type HitKind = display.HitKind

Limits, diagnostics, and output types are aliases of their owning packages.

type HitRange

type HitRange = display.HitRange

Limits, diagnostics, and output types are aliases of their owning packages.

type Item

type Item = display.Item

Limits, diagnostics, and output types are aliases of their owning packages.

type ItemKind

type ItemKind = display.ItemKind

Limits, diagnostics, and output types are aliases of their owning packages.

type ItemRange

type ItemRange = display.ItemRange

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 Limits

type Limits = source.Limits

Limits, diagnostics, and output types are aliases of their owning packages.

type LineBox

type LineBox = display.LineBox

Limits, diagnostics, and output types are aliases of their owning packages.

type Macro

type Macro struct {
	Body string
	Args int
}

Macro is a host-provided TeX macro.

type MissingFallback added in v0.4.0

type MissingFallback = display.MissingFallback

Limits, diagnostics, and output types are aliases of their owning packages.

type Mode

type Mode = ir.Mode

Mode selects root math style.

type NodeID added in v0.4.0

type NodeID = ir.NodeID

Limits, diagnostics, and output types are aliases of their owning packages.

type Paint

type Paint = display.Paint

Limits, diagnostics, and output types are aliases of their owning packages.

type ParseOptions

type ParseOptions struct {
	Macros     map[string]Macro
	References map[string]string
	Limits     Limits
}

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 Path

type Path = geometry.Path

Limits, diagnostics, and output types are aliases of their owning packages.

type PathTemplate

type PathTemplate = display.PathTemplate

Limits, diagnostics, and output types are aliases of their owning packages.

type PixelGrid added in v0.4.0

type PixelGrid = display.PixelGrid

Limits, diagnostics, and output types are aliases of their owning packages.

type Point

type Point = geometry.Point

Limits, diagnostics, and output types are aliases of their owning packages.

type RGBA

type RGBA = display.RGBA

Limits, diagnostics, and output types are aliases of their owning packages.

type Range

type Range = source.Range

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 Rect

type Rect = geometry.Rect

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

type RenderResult struct {
	Box         *display.Box
	Diagnostics []source.Diagnostic
	Alt         display.Alt
}

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 Role

type Role = display.Role

Limits, diagnostics, and output types are aliases of their owning packages.

type Segment

type Segment = geometry.Segment

Limits, diagnostics, and output types are aliases of their owning packages.

type Severity

type Severity = source.Severity

Limits, diagnostics, and output types are aliases of their owning packages.

type SnapAxis added in v0.4.0

type SnapAxis = display.SnapAxis

Limits, diagnostics, and output types are aliases of their owning packages.

type Style

type Style = display.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 TagBox

type TagBox = display.TagBox

Limits, diagnostics, and output types are aliases of their owning packages.

type Variation added in v0.4.0

type Variation = font.Variation

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.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL