The R output in rmarkdown strips all terminal control sequences – colors and formats (i.e., bold or italics). However, it is relatively easy to restore it. For this, one needs to install the fansi package and include the following chunk in the rmarkdown document, hooking a custom function to the output:
```{r echo=FALSE}
options(crayon.enabled = TRUE)
knitr::knit_hooks$set(output = function(x, options){
paste0(
'<pre class="r-output"><code>',
fansi::sgr_to_html(x = htmltools::htmlEscape(x), warn = FALSE),
'</code></pre>'
)
})
```
If you are using the crayon package, however, you might run into the following problem: in some situations crayon “thinks” that the terminal has a limited capability of displaying colors, and will use only the 16 base colors. Even if more colors are available. One such situation is when one includes colored output in a vignette processed automatically – there is no way to convince the num_colors function from crayon that it should report 256 colors.
Therefore, we need to substitute the num_colors function by a dumber version:
num_colors <- function(forget=TRUE) 256
library(crayon)
assignInNamespace("num_colors", num_colors, pos="package:crayon")