在表内使用 xparse-defined 命令

在表内使用 xparse-defined 命令

这是这个问题,我想知道为什么使用tline下面的命令无法编译

\documentclass{article}
\usepackage{xparse,tabu}
\usepackage[table]{xcolor}

\NewDocumentEnvironment {trace} {} {%
  \table
    \tabu to \linewidth {|@{ }r@{::}l|l|X|}
      A & B & C & D \\
  }{%
    \endtabu
  \endtable
}

\newcommand{\commentcell}{\cellcolor[gray]{0.9}}
\newcommand{\linecell}{\cellcolor[gray]{0.75}}
\newcommand{\classcell}{\cellcolor[gray]{0.75}}
\newcommand{\methodcell}{\cellcolor[gray]{0.75}}
\newcommand{\codecell}{\cellcolor[gray]{0.75}}
\NewDocumentCommand \tline { o m m m m } {\linecell #2 & \classcell #3 & \methodcell #4 & \codecell #5 \\ %
    \IfNoValueTF {#1}
        {} % No comment was provided, skip creating a line
        {\hline\multicolumn{4}{ |r| }{\commentcell #1} \\ }
    \hline
}

\begin{document}

% This works
\begin{trace}
 a & b & c & d
\end{trace}

% This fails with 'Missing Number'. Note that tabu definitely does not like the 
% ending \\ caused by the \tline, but I know that I need to use \\ inside my 
% tline command to cause a line break, so the question is how do I optionally
% create two rows inside tline without using \\, or is there a command tabu 
% prefers to \\. I tried \newline with no luck
\begin{trace}
 \tline{a}{b}{c}{d}
\end{trace}

\end{document}

答案1

您不能\multicolumn在用 定义的命令中使用\NewDocumentCommand,但如果您使用 ,它可以工作\DeclareExpandableDocumentCommand。但是,tabu似乎不同意在用 定义的环境中所做的操作\NewDocumentEnvironment

我明确重复了环境只是为了表明输出是相同的。

\documentclass{article}
\usepackage{xparse,tabu}
\usepackage[table]{xcolor}

\newenvironment{trace}
 {%
  \table
  \tabu to \linewidth {|@{ }r@{::}l|l|X|}
    A & B & C & D \\
 }
 {%
  \endtabu
  \endtable
 }

\newcommand{\commentcell}{\cellcolor[gray]{0.9}}
\newcommand{\linecell}{\cellcolor[gray]{0.75}}
\newcommand{\classcell}{\cellcolor[gray]{0.75}}
\newcommand{\methodcell}{\cellcolor[gray]{0.75}}
\newcommand{\codecell}{\cellcolor[gray]{0.75}}
\DeclareExpandableDocumentCommand \tline { o m m m m } {%
  \linecell #2 & \classcell #3 & \methodcell #4 & \codecell #5 \\ %
    \IfNoValueTF {#1}
        {}% No comment was provided, skip creating a line
        {\hline\multicolumn{4}{ |r| }{\commentcell #1} \\ }
    \hline
}

\begin{document}

% This works
\begin{trace}
 a & b & c & d
\end{trace}

\begin{trace}
 \tline{a}{b}{c}{d}
\end{trace}

\begin{table}
\begin{tabu} to \linewidth {|@{ }r@{::}l|l|X|}
  A & B & C & D \\
  \linecell a & \classcell b & \methodcell c & \codecell d \\
\end{tabu}
\end{table}


\end{document}

在此处输入图片描述

相关内容