2

This question is for a command, that would do the same thing as \multicolumn except that it just uses the total number of columns in the row.

Something as simple as

\newcommand\allcolumns[2]{\multicolumn\AnswerToThisQuestion{#1}{#2}}

A \multicolumn* variant to do the same might be cute.

Yossi Gil
  • 15,951
  • 1
    As far as I can tell, LaTeX doesn't keep a count of the number of columns. Instead, \multicolumn simply counts down to zero. OTOH, \hline uses \noalign and \arrayrulewidth. – John Kormylo Feb 13 '17 at 15:56
  • I did not quite get this "speaking in tongues" of \hline and longer latex commands I dare not type lest I err. In other words: are you saying that I can the same functionality can be obtained with tricks using \arrayrulwidth? – Yossi Gil Feb 13 '17 at 16:23
  • some packages need this (longtable for example has to do it for \caption (which in that package is in a \multicolumn just as described) but one difficulty is defining what you mean by number of columns, if you use \begin{tabular}{cccc} but every row just has two entries, you would want to generate \multicolumn{2} not \multicolumn{4} ams matrices for example are always declared with more columns than used. – David Carlisle Feb 13 '17 at 17:01
  • For some reason, \noalign{\hrule} expands to the size of the enclosing \vbox, but \noalign{(\hfill)} expands to \textwidth (and includes \parindent}. – John Kormylo Feb 13 '17 at 17:26
  • @JohnKormylo: Yes, but \hline does not need to know the number of columns. It just needs the width of the box. –  Feb 13 '17 at 17:45
  • @ChristianHupfer - Given the width one can use \makebox to create the entry. This approach appears to be a dead end, though. – John Kormylo Feb 13 '17 at 17:52
  • And how would you manage the column type argument to \multicolumn? – Yossi Gil Feb 13 '17 at 18:11

1 Answers1

5

This is an ugly hack, exploiting counting the number of columns with \@addamp, stepping a counter, which is reset every time a new tabular environment is started.

I don't claim this to work for any occasion.

\documentclass{article}

\usepackage{xpatch}

\newcounter{colcntr}



\makeatletter
\xpatchcmd{\@addamp}{\if@firstamp}{\stepcounter{colcntr}\if@firstamp}{}{}
\makeatother

\newcommand{\allcolumns}[2]{%
  \multicolumn{\number\value{colcntr}}{#1}{#2}%
}


\AtBeginEnvironment{tabular}{\setcounter{colcntr}{0}}

\begin{document}
\begin{tabular}{|l|l|l|}
  Long & table column & stuff \tabularnewline
  \allcolumns{|c|}{Foo stuff}
\end{tabular}

\end{document}

enter image description here

  • I am confused. LaTeX is happy to complain when I use too many columns. So, it must be keeping the number of columns somewhere. Even if this location is not accessible, one can still hook to the code that checks for too many columns. – Yossi Gil Feb 13 '17 at 18:09
  • @YossiGil: That's true, but I haven't found it yet –  Feb 13 '17 at 18:33