[Tex/LaTex] Listings package: How to highlight math operators

highlightinglistings

I am using the listings package to include GAUSS code to Latex.

E.g. like this:

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

\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}

While the strings (proc, retp etc.) are highlighted, the math operators (=, *, /) are not. What am I doing wrong here?

Best Answer

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