[Tex/LaTex] Adding a Caption to \lstnewenvironment using \mdframed

captionslistingsmdframedsourcecode

I found on the Internet the piece of LaTeX code I really liked :

\documentclass{article}
\usepackage{listings,mdframed,xcolor}

\definecolor{codeBackground}{rgb}{0.9, 0.9, 0.8}
\lstnewenvironment{mylisting}{
  \lstset{
    moredelim=**[is][\bfseries]{|}{|},% bold everything in between ||
    moredelim=**[is][\itshape]{*}{*}  % italic everything in between **
  }%
\mdframed[backgroundcolor=codeBackground,shadow=true,shadowsize=2pt,shadowcolor=black!30]%
}{%
  \endmdframed\ignorespaces
}

\begin{document}


\begin{mylisting}
public |class| Test {
  public *static |void|* main(String[] argumente) {
    System.out.println("Hallo Welt!");
  }
}
\end{mylisting}

\end{document}

I would like to add numbered caption to this source code, but neither

\begin{mylisting}{caption=code caption}
public |class| Test {
  public *static |void|* main(String[] argumente) {
    System.out.println("Hallo Welt!");
  }
}
\end{mylisting}

nor:

\begin{mylisting} \caption{code caption}
public |class| Test {
  public *static |void|* main(String[] argumente) {
    System.out.println("Hallo Welt!");
  }
}
\end{mylisting}

does work. Any ideas?

Best Answer

You can require a new parameter to your environment which contains the caption, and use \captionof from the caption package:

enter image description here

Code:

\documentclass{article}
\usepackage{listings,mdframed,xcolor}
\usepackage{caption}

\definecolor{codeBackground}{rgb}{0.9, 0.9, 0.8}
\lstnewenvironment{mylisting}[1]{
  \lstset{
    moredelim=**[is][\bfseries]{|}{|},% bold everything in between ||
    moredelim=**[is][\itshape]{*}{*}  % italic everything in between **
  }%
\mdframed[backgroundcolor=codeBackground,shadow=true,shadowsize=2pt,shadowcolor=black!30]%
}{%
  \endmdframed
  \captionof{lstlisting}{#1}
  \ignorespaces
}

\begin{document}


\begin{mylisting}{My Caption}
public |class| Test {
  public *static |void|* main(String[] argumente) {
    System.out.println("Hallo Welt!");
  }
}
\end{mylisting}
\end{document}