Listings package: How to highlight math operators?

You can't do this with the emph key. But you can do it using the literate key:

\documentclass{article}
\usepackage{listings,xcolor}
\begin{document}

\lstset{
emph={proc,retp,endp,local}, emphstyle={\color{blue}\textbf},
literate={./}{{{\color{red}./}}}2 {.^}{{{\color{red}.\^{}}}}2 {=}{{{\color{red}=}}}1
}

\begin{lstlisting}
proc(1) = tdist(n,v);
local x, z, z2, u, t;
x=rndn(n,1); 
z=rndn(n,v);
z2=z.^2; 
t=x./((U./v)^(1/2));
retp(t);
endp;
\end{lstlisting}

\end{document}

Note that all the braces are required, since you need to limit the scope of the \color command.

output of code


I would like to add some observations to Alan's answer, since I also ran into that issue, landed here and I see your question is only partially answered.

If you want operators like / or * coloured, too, you might get in trouble with comments in code. As literate will break the way comments will be recognized by the listings package. Here is an example:

/** 
 * This is a 
 * comment ...
 **/
let java = s / c + r * i - p + t    // and this is some code

Screenshot:

screenshot0

Now you want to highlight / and * in the equation, but it breaks the commets:

literate=%
  {+}{{{\color{Red}+}}}1
  {-}{{{\color{Red}-}}}1
  {*}{{{\color{Red}*}}}1
  {/}{{{\color{Red}/}}}1
  {=}{{{\color{Red}=}}}1

Result:

Screenshot1

Obviously, the comments both are broken. Now I played around with adding spaces to the pattern, but with insufficient results.

literate=%
  {\ +}{{{\color{Red}\ +}}}1
  {\ -}{{{\color{Red}\ -}}}1
  {\ *}{{{\color{Red}\ *}}}1
  {\ /}{{{\color{Red}\ /}}}1
  {\ =}{{{\color{Red}\ =}}}1

The block comment is now recognized, but the one-line comment not.

Screenshot2

So, why not appending a whitespace, too?

literate=%
  {\ +\ }{{{\color{Red}\ +\ }}}1
  {\ -\ }{{{\color{Red}\ -\ }}}1
  {\ *\ }{{{\color{Red}\ *\ }}}1
  {\ /\ }{{{\color{Red}\ /\ }}}1
  {\ =\ }{{{\color{Red}\ =\ }}}1

This is the closest I could get to the desired result.

Screenshot3

You can see it somehow shrinks the whitespaces. Some could dive into the dozens of different TeX whitespaces from here. But you'll get an idea.