5

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⟩
⟨first 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
}

2 Answers 2

6

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
1
  • Indeed, it seems to work. Simply awesome, thanks!
    – morbusg
    Feb 3, 2011 at 19:46
5

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.

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

You must log in to answer this question.

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