[Tex/LaTex] lstlisting in a box

boxescolorlistingsverbatim

My problem is that I am trying to write a document with coloured sections for examples. Examples can contain code listings. Somehow I can't seem to combine a background colouring with a listing, or even verbatim.

An example of what I tried is this:

\colorbox{lightgray}{
\begin{minipage}{4cm}
An example text

\begin{lstlisting}[frame=single,language=XML,caption=A Fibonaci example\label{code:fibonaci}]
  <xml></xml>
\end{lstlisting}   

Some more text
\end{minipage}  
}

Any ideas are appreciated!

Best Answer

Please always post complete documents showing packages used. The problem is that you can not use verbatim like constructs in the argument of a macro like \colorbox. lrbox environment was introduced for this reason

enter image description here

\documentclass{article}
\usepackage{color,listings}
\definecolor{lightgray}{rgb}{.7,.7,.7}
\newsavebox\lstbox
\begin{document}

\begin{lrbox}{\lstbox}\begin{minipage}{4cm}
An example text

\begin{lstlisting}[frame=single,language=XML,caption=A Fibonaci example\label{code:fibonaci}]
  <xml></xml>
\end{lstlisting}   

Some more text
\end{minipage}\end{lrbox}  

\colorbox{lightgray}{\usebox\lstbox}


\end{document}