formula

package module
v0.0.0-...-c36a288 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 23 Imported by: 1 module, 0 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

NSGo Formula

English | 简体中文

Native math for NSGo apps. Untie lays out TeX and Typst formulas, and this module draws them on a canvas in New Computer Modern Math, inline on their text's baseline or as display formulas of their own. Formulas follow the text's size and color, wrap a display formula that is too wide at its relations and operators, read to assistive technology as what they say in English or Chinese, and copy as TeX and Presentation MathML.

Install

go get github.com/nsgo-dev/nsgo-formula

The module embeds its 1.4 MB math font; an app links it, Untie and the font only when it imports this module.

Typeset a TextView's formulas

Give a text view the plugin, and its $…$, $$…$$, \(…\) and \[…\] formulas are typeset:

import (
	"github.com/nsgo-dev/nsgo/base/textview"

	formula "github.com/nsgo-dev/nsgo-formula"
)

textview.TextView{Markdown: source, Plugins: []textview.Plugin{formula.Plugin()}}

The same Plugins field works on ui.TextView, and textview.Provide gives the plugin to every text view below a scope. formula.Plugin() uses the default renderer; formula.NewRenderer(formula.Fonts{…}) makes one with your own math, text and fallback fonts, and its Plugin() method typesets with them.

formula.View shows a formula anywhere else: Source in Dialect (formula.TeX or formula.Typst), Display for a formula on a line of its own.

Streaming replies

While a reply streams in, a formula's source is often incomplete. Give the views StreamingFunc and they show what parses so far without marking what has yet to arrive as errors; once the function reports false, any error left shows, without rebuilding the view:

streamingMath := textview.Plugin{RenderMath: func(cx *core.Scope, m textview.Math) core.Node {
	return formula.View{Source: m.TeX, Display: m.Display, StreamingFunc: streaming.Get}
}}

ui.TextView{MarkdownFunc: reply.Get, Options: textview.Options{Streaming: true}, Plugins: []textview.Plugin{streamingMath}}

Copy as MathML and TeX

Selecting a formula in a selectable text view and copying it writes its TeX between $ or $$ as plain text, Presentation MathML (application/mathml+xml) and its source (text/x-tex). Copy one yourself with formula.Copy(cx, source, dialect, display), which writes text/x-typst for Typst; formula.MathML and formula.ClipboardItem give the same representations without the clipboard. Where the platform writes only plain text, the copy is the source.

TSX

Import the tsx package for its effect in the Go host, next to NSGo's tsx/textview or tsx/ui. It registers Formula in the TSX module nsgo-formula, and go tool nsgo check writes its types to .nsgo/types/nsgo-formula.d.ts.

import _ "github.com/nsgo-dev/nsgo-formula/tsx"
import { TextView } from "nsgo/base";
import { Formula } from "nsgo-formula";

<TextView markdown={source}
  plugins={[{ renderMath: (math) => <Formula source={math.tex} display={math.display} /> }]} />

Formula takes source, dialect ("tex" or "typst", FormulaDialect), display, streaming, accessibilityLabel and the usual styling props; it uses the default renderer. A sandboxed bundle imports it only when its tsx.Sandbox lists "nsgo-formula" in Modules.

Platforms

Platform How formulas are typeset Checked by CI
macOS, Windows, Linux In the app, the font parsed off the main thread Tests on macOS, headless and native
iOS, iPadOS, Android In the app, as on desktops Vetted
watchOS In the app, drawn through the SwiftUI and Core Graphics canvas host Vetted
Web In a dedicated Web Worker, nsgo-worker.js, which the nsgo tool writes next to the app; in the page where the browser has no Worker Tests in Chrome
HarmonyOS, WeChat mini programs In the app's own WebAssembly instance Vetted

On the web the worker reuses the page's compiled module, so it fetches and compiles nothing again; a page that loads the app from another origin starts it from a Blob instead. Until the font has loaded, a formula is an empty em square.

Example

examples/formulas shows a document with inline and display formulas, a Typst formula copied as MathML, and a chat reply that streams formulas in:

go tool nsgo dev examples/formulas

