# Why does the listings package not highlight operators correctly?

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},
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}


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

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},
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}


• This works, but you forgot a small detail of adding in ^ in the otherkeywords. :-) – I Like to Code Jul 6 '17 at 6:14
• @ILiketoCode You are right, I didn't noticed it. Added it in the answer. – Arzigoglu Jul 6 '17 at 6:17