[texhax] How to write a TeX code into file literally

Heiko Oberdiek heiko.oberdiek at googlemail.com
Sun Oct 9 13:27:27 CEST 2011


On Sun, Oct 09, 2011 at 06:22:41PM +0800, Yue Wu wrote:

> Another question arises, I try to let TeX not expand macros at all for a
> \write, so I tried with it:
> 
> \newwrite\myout
> \immediate\openout\myout=myout.tex
> \long\def\myoutone{%
>   \begingroup
>   \catcode`\|=0
>   |catcode`|\=12
>   |catcode`|#=12
>   |catcode`|&=12
>   |immediate|write|myout{}
>   |myouttwo
> }
> \long\def\myouttwo#1#2{%
>   |immediate|write|myout{#1|endgraf#2}
>   |endgroup
> }

\catcode`\|=0 is inside the definition, thus it is only
called if \myoutone is executed. For the definition text
the catcodes are used that are active at the time of the
definition. Therefore you don't need the hack with |.

\def\myoutone{%
  \begingroup
  \catcode`\\=12 %
  \catcode`\#=12 %
  \catcode`\&=12 %
  \immediate\write\myout{}%
  \myouttwo
}
\long\def\myouttwo#1#2{%
  \endgroup
  \immediate\write\myout{#1\noexpand\endgraf#2}%
}

If you are using plain TeX or LaTeX look at \dospecials and
\@sanitize, e.g. for plain TeX:

\def\myoutone{%
  \begingroup
  \def\do#1{\catcode`#1=12 %}%
  \dospecials
  \catcode`\{=1 % are needed as argument delimiter for \myouttwo
  \catcode`\}=2 %
  \immediate\write\myout{}%
  \myouttwo
}

Yours sincerely
  Heiko Oberdiek


More information about the texhax mailing list