3

I'm going to change a catcode to active and then implement my own formatting of small verbs:

\if-not-active
  \catcode`|=\active
  \def|#1|{\foo{#1}}
\fi

I want to make this non-intrusive and check first, whether it's already active. If it is, make no changes. How can I do this?

yegor256
  • 12,021

2 Answers2

6

You can access the category code of any character.

\ifnum\catcode`|=\active
  \typeout{BEWARE! The bar is active!}%
\else
  \catcode`|=\active
  \def|#1|{\foo{#1}}
\fi

TeX maintains a few arrays for the characters, indexed from 0 to 255 (or 0x10FFFF when using a Unicode engine)

\catcode
\lccode
\uccode
\sfcode
\mathcode
\delcode

Each entry in these arrays is an integer and you assign the values with

<array name><integer>=<integer>

For instance, plain TeX begins by assigning

\catcode`{=1
\catcode`}=2

so as to enable reading macro arguments. Other assignments are hardwired, for instance assigning category code 0 to the backslash or space factor code 999 to the uppercase letters.

How you denote the integers is irrelevant. For instance any of

\catcode`|=13
\catcode 124=13
\catcode`^^<=`\^^M

would be equivalent to

\catcode`|=\active

If TeX finds the name of one of those arrays when an assignment doesn't make sense, it interprets it as querying the value in a slot. Thus

\the\catcode`\\

will print 0. But already \catcode`| returns an integer that can be fed to \ifnum or in any place where TeX is expecting an integer.

A bit of overloading, but it's done for keeping TeX as small as possible and is not as mysterious as it can appear at the beginning.


Another case of overloading is with \font, the primitive for defining a control sequence to mean a font change. If you use \font where TeX is expecting a font switching command, it will point to the current font.

So if you want to query the width of A in the current font you can use

\fontcharwd\font`A
egreg
  • 1,121,712
4
\ifnum\catcode`\|=\active
yes
\else
no
\fi

(\active is just a shortcut for the number 13)

David Carlisle
  • 757,742