untie

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 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;
  • source-mapped hit regions;
  • OpenType MATH metrics, glyph outlines, variants, and assemblies;
  • reusable rendering with bounded caches;
  • inline and display layout, line breaking, equation tags, and overflow bounds;
  • deterministic text and speech alternatives for accessibility;
  • 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.

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

The current tagged release is v0.2.0. Untie remains pre-1.0 while its API stability tiers are validated in real integrations. Release notes are generated from Conventional Commits; see GitHub Releases for published changes and 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, 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

	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
)
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
	CodeMissingGlyph       = source.CodeMissingGlyph
	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
)
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 (
	// 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 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 Code

type Code = source.Code

Code is a stable diagnostic identifier.

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

func (e *Engine) Limits() Limits

Limits returns the effective resource limits used by the Engine.

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

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

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

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

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

type Mode = ir.Mode

Mode selects root math style.

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
	Limits Limits
}

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

type TagBox

type TagBox = display.TagBox

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

Jump to

Keyboard shortcuts

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