Assume that a token register contains a sequence of letter tokens, each having a catcode of 12. I want to store in a second token register the same sequence of letter token, altering some catcodes on the way (like changing all # so that they have catcode 6).

I see three ways to do this:

  1. Iterating over the sequence of tokens with futurelet and do the replacement. This method has the inconvenient that adding tokens at the end of a token register involves a lot of expansions and parsing but the advantage that it can be generalised.

  2. Using a macro with an argument template (like what we do to see if a token is in a sequence) to quickly parse the token register. It has the drawback that it is maybe not easy to generalise.

  3. Write the tokens in some auxiliary file, reconfigure the lexer and reread these tokens. It is ugly.

Is there an easier way to go? (In plain TeX, no Lua, no Perl, no OCaml…)

  • 4
    Is e-TeX's \scantokens allowed?
    – egreg
    Commented Dec 5, 2013 at 18:22
  • @egreg No it is not. :) I am looking for a TeXbook answer. Commented Dec 5, 2013 at 18:23
  • 4
    So the only way is a slow parsing character by character.
    – egreg
    Commented Dec 5, 2013 at 18:48
  • 3
    Refusing e-TeX is really making it deliberately hard, in contradiction to the question title. Is this for a paper on the history of TeX? The TeXbook answer is really "Don't do this kind of thing. TeX was not made for it." Commented Dec 8, 2013 at 6:00
  • 1
    are there space tokens possibly involved or exclusively catcode 12 (perhaps 11?) character tokens? (I am asking this because \string or e-TeX \detokenize may produce catcode 10 spaces, and perhaps this is what you have as input to your catcode changing task).
    – user4686
    Commented Mar 13, 2014 at 18:51

3 Answers 3


I took this question as a learning opportunity for me, more than an actual attempt to satisfy a question for you, and so my answer is not yet a generalized approach (though I think it could get there with a little work). I would say this method falls in your category #2, "Using a macro with an argument template (like what we do to see if a token is in a sequence) to quickly parse the token register."

I didn't know how to test whether I was successful with manipulating a # symbol's catcode, so I took a less challenging problem, the underscore _, knowing that I could throw it between some dollar signs and immediately know whether I was successful in changing the catcode.

The solution was EDITED so that the \iterationengine is now recursive, and will continue until all catcode12 underscores have been replaced with catcode8 underscores. Originally, I had to invoke the iteration engine successively, by hand.

In the MWE below, after setting up my macro, I test it on four separate strings, containing 0, 1, 2, and 3 underscores.

I haven't been able to confirm it, but the detector routine (\detectus) may fail if it encounters a catcode12 underscore followed by a normal catcoded \testchar (in this case, \relax).

  \if T\Detected%
    \if T\Detected\protected@edef\catEightTok{\expandafter\changeus\catEightTok\relax}\fi%
  \makebox[3cm][l]{$\rawtok$} raw token in math\par
  \makebox[3cm][l]{\catTwelveTok} detokenized raw token (cat12)\par
  \makebox[3cm][l]{$\catTwelveTok$} cat12 token in math\par
    detokenized converted token (cat 8)\par
  \makebox[3cm][l]{$\catEightTok$} converted token, in math
\vspace{1ex}\def\rawtok{a_b c_d}\runtest\par
\vspace{1ex}\def\rawtok{a_b c_d e_f}\runtest\par

enter image description here


This is a Plain TeX (or any other format) general purpose macro \scanthechars which accepts on input a string of character tokens of catcode 12 (1) and puts them in the same order but with transformed catcodes in a token list register called \replacetoks.

(1) this update adds two \string's to the \@@scanthechars macro, and as a result the input is not anymore restricted to be with catcode 12 tokens only. It may even contain control sequences (but not braced material) which will go through unarmed, and one may convert back and forth between various catcode regimes -- see updated image.

The interface to specify the catcodes is via a macro \replacesetup which is fetched with a comma separated list of things like \!{3} which means to transform the character token ! into a catcode 3 character token !.

The illustrative tests use \detokenize for simplicity sake, to produce easily catcode 12 tokens, or verbatim output, hence the code needs etex or pdftex for compilation. But the macros themselves are strictly Knuthian.

