[texhax] combing adjacent macros

Donald Arseneau asnd at triumf.ca
Mon May 25 14:41:33 CEST 2009


Henry Kannapell <hnk at cs.stanford.edu> writes:

> I am a novice Tex user, but would like to find a method of combining
> adjacent macros that I define in a style sheet.
> 
> \newcommand\hyph{\emph{(hyph.)} %% hyphenated
> \newcommand\var{\emph{(var.)} %% variation
> \newcommand\slang{\emph{(slang)} %% slang term
> 
> In some cases, however, I have more than one tag. What I would like to  do is
> then have a pair of adjacent macros expand like this:
> 
> \hyph\var -> (hyph., var)
> 
> I think I could create a recursive macro which checks the second  command,
> and if it is in the same group of macros (there are perhaps 9  that I have
> defined), combine them. But that would be 9 different  definitions, with 9
> different checks in each one - surely there is a  better solution than that.
> 
> A general solution would be able to deal with an unlimited number of
> adjacent macros. And, it should be able to define a group composed of  the 9
> macros, and do the recursion based on the group, not each  individual macro.

The important question is: are these used in a place where it is
always safe to look at the next character or command?  Things can
get messy looking ahead to see an alignment separator (&).  If they
are safe in general, are they safe to take a macro argument?  That
means they are never used right before }, or certain other contexts.

Here is my suggestion.  Expand the next token and look for a consistent
command name.  (Yes, \@ifnextchar can test commands.)

\makeatletter

\newcommand\cwtag[1]{%
  \cwtag at start \let\cwtag at start\relax % start and locally disable restart
  \emph{#1}%
  \expandafter\cwtag at tail
}

\newcommand\cwtag at tail{%
 \@ifnextchar\cwtag{\cwtag at join}{\cwtag at stop}%
 }
\newcommand\cwtag at start{\begingroup (}
\newcommand\cwtag at join{,\ }
\newcommand\cwtag at stop{)\endgroup}

\makeatother

\newcommand\hyph{\cwtag{hyph.} %% hyphenated
\newcommand\var{\cwtag{var.} %% variation
\newcommand\slang{\cwtag{slang} %% slang term
...

-- 
Donald Arseneau                          asnd at triumf.ca


More information about the texhax mailing list