# Put colored text inside a lstlisting

So I've been looking for a way to color text inside a lstlisting. There are already several questions answere. E.g. here: How can I highlight some lines from source code?

All solutions I've found have the same approach. Just use an escape character and colour the text. However, if I do this my font is not monospace anymore. Is there a way to fix this? Neither setting font to \ttfamily or using \verb/\texttt did work.

Here is an example of what's going wrong:

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

\begin{document}

\begin{lstlisting}[escapeinside={(*@}{@*)}, basicstyle=\tiny\ttfamily]
this is monospace
as you can see here
(*@\color{orange}not monospace anymore@*)
\end{lstlisting}

\end{document}


Cheers
Pascal

• The listings manual says (section 5.12): Note: Any escape to LaTeX may disturb the column alignment since the package can’t control the spacing there. so probably there is no easy solution. – Marijn Jun 2 '19 at 10:12
• Welcome to TeX.SE by the way! – Marijn Jun 2 '19 at 10:12
• But if you are willing to make the listings font a bit more narrow (while it still remains monospaced, i.e., every character and space has the same width) you can do something like \begin{lstlisting}[escapeinside={(*@}{@*)},basicstyle=\tiny\ttfamily,columns=fixed,basewidth=.5em] as in tex.stackexchange.com/questions/17646/…. – Marijn Jun 2 '19 at 10:23

You can get around the problem with \aftergroup.

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

\def\speciallstcolor{\begingroup\color{orange}}
\def\endspeciallstcolor{\endgroup}

\begin{document}

\begin{lstlisting}[escapeinside={(*@}{@*)}, basicstyle=\tiny\ttfamily]
this is monospace
as you can see here
(*@\aftergroup\speciallstcolor@*)not monospace anymore(*@\aftergroup\endspeciallstcolor@*)
(that was a lie)
\end{lstlisting}

\end{document}