[Tex/LaTex] Managing keyword colors with listings

listings

I am working in a document that presents R code with the listings package, and I am having trouble with the font color with some characters and words that apparently are taken as first keywords.

In this example

\documentclass{article}
\usepackage{xcolor} 
\usepackage{listings}
\lstset{
  language=R,
  keywordstyle=\color{blue},
  keywordstyle=[2]{\color{red}},
  commentstyle=\color{gray},
  backgroundcolor=\color{gray!25},
  morekeywords=[2]{arg,pos},
  moredelim=[is][\color{violet}]{''}{''}
}
\begin{document}
\begin{lstlisting}
# define one / two / three characteristics
install(''"tree/site"'', arg = 1, pos = "t")
\end{lstlisting}
\end{document}

that produces:
listings output

Here the slashes are printed in blue both in the comments and inside the quotes, and they do not respect the colors defined in lstset.

Besides pos that has explicitly defined as a keywordstyle [2] in red appears in blue.

I appreciate your help or suggestions.

Best Answer

pos already is defined as keyword. You can remove before defining it new:

deletekeywords = {pos}

/ also is defined as keyword but with otherkeywords. Unfortunately there is no deleteotherkeywords but you can set the list anew leaving / out:

otherkeywords = {!,!=,~,$,*,\&,\%/\%,\%*\%,\%\%,<-,<<-,_}

The original definition of R where I found the above can be found in the file lstlang3.sty.

Full example:

\documentclass{article}
\usepackage{xcolor} 
\usepackage{listings}
\lstset{
  language=R,
  deletekeywords={pos},
  otherkeywords={!,!=,~,$,*,\&,\%/\%,\%*\%,\%\%,<-,<<-,_},
  keywordstyle=\color{blue},
  keywordstyle=[2]{\color{red}},
  commentstyle=\color{gray},
  backgroundcolor=\color{gray!25},
  morekeywords=[2]{arg,pos},
  moredelim=[is][\color{violet}]{''}{''}
}
\begin{document}
\begin{lstlisting}
# define one / two / three characteristics
install(''"tree/site"'', arg = 1, pos = "t")
\end{lstlisting}
\end{document}

enter image description here

Related Question