[Tex/LaTex] Why does the listings package not highlight operators correctly

listings

I am typing some notes about the programming language R.
Unfortunately, the listings package seems to recognize some math operators,
but not others.
For instance, in the example below,
* and %% are typeset in a different color as desired,
but %/% and + and - and ^ are not typeset in a different color.

\documentclass[12pt]{scrartcl}

\usepackage{xcolor}

\usepackage{listings}
\lstset{
language=R,
basicstyle=\footnotesize\ttfamily,
backgroundcolor=\color{white!95!black},
commentstyle=\color{green},
keepspaces=true,
keywordstyle=\color{blue}}

\begin{document}

You can use R as a simple calculator:
\begin{lstlisting}
> # The hash symbol '#' will comment out the rest of the line
> 2 + 3
[1] 5
> 7 - 3
[1] 4
> 4 * 5
[1] 20
> 3^4          # Exponentiation
[1] 81
> 43 %% 10     # Modulo operator
[1] 3
> 43 / 10      # Floating point division
[1] 4.3
> 43 %/% 10    # Integer division
[1] 4
\end{lstlisting}

\end{document}

enter image description here

How do I get an output where all of the math operators are typeset in blue?

Best Answer

For the R language, listings defines:

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

so neither + nor - nor ^ are listed, they have to be added.

Regarding %/% it seems that only adding \% before it in otherkeywords let it work as expected.

In other words, adding:

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

to your \lstset does what you want.

\documentclass[12pt]{scrartcl}

\usepackage{xcolor}

\usepackage{listings}
\lstset{
language=R,
basicstyle=\footnotesize\ttfamily,
backgroundcolor=\color{white!95!black},
commentstyle=\color{green},
keepspaces=true,
otherkeywords={!,!=,~,$,*,\&,+,-,^,\%,\%/\%,\%*\%,\%\%,<-,<<-,_,/},
keywordstyle=\color{blue}}

\begin{document}

You can use R as a simple calculator:
\begin{lstlisting}
> # The hash symbol '#' will comment out the rest of the line
> 2 + 3
[1] 5
> 7 - 3
[1] 4
> 4 * 5
[1] 20
> 3^4          # Exponentiation
[1] 81
> 43 %% 10     # Modulo operator
[1] 3
> 43 / 10      # Floating point division
[1] 4.3
> 43 %/% 10    # Integer division
[1] 4
\end{lstlisting}

\end{document} 

enter image description here

Related Question