[Tex/LaTex] create new environment with mdframed and listing

environmentslistingsmdframed

I have some code snippets using a lstlisting environment in a mdframed environment:

\begin{mdframed}[roundcorner=5pt]
\begin{lstlisting}[mathescape, caption={some snippet}, label=lst:snippet1, numbers=left,numberstyle=\tiny ,stepnumber=2, showstringspaces=false, basicstyle=\small, xleftmargin=-5pt, frame=b]
// blabla some code
\end{lstlisting}
\end{mdframed}

Now I don't want to type all the arguments every time I write a snippet, so I thought I could just create a new environment like this:

\newenvironment{lst}[2]
{%
\begin{mdframed}[roundcorner=5pt]%
\begin{lstlisting}[mathescape, caption={#1}, label=#2, numbers=left,numberstyle=\tiny ,stepnumber=2, showstringspaces=false, basicstyle=\small, xleftmargin=-5pt, frame=b]%
}%
{%
\end{lstlisting}%
\end{mdframed}%
}

but when I try to use it it won't compile with lots of error messages.

\begin{lst}{some caption}{lst:label1}
    // blabla code
\end{lst}

Why doesn't it work and how can I make it work?

edit: I just found \lstnewenvironment for creating a new listing environment. But still I can't figure out how to encapsulate both, mdframed and lstlisting, in one environment statement.

edit2: minimal (non-)working example:

\documentclass{scrreprt}

\usepackage{listings}
\usepackage[framemethod=TikZ]{mdframed}

\newenvironment{lst}[2]
{%
\begin{mdframed}[roundcorner=5pt]%
\begin{lstlisting}[mathescape, caption={#1}, label=#2, numbers=left,numberstyle=\tiny ,stepnumber=2, showstringspaces=false, basicstyle=\small, xleftmargin=-5pt, frame=b]%
}%
{%
\end{lstlisting}%
\end{mdframed}%
}

\begin{document}

A framed listing %\ref{lst:label1}:
\begin{lst}{fancy title}{lst:label1}
// initializing a
int a = 5;
\end{lst}

\end{document}

Best Answer

You have to use \lstnewenvironment:

\documentclass{scrreprt}

\usepackage{listings}
\usepackage[framemethod=TikZ]{mdframed}

\lstnewenvironment{lst}[2]
  {%
   \mdframed[roundcorner=5pt]%
   \lstset{
     mathescape,
     caption={#1},
     label=#2,
     numbers=left,
     numberstyle=\tiny,
     stepnumber=2,
     showstringspaces=false,
     basicstyle=\small,
     xleftmargin=-5pt,
     frame=b,
   }%
  }
  {\endmdframed}

\begin{document}

A framed listing \ref{lst:label1}:
\begin{lst}{fancy title}{lst:label1}
// initializing a
int a = 5;
\end{lst}

\end{document}

enter image description here

Related Question