shape_math: Shape math expression (LaTeX or Typst)

View source: R/shape_math.R

shape_mathR Documentation

Shape math expression (LaTeX or Typst)

Description

Parses a math expression and returns positioned glyphs for rendering. The function uses HarfBuzz's OpenType MATH table support to properly position mathematical symbols, scripts, fractions, and other structures according to the font's mathematical typesetting rules. Both LaTeX and Typst syntaxes are supported and automatically detected.

Usage

shape_math(
  math,
  family = "math",
  size = 12,
  res = 72,
  inline = TRUE,
  color = "black",
  path = NULL,
  index = 0
)

Arguments

math

A character vector of math expressions. Supports both LaTeX and Typst syntax (auto-detected). For LaTeX, use raw strings like r"(\\alpha)" or escape backslashes: "\\alpha". For Typst, use function syntax like "frac(a, b)" or "sqrt(x^2 + y^2)".

family

Font family name. For best results, use a font with an OpenType MATH table such as "STIX Two Math", "Latin Modern Math", "Cambria Math", or "Libertinus Math". Fonts without a MATH table will use fallback positioning constants based on TeX defaults, which produces reasonable but less precise results. Default uses the system's default math font.

size

The size in points to use for the font

res

The resolution to use when doing the shaping. Should optimally match the resolution used when rendering the glyphs.

inline

Logical. If TRUE (default), uses inline style. If FALSE, uses display style (larger operators with limits above/below).

color

Base color for the equation (default "black"). Individual elements can override this using ⁠\textcolor{color}{content}⁠.

path, index

path an index of a font file to circumvent lookup based on family and style

Details

Font Requirements

Mathematical typesetting works best with fonts that include an OpenType MATH table, which provides precise positioning parameters for scripts, fractions, radicals, and other structures. When using a font without a MATH table (such as Arial or Times New Roman), the function falls back to default positioning constants based on TeX conventions. The results will be reasonable but may not match the typographic quality of a dedicated math font.

Syntax Detection

The function automatically detects whether the input is LaTeX or Typst syntax. LaTeX is detected when the input contains backslash commands like ⁠\frac⁠ or ⁠\alpha⁠. Otherwise, Typst syntax is assumed. You can freely mix expressions in a vector, each will be parsed independently.

Supported Typst Syntax

Typst math uses function-call syntax instead of backslash commands:

Symbols

Greek letters as identifiers: alpha, beta, gamma, etc. Operators: +, -, *, /, =

Numbers

123, 3.14

Text

"text in quotes"

Styling

bold(x), italic(x), upright(x), sans(x), mono(x), cal(X), frak(X), bb(R)

Scripts

x^2, x_i, x_i^2

Fractions

frac(a, b)

Binomials

binom(n, k)

Over/under

overbrace(x, "label"), underbrace(x, "label"), overline(x), underline(x)

Radicals

sqrt(x), root(n, x)

Delimiters

lr((x)), abs(x), norm(x), floor(x), ceil(x)

Big operators

sum, integral, product - use limits(sum) for above/below placement or scripts(sum) for side scripts

Accents

hat(x), tilde(x), dot(x), ddot(x), bar(x), vec(x), acute(x), grave(x), breve(x). Optional parameters: accent(i, hat, dotless: true) uses dotless ı/ȷ, ⁠accent(x, hat, size: 150%)⁠ scales the accent

Wide accents

widehat(abc), widetilde(abc), overrightarrow(AB), overleftarrow(AB)

Spacing

thin, med, thick, quad, wide or ⁠h(1em)⁠

Functions

sin, cos, tan, log, exp, lim

Custom operator

op("name")

Matrices

