# How to add a hook to a macro

LaTeX uses hooks extensively, one method employed is the command g@addto@macro. It is defined in source2e as:

 \long\def\g@addto@macro#1#2{%
\begingroup
\toks@\expandafter{#1#2}%
\xdef#1{\the\toks@}%
\endgroup}


I have used the g@addto@macro in the minimal example below:

\documentclass{article}
\begin{document}

\long\def\mainmacro{Preambles in main macro. \par}
\xdef\testOne{Contents of first macro. \par }
\xdef\testTwo{Contents of second macro. \par }

\makeatletter
\makeatother

\mainmacro
\end{document}


What would be the best way to add a hook to the macro - at the beginning or for that matter anywhere but the end?

-
See Patching Existing Commands on the UK TeX FAQ. – Matthew Leingang Dec 7 '10 at 19:03
@MatthewLeingang: The link is dead now. – krlmlr Jul 5 '12 at 11:16
Sorry! here's a new link: cs.sunysb.edu/documentation/latex/help/faq/uktug-faq/… – Matthew Leingang Jul 9 '12 at 15:35

\def\foo{\message{Here is the original \string\foo}}
\def\foohook{\message{Whatever.}}

% Add a hook to \foo (\foohook does not have be predefined):
\toks0\expandafter{\expandafter\foohook\foo}
\edef\foo{\the\toks0}

% Demo:
\foo
\def\foohook{\message{Redefined \string\foohook}}
\foo
\bye


(Complete working example; to turn it into latex, remove \bye and add necessary latex cruft.)

-
Thanks. Looks so much simpler than the LaTeX @g@addto@macro. TeX is fine too. For examples that don't use LaTeX packages I rather prefer TeX myself. – Yiannis Lazarides Dec 7 '10 at 16:30

Have a look at the etoolbox package, which provides a rich set of commands for “hook management” and even “patching” of commands.

-