4

I'm trying to create a table environment with:
A header row that spans an arbitrary number of columns,
aligned, automatically numbered cells with aligned numbers
uniform spacing between the all numbers and content cells,
and the need to pass only the number of columns and header text as parameters.

I almost have it:

\documentclass[a4paper]{book}
\usepackage{environ}
\usepackage{tabu}
\usepackage{array}

\newcounter{mycounter}
\newcommand{\mycount}{\stepcounter{mycounter}\arabic{mycounter})}

\makeatletter
\edef\numcols{\tabu@nbcols} % allows for arbitrary column span
\makeatother

\newcolumntype{C}{>{\mycount\makebox[1em]}l}
\NewEnviron{mytable}[2]{ % table format, header text
  \begin{tabu}{#1}
    \multicolumn{\numcols}{c}{#2} \\
    \BODY
  \end{tabu}
}



\begin{document}

\begin{mytable}{CCCC}{I span all columns.} % cell content chosen at random
  83   & some text   & $23+7$ & 9999 \\
  5000 & more text   & $23+7$ & 9999 \\
  5000 & 83          & $23+7$ & 9999 \\
\end{mytable}

\end{document}

Compiled:

Misalignment

This almost nails it, the problem is that the cell numbers don't align (I want the parentheses to line up), and that cell numbers with more digits shift the other content to the side, as displayed in the bottom row. What is the best way to fix this?

1
  • Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format.
    – user11232
    Oct 31, 2014 at 1:54

1 Answer 1

6

Use

\newcolumntype{C}{>{\makebox[1em][r]{\mycount}\hspace{0.5em}}l}

enter image description here

3
  • Follow up question: is there a good way to cause the table to reflow to accommodate larger numbers? If a counter gets to high, it overflows to the column on its left.
    – Texman
    Oct 31, 2014 at 2:04
  • @Texman You can change 1em to 2em for example. If you want automatic adjustment, there is also \varwidth.
    – user11232
    Oct 31, 2014 at 2:10
  • I understand changing the makebox size for specific cases, but I can't seem to discern the correct way to use \varwidth here. Could you explain further?
    – Texman
    Oct 31, 2014 at 3:02

You must log in to answer this question.

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