Based on \NewDocumentEnvironment
, \colorbox
this is rather straight forward. Please keep in mind that \colorbox
doesn't allow page breaks inside your solutions.
\documentclass[]{article}
\begin{filecontents}[overwrite]{solutions.sty}
\RequirePackage{xcolor}
\newif\ifsolutions
\solutionsfalse
% If solution is false the environment should blank whatever is inside it
% If true it should shade the background gray
\DeclareOption{solutions}{\solutionstrue}
\ProcessOptions\relax
\NewDocumentEnvironment{solution}{m +b}
{%
\ifsolutions
\expandafter\@secondoftwo
\fi
\@gobble
{%
#1 $\delta$
\par
\noindent
\colorbox[gray]{0.9}
{%
\begin{minipage}{\dimexpr\linewidth-2\fboxsep\relax}%
#2%
\end{minipage}%
}%
\par
#1 $\delta$
}%
}
{}
\end{filecontents}
\usepackage[solutions]{solutions}
\begin{document}
You had a question
\begin{solution}{a}
This is a solution to your problem.
\end{solution}
\end{document}
On how this works:
The +b
argument of a \NewDocumentEnvironment
will collect the contents of that environment as an argument, in the definition you can then refer to said contents by #2
(in this case, as it's the second argument).
The \ifsolutions
is evaluated, but the contents aren't immediately put inside that \if...
conditional, as that can get unstable in TeX. Instead we put an argument after the \if...\fi
part, and if the conditional is true execute that argument (\expandafter\@secondoftwo
first expands the \fi
closing the conditional block, then executes \@secondoftwo
that's defined as \providecommand\@secondoftwo[2]{#2}
). If the conditional is false everything up to \fi
will be removed and \@gobble
will gobble up the contents (\@gobble
is defined as \providecommand\@gobble[1]{}
).
A variant that displays another symbol if \ifsolutions
is false:
\documentclass[]{article}
\begin{filecontents}[overwrite]{solutions.sty}
\RequirePackage{xcolor}
\newif\ifsolutions
\solutionsfalse
% If solution is false the environment should blank whatever is inside it
% If true it should shade the background gray
\DeclareOption{solutions}{\solutionstrue}
\ProcessOptions\relax
\providecommand\@secondofthree[3]{#2}
\NewDocumentEnvironment{solution}{m +b}
{%
\ifsolutions
\expandafter\@secondofthree
\fi
\@secondoftwo
{%
#1 $\delta$
\par
\noindent
\colorbox[gray]{0.9}
{%
\begin{minipage}{\dimexpr\linewidth-2\fboxsep\relax}%
#2%
\end{minipage}%
}%
\par
#1 $\delta$
}%
{$\alpha$}% this shows up if \ifsolutions is false
}
{}
\end{filecontents}
\usepackage[solutions]{solutions}
\begin{document}
You had a question
\begin{solution}{a}
This is a solution to your problem.
\end{solution}
\end{document}
#1
? Are you having trouble with the shading part, or with the ignoring part, or both? For ignoring, I would just\usepackage{comment}
and then\excludecomment{solution}
.