我想将一些文本附加到命令中,但同时扩展计数器。以下是问题的示例:
梅威瑟:
\documentclass{article}
\newcommand{\topics}{}
\newcounter{topic}
\newcommand{\topic}[1]{\stepcounter{topic}\expandafter\def\expandafter\topics\expandafter{\topics\hangindent=0.5cm Topic \#\thetopic: #1\par}}
\topic{test A}
\topic{test B}
\topic{test C}
\begin{document}
\topics
\end{document}
得出的结果为:
Topic #3: test A
Topic #3: test B
Topic #3: test C
但它应该产生:
Topic #1: test A
Topic #2: test B
Topic #3: test C
我也尝试过这个,但没有成功:
\newcommand{\topic}[1]{\stepcounter{topic}\g@addto@macro\topics{\hangindent=0.5cm Topic \#\thetopic: #1\par}}
答案1
您可以\edef
在这里使用:
\newcommand{\topic}[1]{%
\stepcounter{topic}%
\edef\topics{\unexpanded\expandafter{\topics}\hangindent=0.5cm
\noexpand\textbf{Topic \#\thetopic:} \unexpanded{#1}\par}%
}
会将\unexpanded\expandafter{...}
当前\topics
列表展开一次,但会阻止其完全展开。这对于以后的调用非常重要,\topic
以确保展开不会破坏其他不应完全展开的命令(请参阅\textbf
我示例中的用法)。
使用此宏可获得所需的输出
答案2
答案3
\stepcounter
如果在扩展后移动,则宏可以正常工作\topics
:
\documentclass{article}
\newcounter{topic}
\def\topics{}
\def\topic#1{%
\expandafter\def\expandafter\topics\expandafter{\topics
\stepcounter{topic}
\hangindent=0.5cm
Topic \#\thetopic: #1\par}}
\topic{test A}
\topic{test B}
\topic{test C}
\begin{document}
\topics
\end{document}
由于\topics
只扩展一次,您可以在其中和的参数中包含所有类型的宏\topic
。
答案4
你需要扩展\thetopic
前执行附加操作:
\documentclass{article}
\newcommand{\topics}{}
\newcounter{topic}
\newcommand{\topic}[1]{%
\stepcounter{topic}%
% newer versions of the engines (TeX Live 2019)
\expandafter\appendtotopics\expandafter{\expanded{\thetopic}}{#1}%
% for older versions of the TeX engines use the following
%\begingroup\edef\x{\endgroup\noexpand\appendtotopics{\thetopic}}\x{#1}%
}
\newcommand{\appendtotopics}[2]{%
\expandafter\def\expandafter\topics\expandafter{%
\topics\hangindent=0.5cm Topic \##1: #2\par
}%
}
\topic{test A}
\topic{test B}
\topic{test C}
\begin{document}
\topics
\end{document}
一个expl3
版本:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\topics}{}
{
\tl_use:N \g_kessels_topics_tl
}
\NewDocumentCommand{\topic}{m}
{
\kessels_topic:n { #1 }
}
\int_new:N \g_kessels_topic_int
\tl_new:N \g_kessels_topics_tl
\cs_new_protected:Nn \kessels_topic:n
{
\int_gincr:N \g_kessels_topic_int
\__kessels_topic_add:fn { \int_to_arabic:n { \g_kessels_topic_int } } { #1 }
}
\cs_new_protected:Nn \__kessels_topic_add:nn
{
\tl_gput_right:Nn \g_kessels_topics_tl { \hangindent=0.5cm~Topic~\##1:~#2\par }
}
\cs_generate_variant:Nn \__kessels_topic_add:nn { f }
\ExplSyntaxOff
\topic{test A}
\topic{test B}
\topic{test C}
\begin{document}
\topics
\end{document}