Development

go tool nsgo check
go tool nsgo test
go tool nsgo test -target macos
go tool nsgo test -target web

License

Apache License 2.0; see LICENSE and NOTICE, which credits Untie (MIT or Apache 2.0) and its MyGo adapter, and New Computer Modern Math, under the GUST Font License (fonts/LICENSE).

Documentation

Overview

Package formula typesets math, written in TeX or Typst, with Untie (github.com/caelyreth/untie), and draws it in the font size and the text color it inherits: inline, on its text's baseline, or as a display formula of its own. Its font is New Computer Modern Math Book, embedded and loaded off the engine's goroutine as a formula first shows, or the app's through NewRenderer. textview.TextView draws its formulas so with Plugin.

Index

Constants

View Source
const (
	// MIMETeX is the media type of a TeX formula's source on the clipboard.
	MIMETeX = "text/x-tex"
	// MIMETypst is the media type of a Typst formula's source on the clipboard.
	MIMETypst = "text/x-typst"
	// MIMEMathML is the media type of Presentation MathML on the clipboard.
	MIMEMathML = "application/mathml+xml"
)

Variables

This section is empty.

Functions

func ClipboardItem

func ClipboardItem(source string, dialect Dialect, display bool) core.ClipboardItem

ClipboardItem builds one clipboard item carrying source as plain text, Presentation MathML (application/mathml+xml) when serialization succeeds, and the formula's dialect source (text/x-tex for TeX, text/x-typst for Typst).

func Copy

func Copy(cx *core.Scope, source string, dialect Dialect, display bool)

Copy puts a formula on the system clipboard with its plain text, Presentation MathML (application/mathml+xml) and dialect source (text/x-tex or text/x-typst) through WriteClipboardItems, falling back to plain text via SetClipboard on platforms without representation access.

func MathML

func MathML(source string, dialect Dialect, display bool) (string, error)

MathML returns deterministic Presentation MathML for source in dialect and display mode, produced through Untie's canonical IR and mathml.Marshal.

func Plugin

func Plugin() textview.Plugin

Plugin is Default().Plugin(), for textview.TextView{Plugins: []textview.Plugin{formula.Plugin()}}.

Types

type Dialect

type Dialect uint8

Dialect is the language a formula is written in.

const (
	// TeX is LaTeX's math, as $…$ holds it; the zero value.
	TeX Dialect = iota
	// Typst is Typst's math mode.
	Typst
)

type Fonts

type Fonts struct {
	Math      []byte
	Text      []byte
	Fallbacks [][]byte
}

Fonts are a renderer's fonts, OpenType files: Math, with a MATH table, lays the formulas out; Text, else Math, sets \text and \operatorname; and Fallbacks are tried in order for characters the others lack. Text runs these fonts cannot cover use the platform's system fonts. The app is responsible for its fonts' licenses.

type HitEvent

type HitEvent struct {
	Source      string
	Dialect     Dialect
	Phase       HitPhase
	Hit         untie.Hit
	Found       bool
	Point       untie.Point
	Caret       untie.CaretStop
	HasCaret    bool
	Diagnostics []untie.Diagnostic
	Position    core.Point
	Clicks      int
	Modifiers   core.Modifiers
}

HitEvent carries the Untie source part and nearest caret under a formula's pointer. Diagnostics contains supplied diagnostics whose ranges cover that part, so an editor can route presses, caret placement and diagnostics without reproducing Untie's geometry.

type HitPhase

type HitPhase uint8

HitPhase identifies the pointer interaction reported by HitEvent.

const (
	// HitHover reports pointer movement over the formula.
	HitHover HitPhase = iota
	// HitPress reports the primary press that starts a click.
	HitPress
	// HitClick reports the completed primary click at its press point.
	HitClick
)

type Renderer

type Renderer struct {
	// contains filtered or unexported fields
}

Renderer lays formulas out in one set of fonts and keeps the last layouts it made, as shapes ready to draw. Missing text runs are measured and drawn by each View with its platform text engine. It is safe for concurrent use, so the engines of a process share one.

func Default

func Default() *Renderer

