1

The following MWE works as I expect but when I make certain changes I get errors:

  1. If I introduce say \textbf{something} within a \solution{} say \solution{\textbf{xx}}.
  2. If I change \theenumi to \textbf{\theenumi}

Probably both issues are the same problem.

The MWE below is based on the work from Write the value of enumerate to output file.

\documentclass{article}

\makeatletter
 \newwrite\solutions@file
 \newcommand{\collectSolutions}{\immediate\openout\solutions@file=\jobname.sol}
 \newcommand{\solution}[1]{\immediate\write\solutions@file{\theenumi #1}}
 \newcommand\printSolutions{\immediate\closeout\solutions@file{\input{\jobname.sol}}}
\makeatother


\begin{document}
\collectSolutions

\begin{enumerate}
    \item hello \solution{xx}
    \item hello \solution{xx}
    \item hello \solution{xx}
\end{enumerate}

\printSolutions
\end{document}
  • Try \solution{\noexpand\textbf{xx}} – koleygr Aug 25 at 9:37
  • @koleygr This does indeed work but since I need xx to represent any latex code I don't want to have to noexpand every \ . Perhaps this can be done in general? I tried it in the definition of \solution but it didn't work. – Geoff Aug 25 at 11:12
  • Try \newcommand{\solution}[1]{\immediate\write\solutions@file{\theenumi \unexpanded{#1}}} – koleygr Aug 25 at 11:24
  • 1
    Ooh that seemed to work! I then did \noexpand\textbf\theenumi\unexpanded{#1}} and it solved both of my questions! – Geoff Aug 25 at 11:29
  • I tested too and show that ... Thus... removed the comment. – koleygr Aug 25 at 11:34
2

The solution has to be expanded when will be printed through \printSolutions command.

So, try:

\newcommand{\solution}[1]{\immediate\write\solutions@file{\theenumi \unexpanded{#1}}}

This way the content of the file will be expanded at the time that will be "input"-ed by the command \printSolutions.

Edit: As you found out, \noexpand is also needed to keep the \theenumi value like:

\newcommand{\solution}[1]{\immediate\write\solutions@file{\noexpand\textbf{\theenumi} \unexpanded{#1}}}
  • 1
    I like this. My final comment above combined both of your ideas. It's confusing that in one case the solution is \noexpand and the other it is \unexpanded. – Geoff Aug 25 at 11:32
  • Yes ... I thought for a minute that you could add \theenumi inside the \unexpanded command but it will expand only with the last value of it. – koleygr Aug 25 at 11:34

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.