
我正在嘗試建立我自己的食譜風格,其中有一種成分萬客隆。有時,成分應該分開並有標題,所以我嘗試使用可選參數。最小的例子如下:
\documentclass{scrartcl}
\newcommand{\ingredient}[3][]{
#1 #2 & #3 \\
}
\begin{document}
\begin{tabular}{r|l}
\ingredient[\multicolumn{2}{l}{Head} \\]{test1}{test2}
\ingredient[test3]{test4}{test5}
\ingredient{test6}{test7}
\end{tabular}
\end{document}
這段程式碼有什麼問題?我收到以下錯誤訊息:
! Misplaced \omit.
\multispan ->\omit
\@multispan
l.7 ...[\multicolumn{2}{l}{Head} \\]{test1}{test2}
答案1
表格材料是真的對一行「之前」允許的內容很挑剔。特別是,它必須是完全可擴展的。
因此,即使是任務需要\ingredient
檢查其可選參數是否足以啟動該行,然後\multicolumn
不再允許出現。
解決這個問題的最簡單方法是將第一個參數設定為\ingredient
強制:
\documentclass{scrartcl}
\newcommand{\ingredient}[3]{
#1 #2 & #3 \\
}
\begin{document}
\begin{tabular}{r|l}
\ingredient{\multicolumn{2}{l}{Head} \\}{test1}{test2}
\ingredient{test3}{test4}{test5}
\ingredient{}{test6}{test7}
\end{tabular}
\end{document}
答案2
你能如果您使用\DeclareExpandableDocumentCommand
來自xparse
包裹。
代碼:
\documentclass{scrartcl}
\usepackage{xparse}
\DeclareExpandableDocumentCommand{\ingredient}{O{} m m}{%
#1 #2 & #3 \\%
}%
\begin{document}
\begin{tabular}{r|l}
\ingredient[\multicolumn{2}{l}{Head} \\]{test1}{test2}
\ingredient[test3]{test4}{test5}
\ingredient{test6}{test7}
\end{tabular}
\end{document}
答案3
您可以「創造性地」使用noalign
來實現該功能。在下面的程式碼中,我定義了一個功能\NewDocumentCommandOptionalInTabular
類似於\NewDocumentCommand
函數,除了你能根據需要使用可選參數(或星號)。
\documentclass{scrartcl}
% ======== copy paste this part ========
\ExplSyntaxOn
\cs_new_protected:Npn \NewDocumentCommandOptionalInTabular #1 #2 #3 {
\NewDocumentCommandOptionalInTabular_aux:xnnn {\exp_not:c{\cs_to_str:N #1-aux}} #1 {#2} {#3}
}
\cs_new_protected:Npn \NewDocumentCommandOptionalInTabular_aux:nnnn #1 #2 #3 #4 {
\cs_new:Npn #2 { \noalign \bgroup #1 }
\NewDocumentCommand #1 {#3} { \egroup #4 }
}
\cs_generate_variant:Nn \NewDocumentCommandOptionalInTabular_aux:nnnn {x}
\ExplSyntaxOff
% ======== end ========
% then you can just use \NewDocumentCommandOptionalInTabular to replace \NewDocumentCommand
\NewDocumentCommandOptionalInTabular \ingredient {O{} m m}{
#1 #2 & #3 \\
}
\begin{document}
\begin{tabular}{r|l}
\ingredient[\multicolumn{2}{l}{Head} \\]{test1}{test2}
\ingredient[test3]{test4}{test5}
\ingredient{test6}{test7}
\end{tabular}
\end{document}
靈感來自艾格格的回答。