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}
\long\def... works for the given example, but I don't seem to be able to use\bhookand\ehookin the begin and end blocks of a custom environment, such as\NewDocumentEnvironment{testhook}{}{\bhook}{\ehook}. Why? – krlmlr Jul 05 '12 at 10:43\bhookends 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 05 '12 at 10:45