Stage 2 · Text and documents 9 / 48 ≈ 22 min read

LaTeX Document Structure: documentclass, Sections, TOC

How a document is organised — class, preamble, body — what actually happens at \begin{document}, why every environment is a group, which division units each class offers, and where the page-numbering switch belongs.

    The three parts of every document

    Every LaTeX file splits into three zones: the document class declaration, the preamble (everything between that line and \begin{document}, where packages and settings live), and the body. They are not three sections of a text; they are three different jobs. The class line names a file of layout rules to be read, the preamble runs a small program that configures those rules, and the body is the only zone whose characters reach a page.

    The word run is the one to hold onto. Nothing in the preamble is typeset, but everything in it is executed, in order, exactly once, before a single box exists on page one. A \newcommand there defines something the body will use later; a \setlength there changes a register the class filled in when it loaded; a \typeout there writes into the log and nowhere else, which is the only way to watch the preamble think. Because it is a program, it has the same failure mode as a program: an instruction in the wrong order is an instruction that refers to something that does not exist yet.

    Crossing the boundary is how most "mysterious" errors are manufactured. Ordinary characters typed above \begin{document} stop the run with LaTeX Error: Missing \begin{document} and a line of apology, because LaTeX is in a state where typesetting material is illegal; a package line below it is refused, because LaTeX retires a list of commands the moment the body opens; text left above the boundary in a file that only ever loads classes and packages simply never reaches the page, with no error to announce the loss. The compiler reports each of these at the line where it noticed, not at the line where you crossed, so learning to read the three zones off the source is what turns a ten-minute hunt into a ten-second one.

    Document classes: divisions, options and the contents list

    The class decides the default look and, more importantly, the units of division you are allowed to use: article for papers without chapters, report for longer documents with chapters and an abstract page, book for two-sided books with chapters, beamer for slides. That choice is structural, not cosmetic, because the units differ. \chapter does not exist in article at all, \frontmatter exists only in the chapter-bearing classes, and a frame environment exists only in beamer. Writing a body that needs a unit your class never defined is not a style problem; the command is undefined and the run says so.

    Square brackets pass options: \documentclass[12pt,a4paper]{article} asks for the same class on A4 at 12 pt. The standard families accept the same handful — a base size (10pt, 11pt, 12pt), a paper (a4paper, letterpaper, and the metric variants that rescale the class's own dimensions to it), a side (oneside or twoside) and a column mode — with different defaults: article and report come out oneside while book comes out twoside, which is one reason a thesis written in report suddenly gains blank verso pages when somebody "just" changes the class line. Options are read once, at load time, so they cannot be repeated later, and the class forwards any option it does not recognise to every package loaded afterwards — handy for a shared draft switch, baffling when a typo inside the square brackets turns into an error naming a file three hundred lines away.

    Each class hands you a ladder of those division units, and every rung is a command that does three jobs at once: it steps a counter, prints that counter beside your heading, and records the heading for the contents list. \section{…}, \subsection{…} and \subsubsection{…} number themselves in the format your class chose — plain 2 in an article, chapter-prefixed 2.1 in a book — and you never type a number by hand, because a hand-typed number is a claim that stops being true the moment you insert a section above it. The ladder is also where beginners over-build; the test is cheap: keep a level only if you have two of them at that depth, twice. Numbering and listing are governed by two separate depth dials in every class, so "numbered but not listed" is a setting rather than damage — the sectioning lesson names both dials and the level numbers they count against.

    Put \tableofcontents where you want the list and LaTeX builds it for you: every heading writes a line into a side file during one pass and the command replays that file during the next. Append a * to any heading to drop the number — \section*{Acknowledgements} — and understand that the star drops the entry along with it, because the star suppresses the bookkeeping rather than the ink.

    \text{1. Introduction} \quad \text{2. Notation} \quad \text{3. Main Results}
    \text{1. Introduction} \quad \text{2. Notation} \quad \text{3. Main Results}
    Change the class and keep the body — that is the payoff of markup — but check the table first: if your draft uses \chapter, \part or front matter, some of those classes cannot compile it at all, and a two-pass build is required the moment a contents list exists.
    \begin{array}{l|ccc}\text{class} & \texttt{\textbackslash part} & \texttt{\textbackslash chapter} & \texttt{\textbackslash frontmatter} \\ \hline \texttt{article} & \text{yes} & \text{no} & \text{no} \\ \texttt{report} & \text{yes} & \text{yes} & \text{yes} \\ \texttt{book} & \text{yes} & \text{yes} & \text{yes} \\ \texttt{beamer} & \text{yes} & \text{no} & \text{no}\end{array}
    \begin{array}{l|ccc}\text{class} & \texttt{\textbackslash part} & \texttt{\textbackslash chapter} & \texttt{\textbackslash frontmatter} \\ \hline \texttt{article} & \text{yes} & \text{no} & \text{no} \\ \texttt{report} & \text{yes} & \text{yes} & \text{yes} \\ \texttt{book} & \text{yes} & \text{yes} & \text{yes} \\ \texttt{beamer} & \text{yes} & \text{no} & \text{no}\end{array}
    LaTeX Document Structure: documentclass, Sections, TOC — Document classes: divisions, options and the contents list
    Rendered output — typeset from the source shown on this page.

    A complete skeleton

    This document compiles as-is, and it is worth reading twice: once for what each line does, and once for which side of the boundary each line sits on. The title block is a good example of the asymmetry. \title{…}, \author{…} and \date{…} are in the preamble and print nothing there; they store three pieces of data. \maketitle is the first line of the body and prints all three, using the layout the class supplied. Move either half across the boundary and you get one of the two classic failures: a title that never appears, or \maketitle called while LaTeX is still refusing to typeset.

    Below it sit two sections, one subsection, and a cross-reference. \label{sec:main} attaches a name to whatever was numbered last, and \ref{sec:main} prints that number on demand — so the sentence survives reordering the two sections, deleting one, or adding three above them. Note where the label stands: inside the section, after the heading, because that is what makes "whatever was numbered last" mean this section.

    \documentclass[12pt]{article}
    
    \title{A Short Study of Circles}
    \author{A. Student}
    \date{\today}
    
    \begin{document}
    \maketitle
    
    \section{Introduction}
    Circles appear everywhere.
    
    \subsection{Notation}
    We write $r$ for the radius.
    
    \section{Main Results}
    \label{sec:main}
    
    See Section~\ref{sec:main} again.
    
    \end{document}

    What \begin{document} switches on

    The line is a border between two states of the engine, and LaTeX treats it as an event. Up to it, material is read and executed with no page in existence; at it, the run opens the output machinery, starts page one, fixes the body font and brings the page counter to life. From that moment assignments change what the reader sees instead of what the next instruction means. The two hooks named \AtBeginDocument{…} and \AtEndDocument{…} exist precisely because this is a moment you can attach code to: they run in declaration order at the boundary and just before the last page is finished, which is how a package installs its own set-up without you calling anything.

    It is also where a group of commands is quietly taken out of service. \documentclass, \usepackage and their relatives are legal only before the boundary, and LaTeX says so in as many words when you use them later. The mirror mistake is rarer but worse: calling a typesetting command such as \maketitle or \tableofcontents in the preamble, where the command exists and the state does not, so the run stops with Missing \begin{document} while your braces are all perfectly balanced. The line number it prints is inside the preamble, which is exactly why beginners misread this error as a package problem.

    \end{document} is the other half of the transaction and is not a full stop. It flushes whatever is still waiting — the page being built, any figure that has not found a home — writes the accumulated cross-reference data into the side files and closes them, and finishes the PDF. Stop a file in mid-sentence without it and you get a truncated document plus a next run that knows nothing about your labels, because the file that carries them was never written out. This is also the moment a data flow worth naming becomes visible: the side file left by run n is read back at \begin{document} of run n+1, which is why a first compile of a fresh document resolves nothing and a second resolves everything.

    \documentclass[12pt]{article}     % which file of layout rules to load
    
    \usepackage[T1]{fontenc}          % every \usepackage line has to be up here
    \usepackage{amsmath}
    
    \newcommand{\asis}{as it stands}  % definitions belong to the preamble too
    
    \title{A Tale of Two Zones}
    \author{A. Student}
    \date{\today}
    
    % These two are the proof that the boundary is an event, not a position:
    % code attached to it runs exactly when the body opens and when it closes.
    \AtBeginDocument{\typeout{*** the body starts now ***}}
    \AtEndDocument  {\typeout{*** the last page has been shipped ***}}
    
    % Typesetting commands may be WRITTEN here, and then do nothing at all:
    % \maketitle            % <-- uncomment this line
    % \tableofcontents      %     run stops: Missing \begin{document}
    
    \begin{document}                  % <<< the boundary; nothing was on a page yet
    
    \maketitle                        % reads the title data collected above
    
    \section{Zone one}
    Everything before the boundary was \asis{} executed; none of it was read.
    
    Text typed here, in the body, is what actually reaches the page.
    
    \end{document}                    % ships the page, writes the aux files, closes

    Environments are groups, and settings die at the end

    \begin{…} and \end{…} look like a pair of brackets you type twice, and that approximation breaks the first time it matters. The real mechanism: \begin{center} runs the start code of an environment and registers its name as the innermost open one; \end{center} runs the end code and pops it. When the two names disagree LaTeX stops with LaTeX Error: \begin{center} ended by \end{itemize}. — and the message names the pair it was tracking, not the line you mistyped, so the search runs outward from the environment that is still open. A stray \end{…} with nothing open produces the mirror image, \begin{document} ended by \end{center}., because at the outermost level the open environment really is document. That single fact explains half of the "error at the bottom of my file" reports.

    The second mechanism is the one that pays for years: every environment is also a group. Font selections, lengths, spacing parameters and \newcommand definitions made inside it are undone at the matching \end{…}, which is what keeps \small in a caption from shrinking the rest of the document and lets a quote borrow your paragraph indent without stealing it. The same scoping applies to the braces you type yourself and to \begingroup … \endgroup, so an assignment written in a paragraph inside {…} lasts until the closing brace and not one character longer.

    Because groups end, some things that look like settings do not survive a pair of \begin/\end and some things do. Counters are the useful exception — stepping one is a global change, which is why a section opened inside a group still leaves the next one numbered correctly — and so is \label, because it does not live in memory: it writes into a side file that the next pass reads back, which is how a reference escapes both the group and the run. Everything else that has to leave an environment needs an explicit \global, and needing one is usually a sign that the material belonged outside.

    Nesting has a shape as well as a limit. Environments must nest like brackets, never interleave: \begin{A}\begin{B}\end{A}\end{B} is a category error, not a style one, and no package will talk LaTeX out of it. Some pairs are also regions rather than scopes — a tabular or a minipage is typeset as one unbreakable box, so material that wants a page break cannot be inside one, and a float placed inside a \footnote or another box stops with Not in outer par mode. Lists nest to four levels, because the kernel ships exactly four counters for them, and a fifth level has nothing left to step.

    \begin{array}{l|l}\text{written inside an environment} & \text{state at the matching }\texttt{\textbackslash end} \\ \hline \texttt{\textbackslash setlength} & \text{reverted} \\ \texttt{\textbackslash fontfamily} \text{ selection} & \text{reverted} \\ \texttt{\textbackslash newcommand} & \text{command gone again} \\ \texttt{\textbackslash stepcounter} & \text{kept, it is global} \\ \texttt{\textbackslash label} & \text{kept, it goes via the .aux}\end{array}
    \begin{array}{l|l}\text{written inside an environment} & \text{state at the matching }\texttt{\textbackslash end} \\ \hline \texttt{\textbackslash setlength} & \text{reverted} \\ \texttt{\textbackslash fontfamily} \text{ selection} & \text{reverted} \\ \texttt{\textbackslash newcommand} & \text{command gone again} \\ \texttt{\textbackslash stepcounter} & \text{kept, it is global} \\ \texttt{\textbackslash label} & \text{kept, it goes via the .aux}\end{array}
    Print a length on both sides of an environment, as the listing does with \the\parindent: it turns "my change stopped working" into a two-line experiment you can run in ten seconds.
    \documentclass[11pt]{article}
    
    \begin{document}
    
    \section{An environment is a group}
    
    The class default is \verb|\parindent| = \the\parindent.
    
    \begin{center}
      \setlength{\parindent}{2cm}     % assignment made inside the environment
      \def\fish{salmon}               % definition made inside it too
      Inside \texttt{center}: \the\parindent, and \fish{} is a word here.
    \end{center}
    
    Back outside: \the\parindent.     % the environment closed its group
    
    % \fish{}                          % <-- uncomment: Undefined control sequence
    % \begin{center}
    % \end{itemize}                    % <-- \begin{center} ended by \end{itemize}
    
    \begin{itemize}
      \item Each item is a group of its own, and so is each cell of a
            \texttt{tabular}; the ampersand closes one and opens the next.
    \end{itemize}
    
    \end{document}

    Pages, sides, matter and where the numbering switch goes

    Paper and side were already chosen in the option list, but they deserve restating at page level because they are structural rather than cosmetic: twoside mirrors the margins so binding does not eat text and makes headings and folios alternate left and right, while a4paper rescales the class's own dimensions to the sheet instead of merely naming it. Those belong in the square brackets of \documentclass, not sprinkled through the body — a \pagestyle or \setlength typed where a page break wants it is a repair, and repairs are how a document stops having a single layout you can reason about.

    One of those repairs is the commonest structural question of all, so it is worth getting exactly right: \pagenumbering{…} does two jobs in one stroke — it restyles \thepage with any of the five styles (roman, arabic, Alph, alph, fnsymbol) and it resets the count to one. That is why front matter and body can carry different numbers without anybody editing a counter, and why \frontmatter, \mainmatter and \backmatter are not decoration in the chapter-bearing classes — between them they perform the switch, restart the arabic count, and turn chapter numbering on or off. Articles have none of the three, and using \frontmatter in an article is an undefined-command error: the most common paste-from-a-template bug.

    Where the switch sits is the part with a consequence. A page is assembled by the output routine only when it is full, so a numbering style changed halfway down a page applies to that whole page, folio and all — which is why every one of these switches belongs behind \clearpage, never in the middle of text. The same asymmetry governs the contents list: its entries carry the page numbers the headings had when they were processed, so the numbering must be settled before \tableofcontents runs, not after. And \clearpage versus \cleardoublepage is a structural choice too, since only the second guarantees a chapter opens on a recto page in twoside mode, at the cost of a blank verso you may not want.

    \begin{array}{l|l}\texttt{\textbackslash pagenumbering\{roman\}} & \text{iv, iii, ii, i} \\ \hline \texttt{\textbackslash pagenumbering\{arabic\}} & 4,\ 3,\ 2,\ 1 \\ \hline \texttt{\textbackslash pagenumbering\{Alph\}} & \text{D, C, B, A}\end{array}\quad\text{each switch also resets the count}
    \begin{array}{l|l}\texttt{\textbackslash pagenumbering\{roman\}} & \text{iv, iii, ii, i} \\ \hline \texttt{\textbackslash pagenumbering\{arabic\}} & 4,\ 3,\ 2,\ 1 \\ \hline \texttt{\textbackslash pagenumbering\{Alph\}} & \text{D, C, B, A}\end{array}\quad\text{each switch also resets the count}
    Reaching for \setcounter{page}{1} alone restarts the printed count but leaves the numbering name space unchanged, so two pages then read "1" and every link into them collides; the counters and headers lessons take that one apart.

    Splitting a long document across files

    A thesis is not one file, and the two commands that fix that are not interchangeable. \input{chapters/intro} pastes another file into the stream at that exact point — no page break, no separate state — so it is the right tool for a preamble you keep in its own file or for a section that happens to run long. \include{chapter1} does the same but wraps the material in \clearpage, giving each chapter a fresh page and, more quietly, its own side file for references, which is the form \includeonly{} can act on.

    The consequence of a paste is worth noticing here because it is a grouping fact: \input knows nothing about files, so an environment opened in one included file and closed in the next compiles without complaint. Nothing detects it, nothing warns you, and six months later the file boundary is invisible to whoever has to work out which \end{…} belongs to which \begin{…}. Keep \input at whole-object granularity — a preamble, a chapter, a figure — and let the boundaries of the files coincide with the boundaries of the groups.

    \includeonly{chapter2,chapter3} in the preamble makes LaTeX read those files and skip the rest while still keeping every label, counter value and page number from the full build. That is the workflow for editing one stubborn chapter of a 200-page document without waiting for the whole thing to compile — but note the caveat: skipped content still occupies its real space, so if you want a fast draft of only what you wrote, you comment lines out instead, and then the page numbers lie.

    Two rules prevent almost every multi-file disaster, and the second is a judgement call about which command you should even be reaching for. Only the main file may contain \documentclass, the preamble and \begin{document}; a chapter file holding any of those produces an option clash or a doubled title page the moment it is read. And \include is legal only between \begin{document} and \end{document}, so preamble material is always \input: reach for \include when a unit should start on a fresh page and be switchable from the preamble, and for \input when it should simply continue where the previous line stopped. Which file counts as the root, how paths resolve when a folder moves, and how to compile one chapter alone are a lesson of their own.

    Where structure stops and the rest begins

    Three neighbouring topics look like part of this lesson and are not. Choosing and loading packages is a preamble question, not a structure question: \usepackage[margin=2.5cm]{geometry} changes the layout your class set up, and when a document has an odd margin the culprit is usually a package option rather than the class. Making \ref{sec:main} resolve to the right number is a cross-referencing question — the side-file round-trip and the two-pass rule live there, not here. And styling a heading (font, size, colour, spacing above and below) needs a package such as titlesec, because those dimensions are defined inside the class file and you should not edit a distributed .cls.

    The clean division of labour: the class owns the geometry of the page and the shape of every heading, the preamble owns the switches, the body owns only content and structure, and the groups inside the body own how far any one setting reaches. When you can state which of those four layers a bug lives in, you have already narrowed it — and you have a sentence to paste into a question, which is what makes it answerable.

    Structural errors are also the easiest to diagnose, because they announce themselves at the top of the log. LaTeX Error: Environment abstract undefined. means you are in a class that does not define it — almost always an article used where a template expected report. Command \maketitle undefined, or a title printed in the middle of page one, means \title{}, \author{} or \date{} was set on the wrong side of \maketitle. \begin{center} ended by \end{itemize} is the nesting bookkeeping described above and nothing else. And a complaint about \begin{document} ended by \end{…} while your braces all look balanced means an environment somewhere above was never closed — search for unmatched \begin/\end pairs, not for missing braces, when the message names the document boundaries.

    Lesson cheat sheet

    One key line of code from each section — jump to it or copy it straight from here.

    Section Key code
    \text{1. Introduction} \quad \text{2. Notation} \quad \text{3. Main Results}
    \documentclass[12pt]{article}
    \documentclass[12pt]{article} % which file of layout rules to load
    \documentclass[11pt]{article}
    \begin{array}{l|l}\texttt{\textbackslash pagenumbering\{roman\}} & \text{iv, iii, ii, i} \\ \hline \texttt{\textbackslash pagenumbering\{arabic\}} & 4,\ 3,\ 2,\ 1 \\ \hline \texttt{\textbackslash pagenumbering\{Alph\}} & \text{D, C, B, A}\end{array}\quad\text{each switch also resets the count}

    Common mistakes

    • Mixing article with \chapter. Articles have no chapters, and no \frontmatter either: the command is undefined, so ! Undefined control sequence. here is a complaint about your class, not about a package you forgot.
    • Hard-coding section numbers in the text ("see Section 3"). Insert a section and every hand-written number is a lie — use \label/\ref, and put the label after the heading so it attaches to that heading.
    • Typing prose above \begin{document}, or calling \maketitle there. The first ordinary characters before the boundary stop the run with LaTeX Error: Missing \begin{document}. — the complaint is about the state of the engine, not about your sentence, so the fix is to move the material below the boundary rather than to edit it.
    • Interleaving environments — \begin{quote}\begin{itemize}\end{quote}\end{itemize}. They must nest like brackets, and the error names whichever one was still open, so a message about quote can be caused by the list inside it.
    • Setting a length or defining a command inside an environment and expecting it to last. An environment is a group: the value is restored at \end{…}. Move the assignment above \begin{document} for a document-wide change, or make it \global when you really mean one leak.
    • Restarting the folio in mid-page. \pagenumbering{arabic} restyles and resets, and the style applies to the page being assembled, so put it after \clearpage; and never substitute a bare \setcounter{page}{1}, which gives two pages numbered 1 and duplicate link destinations.

    Questions about this lesson

    Which document class should I use for a paper, a report or a thesis?
    Pick it by the units the document needs, not by its length. article has sections down to subparagraphs and no chapters, which suits a journal paper, a letter or a problem set. report adds \chapter, an abstract that gets its own page and the front/main/back-matter switches, which covers most project reports and internal documents. book is report with two-sided layout: mirrored margins, chapters opening on a recto page and a running head that alternates, which is what a printed thesis wants. beamer replaces the whole ladder with frames. Specialised classes such as IEEEtran or acmart sit on top of these and add journal-specific layout; if one exists for your destination, use it and stop deciding.
    What exactly is the preamble in LaTeX, and what is allowed in it?
    Everything between \documentclass and \begin{document}. It is executed, not typeset, so the legal contents are declarations: package lines, class options already consumed, \newcommand and \newenvironment definitions, counter settings, length assignments and \AtBeginDocument hooks. What is not allowed is any material that wants to reach a page — a paragraph of text, \maketitle, \tableofcontents — and LaTeX stops with Missing \begin{document} when it sees one. Text-only material is not silently discarded either: that error is the compiler telling you it has no page to put it on yet.
    What is the difference between \input and \include in LaTeX?
    \input pastes a file into the token stream at that exact point: no page break, no separate reference data, and it works in the preamble, which is why your preamble lives in preamble.tex read with \input. \include may only appear in the body, wraps the file in \clearpage so it starts on a fresh page, keeps its own side file for labels, and is the only form \includeonly can act on. Use \include for chapters you want to compile selectively, \input for everything you want to continue inline. Path handling, subfiles and compiling one chapter alone go deeper in the multi-file lesson.
    Why do LaTeX environments need both \begin and \end, and what happens if they do not match?
    The pair is both a scope and a bookkeeping entry: \begin registers the environment as the innermost open one and \end pops it, so the names have to agree or LaTeX cannot tell what just closed. A mismatch stops the run with \begin{center} ended by \end{itemize}, and a stray \end with nothing open reports \begin{document} ended by \end{center}, because document is what is open at the outermost level. Both messages name the environment being tracked rather than your typo, so search outward from whichever pair is still unclosed. An unclosed brace group, by contrast, is reported as Missing } inserted near the end of the file.
    Why does a setting I made inside an environment stop working afterwards?
    Because every environment is a group. Font switches, \setlength, \parskip, spacing parameters and commands defined with \newcommand inside \begin{...}...\end{...} are all undone at the closing pair, which is the mechanism that keeps a caption small without shrinking the document. Two things do escape: counters, because stepping one is a global change, and \label, because it writes to a side file that the next pass reads instead of living in memory. To make anything else leave the environment you have to ask for it with \global, and to change the whole document you should be doing it above \begin{document}.
    How do I number the front of a LaTeX document in roman and the body in arabic?
    In report and book, \frontmatter and \mainmatter do it for you: the first switches the folio style to roman and unnumbers chapters, the second clears to a fresh page, restarts at arabic 1 and turns numbering back on. In an article you write the same three moves by hand — \pagenumbering{roman}, \clearpage, content, \clearpage, \pagenumbering{arabic} — remembering that \pagenumbering resets the count as well as restyling it. Settle this before \tableofcontents, because the list carries page numbers as they stood when each heading was seen, and do it with \pagenumbering rather than a bare \setcounter{page}{1}, which leaves two pages printed "1" and colliding PDF destinations.

    Live playground: edit the LaTeX, see it render

    The preview updates as you type — break it on purpose to see how errors look.

    KaTeX error
    Try an example

    Keep reading

    Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.