使用xparse
,如何让这样的事情发挥作用?
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentEnvironment{ anenvironment }{ >{\SplitArgument{1}{,}}o }{
\begin{ auxanenvironment }[#1]
}{
\end{ auxanenvironment }
}
\NewDocumentEnvironment{ auxanenvironment }{ O{}o }{
Do~something~with~#1\IfValueTF{ #2 }{ ,~and~something~else~with~#2. }{ . }
}{}
\ExplSyntaxOff
\begin{document}
\begin{anenvironment}[this argument, this other argument]
\end{anenvironment}
\begin{anenvironment}[this argument]
\end{anenvironment}
\end{document}
答案1
虽然可以使用辅助环境来实现这一点,但我不认为这是最好的方法。
您还应该处理可选参数未出现的情况:它是可选的,不是吗?
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentEnvironment{anenvironment}{ >{\SplitArgument{1}{,}}o }
{
\IfValueT{#1}{ \noibe_anenvironment_arg:nn #1 }
%<initial code for the environment>
\par Start\par
}
{
%<final code for the environment>
End\par
}
\cs_new_protected:Nn \noibe_anenvironment_arg:nn
{
\tl_if_novalue:nF { #1 }
{
Do~something~with~#1
\tl_if_novalue:nTF { #2 }
{.}
{
,~and~something~else~with~#2.
}
}
}
\ExplSyntaxOff
\begin{document}
\begin{anenvironment}[this argument, this other argument]
\end{anenvironment}
\medskip
\begin{anenvironment}[this argument]
\end{anenvironment}
\medskip
\begin{anenvironment}
\end{anenvironment}
\end{document}
如果不知道您的实际用例,很难做到不那么通用。如果参数用于设置选项,我建议您考虑使用键值接口。
答案2
这是一种完全不同的方法。
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{listofitems}
\newenvironment{anenvironment}[1][\relax]{%
\ifx\relax#1\relax\else
\readlist*\arglist{ #1}%
\foreachitem\x\in\arglist[]{%
Doing something with \detokenize\expandafter{\x}.\x\par
}%
\fi\par
}{%
\par Done doing something.\par\medskip
}
\begin{document}
\begin{anenvironment}
This is a test.
\end{anenvironment}
\begin{anenvironment}[\itshape]
This is a test.
\end{anenvironment}
\begin{anenvironment}[\itshape,\bfseries, \tiny]
This is a test.
\end{anenvironment}
\end{document}
答案3
我不确定这是否是正确的方法,但我刚刚发现,删除第 6 行参数周围的方括号,并将auxanenvironment
的参数更改为强制参数可以解决问题:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentEnvironment{ anenvironment }{ >{\SplitArgument{1}{,}}o }{
\begin{ auxanenvironment }#1
}{
\end{ auxanenvironment }
}
\NewDocumentEnvironment{ auxanenvironment }{ mm }{
Do~something~with~#1\IfValueTF{ #2 }{ ,~and~something~else~with~#2. }{ . }
}{}
\ExplSyntaxOff
\begin{document}
\begin{anenvironment}[this argument, this other argument]
\end{anenvironment}
\begin{anenvironment}[this argument]
\end{anenvironment}
\end{document}