9

I'm trying to make sense of the \mathpalette code used in this answer. To repeat it below:

\makeatletter
\newcommand{\raisemath}[1]{\mathpalette{\raisem@th{#1}}}
\newcommand{\raisem@th}[3]{\raisebox{#1}{$#2#3$}}
\makeatother
$\Pi_{\raisemath{2pt}{-}}$

When I did \tracingmacros=1, the interesting part of the log file was:

 \raisemath #1->\mathpalette {\raisem@th {#1}}
 #1<-2pt

 \mathpalette #1#2->\mathchoice {#1\displaystyle {#2}}{#1\textstyle {#2}}
 {#1\scriptstyle {#2}}{#1\scriptscriptstyle {#2}}
 #1<-\raisem@th {2pt}
 #2<--

 \raisem@th #1#2#3->\raisebox {#1}{$#2#3$}
 #1<-2pt
 #2<-\displaystyle 
 #3<--

 etc...

 \raisem@th #1#2#3->\raisebox {#1}{$#2#3$}
 #1<-2pt
 #2<-\textstyle 
 #3<--

 etc...

From the code \mathpalette{\raisem@th{#1}} in the definition of \raisemath, I'd think that \mathpalette only is given one parameter in this instance, \raisem@th{2pt}. So, how does the second parameter, -, end up being passed to \mathpalette?

10

True, only a single argument is given to \mathpalette within the \raisemath macro. The second argument to \mathpalette is grabbed from the remainder of the input stream.

Here's a smaller example exhibiting the same setup:

\documentclass{article}
\newcommand{\abcd}[1]{\defg{#1}}
\newcommand{\defg}[2]{#1-#2}
\begin{document}
\abcd{1234}{5678}
\end{document}

It is clear that \abcd only takes a single argument as the definition only has [1] - that argument based on the input is {1234}. Therefore,

\abcd{1234}{5678}

expands to

\defg{1234}{5678}

with {5678} remaining in the input stream. Now, \defg gobbles the next two arguments, the first being {1234} and the second being {5678}.


Here's another practical example:

\documentclass{article}
\newcommand{\boldtext}{\textbf}
\begin{document}
\boldtext{abcd}
\end{document}

\boldtext is defined to not take any argument. However, we know \textbf takes an argument. So, it suffices to use \boldtext as a replacement for \textbf without technically having to grab the argument for \textbf. Another way to define it (although not really necessary) would be to grab the argument explicitly:

\newcommand{\boldtext}[1]{\textbf{#1}}

Why not just define things explicitly? It depends on what you want to do with the argument. If category code changes are involved, then it may be best to not grab arguments explicitly.

  • 1
    \section also extensively makes use of these methods :-) – 1010011010 Aug 27 '15 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.