Copy to clipboard buttons for code blocks

The pkgdown and now blogdown packages have the super-nice copy to clipboard buttons for code blocks (see and ). Is it possible to get something similar for standard Rmarkdown documents? Has anyone done this and has a MWE perhaps referencing appropriate .js and .css files?


Hi @garthtarr,

Why not use the bookdown package directly if it now supports copy-to-clipboard?

Assuming you have the right packages installed, this should be a MWE from the klippy website here

tf <- tempfile(fileext = c(".Rmd", ".html"))
  c("```{r klippy, echo=FALSE, include=TRUE}",
    "Insert this chunk in your `Rmd` file:",
    "`r ''````{r klippy, echo=FALSE, include=TRUE}",
rmarkdown::render(tf[1], "html_document", tf[2])
browseURL(paste0("file://", tf[2]))
# }

Thanks for the reply @mattwarkentin. The klippy is OK but feels a bit hacky and bookdown is probably overkill (I also have a system for outputting questions in one HTML file and solutions in another HTML file, but all text in the same Rmd file that I don't think would work easily in bookdown).

What would be really nice is an option in the YAML to enable/disable copy to clipboard buttons (along the same lines as the code_folding option).

I ended up borrowing out the relevant js, css and html files from the pkgdown pull request and incorporated that into my RMarkdown website.

Unless I am misinterpreting, bookdown::html_document2() is essentially a drop-in replacement for rmarkdown::html_document() to get access to the additional bookdown features. I use pdf_document2() and html_document2() very often in place of their rmarkdown relatives, even when I am only creating single Rmd documents.

You can definitely define a new YAML parameter to toggle copy-to-clipboard if you are comfortable editing the template files.

I didn't know about the bookdown::html_document2, that's cool and might be useful in future. Unfortunately, it seems the copy to clipboard functionality is specific to bookdown::gitbook format, so doesn't come "for free" with bookdown::html_document2.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.