7

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

3
  • 1
    see here ... perhaps this will help you
    – J_F
    Nov 20, 2017 at 13:26
  • Do you know if the hook was ever shipped with a package? I cannot view Gabor's gist.
    – landau
    Nov 20, 2017 at 13:43
  • I did not found such a function in the GitHub repository and also can not open his gist file ...
    – J_F
    Nov 20, 2017 at 13:45

2 Answers 2

5

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."))
```
0
3

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.

2
  • Does not work for me. I get ! Package inputenc Error: Keyboard character used is undefined (inputenc) in inputencoding `utf8'. Crayon 1.3.4, rmarkdown 1.8, knitr 1.20, R 3.4.3 (2017-11-30), Mint 18.2. Mar 5, 2018 at 22:57
  • I had to add term.cap = "256" and replace < and > with "&lt;" and "&gt;" for it to work for me. May 3, 2018 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.