7

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?

1 Answer 1

7

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .