2.1.2 ⁂Hook Management
The etoolbox package [51] comes with some useful hook management tools that allow you to append (or prepend) code to a control sequence's definition. To append ⟨code⟩ to the definition of the command ⟨cs⟩:
or to make the effect global:
Example
This produces:
Note that no expansion is performed on ⟨code⟩. For example:
\newcommand{\mymacro}{x}% \newcommand{\myothermacro}{AB}% \appto\mymacro{\myothermacro} \renewcommand{\myothermacro}{YZ}% \appto\mymacro{\myothermacro}
is equivalent to:
\newcommand{\mymacro}{x\myothermacro\myothermacro}
When you actually use \mymacro
it will use whatever the
definition of \myothermacro
is at the time, which may not
be what you intended.
If you want ⟨code⟩ expanded before being appended to ⟨cs⟩ then you need to use:
or its global equivalent:
So
\newcommand{\mymacro}{x}% \newcommand{\myothermacro}{AB}% \eappto\mymacro{\myothermacro}% \renewcommand{\myothermacro}{YZ}% \eappto\mymacro{\myothermacro}
is equivalent to:
\newcommand{\mymacro}{xABYZ}
When you use any of the versions that expand the item, if the item contains a command that shouldn't be expanded, you need to use:
where ⟨cs⟩ is the command that shouldn't be expanded. Fragile commands will typically need to have their expansion suppressed. For example:
\newcommand{\mymacro}{x}% \newcommand{\myothermacro}{AB}% \eappto\mymacro{\noexpand\footnote{\myothermacro}}
is equivalent to:
Now the fragile \footnote
command won't be processed until
\mymacro
is used later on in the document.
There are similar commands for prepending code to a command:
or its global equivalent:
As with \appto
and \gappto
, no expansion is performed
on ⟨code⟩. If you want ⟨code⟩ expanded you need to use:
or its global equivalent:
The expansion commands, such as \eappto
and \epreto
,
fully expand ⟨code⟩. This means that a recursive
expansion is performed until everything is expanded except commands
that have been prefixed with \noexpand
or commands that
don't expand, such as primitives or robust commands.
For example:
\newcommand{\mymacro}{x}% \newcommand{\mymacroB}{\mymacroC}% \newcommand{\mymacroC}{\mymacroD}% \newcommand{\mymacroD}{Z}% \eappto\mymacro{\mymacroB}
is equivalent to:
\newcommand{\mymacro}{xZ}
It may be that you only want one-level of expansion. In which case you can use the etoolbox command:
For example:
\newcommand{\mymacro}{x}% \newcommand{\mymacroB}{\mymacroC}% \newcommand{\mymacroC}{\mymacroD}% \newcommand{\mymacroD}{Z}% \eappto\mymacro{\expandonce\mymacroB}
is equivalent to:
\newcommand{\mymacro}{x\mymacroC}
There are also analogous commands that require the name (without the leading backslash) of the control sequence:
(appending without expansion)
(global version)
(appending with expansion)
(global version)
(prepending without expansion)
(global version)
(prepending with expansion)
(global version).
This book is also available as A4 PDF or 12.8cm x 9.6cm PDF or paperback (ISBN 978-1-909440-07-4).