I want to change the catcode in a macro, but it seems it doesn't work. Can anyone help me?
\def\A{\catcode`\|=0 |bf{test}}
|bf{test} would not work as expect.
I want to change the catcode in a macro, but it seems it doesn't work. Can anyone help me?
\def\A{\catcode`\|=0 |bf{test}}
|bf{test} would not work as expect.
This doesn't work because the | was already read as part of the argument of \def\A and therefore has its catcode already before the included \catcode is executed.
You need to move the catcode change out of the macro:
\begingroup
\catcode`\|=0
\gdef\A{|bf{test}}
\endgroup
There are also other ways to do it: eTeX privides \scantokens which re-read its content so that the catcodes are reapplied and there is a trick to do it using \lowercase.
Note that in this example makes actually no difference if \ or | is used. It would if you also change the catcode of \ to something else. If you tell us more about your exact application more specific answers can be given.
Also note that your code example would make the catcode change active for the rest of the group \A is used in, which is most likely not what you intend.
\begingroup
\catcode\|=0 \catcode\=12
|@tfor|B:=\test|input|do{\if |B |relax |else do something|fi}
\test read be macro as argument #1 into test using\expandafter@gobble\string#1. Note that\stringreturns the following token (e.g. a macro) as its string representation, e.g. the macro\testas string "\test". The@gobblethen removes the\ . The\expandafteris required to expand\stringbefore@gobble. Alternatively you can change the\escapecharvariable which tells\stringwhich character to place for the\ `.
– Martin Scharrer
Mar 04 '11 at 16:19