
答案1
下面實作了我的評論中列出的參數結構,同時也考慮了@Teepeemm 所做的旁注。
\documentclass{article}
\ExplSyntaxOn
\NewDocumentCommand \mycmd { O{} }
{
e
\clist_map_function:nN {#1} \__idlecustard_exponent_chain:nw
\use_none:n \__idlecustard_exponent_chain_mark:
}
\cs_new:Npn \__idlecustard_exponent_chain:nw
#1 #2 \__idlecustard_exponent_chain_mark:
{ \sp { #1 #2 \__idlecustard_exponent_chain_mark: } }
\ExplSyntaxOff
\begin{document}
$\mycmd$
$\mycmd[1]$
$\mycmd[1, 2]$
$\mycmd[1, 2, 3]$
\end{document}
答案2
網站上有數十個問題詢問「具有可變數量參數的命令」。你可能做,但最好不要做。
像這樣的語法\cmd[1,2,3]
要簡單得多。
這裡有一個稍微複雜的地方,你需要支持每個指數:你需要得到
e^{1^{2^{3}}}
但我們可以利用這樣一個事實,即在這種情況下\bgroup
和\egroup
代替牙套是完全安全的。
\documentclass{article}
\usepackage{amsmath}
\ExplSyntaxOn
\NewDocumentCommand{\mycmd}{o}
{
e\IfValueT{#1}{\idle_exponents:n{#1}}
}
\cs_new_protected:Nn \idle_exponents:n
{
\clist_map_function:nN { #1 } \__idle_exponents:n
\prg_replicate:nn { \clist_count:n { #1 } } { \egroup }
}
\cs_new_protected:Nn \__idle_exponents:n
{
^\bgroup\scriptstyle #1
}
\ExplSyntaxOff
\begin{document}
$\mycmd+\mycmd[1]+\mycmd[1,2]+\mycmd[1,2,3]$
\end{document}
僅出於學術興趣:
\documentclass{article}
\usepackage{amsmath}
\ExplSyntaxOn
\NewDocumentCommand{\mycmd}{}
{
\seq_clear:N \l__idle_exponents_seq
e\idle_exponents_gather:
}
\seq_new:N \l__idle_exponents_seq
\cs_new_protected:Nn \idle_exponents_gather:
{
\peek_catcode:NTF \c_group_begin_token
{
\__idle_exponents_add:n
}
{
\__idle_exponents_deliver:
}
}
\cs_new_protected:Nn \__idle_exponents_add:n
{
\seq_put_right:Nn \l__idle_exponents_seq { #1 }
\idle_exponents_gather:
}
\cs_new_protected:Nn \__idle_exponents_deliver:
{
\seq_map_function:NN \l__idle_exponents_seq \__idle_exponents:n
\prg_replicate:nn { \seq_count:N \l__idle_exponents_seq } { \egroup }
}
\cs_new_protected:Nn \__idle_exponents:n
{
^\bgroup\scriptstyle #1
}
\ExplSyntaxOff
\begin{document}
$\mycmd+\mycmd{1}+\mycmd{1}{2}+\mycmd{1}{2}{3}$
\end{document}