更改RMarkdown代码输出(HTML,PDF)中错误消息的颜色 [英] Change color of error messages in RMarkdown code output (HTML, PDF)

查看:349
本文介绍了更改RMarkdown代码输出(HTML,PDF)中错误消息的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以自动在R Markdown中使错误的文本颜色变为红色,而无需稍后手动编辑HTML.

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
```

在上面的代码中,Example 1的输出必须为红色.目前,我正在编辑生成的HTML(将style="color:red;"添加到适当的标记中),但是我想知道是否有一种自动方法.假设在编织之前不知道代码是否会产生错误.

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>")
})
```

通常,输出挂钩使我们能够控制R代码不同部分的输出(整个块,源代码,错误,警告等).有关详细信息,请检查 https://yihui.name/knitr/hooks/#output-hooks.

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.

这是我使用jQuery/Javascript的快速而肮脏的"解决方案.只需将其添加到YAML标头下方即可. 可能不是防弹的,因为它使用字符串"Error"检查错误消息,这也可能在其他应用程序中发生.

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>

这篇关于更改RMarkdown代码输出(HTML,PDF)中错误消息的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