# Making etoolbox work with the Exam document class

I am trying to use the etoolbox with the document class exam. I have had good luck using etoolbox with the article class, but I can't get it to work inside of the question environment. Here's a minimal example:

\documentclass[12pt]{exam}
\usepackage{etoolbox}

\def\QuizKey{\newpage }

\eappto{\QuizKey}{\noexpand\par\arabic{question}.\ \unexpanded{#2}}
\vspace{#1}
}

\begin{document}
\appto{\QuizKey}{Opening Code}

\begin{questions}
\question When did the Internet first begin?\answer{1985}

\appto{\QuizKey}{Something else to test}
\end{questions}

\appto{\QuizKey}{Ending Code}

\QuizKey

\end{document}


My end result is that the \QuizKey printout does everything it was told to in the document, except the parts in the questions environment. I'm guessing the \eappto and \appto commands aren't able to reach the hook, or perhaps they are not allowed to be used inside of the environment, but it doesn't seem to cause any errors, either. Is there a way I can fix this?

An environment forms a group, so the change to \QuizKey is lost as soon as the environment ends, unless the change is global. Use \xappto and \gappto.

\documentclass[12pt]{exam}
\usepackage{etoolbox}

\newcommand\QuizKey{\newpage}

\xappto{\QuizKey}{\arabic{question}.\ \unexpanded{#2\par}}% <-- don't forget
\vspace{#1}%
}

\begin{document}
\gappto{\QuizKey}{Opening Code\par}

\begin{questions}
\question When did the Internet first begin?\answer{1985}

\gappto{\QuizKey}{Something else to test\par}
\end{questions}

\gappto{\QuizKey}{\par Ending Code}

\QuizKey

\end{document}


• Ah. That seems so strange to me that a group would have a separate instance of a globally defined item like that. I guess it makes sense, though, because that way your code can have a new formatting that doesn't accidentally carry over when you leave without the need to reset everything. Thanks, though! Apr 5, 2017 at 3:22
• @retupmoc258 There is no global variable, apart from some particular internal parameter. The user is responsible of always doing global assignments to the variables that need to keep their value across groups. Apr 5, 2017 at 7:36