[Tex/LaTex] How to highlight operators and brackets in a C listing

colorhighlightinglistings

How can I apply a certain style to C (or, well, any other programming language) operators? So that when I write

\begin{lstlistings}[language=C++]
    int i = 0;
    if(i > 1) {
        // do something
    }
\end{lstlisting}

I'll get = and > (and other operators, and preferably also ( and ), { and }) highlighted in red, for instance? I managed to treat those characters like other keywords (bold and blue in my case), but this isn't the behavior I want, and it destroys comment definitions.

Best Answer

Here is a workaround that doesn't break one-line comments and only applies the desired style to operators outside comments and strings.

Caveats:

  • I've had to define all digits as "letters" to prevent my operator style from being applied to them; there may be side effects associated with that.
  • Outside comments and strings, the operator style will be applied to all characters that listings classifies as "other".

enter image description here

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}

\newcommand\opstyle{\color{red}} % <--- customise operator style here

\makeatletter

\lstset
{%
  language=C++,
  alsoletter=0123456789,% to prevent \opstyle from being applied to digits
}

% Hook into listings
\lst@AddToHook{OutputOther}{\ProcessOther@silmeth}

% helper macro
\newcommand\ProcessOther@silmeth
{%
  \ifnum\lst@mode=\lst@Pmode%     % If we're in `Processing' mode...
    \def\lst@thestyle{\opstyle}%  % ... redefine the style locally
  \fi%
}

\makeatother

\begin{document}
\begin{lstlisting}[]
int i = 0;
if(i > 1) && (1/2 < 2) {

    // one-line comment ()={}><;&

    printf("string: ()={}><;&");

    /*
      block comment ()={}><&;
    */
}
\end{lstlisting}
\end{document}