13

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!

  • You are trying to write code from a programming language? What programming language? – OSjerick Nov 11 '13 at 17:54
19

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

  • The red text is not in monospaced font. You might want to use \texttt{\textcolor{red}{red text}. (Ideally in verbatim instead of lstlisting - to have matching fonts.) – Janine Aug 8 '16 at 13:26
  • @JanineDaum This type of escaping won't work in the verbatim environment, but you can of course make listings use the typewriter font by saying basicstyle=\ttfamily in \lstset. Panichi didn't say anything about what kind of settings he was using for his listings, which is probably why I didn't add any other settings. For the example in the post, adding columns=flexible or columns=fullflexible would make the letter spacing more similar to the red text. – Torbjørn T. Aug 8 '16 at 21:19
  • It would of course have to go outside of \verb, like\verb+This is normal text, +\texttt{\textcolor{red}{red text, }}\verb+more.+ – Janine Aug 12 '16 at 13:24
  • Torbjorn, good idea of having listings use \ttfamily! – Janine Aug 12 '16 at 13:32
  • What if the code I want to have with different color spans over multiple lines? – Andry Sep 26 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.