我正在尝试将环境的内容(即主体)保存到宏中以供以后使用(以便稍后在文档中排版)。我考虑使用包(参见下面的最小示例),但如果环境主体内有其他宏(如),environ
我会收到错误。\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}
答案1
将任意 LaTeX 内容放置在 edef 或 xdef 中永远是不安全的。
您想要的宏已经定义为,\BODY
因此您不需要\let
给\xdef
它一个全局名称,
\documentclass{article}
\usepackage{environ}
\newcounter{problemnumber}\setcounter{problemnumber}{0}
\NewEnviron{problem}{%
\stepcounter{problemnumber}%%%%%%
\global\expandafter\let\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}
答案2
\global\let
您应该按照 David 所指出的方式使用。
这是一个更简短的实现,其中还带有一个用于打印问题的界面。
\documentclass{article}
\ExplSyntaxOn
\seq_new:N \g_digitalink_problem_seq
\NewDocumentEnvironment{problem}{+b}
{
\seq_gput_right:Nn \g_digitalink_problem_seq { #1 }
}
{}
\NewExpandableDocumentCommand{\getproblem}{m}
{
\seq_item:Nn \g_digitalink_problem_seq { #1 }
}
\ExplSyntaxOff
\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}
Typesetting the problems in a different order, later in the document.
\bigskip
\textbf{Problem 2:}\quad\getproblem{2}\par\hrulefill
\textbf{Problem 1:}\quad\getproblem{1}\par\hrulefill
\end{document}