[texhax] Low-level TeX question: string substitution macro

Toby Cubitt tsc25 at cantab.net
Tue May 29 22:26:45 CEST 2007


CV Radhakrishnan wrote:
> On Tue, May 29, 2007 7:08 pm, Toby Cubitt said:
>> I'm trying to write an internal macro that does string substitution, in
>> order to escape certain characters in the string before writing it to a
>> file. (The package is supposed to be writing a sed script, so I need to
>> escape characters that have a special meaning in regular expressions.)
>>
>> If this was a user-level macro to be used in the LaTeX source itself, I
>> think can see how it could be done, by changing the catcodes of the
>> characters to be escaped to 13 (active character), then defining these
>> active characters to expand to escaped versions of themselves. (I
>> suppose this would be somewhat akin to LaTeX's \verb command). The
>> trouble is, this macro is to be used in a LaTeX package, and I need
>> something like the following to work:
[snip]
> This will work with a slight modification as given below:
> 
> |gdef|@escapechars{%
> %   |begingroup
>    |catcode`|=0
>    |catcode`.=13 |catcode`[=13 |catcode`]=13
>    |catcode`^=13 |catcode`$=13 %$
>    |catcode`\=13
>    |def\{|string\|string\}%
>    |def^{|string\|string^}%
>    |def${|string\|string$}%
>    |def.{|string\|string.}%
>    |def[{|string\|string[}%
>    |def]{|string\|string]}%
> %   #1|endgroup%
> }
> |endgroup%
> 
> {\tt\@escapechars \foobar ^FOO $foo}

This is exactly what I meant by "if this was a user-level macro to be 
used in the LaTeX source itself, I think can see how it could be done". 
If you replace the final line by:

\def\@tmpa{\foobar ^FOO $foo}
{\expandafter\@escapechars\@tmpa}

then it fails with the "undefined control sequence \foobar" error, as 
before. The point is that the string containing the characters I need to 
escape is stored in a macro, *not* entered manually in the LaTeX source.

Thanks for taking the time to reply though,

Toby


More information about the texhax mailing list