创建宏以将元素附加到另一个宏

创建宏以将元素附加到另一个宏

总体概述

目标是在书的末尾列出照片来源的列表。

平均能量损失

\documentclass{article}

\newcommand\credittable{} % This command contain the final rendering. 

\newcommand{\addcredit}[1] % Prepare each entry rendering for \credittable and append it.
{
  \let\tempcredittable\credittable
  \renewcommand{\credittable}{\expandafter\tempcredittable #1. }
}

\begin{document}


\addcredit{Author0} 
\addcredit{Author1}

{\Large Credits}
\credittable % Make the final list of credits
\end{document}

问题

这是输出xelatex

! TeX capacity exceeded, sorry [input stack size=5000].
\tempcredittable ->\expandafter \tempcredittable A
                                                  uthor0.
l.20 \credittable

No pages of output.
Transcript written on test.log.

但是,我注意到此代码在只有一个条目时有效。这没什么帮助。

问题

那么,如何创建一个附加另一个现有命令的命令?

答案1

我用 etoolbox 找到了这个解决方案:

\documentclass{article}
\usepackage{etoolbox}

\newcommand\credittable{} % This command contain the final rendering. 

\newcommand{\addcredit}[1]{ % Append the new content to \credittable
  \gappto\credittable{#1. }
}

\begin{document}

\addcredit{Author0} 
\addcredit{Author1}

{\Large Credits}
\credittable % Make the final list of credits
\end{document}

答案2

您需要在定义时进行单级扩展:

\newcommand{\addcredit}[1]
{% <--- don't forget
  \expandafter\gdef\expandafter\credittable\expandafter{\credittable #1. }% <--- don't forget
}

在这种情况下\def使用起来更简单;更好的是,\gdef分组不会影响重新定义。

还有更好的方法。

\documentclass{article}
\usepackage{booktabs} % for the last example

\ExplSyntaxOn

\NewDocumentCommand{\addcredit}{m}
 {
  \fauve_credit_add:n { #1 }
 }

\NewDocumentCommand{\credittable}{sO{.~}}
 {
  \fauve_credit_print:n { #2 }
  \IfBooleanF{#1}{#2}
 }

\seq_new:N \g_fauve_credit_list_seq

\cs_new_protected:Nn \fauve_credit_add:n
 {
  \seq_gput_right:Nn \g_fauve_credit_list_seq { #1 }
 }

\cs_new_protected:Nn \fauve_credit_print:n
 {
  \seq_use:Nn \g_fauve_credit_list_seq { #1 }
 }

\ExplSyntaxOff

\begin{document}


\addcredit{A.~Uthor (London)} 
\addcredit{R.~Eporter (New York)}

\section*{Credits}

\credittable

\section*{Credits again}

\credittable*[ -- ]

\section*{Credits in table}

\begin{tabular}{@{}l@{}}
\toprule
\multicolumn{1}{@{}c@{}}{Credits} \\
\midrule
\credittable[\\]
\bottomrule
\end{tabular}

\end{document}

分隔符\credittable*末尾不重复。分隔符的默认值为“句号空格”。

非常灵活,不是吗?

在此处输入图片描述

答案3

这是你想要的吗? :

\documentclass{article}

\newcommand\credittable{}%

\newcommand{\addcredit}[1]{%
  \expandafter\renewcommand
  \expandafter{%
  \expandafter\credittable
  \expandafter}%
  \expandafter{%
  \credittable
  \formatcreditentry{#1}}%
}

\newcommand\formatcreditentry[1]{#1. }%

\begin{document}

\addcredit{Author0} 
\addcredit{Author1}

{\Large Credits}
\credittable % Make the final list of credits
\end{document}

你可能感兴趣

  • 实际如何\expandafter运作,
  • \g@addto@macro
  • LaTeX 2ε 内核的\@starttoc-机制。\addtocontents

相关内容