Style code chunk with pdf output

I'm trying to do a bit customization to code chunks with rmarkdown pdf output. For example, set the background to white and add borders with shadow effect like this

Any recipe or pointer for this? Thank you!

Hi @enixam,

I think the best way to achieve this type of formatting for the entire document is using knitr output hooks. You can learn more about them here.

Basically, you need to figure out the latex syntax needed to produces the aesthetics you want, and then have the output hook return the source code so that it looks that way. Hooks are very powerful.

Adding something like this to your setup chunk early in the document:

knitr::knit_hooks$set(
  source = function(x, options) {
    # insert formatting code here
  }
)

The x variable is the source code for any given chunk. The source output hook should return the text formatted to look like the above image.

This should get you started:

---
title: "Untitled"
output: pdf_document
header-includes:
  - \usepackage[skins]{tcolorbox}
---

```{r setup, include=FALSE}
knitr::knit_hooks$set(
  source = function(x, options) {
    x <- paste0(xfun::split_lines(x), collapse = "\n\n")
    paste0(
      "\\begin{tcolorbox}[enhanced,fontupper=\\large,drop shadow southeast, sharp corners,colback=white,colframe=lightgray]", 
    x, "\\end{tcolorbox}"
    )
  }
)
```

```{r}
1 + 1
```

2 Likes

Thank you @mattwarkentin a lot! I'll look into that.

1 Like