3

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.

Dov
  • 1,481
  • 1
    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 –  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
  • 1
    Off-Topic comment: You've got a bunch of questions, with answers, but you rarely accept answers -- this is not how TeX.SX works :-( –  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
  • @Dov: There are more than one questions ;-) Go through your list of questions –  Jun 14 '16 at 16:16
  • @Christian. Why do people post answers in comments? Second answer ALSO has no answers posted. http://tex.stackexchange.com/questions/313940/big-blanks-in-document-why – Dov Jun 14 '16 at 16:17
  • 1
    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

1 Answers1

4

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}

enter image description here

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

enter image description here

egreg
  • 1,121,712