Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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!

share|improve this question
    
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
add comment

2 Answers

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}

enter image description here

share|improve this answer
add comment

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}

Result

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.