9

I want to capture the math mode through a redefinition of the $. I thought about something like

\def$#1${here was a formula}
% to test
$x+y=z$

I would expect "here was a formula" as output. Is it possible ?

EDIT : egreg's solution works for me :

\documentclass{article} 
\catcode`\$=\active
\gdef$#1${Formula(\detokenize{#1})}
\begin{document}

voila le calcul $3+4=5$

\end{document}

But i would like also to redefine the double dollar $$ ...$$. If i define additionally :

\gdef$$#1$${centered-Formula(\detokenize{#1})}

then the following works :

voila un calcul centré $$x+y=z$$

but I can't use the single dollar anymore: $3+4=5$ fails now to compile.

Question : how can I have both $...$ and $$...$$ available ?

  • 5
    Possible, but slightly dangerous: \catcode`$=\active and then \protected\def$#1${foo} – egreg Jun 15 '12 at 12:45
  • 4
    Why do you want this? There may be an easier way to achieve what you want. – Seamus Jun 15 '12 at 13:01
  • 1
    @Seamus: I actually did it in this answer (because I prefer $...$ to \(...\)). – Hendrik Vogt Jun 15 '12 at 13:23
  • @egreg. I know, I can put the \catcode in a group, and this will have no effect outside. But if i don't, how can I cancel the effect of '\catcode$=\active' later on in the document ? And for which reason did you put a \protected` ? – nicolas roy Jun 15 '12 at 19:19
  • 2
    Well, my question about how to cancel the effect, was just a subsidiary question, because to frightened me with "dangerous". But your answer is perfect for me. What i want to do : i want to export a tex document into some xml file. For this, i need to capture the maths formulas, a make \write of the \detokenize of the content of the math environment. With your catcode trick, it works. – nicolas roy Jun 15 '12 at 19:41
14

You can, but there's no guarantee that it will work in all situations:

\begingroup
\catcode`\$=\active
\protected\gdef$#1${...}
\endgroup
\AtBeginDocument{\catcode`\$=\active}

For $$...$$, with even less guarantees:

\documentclass{article}
\usepackage[T1]{fontenc}
\catcode`$=\active
\makeatletter
\protected\def${\@ifnextchar$\@doubledollar\@singledollar}
\def\@doubledollar$#1$${centeredFormula(\detokenize{#1})}
\def\@singledollar#1${Formula(\detokenize{#1})}
\makeatother

\begin{document}

$a+b=b+a$

$$a-b\ne b-a$$

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.