5

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 at 10:12
  • Welcome to TeX.SE by the way! – Marijn Jun 2 at 10:12
  • 1
    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 at 10:23
6

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}

MWE output

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.