8

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!

Werner
  • 603,163
Rik
  • 115

2 Answers2

11

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}
David Carlisle
  • 757,742
  • Thank you David! That was what I was looking for! I will play around with some settings as width and coloring for the code listing as suggested by @hpesoj626. Thank you both. – Rik Apr 10 '13 at 10:23
0

This is what I usually use.

\documentclass[12pt]{article}
\usepackage[margin=1.6cm]{geometry}
\usepackage{amsmath, amssymb}
\usepackage{xcolor}
\usepackage{listings}
\lstset
{
    language=[LaTeX]TeX,
    breaklines=true,
    basicstyle=\tt\normalsize,
    keywordstyle=\color{blue},
    identifierstyle=\color{magenta},
    frame = single
}

Note the use of frame = single as an argument. Using frame = true will get you nowhere. Just as a tip