I would like to include answers in an exam paper so that the paper could be compiled in two different ways: with and without the answers. The way this is usually done in British universities (or at least some of them) is to use the comment package, like this:
\documentclass{article}
\usepackage{comment}
\excludecomment{answer}
\newcommand{\showanswers}{\renewenvironment{answer}{\begin{answershown}}{\end{answershown}}}
\newenvironment{answershown}{\textbf{Answer:} }{}
% \showanswers % comment out to hide the answer
\begin{document}
Is the following command correct?
\begin{verbatim}
public class
\end{verbatim}
\begin{answer} % do not indent!
The following command is not correct:
\begin{verbatim}
public class
\end{verbatim}
\end{answer} % do not indent!
\end{document}
Here \showanswer is a toggle between the clean version of the paper (without the answers) and the version containing the answers. The disadvantage is that the comment package does not allow indentation (which is important in that it clearly shows the structure, potentially complicated, of the paper), and so compiling the source code above produces an error message:
Runaway argument?
! File ended while scanning use of \next.
<inserted text>
\par
<*> ./mwe.tex
?
To allow indentation, I can use the environ package:
\documentclass{article}
\usepackage{environ}
\NewEnviron{answer}{}
\newcommand{\showanswers}{\RenewEnviron{answer}{\textbf{Answer:} \BODY}}
\showanswers % comment out to hide the answer
\begin{document}
Is the following command correct?
\begin{verbatim}
public class
\end{verbatim}
\begin{answer}
The following command is not correct:
\begin{verbatim}
public class
\end{verbatim}
\end{answer}
\end{document}
But environ does not like verbatim in the answer, and compiling the latter source code produces:
Runaway argument?
public class \end {verbatim}\env@ignore The following command is no\ETC.
! File ended while scanning use of \@xverbatim.
<inserted text>
\par
<*> ./mwe.tex
?
Is there a way to have both indentation and verbatim (in answers)?


adjustwidthuseful. – tobiasBora Nov 26 '21 at 21:21environand use the normal\newenvironmentfrom LaTeX, which does not grab the whole environment at once. (or if you really need to grab it usecprotEnv, but may be overkill) – user202729 Nov 27 '21 at 05:05Package Listings Warning: Text dropped after begin of listing on input line 19. ...(It says "warning" but in fact the system enters into a dialogue with me which I can't leave without simply closing the window.) I have tried bothlistingsandmcodepackages. But for my purpose it would be good to be able to deal withverbatimas well: I would like my colleagues to use my style file, and some of them likeverbatim. – Vlad Nov 27 '21 at 08:29\newenvironment(which I need in the clean version of the exam paper). (Things like\iffalse\fidid not work for me.) And no success withcprotEnvso far. – Vlad Nov 27 '21 at 08:49