Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 495
landau Avatar asked Nov 20 '17 13:11

landau


1 Answers

This seems to work:

---
title: "MWE"
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>",
    ansistrings::ansi_to_html(text = x, fullpage = FALSE),
    "</code></pre>"
  )
})
message(crayon::make_style("green")("My green message."))
```

Markdown output:

---
title: "MWE"
output: html_document
---

<pre class="r-output"><code>
## <span style="color:#4e9a06">My green message.</span>
</code></pre>

One caveat: ansistrings is not released yet.

like image 186
landau Avatar answered Oct 20 '22 18:10

landau