11

I am trying to understand Knuth's manmac.tex. At line 436 you can find the following code:

\newwrite\ans
\immediate\openout\ans=answers % file for answers to exercises
\outer\def\answer{\par\medbreak
  \immediate\write\ans{}
  \immediate\write\ans{\string\ansno\chapno.\the\exno:}
  \copytoblankline}
\def\copytoblankline{\begingroup\setupcopy\copyans}
\def\setupcopy{\def\do##1{\catcode`##1=\other}\dospecials
  \catcode`\|=\other \obeylines}
{\obeylines \gdef\copyans#1
  {\def\next{#1}%
  \ifx\next\empty\let\next=\endgroup %
  \else\immediate\write\ans{\next} \let\next=\copyans\fi\next}}

Why Knuth used construction {\obeylines \gdef\CMD{BODY}} instead of \def\CMD{BODY}? If I understand correct \obeylines applies only to

\gdef\copyans#1
  {\def\next{#1}%
  \ifx\next\empty\let\next=\endgroup %
  \else\immediate\write\ans{\next} \let\next=\copyans\fi\next}

and there are no characters here that \obeylines could affect.

Note: another example from manmac.tex (line 400)

{\obeylines \gdef|{\ttverbatim \spaceskip\ttglue \let^^M=\  \let|=\endgroup}}
1
  • 9
    The definition is tokenised as \gdef\copyans#1^^M{...} and not \gdef\copyans#1{...}. Commented May 20 at 16:55

1 Answer 1

14

The definition is:

{\obeylines \gdef\copyans#1
  {\def\next{#1}%
  \ifx\next\empty\let\next=\endgroup %
  \else\immediate\write\ans{\next} \let\next=\copyans\fi\next}}

After \obeylines is executed, \gdef reads the <parameter text> for the definition of \copyans. The parameter text then is #1^^M, because there is no % at the end of the line to "hide" the end-line character (which usually is a space, but after \obeylines it is an active ^^M token).

That's why, in texbook.tex you see, e.g.:

\exercise After you have mastered the material in this book, what will
you be: a \TeX pert, or a \TeX nician?
\answer A \TeX nician (underpaid); sometimes also called a \TeX acker.

\endchapter

The \exercise macro typesets the exercise number, and then the exercise text is typeset normally. The \answer macro then writes the current exercise number to the answers.tex file, and calls (eventually) \copyans to grab everything until the next <newline>.

3
  • Re-welcome :-))
    – Sebastiano
    Commented May 20 at 18:55
  • Wow! This is not trivial to understand =) Is the idea with \gdef| same, i.e. \obeyline required for ^^M? Commented May 20 at 19:13
  • 1
    @AlexeyIsmagilov More or less, yes. There, \obeylines is used as a shortcut to make ^^M an active token, so that it can be used explicitly inside the definition of |. Commented May 20 at 21:04

You must log in to answer this question.

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