How to apply a macro to each column of a table

You can use the relatively new collcell package to collect the cell content and feed it to a macro of your choice. It uses the array package to place code before and after each cell.

\documentclass{article}
\usepackage{collcell}
\usepackage{array}% actually already loaded by `collcell`
\newcommand*{\mymacro}[1]{\fbox{#1}}% Do anything you like with `#1`
\newcolumntype{C}{>{\collectcell\mymacro}c<{\endcollectcell}}

\begin{document}

\begin{tabular}{CC}
  TestA  & A longer test cell \\
  \empty & The new version supports 'verb'! \\
\end{tabular}

\end{document}

Make sure you use the version 2011/02/27 (or later) which contains a lot of improvements.

There is also the possibility to do it the following way, which compiles faster than collcell but does not work in the last cell of each row. It reads everything between the internally used macros \ignorespaces and \unskip. I got this from Ulrike Fischer on de.c.t.t a while ago.

\documentclass{article}
\usepackage{array}
\newcommand*{\mymacro}[1]{\fbox{#1}}

\def\simplecollect#1#2\ignorespaces#3\unskip{#1{#3}\unskip}
\newcolumntype{S}{>{\simplecollect\mymacro}c}

\begin{document}

\begin{tabular}{Sc}
  TestA  & Doesn't work in the last cell \\
  \empty & Sorry!  \\
\end{tabular}

\end{document}

It should be as simple as:

\def\mymacro#1{\lowercase{#1}}
\halign{&\mymacro{#}\cr
HELLO&WORLD\cr
TEST&123\cr}
\bye

For Yiannis's comment to apply the macro only to the first column, change the preamble (&\mymacro{#}\cr) to \mymacro{#}&&#\hfil\cr, for example. An ampersand at the very beginning tells TeX to repeat the definition(s) for every column, whereas && defines that the following column definitions should be repeated.

Ofcourse, you don't need to repeat anything if you don't want to.


You can do this by using the array package and defining a \newcolumntype.

For example we can define a macro \test that can take a parameter as its argument and capitalize it.

\def\test#1 {\uppercase{#1}}

We can then define a new column type as:

\newcolumntype{D}{>{\test}l<{.}}

and our minimal example would be:

\documentclass{article}
\usepackage{array}
\begin{document}
  \def\test#1 {\uppercase{#1}}
  \newcolumntype{D}{>{\test}l<{.}}
  \begin{tabular}{DD}
    test &test \\
    other &test \\
  \end{tabular}
\end{document}

Please note that this approach involves delimited macros, in this case the space after the word in the table acts to tell the command that it must only read up to there and obviously will fail if there are more than one word as Martin pointed out. One could use other types of delimiters perhaps a . or a !.

Tags:

Macros

Tables