[Tex/LaTex] R-code linebreaks AND themes in knitr

highlightingknitrline-breakingr

hpesoj626 provides two great minimal working examples for how to get R-code linebreaks AND code highlighting in knitr. I was wondering if it was possible to use Yihui's knitr themes within either of the two examples? And if so, how?

Here is the code for the example that I personally prefer (I added language=R and the three lines between hashtags in the setup chunk, and deleted highlight = FALSE in the chunk in the document):

\documentclass[twocolumn]{article}

\usepackage{listings}
\usepackage{inconsolata}

\lstset{breaklines=true,showstringspaces=false,language=R}

<<setup, include=FALSE, cache=FALSE>>=
opts_chunk$set(fig.path = 'figure/listings-')
options(replace.assign = TRUE, width=60)
render_listings()
################################################
# not part of hpesoj626's example and not working:
opts_chunk$set(fig.path = 'figure/listings-')
opts_knit$set( out.format="latex" )
################################################
@

\title{Function listings with linebreaks and code highlighting}

\begin{document}
\maketitle

Two ways of printing the code.

<<tidy=TRUE>>=
theFunction <- function(x) {
  tmp <- "A really long string that should be line-broken but it would be nice to also see code highlighting colors. The function is in the real code sourced, but for the sake of easier reproducibility, it is written here instead."
}

theFunction
@

\end{document} 

I was wondering if it was possible to integrate knitr themes into this minimal working example, similar to what Michael suggested here:

opts_knit$set( out.format="latex" )
knit_theme$set("print")

Adding these two lines to the minimal working example above does not do anything (when I delete all other options in the setup chunk and only include these two lines, syntax highlighting works fine).

Alternatively, if adding themes does not work, is it possible to redefine the default listings style such that it exactly resembles a theme (similar to what hpesoj626 suggested in his first answer, but then with R syntax highlighting of all keywords, numbers, commas…)? I tried writing down all definitions based on Carsten Heinz' drivers manual for the listings package (lstdrvs.pdf here) but did not manage.

Best Answer

I was able to get themes working as follows:

<<echo=FALSE>>=

knit_theme$set("biogoo")
@


<<results='asis', echo=FALSE>>=

x <-1:10
y <- x^2
@