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 have a global hook (=macro) that should be appended to whenever an environment is executed. (Here, defined by the \bhook-\ehook pair.) However, I was unable to derive a working solution.

\documentclass{article}
\pagestyle{empty}

\usepackage{etoolbox}

\newcommand\myhook{}
\gappto{\myhook}{hooked!}

% How to define these macros?
\newcommand\bhook{\gappto{\myhook}\bgroup}
\newcommand\ehook{\egroup}

% Usage, result should be equivalent to
% \gappto{\myhook}{hook this!}
\bhook{hook this!}\ehook

\begin{document}
  \myhook
\end{document}

Compilation of this code results in an error, as does replacing \bgroup/\egroup with \begingroup/\endgroup or

{\if0=`}\fi

and

\if0=`{\fi}

Is there a way to replace an environment with a command? No, the \NewEnviron from the environ package doesn't work here either. (At least for my special case -- I want to allow pretty much everything inside this environment.)

Is this a deficiency in \gappto, or why do the "usual tricks" not work? Would this be easier to achieve using \def and friends?

EDIT: To further complicate matters, the \bhook and \ehook commands are to be embedded in a custom environment:

\NewDocumentEnvironment{testhook}{}{\bhook}{\ehook}
share|improve this question

1 Answer 1

up vote 2 down vote accepted

Arguments to macros must be enclosed in explicit braces if they consist of more than one token (and are not “delimited” in the macro's definition, but \newcommand defined macros always require arguments in braces).

If you really want a syntax

\bhook Hook this!\ehook

you can say

\long\def\bhook#1\ehook{\gappto{\myhook}{#1}}

so that the argument to \bhook is effectively delimited and ends at the first \ehook token at the same brace level.

A different approach with environ might be

\usepackage{environ}
\NewEnviron{hook}{%
  \expandafter\gappto\expandafter\myhook\expandafter{\BODY}%
}

so that

\begin{hook}
Hook this!
\end{hook}

would be equivalent to the call above.

share|improve this answer
    
Thank you. The \long\def... works for the given example, but I don't seem to be able to use \bhook and \ehook in the begin and end blocks of a custom environment, such as \NewDocumentEnvironment{testhook}{}{\bhook}{\ehook}. Why? –  krlmlr Jul 5 '12 at 10:43
    
@user946850 The argument to \bhook ends when TeX scans \ehook, which doesn't happen because what's seen is only \end{testhook}: TeX doesn't expand tokens when gathering an argument. –  egreg Jul 5 '12 at 10:45

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.