I struggle with the following listings styles. I have code of two different languages
(R and LaTeX) in my .tex file. As some settings are the same for R listings and
LaTeX listings, I define the style "all". It should be respected by
any \begin{lstlisting} .. \end{lstlisting}. I therefore use style=all in the
lstset definitions for the two languages. Then, there are additional, language
specific settings, which should also be respected. However, as you can see, that
does not quite work. Although I set the keywords in the R listings to just be
if, else, or function, lapply and sapply get a blue color as well. Why? And how
can this be solved?
It seems like I would have to repeat all the definitions in the optional
argument of the lstlisting environment. But it's tedious to do this every
time, that's why I wanted to define styles in the first place. Also, it's not clear to me why a setting like keywords is overwritten since the optional argument of lstlisting does not contain keywords=....
\documentclass{scrartcl}
\usepackage[T1]{fontenc}
\usepackage[american]{babel}
\usepackage{xcolor}
\usepackage{fancyvrb}
\usepackage{listings}
\xdefinecolor{blue}{RGB}{0, 0, 255}
\xdefinecolor{red}{RGB}{255, 0, 0}
% this style should be active for all lstlistings environments
\lstdefinestyle{all}{
basicstyle=\ttfamily\small,
frame=lrtb, framerule=1pt, framexleftmargin=1pt,
showstringspaces=false
}
% this style should be active (additionally to "all") for "input" lstlistings environments
\lstdefinestyle{input}{
commentstyle=\itshape\color{red},
keywordstyle=\color{blue}
}
% listings settings for LaTeX in general [this is not respected!]
\lstset{
language=[LaTeX]TeX,
style=all,
keywords={},
otherkeywords={}
}
% listings settings for R (should hold for all R listings in general)
\lstset{
language=R,
style=all,
literate={<-}{{$\leftarrow$}}2,% this is respected
keywords={if, else, function},% this is not respected
otherkeywords={}
}
\begin{document}
\begin{lstlisting}[{language=[LaTeX]TeX}, style=input]
\begin{enumerate}
\item foo % bar
\end{enumerate}
\end{lstlisting}
\begin{lstlisting}[language=R, style=input]
x <- 4
s <- lapply(1:10, function(z) z+x)
k <- sapply(1:10, function(z) z+2*x) # other case
\end{lstlisting}
\end{document}
lstsetand create two language styles, which you may use then together with the input style. – bloodworks Jan 17 at 16:33