[Tex/LaTex] Make first row of table all bold

boldformattingtables

I'm trying to do something that I thought would be relatively simple but seems to be quite hard. I have a table with a number of columns, and I'd like to make all of the titles appear in bold text. Obviously I can add \textbf to each of them in turn, but it strikes me that there must be a nicer way of doing this (particularly for tables with many columns).

As far as I can see there isn't a good way of doing this with plain LaTeX. Are there any packages that make this (and possibly other table-related issues) easier?

Best Answer

Taking apan's comment and turning it into an example:

\documentclass{article}
\usepackage{array}
\newcolumntype{$}{>{\global\let\currentrowstyle\relax}}
\newcolumntype{^}{>{\currentrowstyle}}
\newcommand{\rowstyle}[1]{\gdef\currentrowstyle{#1}%
  #1\ignorespaces
}

\begin{document}
\begin{tabular}{$l^c^r}
\rowstyle{\bfseries}
a & a & a \\
b & b & b \\
c & c & c \\
\end{tabular}
\end{document}

This gives:

enter image description here

You might, of course, choose different markers for the column types.


To explain what is going on, the first 'column' is of type $ (could be any symbol not required in the preamble). This simply sets \currentrowstyle to do nothing, which means that in each row this command will be a no-op unless something else happens. The first real column (here l) will contain the command to make it bold (if required), but that is not true for the other columns. They therefore are preceded by ^, which is another fake column type used to apply \currentrowstyle.

In a normal row, \currentrowstyle therefore starts off as \relax and never changes, so the ^ do nothing and the row is unchanged. However, if the first column sets \rowstyle, this is saved as \currentrowstyle (for the later columns) and applied (for this column). The ^ then insert this at the start of each column in the row, so everything is bold.

(All of the operations are global as table cells form groups.)