# Conditionals work, Listings work, but when put together, no [duplicate]

In an earlier question I learned the following code to define conditionally compiled text (for a teacher guide)

\newtoggle{teach}
\toggletrue{teach}
\NewEnviron{teachr}
{\iftoggle{teach}{\BODY}{}}
\newcommand{\cpp}{\begin{lstlisting}[language=C++]}


If I want to embed code within this conditionally compiled text, it fails. Conditional text works fine.

\begin{teachr}

\cpp
class foo {};
\end{lstlisting}

\end{teachr}


The error message is: ! LaTeX Error: \begin{teachr} on input line 166 ended by \end{lstlisting}.

I assume this is some obvious failing, but if I should construct an mwe let me know and I will edit the question.

## marked as duplicate by David Carlisle, Stefan Pinnow, Thorsten, user36296, user31729 Jun 14 '16 at 16:54

• lstlisting is a verbatim content environment. This can't be used (this way). Your code is a fragment and not really useful for us in order to help you – user31729 Jun 14 '16 at 16:08
• For listings, you need \lstnewenvironment rather than some command-form usage. Moreover, you can't nest a listing inside another environment s the cat-codes are important. – Werner Jun 14 '16 at 16:08
• Off-Topic comment: You've got a bunch of questions, with answers, but you rarely accept answers -- this is not how TeX.SX works :-( – user31729 Jun 14 '16 at 16:09
• @Christian Which one?The last question has no answer. I can't select a comment as an answer. – Dov Jun 14 '16 at 16:14
• the "answers" in the question that you link to are comments as the question is not clear enough to answer, the comments are just requests for information. – David Carlisle Jun 14 '16 at 16:25

You cannot do it like this: a lstlisting environment cannot be nested inside an environment defined with \NewEnviron. Moreover, you can't nest an environment in one defined by \NewEnviron if you don't use the proper \begin tag.

\documentclass{article}

\usepackage{listings}
\usepackage{comment}

\lstnewenvironment{cpp}[1][]
{\lstset{language=C++,#1}}
{}

\newenvironment{teacher}{}{}
%\excludecomment{teacher} % uncomment to hide

\begin{document}

This always shows
\begin{cpp}
class foo {};
\end{cpp}

\begin{teacher}
The following is for teacher only
\begin{cpp}
class bar {};
\end{cpp}
\end{teacher}

\end{document}


If the line with \excludecomment has the % removed, the output will be

• @Dov Yes, but it's much harder. egreg's solution is way nicer. – Henri Menke Jun 14 '16 at 16:34