Only catcodes of 3, 4, 6, 7, 8, 11, 12, 13 are dealt with.

Each use of \scanthechars resets \replacesetup: next call to \scanthechars must follow a renewed \replacesetup. Since now the input is not restricted to be only with catcode 12 tokens, one may use \scanthechars many times on the same string. See the code and image for how this is done.

catcode replace

catcode replace (seq.)

The code:

\catcode`@ 11
\long\def\@gobble      #1{}
\long\def\@firstoftwo  #1#2{#1}
\long\def\@secondoftwo #1#2{#2}


\def\replacesetup #1{%
% this assumes non nil escapechar
    \def\replace@list {}%
    \def\replace@do ##1##2%
       {\expandafter\def\csname replace@setup@\expandafter
                                      \@gobble\string##1\endcsname {##2}}%
    \replace@setup #1,\relax\relax,%

\def\replace@setup #1#2,{%
          {\replace@list \replace@do #1{#2}}%

\def\scanthechars #1{\replacetoks{}%
                                 \lccode`a=`a \lccode`(=\the\lccode`(
           \@scanthechars #1\relax}

\def\@scanthechars #1{\ifx #1\relax\expandafter\@firstoftwo
                      {\def\replace@do ##1##2{\expandafter
                         \let\csname replace@setup@\expandafter
                       \replace@list % resets to relax everything
                      {\@@scanthechars #1}%

\def\@@scanthechars #1{\expandafter
                 \ifx\csname replace@setup@\string#1\endcsname\relax
                    \replacetoks\expandafter{\the\replacetoks #1}%
                    \ifcase\csname replace@setup@\string#1\endcsname\relax
                    \or\or\or % catcode=3
                      \lccode`$=`#1 %$
                      {\replacetoks\expandafter{\the\replacetoks $}}%$
                    \or % catcode=4
                      {\replacetoks\expandafter{\the\replacetoks &}}%
                    \or\or % 6
                      {\replacetoks\expandafter{\the\replacetoks ##}}%
                    \or % 7
                      {\replacetoks\expandafter{\the\replacetoks ^}}%
                    \or % 8
                      {\replacetoks\expandafter{\the\replacetoks _}}%
                    \or\or\or % 11
                      {\replacetoks\expandafter{\the\replacetoks a}}%
                    \or % 12
                      {\replacetoks\expandafter{\the\replacetoks (}}%
                    \or % 13
                      {\replacetoks\expandafter{\the\replacetoks ~}}%

\catcode`@ 12

% utility macro to get the catcode of a character token
% manages only catcodes 3,4,6,7,8,11,12,13
\def\TheCatcode #1{\ifcat\noexpand#1$3\else% $
                          \ifcat\noexpand#1\noexpand~13\else not handled
                   \fi\fi\fi\fi\fi\fi\fi\fi }



Test I. 










\ifx\z\y OK\else WRONG\fi


Test II.



\catcode`@ 11
\catcode`@ 12

% creates an x with catcode 12 a, b, c






\ifx\z\y OK\else WRONG\fi


Test III.



\expandafter\scanthechars\expandafter {\detokenize{abcd}}% convert to catcode 12

\edef\y {\the\replacetoks}

\def\PrintTheCatcode #1{\string#1 with catcode \TheCatcode #1\par }
% previously, we used xinttools.sty:
% \xintApplyInline{\PrintTheCatcode}{\y}

\def\PrintTheCatcodes #1{\ifx#1\relax\else\PrintTheCatcode#1\expandafter
                                          \PrintTheCatcodes\fi }

% \replacesetup must be redone each time

\expandafter\scanthechars\expandafter {\detokenize{adbdcda}}



Test IV.

\overfullrule 0pt

\replacesetup {\!{6}}

\scanthechars {!}




\ifx\z\y OK\else WRONG\fi


From now on we don't require the input to be with catcode 12 tokens.

