The reason for this is because the assigned comment environment <env>
doesn't process the construction \begin{<env>}
...\end{<env>}
as a regular group (from the documentation):
Note: for an included comment, the \begin
and \end
lines act as if they don't exist.
In particular, they don't imply grouping, so assignments &c are not local.
A lengthier explanation: The expansion of \begin{answer}
does result in \begin{proof}[Answer]
, but the group is immediately closed before searching for \end{answer}
. Internally, LaTeX keeps track of which group you're in with every call to \begin
. The macro responsible for holding the information on the curr
ent envir
onment is \@currenvir
which, based on your definition
\newenvironment{answer}
{\begin{proof}[Answer]}
{\end{proof}}
holds proof
rather than answer
after expanding \begin{answer}
. Ultimately the comment
package's search finds \end{answer}
, but this fails the LaTeX test for a matching environment \begin
, resulting in the posted error.
In short, it's processed differently than expected.
A way around this is to set the nested environment using a command-form:
\documentclass{article}
\usepackage{comment,amsthm}
\newenvironment{answer}{\proof[Answer]}{\endproof}
\excludecomment{answer}
\begin{document}
This is always printed.
\begin{answer}
Hide this.
\end{answer}
\end{document}
Note the requirement that the \end{<env>}
for a commented <env>
should be on a line of its own without spaces:
The opening and closing commands should appear on a line of their own. No starting
spaces, nothing after it.