# How to change catcode in environment

I try to locally change catcode in environment

\newenvironment{wse}
{
\catcode^=\active%
\def^{\mathchar\numexpr"7000+\^\relax}%
$} {$
}


but the next code

\begin{wse}
x^2
\end{wse}


breaks with

! Missing control sequence inserted.


What is wrong?

When you do \newenvironment, the category code of ^ is 7 and this is not changed by \catcode^=\active.

\begingroup
\catcode^=\active
\gdef\changehat{\def^{\mathchar\numexpr"7000+\^\relax}}
\endgroup

\newenvironment{wse}
{%
\catcode^=\active
\changehat
$% } {%$%
}


Full example

\documentclass{article}

\begingroup
\catcode^=\active
\gdef\changehat{\def^{\mathchar\numexpr"7000+\^\relax}}
\endgroup

\newenvironment{wse}
{%
\catcode^=\active
\changehat
$% } {%$%
}

\begin{document}

X$a^b$X\begin{wse}a^b\end{wse}X

\end{document}


An alternative with the \lowercase trick that assumes ~ is active.

\documentclass{article}

\newenvironment{wse}
{%
\catcode^=\active
\begingroup\lccode~=\^ \lowercase{\endgroup
\def~{\mathchar\numexpr"7000+\^\relax}}%
$% } {%$%
}

\begin{document}

X$a^b$X\begin{wse}a^b\end{wse}X

\end{document}

• It works like a charm! It look's like this is the only way i forget to try. It's because for some days i work on custom env and pretty tired to deal with TeX kind of matryoshka, i mean definition, redef, create local scope and so on. Thank you! – dann Sep 22 '17 at 20:54
• @user6786661 Remember that a \def only stores character tokens with the category code they have at the moment the definition is made and that \def` does no interpretation whatsoever of the tokens in the body. The above indirect method is one of the tricks to use; there exist variations on the theme, I showed also one of them. – egreg Sep 22 '17 at 20:57