[Tex/LaTex] color a text line in a code {lstlisting}

colorlistings

I try to use the package xcolor into a lstlisting code as follows:

\begin{lstlisting}

\color{red}{text...}

\end{lstlisting}

but I can't color the "text…" comments.

Someone could help me, please?

Thanks!

Best Answer

lstlisting is a verbatim environment, so it is designed to print exactly what you write in it, not evaluating any of the macros inside it. However, you can define special delimiters for bits of code that should be evaluated, by using escapeinside={<opening delim>}{<closing delim>} in \lstset. Example:

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstset{escapeinside={<@}{@>}}
\begin{document}
\begin{lstlisting}
This is normal text.
<@\textcolor{red}{red text}@>
More.
\end{lstlisting}
\end{document}

enter image description here