How do I expand a macro into a tabular head?

Better define it as a new column type using the array package:

\documentclass{article}
\usepackage{array}
\newcolumntype{L}{|l|l|l|}
\begin{document}

\begin{tabular}{L}
1 & 2 &3\\
\end{tabular}
\end{document}

This is probably not practical but it's a nice demonstration of \expandafter and gets around the problem of macros in the table preamble with the array package.

\documentclass{article}
\usepackage{array}
\begin{document}
\def\buildtabularhead{|c|c|c|}
\expandafter\tabular\expandafter{\buildtabularhead}
1 & 2 &3\\
\endtabular
\end{document}

The two \expandafters make sure that the macro \buildtabularhead is expanded before LaTeX knows it should be expecting a tabular preamble. Notice also that instead of \begin{tabular}...\end{tabular} I had to use \tabular...\endtabular. Internally the former does the same as the latter but surrounding it with a group and doing important checks, including proper nesting (See source2e Section 54.1).


I had a very dirty answer, but I found theneater solution below while reading the documentation of the array package. In particular, this is inspired from how the * column specifier is defined there.

The idea is to introduce the new column type \expand (\newcolumntype sets up most of the necessary ingredients), and then redefine \NC@rewrite@\expand to expand the next token with \expandafter, and then continue the action that array is doing at that time (namely finding user-defined column types and replacing them by their definition).

\documentclass{article}
\usepackage{array}

\makeatletter
\newcolumntype{\expand}{}
\long\@namedef{NC@rewrite@\string\expand}{\expandafter\NC@find}
\makeatother

\begin{document}
\def\mypream{c|*{2}{c|||}}
\begin{tabular}{c\expand\mypream cc}
    a   & b   & d     &e   & f     & apsdoi \\
    cde & def & erasd &arp & sefoi & wp     
\end{tabular}
\end{document}

Tags:

Macros

Tables