I'm trying to add latex code surrounding r-markdown (.Rmd
) code chunks. I can do this by manually editing the .tex
file generated by knitr
as follows,
\usepackage{fancyvrb}
\usepackage{xcolor}
\usepackage{changepage}
{
\color{gray}
\footnotesize
\begin{adjustwidth}{2cm}{2cm}
\noindent\rule{1cm}{1.5pt} R code \noindent\rule{8cm}{0.3pt}
\begin{verbatim}
\end{verbatim}
\noindent\rule{8cm}{0.3pt}
\end{adjustwidth}
}
where \begin{verbatim}
begins a code chunk that, in turn, ends with \end{verbatim}
. I'd like to avoid manually re-coding this latex decoration manually each time I knit.
It appears that I can place the package information in the YAML
header of the .Rmd
:
---
header-includes:
- \usepackage{fancyvrb}
- \usepackage{xcolor}
- \usepackage{changepage}
---
But I'm not getting the hook setup right. I've tried to modify the hook described here, as follows,
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
def.chunk.hook <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
x <- def.chunk.hook(x, options)
paste0(
"{\n\\color{gray}\n\\footnotesize\n\\begin{adjustwidth}{1cm}{1cm}\n\\noindent\\rule{1cm}{1.5pt} R code \\noindent\\rule{8cm}{0.3pt}\n",
x,
"\n\n\\noindent\\rule{8cm}{0.3pt}\n\\end{adjustwidth}\n}\n"
)
}
)
```
which threw an error. Any suggestions appreciated.
UPDATE:
I am able to change R chunk font color, size and indention by adding the following to my YAML
header:
header-includes:
- \usepackage{changepage}
- \usepackage{xcolor}
- \usepackage{etoolbox}\BeforeBeginEnvironment{verbatim}{\begingroup\color{gray}\footnotesize\begin{adjustwidth}{.5cm}{.5cm}}\AfterEndEnvironment{verbatim}{\end{adjustwidth}\endgroup}
With that, I think there's no need to use the knitr hook function. Perhaps I've overlooked a cleaner approach, though, which allows me to make whatever mods I like.