6

Assume that I enjoy setting my tables using an \itemized or list-like coding structure:

\begin{mytabular}[.5\textwidth]
  \item head1 & head2% <-- header row
  \item abc & def
  \item ghi & jkl
\end{mytabular}

The idea is that I always have the first row being a header row, with subsequent rows representing the items, so the above input should translate to the following output:

\begin{tabularx}{.5\textwidth}{XX}
  \toprule
  head1 & head 2 \\% <-- header row
  \midrule
  abc & def \\
  ghi & jkl \\
  \bottomrule
\end{tabularx}

Since each row is identified by an \item, appropriate redefinitions of \item could be used to tie into discerning whether I'm setting a header/not. Below I've used some delayed redefinition of \item:

\documentclass{article}
\usepackage{tabularx,booktabs,environ}

\NewEnviron{mytabular}[1][\linewidth]{%
  \let\olditem\item
  \gdef\item{%
    \gdef\item{%
      \\\midrule\gdef\item{%
        \\}}}
  \begin{tabularx}{#1}{XX}
    \toprule
    \BODY \\
    \bottomrule
  \end{tabularx}
  \let\item\olditem
}

\begin{document}

\noindent
\begin{mytabular}[.5\textwidth]
  \item head1 & head2
  \item abc & def
  \item ghi & jkl
\end{mytabular}

\end{document}

The intent is that the first \item should do nothing; the second \item should turn into \\ \midline and every subsequent \item should become \\. However, this never happens:

enter image description here

It turns out tabularx processes its body multiple times. Is there a way to establish which cycle of processing I'm in so that one can guarantee appropriate actions to be taken? The aforementioned question is akin to amsmath's use of \ifmeasuring@ in an align-type display.

egreg
  • 1,121,712
Werner
  • 603,163

1 Answers1

11

During its trials tabularx makes various local definitions to stop things happening multiple times, or to stop you getting multiple warnings about the bad boxes for bad trials.

In particular it does

    \hfuzz=\maxdimen
    \let\hfuzz\@tempdima

(Actually without the =) so you get no overfull hbox warnings during the trials.

On the final run it does a setting with all these reverted to normal so you can use

    \ifx\@tempdima\hfuzz
        trial run
    \else
        final run
    \fi

note this needs to be where @ is a letter or you could use

      \expandafter\ifx\csname @tempdima\endcsname\hfuzz
David Carlisle
  • 757,742