5

I have a command to make a formatted header entry in a table. Most table header entries span 1 column, but others span multiple columns, so I defined the command as follows with an optional width argument. However, this does not compile. It gives a Misplaced \omit error.

\documentclass{article}
\newcommand{\hform}[2][1]{\multicolumn{#1}{|c|}{\textbf{#2}}}
\begin{document}
\begin{tabular}{|c|c|}
  \hline
  \hform[2]{Title}\\\hline
  \hform{Col 1} & \hform{Col 2} \\\hline
  blah & blah\\
  blah & blah\\
  \hline
\end{tabular}
\end{document}

Error message:

! Misplaced \omit.
\multispan ->\omit 
                   \@multispan 
l.13   \hform[2]{Title}
                       \\\hline
? 

When I delete the optional argument and make it mandatory however, it does compile.

\documentclass{article}
\newcommand{\hform}[2]{\multicolumn{#1}{|c|}{\textbf{#2}}}
\begin{document}
\begin{tabular}{|c|c|}
  \hline
  \hform{2}{Title}\\\hline
  \hform{1}{Col 1} & \hform{1}{Col 2} \\\hline
  blah & blah\\
  blah & blah\\
  \hline
\end{tabular}
\end{document}

Why is this? What am I doing wrong? On my machine this is a (fairly) minimal working example to produce this problem.

2

1 Answer 1

7

Only commands defined by expansion can come before the \omit and \span primitives that trigger the column spanning. If any non-expandable token is seen then the cell is started as normal. LaTeX uses some non-expandable constructs while testing for [.

So you need to make the argument non-optional, or you could use the xparse package an its \DeclareExpandableDocumentCommand which uses a more complicated, but expandable test for optional arguments.

\documentclass{article}
\usepackage{xparse}
\DeclareExpandableDocumentCommand{\hform}{O{1}m}{\multicolumn{#1}{|c|}{\textbf{#2}}}
\begin{document}
\begin{tabular}{|c|c|}
  \hline
  \hform[2]{Title}\\\hline
  \hform{Col 1} & \hform{Col 2} \\\hline
  blah & blah\\
  blah & blah\\
  \hline
\end{tabular}
\end{document}
2
  • @jgon I updated with an example, but note that while this answers the question about optional arguments, the specific definition here is incorrect as it uses |c| in all columns not just the first, so will lead to double width rules with a | to the right of one column touching a | to the left of the next. Commented Nov 7, 2015 at 17:11
  • Right good point, I'll be careful of that, thanks!
    – jgon
    Commented Nov 7, 2015 at 17:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .