# How to pass contents of environment (declared with \newenvironment in LaTeX2e) as argument to that environment?

I know there's an option in expl3, but how can I do the same in LaTeX2e (or TeX)?

\newenvironment*{myEnv}[1][]{}{}
\begin{myEnv}
I first need to pass this to this environment as an argument.
\end{myEnv}

• This is what the environ package does, the body of the environment is then stored in \BODY. – user194703 Nov 17 '19 at 7:31
• You can do everything what packages do by copying the contents of these packages in the preamble (sandwiched between \makeatletter and \makeatother, of course). I do not know what defines an "official" package, but environ is definitely a very nice and robust package that gets widely used. The source of the package is not very long, so you can have a look at it. – user194703 Nov 17 '19 at 7:38
• Example: \documentclass{article} \usepackage{environ} \NewEnviron{myEnv}[1][]{\underline{\BODY}} \begin{document} \begin{myEnv} I first need to pass this to this environment as an argument. \end{myEnv} \end{document} – user194703 Nov 17 '19 at 7:40
• @Schrödinger'scat, for some reason my custom macro can't break down this \BODY parameter, but can break down regular text into letters. In other words \BODY doesn't behave like regular text. – bp2017 Nov 17 '19 at 7:51
• Well, hard to tell what is going on without seeing your custom macro. You may have to replace \MyCustomMacro{\BODY} by \edef\temp{\noexpand\MyCustomMacro{\BODY}}\temp, but really hard to say. – user194703 Nov 17 '19 at 7:55

The idea of 'collecting the body' is nowadays available in xparse

\documentclass{article}
\usepackage{xparse}
\begin{document}
\NewDocumentEnvironment{myEnv}{O{}+b}{The argument was '#2'}{}
\begin{myEnv}
I first need to pass this to this environment as an argument.
\end{myEnv}
\end{document}


Here, #2 is the second argument (the body).

As pointed out in comments, the long-standing environ package does the same but provides the result as \BODY.

• @bp2017 You need a more sophisticated loop to deal with spaces: there are several approaches (and examples on the site), depending on the other requirements (working by expansion, treatment of braces, ...). I'll adjust my answer to take \par tokens. – Joseph Wright Nov 17 '19 at 8:18
• When I pass \BODY to \zStart as \zStart{\BODY} I don't get processed text, it's as if \zStart didn't work. – bp2017 Nov 17 '19 at 8:20
• @bp2017 Well no, because there is only one token, \BODY. You'll need to expand it once: \expandafter\zStart\expandafter{\BODY}. TeX macros receive the tokens you pass as written, not the expansion of the tokens. I think that was mentioned in comments on the question. – Joseph Wright Nov 17 '19 at 8:23
• – Joseph Wright Nov 17 '19 at 8:39