# How to change #catcode in a macro

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.

-
Li: A tip: If you indent lines by 4 spaces, then they are marked as a code sample. You can also highlight the code and click the "code" button (with "101010" on it). –  lockstep Mar 4 '11 at 9:21

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.

-
Thank you. I know in general, I need to use this code out of a macro. But I wish I can write a macro, which read the stream begin with \\ (such as \test), then stores test (without \) in somewhere. So, if I use \begingroup \catcode\|=0 \catcode\\=12 |@tfor|B:=\test|input|do{\if \|B |relax |else do something|fi} –  Kuang-Li Huang Mar 4 '11 at 16:12
@Kuang-Li Huang: You can convert a macro like \test read be macro as argument #1 into test using \expandafter\@gobble\string#1. Note that \string returns the following token (e.g. a macro) as its string representation, e.g. the macro \test as string "\test". The \@gobble then removes the \\ . The \expandafter is required to expand \string before \@gobble. Alternatively you can change the \escapechar variable which tells \string which character to place for the \\ `. –  Martin Scharrer Mar 4 '11 at 16:19