Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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
}
share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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
share|improve this answer
    
Indeed, it seems to work. Simply awesome, thanks! –  morbusg Feb 3 '11 at 19:46
add comment

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.

share|improve this answer
    
Oh man, that seems more trouble than it's worth. Thanks, though! –  morbusg Jan 1 '11 at 18:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.