# passing current content of commands to a macro

I am sorry for this is probably a current question with a well known answer, but I was not able to google it out.

I am trying to build a macro adding content step by step; at every step I need to pass to the macro the current content of a command. I made lots of attempts with \edef and \expandafter \global, with no success. My macro always uses the content of the command which is current at the moment the macro is called, not at the moment it is created.

The question is motivated by my former question Exercises in lecture notes without predetermined placement (Follow-up) which is still unanswered. However here below I reproduce a simpler code to make this question self-contained.

\documentclass{article}

\makeatletter
\let\@mymacro\@empty%
\newcommand\myEquation[1]{%
$$% \label{eq:\theequation}% #1%$$%
\edef\EquationLabel{eq:\theequation}%
\item There is an equation with number \ref{\EquationLabel}.
}%
}%

\newcommand\refequations{%
\subsection*{Check equations}%
\begin{itemize}%
\@mymacro%
\end{itemize}%
}

\begin{document}

\section*{Two equations}
\myEquation{1+1=2}
\myEquation{2+2=4}

\refequations

\end{document}


One way is to have a helper macro so that you can easily jump forward with \expandafter to use the expansion of the macro rather than the macro itself.

\documentclass{article}

\makeatletter
\let\@mymacro\@empty%
\newcommand\myEquation[1]{%
$$% \label{eq:\theequation}% #1%$$%
\edef\EquationLabel{eq:\theequation}%
}%

\item There is an equation with number \ref{#1}.
}}

\newcommand\refequations{%
\subsection*{Check equations}%
\begin{itemize}%
\@mymacro%
\end{itemize}%
}

\begin{document}

\section*{Two equations}
\myEquation{1+1=2}
\myEquation{2+2=4}

\refequations

\end{document}


With LaTeX3 features it's easier to control what's expanded and what is not.

\documentclass{article}
\usepackage{lipsum}
\usepackage{xparse}

\ExplSyntaxOn
\tl_new:N \g_gherardo_items_tl

\NewDocumentCommand\myEquation{ o m }
{
$$% the optional value is for an explicit label \IfValueT{#1}{\label{#1}} \label{eq:\theequation} #2$$
}
{
% everything is fully expanded
\tl_gput_right:Nx \g_gherardo_items_tl
{
% but not what's inside \exp_not:n
\exp_not:n { \item There~is~an~equation~with~number~\ref }
{eq:\theequation}.
}
}

\NewDocumentCommand\refequations{ }
{
\subsection*{Check~equations}
\begin{itemize}
\g_gherardo_items_tl
\end{itemize}
}
\ExplSyntaxOff

\begin{document}

\section*{Two equations}
\lipsum*[2]
\myEquation{1+1=2}
\lipsum*[3]
\myEquation[mylabel]{2+2=4}

Here's the reference~\ref{mylabel}.

\refequations

\end{document}


You see that you can also add a personal label to your equations for referencing it without the need to know the equation number.

• Thanks, it works! But then I should study LaTeX3! :-) – Gherardo Feb 20 '13 at 6:32