# answers package + environ package + equation won't compile

This MWE works perfectly when the I comment out equation in the teacher environment. With that equation in place I get this error:

(C:\Users\Ethan.Bolker\AppData\Roaming\MiKTeX\2.9\tex\latex\trimspaces\trimspac
es.sty))
! Missing \endcsname inserted.
\csname\endcsname
l.30 \end{teacher}


The code:

\documentclass{article}

\usepackage{amsmath}
\usepackage{environ}

\NewEnviron{teacher}{%
}

\begin{document}

An equation in the master file:
%
$$2+2 = 4$$

\begin{teacher}
In answersout: expand a macro: \LaTeX.
Try an equation:
% comment out the next three lines and the document compiles
$$2+2 = 4$$
\end{teacher}

\end{document}


Some history. A previous problem with the answers package led me to this question: Incomplete \iffalse error using answers package

In fact that was the first error I saw when I encountered this problem. That error message was replaced by the one above when I made my example minimal.

You can substitute the \protected@iwrite mechanism with a stronger one that has the defect that it expands nothing. So if you want to add titles to the teacher's notes you have to work in two steps.

\documentclass{article}

\usepackage{amsmath}
\usepackage{environ}

\newcounter{teacher}

\makeatletter
\NewEnviron{teacher}{%
\stepcounter{teacher}%
(See teacher note \theteacher)
\protect\subsection*{Teacher's note \theteacher}%
}
\begingroup
\def\protected@iwrite##1##2##3{\immediate\write##1{##3}}%
\endgroup
}
\makeatother

\begin{document}

An equation in the master file:
$$2+2 = 4$$

\begin{teacher}
In answersout: expand a macro: \LaTeX.
Try an equation:
$$2+2 = 4$$
\end{teacher}

\section*{Teacher's notes}
\end{document}


The problem here is that \BODY gets expanded before being written to the file. The result isn't plain text, and disaster follows. Protecting doesn't help, because the meaning of \BODY is lost at \end{teacher}. One way around this is to store the bodies of the environments using globally defined macros called \tchI, \tchII, \tchIII, etc. These can be protected, and written to the file.

\documentclass{article}

\usepackage{environ}

\newcounter{tchcount}
\setcounter{tchcount}{0}

\NewEnviron{teacher}{%
\stepcounter{tchcount}
\global\expandafter\let\csname tch\Roman{tchcount}\endcsname\BODY
}

\begin{document}

\begin{teacher}
Try an equation:
$$2+2 = 4$$
\end{teacher}

\begin{teacher}
And another
$$1+1 = 2$$
\end{teacher}