rknitrr-markdown

crayon in R Markdown / knitr reports


How do I tell R Markdown / knitr to respect crayon color codes? I have the following R Markdown report.

---
title: "MWE"
author: "Will Landau"
date: "11/20/2017"
output: html_document
---

```{r color}
message(crayon::make_style("green")("My green message."))
```

When I knit and render it, I see the output

## My green message.

but the text color is not green.

EDIT

Use case: https://github.com/wlandau-lilly/drake/issues/164


Solution

  • Since fansi is now on CRAN, I will add a solution that uses it:

    ---
    title: "fansi Rmd"
    output: html_document
    ---
    
    ```{r color, echo = FALSE}
    options(crayon.enabled = TRUE)
    knitr::knit_hooks$set(message = function(x, options){
      paste0(
        "<pre class=\"r-output\"><code>",
        fansi::sgr_to_html(x = x, warn = FALSE),
        "</code></pre>"
      )
    })
    message(crayon::make_style("green")("My green message."))
    ```