# Using environment argument in new macro definition

I'd like to be able to define an environment that takes a single argument and be able to use that argument to redefine an existing macro such that the argument of the environment gets used automatically as the argument of the macro. Like so...

\newcommand{\argmacro}[1]{<do something with #1>}

\newenvironment{myenvironment}
{\renewcommand{\arglessmacro}{\argmacro{<the sole argument of myenvironment>}}}
{}


I'd basically like to define some text as the 'subject' of an environment such that I can perform my usual macros without having to duplicate the text each time I want to call it. Is there a clean way to reference the argument of myenvironment within the renewcommand definition? Thanks!

• Would you like to add an intended application? As "argument" of myenvironment are you meaning what's between \begin{myenvironment} and \end{myenvironment}? – egreg Nov 29 '12 at 23:28

If I have you understood correctly then the environment myenvironment defines a macro \arglessmacro that applies \argmacro on the environment body, then this is implemented by the following example.

• Package environ is used to define an environment that grabs its body.
• The detour via token register prevents that the environment body is expanded prematurely. An alternative is using eTeX's \unexpanded.
• \arglessmacro is defined in global scope to escape the environment grouping level.

Example file:

\documentclass{article}
\usepackage{environ}

\newcommand{\argmacro}[1]{%
\textbf{#1}%
}
\NewEnviron{myenvironment}{%
\toks0=\expandafter{\BODY}%
\xdef\arglessmacro{%
\noexpand\argmacro{\the\toks0}%
}%
}

\begin{document}
\begin{myenvironment}
Hello World
\end{myenvironment}
\arglessmacro

\begingroup
\renewcommand{\argmacro}[1]{\textit{[#1]}}%
\arglessmacro
\endgroup

\begin{myenvironment}
Foo bar
\end{myenvironment}
\arglessmacro

\end{document}


I'm not entirely clear on what you want: Is this the general idea:

\documentclass{article}
\newcommand{\mymacro}{default definition}
\newenvironment{myenv}[1]
{\renewcommand{\mymacro}{#1}}
{}
\begin{document}

\mymacro

\begin{myenv}{hello world}
\mymacro

And then someother contents
\end{myenv}

\mymacro

\end{document}