# Wrapping \obeylines with \halign into a macro

In the TeXbook, Knuth gives an example:

Are you tired of typing \cr? You can get plain TEX to insert an automatic \cr at the end of each input line in the following way:

\begingroup \let\par=\cr \obeylines %
\halign{⟨preamble⟩
⟨ﬁrst line of alignment⟩
...
⟨last line of alignment}\endgroup


How would one wrap this up into a macro? So that one could use:

\mytable{%
This & is & the & first & row
This & is & the & second & row
}

-

I might be missing a technical issue, but the following seems to work. I simply replaced Joseph's construction of the preamble by the preamble itself, with doubled hash signs because we are inside a definition.

The key point (taken from Joseph's answer) is to use one macro (\mytable) to do \obeylines (i.e. set up the catcode for the newline character), before reading the argument with a different macro, \mytableAux.

\def\mytable{%
\begingroup
\let\par=\cr
\obeylines
\mytableAux
}
\def\mytableAux#1{%
\halign{##&##&##&##&##\cr#1}%
\endgroup
}
\mytable{%
This & is & the & first & row
This & is & the & second & row
}
\bye

-
Indeed, it seems to work. Simply awesome, thanks! – morbusg Feb 3 '11 at 19:46

For example

\def\mytable{%
\begingroup
\let\par=\cr
\obeylines
\mytableAux
}
\def\mytableAux#1{%
\mytoks=\expandafter{\the\myhash}%
\mytoks=\expandafter\expandafter\expandafter
{\expandafter\the\expandafter\myhash\expandafter&\the\mytoks}%
\mytoks=\expandafter\expandafter\expandafter
{\expandafter\the\expandafter\myhash\expandafter&\the\mytoks}%
\mytoks=\expandafter\expandafter\expandafter
{\expandafter\the\expandafter\myhash\expandafter&\the\mytoks}%
\mytoks=\expandafter\expandafter\expandafter
{\expandafter\the\expandafter\myhash\expandafter&\the\mytoks\cr#1}%
\halign\expandafter{\the\mytoks}%
\endgroup
}
\newtoks\mytoks
\newtoks\myhash
\myhash={#}
\mytable{%
This & is & the & first & row
This & is & the & second & row
}
\bye


A lot of the work here is about constructing the template: I've not used a loop or anything subtle, although in a real application you would do. (For example, see how LaTeX2e constructs the \halign template for tabulars.) You need to have the \halign within the group which sets up ^^M=\cr, as this cannot be expanded to do the substitution.

-
Oh man, that seems more trouble than it's worth. Thanks, though! – morbusg Jan 1 '11 at 18:54