I'm quite happy hacking TeX macros and cobbling together bits and pieces from different style files to suit my own ends, but I have a suspicion that my resulting hacks are not quite as elegant as they could be. In particular, with regard to when to expand and when not to expand macros.
A common occurrence for me is defining a meta-command that defines a whole slew of sub-commands. So the names of the sub-commands will contain parameters depending on the parameter passed to the meta-command, and the contents of the sub-commands will also vary a little depending on what the meta-command got. Often it won't be a direct substitution but rather a "if #1
is a
do \this
else do \that
", but \this
and \that
need expansion at define time, not call time.
Here's a very simple example just involving direct substitution:
\def\cohtheory#1{
\expandafter\newcommand\expandafter{\csname #1func\endcsname}[1][*]{%
\MakeUppercase{#1}^{##1}}
}
Sometimes I worry that my commands are more complicated than they need be. For example, if I want to call a command with two arguments and the arguments expand before the command, here's how I've coded it:
\expandafter
\expandafter
\expandafter
\command\expandafter
\expandafter
\expandafter
{\expandafter
\argone
\expandafter
}\expandafter
{\argtwo}
So I'm looking for guidance on when and how to control expansion in defining macros. I strongly suspect that such cannot be given in a simple answer, so to make this a focussed question, let me phrase it thus:
Where's a good reference for writing TeX macros that includes advice on how to best deal with how to handle expansions?
Of course, if anyone can formulate some advice in short answer, I'd be only to happy to read it.
(Note: this was partially motivated by juannavarroperez's adaptation of my answer to this question where over 20 \expandafter
s got condensed down to just 1!)
\@expandtwoargs\command{<arg1>}{<arg2>}
which expands the two arguments using\edef
before feeding it to\command
.\@expandtwoargs
and define a macro for three arguments. Should not be any trouble.\expandafter