Default returns the renderer of the embedded New Computer Modern Math Book, whose font loads on first use: a View waits for it off the engine's goroutine.

func NewRenderer

func NewRenderer(fonts Fonts) (*Renderer, error)

NewRenderer prepares a renderer for fonts, parsing and validating them, which takes a while for a large font: about 120 ms for New Computer Modern Math on an M-series Mac, and runs in a Web Worker in browsers so the page's thread stays responsive. It fails when Math has no usable MATH table.

func (*Renderer) Plugin

func (r *Renderer) Plugin() textview.Plugin

Plugin typesets a text view's formulas with r, for textview.TextView{Plugins: []textview.Plugin{r.Plugin()}} or textview.Provide: an inline one, or a display one with Display's larger operators and limits, wrapped to its block's padded width. TextView centers its lines and scrolls any unbreakable overflow. A copy takes them as their TeX between $ and $$.

type View

type View struct {
	// Source is the formula without its delimiters ($…$); SourceFunc follows what it reads.
	Source     string
	SourceFunc func() string
	Dialect    Dialect
	Display    bool
	// Streaming hides recoverable error and placeholder ink while Source is still arriving. SourceFunc continues to lay out each update. Set it false when the source is complete to show remaining errors; StreamingFunc follows what it reads.
	Streaming     bool
	StreamingFunc func() bool
	// Renderer lays it out; nil is Default().
	Renderer *Renderer
	// Label is what assistive technology reads in place of what the formula says.
	Label     string
	Class     string
	Style     core.Style
	StyleFunc func() core.Style
	// ErrorStyle's color marks what failed to parse; ErrorClass and ErrorStyle style the source a formula past Untie's limits, or whose fonts did not load, shows instead.
	ErrorClass string
	ErrorStyle core.Style
	// Diagnostics are source ranges an editor wants associated with the formula; HitEvent reports the entries whose ranges cover the hit part. DiagnosticsFunc follows what it reads.
	Diagnostics     []untie.Diagnostic
	DiagnosticsFunc func() []untie.Diagnostic
	// OnHit receives hover, press and click events resolved through Untie's Box. It runs on the engine goroutine.
	OnHit  func(HitEvent)
	TestID string
}

View draws a formula. It sizes itself in ems of the font size it inherits, following the user's text size as text does, and paints in the text color it inherits, keeping the colors the formula names (\color{red}). As a core.Span's attachment it sits on the line's baseline. With Display it is a formula on a line of its own: larger operators, and limits above and below. Display formulas wrap at safe relations and operators when wider than the available width; an unbreakable part keeps its overflow. What failed to parse is marked in ErrorStyle's color, the text color without one; a formula past Untie's limits shows its source as text in ErrorClass and ErrorStyle. It keeps its size in a container that stretches its children, standing at the start of the cross axis unless its style sets AlignSelf. Until its renderer's font has loaded, it is an empty em square. Assistive technology reads it as an image labelled with what the formula says, in the language the app shows.

func (View) Render

func (v View) Render(cx *core.Scope) core.Node

Render implements core.Node.

Directories

Path Synopsis
examples
formulas command
Command formulas shows math in an NSGo app: a document whose TeX formulas a text view typesets, a Typst formula of its own that copies as MathML and TeX, and a chat reply that streams formulas in without flashing errors while they are incomplete.
Command formulas shows math in an NSGo app: a document whose TeX formulas a text view typesets, a Typst formula of its own that copies as MathML and TeX, and a chat reply that streams formulas in without flashing errors while they are incomplete.
Package locales says what the formula package's formulas read as, to assistive technology, in the language the app shows.
Package locales says what the formula package's formulas read as, to assistive technology, in the language the app shows.
Package tsx gives TSX the module nsgo-formula, whose Formula is the formula package's View, which links Untie and its bundled math font: an app whose TSX typesets formulas imports this package for its effect.
Package tsx gives TSX the module nsgo-formula, whose Formula is the formula package's View, which links Untie and its bundled math font: an app whose TSX typesets formulas imports this package for its effect.

Jump to

Keyboard shortcuts

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