---
title: Listings
subtitle: Using knitr with listings
date: '2011-12-10'
slug: listings
---

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

```r 
## 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](https://github.com/yihui/knitr/blob/master/inst/examples/knitr-listings.Rnw)
  - LyX source: [knitr-listings.lyx](https://github.com/yihui/knitr/blob/master/inst/examples/knitr-listings.lyx)
  - PDF output: [knitr-listings.pdf](https://github.com/yihui/knitr/releases/download/doc/knitr-listings.pdf)

One screenshot from the PDF output:

![using listings in knitr](https://db.yihui.org/imgur/PKupQ.png)

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](https://gist.github.com/2209775). The key is the option `breaklines=true`.

![break lines in listings output](https://db.yihui.org/imgur/3313T.png)

