
私は、成分マクロを持つ独自のクックブック スタイルを構築しようとしています。 場合によっては、成分を分離して見出しを付ける必要があります。そのため、オプションの引数を使用してみました。 最小限の例は次のようになります。
\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}
に触発されたegregの回答。