Friday, September 25, 2009

Numbering every paragraph

One occasionally finds cause to number every graf in a document. Well, I never have, but I've seen it done. There's a neat little trick that is mentioned in passing in an exercise in the TeXbook that easily enables this. This relies on a TeX primitive \everypar which is essentially a token register which is to say that it holds a list of tokens that can be used again and again. What exactly a token is is a topic for another post. When TeX starts a new paragraph (or more precisely, when it enters horizontal mode), it does two things. First, it inserts an empty box of width \parindent (this is the indentation that occurs at the start of every graf) and then it will process the tokens defined by \everypar before going on to process the rest of the tokens that make up the graf. The upshot of this is that we can cause TeX to do something at the start of every graf, but after it inserts the indentation glue. The way to use this is to doing something like the following.
        \arabic{grafcounter}. }
Thus, at the start of every graf, 1 will be added to our counter and then the value of the counter typeset as arabic numerals followed by a period and a space will be prepended each graf. This is close, but not exactly what we want. We'd really like the graf number to appear in the margin. To do this, we use \llap—which is supposed to be Left overLAP. The way this works is that the argument to \llap will be typeset overlapping anything to the left. In this case, we can change the \everypar line to be
which will cause the graf number to appear indented a single \parindent into the margin—one \parindent to cancel the initial indentation and then a second to indent left into the margin. If there are already tokens in \everypar, we might not want to lose them. In this case, we can use \expandafter to append tokens, similar to how we appended to a macro.
Of course, we might want the other tokens to follow our graf numbering. Prepending; however, is a topic for another day.

No comments:

Post a Comment