7

I am preparing a tutorial for a course and I want to change the colour of the error to be red. I am using BookDown and gitbook as my output format. But I found that the option class.output is not working. I want to add a class to the output for the error message I get. How can I do that? You can use this as an example:

---
title: "Test Book"
author: "therimalaya"
site: bookdown::bookdown_site
output: bookdown::gitbook
---

# Hello World

```{r, error = TRUE, class.output="red"}
rnorm(-10)
```

This works if there is no error.

RLesur
  • 5,810
  • 1
  • 18
  • 53
TheRimalaya
  • 4,232
  • 2
  • 31
  • 37

2 Answers2

6

class.output is not applied to errors (see here).
Following this answer, I suggest you to use an error hook:

```{r error-hook, echo=FALSE}
knitr::knit_hooks$set(error = function(x, options) {
  paste0(
    "```{", 
    ifelse(is.null(options$class.error), 
           "", 
           paste0(" .", gsub(" ", " .", options$class.error))
    ),
    "}\n",
    x,
    "\n```"
  )
})
```

Now, you can use a "new" class.error option in your chunk.

```{r, error = TRUE, class.error="red"}
rnorm(-10)
```

Feel free to open a feature request here.

RLesur
  • 5,810
  • 1
  • 18
  • 53
2

The ability to use custom CSS classes for errors, warnings, and messages was just added to knitr, so you will be able to use the following syntax.

```{r error = TRUE, class.error = "bg-danger text-danger"}
rnorm(-10)
```

Here I'm using Bootstrap classes, but you can pass any class(es) you need to class.error. The chunk options class.message and class.warning also work. Note that class.output is applied only to standard code outputs.

grrrck
  • 1,066
  • 6
  • 7