This question already has an answer here:

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


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


class foo {};


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

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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 – 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
  • 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 :-( – 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
  • 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

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.




%\excludecomment{teacher} % uncomment to hide


This always shows
class foo {};

The following is for teacher only
class bar {};


enter image description here

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

enter image description here

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

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