Quantcast
Viewing all articles
Browse latest Browse all 3

Answer by Martin Schmelzer for RMarkdown - Change Inline Code Color *without changing workflow*

A way to achieve this without changing the workflow too much is to create your own format (e.g. html_notebook2) that is derived from the original but modifies the inline hook of knitr.

To get started you can check out this document.

Basic steps include

  1. Create a new R package
  2. Within this project run usethis::use_rmarkdown_template(). This creates the folder structure for your new format.
  3. Edit skeleton.rmd and template.yaml
  4. Define your format in a R file which has the same name html_notebook2.R(kind of a convention).

The content of the html_notebook2.R file could be

#'@import knitrset_hooks <- function() {  default_hooks  <- knit_hooks$get()  list(    inline = function(x) {      paste0("<span style=\"color: #FF0000;\">", x,"</span>")  })}#' @importFrom rmarkdown output_format knitr_options pandoc_options html_notebook#' @exporthtml_notebook2 = function() {  output_format(    knitr = knitr_options(knit_hooks = set_hooks()),    pandoc = pandoc_options(to = "html"),    clean_supporting = FALSE,    base_format = html_notebook()  )}

In the first part we define a new inline hook which only changes the font color.The second part is the definition of the new format.

After building and installing the package you can create a new rmarkdown document and use output: packagename::html_notebook2 as the output format. All inline code output will be colored red using my code. Here is an example:

---title: "Inline"output: cformat::html_notebook2---## R Markdown`r pi`

Image may be NSFW.
Clik here to view.
enter image description here

I created such a package and you can find it on GitHub. Feel free to copy it and rename it (cformat is a pretty lame working title ;) ).

Notice though that your students could change the color manually using HTML/CSS anyways. A way around could be some kind of key generation using a certain rule (unknown to the students obviously). For each inline chunk a key is generated and embedded using

paste0("<span code=", key," style=\"color: #FF0000;\">", x,"</span>")

If a valid key is embedded, the output was generated using R and not simply copied.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>