I am trying to save the contents (i.e., the body) of an environment into a macro for later use (in order to typeset it later in the document). I thought of using the environ package (see the minimal example below), but I get an error if there are other macros inside the body of the environment (like a \textbf{bold text}).
\documentclass{article}
\usepackage{environ}
\newcounter{problemnumber}\setcounter{problemnumber}{0}
\NewEnviron{problem}{%
\stepcounter{problemnumber}
\expandafter\long\expandafter\xdef\csname myproblem-\theproblemnumber\endcsname{\BODY}
}
\begin{document}
\begin{problem}
Some equation: $E=mc^2$
\end{problem}
\begin{problem}
Some text.
A second paragraph with a \textbf{bold text}. And an inline equation: $E=mc^2$.
\end{problem}
...
Typsetting the problems in a different order, later in the document.
\textbf{Problem 2:}\quad\csname myproblem-2\endcsname\par\hrulefill
\textbf{Problem 1:}\quad\csname myproblem-1\endcsname\par\hrulefill
\end{document}

\BODYthe error is unrelated, you can not have\textbf(or most latex) in\xdef. – David Carlisle Jan 14 '21 at 20:14environpackage) there's alsoVerbatimOutfromfancyvrb, orscontents(see https://tex.stackexchange.com/a/513810/250119 ) – user202729 Nov 01 '21 at 14:25