Verbatim Chunks in R Markdown

Ramnath Vaidyanathan

March 12, 2014

This article is reposted from Addicted to R with the kind permission of Ramnath Vaidyanathan.

RMarkdown has truly revolutinized the way I write. The simplicity of markdown and the extreme flexibility of knitr allows me to combine text and code in ways I would never have been able to do before.

One of the things I have always wanted to do is to be able to print code chunks verbatim, along with the chunk markup. This is especially useful while writing tutorials, where I want the user to see the code chunk “asis”.

Initially, I thought that I could achieve this by indenting the code chunk, thereby “fooling” knitr into believing that it is not a code chunk, and thereby printing it verbatim in a <code> block. But I was terribly mistaken. Apparently, knitr is too smart to be fooled, and no matter how deep you tuck away or indent the chunk, knitr always finds it and executes it!

Digging a little deeper, I found an example from the author in his knitr-examples repo. The basic idea was to write a chunk hook that wraps the source code with the markup. It makes use of the option params.src that contains the chunk options that are set locally.

It works! Well, it almost works. I say almost, because I don’t like how it splits the code and the chunk markup into different blocks. I am sure that I can clean this up using some regex-fu, but I wanted to explore a cleaner solution using hooks.

After a lot of experimentation, I ended up with the following hook. Note that my implementation involves a source hook and not a chunk hook, like the one proposed by Yihui. It is customized for Rmd documents, but is easy to extend for other formats like Rnw.