How can I create custom roxygen2 tags for a package?

80 Views Asked by At

I'm aware of this documentation (https://cran.r-project.org/web/packages/roxygen2/vignettes/extending.html) but I am struggling to make it work for a custom "home brew" package. All I really need is a "simple" custom tag e.g. @information. There seems to be some information missing to bridge the gap (for me) between the documentation and actually having it work in a package (a working example would be great).

I also found this video:
https://www.youtube.com/watch?v=AcibRDNSfoM
and related repositories:
https://github.com/shahronak47/informationtag
https://github.com/shahronak47/infotagdemo
However, they also don't seem to be doing what I would expect.

Can anyone point me at some useful examples?

1

There are 1 best solutions below

0
Ott On BEST ANSWER

Leaning on the example made with the @tip tag in the Extending roxygen2 vignette for a simple descriptive tag @information all you need to do is create a file in the R/ folder of your package and add this content to the file:

#' @importFrom roxygen2 roxy_tag_parse
#' @importFrom roxygen2 roxy_tag_rd
NULL

# define a roxy_tag_parse() method that describes how to parse the tag 
# text. Here it will be processed using Markdown 
#' @export
roxy_tag_parse.roxy_tag_information <- function(x) {
  roxygen2::tag_markdown(x)
}

# define a roxy_tag_rd() method that describes how to convert the tag 
# into `.Rd` commands 
#' @export
roxy_tag_rd.roxy_tag_information <- function(x, base_path, env) {
  roxygen2::rd_section("information", x$val)
}

# Since we provided our own type "information" in rd_section() we need 
# to define a format method for this type
# Feel free to adapt this method to your needs
#' @export
format.rd_section_information <- function(x, ...) {
  paste0(
    "\\section{Information}{\n",
    "\\itemize{\n",
    paste0("  \\item ", x$value, "\n", collapse = ""),
    "}\n",
    "}\n"
  )
}

Later on you can just use the tag as any other tag in your roxygen headers:

#' @information This is some important information I want to display! 

Hope this helps!

EDIT:

If you want to create a separate package for custom roclets and import them when needed, then in your custom package {myroclets} create a file in R/ and add the same contents as stated above. Additionally you need to add a constructor for your @information tag so append the file with

#' @export
information_roclet <- function() {
  roxygen2::roclet("information")
}

to export your information_roclet.

In the case you need to use the information_roclet in another package of yours, just add to DESCRIPTION

Roxygen: list(roclets = c("collate",
                          "rd",
                          "namespace",
                          "myroclets::information_roclet"),
              packages = "myroclets") 

where myroclets is the package where the information_roclet was originally created.