2

I want to write a command that will produce a table, but can also add one multicolumn with an optional argument's contents in it. I tried to do this using ifthenelse to check if the optional argument is empty, but something about having the brackets around multicolumn gives me a mispaced \omit error, and causes the column to be misaligned.

Here is what the command would look like:

\newcommand{\namecol}[1][]{
\begin{table}[h!]
\begin{tabular}{|rlrl|}
    \ifthenelse{\equal{#1}{}}{}{%
        \multicolumn{4}{|l|}{#1} \\
    }
    a & b & c & d \\
    e & f & g & h \\
\end{tabular}
\end{table}
}

and below are the results of calling \namecol and \namecol[x], respectively:

multicol misalignment

corndog
  • 35

2 Answers2

3

Does this fulfill your expectations?

\documentclass{article}
\begin{document}
\newcommand{\namecol}[1][\relax]{
\begin{table}[h!]
\begin{tabular}{|rlrl|}
    \ifx\relax#1\relax\else
        \multicolumn{4}{|l|}{#1} \\
        \fi
    a & b & c & d \\
    e & f & g & h \\
\end{tabular}
\end{table}
}

\namecol

\namecol[x]

\end{document}

enter image description here

2

The problem is that \multicolumn has to be the first object (after macro expansion) in the cell, but \ifthenelse inserts other things and, when \multicolumn is eventually found, it is too late.

A simpler approach is with xparse, where we can test whether the optional argument has been given with the expandable test \IfValueT.

\documentclass{article}
\usepackage{xparse} % not needed if using LaTeX released on or after 2020-10-01

\NewDocumentCommand{\namecol}{o}{% \begin{table}[htp!]% <--- not just h! \begin{tabular}{|rlrl|} \IfValueT{#1}{\multicolumn{4}{|l|}{#1} \} a & b & c & d \ e & f & g & h \ \end{tabular} \end{table} }

\begin{document}

\namecol

\namecol[x]

\end{document}

enter image description here

egreg
  • 1,121,712