# Handle % character in verbatim inside a grey box

I found this snippet on the internet which is used to produce a text area inside a greybox.

\newcommand\greybox[1]{%
\vskip\baselineskip%
\par\noindent\colorbox{lightgray}{%
\begin{minipage}{\textwidth}#1\end{minipage}%
}%
\vskip\baselineskip%
}


I use it like this:

Normal text.
\greybox{Surrounded text.

Even on multiple lines}


to produce output like this:

Now, I need to put some source code inside this grey box, and I was planning to use verbatim to do so. Problem is: verbatim escapes %-like characters, but when it is inside a \greybox (as defined above) it doesn't behave correctly. Percent signs are interpreted as comments.

\greybox{
\begin{verbatim}
code with a % inside
\end{verbatim}
}


Obviously if I do the opposite, that is placing \greybox inside verbatim, everything gets escaped and \greybox is not interpreted.

Any solutions to the problem? I don't mind using listings or other packages if necessary.

• Have you tried \%? – Corentin Sep 20 '13 at 16:28
• verbatim environments or commands never work inside an argument of a command. But you can get a similar grey box easily with a package like mdframed where you'd have an environment. There verbatim would work. – clemens Sep 20 '13 at 16:37

You mentioned that the listings package is acceptable. Here is an example I used for bash commands.

\usepackage{listings} %for source code format
\lstset{basicstyle=\ttfamily\scriptsize}
\lstdefinestyle{command}{backgroundcolor=\color{lightgray}, frame=none}


Here I define

1. Basic style for global environment: the listing would be script-size font size, with monospaced font family.
2. A style name "command", has background light grey, and has no frame outside the listing.

When using the listing,

\begin{lstlisting}[style=command, caption="choose makefile"]
# cp makef.linux Makefile
\end{lstlisting}


and the style looks like

The listings package can also define language style and recognize comments, such as c-style , python,... Check the list in LaTeX/Source Code Listings.