# Change background colour of {verbatim} environment

In an existing document which is not to be modified (except for the preamble), all instances of \begin{verbatim}...\end{verbatim} should have their contents rendered not only in a monospaced font but also on a grey background.

How can this be done?

\documentclass{article}

\usepackage{color}

\let\oldv\verbatim
\let\oldendv\endverbatim

\def\verbatim{\par\setbox0\vbox\bgroup\oldv}
\def\endverbatim{\oldendv\egroup\fboxsep0pt \noindent\colorbox[gray]{0.8}{\usebox0}\par}

\begin{document}

text text text text text
text text text text text
text text text text text
text text text text text
text text text text text
\begin{verbatim}
1
12
123\foo{\ \$ &
}
\end{verbatim}
text text text text text
text text text text text
text text text text text
text text text text text
text text text text text

\end{document}

• However this prevents page breaks. Maybe an approach with mdframed? Jul 4 '12 at 19:45
• @egreg true, I meant to mention that. This question just got asked with a nice looking answer tex.stackexchange.com/questions/15940/… Jul 4 '12 at 19:48