Splitting up LaTeX documents

Posted: 14th November 2010 by Tim in LaTeX
Tags: , , , , , , ,

If you’re writing a large LaTeX document like a book or a thesis, you probably don’t want to have the whole thing in one massive file. It’s the same principle as general programming; splitting the program into smaller components makes it easier to work with, maintain and test. In Microsoft Word you can do this with sub documents. In LaTeX, this can be done using either \include{file} or \input{file}.

Let’s first look at \include{file}. Let’s say you have a master document called thesis.tex and a sub document called intro.tex, like so:

thesis.tex

\documentclass{book}

\author{Tim Murphy}
\title{My Awesome Thesis}

\begin{document}
\maketitle
\thispagestyle{empty}

\include{intro}
\end{document}

intro.tex

\chapter{Introduction}
This is the text in the introduction chapter.

This will produce this document. Note that we do not put the .tex extension in the \include command – LaTeX assumes that this file is a .tex file.

The \include{intro} call has the same effect as typing /clearpage, pasting in all the contents of intro.tex and typing /clearpage again. In other words, it puts the content in it’s own page. If you want to control the files which are allowed to be included, you can use \includeonly{file, file, ...} in the preamble. If used, only the files listed may be included – attempting to include a file not in this list will have the same result as typing \clearpage. This could be useful for removing parts of a document when you’re testing it.

You can use \include as many times as you want in the master document, but it may not be used in the preamble, nor can it be used in files which are being included. For this, you can use the \input{file} command. This has the same effect as copying the code from the included file into the document. No \clearpage effects here – the code is pasted in as-is.

To illustrate, take the example above but add another file – preamble.tex. Then modify thesis.tex and preamble.tex like so:

preamble.tex

\documentclass{book}

\author{Tim Murphy}
\title{My Awesome Thesis}

thesis.tex

\input{preamble}

\begin{document}
\maketitle
\thispagestyle{empty}

\include{intro}
\end{document}

This will result in the same document as above. You can \input files in \include and other \input files to your heart’s desire.

  1. ups says:

    Hi there,

    do you happen to know how to automatically do it if you start from an already large document? I mean something similar to using the index to split the documents according to its sections/subsections.

    Thanks

  2. wolfgang says:

    Tim,

    Great little explanation, it’s often the small staff that we stumble over, so little helping pages like this one go a long way!
    Thanks

  3. cosmus says:

    Hallo, I followed the procedure but keep getting error message : cant be used in the preamble, commands ignored. Why is that the case?