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.


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


    \item hello \solution{xx}
    \item hello \solution{xx}
    \item hello \solution{xx}

  • Try \solution{\noexpand\textbf{xx}}
    – koleygr
    Aug 25, 2019 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, 2019 at 11:12
  • Try \newcommand{\solution}[1]{\immediate\write\solutions@file{\theenumi \unexpanded{#1}}}
    – koleygr
    Aug 25, 2019 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, 2019 at 11:29
  • I tested too and show that ... Thus... removed the comment.
    – koleygr
    Aug 25, 2019 at 11:34

1 Answer 1


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, 2019 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, 2019 at 11:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .