Search code examples
rbookdown

Formatting pdf-output chunks of bookdown


I'm tinkering with bookdown and am generating both html and pdf output.

For the html output the rendered R input and output are placed in blocks with gray background. For the pdf output the input chunks are highlighted but the output isn't. For example the following source code

Blah blah blah

```{r, message=FALSE}
library(mosaic)           # Load mosiac-pakken
tally(~ Smoke, data=fev)  # Optæl Smoke
```

Blah blah blah

results in this tex output:

\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(mosaic)           }\CommentTok{# Load mosiac-pakken}
\KeywordTok{tally}\NormalTok{(}\OperatorTok{~}\StringTok{ }\NormalTok{Smoke, }\DataTypeTok{data=}\NormalTok{fev)  }\CommentTok{# Optæl Smoke}
\end{Highlighting}
\end{Shaded}

\begin{verbatim}
Smoke
  0   1 
589  65 
\end{verbatim}

The input is wrapped in Shaded and Highlighting which can be modified in the preamble of the tex file. The output, however, is only wrapped in a standard verbatim environment which would be problematic to redefine in the file (since a redefinition will mess other parts up). How can I setup my configuration to wrap the output in an environment that I can redefine? Or possibly just keep the input and output wrapped in the same environment?

My _output.yml file looks like this (which is more or less copied from Yihui)

bookdown::pdf_book:
  highlight: zenburn
  includes:
    in_header: latex/preamble.tex
    before_body: latex/before_body.tex
    after_body: latex/after_body.tex
  keep_tex: yes
  dev: "cairo_pdf"
  latex_engine: xelatex
  citation_package: natbib
  template: null
  pandoc_args: --chapters
  toc_depth: 3
  toc_unnumbered: no
  toc_appendix: yes
  quote_footer: ["\\VA{", "}{}"]

How can I change the code to add a wrapper or just redefine the format of the output chunk?


Solution

  • Since bookdown 0.4, you can use a global option bookdown.post.latex to post-process the LaTeX output. In your case, it will be like:

    options(bookdown.post.latex = function(x) {
      # x is the content of the LaTeX output file
      gsub('^\\\\(begin|end)\\{verbatim\\}$', '\\\\\\1{YOUR_ENVIRONMENT}', x)
    })
    

    Then define the custom environment in your LaTeX preamble.