# Highlighting R code in LaTeX using SweaveListingUtils

It is well known that you can use Sweave to integrate R code into a LaTeX document. However, how do we highlight R code in LaTeX? LaTeX got its own powerful package listings that can highlight source code from various languages. Moreover, the package SweaveListingUtils provides utilities for defining R as a listings “language”. To highlight your R code in your Sweave document you have to include the following code chunk:

\RequirePackage{listings}
\RequirePackage{Sweave}

\begin{Scode}{label=SweaveListingsPreparations , results=tex , echo=FALSE}
require(SweaveListingUtils)
SweaveListingOptions(Rcolor=c(0,0,0), overwrite=TRUE,
Keywordstyle="{\\footnotesize\\color{blue}}",
interm.Keywordstyle="{\\footnotesize\\color{blue}}",
Rset=list("fancyvrb" = "true", "language" = "R", "escapechar" = "",
"basicstyle" = "{\\footnotesize\\color{Rcolor}}",
"keywordstyle" = "{\\footnotesize\\color{blue}}",
"literate" = "{<-}{{$\\leftarrow$}}2{<<-}{{$\\twoheadleftarrow$}}2",
"alsoother" = "{$}", "alsoletter" = "{.<-}", "otherkeywords" = "{!,!=,~,$,*,\\&,\\%/\\%,\\%*\\%,\\%\\%,<-,<<-,/}")
)
SweaveListingPreparations()
## Add the packages you use and want to get highlighted
library(RODBC)
library(RMySQL)
\end{Scode}

or alternative

\RequirePackage{listings}
\RequirePackage{Sweave}

<<label=SweaveListingsPreparations , results=tex , echo=FALSE>>=
require(SweaveListingUtils)
SweaveListingOptions(Rcolor=c(0,0,0), overwrite=TRUE,
Keywordstyle="{\\footnotesize\\color{blue}}",
interm.Keywordstyle="{\\footnotesize\\color{blue}}",
Rset=list("fancyvrb" = "true", "language" = "R", "escapechar" = "",
"basicstyle" = "{\\footnotesize\\color{Rcolor}}",
"keywordstyle" = "{\\footnotesize\\color{blue}}",
"literate" = "{<-}{{$\\leftarrow$}}2{<<-}{{$\\twoheadleftarrow$}}2",
"alsoother" = "{$}", "alsoletter" = "{.<-}", "otherkeywords" = "{!,!=,~,$,*,\\&,\\%/\\%,\\%*\\%,\\%\\%,<-,<<-,/}")
@