| Title: | Native 'LaTeX' Math Rendering for Grid Graphics |
| Version: | 0.2.0 |
| Description: | Renders 'LaTeX' math equations as native R grid graphics objects (grobs) using the 'MicroTeX' 'C++' library as the layout engine. Produces resolution-independent vector output that works on any R graphics device, with no external 'LaTeX' installation required. Markdown labels and block documents that mix prose formatting with math are also rendered, for use with both 'grid' and 'ggplot2'. |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| SystemRequirements: | C++17, FreeType (>= 2.9), pkg-config, FriBidi (optional) |
| Depends: | R (≥ 4.2.0) |
| LinkingTo: | Rcpp, systemfonts |
| Imports: | commonmark, grDevices, grid, Rcpp, systemfonts (≥ 1.2.0), tools, utils, xml2 |
| Suggests: | ggplot2 (≥ 4.0.0), grImport2, jpeg, knitr, png, ragg, rmarkdown, rsvg, S7, svglite, testthat (≥ 3.0.0), textshaping, vdiffr |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| URL: | https://github.com/adayim/gridmicrotex, https://adayim.github.io/gridmicrotex/ |
| BugReports: | https://github.com/adayim/gridmicrotex/issues |
| RoxygenNote: | 7.3.3 |
| NeedsCompilation: | yes |
| Packaged: | 2026-10-04 18:35:30 UTC; alim |
| Author: | Alim Dayim |
| Maintainer: | Alim Dayim <ad938@cam.ac.uk> |
| Repository: | CRAN |
| Date/Publication: | 2026-10-04 23:00:28 UTC |
gridmicrotex: Native 'LaTeX' Math Rendering for Grid Graphics
Description
Renders 'LaTeX' math equations as native R grid graphics objects (grobs) using the 'MicroTeX' 'C++' library as the layout engine. Produces resolution-independent vector output that works on any R graphics device, with no external 'LaTeX' installation required. Markdown labels and block documents that mix prose formatting with math are also rendered, for use with both 'grid' and 'ggplot2'.
Author(s)
Maintainer: Alim Dayim ad938@cam.ac.uk (ORCID)
Other contributors:
Nano Michael (Author of included 'MicroTeX' library) [copyright holder]
Bundled math font authors (See inst/COPYRIGHTS for the full list of authors of the bundled math fonts.) [copyright holder]
See Also
Useful links:
Report bugs at https://github.com/adayim/gridmicrotex/issues
List the fonts that have been loaded
Description
One row per font that can be named: the bundled math fonts, and every font
given to load_font() or to a font option of latex_options(). The
math fonts, which math_font takes, are the rows with math TRUE.
Usage
available_fonts(system = FALSE)
Arguments
system |
If |
Value
A data frame with one row per font: name; math (it has a math
table; NA for an installed family that is not loaded); mono
(monospaced); bold and italic (a face of its own is registered, so
\textbf and \textit draw its real design); weight of the regular
face; file of the regular face; and source, one of "bundled",
"file" and "system".
Font pairing
For a consistent look, pair a math font with a matching fontfamily in
gp:
| Math font | Style | Suggested text font |
Lete Sans Math ("lete", default) | Sans-serif | "sans" |
STIX Two Math ("stix") | Serif | "serif"
|
See Also
Examples
available_fonts()
Syntax highlighting languages available
Description
Languages that can follow an opening code fence in
markdown_box_grob(), including those added with
register_highlighter(). Aliases such as py, sh, c++, yml,
jl and tex also work. Other languages are shown as plain code.
Usage
available_highlighters()
Value
A sorted character vector.
See Also
Examples
available_highlighters()
Define a LaTeX shorthand for every label
Description
define_macro() adds a macro without arguments, such as \RR for
\mathbb{R}, that every later label can use. list_macros() shows
them and clear_macros() removes them.
Usage
define_macro(name, definition)
clear_macros(name = NULL)
list_macros()
Arguments
name |
Macro name, without the backslash. For |
definition |
The LaTeX the macro stands for. |
Details
A label can also define its own macros with \newcommand, \def and
the like, including macros with arguments, but those last for that
label only.
Value
list_macros() returns a named character vector of macros and
their definitions. The others return NULL, invisibly.
See Also
Examples
define_macro("RR", "\\mathbb{R}")
define_macro("eps", "\\varepsilon")
grid::grid.newpage()
grid.latex("\\forall \\eps > 0, \\eps \\in \\RR")
clear_macros()
A ggplot2 theme element for LaTeX text
Description
A theme element that renders text, such as an axis or plot title, as
LaTeX. The $ signs are optional. It takes the same settings as
ggplot2::element_text() and inherits from the theme like it.
Usage
element_latex(
math_font = "",
fontsize = NULL,
lineheight = 1.2,
max_width = 0,
input_mode = c("mixed", "math", "document"),
render_mode = c("typeface", "path"),
...
)
Arguments
math_font |
Math font: |
fontsize |
Font size in points. |
lineheight |
Line spacing (default 1.2). |
max_width |
Width in big points (1/72 inch) at which lines wrap.
|
input_mode |
How
|
render_mode |
|
... |
Passed to |
Value
A theme element of class element_latex, a kind of
element_text.
Examples
if (requireNamespace("ggplot2", quietly = TRUE)) {
library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
labs(x = "$\\beta_1 \\cdot x + \\beta_0$") +
theme(axis.title.x = element_latex())
}
A ggplot2 theme element for markdown text
Description
A theme element that renders text, such as an axis or plot title, as
markdown with $math$. It takes the same settings as
ggplot2::element_text() and inherits from the theme like it.
Usage
element_markdown(
math_font = "",
fontsize = NULL,
lineheight = 1.2,
max_width = 0,
render_mode = c("typeface", "path"),
justify = FALSE,
style = NA,
width = NA,
...
)
Arguments
math_font |
Math font, such as |
fontsize |
Font size in points. |
lineheight |
Line spacing (default 1.2). |
max_width |
Width in big points at which lines wrap. |
render_mode |
|
justify |
If |
style |
A |
width |
Width at which the label wraps, as a |
... |
Passed to |
Value
A theme element of class element_markdown, a kind of
element_text.
Block labels
A label with a heading, a list, a table, a rule or several paragraphs
is laid out as a small document, as in markdown_box_grob():
labs(title = "## Findings\n\n- slope $\\beta_1$\n- *p* < 0.001")
Its box is styled by the body rule, as in
style = "body { background: grey95; padding: 8px }".
Text wraps only if
widthis given.Axis tick labels and rotated labels are never laid out as blocks; a rotated one warns.
-
math_font,render_modeandjustifydo not apply to blocks; set them withlatex_options().
ggtext also has an element_markdown(). If both packages are
attached, write gridmicrotex::element_markdown().
See Also
Examples
if (requireNamespace("ggplot2", quietly = TRUE)) {
library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
labs(x = "**weight** in $10^3$ lbs") +
theme(axis.title.x = gridmicrotex::element_markdown())
}
Superseded font functions
Description
load_math_font(), available_math_fonts() and check_math_fonts() came
before load_font() and available_fonts(), which replace them. They keep
working as they did: load_font() also loads a math font, and
available_fonts() lists the math fonts (math is TRUE).
Usage
available_math_fonts()
load_math_font(otf_path)
check_math_fonts()
Arguments
otf_path |
Path to an OTF or TTF math font. |
Value
load_math_font() returns NULL, invisibly. available_math_fonts()
returns a character vector of math font names. check_math_fonts()
prints the math fonts that are loaded and whether the bundled font files
are present, and returns their names, invisibly.
See Also
load_font(), available_fonts()
Examples
available_math_fonts()
A ggplot2 geom for LaTeX math labels
Description
Like ggplot2::geom_text(), with labels written in LaTeX. The $
signs are optional. annotate("latex", ...) adds a single label.
Usage
geom_latex(
mapping = NULL,
data = NULL,
stat = "identity",
position = "identity",
...,
fontsize = 11,
math_font = "",
lineheight = 1.2,
max_width = 0,
input_mode = c("mixed", "math", "document"),
render_mode = c("typeface", "path"),
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE
)
Arguments
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Passed to |
fontsize |
Font size in points, unless |
math_font |
Math font, such as |
lineheight |
Line spacing (default 1.2). |
max_width |
Width in big points at which lines wrap. |
input_mode |
How
|
render_mode |
|
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
Value
A ggplot2 layer.
Aesthetics
geom_latex() understands the following aesthetics (required aesthetics
are in bold):
-
x -
y -
label: LaTeX string -
size: font size in points (default: 11) -
colour: text colour (default:"black") -
angle: rotation angle in degrees (default: 0) -
hjust: horizontal justification, 0-1 (default: 0.5) -
vjust: vertical justification, 0-1 (default: 0.5) -
alpha: transparency (default: 1)
Examples
if (requireNamespace("ggplot2", quietly = TRUE)) {
library(ggplot2)
df <- data.frame(
x = 1:3, y = 1:3,
eq = c("$x^2$", "$\\frac{a}{b}$", "$\\sum_{i=1}^n x_i$")
)
ggplot(df, aes(x, y, label = eq)) + geom_latex()
# Use annotate() for single annotations (no legend, no data frame needed)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
annotate("latex", x = 4, y = 30,
label = r"($\hat{y} = \beta_0 + \beta_1 x$)")
}
A ggplot2 geom for markdown labels
Description
Like ggplot2::geom_text(), with labels written in markdown:
**bold**, *italic*, `code`, ~~strike~~ and $math$, as in
markdown_grob(). annotate("markdown", ...) adds a single label.
Usage
geom_markdown(
mapping = NULL,
data = NULL,
stat = "identity",
position = "identity",
...,
fontsize = 11,
math_font = "",
lineheight = 1.2,
max_width = 0,
render_mode = c("typeface", "path"),
justify = FALSE,
style = NULL,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE
)
Arguments
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Passed to |
fontsize |
Font size in points, unless |
math_font |
Math font, such as |
lineheight |
Line spacing (default 1.2). |
max_width |
Width in big points at which lines wrap. |
render_mode |
|
justify |
If |
style |
A |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
Value
A ggplot2 layer.
Aesthetics
geom_markdown() understands the following aesthetics (required
aesthetics are in bold):
-
x -
y -
label: markdown string -
size: font size in points (default: 11) -
colour: text colour (default:"black") -
angle: rotation angle in degrees (default: 0) -
hjust: horizontal justification, 0-1 (default: 0.5) -
vjust: vertical justification, 0-1 (default: 0.5) -
alpha: transparency (default: 1)
See Also
Examples
if (requireNamespace("ggplot2", quietly = TRUE)) {
library(ggplot2)
df <- data.frame(
x = 1:3, y = 1:3,
lab = c("**bold**", "*slope* $\\beta_1$", "`code` and $x^2$")
)
ggplot(df, aes(x, y, label = lab)) + geom_markdown()
}
Position of a named point in a LaTeX grob
Description
Returns the position of a \mark{name} written in the LaTeX, as grid
units that can be passed straight to other grid functions, for example
to point an arrow at part of a formula.
Usage
grobMark(grob, name)
Arguments
grob |
A grob from |
name |
The name given to |
Value
A list with x and y, each a grid::unit(). Rotation
(rot) is not taken into account.
See Also
Examples
g <- latex_grob(r"($a\mark{eq}^2 = b + c^2$)",
x = grid::unit(0.5, "npc"),
y = grid::unit(0.5, "npc"))
grid::grid.newpage(); grid::grid.draw(g)
mk <- grobMark(g, "eq")
grid::grid.points(mk$x, mk$y, pch = 19,
gp = grid::gpar(col = "red"))
Layout cache
Description
Recently drawn expressions are cached, so drawing the same one again is
fast. latex_cache_limit() sets how many are kept (512 by default),
latex_cache_clear() empties the cache, and latex_cache_info()
reports on it.
Usage
latex_cache_limit(n = 512L)
latex_cache_clear()
latex_cache_info()
Arguments
n |
Number of entries to keep. |
Value
latex_cache_limit() returns the previous limit and
latex_cache_clear() returns NULL, both invisibly.
latex_cache_info() returns a list with size, max_size, hits
and misses.
See Also
Examples
latex_cache_limit(256)
grid.latex("$e^{i\\pi} + 1 = 0$")
latex_cache_info()
latex_cache_clear()
Size of a LaTeX expression
Description
Size of a LaTeX expression
Usage
latex_dims(
tex,
math_font = "",
max_width = 0,
tex_style = "",
input_mode = c("mixed", "math", "document"),
render_mode = c("typeface", "path"),
justify = FALSE,
line_break = c("greedy", "optimal"),
gp = grid::gpar()
)
Arguments
tex |
LaTeX, as a character string. |
math_font |
Math font: |
max_width |
Width in big points (1/72 inch) at which lines wrap.
|
tex_style |
Force a TeX style: |
input_mode |
How
|
render_mode |
|
justify |
If |
line_break |
|
gp |
Graphical parameters from |
Value
A list of grid units in big points:
-
width,height: the size of the bounding box. -
depth: how far it extends below the baseline. -
baseline: the height of the baseline above the bottom.
And is_split: TRUE if the text was wrapped over several lines.
Examples
latex_dims(r"($\frac{a}{b}$)")
Create a grid grob from LaTeX
Description
latex_grob() returns a grob that draws LaTeX: a formula, a label
mixing text and math, or a document body. grid.latex() draws it
straight away. The grob works with grobWidth(), grobHeight(),
grobX() and grobY().
Usage
latex_grob(
tex,
x = grid::unit(0.5, "npc"),
y = grid::unit(0.5, "npc"),
default.units = "npc",
hjust = 0.5,
vjust = 0.5,
rot = 0,
math_font = "",
max_width = 0,
tex_style = "",
input_mode = c("mixed", "math", "document"),
render_mode = c("typeface", "path"),
justify = FALSE,
line_break = c("greedy", "optimal"),
debug = FALSE,
name = NULL,
gp = grid::gpar()
)
grid.latex(tex, ...)
Arguments
tex |
LaTeX, as a character string. |
x, y |
Position. |
default.units |
Units for |
hjust, vjust |
Justification: a number in |
rot |
Rotation in degrees, counter-clockwise. |
math_font |
Math font: |
max_width |
Width in big points (1/72 inch) at which lines wrap.
|
tex_style |
Force a TeX style: |
input_mode |
How
|
render_mode |
|
justify |
If |
line_break |
|
debug |
If |
name |
Grob name. |
gp |
Graphical parameters from |
... |
Arguments passed to |
Details
Style
$...$ sets a formula in text style, as in a paragraph; $$...$$ and
\[...\] set it in display style, with larger operators and limits
above and below. A label with no delimiters is set in text style.
tex_style forces one style on the whole formula; "script" and
"scriptscript" are the smaller styles of sub- and superscripts. For
part of a formula, use \displaystyle, \textstyle, \scriptstyle
or \scriptscriptstyle.
Graphical parameters
-
col: the colour.\textcoloroverrides it. -
fontfamily: the font of text, such as"serif"or the name of any installed font. Math usesmath_font. Bold and italic come from\textbf{}and\textit{}, not fromfontface. -
fontsize,cex: the size isfontsize * cexpoints (default 20). -
lineheight: line spacing (default 1.2).
Errors
Invalid LaTeX is drawn as well as it can be, with one warning listing each problem by line and column. An unknown command is drawn in red. A macro that expands without end, or nesting deeper than 400 levels, is an error.
Pasted LaTeX
LaTeX from a document can be pasted as it is: the output of
knitr::kable() or xtable, a table float, or a paper's body with
input_mode = "document". The preamble, \maketitle and \label draw
nothing, and \caption is drawn where it is written. \ref and
\pageref draw ??, \eqref draws (??) and \cite draws [?],
with a warning. A footnote is set where it is written, and equations
are not numbered.
Not supported: \tag, \verb, \textsc, switches such as \bfseries
and \itshape (use \textbf{} and \textit{}, or \bf and \it),
the description list, theorem environments and TikZ.
Images
\includegraphics[options]{file} draws a local PNG, JPEG or SVG file.
Each format needs a suggested package: png, jpeg, or rsvg and
grImport2 for SVG. width, height and scale size the image,
keepaspectratio fits it inside both, and angle rotates it;
\textwidth means max_width. trim and clip are ignored with a
warning. The extension may be left off, and \graphicspath{{dir/}}
adds a folder to search.
An SVG stays sharp at any size; a PNG or JPEG warns when it is shown
below 150 dpi. PDF and EPS files are not supported. A file that cannot
be drawn is an error, except with input_mode = "document", where it
warns and draws the file name instead.
Parallel code
Do not draw in forked processes, such as parallel::mclapply() or
future::plan(multicore). Use future::plan(multisession) or a socket
cluster instead.
Value
latex_grob() returns a grob of class "latexgrob";
grid.latex() draws it and returns it invisibly.
See Also
latex_dims(), latex_options(), markdown_grob(),
geom_latex()
Examples
grid::grid.newpage()
grid.latex(r"($x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$)",
y = 0.8, gp = grid::gpar(fontsize = 24))
# Colour, and a rotated grob
g <- latex_grob(r"($\colorbox{BurntOrange}{x^{2}} + y^{2}$)",
x = 0.3, y = 0.4, rot = 45)
grid::grid.draw(g)
grid.latex(r"($\textcolor{red}{x^{2}} + y^{2} = z^{2}$)",
x = 0.7, y = 0.4, gp = grid::gpar(col = "grey30"))
# A document body, wrapped at 250 points
grid::grid.newpage()
doc <- r"(\section{Results}
The fitted line is
\[ \hat{y} = \beta_0 + \beta_1 x, \]
and its slope, $\beta_1$, is positive.)"
grid.latex(doc, input_mode = "document", max_width = 250,
x = 0.05, y = 0.95, hjust = 0, vjust = 1,
gp = grid::gpar(fontsize = 12))
Set or show default rendering options
Description
Sets defaults for latex_grob(), grid.latex(), latex_dims(),
latex_tree() and the markdown functions. An argument given in a call
always wins over the default.
Usage
latex_options(
math_font = NULL,
render_mode = NULL,
tex_style = NULL,
input_mode = NULL,
justify = NULL,
line_break = NULL,
markdown_style = NULL,
device_math = NULL,
main_font = NULL,
sans_font = NULL,
mono_font = NULL
)
reset_latex_options()
Arguments
math_font |
Math font: a loaded font with a math table; see
|
render_mode |
|
tex_style |
|
input_mode |
|
justify |
If |
line_break |
|
markdown_style |
Default style for |
device_math |
If Heights are not adjusted: a tall formula can overflow a margin or a
|
main_font, sans_font, mono_font |
The fonts for text: the body, |
Details
With no arguments, returns the current settings (NULL means the
built-in default). Setting an option to NULL resets it. The previous
settings are returned, so do.call(latex_options, old) restores them.
Size and line spacing are set with gp (fontsize, cex,
lineheight), not here.
Value
The previous settings, invisibly. With no arguments, the current settings.
See Also
available_fonts(), load_font(), latex_grob()
Examples
old <- latex_options(math_font = "stix", render_mode = "typeface")
grid.latex("$\\sum_{i=1}^{n} i^{2}$", gp = grid::gpar(fontsize = 14))
do.call(latex_options, old)
# Math in base graphics, with no other change to the plotting code.
latex_options(device_math = TRUE)
plot(1:10, (1:10)^2,
main = "Slope $\\hat{\\beta}_1 = \\sum_{i=1}^{n} x_i^2$",
ylab = "$y^2$")
The layout of a LaTeX expression
Description
Returns what a formula is drawn from: one row per glyph, line, rectangle or run of text, with its position. Useful for checking alignment or building your own grobs.
Usage
latex_tree(
tex,
math_font = "",
max_width = 0,
tex_style = "",
input_mode = c("mixed", "math", "document"),
render_mode = c("typeface", "path"),
justify = FALSE,
line_break = c("greedy", "optimal"),
gp = grid::gpar()
)
Arguments
tex |
LaTeX, as a character string. |
math_font |
Math font: |
max_width |
Width in big points (1/72 inch) at which lines wrap.
|
tex_style |
Force a TeX style: |
input_mode |
How
|
render_mode |
|
justify |
If |
line_break |
|
gp |
Graphical parameters from |
Value
A list of class "latex_tree":
-
records: a data frame with one row per drawn element, with columns such astype,x,y,glyph,font_size,colorandtext. -
bbox:width,height,depthandbaseline, in big points. -
tex: the input. -
render_mode: the render mode used.
See Also
Examples
tree <- latex_tree("\\frac{a}{b}")
print(tree)
head(tree$records)
Wrap the text of a label in \text{}
Description
Turns a label that mixes text and math into pure math: text is wrapped
in \text{} and math is kept as it is. latex_grob() does not need
this; use it to pass a label to latex_grob(input_mode = "math") or to
another renderer that accepts only math.
Math between $...$, $$...$$, \(...\) or \[...\], and math
environments, are kept. A newline becomes a line break, and escaped
characters such as \$ stay text.
Usage
latex_wrap(tex, input_mode = c("mixed", "math"))
Arguments
tex |
A character vector. |
input_mode |
|
Value
A character vector the same length as tex.
Examples
latex_wrap(r"(The equation \(E=mc^2\) is famous)")
latex_wrap(r"(Cost: \$100 for $x$ items)")
latex_wrap("Line 1\nLine 2")
latex_wrap(r"(\frac{\alpha}{\beta})", input_mode = "math")
Load a font
Description
Registers a font under a name that works everywhere a font is named:
gp = gpar(fontfamily = ), latex_options() (main_font, sans_font,
mono_font, math_font) and element_latex(family = ). The font comes
from a file or from an installed family.
Usage
load_font(x, name = NULL, bold = NULL, italic = NULL, bolditalic = NULL)
Arguments
x |
A font file ( |
name |
The name to register the font under. The default is the font's family name. |
bold, italic, bolditalic |
Files of the other faces of the same family, so that bold and italic text uses the real design. Only for a file: the faces of an installed family are found automatically. A face left out is drawn with the regular file. |
Details
A math font loaded here can also be used as text. A font that is already
installed does not need loading to be used as gp$fontfamily; load it to
give it a short name, or to set it as a role in latex_options().
The text of a loaded font is measured and drawn by gridmicrotex from the
font's own file, so it looks the same on every device, base pdf()
included, with its kerning and ligatures. It is drawn as glyphs where the
device has them and as outlines where it has not (and for rotated text).
Other families are drawn by the device, as are right-to-left text and a
character the font has no glyph for, which the device may find in another
font. In base graphics with latex_options(device_math = TRUE) the device
draws all text, so it has to know the font itself.
Value
The name the font is registered under, invisibly.
See Also
available_fonts(), latex_options()
Examples
# The bundled STIX font stands in for your own font file here
otf <- system.file("fonts", "STIXTwoMath-Regular.otf",
package = "gridmicrotex")
load_font(otf, name = "My Font")
available_fonts()
Render a markdown document as a boxed grid grob
Description
Draws a markdown document (headings, paragraphs, lists, task lists,
quotes, code, tables, rules and images) inside an optional box. Text
wraps to width, and math goes between $...$. Everything
markdown_grob() supports works inside each block.
Usage
markdown_box_grob(
md,
x = grid::unit(0.5, "npc"),
y = grid::unit(0.5, "npc"),
width = grid::unit(1, "npc"),
height = NULL,
hjust = 0.5,
vjust = 0.5,
halign = 0,
valign = 1,
padding = NULL,
margin = NULL,
box_gp = NULL,
r = NULL,
style = NULL,
name = NULL,
gp = grid::gpar(),
vp = NULL
)
Arguments
md |
Markdown, as a character string. |
x, y |
Position of the box. |
width |
Width of the box. |
height |
Height of the box. |
hjust, vjust |
Justification of the box about |
halign |
Alignment of blocks in the box: |
valign |
Vertical alignment of the content when |
padding, margin |
A |
box_gp |
Fill and border of the box, such as
|
r |
Corner radius. |
style |
A |
name |
Grob name. |
gp |
Graphical parameters for the text. |
vp |
A viewport. If given, |
Details
A table that is too wide for the box wraps its widest columns;
table-layout: fixed gives the columns equal widths instead. Code
lines do not wrap.
An image on its own line is a block, scaled down to fit; an image inside a sentence is inline. Images must be local PNG, JPEG or SVG files, and need the png or jpeg package, or rsvg and grImport2 for SVG. An image that cannot be drawn is an error.
Value
A grob of class "markdownbox".
Styling
style sets the look of each tag:
markdown_box_grob(md, style = markdown_style( h1 = md_style(color = "steelblue", font_size = 2), blockquote = md_style(border_left = "3px solid grey60") ))
Or the same as CSS, as text or a .css file:
markdown_box_grob(md, style = "
h1 { color: steelblue; font-size: 2rem }
blockquote { border-left: 3px solid grey60 }
")
To style one part, wrap it in a <div> with a class or style,
with blank lines around the tags:
<div class="note"> ## This heading only </div>
<span class="..."> works the same inside a line. See
markdown_style() for tag names and md_style() for properties.
See Also
Examples
md <- paste(
"# Results", "",
"The slope is $\\beta_1$ with *p* < 0.001.", "",
"- first point", "- second point",
sep = "\n"
)
grid::grid.newpage()
grid::grid.draw(markdown_box_grob(
md,
width = grid::unit(4, "in"),
padding = grid::unit(8, "pt"),
box_gp = grid::gpar(fill = "grey95", col = "grey40")
))
Render a markdown label as a grid grob
Description
Draws a line of markdown, such as a plot title, with LaTeX math between
$...$. **bold**, *italic*, `code` and ~~strike~~ work,
and so does some inline HTML. For headings, lists, tables and other
blocks, use markdown_box_grob().
Usage
markdown_grob(md, style = NULL, ...)
grid.markdown(md, ...)
Arguments
md |
Markdown, as a character string. |
style |
A |
... |
Passed to |
Details
These HTML tags are supported:
| tag | effect |
<b>, <strong> | bold |
<i>, <em>, <cite>, <dfn>, <var>,
<address> | italic |
<code>, <kbd>, <samp>, <tt> | monospace |
<u>, <ins> | underline |
<s>, <del>, <strike> | strikethrough |
<sub>, <sup> | sub / superscript |
<mark> | yellow highlight |
<small>, <big> | smaller / larger |
<q> | quotation marks |
<br> | line break |
<span style="..."> | see below |
A style attribute can set color, text-decoration (underline,
line-through), font-size (such as 12pt, 1.2em or smaller)
and font-family; other properties are ignored. Colours
are R colour names, CSS names, #rgb, #rrggbb or rgb().
font-family takes serif, sans-serif, monospace, an installed
font, or a font named with load_font().
Tags nest and can hold markdown and math. Other tags are dropped and their text kept. Links keep their text only. Images must be local PNG, JPEG or SVG files. The characters U+E000 to U+E002 are removed from the input.
Value
A grob, as from latex_grob(). grid.markdown() draws it and
returns it invisibly.
See Also
markdown_box_grob(), geom_markdown()
Examples
grid::grid.newpage()
grid.markdown(r"(The **fitted** slope is $\beta_1$, *p* < 0.001)")
A style for markdown rendering
Description
Creates a style for markdown_grob(), markdown_box_grob() and the
ggplot2 markdown functions, from CSS, a preset, or md_style()
declarations.
Usage
markdown_style(base = NULL, css = NULL, ...)
Arguments
base |
|
css |
CSS text, or a path to a |
... |
Tag styles, each an |
Details
Tags are named as in HTML: body, p, h1 to h6, ul, ol, li,
blockquote, pre (code block), code (inline code), strong, em,
table, tr, td, th, hr, img, a (link), math (a $$...$$
paragraph), footnote, div and span. Every tag inherits from
body, and table cells inherit from table.
As in CSS, an inline style beats a class (.note), which beats a tag
(h1), and a later rule beats an earlier one. Colour, font, line
height and alignment are inherited by nested blocks; margins, padding
and borders are not.
Tag selectors, class selectors and lists (h1, h2) are supported.
Other selectors are ignored.
Value
A style object of class "gridmicrotex_markdown_style".
See Also
Examples
markdown_style()
markdown_style("github", h1 = md_style(color = "firebrick"))
markdown_style(css = "h1 { color: steelblue } .note { padding-left: 2em }")
Declarations for one markdown tag
Description
CSS properties for one tag, for use in markdown_style(). Names are
CSS property names with _ for -, so font_size sets font-size.
Usage
md_style(...)
Arguments
... |
Properties, as named arguments. |
Details
A length can be a number, meaning a multiple of the body font size
(font_size = 2.5); a CSS string such as "2.5em" or "12pt"; or a
grid::unit().
The supported properties are below. Inline ones also work on a
<span> and in markdown_grob(); block ones need
markdown_box_grob().
| property | scope | notes |
color | inline + block | |
font_size | inline + block | |
font_family | inline + block | |
font_weight | inline + block | |
font_style | inline + block | |
text_decoration | inline + block | underline,
overline, line-through |
background | inline + block | a fill behind the text |
border | inline | a frame; the inset is fixed |
border_style | inline | only double |
border_radius | inline | rounds the frame |
box_shadow | inline | |
visibility | inline | hidden keeps the space |
vertical_align | inline | super, sub,
or a length |
transform | inline | rotate(), scale(),
scaleX(-1) |
line_height | block | unitless, as gpar() wants it |
margin_top, margin_bottom | block | margins do not collapse |
margin_left, margin_right | block | |
padding_left, padding_right | block | |
padding_top, padding_bottom | block | |
margin, padding | block | the CSS shorthand: one to four lengths, in CSS's order |
text_align | block | left, center,
right |
border_left | block | the blockquote bar |
border_top | block | the hr rule |
border_bottom | tr | a rule under each table row |
border_color | table | colour of the table's rules |
table_layout | table | fixed divides the
width evenly between the columns |
height | block | the band an hr sits in |
bullet | ul | raw LaTeX for the marker glyph |
marker_gap | ul, ol | marker to text |
font_size also takes the keywords xx-small to xx-large,
smaller and larger.
On body, background, border, border_radius, padding and
margin style the box of markdown_box_grob() or of an
element_markdown() title:
body { background: grey95; padding: 8px;
border: 1px solid grey60; border-radius: 4px }
The box_gp, padding, margin and r arguments of
markdown_box_grob() override this rule.
An unknown property is an error here, but is ignored in CSS text.
Small caps, font-variant-numeric and padding inside an inline
border are not supported.
Value
An object of class gridmicrotex_md_style.
See Also
markdown_style, markdown_box_grob
Examples
md_style(color = "steelblue", font_size = 2.5, margin_top = 1.2)
Add a syntax highlighting grammar
Description
Adds a language for highlighting fenced code blocks in
markdown_box_grob(), from a KDE syntax file (the format used by Kate
and Pandoc). The easiest start is a copy of a built-in grammar:
Usage
register_highlighter(lang, file)
Arguments
lang |
Language name, as written after the opening fence. Case is ignored. A built-in language of the same name is replaced. |
file |
Path to a KDE syntax XML file. |
Details
file.copy(system.file("highlight", "python.xml",
package = "gridmicrotex"),
"mylang.xml")
Many files from https://kate-editor.org/syntax/ work as they are. Files that use dynamic rules are refused with an error. Those files are mostly GPL or LGPL licensed; check the licence before you redistribute one.
Colours come from markdown_style(), using Pandoc's class names (kw
keyword, co comment, st string, ...), so a grammar needs no
colours of its own.
Value
lang, invisibly.
See Also
available_highlighters,
markdown_box_grob, markdown_style
Examples
# Registering a grammar under a name of your own.
f <- system.file("highlight", "python.xml", package = "gridmicrotex")
register_highlighter("mypython", f)
"mypython" %in% available_highlighters()