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:
- Using knitr with listings
- Rnw source: knitr-listings.Rnw
- LyX source: knitr-listings.lyx
- PDF output: knitr-listings.pdf
One screenshot from the PDF output:
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
.