shape_text: Calculate glyph positions for strings

View source: R/shape_text.R

shape_textR Documentation

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 (0, 100, 200, 300, 400, 500, 600, 700, 800, or 900) or strings ("undefined", "thin", "ultralight", "light", "normal", "medium", "semibold", "bold", "ultrabold", or "heavy"). NA will be interpreted as "undefined"/0

width

The width to query for either in numbers (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9) or strings ("undefined", "ultracondensed", "extracondensed", "condensed", "semicondensed", "normal", "semiexpanded", "expanded", "extraexpanded", or "ultraexpanded"). NA will be interpreted as "undefined"/0

features

A systemfonts::font_feature() object or a list of them, giving the OpenType font features to set

variation

A systemfonts::font_variation() object or a list of them, giving the coordinates on the variable font axes to shape with. Settings in variation take precedence over the corresponding italic, weight, and width arguments during shaping.

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 'auto', 'left', 'center', 'right', 'justified', 'justified-left', 'justified-right', 'justified-center', or 'distributed'. 'auto' and 'justified' will chose the left or right version depending on the direction of the text.

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 NA will turn on word wrapping.

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 ("auto") will guess the direction based on the content of the string, resolving to top-to-bottom if the string contains scripts that can only be typeset vertically (e.g. Mongolian) and to left-to-right or right-to-left otherwise. Use "ltr" (left-to-right), "rtl" (right-to-left), "ttb" (top-to-bottom, lines stacking right-to-left as in Japanese), and "ttb-ltr" (top-to-bottom, lines stacking left-to-right as in Mongolian) to turn off detection and set it manually. Scripts that can be typeset both horizontally and vertically (e.g. Japanese) are always set horizontally with "auto".

mixed

How to treat runs of horizontal-only scripts (e.g. Latin) in vertical text: "rotate" shapes them horizontally and marks them for a 90 degree rotation during rendering (see the rotation column in the output); "upright" sets them upright in the vertical line using the font's vert/ vrt2 substitutions, falling back to "rotate" behaviour if the font doesn't provide these; "tate" additionally sets ASCII digit runs of up to 4 digits horizontally on a single line (tate-chu-yoko), as is common for e.g. years and day numbers in Japanese typesetting. Tate runs use the font's hwid/twid/qwid narrow digit forms when available (unless the features are set explicitly), falling back to scaling down to fit the em box. "combine" generalises tate-chu-yoko to any horizontal-only run of up to 4 characters — Latin abbreviations, era names, etc. — equivalent to CSS text-combine-upright: all (narrow digit features are only used for all-digit runs). "tate2"/"tate3" and "combine2"/"combine3" are like "tate" and "combine" but cap the combined run at 2 or 3 digits/characters instead of 4 (runs longer than the cap stay rotated). Finally, "sideways" shapes the entire string horizontally — CJK scripts included — and marks it for rotation, equivalent to CSS text-orientation: sideways. Ignored for horizontal text. Can be given per string.

kinsoku

How to handle CJK line-break prohibitions (kinsoku shori) when wrapping is forced past the last valid break opportunity: "strict" (the default) prohibits lines from starting with closing brackets, sentence punctuation, small kana, the prolonged sound mark, and iteration marks, and from ending with opening brackets; "loose" (like CSS line-break: loose) additionally permits lines to start with small kana, the prolonged sound mark, iteration marks, and centred punctuation (・:;); "none" disables kinsoku processing entirely (the JLREQ spacing collapses of fullwidth punctuation blanks are unaffected). Can be given per string.

kinsoku_style

How line-break prohibition violations are resolved when wrapping is forced: "hang" (ぶら下げ, the default) lets offending punctuation hang past the line end; "push-out" (追い出し) moves it to the next line and expands the spacing of the vacated line; "push-in" (追い込み) pulls it onto the current line by compressing its spacing (punctuation blanks first, then inter-character gaps), falling back to hanging when the line cannot absorb the overflow. Can be given per string.

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 metrics data.frame)

string_id

The index of the string the glyph came from (referencing an element in the strings input)

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 lacks vert/vrt2, and everything with mixed = "sideways"; 0 otherwise

spacer

Logical. TRUE for null glyphs created from NA strings, which reserve advance (given by tracking) without shaping any characters. FALSE for 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 TRUE then it is left-to-right, otherwise it is right-to-left. Vertical text is not right-to-left so ltr is always TRUE for it; consult direction for 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")


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