⁠mat(1, 2; 3, 4)⁠ - semicolon separates rows, comma separates columns. Optional parameters: mat(augment: 1, ...) for vertical divider after column 1, ⁠mat(augment: #(vline: 1, hline: 0), ...)⁠ for both vertical and horizontal dividers, ⁠mat(rowgap: 1em, ...)⁠ and ⁠mat(columngap: 2em, ...)⁠ for custom spacing

Cases

⁠cases(a &"if" b, c &"if" d)⁠

Cancel

cancel(x)

Display styles

display(x), inline(x), script(x), sscript(x). Optional cramped: true parameter reduces superscript height: display(x^2, cramped: true)

Phantom

hide(x)

Attachment

attach(base, t: top, b: bot)

Stretch

⁠stretch(=, size: 3em)⁠ stretches a glyph to a specified size

Math class

class("relation", x) forces a symbol to behave as a specific math class (affects spacing). Classes: normal, punctuation, opening, closing, fence, large, relation, unary, binary, vary

Supported LaTeX Commands

LaTeX math expressions is a huge specification and also includes numerous extensions with additional functionality. Supporting the full set would be unfeasible but textshaping tries hard to cover all but the most esoteric needs. The list of supported functionality is:

Greek letters

⁠\alpha⁠, ⁠\beta⁠, ⁠\gamma⁠, ⁠\delta⁠, ⁠\epsilon⁠, ⁠\varepsilon⁠, ⁠\zeta⁠, ⁠\eta⁠, ⁠\theta⁠, ⁠\vartheta⁠, ⁠\iota⁠, ⁠\kappa⁠, ⁠\lambda⁠, ⁠\mu⁠, ⁠\nu⁠, ⁠\xi⁠, ⁠\pi⁠, ⁠\varpi⁠, ⁠\rho⁠, ⁠\varrho⁠, ⁠\sigma⁠, ⁠\varsigma⁠, ⁠\tau⁠, ⁠\upsilon⁠, ⁠\phi⁠, ⁠\varphi⁠, ⁠\chi⁠, ⁠\psi⁠, ⁠\omega⁠, ⁠\Gamma⁠, ⁠\Delta⁠, ⁠\Theta⁠, ⁠\Lambda⁠, ⁠\Xi⁠, ⁠\Pi⁠, ⁠\Sigma⁠, ⁠\Upsilon⁠, ⁠\Phi⁠, ⁠\Psi⁠, ⁠\Omega⁠

Binary operators

+, -, =, ⁠\pm⁠, ⁠\mp⁠, ⁠\times⁠, ⁠\div⁠, ⁠\cdot⁠, ⁠\ast⁠, ⁠\star⁠, ⁠\circ⁠, ⁠\bullet⁠, ⁠\cap⁠, ⁠\cup⁠, ⁠\vee⁠, ⁠\wedge⁠, ⁠\setminus⁠, ⁠\oplus⁠, ⁠\ominus⁠, ⁠\otimes⁠, ⁠\oslash⁠, ⁠\odot⁠, ⁠\ltimes⁠, ⁠\rtimes⁠, ⁠\boxplus⁠, ⁠\boxminus⁠, ⁠\boxtimes⁠

Relations

⁠\leq⁠, ⁠\le⁠, ⁠\geq⁠, ⁠\ge⁠, ⁠\neq⁠, ⁠\ne⁠, ⁠\equiv⁠, ⁠\approx⁠, ⁠\sim⁠, ⁠\simeq⁠, ⁠\cong⁠, ⁠\propto⁠, ⁠\ll⁠, ⁠\gg⁠, ⁠\subset⁠, ⁠\supset⁠, ⁠\subseteq⁠, ⁠\supseteq⁠, ⁠\in⁠, ⁠\ni⁠, ⁠\notin⁠, ⁠\perp⁠, ⁠\parallel⁠, ⁠\mid⁠, ⁠\prec⁠, ⁠\succ⁠, ⁠\preceq⁠, ⁠\succeq⁠, ⁠\leqslant⁠, ⁠\geqslant⁠, ⁠\lesssim⁠, ⁠\gtrsim⁠, ⁠\vDash⁠, ⁠\Vdash⁠, ⁠\triangleq⁠

Arrows

⁠\to⁠, ⁠\rightarrow⁠, ⁠\leftarrow⁠, ⁠\Rightarrow⁠, ⁠\Leftarrow⁠, ⁠\leftrightarrow⁠, ⁠\Leftrightarrow⁠, ⁠\mapsto⁠, ⁠\hookleftarrow⁠, ⁠\hookrightarrow⁠, ⁠\uparrow⁠, ⁠\downarrow⁠, ⁠\Uparrow⁠, ⁠\Downarrow⁠, ⁠\updownarrow⁠, ⁠\nearrow⁠, ⁠\searrow⁠, ⁠\swarrow⁠, ⁠\nwarrow⁠, ⁠\nleftarrow⁠, ⁠\nrightarrow⁠, ⁠\nLeftarrow⁠, ⁠\nRightarrow⁠, ⁠\nleftrightarrow⁠, ⁠\nLeftrightarrow⁠, ⁠\leftarrowtail⁠, ⁠\rightarrowtail⁠, ⁠\twoheadleftarrow⁠, ⁠\twoheadrightarrow⁠, ⁠\curvearrowleft⁠, ⁠\curvearrowright⁠

Scripts

x^2, x_i, x_i^2

Fractions

⁠\frac{num}{denom}⁠, ⁠\dfrac{}{}⁠ (display style), ⁠\tfrac{}{}⁠ (text style), ⁠\cfrac{}{}⁠ (continued fraction)

Roots

⁠\sqrt{x}⁠, ⁠\sqrt[n]{x}⁠

Big operators

⁠\sum⁠, ⁠\prod⁠, ⁠\coprod⁠, ⁠\int⁠, ⁠\iint⁠, ⁠\iiint⁠, ⁠\oint⁠, ⁠\bigcup⁠, ⁠\bigcap⁠, ⁠\bigvee⁠, ⁠\bigwedge⁠, ⁠\bigoplus⁠, ⁠\bigotimes⁠, ⁠\bigodot⁠, ⁠\biguplus⁠, ⁠\bigsqcup⁠ (with ⁠_{lower}^{upper}⁠ limits). Use ⁠\limits⁠ to force limits above/below or ⁠\nolimits⁠ to force side scripts

Delimiters

⁠\left(⁠, ⁠\right)⁠, ⁠\left[⁠, ⁠\right]⁠, ⁠\left\{⁠, ⁠\right\}⁠, ⁠\langle⁠, ⁠\rangle⁠, ⁠\lfloor⁠, ⁠\rfloor⁠, ⁠\lceil⁠, ⁠\rceil⁠, ⁠\vert⁠, ⁠\Vert⁠, ⁠\ulcorner⁠, ⁠\urcorner⁠, ⁠\llcorner⁠, ⁠\lrcorner⁠

Manual delimiter sizing

⁠\big⁠, ⁠\Big⁠, ⁠\bigg⁠, ⁠\Bigg⁠ and variants ⁠\bigl⁠, ⁠\bigr⁠, ⁠\bigm⁠, ⁠\Bigl⁠, ⁠\Bigr⁠, ⁠\Bigm⁠, etc. for manual control of delimiter size

Accents

⁠\hat{x}⁠, ⁠\check{x}⁠, ⁠\tilde{x}⁠, ⁠\acute{x}⁠, ⁠\grave{x}⁠, ⁠\dot{x}⁠, ⁠\ddot{x}⁠, ⁠\dddot{x}⁠, ⁠\ddddot{x}⁠, ⁠\breve{x}⁠, ⁠\bar{x}⁠, ⁠\vec{x}⁠, ⁠\mathring{x}⁠

Wide accents

⁠\widehat{abc}⁠, ⁠\widetilde{abc}⁠, ⁠\overline{abc}⁠, ⁠\underline{abc}⁠, ⁠\overbrace{abc}⁠, ⁠\underbrace{abc}⁠, ⁠\overrightarrow{AB}⁠, ⁠\overleftarrow{AB}⁠, ⁠\overleftrightarrow{AB}⁠, ⁠\underrightarrow{}⁠, ⁠\underleftarrow{}⁠, ⁠\underleftrightarrow{}⁠. Overbrace/underbrace support annotations: ⁠\overbrace{x+y}^{n}⁠, ⁠\underbrace{x+y}_{n}⁠

Functions

⁠\sin⁠, ⁠\cos⁠, ⁠\tan⁠, ⁠\cot⁠, ⁠\sec⁠, ⁠\csc⁠, ⁠\arcsin⁠, ⁠\arccos⁠, ⁠\arctan⁠, ⁠\arccot⁠, ⁠\sinh⁠, ⁠\cosh⁠, ⁠\tanh⁠, ⁠\coth⁠, ⁠\log⁠, ⁠\ln⁠, ⁠\lg⁠, ⁠\exp⁠, ⁠\lim⁠, ⁠\liminf⁠, ⁠\limsup⁠, ⁠\max⁠, ⁠\min⁠, ⁠\sup⁠, ⁠\inf⁠, ⁠\det⁠, ⁠\dim⁠, ⁠\ker⁠, ⁠\hom⁠, ⁠\arg⁠, ⁠\deg⁠, ⁠\gcd⁠, ⁠\Pr⁠, ⁠\mod⁠

Text

⁠\text{...}⁠

Font styles

⁠\mathbf{x}⁠, ⁠\mathit{x}⁠, ⁠\mathrm{x}⁠, ⁠\mathsf{x}⁠, ⁠\mathtt{x}⁠, ⁠\mathcal{X}⁠, ⁠\mathscr{X}⁠, ⁠\mathfrak{X}⁠, ⁠\mathbb{R}⁠, ⁠\boldsymbol{x}⁠, ⁠\bm{x}⁠

Math styles

⁠\displaystyle⁠, ⁠\textstyle⁠, ⁠\scriptstyle⁠, ⁠\scriptscriptstyle⁠ to control operator size and limit placement

Matrices

⁠\begin{matrix}⁠, ⁠\begin{pmatrix}⁠, ⁠\begin{bmatrix}⁠, ⁠\begin{vmatrix}⁠, ⁠\begin{Vmatrix}⁠, ⁠\begin{Bmatrix}⁠, ⁠\begin{smallmatrix}⁠ (with & for column separators and ⁠\\⁠ for row separators)

Alignment environments

⁠\begin{aligned}⁠, ⁠\begin{gathered}⁠, ⁠\begin{split}⁠, ⁠\begin{array}{lcr}⁠ for multi-line equations with alignment points

Cases

⁠\begin{cases}⁠, ⁠\begin{rcases}⁠, ⁠\begin{dcases}⁠, ⁠\begin{drcases}⁠

Stacked expressions

⁠\binom{n}{k}⁠, ⁠\tbinom{n}{k}⁠, ⁠\dbinom{n}{k}⁠, ⁠\overset{a}{b}⁠, ⁠\underset{a}{b}⁠, ⁠\stackrel{a}{b}⁠, ⁠\atop⁠

Operator names

⁠\operatorname{name}⁠, ⁠\operatorname*{name}⁠ (with limits)

Phantoms

⁠\phantom{x}⁠ (invisible with full dimensions), ⁠\hphantom{x}⁠ (width only), ⁠\vphantom{x}⁠ (height/depth only)

Colors

⁠\textcolor{color}{text}⁠, ⁠\color{color}{text}⁠, ⁠\colorbox{color}{text}⁠

Cancellation

⁠\cancel{x}⁠, ⁠\bcancel{x}⁠, ⁠\xcancel{x}⁠, ⁠\cancelto{v}{x}⁠

Boxing

⁠\boxed{expression}⁠

Substack

⁠\substack{a \\ b}⁠ for multi-line subscripts

Negation

⁠\not⁠ followed by a symbol (e.g., ⁠\not=⁠)

Extensible arrows

⁠\xrightarrow{above}⁠, ⁠\xleftarrow[below]{above}⁠, ⁠\xRightarrow{}⁠, ⁠\xLeftarrow{}⁠, ⁠\xleftrightarrow{}⁠, ⁠\xLeftrightarrow{}⁠, ⁠\xhookleftarrow{}⁠, ⁠\xhookrightarrow{}⁠, ⁠\xmapsto{}⁠, ⁠\xlongequal{}⁠

Spacing

⁠\!⁠ (negative thin), ⁠\,⁠ (thin), ⁠\:⁠ (medium), ⁠\;⁠ (thick), ⁠\ ⁠ (space), ⁠\quad⁠, ⁠\qquad⁠

Smash

⁠\smash{x}⁠ (zero height and depth), ⁠\smash[t]{x}⁠ (zero height), ⁠\smash[b]{x}⁠ (zero depth) for fine vertical spacing control

Modular arithmetic

⁠\pmod{n}⁠ for "(mod n)", ⁠\bmod⁠ as binary operator, ⁠\pod{n}⁠ for "(n)"

Rule

⁠\rule{width}{height}⁠ for custom-sized horizontal rules

Miscellaneous symbols

⁠\infty⁠, ⁠\partial⁠, ⁠\nabla⁠, ⁠\forall⁠, ⁠\exists⁠, ⁠\nexists⁠, ⁠\emptyset⁠, ⁠\varnothing⁠, ⁠\aleph⁠, ⁠\hbar⁠, ⁠\ell⁠, ⁠\wp⁠, ⁠\Re⁠, ⁠\Im⁠, ⁠\angle⁠, ⁠\triangle⁠, ⁠\prime⁠, ⁠\ldots⁠, ⁠\cdots⁠, ⁠\vdots⁠, ⁠\ddots⁠, ⁠\neg⁠, ⁠\lnot⁠, ⁠\bot⁠, ⁠\top⁠, ⁠\dagger⁠, ⁠\ddagger⁠, ⁠\diamond⁠, ⁠\square⁠, ⁠\checkmark⁠, ⁠\imath⁠, ⁠\jmath⁠, ⁠\complement⁠, ⁠\eth⁠, ⁠\hslash⁠, ⁠\mho⁠, ⁠\dotsb⁠, ⁠\dotsc⁠, ⁠\dotsi⁠, ⁠\dotsm⁠, ⁠\dotso⁠

Value

A list with four element: shape contains the position of each glyph, relative to the origin in the enclosing textbox. metrics contain metrics about the full math expression. lines contain line segments (fraction bars, overlines, cancel lines, etc.). boxes contain position and dimensions of boxes.

shape is a data.frame with the following columns:

glyph

Row number within the string

index

Glyph index in the font

metric_id

Index of the metrics row (same as string_id)

string_id

Index of the input string this glyph belongs to

x_offset

X position relative to the origin

y_offset

Y position relative to the baseline (positive is up)

font_path

Path to the font file

font_index

Index of the font face in the font file

font_size

Font size used for this glyph (may differ for scripts)

advance

Horizontal advance width of the glyph

color

Color for this glyph

metrics is a data.frame with the following columns:

width

Total width of the expression

height

Height above the baseline

depth

Depth below the baseline

lines is a data.frame with the following columns:

x1

X position of start point

y1

Y position of start point

x2

X position of end point

y2

Y position of end point

thickness

Line thickness

string_id

Index of the input string this line belongs to

color

Color for this line

boxes is a data.frame with the following columns:

x

X position of the left edge

y

Y position of the bottom edge

width

Width of the box

height

Height of the box

string_id

Index of the input string this box belongs to

color

Fill color for the box

Examples

# Simple superscript
shape_math("x^2")

# === LaTeX syntax ===

# Greek letters (LaTeX)
shape_math(r"(\alpha + \beta)")

# Fraction (LaTeX)
shape_math(r"(\frac{a}{b})")

# Display mode sum (inline = FALSE)
shape_math(r"(\sum_{i=1}^n i)", inline = FALSE)

# Quadratic formula (LaTeX)
shape_math(r"(x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a})")

# Matrix (LaTeX)
shape_math(r"(\begin{pmatrix} a & b \\\\ c & d \end{pmatrix})")

# Binomial coefficient (LaTeX)
shape_math(r"(\binom{n}{k})")

# === Typst syntax ===

# Greek letters (Typst)
shape_math("alpha + beta")

# Fraction (Typst)
shape_math("frac(a, b)")

# Square root (Typst)
shape_math("sqrt(x^2 + y^2)")

# Matrix (Typst - semicolon separates rows)
shape_math("mat(a, b; c, d)")

# Styled text (Typst)
shape_math("bold(x) + italic(y)")

# Delimiters (Typst)
shape_math("abs(x) + norm(v)")

# Binomial (Typst)
shape_math("binom(n, k)")

textshaping documentation built on Nov. 20, 2026, 5:08 p.m.