Listings Environment – How to Use Listing in newenvironment

environmentslistings

I am trying to do a new environment or command (i tried both) where i can put in the name, description and code of a Method in c++ and it gives me a new section with the MethodName, the code listed and the description below. But i am not able to use the listings environment in a new command or new environment.. Consider my MWE

 \documentclass[a4paper,11pt]{article}
\usepackage{listings}

\newcommand{\method}[3]
{
\section{#1}\label{#1}
\begin{lstlisting}
#2
\end{lstlisting}
#3
}

 \begin{document}
 \method{MethodName}{Method Void MethodName()}{Description of the Method blablabla}
 \end{document}

How can I fix this?

I would prefer to do it using a macro since I don't need an ending.

Best Answer

Verbatim material can't be placed in a macro argument because then the material got already parsed by TeX and the switching to verbatim mode comes to late. For custom environments listings provides \lstnewenvironment which also allows to add your own code before and after the verbatim material. There is unfortunatly no equivalent for macros.

This solution requires to provide the description before the code, store it in a temporary macro and place that it after the code.

\documentclass{article}
\usepackage{listings}

\lstnewenvironment{method}[2]
  {\section{#1}\label{#1}\def\MethodDescription{#2}}
  {\MethodDescription}

\begin{document}

\begin{method}{MethodName}{Description of the Method blablabla}
Method Void MethodName()
\end{method}

\end{document}
Related Question