[Tex/LaTex] Expanding all arguments of a command before appending it to another macro

expansion

\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 \expandafters 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 expandafters, 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:

\documentclass{article}

\usepackage{ltxcmds}

\newcounter{mycounter}
\setcounter{mycounter}{7}

\newcommand{\mysndc}[3]{#1 #2 #3}

\newcommand{\mycommand}{}
\makeatletter
\newcommand{\mytrdc}[1]{%
  \begingroup
  \edef\x{%
    \endgroup
    \noexpand\ltx@GlobalAppendToMacro{\noexpand\mycommand}{%
    \noexpand\mysndc{\arabic{mycounter}}{#1}{\thepage}}}%
  \x}

\makeatother
\begin{document}
x

\mytrdc{8}

\newpage
\setcounter{mycounter}{4}

\show\mycommand
\end{document}

The idea is simple: create a temporary, \edefed 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.

Related Question