# Comment environment not working with complex structures inside it

I am a math teacher and would love to use latex to prepare exercise to send to my students. I usually do something like this:

\section{exercise}
text text text
$$some equation here$$

\section{Solution}
here is contained the solution of the exercise;
It includes formulas, equation environment, graphics and so on: for example something like
\begin{equation*}
\begin{aligned}
&x+2y^2=5\\
&5x-2y=7
\end{aligned}
\end{equation*}


Problem comes when I try to use the comment package in a way like the following: In the preamble I set

    \usepackage{comment}
\excludecomment{SOLUTIONS}
%\includecomment{SOLUTIONS}


Then I use a SOLUTIONS environment just befone the Solution section. This is intended to produce just the text and, in a second moment, I will swap the comment between \includecomment{SOLUTIONS} and \excludecomment{SOLUTIONS} in the preamble to generate a pdf which include also the solution, not only the trace. I use something like the following:

\usepackage{comment}
\excludecomment{SOLUTIONS}
%\includecomment{SOLUTIONS}

\begin{document}
\section{exercise}
text text text
$$some equation here$$

\begin{SOLUTIONS}
\section{Solution}
here is contained the solution of the exercise;
It includes formulas, equation environment, graphics and so on: for example something like
\begin{equation*}
\begin{aligned}
&x+2y^2=5\\
&5x-2y=7
\end{aligned}
\end{equation*}
\end{SOLUTIONS}
\end{document}


If I try to compile the document, I get an error (I use texstudio, updated to the latest version; also the comment package is updated to the latest version). Same error happens if I use the standard \begin{comment}...\end{comment} instead of the custom SOLUTIONS environment. Elsewhere i read it is not possible to nest environment in Latex: should this be the problem? Is there some workaround other than comment/uncomment any single line of code on the solution area?

It appears as though environments defined with \includecomment and \excludecomment are sensitive to whitespace. After removing the indentation from the SOLUTIONS environment, the file compiles without any errors.

Here is the full file:

\documentclass{article}
\usepackage{comment}
\usepackage{amsmath}
\excludecomment{SOLUTIONS}
%\includecomment{SOLUTIONS}

\begin{document}
\section{exercise}
text text text
$$some equation here$$

\begin{SOLUTIONS}
\section{Solution}
here is contained the solution of the exercise;
It includes formulas, equation environment, graphics and so on: for example something like
\begin{equation*}
\begin{aligned}
&x+2y^2=5\\
&5x-2y=7
\end{aligned}
\end{equation*}
\end{SOLUTIONS}
\end{document}

• Really useful. I could have read better the documentation on the comment package to find the solution, anyway thanks for pointing it out. Nov 17 '20 at 17:27