[Tex/LaTex] lstlisting environment as item in description

descriptionlistingsvertical alignment

I would like to show some listings inside a description environment like this:

\usepackage{listings}   % fancy code listings
\usepackage{caption}    % fancy chapters for fancy code listings
\captionsetup[lstlisting]{singlelinecheck=false, margin=0pt, font={sf,sl,footnotesize}}

\lstset{%
  language=[ISO]C++,
  basicstyle=\ttfamily\footnotesize,
  frame=lines,
  keywordstyle=\color{blue}\textbf,
  commentstyle=\color[rgb]{0.0,0.4,0.0}\scriptsize,
  extendedchars=true,         
  breaklines=true             
}

\begin{description}
\item[Example:]
  \begin{lstlisting}
    /* increment a by one */
    a = a + 1
  \end{lstlisting}
\end{description}

But for some reason the caption 'Do not do this' is always visible above the \item entry 'Example:'. This problem however vanishes if I write something between \item and the lstlisting environment like this:

\begin{description}
\item[Example:] Bad code example
  \begin{lstlisting}
    /* increment a by one */
    a = a + 1
  \end{lstlisting}
\end{description}

I would like to get this to work without the extra text, 'Bad code example' in this case.

I tried to use \vspace{} and \phantom{text} instead of extra text, but both seem to be ignored.

Could someone please help me out?

Best Answer

Adding a \leavevmode helps here:

Sample output

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}   % fancy code listings
\usepackage{caption}    % fancy chapters for fancy code listings
\captionsetup[lstlisting]{singlelinecheck=false, margin=0pt, font={sf,sl,footnotesize}}

\lstset{%
  language=[ISO]C++,
  basicstyle=\ttfamily\footnotesize,
  frame=lines,
  keywordstyle=\color{blue}\textbf,
  commentstyle=\color[rgb]{0.0,0.4,0.0}\scriptsize,
  extendedchars=true,         
  breaklines=true             
}

\begin{document}

\begin{description}
\item[Example:]\leavevmode
  \begin{lstlisting}[caption=Do not do this]
    /* increment a by one */
    a = a + 1
  \end{lstlisting}
\end{description}
\end{document}
Related Question