4

I'm generating pdf files from R markdown files (.Rmd). I'd like to style the output with the LaTeX listings package. Is there some way to indicate in the .Rmd file which style to wrap the R output in?

For example, the following Rmd:

```{R}
1:10
````

run through knitr and pandoc produces:

\begin{lstlisting}[language=R]
1:10
\end{lstlisting}

\begin{lstlisting}
[1]  1  2  3  4   5  6  7  8  9  10
\end{lstlisting}

I have not found a way to differentiate the two listings in the pdf output. I think I need either a style on one or both lstlistings, or to give the output a language option that I could then add to the header. For example, this would work:

\begin{lstlisting}[language=R,style=Rsource]
1:10
\end{lstlisting}

\begin{lstlisting}
[1]  1  2  3  4   5  6  7  8  9  10
\end{lstlisting}

Because I could add something to the header to style Rsource differently from the default listings:

\lstset{language=R,frame=single}

\lstdefinestyle{Rsource}{
  backgroundcolor=\color[gray]{0.95},
}

This boxes both code and output, but shades only the code. Is there a way to specify this from the Rmd source? I don't want to manually alter the tex output.

I know I can use the pandoc --highlighting-style option, and that's my alternative approach. However, I would like to box both code and output, and only shade the code. I know how to do this with listings styles (once the listings are labeled with the right options), but I'm not sure it's possible with the pandoc styles.

Follow-up

I've come up with a solution by filtering the pandoc output through sed to add the style options I need. More details are on my related post over on tex.stackexchange. I'm still interested in an answer that uses built-in features of knitr and/or pandoc.

Community
  • 1
  • 1
Tyler
  • 9,872
  • 2
  • 33
  • 57

0 Answers0