[Tex/LaTex] How to backcolor in verbatim

boxescolorspacingverbatim

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.

\documentclass{article}
\usepackage{xcolor}
\usepackage{alltt}
% Global:
\setlength{\fboxsep}{0pt}
% Better:
\newcommand\hi[2][red]{{%
  \setlength{\fboxsep}{0pt}%
  \colorbox{#1}{#2\strut}%
}}
\begin{document}
\begin{alltt}
hello \colorbox{red}{world\strut} blah
hello world blub
hello \hi{world} blub
\end{alltt}
\end{document}

Another alternative, the best one IHMO, is to compensate for the fboxsep before and after the box:

\documentclass{standalone}
\usepackage{xcolor}
\usepackage{alltt}
% Compensate for fbox sep:
\newcommand\Hi[2][red]{%
  \hspace*{-\fboxsep}%
  \colorbox{#1}{#2}%
  \hspace*{-\fboxsep}%
}
\begin{document}
\begin{alltt}
hello world blah
hello \Hi{world} blah
\end{alltt}
\end{document}

Result:

Result

Related Question