Stage 6 · Production, macros and packages 42 / 48 ≈ 24 min read

LaTeX Preamble and Packages: Options, Order, Clashes

A package is a file of code read at one exact moment, and that is why preambles break. What a class adds, how options are declared and forwarded, why hyperref loads last, and what the log says when two files disagree about one package.

    What a package actually is, and what a class adds

    A package is a file of LaTeX code named <name>.sty and nothing more. When LaTeX meets \usepackage{amssymb} it searches the file tree for amssymb.sty, reads it token by token in the same catcode regime as your own source, and continues as if the file body had been pasted at that spot. It can define commands (that one hands you \mathbb and \aleph), change defaults (geometry sets margins), or attach behaviour to machinery that already exists (hyperref rewrites the cross-reference writing commands so that a \ref becomes a clickable link). Loading is inert: nothing appears on the page until the document uses what the package defined.

    Two lines make a package identifiable and debuggable. \ProvidesPackage{mynotes}[2026-01-15 v1.3 lecture notes] registers name, date and version; LaTeX writes all three into the .log and keeps them for the double-load test. That test is why a second \usepackage{amsmath} is silently ignored — the file has already been read, so the request is a no-op — unless the two option lists differ, which is the clash discussed two sections below. Inside a package, dependencies arrive through \RequirePackage rather than \usepackage: they do the same job, and the difference is a reading aid, because \RequirePackage only ever appears in package files.

    A class is a package with two extra duties. It is read before anything else, it owns the machinery a document runs on — sectioning commands, the counters, the page geometry registers, \maketitle — and it is the file that receives the options written on the \documentclass line and passes them down to everything loaded afterwards. A class may also be a thin layer over another class: most venue and university styles begin with \LoadClass{article} or \LoadClass{report}, and option forwarding applies along that chain exactly as it does from class to package. \ProvidesClass is the counterpart declaration, and the class brackets are the only place where a class name is legal.

    Both kinds of file live in the same tree and are found by the same search path, which is why "where is this file" is one question with one answer: kpsewhich amsmath.sty prints the absolute path the engine will read, and kpsewhich --var-value TEXMFHOME prints the per-user directory that wins over the distribution. Note what is not on that path: a plain fragment of definitions is not a package, does not take \ProvidesPackage, and is read with \input{base} — which appends no extension and takes no options.

    LaTeX Preamble and Packages: Options, Order, Clashes — What a package actually is, and what a class adds
    Rendered output — typeset from the source shown on this page.

    The short list that covers most documents

    Mathematics: amsmath plus amssymb, with mathtools on top when you want \coloneqq, \DeclarePairedDelimiter or the fixes to amsmath spacing. Graphics: graphicx. Tables: booktabs. Links and PDF metadata: hyperref. Around those, three lines that are not optional in practice: fontenc and inputenc for text that is not seven-bit ASCII, and geometry for margins. Nine documents out of ten are that list plus one package specific to the subject.

    The argument for keeping it short is a cost model, not taste. Every .sty is executed on every run, so the preamble is where a small document spends most of its compile time; and each package is a set of definitions that other packages may patch, so the clash surface grows quadratically — five packages are ten pairs that can disagree, forty are seven hundred and eighty. A package imported for one command you could have typed by hand buys a typing saving and pays a compatibility risk for the remaining life of the document.

    The other reason a long preamble misbehaves is that two packages often claim the same job. subfigure and subcaption both define \subref; titlesec and a KOMA class both own the format of a heading; natbib and biblatex both own \citet; inputenc and fontspec both own the input encoding, and loading both on XeLaTeX stops the run with an error from one of them. Loading the pair is how people end up with a document whose behaviour depends on which of the two happened to be read first.

    So read a preamble the way you read a dependency list: what does each line add, and who else touches the same commands. The same reading is the debugging move — delete the last few \usepackage lines and see whether the symptom goes; if it does, the culprit is the last one you removed, and the fix is usually an option or an order change rather than a different package.

    \mathbb{R} \quad \mathbb{N} \quad \aleph_0
    \mathbb{R} \quad \mathbb{N} \quad \aleph_0
    The fancy alphabets ride on the same two math packages: \mathbb, \mathcal, \mathfrak and \mathscr all come from the AMS font bundles amssymb pulls in.

    Loading order is load-bearing

    LaTeX has no dependency resolution and no namespaces: the preamble is a single script executed top to bottom, once. A package that changes behaviour it does not own either defines the command from scratch, checks whether a name exists, or patches the definition that happens to be current at the moment it is read. Patching is the fragile one, because it edits the text of something another file wrote — so the file being patched must already have been read. That is the entire mechanism behind "order matters", and nothing about it is folklore: the same source file in a different position in the preamble means a different document.

    The rules people memorise follow from it. mathtools after amsmath, because it repairs amsmath definitions. xcolor — and therefore its name-list options dvipsnames, svgnames — before tikz and pgfplots, which would otherwise load it themselves with no options at all. fontenc before hyperref, which writes PDF bookmark strings and needs the text encoding settled. hyperref last among packages that typeset or reference material, because it hooks \label, \ref and the auxiliary-file writing commands. cleveref after hyperref, because it wraps the very commands hyperref has just replaced — that pair is the one ordering rule worth remembering by name instead of deriving.

    Driver options are the same mechanism one level down. xcolor, graphicx and pgf each have a driver component that emits colours, inclusions and specials for one output path, and each accepts a driver option: pdftex, dvipdfmx, xetex, luatex, dvips. Current versions detect the engine from the format file, so the useful advice is negative: do not pin a driver in a shared preamble. Options given to the class are passed to every package, which is why \documentclass[dvips]{article} reaches graphicx and xcolor without repeating anything — and why a hard-coded driver is the standard way for a project to stop compiling when somebody switches from pdflatex to lualatex. The error it produces names the package, never the word driver.

    Two qualifications keep this from becoming superstition. "Last" for hyperref means last among content packages; cleveref, bookmark and standalone are documented to come after it, so the line is really "hyperref near the end, its own adapters after it". And order can be bought without moving lines: \PassOptionsToPackage and \PassOptionsToClass state options for a file that someone else will load later, which is the only clean fix when the offending load lives in a class you are not allowed to edit.

    % A disciplined preamble, in loading order:
    \documentclass[11pt,a4paper]{article}
    
    % --- mathematics
    \usepackage{amsmath}    % aligned, \eqref, \text …
    \usepackage{amssymb}    % \mathbb, \aleph …
    \usepackage{mathtools}  % fixes on top of amsmath
    
    % --- graphics and tables
    \usepackage{graphicx}
    \usepackage{booktabs}
    
    % --- references and links (always LAST)
    \usepackage{hyperref}
    \usepackage{cleveref}   % after hyperref
    
    % --- document metadata
    \title{…} \author{…}

    Options, and the clash they cause

    \usepackage[a4paper,margin=2cm]{geometry} hands the package one comma-separated token list; LaTeX itself does nothing with it beyond splitting it off the file name. A package written against the kernel consumes it with three calls: \DeclareOption registers a handler for one name, \ExecuteOptions applies the defaults, \ProcessOptions walks the user list and runs the handlers it found. A spelling with = in it, like margin=2cm, needs either hand-rolled keyval parsing or the kvoptions wrapper, because the plain kernel mechanism has no concept of a value.

    The classic failure has its own name: ! LaTeX Error: Option clash for package geometry. It means the file had already been loaded — by the class, or by another package you loaded — and the options requested now are not the options in force. LaTeX cannot re-execute a file with a different option set, so it stops. Nothing is broken: the message reports that two lines, possibly in two different files, disagree about one name. The fix is to make the first load the only load, either by loading the package yourself earlier with the union of the options, or by declaring them in advance with \PassOptionsToPackage{dvipsnames}{xcolor} before the line that pulls xcolor in through tikz.

    Options are also the reason one package behaves differently in two documents: they are read once, at load time, and most packages never look at them again. That has two consequences people trip over. You cannot change an option after \begin{document} — which is why packages with a lot of configuration expose a second entry point such as \pgfplotsset{...} or \sisetup{...} instead of an option. And class options are inherited downward: \documentclass[draft]{report} reaches graphicx, hyperref and your own package, so a switch you never typed can be active in a file you wrote.

    Read a clash forensically rather than by trial and error. The message names the package requested twice, never the file that loaded it first; search the log upward for the first line of the form File: geometry.sty and you have found the load you must beat. In a multi-file project the same search crosses files, and the answer is usually the class — a venue or university class that loads xcolor, hyperref or geometry with its own options has no way to know what else you were going to want.

    Declaring options in a file of your own

    All of the above is available in a file you write, and a package with options costs about twelve lines. The identification block is fixed: \NeedsTeXFormat{LaTeX2e}[2021-11-15] states the minimum format release, so an installation older than that stops with You need LaTeX2e release 2021-11-15 or later instead of failing obscurely further down; \ProvidesPackage{name}[date version description] registers the file, and that date is what \@ifpackagelater{name}{YYYY/MM/DD}{...}{...} later compares against.

    Then comes the option block, in this order and no other. \DeclareOption{draft}{\mynotes@drafttrue} pairs a name with code, and the code is stored rather than run. A catch-all — \DeclareOption*{\PassOptionsToPackage{\CurrentOption}{geometry}} — receives every name you did not declare, which is how a wrapper package hands options through to the package it exists to configure. \ExecuteOptions{final} applies your defaults, and \ProcessOptions\relax runs the user list over them, so the user wins. The \relax is written by every CTAN package because it terminates the scan before the next token, rather than letting a bracket or a digit on the following line be read as part of the option list.

    Two consequences explain most of what beginners find strange in other people's source. A switch such as \ifmynotes@draft is only meaningful after \ProcessOptions, so any dependency that depends on it has to be required after that line — which is precisely why \PassOptionsToPackage exists for the case where the dependency has to come first. And an option that you neither declare nor catch all is a load-time error naming your file, not a warning: Unknown option `twoside' for package `mynotes'. The catch-all is what turns that into a feature.

    The @ in those internal names is a namespace, not decoration: @ is a letter only between \makeatletter and \makeatother, so \mynotes@draft cannot be typed by accident in a document. Package files are read with @ already a letter, which is why the same lines work inside a .sty and fail when pasted into a preamble, where they need the \makeatletter pair around them.

    \underbrace{\texttt{[draft,12pt]}}_{\text{one token list}} \;\xrightarrow{\;\texttt{ProcessOptions}\;}\; \underbrace{\texttt{draft}\to\texttt{true}}_{\text{declared handler}} \;\cup\; \underbrace{\texttt{12pt}\to\texttt{forwarded}}_{\text{catch-all handler}}
    \underbrace{\texttt{[draft,12pt]}}_{\text{one token list}} \;\xrightarrow{\;\texttt{ProcessOptions}\;}\; \underbrace{\texttt{draft}\to\texttt{true}}_{\text{declared handler}} \;\cup\; \underbrace{\texttt{12pt}\to\texttt{forwarded}}_{\text{catch-all handler}}
    A class uses the same four calls with one extra constraint: the option block must close before \LoadClass, because the options being forwarded belong to a file that has not been read yet.
    % ============================================================
    % mynotes.sty  —  a package that declares its own options
    % beside the document, or in TEXMFHOME/tex/latex/mynotes/
    % ============================================================
    \NeedsTeXFormat{LaTeX2e}[2021-11-15]   % refuse a too-old format loudly
    \ProvidesPackage{mynotes}[2026-01-15 v1.3 lecture notes with options]
    
    % ---- 1. storage for the answers the handlers will write
    \newif\ifmynotes@draft
    \newif\ifmynotes@wide
    \newcommand{\mynotes@pointsize}{11pt}
    
    % ---- 2. one handler per option. The body is stored here and RUNS
    %         only at \ProcessOptions, so nothing may read it before.
    \DeclareOption{draft}{\mynotes@drafttrue}
    \DeclareOption{final}{\mynotes@draftfalse}
    \DeclareOption{wide}{\mynotes@widetrue}
    \DeclareOption{12pt}{\renewcommand{\mynotes@pointsize}{12pt}}
    
    % ---- 3. everything you do not implement goes to the package it belongs to
    \DeclareOption*{\PassOptionsToPackage{\CurrentOption}{geometry}}
    
    % ---- 4. defaults first, then the walk over the user list.
    %         \relax terminates the scan: without it the next token is read as
    %         a possible continuation of the option list.
    \ExecuteOptions{final}
    \ProcessOptions\relax
    
    % ---- 5. only now is it legal to branch on the switches
    \ifmynotes@wide
      \RequirePackage[a4paper,margin=3.5cm]{geometry}
    \else
      \RequirePackage[a4paper,margin=2.5cm]{geometry}
    \fi
    
    \ifmynotes@draft
      \RequirePackage{lineno}
      \RequirePackage{etoolbox}
      \AtEndPreamble{\linenumbers}       % etoolbox: after every other \usepackage line
    \fi
    
    \AtEndOfPackage{\typeout{mynotes v1.3: options settled}}
    \endinput
    
    % ============================================================
    % main.tex  —  the same mechanism seen from the calling side
    % ============================================================
    % geometry is loaded by mynotes, so its option must be handed over
    % BEFORE the first load, or the run ends in an option clash:
    %   ! LaTeX Error: Option clash for package geometry.
    \documentclass[11pt,a4paper]{article}
    \PassOptionsToPackage{dvipsnames}{xcolor}
    \usepackage[wide,draft,twoside]{mynotes}
    %                                 twoside is caught by \DeclareOption*
    \begin{document}
    Draft mode: every line numbered, wide margins.
    \end{document}

    Key-value options with kvoptions

    The kernel option list carries names, not values, so every package with key=value options builds the second layer itself. The two pieces on CTAN are keyval — \define@key{family}{key}{code} for the declarations and \setkeys{family}{list} for the parse — and kvoptions, which wires such a family into the bracket of \usepackage so that you write declarations instead of parsing code. A third route, l3keys2e, exposes the LaTeX3 key engine to package options; the difference is scale, discussed below.

    \SetupKeyvalOptions{family=MY,prefix=MY@} fixes the family name that \setkeys addresses and the prefix of every macro the declarations create. Then one call per key states the shape of its value: \DeclareStringOption[8pt]{padding} creates \MY@padding with a default, \DeclareBoolOption[false]{shadow} creates the switch \ifMY@shadow together with \MY@shadowtrue and \MY@shadowfalse, \DeclareCompressedOption accepts the key=true spelling for a group of flags, and \DeclareDefaultOption{...} is the catch-all for keys you would rather forward or ignore than reject. \ProcessKeyvalOptions{MY} ends the block and runs the parse against the family named on that line.

    The errors this machinery produces are nearly always about one word. ! Package keyval Error: framewidth not allowed. means the family was found and no declaration matches that key — a typo, or a key that belongs to a different package with a similar name; keyval never guesses. The quiet failure is a mismatch between family and prefix, which leaves you reading a macro that was never written, and the structural one is a family collision: families are global, so two packages that both call theirs MY share defaults and handlers. That is why the convention is a prefix derived from the package name.

    Choose the layer by how many places have to read the same keys. A handful of switches: kvoptions, and be done. A long option set, or the same keys needed by a command and an environment as well as the package: an l3keys family defined once (\keys_define:nn with .code:n, .initial:n, .choices:) serves all three and reports unknown keys in one place. That is what tcolorbox, mdframed and the KOMA classes are built on, and it is why their options behave alike across commands.

    \texttt{color=red} \;\longmapsto\; \langle\,\texttt{color},\ \texttt{red}\,\rangle \;\ne\; \texttt{color red}
    \texttt{color=red} \;\longmapsto\; \langle\,\texttt{color},\ \texttt{red}\,\rangle \;\ne\; \texttt{color red}
    Keys are read once, at load time: calling \setkeys later changes the macros behind them but does not re-run whatever already looked at those values.
    % ============================================================
    % myframe.sty  —  key/value options with kvoptions
    % ============================================================
    \NeedsTeXFormat{LaTeX2e}[2020-10-01]
    \ProvidesPackage{myframe}[2026-01-15 v1.0 framed boxes, keyval options]
    
    \RequirePackage{kvoptions}        % pulls in keyval
    \RequirePackage{xcolor}
    
    % ---- family = the namespace \setkeys talks to; prefix = the names it writes
    \SetupKeyvalOptions{
      family = MY,
      prefix = MY@,
    }
    
    % ---- one declaration per key: the shape of the value, and the default
    \DeclareStringOption[black]{color}         % -> \MY@color
    \DeclareStringOption[8pt]{padding}         % -> \MY@padding
    \DeclareBoolOption[false]{shadow}          % -> \ifMY@shadow, \MY@shadowtrue
    \DeclareCompressedOption{compressed}       % -> \ifMY@compressed, accepts compressed=true
    \DeclareDefaultOption{%                    % the catch-all: drop it and unknown keys error
      \PackageWarning{myframe}{Ignoring unknown key \CurrentOption}%
    }
    
    % ---- defaults, then the parse. Both must precede any use of \MY@...
    \ExecuteOptions{color=black}
    \ProcessKeyvalOptions{MY}                  % ends the block and runs the parse
    
    \newcommand{\frameit}[1]{%
      \setlength{\fboxsep}{\MY@padding}%
      \fcolorbox{\MY@color}{white}{#1}%
    }
    \endinput
    
    % ============================================================
    % main.tex
    % ============================================================
    \documentclass{article}
    \usepackage[color=red!40,padding=12pt,compressed=true,shadow]{myframe}
    % Without \DeclareDefaultOption a key nobody declared is a load-time error:
    %   ! Package keyval Error: framewidth not allowed.
    \begin{document}
    \frameit{A box whose colour and padding came from the option list.}
    \end{document}

    One preamble for many documents

    Once a preamble works it becomes an asset, and there are three sizes of container for it. A fragment: base.tex, read from the master with \input{base} — no identification block required, no extension guessing, easy to edit, visible only to that project. A package: mynotes.sty with the format block from the previous section, so that any folder can say \usepackage{mynotes}. A class: mythesis.cls, when what varies is layout and numbering rather than the command set — and a derived class costs about three lines more than the package version, because it inherits: \DeclareOption*{\PassOptionsToClass{\CurrentOption}{report}}, then \ProcessOptions\relax, then \LoadClass[12pt,a4paper]{report}.

    Installation is the part people expect to be difficult and is one command each way. kpsewhich --var-value TEXMFHOME prints a directory you own; put the file under TEXMFHOME/tex/latex/mynotes/mynotes.sty and every engine finds it in every project, no database refresh needed. Next to the source file also works, which is the honest choice for a shared repository: a personal tree is invisible to a co-author, to a clone and to CI, so a project that must build anywhere keeps base.tex under version control and lets only genuinely personal notation live in TEXMFHOME.

    The multi-file case is where a shared preamble earns its keep, and two packages own it. subfiles lets a child document compile alone from a two-line prologue, \documentclass[../main.tex]{subfiles}, which means the master's class and preamble are re-read for that one chapter instead of being copied into it. The standalone class does the equivalent for a figure: the child has no page geometry of its own, border=2pt crops to the drawing, and \includestandalone with subpreambles=true re-executes the child preamble inside the master when the figure needs packages the master does not load.

    Both mechanisms import the clash problem, in the form that bites hardest: the child loads xcolor with dvipsnames, the master loads it with svgnames, and the option clash appears in a file you did not edit. The defences are the same two as before — the master declares the union first with \PassOptionsToPackage, or the child stops carrying a preamble and inherits — and load order still applies at the seam: standalone is documented to be loaded after hyperref, because both install code at the beginning of the document. This is also why a child compiled alone can report ! Undefined control sequence. for a macro defined in the master: it is not the same file being read, it is a different \jobname and a shorter path back to the graphics.

    \text{one preamble} \;\longrightarrow\; \underbrace{\texttt{main.tex} + \sum_i \texttt{ch}_i}_{\text{the same options, every single time}}
    \text{one preamble} \;\longrightarrow\; \underbrace{\texttt{main.tex} + \sum_i \texttt{ch}_i}_{\text{the same options, every single time}}
    A class file may itself \input{base}, which is how a department ships one package list and lets four different document classes read it.
    % ============================================================
    % base.tex  —  a fragment, read with \input: no \ProvidesPackage
    %              needed, no extension guessing, project-local
    % ============================================================
    \ProvidesFile{base.tex}[2026-01-15 shared preamble v1.4]
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath,amssymb,mathtools}
    \usepackage{graphicx,booktabs}
    \usepackage[a4paper,margin=2.5cm]{geometry}
    \newcommand{\R}{\mathbb{R}}
    
    % ============================================================
    % mynotes.sty  —  the same content as a real package, so that any
    %                folder can say \usepackage{mynotes}
    %                install: TEXMFHOME/tex/latex/mynotes/mynotes.sty
    %                check:   kpsewhich mynotes.sty
    % ============================================================
    \NeedsTeXFormat{LaTeX2e}[2020-10-01]
    \ProvidesPackage{mynotes}[2026-01-15 v1.4 house style]
    \RequirePackage{amsmath,amssymb,mathtools}   % \RequirePackage, not \usepackage
    \DeclareOption*{\PassOptionsToPackage{\CurrentOption}{geometry}}
    \ProcessOptions\relax
    \RequirePackage{geometry}
    \endinput
    
    % ============================================================
    % mythesis.cls  —  a class is a package that also owns the layout.
    %                 The option block has to close before \LoadClass.
    % ============================================================
    % \NeedsTeXFormat{LaTeX2e}[2020-10-01]
    % \ProvidesClass{mythesis}[2026-01-15 v1.0 department thesis style]
    % \DeclareOption*{\PassOptionsToClass{\CurrentOption}{report}}
    % \ProcessOptions\relax
    % \LoadClass[12pt,a4paper]{report}
    % \RequirePackage{mynotes}
    % \endinput
    
    % ============================================================
    % main.tex  —  one master, children that can be compiled alone
    % ============================================================
    % \documentclass[12pt,a4paper]{report}
    % \input{base}
    % \usepackage{subfiles}
    % \usepackage[colorlinks=true]{hyperref}
    % \usepackage{standalone}        % documented to come AFTER hyperref
    % \begin{document}
    % \subfile{chapters/03-structure}
    % \includestandalone[width=.6\linewidth,subpreambles=true]{figures/circuit}
    % \end{document}
    
    % ============================================================
    % chapters/03-structure.tex  —  the child re-reads the master preamble
    % ============================================================
    % \documentclass[../main.tex]{subfiles}
    % \begin{document}
    % \chapter{Structure}
    % $\R$ is complete, and \autoref{eq:master} still resolves.
    % \end{document}

    Hooks, patches and the log

    The preamble is not a single moment, and packages that have to cooperate agree on when their code runs. Written directly in a file, it runs when the file is read. \AtBeginDocument{...} defers it to the begin-document hook — the place for a length the class has not finished setting, or a command another package will only define later. \AtEndDocument{...} is the symmetric one. Because the class and hyperref both install code at that hook, a \setlength that "does nothing" in your preamble has usually been undone by a file loaded after yours, not ignored.

    etoolbox supplies the timing a real preamble needs. \AtEndPreamble{...} runs at the last moment before \begin{document}, which buys you "after everything" without editing the load order of files you do not own. \AtBeginEnvironment{theorem}{...}, \AtEndEnvironment and \BeforeBeginEnvironment attach code to an environment instead of to a position in a file — how a style adjusts \topsep inside itemize without redefining the environment. \newrobustcmd defines a command that survives being written into a table of contents. And \patchcmd{cmd}{search}{replace}{success}{failure} performs a surgical redefinition whose last two arguments are the reason package debugging is survivable: you decide what happens when the text you are looking for is no longer there.

    That is also the shape of a conflict diagnosis, because "package X breaks package Y" resolves into one of three cases. The same name was defined twice, and a \newcommand says so with Command \foo already defined. One package patched the other too early, which is an ordering problem and is fixed by moving a line or by \AtEndPreamble. Or both installed begin-document code and the order of the hooks decides the result, which is what makes hyperref and a dozen smaller packages sensitive to position. Two kernel tests let a file adapt instead of hoping: \@ifpackageloaded{cleveref}{...}{...} and \@ifpackagelater{pgfplots}{2023-01-01}{...}{...}.

    For the version question the answer is already in the log, and \listfiles as the first line of the file makes it explicit: the run ends with a block naming every file read, each with its date, version and identification string. That block is the portable part of a bug report — two machines disagree about package versions far more often than LaTeX behaves differently. Read the rest of the log from the first line beginning with ! and then upwards, not from the bottom: the message names the symptom, the earlier lines name the file that caused it, and Option clash for package X means nothing until you have found the first File: X.sty above it.

    \texttt{AtEndPreamble} \;<\; \texttt{begin document} \;<\; \texttt{AtBeginDocument} \;<\; \texttt{first page} \;<\; \texttt{AtEndDocument}
    \texttt{AtEndPreamble} \;<\; \texttt{begin document} \;<\; \texttt{AtBeginDocument} \;<\; \texttt{first page} \;<\; \texttt{AtEndDocument}
    The file list is the only part of a log worth pasting into a question; the rest of it is one machine's paths, and it buries the three lines that matter.
    \texttt{.log}:\;\bigl\{\,\texttt{pkg.sty}\;{\textstyle 2024/03/15}\;v1.9\,\bigr\} \;\longrightarrow\; \text{two machines, two answers}
    \texttt{.log}:\;\bigl\{\,\texttt{pkg.sty}\;{\textstyle 2024/03/15}\;v1.9\,\bigr\} \;\longrightarrow\; \text{two machines, two answers}
    \documentclass[11pt]{article}
    \listfiles                      % first line: the .log ends with a versioned
                                    % list of every file that was read
    \usepackage{amsmath}
    \usepackage{xcolor}
    \usepackage{etoolbox}
    \usepackage[colorlinks=true,linkcolor=blue]{hyperref}
    
    % ---- 1. code that must see the FINAL state of the preamble
    \AtEndPreamble{\typeout{HOOK: preamble complete, hyperref loaded}}
    
    % ---- 2. code that must wait until the class has finished setting defaults
    \AtBeginDocument{\setlength{\parskip}{6pt}}
    
    % ---- 3. attaching behaviour to an environment instead of to a point in a file
    \BeforeBeginEnvironment{quote}{\par\smallskip}
    \AtEndEnvironment{quote}{\par\medskip}
    
    % ---- 4. a surgical patch: five arguments, and the last two are the point
    \newcommand{\thmref}[1]{\textit{\ref{#1}}}
    \patchcmd{\thmref}{\textit}{\textbf}
      {\typeout{thmref patched}}
      {\typeout{thmref NOT patched -- the search text is gone, do not patch blind}}
    
    % ---- 5. adapting to what is loaded, instead of hoping about it
    \makeatletter
    \@ifpackageloaded{cleveref}{\typeout{cleveref is present}}{\typeout{no cleveref}}
    \@ifpackagelater{pgfplots}{2023-01-01}{\typeout{recent pgfplots}}{\typeout{pgfplots is old, or absent}}
    \makeatother
    
    \begin{document}
    % Everything inside \AtBeginDocument has run by now, so \parskip is 6pt here.
    \thmref{eq:x}
    \begin{equation}\label{eq:x} E=mc^{2} \end{equation}
    \end{document}
    
    % ============================================================
    % The tail of the .log, which is the part worth pasting into a report:
    %   File: article.cls 2024-01-24 v1.4n Standard LaTeX document class
    %   File: amsmath.sty 2023-05-13 v2.9o AMS mathematical facilities
    %   File: xcolor.sty 2022/06/12 v2.14 LaTeX driver package
    %   File: etoolbox.sty 2020-10-19 v2.5k e-TeX tools for LaTeX
    %   File: hyperref.sty 2024-01-13 v7.01a Hypertext links for LaTeX
    % And the way an option clash is read -- the message names the second
    % request, the line above it names the first load:
    %   File: geometry.sty 2020/01/02 v5.9 ...        <- loaded by mynotes.sty
    %   ! LaTeX Error: Option clash for package geometry.

    Lesson cheat sheet

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

    Section Key code
    \mathbb{R} \quad \mathbb{N} \quad \aleph_0
    \documentclass[11pt,a4paper]{article}
    \NeedsTeXFormat{LaTeX2e}[2021-11-15] % refuse a too-old format loudly
    \NeedsTeXFormat{LaTeX2e}[2020-10-01]
    \ProvidesFile{base.tex}[2026-01-15 shared preamble v1.4]
    \documentclass[11pt]{article}

    Common mistakes

    • ! LaTeX Error: Option clash for package xcolor. The file was already loaded — by the class, or by tikz — and the two option lists differ. Fix it at the first load, not the second: \PassOptionsToPackage{dvipsnames,svgnames}{xcolor} above the line that pulls it in, or load xcolor yourself earlier with the union of both lists.
    • ! LaTeX Error: File `mynotes.sty' not found. The file exists but not where the run looks. Beside a child file rather than beside the master is the usual cause, as is an installed file the filename database has not been told about (mktexlsr, or MiKTeX's refresh). Check the name the engine would resolve with kpsewhich mynotes.sty, or avoid the question with \input{base}.
    • Unknown option `twoside' for package `mynotes'. A class option typed into a package bracket, or your own .sty receiving a name it never declared. Add the catch-all \DeclareOption*{\PassOptionsToPackage{\CurrentOption}{geometry}} so unclaimed options are forwarded instead of being fatal.
    • ! Package keyval Error: framewidth not allowed. A key/value option reached the right family and matched no declaration: a typo, or a key from a different package with a similar name. Key names are exact strings, and there is no fuzzy matching to blame.
    • ! Undefined control sequence. pointing at \mathscr, \coloneqq or \crefrange: the command belongs to the AMS font bundle, mathtools or cleveref and none of them is loaded — or it is loaded in the master and not in the child you compiled alone, which is the subfiles form of the same mistake.
    • A \setlength or \renewcommand in the preamble that changes nothing on the page: a file read later applies its own value on top of yours, most often the class at \AtBeginDocument, or geometry, or hyperref. Defer your code with \AtBeginDocument{...} or etoolbox's \AtEndPreamble{...} instead of fighting the sequence, and check which file wins with \show\parskip.

    Questions about this lesson

    Why does LaTeX say option clash for package, and how do I fix it for good?
    Because the same .sty was requested twice with different option lists, and LaTeX cannot re-execute a file with new options. The first load wins, so the fix is always to control the first load: write \usepackage[dvipsnames,svgnames]{xcolor} yourself before anything else pulls it in, or state the options in advance with \PassOptionsToPackage{dvipsnames}{xcolor} when the first load happens inside a class or another package you do not own. In a multi-file project the clashing load is often in the class, which is why the error names geometry or xcolor but no line of your document.
    Does the order of usepackage lines really matter in a LaTeX preamble?
    It matters whenever one package touches something another defines, because the preamble is executed once, top to bottom, with no dependency resolution. The rules that follow: mathtools after amsmath, xcolor before tikz and pgfplots, fontenc before hyperref, hyperref near the end, cleveref after hyperref, standalone after hyperref. Order also decides which \AtBeginDocument code runs first. If two lines are independent of each other their order is irrelevant, so treat "load everything in this exact sequence" as superstition and "the patcher comes after the patched" as the rule.
    How do I see which packages and versions a LaTeX document actually loaded?
    Put \listfiles on the first line of the main file and look at the end of the .log: it lists every file read, with the date and version string each one declared through \ProvidesPackage or \ProvidesClass. That block is what to paste into a bug report when a document builds on one machine and not another, because package versions drift apart long before LaTeX itself does. Per package you can also test the version in the source with \@ifpackagelater{name}{YYYY/MM/DD}{yes branch}{no branch}.
    What is the difference between a LaTeX class file and a package file?
    A package (.sty) is code read by \usepackage: it defines commands, changes defaults or attaches behaviour, and it processes options handed in a bracket. A class (.cls) is read by \documentclass, is loaded before everything else, owns the page geometry, the sectioning commands and the counters, and processes the options written on the class line and forwards them to the packages. A class can inherit from another class with \LoadClass, which is what most journal and thesis styles do; a package cannot. Both use the same option mechanism, \DeclareOption, \ExecuteOptions and \ProcessOptions.
    How do I reuse the same LaTeX preamble in several documents without copying it?
    Three sizes. A fragment file such as base.tex read with \input{base} — simplest, project-local, no version string, no options. A package mynotes.sty with \NeedsTeXFormat, \ProvidesPackage and \RequirePackage for its dependencies; installed under TEXMFHOME (find the path with kpsewhich --var-value TEXMFHOME) it is visible to every project on that machine, which is also its weakness, because co-authors and CI do not have your personal tree. A class mythesis.cls with \LoadClass{report} when the differences are layout and numbering. For chapters that compile alone, subfiles and standalone re-read the master preamble instead of duplicating it.
    What is the difference between AtBeginDocument and AtEndPreamble in etoolbox?
    AtEndPreamble runs at the last moment of the preamble, before \begin{document} is executed, so it sees every package definition and can still change things the normal way — that is the place for code that must run after everything else is loaded. AtBeginDocument runs later, inside the begin-document hook, after the class has applied its own settings, which is what you want for lengths and fonts a class or package would otherwise overwrite, and too late for anything that has to exist before the first page is set up. \AtEndOfPackage does the same job inside a .sty file, at the end of that one file.

    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.