# Howto hide a Listings or Verbatim environment using a \newif enable command

Due to make life easier I want to create a Exercise sheet for a lecture including the corresponding solutions. Therefore I defined a \newif to control whether the solution should be included or not. That worked fine until I need a lstlisting or a verbatim environment in it. The following code is the minimal example for the error, it works with verbatim too.

\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\newif\ifsolution
\solutionfalse

\ifsolution
\newcommand{\solution}[1]{#1}
\else
\newcommand{\solution}[1]{}
\fi

\begin{document}
This is always shown.
\solution{The listing is only shown if ifsolution is true.
\begin{lstlisting}
Test
\end{lstlisting}
}
\end{document}


Setting solution to true produces the error. How can I defined a command or an environment with this function?

-

My first assessment was wrong, but like Gonzalo kindly noted

verbatim material cannot appear in the argument of standard commands

A solution that does work is, not using any arguments:

\ifsolution
\def\solution{\relax}
\else
\newcommand{\solution}[1]{}
\fi


But you can also use the comment package. It provides the ability to easily define a certain environment as comment.

\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

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

\begin{document}
This is always shown.
\begin{solution}
The listing is only shown if ifsolution is true.
\begin{lstlisting}
Test
\end{lstlisting}
\end{solution}

\end{document}


With \excludecomment{solution} the solutions won't be shown and when you write \includecomment{solution} instead, they will be shown.

-
The problem is that verbatim material cannot appear in the argument of standard commands. –  Gonzalo Medina Aug 27 '12 at 14:07
@GonzaloMedina: Mmh, seems I assumed too much and tested too little. I better just keep the second solution. –  canaaerus Aug 27 '12 at 14:07
Thanks, your first idea is the one I need in my document. –  Grisu Aug 27 '12 at 14:25
@GonzaloMedina: The name is Medina. Gonzalo Medina. - a secret agent who holds the rare double-O prefix - the license to TeX. –  Paulo Cereda Aug 27 '12 at 18:57