2

I want to define a new command \tableheadline that (1) formats the headline text in some way and (2) takes an optional argument for spanning multiple columns while centering the headline. I tried the following implementation:

\documentclass{minimal}

\newcommand{\tableheadline}[2][1]{\multicolumn{#1}{c}{\textit{#2}}}
% \newcommand{\tableheadline}[2][1]{\multicolumn{1}{c}{\textit{#2}}}

\begin{document}
  \begin{tabular}[\textwidth]{cc} 
    \tableheadline[2]{C}
    \tableheadline{A} & \tableheadline{B} \\
    0 & 1 \\
    2 & 3 \\
  \end{tabular}
\end{document}

This, however, gives me an error:

! Misplaced \omit.
\multispan ->\omit
                   \@multispan
l.8 \tableheadline[2]{C}

I also get the error when I do not even use the optional argument (see commented line in the MWE). Any ideas what I am doing wrong?

  • 2
    This seems to be similar: tex.stackexchange.com/questions/67947/… – koleygr Jul 2 '18 at 14:57
  • Unfortunately, I couldn't figure out a solution based on the linked thread, yet. Is this obvious for you? – seyfe Jul 2 '18 at 15:34
  • 1
    Just said that this is a similar question... Didn't manage to make it work but is still similar (source of the problem is the one mentioned by egreg in his answer: His answer works if you add a `\\` that you missed in the end of first tabular line) – koleygr Jul 2 '18 at 15:40
  • Yes, that's true. Good spot! – seyfe Jul 2 '18 at 20:08
4

A command with optional argument stops the scanning for \omit and starts a cell; when \multicolumn is then seen it's too late.

You can use xparse, though:

\usepackage{xparse}
\NewExpandableDocumentCommand{\tableheadline}{O{1}m}{\multicolumn{#1}{c}{\textit{#2}}}

This is only possible when the optional argument is not the last argument in the list, but this is your case.

Full example:

\documentclass{article}
\usepackage{xparse}

\NewExpandableDocumentCommand{\tableheadline}{O{1}m}{%
  \multicolumn{#1}{c}{\textit{#2}}%
}

\begin{document}

\begin{tabular}{cc}
\tableheadline[2]{C} \\
\tableheadline{A} & \tableheadline{B} \\
0 & 1 \\
2 & 3 \\
\end{tabular}

\end{document}

enter image description here

Notes.

  1. [\textwidth] does nothing at all: the optional argument can be t, b or c, anything else is ignored.

  2. You were missing \\ for ending the first row.

  3. Don't use minimal for examples.

  • Does this compile for you with the MWE in the original question? For me, it doesn't :/ – seyfe Jul 2 '18 at 15:36
  • @seyfe Yes, it does, provided you fix the missing \\. – egreg Jul 2 '18 at 16:05
  • Oh yes thanks a lot! The \textwidth was a remainder of the tabularx environment, I was using before. The missing `\` was key! Why shouldn't one use minimal? I thought it is used for debugging purposes. – seyfe Jul 2 '18 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.