Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chunk option class.output is not working on Error Message

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.

like image 541
TheRimalaya Avatar asked Jan 31 '18 09:01

TheRimalaya


2 Answers

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.

like image 100
RLesur Avatar answered Sep 23 '22 02:09

RLesur


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.

like image 44
grrrck Avatar answered Sep 23 '22 02:09

grrrck