Use local {
... }
groups wisely
As pointed out in this answer, active characters like ~
can be used as a macro name. Unfortunately, ~
is the only active character by default, and changing the catcode for another character is expensive: \catcode`!13
takes 12 bytes. If the new macro definition is only needed in a small region of your code, local groups can be a solution.
When TeX enters a new local group opened by {
, it creates a new grouping level on the internal save stack. This means that all current macros and registers are saved. Any modifications to them (unless explicitly marked as \global
) are now only being active until the group is closed by }
. This means that ~
can be redefined within a group, used there with the new definition, and the old defintion will automatically be restored after the group has finished.
Here's an example:
\def~{abc}
~ -- {\def~{123}~} -- ~
This outputs
abc - 123 - abc
An interesting side effect of this grouping mechanism is that the old values are still available inside the group until they are changed there. To illustrate that, imagine we want to print a number of characters based on the value of a counter, pad them with spaces up to a fixed length, and go on with the original counter value. This could be achieved by the following:
\newcount\x
\x=3
Print a char \the\x\ times,
{\x=-\x \advance\x 10 pad with \the\x\ spaces,}
and go on with x=\the\x.
which outputs
Print a char 3 times, pad with 7 spaces, and go on with x=3.
This grouping behaviour is especially important if you want to use TeX's standard macros for looping \loop ... \repeat
nested. These macros define internal commands and use them for determining how to proceed. Nesting them without putting the inner loop into braces will confuse the internal commands and lead to unexpected behaviour.