2

Consider the following example:

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor}

\lstset{language=R,
    morecomment=[l]{>},
    commentstyle=\color{blue},
    alsoletter={*}
    }
\begin{document}

\begin{lstlisting}
> q_A=0:6
> q_B=6-q_A
> N_A=6
> N_B=4
> (factorial(q_A+N_A-1)/(factorial(q_A)*factorial(N_A-1)))
[1]   1   6  21  56 126 252 462
\end{lstlisting}

\end{document}

The above code compiles to a simplified version of the image below (from the main document):

http://i.imgur.com/D3rkYpZ.png?1

When compiling this, the asterisk *, the underscore _, and the slash / are all still treated as special characters that should not be highlighted. I've already included the alsoletter key to include e.g. *, but the key seems to be ignored. How can I get the entire line starting with a > to be blue?

I've already checked e.g. How can I get identifier style to apply to '%' (in a Perl listing)? for special identifiers, but that doesn't seem to work here. Neither does the "normal" approach of simply using alsoletter=* or alsoletter={/}, etc.

Where is it going wrong?

1
2

The problem comes from how the listings language for R is defined. If you look up the definition in lstdvrs.dtx (search for \lst@definelanguage{R}), you'll see that *, /, and _ are all defined as "otherkeywords":

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

I refer you to this other answer of mine to understand why this is problematic, and what can be done about it.

I don't think you actually want to declare * as a "letter", here (at least, that's not necessary for * to be coloured in blue like the rest of the line). There are nasty side effects to that; see the side note in https://tex.stackexchange.com/a/164634/21891.

enter image description here

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor}

\lstset{
    language=R,
    otherkeywords={},
    otherkeywords={!,!=,~,$,\&,\%/\%,\%*\%,\%\%,<-,<<-},
    morecomment=[l]{>},
    commentstyle=\color{blue},
}
\begin{document}

\begin{lstlisting}
> q_A=0:6
> q_B=6-q_A
> N_A=6
> N_B=4
> (factorial(q_A+N_A-1)/(factorial(q_A)*factorial(N_A-1)))
[1]   1   6  21  56 126 252 462
\end{lstlisting}

\end{document}
1
  • This is too easy... – 1010011010 Aug 9 '14 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.