Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
1  
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
1  
Actually \newcommand uses \long, while \newcommand* doesn't. –  egreg Aug 27 '12 at 14:10
    
Thanks, your first idea is the one I need in my document. –  Grisu Aug 27 '12 at 14:25
3  
@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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.