\replacesetup{\#{3}, \_{11}, \^{11}, \!{4}, \?{7}, \&{8}, \@{6}}

\detokenize{\replacesetup{\#{3}, \_{11}, \^{11}, \!{4}, \?{7}, \&{8}, \@{6}}}

\scanthechars {\tabskip1ex #\mathstrut @#\hfil!\hfil #@#\hfil!\hfil#@#\cr
                        1!23!456\cr 7890!a!bc\cr
                \noalign\bgroup\hrule\egroup }

\detokenize{\scanthechars {\tabskip1ex #\mathstrut @#\hfil!\hfil #@#\hfil!\hfil#@#\cr
                        1!23!456\cr 7890!a!bc\cr
                \noalign\bgroup\hrule\egroup }



% \expandafter\PrintTheCatcodes\the\replacetoks\relax

% attention _ is mathematically active!
% in plain.tex \mathcode`\_="8000 % \_


\replacesetup{\#{3}, \_{11}, \^{11}, \!{4}, \?{7}, \&{8}, \@{6}}
\detokenize {\replacesetup{\#{3}, \_{11}, \^{11}, \!{4}, \?{7}, \&{8}, \@{6}}}
\scanthechars {##___^?\bgroup abc\egroup &\bgroup\hbox\bgroup___\egroup\egroup##}

\detokenize {\scanthechars {##___^?\bgroup abc\egroup &\bgroup\hbox\bgroup___\egroup\egroup##}}




\string_ is mathematically active, the subscript is in an \string\hbox\space
hence the catcode 11 version is used, but the first three use \string\_ as
defined in plain.tex for the math active \string_, which now has catcode letter

Let's now go back to catcode 12:


\replacesetup {\#{12}, \_{12}, \^{12}, \!{12}, \?{12}, \&{12}, \@{12}}



\detokenize{\replacesetup {\#{12}, \_{12}, \^{12}, \!{12}, \?{12}, \&{12}, \@{12}}}







  • in the image in smaller print the #### are the way \detokenize prints ## from its input (which is seen at the bottom of the image, where now \meaning has been used but # at this stage has catcode 12).
    – user4686
    Commented Mar 14, 2014 at 18:49
  • if anybody reads this, just to point out that unarmed is to be read unharmed. Knew something was fishy, took me a while to find out what.
    – user4686
    Commented Mar 14, 2014 at 21:09

In the intervening years since my other answer, I have written the tokcycle package for taking an argument or input stream one token at a time, and "doing something with it". It can easily be set up to do something with cat-12 # tokens and reconvert them to cat-6, since this seems to be what the OP desires.

The MWE works through a progression:

  1. the standard cat-6 approach to \def

  2. What happens if the argument of the \def contains cat-12 #.

  3. What happens if both the argument and the \def parameter itself are cat-12 #.

  4. Now I set up tokcycle to convert cat-12 # tokens back to cat-6. In this step, I first pass only cat-6 # tokens to the cycle, to show that it can process them without issue (but no conversion is needed).

  5. Here, I convert a cat-12 # in the argument to a \def back to cat-6, with the expected result.

  6. Here, I convert the cat-12 # tokens in both the argument and in the \def parameter specification back to cat-6, with the expected result.

  7. Here, I operate in an underlying cat-12 # environment, and still successfully convert occurrences of # back to cat-6, with the expected result.

The MWE:

\documentclass {article}
1.\def\Q#1{My argument is [#1]}

2.\def\QQ#1{My argument is [\TWELVEhash1]}

3.\def\QQQ\TWELVEhash1{My argument is [\TWELVEhash1]}


\gdef\W#1{My argument is [#1]}

\gdef\WW#1{My argument is [\TWELVEhash1]}

\gdef\WWW\TWELVEhash1{My argument is [\TWELVEhash1]}

\gdef\WWWW#1{My argument is [#1]}
\WWWW{X} #####

enter image description here


The case, above, of cat-6 changes is more challenging because of the way cat-6 tokens are processed (the need for ##, ####, etc). For other catcode conversions, the tokcycle process is easier, since I don't have to ascertain whether the token is part of a parameter. Here, I do something analogous with the underscore _.

\documentclass {article}


2. \expandafter\tokencyclexpress\Q\endtokencyclexpress


4. $\tokencyclexpress a_1\endtokencyclexpress$

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .