在这答案是,我得到了下面的代码,解决了我原来的问题。
\ExplSyntaxOn
\NewDocumentEnvironment{withalignment}{m}
{
\begin{\vincent_alignment:n { #1 }}
}
{
\end{\vincent_alignment:n { #1 }}
}
\cs_new:Nn \vincent_alignment:n
{
\str_case:nn { #1 }
{
{c}{center}
{center}{center}
{l}{flushleft}
{left}{flushleft}
{r}{flushright}
{right}{flushright}
}
}
\ExplSyntaxOff
可以这样使用:
\begin{withalignment}{left}
\lipsum[1][1-4]
\end{withalignment}
\begin{withalignment}{center}
\lipsum[1][1-4]
\end{withalignment}
然而,问题是当我通过宏/命令提供对齐时:
\newcommand{\myalignment}{center}
\begin{withalignment}{\myalignment}
\lipsum[1][1-4]
\end{withalignment}
似乎不起作用。如何在处理参数之前充分展开它以使其起作用?
答案1
我做的改变:
- [必填] 在定义中
\vincent_alignment:n
,\str_case:nn
被替换为\str_case:en
- [可选] 在定义
withalignment
环境时,分别在和\exp_args:Ne
前面添加一个。此更改是可选的,但应该会提高效率。\begin
\end
withalignment
\documentclass{article}
\usepackage{lipsum}
\ExplSyntaxOn
\NewDocumentEnvironment{withalignment}{m}
{
\exp_args:Ne \begin {\vincent_alignment:n { #1 }}
}
{
\exp_args:Ne \end {\vincent_alignment:n { #1 }}
}
\cs_new:Nn \vincent_alignment:n
{
\str_case:en { #1 }
{
{c}{center}
{center}{center}
{l}{flushleft}
{left}{flushleft}
{r}{flushright}
{right}{flushright}
}
}
\ExplSyntaxOff
\begin{document}
\begin{withalignment}{left}
\lipsum[1][1-4]
\end{withalignment}
\begin{withalignment}{center}
\lipsum[1][1-4]
\end{withalignment}
\newcommand{\myalignment}{center}
\begin{withalignment}{\myalignment}
\lipsum[1][1-4]
\end{withalignment}
\renewcommand{\myalignment}{right}
\begin{withalignment}{\myalignment}
\lipsum[1][1-4]
\end{withalignment}
\end{document}
奖励:应用第二种解决方案Ulrike Fischer 建议在问题评论中
\documentclass{article}
\usepackage{lipsum}
\ExplSyntaxOn
\NewDocumentEnvironment{withalignment}{m}
{
\exp_args:Ne \begin {\vincent_alignment:e { #1 }}
}
{
\exp_args:Ne \end {\vincent_alignment:e { #1 }}
}
\cs_new:Nn \vincent_alignment:n
{
\str_case:nn { #1 }
{
{c}{center}
{center}{center}
{l}{flushleft}
{left}{flushleft}
{r}{flushright}
{right}{flushright}
}
}
\cs_generate_variant:Nn \vincent_alignment:n {e}
\ExplSyntaxOff
\begin{document}
\begin{withalignment}{left}
\lipsum[1][1-4]
\end{withalignment}
\begin{withalignment}{center}
\lipsum[1][1-4]
\end{withalignment}
\newcommand{\myalignment}{center}
\begin{withalignment}{\myalignment}
\lipsum[1][1-4]
\end{withalignment}
\renewcommand{\myalignment}{right}
\begin{withalignment}{\myalignment}
\lipsum[1][1-4]
\end{withalignment}
\end{document}