Hendrik's answer is great. Nevertheless, please allow me to elaborate on \string
and \escapechar
a little more:
Like you said the \string
primitive converts a control sequence into a list of character tokens1. It also works on other tokens and turns them into their string representation. Two things are notable here: All characters with the exception of spaces are returned as category code (catcode) 12 "other", even if their where from catcode 11 "letter" beforehand. If the control sequence contained spaces (possible with \csname .. \endcsname
) then they have still catcode 10 "space". This catcode change has no influence on typesetting or \write
ing these characters.
Secondly, the backslash in the control sequence is not stored by TeX with every control sequence name. The backslash is only required to mark a control sequence as one and once that got tokenized it is no longer required. Also the backslash is not hard wired into TeX. Every character with the catcode 0 "escape character" will work. However by default the backslash is the only one character with this catcode.
Because TeX doesn't store the escape character used for every particular control sequence it needs to get told how to represent it when it has to turn the control sequence back into a string. This is done using the \escapechar
register2 which holds the ASCII number of the used character. By default it is that to 92 which is the number for the backslash. This register can be changed at will. If it contains a negative number, no escape character will be produced by \string
at all. This fact is often used by (La)TeX code which like to get the macro name only. Has Hendrik already wrote in his great answer, you need to make sure that the escape character is available in the currently used font. Usually you are right when using a tt font.
So, for example \escapechar=`\A\catcode`\|=0 |string|foo
will output Afoo
, not \foo
or |foo
. After the catcode change TeX doesn't care here if you use |
or \
and you can mix them as you want (Note that \\
can be written as |\
now but not as ||
because the second backslash is not an escape character). You are also not forced to keep \escapechar
to a character of catcode 0.
1) Knuth, The TeXBook, page 40, paragraph 1, Chapter 7: How TEX Reads What You Type.
2) Knuth, The TeXBook, page 40, paragraph 6, Chapter 7: How TEX Reads What You Type.