
Usando xparse
, ¿cómo se puede hacer que algo como esto funcione?
\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}
Respuesta1
Si bien es posible hacerlo con un entorno auxiliar, no creo que sea la mejor manera de hacerlo.
También deberías abordar el caso en el que el argumento opcional no aparece: es opcional, ¿no?
\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}
Sin conocer su caso de uso real, es difícil ser menos genérico. Le sugiero que considere una interfaz clave-valor, si el argumento es para configurar opciones.
Respuesta2
Un enfoque completamente diferente.
\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}
Respuesta3
No estoy seguro de que esta sea la forma correcta de hacerlo, pero acabo de descubrir que eliminar las llaves alrededor del argumento en la línea 6 y cambiar auxanenvironment
los argumentos a obligatorios resuelve el problema:
\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}