Using knitr with listings


It is easy to define your own output hooks in knitr to decorate your results with the LaTeX listings package. Here is a snippet that you may use:

## a common hook for messages, warnings and errors
hook_lst_bf = function(x, options) {
    paste("\\begin{lstlisting}[basicstyle={\\bfseries}]\n", x, 
        "\\end{lstlisting}\n", sep = "")
knit_hooks$set(source = function(x, options) {
    paste("\\begin{lstlisting}[language=R,numbers=left,stepnumber=2]\n", x, 
        "\\end{lstlisting}\n", sep = "")
}, output = function(x, options) {
    paste("\\begin{lstlisting}[basicstyle={\\ttfamily}]\n", x, 
        "\\end{lstlisting}\n", sep = "")
}, warning = hook_lst_bf, message = hook_lst_bf, error = hook_lst_bf)

## empty highlight header since it is not useful any more
set_header(highlight = "")

As you can see, knitr exposes everything to the user. All you need to do is to make sure that these pieces R source and output can be wrapped in proper environments.

Wait, do not copy the code above, because I have already made them into knitr via the function render_listings() with a few tweaks. Here is an example:

One screenshot from the PDF output:

using listings in knitr

I thank Frank Harrell for the LaTeX style file Sweavel.sty.

More listings options

The listings package has tons of options that you can use, so be sure to read its manual to know its full power. Below is an example to show how to break lines in the error messages, and you can download its the Rnw source. The key is the option breaklines=true.

break lines in listings output