[Tex/LaTex] Various \textcolor within lstlisting

colorlistings

How can you set various words in your lstlisting to various text colors?

For instance, I want the word "fail" to appear in red and the word "pass" in green.

I have the feeling there should be some easy escape possibility!?

What did not work

I tried using the parameter

escapeinside={(*@}{@*)}

and then within the lstlisting

(*@\color{red}@*) fail (*@\color{black}@*)

But this has no effect.

Therefore, I've tried

$\textcolor{red}{\lstinline!fail!}$

but listings does not like nested lstinline within lstlistings.

Complex solution

a not quite suitable solution is described in \textcolor within lstlisting?: it is intended for one color only, so I would have to add something like

moredelim=**[is][\color{red}]{@}{@},

for every color I use 🙁

Best Answer

The escaped part is a group, so color command issued there are lost at the end. There is no official way to set a color globally but you can look here How can I change the text color in such a way that the effect transcends groups?.

Beside this you can try to set the color with \aftergroup (but color of keywords will overwrite this settings):

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{listings}

\begin{document}

\def\redcolor{\color{red}}
\def\blackcolor{\color{black}}
\begin{lstlisting}[escapechar=@]
#@\aftergroup\redcolor@include@\aftergroup\blackcolor@ <fstream.h>
void main () {
fail
pass
}
\end{lstlisting}

\end{document}
Related Question