| shape_math | R Documentation |
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.
shape_math(
math,
family = "math",
size = 12,
res = 72,
inline = TRUE,
color = "black",
path = NULL,
index = 0
)
math |
A character vector of math expressions. Supports both LaTeX and
Typst syntax (auto-detected). For LaTeX, use raw strings like |
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 |
color |
Base color for the equation (default "black"). Individual
elements can override this using |
path, index |
path an index of a font file to circumvent lookup based on family and style |
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.
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.
Typst math uses function-call syntax instead of backslash commands:
Greek letters as identifiers: alpha, beta, gamma, etc.
Operators: +, -, *, /, =
123, 3.14
"text in quotes"
bold(x), italic(x), upright(x), sans(x), mono(x),
cal(X), frak(X), bb(R)
x^2, x_i, x_i^2
frac(a, b)
binom(n, k)
overbrace(x, "label"), underbrace(x, "label"),
overline(x), underline(x)
sqrt(x), root(n, x)
lr((x)), abs(x), norm(x), floor(x), ceil(x)
sum, integral, product - use limits(sum) for
above/below placement or scripts(sum) for side scripts
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
widehat(abc), widetilde(abc), overrightarrow(AB),
overleftarrow(AB)
thin, med, thick, quad, wide or h(1em)
sin, cos, tan, log, exp, lim
op("name")
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(a &"if" b, c &"if" d)
cancel(x)
display(x), inline(x), script(x), sscript(x).
Optional cramped: true parameter reduces superscript height:
display(x^2, cramped: true)
hide(x)
attach(base, t: top, b: bot)
stretch(=, size: 3em) stretches a glyph to a specified size
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
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:
\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
+, -, =, \pm, \mp, \times, \div,
\cdot, \ast, \star, \circ, \bullet, \cap, \cup, \vee,
\wedge, \setminus, \oplus, \ominus, \otimes, \oslash, \odot,
\ltimes, \rtimes, \boxplus, \boxminus, \boxtimes
\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
\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
x^2, x_i, x_i^2
\frac{num}{denom}, \dfrac{}{} (display style),
\tfrac{}{} (text style), \cfrac{}{} (continued fraction)
\sqrt{x}, \sqrt[n]{x}
\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
\left(, \right), \left[, \right], \left\{,
\right\}, \langle, \rangle, \lfloor, \rfloor, \lceil,
\rceil, \vert, \Vert, \ulcorner, \urcorner, \llcorner,
\lrcorner
\big, \Big, \bigg, \Bigg and variants
\bigl, \bigr, \bigm, \Bigl, \Bigr, \Bigm, etc. for manual
control of delimiter size
\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}
\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}
\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{...}
\mathbf{x}, \mathit{x}, \mathrm{x}, \mathsf{x},
\mathtt{x}, \mathcal{X}, \mathscr{X}, \mathfrak{X}, \mathbb{R},
\boldsymbol{x}, \bm{x}
\displaystyle, \textstyle, \scriptstyle,
\scriptscriptstyle to control operator size and limit placement
\begin{matrix}, \begin{pmatrix}, \begin{bmatrix},
\begin{vmatrix}, \begin{Vmatrix}, \begin{Bmatrix}, \begin{smallmatrix}
(with & for column separators and \\ for row separators)
\begin{aligned}, \begin{gathered},
\begin{split}, \begin{array}{lcr} for multi-line equations with
alignment points
\begin{cases}, \begin{rcases}, \begin{dcases},
\begin{drcases}
\binom{n}{k}, \tbinom{n}{k}, \dbinom{n}{k},
\overset{a}{b}, \underset{a}{b}, \stackrel{a}{b}, \atop
\operatorname{name}, \operatorname*{name} (with limits)
\phantom{x} (invisible with full dimensions),
\hphantom{x} (width only), \vphantom{x} (height/depth only)
\textcolor{color}{text}, \color{color}{text},
\colorbox{color}{text}
\cancel{x}, \bcancel{x}, \xcancel{x}, \cancelto{v}{x}
\boxed{expression}
\substack{a \\ b} for multi-line subscripts
\not followed by a symbol (e.g., \not=)
\xrightarrow{above}, \xleftarrow[below]{above},
\xRightarrow{}, \xLeftarrow{}, \xleftrightarrow{}, \xLeftrightarrow{},
\xhookleftarrow{}, \xhookrightarrow{}, \xmapsto{}, \xlongequal{}
\! (negative thin), \, (thin), \: (medium), \; (thick),
\ (space), \quad, \qquad
\smash{x} (zero height and depth), \smash[t]{x} (zero height),
\smash[b]{x} (zero depth) for fine vertical spacing control
\pmod{n} for "(mod n)", \bmod as binary operator,
\pod{n} for "(n)"
\rule{width}{height} for custom-sized horizontal rules
\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
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:
Row number within the string
Glyph index in the font
Index of the metrics row (same as string_id)
Index of the input string this glyph belongs to
X position relative to the origin
Y position relative to the baseline (positive is up)
Path to the font file
Index of the font face in the font file
Font size used for this glyph (may differ for scripts)
Horizontal advance width of the glyph
Color for this glyph
metrics is a data.frame with the following columns:
Total width of the expression
Height above the baseline
Depth below the baseline
lines is a data.frame with the following columns:
X position of start point
Y position of start point
X position of end point
Y position of end point
Line thickness
Index of the input string this line belongs to
Color for this line
boxes is a data.frame with the following columns:
X position of the left edge
Y position of the bottom edge
Width of the box
Height of the box
Index of the input string this box belongs to
Fill color for the box
# 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)")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.