This a followup to a previous question of mine: Compiling questions in exam class
I finally managed to create something that does what I want in a nice automatic manner.
First I derived the class exam into
\ProvidesClass{examFull}[2016/11/09 v1.0]
\LoadClassWithOptions{exam}
\RequirePackage{etex}
\newcommand\insertQuestions{
\input{\jobname.exm}
\newwrite\examfile
\immediate\openout\examfile=\jobname.exm}
\AtEndDocument{
\immediate\closeout\examfile}
\newcommand\create@environment[1]{
\newenvironment{my#1}{%
\begin{#1}
\immediate\write\examfile{\string\begin{#1}}
}{%
\immediate\write\examfile{\string\end{#1}}
\end{#1}
}
}
\newcommand\create@item[1]{
\expandafter\newcommand\csname my#1\endcsname[2]{%
\csname #1\endcsname[##1] ##2
\immediate\write\examfile{\string\csname \space #1\string\endcsname[##1] \unexpanded##2}%
}
}
\create@environment{questions}
\create@environment{parts}
\create@environment{subparts}
\create@environment{subsubparts}
\create@item{question}
\create@item{part}
\create@item{subpart}
\create@item{subsubpart}
This class defines new exam-like commands by adding my at the beginning. This commands typeset their argument and they also store it in \jobname.exm.
The main reason to use \unexpanded is so mathmode commands can be used in the argument without being expanded until the file is inserted. The class still needs some improvement, as checks for non-existent file.
Here's a MWE of how it works:
\documentclass{examFull}
\usepackage{amsmath, amssymb}
\begin{document}
\insertQuestions
\clearpage
\begin{myquestions}
\myquestion{2}{This is a question $3\in\mathbb{R}$}
\begin{solutionbox}{3in}
This is a solution
\end{solutionbox}
\begin{myparts}
\mypart{2}{This is a part}
\begin{solutionbox}{3in}
This is a solution
\end{solutionbox}
\end{myparts}
\end{myquestions}
\end{document}
Here comes the question. Running this twice gives the correct document:

However, I get "Missing {" errors in the \myquestion and \mypart lines, and "Forbidden control sequence" also in those lines. Does anyone have any idea what's going wrong and how could I fix it?
\unexpanded##2should presumably be\unexpanded{##2}as it takes a brace group – David Carlisle Nov 09 '16 at 19:25