我正在尝试创建一个环境,将每个段落包装在不同环境中。例如,如果我将每个段落包装在flushleft
其中,它将看起来像这样:
\documentclass{article}
\newcounter{conversationpar}
\newenvironment{conversation}{
\setcounter{conversationpar}{0}
\everypar={
\refstepcounter{conversationpar}
\ifnum\value{conversationpar}>1\end{flushleft}\fi
\begin{flushleft}
}
}{
\end{flushleft}
}
\begin{document}
\begin{conversation}
Let her hang me: hee that is well hang'de in this world, needs to feare no colours.
Make that good.
He shall see none to feare.
\end{conversation}
\end{document}
这不起作用,但理论上我希望它产生与执行以下操作相同的结果:
\begin{flushleft}
Let her hang me: hee that is well hang'de in this world, needs to feare no colours.
\end{flushleft}
\begin{flushleft}
Make that good.
\end{flushleft}
\begin{flushleft}
He shall see none to feare.
\end{flushleft}
感谢您的帮助。
答案1
我不确定您最终希望如何使用它,但是此代码将conversation
在每个部分中分割环境主体\par
并将每个部分放置在flushleft
环境内:
\documentclass{article}
\ExplSyntaxOn
% create a macro that will hold every paragraph of the evironment's body as a sequence
\seq_new:N \l__myconv_conversationpars_seq
% create a new environment macro, +b is a pseudo-argument that represents the body,
% the + denotes that the body may contain \pars,
% you can refer to the body using #1 (since it is the first argument statement)
\NewDocumentEnvironment{conversation} { +b } {
% split the body (provided by #1) at every \par and
% store the single parts as sequence in the previously defined macro
\seq_set_split:Nnn \l__myconv_conversationpars_seq { \par } { #1 }
% for each item in the sequence, place it inside a flushleft environment
\seq_map_inline:Nn \l__myconv_conversationpars_seq {
\begin{flushleft}
##1
\end{flushleft}
}
} { }
\ExplSyntaxOff
\begin{document}
\begin{conversation}
Let her hang me: hee that is well hang'de in this world, needs to feare no colours.
Make that good.
He shall see none to feare.
\end{conversation}
\end{document}
编辑
从评论中我了解到,您希望为您的环境提供两个额外的强制参数,并使用第一个或第二个,具体取决于当前项是奇数还是偶数。我将其添加到上面的代码中:
\documentclass{article}
\ExplSyntaxOn
\seq_new:N \l__myconv_conversationpars_seq
% add two mandatory arguments, the body now being the third argument
\NewDocumentEnvironment{conversation} { m m +b } {
\seq_set_split:Nnn \l__myconv_conversationpars_seq { \par } { #3 }
% for each item in the sequence, return index as ##1 and the item as ##2
\seq_map_indexed_inline:Nn \l__myconv_conversationpars_seq {
\begin{flushleft}
% test whether the index is odd,
% if yes, use value of first mandatory argument stored in #1,
% if not, use value of first mandatory argument stored in #2
% (~ denotes a space)
\int_if_odd:nTF { ##1 } { #1 } { #2 } : ~
##2
\end{flushleft}
}
} { }
\ExplSyntaxOff
\begin{document}
\begin{conversation}{odd}{even}
Let her hang me: hee that is well hang'de in this world, needs to feare no colours.
Make that good.
He shall see none to feare.
\end{conversation}
\end{document}