I have some code I want to typeset as verbatim (lstlisting would be ok as well) – but I want to highlight some parts of it via a different background color, i.e. something like this:
\begin{verbatim}
hello \colorbox{red}{world} blah
hello world blub
\end{verbatim}
Where colorbox
should not be interpreted verbatim and should not introduce additional horizontal spaces, i.e. blah and blub should be correctly aligned (like without any highlighting).
I tried the Verbatim
and lstlisting
environments like this:
\begin{lstlisting}[escapechar=\%]
or
\begin{Verbatim}[commandchars=\\\{\}]
in combination with a then escaped colorbox
command – the highlighting works – but the additional spaces are introduced and screw up the character alignment.
How can I do it right?
Best Answer
I think the
alltt
environment from the package with the same name is better suited here. It makes everything verbatim except\
,{
and}
, similar to\begin{Verbatim}[commandchars=\\\{\}]
.The mentioned added space is due to the used
\fboxsep
which makes the box bigger. You can avoid this by setting this value to zero, either globally or locally using a own macro. This however makes the box very tight on all four sites. An added\strut
makes sure that it has always the same height and depth.Another alternative, the best one IHMO, is to compensate for the
fboxsep
before and after the box:Result: