| Title: | Bindings to the 'HarfBuzz' and 'Fribidi' Libraries for Text Shaping |
| Version: | 1.1.0 |
| Description: | Provides access to the text shaping functionality in the 'HarfBuzz' library and the bidirectional algorithm in the 'Fribidi' library. 'textshaping' is a low-level utility package mainly for graphic devices that expands upon the font tool-set provided by the 'systemfonts' package. |
| License: | MIT + file LICENSE |
| URL: | https://github.com/r-lib/textshaping |
| BugReports: | https://github.com/r-lib/textshaping/issues |
| Depends: | R (≥ 3.2.0) |
| Imports: | lifecycle, stats, stringi, systemfonts (≥ 1.3.3), utils |
| Suggests: | covr, grDevices, grid, knitr, rmarkdown, testthat (≥ 3.3.0) |
| LinkingTo: | cpp11 (≥ 0.2.1), systemfonts (≥ 1.3.3) |
| VignetteBuilder: | knitr |
| Config/build/compilation-database: | true |
| Config/testthat/edition: | 3 |
| Config/usethis/last-upkeep: | 2025-04-23 |
| Encoding: | UTF-8 |
| SystemRequirements: | freetype2, harfbuzz, fribidi |
| Config/roxygen2/version: | 8.1.1 |
| NeedsCompilation: | yes |
| Packaged: | 2026-11-20 08:23:45 UTC; thomas |
| Author: | Thomas Lin Pedersen
|
| Maintainer: | Thomas Lin Pedersen <thomas.pedersen@posit.co> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-20 14:50:02 UTC |
textshaping: Bindings to the 'HarfBuzz' and 'Fribidi' Libraries for Text Shaping
Description
Provides access to the text shaping functionality in the 'HarfBuzz' library and the bidirectional algorithm in the 'Fribidi' library. 'textshaping' is a low-level utility package mainly for graphic devices that expands upon the font tool-set provided by the 'systemfonts' package.
Author(s)
Maintainer: Thomas Lin Pedersen thomas.pedersen@posit.co (ORCID)
Authors:
Thomas Lin Pedersen thomas.pedersen@posit.co (ORCID)
Other contributors:
Posit Software, PBC (ROR) [copyright holder, funder]
See Also
Useful links:
Get available OpenType features in a font
Description
This is a simply functions that returns the available OpenType feature tags
for one or more fonts. See font_feature() for
more information on how to use the different feature with a font.
Usage
get_font_features(
family = "",
italic = FALSE,
bold = FALSE,
path = NULL,
index = 0
)
Arguments
family |
The name of the font families to match |
italic |
logical indicating the font slant |
bold |
|
path, index |
path and index of a font file to circumvent lookup based on family and style |
Value
A list with an element for each of the input fonts containing the supported feature tags for that font.
Examples
# Select a random font on the system
sys_fonts <- systemfonts::system_fonts()
random_font <- sys_fonts$family[sample(nrow(sys_fonts), 1)]
# Get the features
get_font_features(random_font)
Get gibberish text in various scripts
Description
Textshaping exists partly to allow all the various scripts that exists in the world to be used in R graphics. This function returns gibberish filler text (lorem ipsum text) in various scripts for testing purpose. Some of these are transliterations of the original lorem ipsum text while others are based an a distribution model.
Usage
lorem_text(
script = c("latin", "chinese", "arabic", "devanagari", "cyrillic", "kana", "hangul",
"greek", "hebrew", "armenian", "georgian"),
n = 1
)
lorem_bidi(
ltr = c("latin", "chinese", "devanagari", "cyrillic", "kana", "hangul", "greek",
"armenian", "georgian"),
rtl = c("arabic", "hebrew"),
ltr_prop = 0.9,
n = 1
)
Arguments
script |
A string giving the script to fetch gibberish for |
n |
The number of paragraphs to fetch. Each paragraph will be its own element in the returned character vector. |
ltr, rtl |
scripts to use for left-to-right and right-to-left text |
ltr_prop |
The approximate proportion of left-to-right text in the final string |
Value
a character vector of length n
References
https://generator.lorem-ipsum.info
Examples
# Defaults to standard lorem ipsum
lorem_text()
# Get two paragraphs of hangul (Korean)
lorem_text("hangul", 2)
# Get gibberish bi-directional text
lorem_bidi()
Create a grid grob for a math expression
Description
This function creates a grid grob that renders a math expression.
The grob can be used with standard grid functions like grid::grid.draw(),
combined with other grobs using grid::grobTree(), or used in ggplot2
annotations. Like the standard grid grobs, math_grob() creates a grob
object to pass around while grid.math() both creates the grob and render it
in one pass.
Usage
math_grob(
math,
x = 0.5,
y = 0.5,
hjust = "left",
vjust = "baseline",
default.units = "npc",
name = NULL,
gp = NULL,
vp = NULL,
family = "math",
size = 12,
res = 72,
inline = TRUE,
path = NULL,
index = 0,
color = "black"
)
grid.math(
math,
x = 0.5,
y = 0.5,
hjust = "left",
vjust = "baseline",
default.units = "npc",
name = NULL,
gp = NULL,
vp = NULL,
family = "math",
size = 12,
res = 72,
inline = TRUE,
path = NULL,
index = 0,
color = "black",
draw = TRUE
)
Arguments
math |
A single math expression string. Use raw strings for
cleaner syntax, e.g., |
x, y |
The position of the grob. Can be a unit object or a numeric value (interpreted as npc units). |
hjust |
Horizontal justification. Either a numeric value (0 = left,
0.5 = center, 1 = right) or a character string ( |
vjust |
Vertical justification. Either a numeric value (0 = bottom,
0.5 = center, 1 = top) or a character string ( |
default.units |
A string indicating the default units to use if
|
name |
A character identifier for the grob. |
gp |
A |
vp |
A |
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 |
path, index |
path an index of a font file to circumvent lookup based on family and style |
color |
Base color for the equation (default "black"). Individual
elements can override this using |
draw |
Should the created grob be rendered |
Value
A grob object of class "math_grob".
Examples
# Create a math grob (baseline at y=0.5)
g <- math_grob(r"(\frac{a}{b})", x = 0.5, y = 0.5)
# Draw it (requires a device that supports glyph rendering)
try(grid::grid.draw(g))
# Center the expression in the viewport
g <- math_grob(r"(E = mc^2)", x = 0.5, y = 0.5,
hjust = "center", vjust = "center")
try(grid::grid.draw(g))
# Combine with other grobs
tree <- grid::grobTree(
grid::rectGrob(gp = grid::gpar(fill = "lightblue")),
math_grob(r"(E = mc^2)", x = 0.5, y = 0.5,
hjust = "center", vjust = "center")
)
try(grid::grid.draw(tree))
Preview shaped math expression
Description
This function allows you to preview the layout that shape_math()
calculates. It renders the positioned glyphs and lines (fraction bars,
radical overlines, cancel lines, etc.) using grid graphics, and shows the
position of the baseline relative to the equation. This is primarily
a debugging and visualization tool.
Usage
plot_math(shaped, id = 1)
Arguments
shaped |
The output of a call to |
id |
The index of the expression to show if |
Value
This function is called for its side effects
Examples
## Not run:
shaped <- shape_math(r"(\frac{a}{b})", family = "STIX Two Math")
plot_math(shaped)
shaped <- shape_math("x^2 + y^2 = z^2", family = "STIX Two Math")
plot_math(shaped)
## End(Not run)
Preview shaped text and the metrics for the text box
Description
This function allows you to preview the layout that shape_text()
calculates. It is purely meant as a sanity check to make sure that the values
calculated are sensible and shouldn't be used as a plotting function for
rendering text on its own.
Usage
plot_shape(shape, id = 1)
Arguments
shape |
The output of a call to |
id |
The index of the text run to show in case |
Value
This function is called for its side effects
Examples
arab_text <- lorem_text("arabic", 2)
shape <- shape_text(
arab_text,
max_width = 5,
indent = 0.2
)
try(
plot_shape(shape)
)
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 |
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 |
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- uselimits(sum)for above/below placement orscripts(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,wideorh(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, ...)andmat(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). Optionalcramped: trueparameter 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\limitsto force limits above/below or\nolimitsto 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,\Biggand 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,\scriptscriptstyleto 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
\notfollowed 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)",\bmodas 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)")
Calculate glyph positions for strings
Description
Performs advanced text shaping of strings including font fallbacks, bidirectional script support, word wrapping and various character and paragraph level formatting settings.
Usage
shape_text(
strings,
id = NULL,
family = "",
italic = FALSE,
weight = "normal",
width = "undefined",
features = font_feature(),
variation = font_variation(),
size = 12,
res = 72,
lineheight = 1,
align = "auto",
hjust = 0,
vjust = 0,
max_width = NA,
tracking = 0,
indent = 0,
hanging = 0,
space_before = 0,
space_after = 0,
direction = "auto",
mixed = "rotate",
kinsoku = "strict",
kinsoku_style = "hang",
path = NULL,
index = 0,
bold = deprecated()
)
Arguments
strings |
A character vector of strings to shape |
id |
A vector grouping the strings together. If strings share an id the shaping will continue between strings |
family |
The name of the font families to match |
italic |
logical indicating the font slant |
weight |
The weight to query for, either in numbers ( |
width |
The width to query for either in numbers ( |
features |
A |
variation |
A |
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. |
lineheight |
A multiplier for the lineheight |
align |
Within text box alignment, either |
hjust, vjust |
The justification of the textbox surrounding the text |
max_width |
The requested with of the string in inches. Setting this to
something other than |
tracking |
Tracking of the glyphs (space adjustment) measured in 1/1000 em. |
indent |
The indent of the first line in a paragraph measured in inches. |
hanging |
The indent of the remaining lines in a paragraph measured in inches. |
space_before, space_after |
The spacing above and below a paragraph, measured in points |
direction |
The overall directional flow of the text. The default
( |
mixed |
How to treat runs of horizontal-only scripts (e.g. Latin) in
vertical text: |
kinsoku |
How to handle CJK line-break prohibitions (kinsoku shori)
when wrapping is forced past the last valid break opportunity: |
kinsoku_style |
How line-break prohibition violations are resolved
when wrapping is forced: |
path, index |
path an index of a font file to circumvent lookup based on family and style |
bold |
logical indicating whether the font weight |
Value
A list with two element: shape contains the position of each glyph,
relative to the origin in the enclosing textbox. metrics contain metrics
about the full strings.
shape is a data.frame with the following columns:
- glyph
The placement of the the first character contributing to the glyph within the string
- index
The index of the glyph in the font file
- metric_id
The index of the string the glyph is part of (referencing a row in the
metricsdata.frame)- string_id
The index of the string the glyph came from (referencing an element in the
stringsinput)- x_offset
The x offset in pixels from the origin of the textbox
- y_offset
The y offset in pixels from the origin of the textbox
- font_path
The path to the font file used during shaping of the glyph
- font_index
The index of the font used to shape the glyph in the font file
- font_size
The size of the font used during shaping
- advance
The advancement amount to the next glyph
- ascender
The ascend of the font used for the glyph. This does not measure the actual glyph
- descender
The descend of the font used for the glyph. This does not measure the actual glyph
- rotation
The rotation in degrees the renderer should apply to the glyph. Non-zero for rotated runs in vertical text: horizontal-only scripts with
mixed = "rotate"(the default), UAX#50 Tr characters when the font lacksvert/vrt2, and everything withmixed = "sideways";0otherwise- spacer
Logical.
TRUEfor null glyphs created fromNAstrings, which reserve advance (given bytracking) without shaping any characters.FALSEfor all real glyphs- cell_x0, cell_y0, cell_x1, cell_y1
The bounds of the glyph's cell, i.e. its advance slot along the main axis and its em box along the cross axis, in pixels relative to the origin of the textbox (see below for the precise anchoring convention). Cells tile seamlessly: within a run of text the end of one cell coincides with the start of the next, so they can be used directly for backgrounds and other per-cell decorations
Cell anchoring convention
The cell is the glyph's advance slot along the main axis and its em box
along the cross axis. Deriving it from x_offset/y_offset requires
knowing the anchoring convention, which differs by direction and rotation,
so prefer the cell_* columns. For reference: for horizontal text the
cell spans [x_offset, x_offset + advance] along the line and
[y_offset + descender, y_offset + ascender] across it. For vertical
text, upright glyphs (and spacers) occupy the advance slot along the
column and [x_offset, x_offset + em] across it — the slot is not
recoverable from y_offset, which is the font's VORG origin and may sit
anywhere inside the slot. Rotated runs sit on their baseline: -90 runs
(in "ttb") span [y_offset - advance, y_offset] along the column and
[x_offset + descender, x_offset + ascender] across it, while +90 runs
(only in "ttb-ltr") span [y_offset, y_offset + advance] (exact only
when tracking is 0 for the run) and [x_offset - ascender, x_offset - descender].
Note that the cross-axis em width is generally not ascender - descender;
use cell_x0/cell_x1 rather than deriving it from the font extents.
Block anchoring
The whole shaped block is anchored the same way in every direction: the
origin sits at the hjust/vjust anchor point of the content box, with
hjust justifying along the main axis and vjust across it. Concretely,
left_border is -vjust * width for vertical text (-hjust * width for
horizontal) and top_border marks the block-start edge by hjust. With
the default hjust = vjust = 0 the content box thus always starts at the
origin — its left edge at x = 0 and its block-start edge at y = 0 —
whether the text is horizontal, "ttb", or "ttb-ltr"; the direction only
affects the order in which lines or columns fill the box. Ink may extend
past the box edges; the bearings report how far.
Null glyphs (spacer == TRUE) have no glyph to report so index is NA,
but they carry the font their span resolved to (font_path, font_index,
font_size, ascender, and descender) so consumers can compute
font-relative metrics such as underline position for the reserved space. The
resolved font may legitimately differ from that of neighbouring glyphs when
the NA span specifies a different family.
metrics is a data.frame with the following columns:
- string
The text the string consist of
- width
The width of the string
- height
The height of the string
- left_bearing
The distance from the left edge of the textbox and the leftmost glyph
- right_bearing
The distance from the right edge of the textbox and the rightmost glyph
- top_bearing
The distance from the top edge of the textbox and the topmost glyph
- bottom_bearing
The distance from the bottom edge of the textbox and the bottommost glyph
- left_border
The position of the leftmost edge of the textbox related to the origin
- top_border
The position of the topmost edge of the textbox related to the origin
- pen_x
The horizontal position of the next glyph after the string
- pen_y
The vertical position of the next glyph after the string
- ltr
The global direction of the string. If
TRUEthen it is left-to-right, otherwise it is right-to-left. Vertical text is not right-to-left soltris alwaysTRUEfor it; consultdirectionfor the resolved direction- direction
The resolved global direction of the string (
"ltr","rtl","ttb", or"ttb-ltr")
For vertical text ("ttb"/"ttb-ltr") glyphs flow along the y axis and lines
stack as columns (right-to-left for "ttb", left-to-right for "ttb-ltr").
Upright runs automatically use the font's vert/vrt2 and vkna
substitutions when available unless these features are set explicitly.
max_width constrains the height of a column, and hjust/vjust justify
along the main axis and across columns respectively. The advance column
gives the advance along the main axis.
Examples
string <- "This is a long string\nLook; It spans multiple lines\nand all"
# Shape with default settings
shape_text(string)
# Mix styles within the same string
string <- c(
"This string will have\na ",
"very large",
" text style\nin the middle"
)
shape_text(string, id = c(1, 1, 1), size = c(12, 24, 12))
# Vertical text. CJK scripts stay horizontal with "auto", so request it
# explicitly; runs of horizontal-only scripts are rotated by default
# (Japanese strings written with Unicode escapes so they render in the
# PDF manual)
shape_text("\\u65e5\\u672c\\u8a9eABC\\u3067\\u3059", direction = "ttb")
# ...or set them upright if the font provides vert/vrt2 substitutions
shape_text("\\u65e5\\u672c\\u8a9eABC\\u3067\\u3059", direction = "ttb", mixed = "upright")
# Digit runs of up to 4 digits can be set horizontally on a single line
# (tate-chu-yoko) with mixed = "tate", using the font's narrow digit
# forms (hwid/twid/qwid) when available
shape_text("2024\\u5e7412\\u670825\\u65e5\\u767a\\u58f2", direction = "ttb", mixed = "tate")
Calculate the width of a string, ignoring new-lines
Description
This is a very simple alternative to systemfonts::shape_string() that
simply calculates the width of strings without taking any newline into
account. As such it is suitable to calculate the width of words or lines that
have already been split by \n. Input is recycled to the length of
strings.
Usage
text_width(
strings,
family = "",
italic = FALSE,
weight = "normal",
width = "undefined",
features = font_feature(),
variation = font_variation(),
size = 12,
res = 72,
include_bearing = TRUE,
direction = "auto",
mixed = c("rotate", "upright"),
path = NULL,
index = 0,
bold = deprecated()
)
Arguments
strings |
A character vector of strings |
family |
The name of the font families to match |
italic |
logical indicating the font slant |
weight |
The weight to query for, either in numbers ( |
width |
The width to query for either in numbers ( |
features |
A |
variation |
A |
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. |
include_bearing |
Logical, should left and right bearing be included in the string width? |
direction |
The overall directional flow of the text. The default
( |
mixed |
How to treat runs of horizontal-only scripts (e.g. Latin) in
vertical text: |
path, index |
path an index of a font file to circumvent lookup based on family and style |
bold |
logical indicating whether the font weight |
Value
A numeric vector giving the width of the strings in pixels, measured
along the main text axis (i.e. the height of the string for vertical text).
Use the provided res value to convert it into absolute values.
Examples
strings <- c('A short string', 'A very very looong string')
text_width(strings)