I am adapting to LaTeX3 the code given there to provide for an environment the content of which is not displayed but the labels of which are taken into account.
The idea is to typeset the content into a vbox to be discarded, but before that, to change the meaning of \label to a new \qlabel command that stores label information into a clist, and thereafter to process the clist with \dolabels to output relevant label information into .aux.
This seems to work… until amsmath is loaded, whether before or after the code. What happens is the reference to the non-typeset labels are undefined. I have reason to believe that amsmath somehow makes it difficult to change the meaning of \label (the clist remains empty), but I am at a complete loss as to how to eschew this.
Here is my code. Compiling (with LuaLaTeX) as is correctly gives references (2) (1) (4) at the end. Uncommenting one of the \usepackage{amsmath} gives (??) (1) (4) instead.
\documentclass{article}
%\usepackage{amsmath}
\ExplSyntaxOn
\makeatletter
\clist_new:N \g__chato_exo_labels_cl
\box_new:N \l__chato_exo_dummy_box
\cs_new:Nn\cs__chato_exo_dolabels:nnn{@bsphack \protected@write @auxout {}{\string \newlabel {#1}{{#2}{#3}}}@esphack}
\cs_new:Nn\cs__chato_exo_qlabel:n{\clist_gput_right:Nx \g__chato_exo_labels_cl { {{#1}{@currentlabel}{\thepage}} } }
\NewDocumentEnvironment{question}{O{}}
{\begingroup\let\ltx@label\cs__chato_exo_qlabel:n\vbox_set:Nw \l__chato_exo_dummy_box}
{\vbox_set_end:\endgroup\clist_map_inline:Nn \g__chato_exo_labels_cl {\cs__chato_exo_dolabels:nnn ##1}}
\makeatother
\ExplSyntaxOff
%\usepackage{amsmath}
\begin{document}
\begin{equation}
i,i,i, \label{eq2}
\end{equation}
\begin{question}[truc]
choucroute
\begin{equation}
i,i,i, \label{eq1}
\end{equation}
\begin{equation}
oon \label{eq}
\end{equation}
\end{question}
\begin{equation}
i,i,i, \label{eq3}
\end{equation}
(\ref{eq1}) (\ref{eq2}) (\ref{eq3})
\end{document}
\ltx@labelis not defined and so never executed. With amsmath the code work ok but will probably break if you load hyperref. – Ulrike Fischer Aug 29 '22 at 10:12\labelwhenamsmathis not loaded and\ltx@labelwhen it is ? – ysalmon Aug 29 '22 at 12:46