Chunk option class.output is not working on Error Message
Asked Answered
C

2

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.

Cooperate answered 31/1, 2018 at 9:11 Comment(1)
Thanks for your support!Shane
S
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.

Shane answered 31/1, 2018 at 18:21 Comment(0)
G
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.

Guzel answered 5/3, 2019 at 15:28 Comment(1)
I see,there has quite some classes, thanks a lot...Pooley

© 2022 - 2024 — McMap. All rights reserved.