This is truly an unimportant curiosity/itch question. I have chapters in a book that can compile either within the whole book or by themselves. At the end, the files have statements like:


This works fine but gives a warning about a nested \if. I presume that there is no way to avoid it, but if there is, I would love to know.

  • By the way, sounds like a job for the standalone package.
    – user202729
    Commented Mar 30, 2022 at 11:29
  • Or include/includeonly.
    – Teepeemm
    Commented Mar 30, 2022 at 13:00
  • thx, guys. \includeonly requires changing the main file when I want to switch chapters. the chapter approach, each self-compilable or full-in compilable, with me being able to quickly open chapter x for pdf preview works great. I import the labels from all the other files --- voi'la.
    – ivo Welch
    Commented Mar 31, 2022 at 4:00

3 Answers 3


What would be the structure of such a document?

You possibly have something like

%% file main.tex






Then you have

%% file commonsetup.tex

% define the conditional end

%<packages and settings>

and the chapter files will have

% file chapter1.tex

Text for the first chapter

  • this is exactly how I have it.
    – ivo Welch
    Commented Mar 31, 2022 at 4:01

The thing is to execute the \fi before the \end{document}. There are plenty ways you can do that. I'd define in the preamble:


then use \endifchapteronly when needed. The \expandafter expands \fi, then \@secondoftwo uses \end{document}.

You could also use expl3. expl3 conditionals always expand \fi before running the true or false branches:

\NewDocumentCommand \endifchapteronly { }
    \legacy_if:nT { chapteronly }
      { \end{document} }

Or, if you prefer an ad hoc one-liner:

\expanded{\ifchapteronly \noexpand\end{document} \fi}

P.S.: This answer assumes you are not using \include. A file included with \include is itself read inside two conditionals, so you'd need to terminate three \fi. But \include has its own \includeonly mechanism, so you wouldn't need this contraption anyway

  • 1
    are you sure that shouldn't be called \stopeventually ? Commented Mar 30, 2022 at 7:35
  • 2
    Are you sure you can do \newcommand\endifchapteronly{...}?
    – egreg
    Commented Mar 30, 2022 at 8:08
  • @egreg Bah, forgot about that pesky detail Commented Mar 30, 2022 at 17:38

The switching between something and \fi can be done by \afterfi macro:



You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .