\documentclass{article}
\makeatletter
\usepackage{ltxcmds}
\newcounter{mycounter}
\setcounter{mycounter}{7}
\newcommand{\mysndc}[3]{#1 #2 #3}
\newcommand{\mycommand}{}
\newcommand{\mytrdc}[1]{\ltx@GlobalAppendToMacro{\mycommand}{%
\mysndc{\arabic{mycounter}}{#1}{\thepage}}}
\makeatother
\begin{document}
x
\mytrdc{8}
\newpage
\setcounter{mycounter}{4}
\mycommand
\end{document}
When \mycommand
is called, it is \mysndc{\arabic{mycounter}}{8}{\thepage}
resulting in 4 8 2
. What I would like it to be is \mysndc{7}{8}{2}
resulting in 7 8 1
. To achieve this, the arguments of \mysndc
must be expanded before \mysndc
is appended to \mycommand
. \expandafter
should be useful, but diverse placements of it (also more than one \expandafter
) did not yield the desired result, e.g.
\newcommand{\mytrdc}[1]{\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\ltx@GlobalAppendToMacro{\mycommand\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter}{\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\mysndc\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter{\expandafter\expandafter\expandafter\arabic{mycounter}\expandafter\expandafter\expandafter}\expandafter\expandafter\expandafter{\expandafter#1\expandafter}\expandafter{\thepage}}}
. Where must I place how many \expandafter
s to expand the arguments of \mysndc
before appending it to \mycommand
and why exactly? I found numerous similar questions and answers to them here at tex.SE, but still was not able to get it right. If possible, I prefer a solution with expandafter
s, so that I can learn from it, and without using e-TeX/etextools/etextoolbox/LaTeX3/…
Best Answer
The easiest way to tackle this is probably to force expansion of everything using
\edef
, as that was we avoid needing to shuffle arguments. (\mytrdc
is not expandable in any case, so we can use an assignment.) One possible approach using\edef
:The idea is simple: create a temporary,
\edef
ed macro\x
which contains the expanded material required plus the necessary 'set up', then execute it. Everything is done in a group so we don't mess up any other meaning of\x
.