tabu
当我在条件语句中用定义环境时,收到错误消息(“对齐制表符 & 位置错误。”)\newenvironment
。可以避免这种情况吗?
这是一个最小的工作示例:
\documentclass{article}
\usepackage{tabu}
\begin{document}
\newif\ifmyparameter
\myparametertrue
% this produces an error
\newenvironment{tableau}[1]{%
\ifmyparameter
\begin{tabular}{|lll||#1|}
\else
\begin{tabular}{|rrr||#1|}
\fi%
}{\end{tabular}}
% but it works if there is no conditional
%\newenvironment{tableau}[1]{%
% \begin{tabu}{|lll||#1|}
% }{\end{tabu}}
% it also works if I use a tabular environment instead of tabu
%\newenvironment{tableau}[1]{%
% \ifmyparameter
% \begin{tabular}{|lll||#1|}
% \else
% \begin{tabular}{|rrr||#1|}
% \fi%
% }{\end{tabular}}
\begin{tableau}{c|c|c}
a & b & c & d & e & f \\
c & d & e & f & g & h\\
\end{tableau}
\end{document}
解决此问题的一种方法是将整个\newenvironment
命令放在条件中。这样编译时不会出错,但需要大量重复代码才能获得新环境的两个完整定义(即在实际应用程序中,而不仅仅是 MWE)。
\documentclass{article}
\usepackage{tabu}
\begin{document}
\newif\ifmyparameter
\myparametertrue
\ifmyparameter
\newenvironment{tableau}[1]{%
\begin{tabu}{|lll||#1|}
}{\end{tabu}}
\else
\newenvironment{tableau}[1]{%
\begin{tabu}{|rrr||#1|}
}{\end{tabu}}
\fi%
\begin{tableau}{c|c|c}
a & b & c & d & e & f \\
c & d & e & f & g & h\\
\end{tableau}
\end{document}
答案1
问题是,你必须\fi
在启动tabular
/tabu
环境之前将其删除。请参阅\@firstoftwo 和 \@secondoftwo 起什么作用?了解更多信息。
\documentclass{article}
\usepackage{tabu}
\newif\ifmyparameter
\myparametertrue
\makeatletter
\newenvironment{tableau}[1]{%
\ifmyparameter
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
{\begin{tabu}{|lll||#1|}}
{\begin{tabu}{|rrr||#1|}}%
}{\end{tabu}}
\makeatother
\begin{document}
\begin{tableau}{c|c|c}
aaaa & bbbb & ccccc & dddd & eeee & ffff \\
c & d & e & f & g & h\\
\end{tableau}
\bigskip
\myparameterfalse
\begin{tableau}{c|c|c}
aaaa & bbbb & ccccc & dddd & eeee & ffff \\
c & d & e & f & g & h\\
\end{tableau}
\end{document}