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


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

    int i = 0;
    if(i > 1) {
        // do something

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.


  • 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



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


  alsoletter=0123456789,% to prevent \opstyle from being applied to digits

% Hook into listings

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


int i = 0;
if(i > 1) && (1/2 < 2) {

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

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

      block comment ()={}><&;