I used the great answer from @Sharpie on 19 Jan 2012 Getting Sweave code chunks to stay inside page margins? to get linebreaks in the R-code, but how can there be code highlighting (colors) too?
\documentclass[a4paper]{article}
\usepackage{listings}
\usepackage{inconsolata}
<<echo=FALSE>>=
options(width=60)
listing <- function(x, options) {
paste("\\begin{lstlisting}[basicstyle=\\ttfamily,breaklines=true]\n",
x, "\\end{lstlisting}\n", sep = "")
}
knit_hooks$set(source=listing, output=listing)
@
\title{Function listings with linebreaks and code highlighting}
\begin{document}
\maketitle
Two ways of printing the code.
<<tidy=TRUE,highlight=FALSE>>=
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}
Best Answer
You can directly set your
listings
settings in your.Rnw
file. Here I have defined a new styleRsetings
.where the colors are defined as follows.
A few words about the key-value list in the
\lstset
."
are typeset in\color{delimcolor}
otherkeywords
andmorekeywords
if you are using more of these in your actual document. (Sorry, I am not yet very familiar with R since I am just starting with it.)listings
package or you can type and entertexdoc listings
in your terminal.With these, you can now re-write your
.Rnw
file asAnd here is the output.