# NewEnviron, \BODY and lstlisting [duplicate]

I was trying to understand egreg's answer to Hide content to show later, and I noticed that there were some problems when using lstlisting or tcblisting environments inside the solution environment proposed by egreg, while other environments like figureor proof seem to work fine.

I looked to several related questions (like Using an environ environment with \newenvironment and How to remove \BODY defined in the algorithmic package?), and I think (but am not sure) that the conflict comes from the listing package which possibly defines a \BODY command, as does environ.

For example, a minimal non working example is the following :

\documentclass[10pt]{book}
\usepackage{environ}
\usepackage{listings}

\NewEnviron{solution}{\BODY}

\begin{document}

\begin{solution}
This is an environment containing code.
\begin{lstlisting}
My code
\end{lstlisting}
\end{solution}

\end{document}


With this code, I have the following error : Text dropped after begin of listing

Where does this error comes from, and how can I avoid it ? My goal would be to have a solution environment, defined with \NewEnviron, and which could contain an lstlistingor a tcblisting environment.

Note : I am aware that in the code I have defined, I could use \newenvironment instead of \NewEnviron, but the environment I want (which is exactly the one in egreg's answer to Hide content to show later) really needs the features of \NewEnviron, especially the \BODY macro, since I want to store the content of \solution in order to display it later.

• You can't have verbatim material like lstlisting inside of another command. Environments defined with environ look like environments but in many aspects behave like commands => you can't have verbatim material in an environment defined with environ – clemens Jul 27 '15 at 10:22
• – clemens Jul 27 '15 at 11:51
• Thanks a lot, my guess for the origin of the problem was wrong, and I realize that my question is a total duplicate. (For the sake of completeness, the solution uses \cprotectEnv). – mvienney Jul 27 '15 at 11:53
• An alternative solution with tcolorboxes and tcblistings can be found in tex.stackexchange.com/a/257455/1952 – Ignasi Jul 28 '15 at 11:57

If you are able to settle for verbatim code that is not syntax highlighted, and which does not require page breaking, you could place it in a verbatimbox prior to entering your newly defined solution environment.

Of course, by that point, it is in a box, and not available as text.

\documentclass[10pt]{book}
\usepackage{environ}
%\usepackage{listings}
\usepackage{verbatimbox}
\NewEnviron{solution}{\BODY}

\begin{document}

\begin{verbbox}
c My code
i = 0
do while(i .lt. 10)
print *, i
i = i + 1
end do
stop
\end{verbbox}
\begin{solution}
This is an environment containing code.

\theverbbox
\end{solution}

\end{document}