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

巧了我就是萌 提交于 2019-12-10 12:51:42

问题


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.


回答1:


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.


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>



回答2:


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



来源:https://stackoverflow.com/questions/47340955/change-color-of-error-messages-in-rmarkdown-code-output-html-pdf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!