# How to \enddocument inside an environment

I have a document of the form

\begin{document}
some text
\begin{myenv}
....
\end{myenv}
some other stuff
\end\document


I would like to set a boolean \newif\if@test in the header to control the output, such that if I set \@testtrue, the document would end just after \end{myenv} and not display some other stuff. My attempt is to put

\if@test \enddocument


at the end of the declaration of myenv. But this does not work, LaTeX complains that begin{myenv} is ended by \enddocument ...

How could I do that?

-
I think that if it is an environment that is nested this is going to be a problem. – Peter Grill Jan 18 '12 at 19:08
Related but not a duplicate: Calling \end{document} in a macro – Martin Scharrer Jan 18 '12 at 19:38

A simple solution is to use \stop to stop further compilation.

\documentclass{article}
\newenvironment{myenv}{}{\stop}
\begin{document}
some text
\begin{myenv}
Some other text
\end{myenv}
some other stuff
\end{document}


This is a TeX command redefined in LaTeX ltmiscen.dtx.

-
Indeed, \stop is the way to go here. For a further example see Ulrike's answer to one of my questions which introduced me to this nice macro. – Martin Scharrer Jan 18 '12 at 19:43
this is definitly the simple solution i was looking for ! – nicolas roy Jan 18 '12 at 19:47

To comment some phrases of your document I recommend the package comment.

On the other hand I recommend the package etoolbox with the hook \AfterEndEnvironment.

Here an example:

\documentclass{article}%
\usepackage{etoolbox}
\newbool{myenv:enddocument}
\booltrue{myenv:enddocument}
\AfterEndEnvironment{myenv}{%
\ifbool{myenv:enddocument}%
{\def\tempa{\end{document}}}%
{\let\tempa\relax}%
\tempa%
}
\newenvironment{myenv}%
{\par\noindent}%
{\par}
\begin{document}

some text
\begin{myenv}
....
\end{myenv}
some other stuff
\end{document}

-
to comment part of my text, i usually use either a command \comm defined by {} or an environment defined with \NewEnviron{comm}{}. Thanks for the interesting \AfterEndEnvironment – nicolas roy Jan 18 '12 at 19:52
\ifbool{myenv:enddocument}{\end{document}}{} – Ahmed Musa Jan 18 '12 at 21:13

The following works due to the minimal grouping within your environment:

\documentclass{article}
\newenvironment{myenv}{Start}{Finish}% \begin{myenv}...\end{myenv}
\makeatletter
\newif\if@test% New condition \@test<true><false>
\@testtrue% \@testfalse
\makeatother
\begin{document}
some text
\begin{myenv}
...
\end{myenv}
some other stuff
\end{document}​


\g@addto@macro works similar to etoolbox's \appto command. \aftergroup waits for the current group to finish before executing \enddocument.

-
yes, but i don'T want to have the boolean test in myenv, but in the header. – nicolas roy Jan 18 '12 at 19:53
@nicolasroy: I've updated my answer to accommodate for this, adding the test condition to the start of the environment \myenv. – Werner Jan 18 '12 at 19:57