d.b
d.b

Reputation: 32548

Change color of error messages in RMarkdown code output (HTML, PDF)

Is there a way to automatically make text color of errors red in R Markdown without manually editing the HTML later.

---
title: ""
---

#### Example 1

```{r e1, error = TRUE}
2 + "A"
```

#### Example 2

```{r e2, error = TRUE}
2 + 2
```

In the above code, output of Example 1 would have to be red. Currently, I edit the generated HTML (add style="color:red;" to the appropriate tag) but I am wondering if there is an automatic way. Assume that it is not known before knitting whether the code will generate error.

Upvotes: 11

Views: 1554

Answers (2)

symbolrush
symbolrush

Reputation: 7457

I stumbled here because I had the same question but for PDF output rather than HTML.

It turns out combining @Martin Schmelzer's Solution with some hints from @Yihui Xie found here helps to achieve the same behavior in a PDF output.

Add \usepackage{xcolor} to your YAML header and the following chunk to your .Rmd file.

```{r}
color_block = function(color) {
  function(x, options) sprintf('\\color{%s}\\begin{verbatim}%s\\end{verbatim}',
                               color, x)
}
knitr::knit_hooks$set(error = color_block('red'))
```

The result is red error messages like

enter image description here

Upvotes: 1

Martin Schmelzer
Martin Schmelzer

Reputation: 23889

1. Use a knitr hook

The preferred solution is to use the output hook for errors:

```{r}
knitr::knit_hooks$set(error = function(x, options) {
  paste0("<pre style=\"color: red;\"><code>", x, "</code></pre>")
})
```

Output hooks in general allow us to control the output of different parts of our R code (the whole chunk, the source code, errors, warnings, ...). For details check https://yihui.name/knitr/hooks/#output-hooks.

enter image description here


2. Quick and dirty solution using JS/jQuery

And this is my "quick and dirty" solution using jQuery/Javascript. Just add it beneath the YAML header. Might not be bulletproof, since it checks for error messages using the string "Error" which might occur in other applications as well.

<script type="text/javascript">
$(document).ready(function() {
  var $chks = $("pre:not(.r) > code");
  $chks.each(function(key, val) {
    cntnt = $(this).html();
    if (cntnt.indexOf("Error") != -1) {
      $(this).css('color', 'red');
    }
  })
})
</script>

Upvotes: 13

Related Questions