[texhax] What's wrong with \catcode`\_=12

Heiko Oberdiek heiko.oberdiek at googlemail.com
Thu Oct 6 12:06:08 CEST 2011


On Thu, Oct 06, 2011 at 10:52:43AM +0800, Yue Wu wrote:

> On Thu, Oct 06, 2011 at 02:53:00AM +0200, Heiko Oberdiek wrote:
> > On Thu, Oct 06, 2011 at 08:29:21AM +0800, Yue Wu wrote:
> > 
> > > I want to define a macro to let _ can be directly used in it but failed,
> > > The minimum failed example:
> > > 
> > > \def\mytest#1{{\chardef\_=95 \catcode`\_=12 #1}}
> > > \mytest{foo_bar}

> > What's the purpose of "\chardef\_=95"?
> 
> 
> I want the char `_' to produce a literal `_' as it is, but with the
> macros following, it will produce a `??'.
> 
> 
> > That "\_" prints as "_"?
> > 
> > \def\mytest{%
> >   \begingroup
> >   \catcode`\_=12 %
> >   \mytesti
> > }
> > \def\mytesti#1{%
> >   \chardef\_=95 %
> >   #1%
> >   \endgroup
> > }
> > \mytest{foo_bar\_bla}

The `_' and `\_' both print the character 95 of the current font
in the current font encoding. Font encoding T1 works:

  \font\eclmr=ec-lmr10
  \eclmr

In OT1 is different, because OT1 is not consistent.
Typewriter (cmtt) does have the underscore in that position:

  \tt

LaTeX users can use \textunderscore:

\documentclass{article}

\begingroup
  \catcode`\_=\active
  \makeatletter
\@firstofone{%
  \endgroup
  \newcommand*{\mytest}{%
    \begingroup
    \catcode`\_=\active
    \mytest at i
  }%
  \newcommand*{\mytest at i}[1]{%
    \def_{\textunderscore}%
    \def\_{\textunderscore}%
    #1%
    \endgroup
  }%
}

\begin{document}
\mytest{foo_bar\_bla}
\end{document}

Yours sincerely
  Heiko Oberdiek


More information about the texhax mailing list