Starting from version 6.0.0, roxygen supports Markdown markup within
most roxygen tags. Roxygen uses the commonmark package, which
is based on the CommonMark Reference Implementation to parse these tags.
See https://commonmark.org/help/ for more about the parser
and the markdown language it supports. You can also still use the
.Rd
syntax, some of which we will present below in the Rd syntax section.
There are two ways to turn on Markdown support for a package: globally, at the package level, and locally at the block level.
To turn on Markdown for the whole package, insert this entry into the
DESCRIPTION
file of the package:
Roxygen: list(markdown = TRUE)
The position of the entry in the file does not matter. After this, all Roxygen documentation will be parsed as Markdown.
Alternatively, you can use the @md
tag to turn on
Markdown support for a single documentation chunk. This is a good option
to write any new documentation1 for existing packages in markdown.
There is also a new @noMd
tag. Use this if you turned on
Markdown parsing globally, but need to avoid it for a single chunk. This
tag is handy if the Markdown parser interferes with more complex Rd
syntax.
Here is an example roxygen chunk that uses Markdown.
#' Use roxygen to document a package
#'
#' This function is a wrapper for the [roxygen2::roxygenize()] function from
#' the roxygen2 package. See the documentation and vignettes of
#' that package to learn how to use roxygen.
#'
#' @param pkg package description, can be path or package name. See
#' [as.package()] for more information
#' @param clean,reload Deprecated.
#' @inheritParams roxygen2::roxygenise
#' @seealso [roxygen2::roxygenize()], `browseVignettes("roxygen2")`
#' @export
#' @md
The usual Markdown heading markup creates sections and subsections.
Top level headings, i.e. ‘#
’ create sections, via the
\section{}
Rd tag. ‘#
’ may only appear after
the @description
and @details
tags. Since
@details
can appear multiple times in a block, you can
always precede a ‘#
’ section with @details
, if
you prefer to place it towards the end of the block, after
@return
for example:
#' @details
#' Trim the leading and trailing whitespace from a character vector.
#'
#' @param x Character vector.
#' @return Character vector, with the whitespace trimmed.
#'
#' @details # This will be a new section
#' ...
Top level sections are always placed at a fixed position in the
manual page, after the parameters and the details, but before
\note{}
, \seealso{}
and the
\examples{}
. Their order will be the same as in the roxygen
block.
Headings at level two and above may appear inside any roxygen tag
that formats lines of text. E.g. @description
,
@details
, @return
, etc. They create
subsections, via the \subsection{}
Rd tag. They are allowed
within top level sections as well, i.e. after ‘#
’.
Subsections can be nested. Example:
#' @details
#' ## Subsection within details
#' ### Sub-subsection
#' ... text ...
Emphasis and strong (bold) text are supported. For emphasis, put the text between asterisks or underline characters. For strong text, use two asterisks at both sides.
#' @references
#' Robert E Tarjan and Mihalis Yannakakis. (1984). Simple
#' linear-time algorithms to test chordality of graphs, test acyclicity
#' of hypergraphs, and selectively reduce acyclic hypergraphs.
#' *SIAM Journal of Computation* **13**, 566-579.
#' See `::is_falsy` for the definition of what is _falsy_
#' and what is _truthy_.
Inline code is supported via backticks.
#' @param ns Optionally, a named vector giving prefix-url pairs, as
#' produced by `xml_ns`. If provided, all names will be explicitly
#' qualified with the ns prefix, i.e. if the element `bar` is defined ...
For blocks of code, put your code between triple backticks:
#' ```
#' pkg <- make_packages(
#' foo1 = { f <- function() print("hello!") ; d <- 1:10 },
#' foo2 = { f <- function() print("hello again!") ; d <- 11:20 }
#' )
#' foo1::f()
#' foo2::f()
#' foo1::d
#' foo2::d
#' dispose_packages(pkg)
#' ```
Note that this is not needed in @examples
, since its
contents are formatted as R code, anyway.
You can use similar syntax to include a block of R code and/or its output in the manual page. See section ‘Dynamic R code’ below.
Regular Markdown lists are recognized and converted to
\enumerate{}
or \itemize{}
lists:
#' There are two ways to use this function:
#' 1. If its first argument is not named, then it returns a function
#' that can be used to color strings.
#' 1. If its first argument is named, then it also creates a
#' style with the given name. This style can be used in
#' `style`. One can still use the return value
#' of the function, to create a style function.
#' The style (the `...` argument) can be anything of the
#' following:
#' * An R color name, see `colors()`.
#' * A 6- or 8-digit hexa color string, e.g. `#ff0000` means
#' red. Transparency (alpha channel) values are ignored.
#' * A one-column matrix with three rows for the red, green
#' and blue channels, as returned by [grDevices::col2rgb()]
Nested lists are also supported.
Note that you do not have to leave an empty line before the list. This is different from some Markdown parsers.
Use GFM table formatting:
| foo | bar |
| --- | --- |
| baz | bim |
By default, columns are left-aligned. Use colons to generate right and center aligned columns:
| left | center | right |
| :--- | :----: | ----: |
| 1 | 2 | 3 |
Markdown hyperlinks work as usual:
#' See more about the Markdown markup at the
#' [Commonmark web site](http://commonmark.org/help)
URLs inside angle brackets are also automatically converted to hyperlinks:
#' The main R web site is at <https://r-project.org>.
Markdown notation can also be used to create links to other help topics. There are two basic forms:
[ref]
: The target topic and the link text are one and
the same.[text][ref]
: Link text differs from the target.First we explore the simplest form: [ref]
. The presence
of trailing parentheses, e.g., [func()]
, signals that the
target func
is a function, which causes two things to
happen:
func()
is automatically typeset as
code.[ref] examples |
Links to help topic for … |
Notes |
---|---|---|
[func()] [pkg::func()] |
a function in same package or in pkg |
Always typeset as code. Produces Rd: \code{\link[=func]{func()}} or \code{\link[pkg:func]{pkg::func()}} |
[thing] [pkg::thing] |
a topic in same package or in pkg |
Use for a topic that documents NULL and
name is setvia @name , e.g., a dataset or concept.Not typeset as code. Produces Rd: \link{thing} or\link[pkg:thing]{pkg::thing} |
[`thing`] [`pkg::thing`] |
a topic in same package or in pkg |
Same as above, but explicit backticks mean that it is typeset as code. Good for documenting a class. Produces Rd: \code{\link{thing}} or\code{\link[pkg:thing]{pkg::thing}} |
Use the second form [text][ref]
to link to the topic
specified by ref
, but with text
as the link
text.
[text][ref] examples |
Links to help topic for … |
Notes |
---|---|---|
[text][func()] [text][pkg::func()] |
a function in same package or in pkg |
Text is not typeset as code. Produces Rd: \link[=func]{text} or\link[pkg:func]{text} |
[text][thing] [text][pkg::thing] |
a topic in same package or in pkg |
Text is not typeset as code. Use for a topic that documents NULL and name is set via @name ,e.g., a dataset or concept. Produces Rd: \link[=thing]{text} or\link[pkg:thing]{text} |
In the [text][ref]
, the link text is treated like normal
text by default.
[`text`][ref]
.It is never appropriate to use backticks around the ref
in this form.
[text][`blah-blah`]
[text][blah-blah]
S3 and S4 class not done yet
Examples | Help topic for what? |
Notes |
---|---|---|
[abc-class] [pkg::abc-class] |
an S4 class named “abc” in same package or in pkg |
In Rd: \linkS4class{abc} or\link[pkg:abc-class]{pkg::abc} |
[abc][abc-class] |
*is this a thing? | ??? \link[=abc-class]{abc} |
Markdown syntax for inline images works. The image files must be in
the man/figures
directory:
#' Here is an example plot:
#' 
Similarly to the knitr package, you can use the Markdown inline code markup or Markdown code blocks to evaluate R code and insert its output into the manual page.
To insert code inline, enclose it in `r `
. Roxygen will
interpret the rest of the text within backticks as R code and evaluate
it, and replace the backtick expression with its value. After all such
substitutions, the text of the whole tag is interpreted as Markdown, as
usual.
A simple example:
#' @title Title `r 1 + 1`
#' @description Description `r 2 + 2`
#' @md
<- function() NULL foo
will be turned into:
#' @title Title 2
#' @description Description 4
#' @md
<- function() NULL foo
The resulting text, together with the whole tag is interpreted as
markdown, as usual. This means that you can use R to dynamically write
markdown. To markup something as code from within R, you must replace
the inner backticks with the unicode hex code "\x60"
,
rather than an actual unicode backtick character.
The interpretation from the source all the way to the final Rd documentation goes through three steps. For example:
#' Title
#' Description `r paste0('\x60', 'bar', '\x60')`
#' @md
<- function() NULL foo
is run through knitr to evaluate R, yielding:
#' Title
#' Description `bar`
#' @md
<- function() NULL foo
is then run through roxygen’s markdown engine, yielding:
#' Title
#' Description \code{bar}
#' @md
<- function() NULL foo
is finally turned into Rd documentation using roxygen, yielding:
% Generated by roxygen2: do not edit by hand
% Please edit documentation in ./<text>
\name{foo}
\alias{foo}
\title{Title
Description \code{bar}}
\usage{
foo()
}
\description{
Title
Description \code{bar}
}
To insert entire blocks of code, enclose them in ```{r}
,
just like in knitr documents. They go through the same three steps
described above for inline code.
For example:
#' @title Title
#' @details Details
#' ```{r lorem}
#' 1+1
#' ```
#' @md
<- function() NULL foo
becomes:
% Generated by roxygen2: do not edit by hand
% Please edit documentation in ./<text>
\name{foo}
\alias{foo}
\title{Title}
\usage{
foo()
}
\description{
Title
}
\details{
Details
\if{html}{\out{<div class="sourceCode r">}}\preformatted{1+1
#> [1] 2
}\if{html}{\out{</div>}}
}
Code blocks support knitr chunk options, e.g. to keep the output of
several expressions together, you can specify
results="hold"
:
#' ```{r results="hold"}
#' names(mtcars)
#' nrow(mtcars)
#' ```
Plots will create .png
files in the
man/figures
directory. Note that plots in
man/figures
may quickly increase the size of your package.
The file names are created from the chunk names.
#' ```{r iris-pairs-plot}
#' pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species",
#' pch = 21, bg = c("red", "green3", "blue")[unclass(iris$Species)])
#' ```
This feature is powered by the knitr package.
This causes some limitations and differences to keep in mind:
Inline and fenced code blocks from the same roxygen block share the same evaluation environment. As a result, variables created in one code block can be reused in another one. For example:
#' Title `r baz <- 420` `r baz`
#'
#' Description `r exists('baz', inherits = FALSE)`
#' @md
<- function() NULL
bar
#' Title
#'
#' Description `r exists('baz', inherits = FALSE)`
#' @md
<- function() NULL zap
becomes:
% Generated by roxygen2: do not edit by hand
% Please edit documentation in ./<text>
\name{bar}
\alias{bar}
\title{Title 420}
\usage{
bar()
}
\description{
Description TRUE
} % Generated by roxygen2: do not edit by hand
% Please edit documentation in ./<text>
\name{zap}
\alias{zap}
\title{Title}
\usage{
zap()
}
\description{
Description FALSE
}
Notice how inside the documentation for zap()
,
baz
does not exist (“Description
FALSE
”).
The R code is evaluated in a new environment that is the child of
the package environment of the package you are documenting. This means
that you can call (internal or exported) functions of the package. For
example, packageName()
will report the name of the current
package:
#' To insert the name of the current package: `packageName()`.
The code blocks are run every time you call
roxygenize()
(or devtools::document()
) to
generated the Rd files.
Some knitr chunk options are reset at the start of every code
block, so if you want to change these, you’ll have to specify them for
every chunk. These are currently error
,
fig.path
, fig.process
.
Some knitr options might not create meaningful output.
The Markdown code runs every time you call
roxygenize()
(or devtools::document()
) to
generate the Rd files. This potentially makes roxygenize()
(much) slower. You can turn on knitr caching as usual, but make sure to
omit the cache from the package.
knitr calls the appropriate print()
or (if
available) knitr::knit_print()
methods on the result. The
resulting markdown from some of these methods may not be supported by
roxygen’s subset of markdown (see vignette("rd.Rmd")
). You
can always override the automatic methods, and have your R calls return
valid markdown as a character vector, wrapped in
knitr::asis_output()
.
Also recall that everything outside of inline or fenced code is not handled by rmarkdown, but by roxygen. Not all features from rmarkdown are available.
Rd
markupNote that turning on Markdown does not turn off the standard
Rd
syntax. We suggest that you use the regular
Rd
tags in a Markdown roxygen chunk only if necessary. The
two parsers do occasionally interact, and the Markdown parser can pick
up and reformat Rd syntax, causing an error, or corrupted manuals.
Leading whitespace is interpreted by the commonmark parser, whereas
it is ignored by the Rd
parser (except in
\preformatted{}
). Make sure that you only include leading
whitespace intentionally, for example, for nested lists.
The Commonmark parser does not require an empty line before lists, and this might lead to unintended lists if a line starts with a number followed by a dot, or with an asterisk followed by whitespace:
#' You can see more about this topic in the book cited below, on page
#' 42. Clearly, the numbered list that starts here is not intentional.
Links to operators or objects that contain special characters, do not
work currently. E.g. to link to the %>%
operator in the
magrittr
package, instead of
[magrittr::%>%]
, you will need to use the
Rd
notation:
\code{\link[magrittr]{\%>\%}}
.
Within roxygen tags, you can use .Rd
syntax to format
text. Below we show you examples of the most important .Rd
markup commands. The full details are described in R
extensions. Before roxygen version 6.0.0 this was the only supported
syntax. Now all of the formatting described below can be achieved more
easily with Markdown syntax, with the important exception of mathematical
expressions.
Note that \
and %
are special characters.
To insert literals, escape with a backslash: \\
,
\%
.
\emph{italics}
\strong{bold}
\code{r_function_call(with = "arguments")}
,
\code{NULL}
, \code{TRUE}
\pkg{package_name}
To other documentation:
\code{\link{function}}
: function in this
package
\code{\link[MASS]{abbey}}
: function in another
package
\link[=dest]{name}
: link to dest, but show
name
\code{\link[MASS:abbey]{name}}
: link to function in
another package, but show name.
\linkS4class{abc}
: link to an S4 class
To the web:
\url{http://rstudio.com}
\href{http://rstudio.com}{Rstudio}
\email{[email protected]@rstudio.com}
(note the doubled
@
)
Ordered (numbered) lists:
#' \enumerate{
#' \item First item
#' \item Second item
#' }
Unordered (bulleted) lists
#' \itemize{
#' \item First item
#' \item Second item
#' }
Definition (named) lists
#' \describe{
#' \item{One}{First item}
#' \item{Two}{Second item}
#' }
Standard LaTeX (with no extensions):
\eqn{a + b}
: inline equation
\deqn{a + b}
: display (block) equation
Tables are created with \tabular{}
. It has two
arguments:
Column alignment, specified by letter for each column
(l
= left, r
= right, c
=
centre.)
Table contents, with columns separated by \tab
and
rows by \cr
.
The following function turns an R data frame into the correct format,
adding a row consisting of the (bolded) column names and prepending each
row with #'
for pasting directly into the
documentation.
<- function(df, ...) {
tabular stopifnot(is.data.frame(df))
<- function(x) if (is.numeric(x)) "r" else "l"
align <- purrr::map_chr(df, align)
col_align
<- lapply(df, format, ...)
cols <- do.call("paste",
contents c(cols, list(sep = " \\tab ", collapse = "\\cr\n#' ")))
paste("#' \\tabular{", paste(col_align, collapse = ""), "}{\n#' ",
paste0("\\strong{", names(df), "}", sep = "", collapse = " \\tab "), " \\cr\n#' ",
"\n#' }\n", sep = "")
contents,
}
cat(tabular(mtcars[1:5, 1:5]))
#> #' \tabular{rrrrr}{
#> #' \strong{mpg} \tab \strong{cyl} \tab \strong{disp} \tab \strong{hp} \tab \strong{drat} \cr
#> #' 21.0 \tab 6 \tab 160 \tab 110 \tab 3.90\cr
#> #' 21.0 \tab 6 \tab 160 \tab 110 \tab 3.90\cr
#> #' 22.8 \tab 4 \tab 108 \tab 93 \tab 3.85\cr
#> #' 21.4 \tab 6 \tab 258 \tab 110 \tab 3.08\cr
#> #' 18.7 \tab 8 \tab 360 \tab 175 \tab 3.15
#> #' }
If you wish to convert the .Rd
syntax in
existing documentation to markdown, you can have a look at roxygen2md package.↩︎