listings: Changing the meaning of underscore for the language R (customizing a language)

The R language highlighting is defined in lstdrvrs.dtx. If you look there, you will find

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

So you just need to add that to your \lstset to overwrite the defaults, but with the underscore and slash removed:

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

Doing this will prevent the slash and underscore from ever being highlighted, though, so this won't work if you need them to be highlighted in other contexts. Just to make things uniform between division and multiplication, you may also wish to remove the asterisk * from the list. (You might need to remove a few other things as well to keep math in general uniform; I don't know R.)

Unfortunately, Pygments doesn't seem to offer as much as listings in terms of keyword highlighting for R, so if that's what you need, Pygments-based highlighting packages like minted and pythontex may not be an alternative (at least, not without writing a custom lexer).


You can seek shelter inside escapeinside option as below:

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}
\lstset{
    language=R,
    basicstyle=\ttfamily,
    keywordstyle=\color{red}\bfseries,
    escapeinside=||
}

\begin{document}

\begin{lstlisting}
my|\_|Variable <- qnorm(0.05/2, mean=0, sd=1)
# even inside comments |/| doesn't highlight.
>> 1.959964
\end{lstlisting}

\end{document}

enter image description here

Tags:

Listings