Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I am putting together a large document and my preamble is unwieldly and disorganised. What order does it make sense to load packages. Obviously, hyperref goes last, apart from things that have to go after hyperref. I tend to load font packages first, as they seem like a big global change. What other categories should I arrange my preamble around? Are there other cases where load order is important? Should I keep other commands close to the packages they relate to? e.g. should I keep my bibliography formatting commands near my \usepackage{biblatex} call?

share|improve this question
3  
Related: tex.stackexchange.com/questions/3090/… –  Torbjørn T. Jan 11 '12 at 16:06
1  
interesting read that is slightly related: markelikalderon.com/2008/07/31/… –  Tobias Kienzler Jan 11 '12 at 21:34
    
Also related: tex.stackexchange.com/questions/27347/… –  lockstep Jan 11 '12 at 23:48

5 Answers 5

up vote 71 down vote accepted
+50

If you want to see how things can get tangled in a preamble have a look at the preamble of the Comprehensive LaTeX Symbol List. It might not be exactly spaghetti code but it can certainly be classified as code soup!

So you right, you need to have a strategy and start working on it early in the development of your document. The tips below are from my own workflow and observations.

Early on, when I started with LaTeX, I realized that having used numerous macros and packages to change the looks of almost every single parameter originally set by the LaTeX book.cls, I would have been better off to have developed my own class and this is my first tip.

1. Consider developing your own class or package to hold your changes.

It is as simple as hitting a save as button to save the base class .dtx file and its .ins file. It will get you going with literate programming and honestly it should not take longer than an hour or two to find out how it all works. When you use doc for the first time you might get disoriented, but eventually you get used to the conventions. Another advantage of this approach is that at the beginning of developing a new document, you will find out that on Mondays, Wednesdays and Thursdays, you will want your document to look one way and on the rest of the days of the week you will want it in another way. By writing your rationale down using literate programming, it helps you settle your ideas.

2. Have the packages and own related commands, near each other

For smaller changes, i.e., write short packages, either using the doc/docstrip system or if you are in a hurry just use the package filecontents and write them on the fly while developing the document. This tends to remove a lot of code and comment lines in the preamble. I have all maths related macros normally in a package called moremaths.

% MATHEMATICS
\usepackage{amsfonts}
\usepackage{amsmath}[2000/07/18] %% Displayed equations
\let\equation\gather                          %% See tabu and hyperref docs
\let\endequation\endgather
\usepackage{amssymb}[2002/01/22] %% and additional symbols
\usepackage{amsfonts}
\usepackage{xfrac}
\usepackage{stmaryrd}
\usepackage{mathtools}
\usepackage{eucal} 

Similarly, for tables

%% Tables
%%  TABLES
\RequirePackage{array}
\RequirePackage{booktabs}
\RequirePackage{longtable}
\RequirePackage{tabularx}
\RequirePackage{dcolumn}
\RequirePackage{multirow}
%% Set some local commands and colors
\RequirePackage{colortbl}              % for colored table cells
\definecolor{green}{rgb}{0.1,0.1,0.1}
\newcommand{\done}{\cellcolor[gray]{0.9}done}  %{0.9}for done tables
%
%

3. Divide the preamble into headings, such as typography, graphics, maths, sectioning etc.

If you do not develop your own class and use any of the major classes such as Koma or memoir, you will discover that in general these classes have their own configuration commands for every possible change; it helps if you divide all the relevant commands in sections. If the sections grow, i.e, if you have too many typography save the code in a package and name it moretypography or moremaths etc. Again here, if the preamble grows question the need for your own class.

4. Have the problematic package settings in their own packages e.g., sethyperef or setlistings package etc.

Some packages are difficult to set and can give you problems if they are loaded before or after some packages (See Which packages should be loaded after hyperref instead of before?). Others need some complicated and long settings. Again here if you work on a long documents it may be worth changing these settings to small packages. If you identify sources of errors better save and restore commands rather than move them around. For example the verse package gave me problems with the macro theHpoemline and I normally only load it together with the following macros.

\let\oldH\theHpoemline
\let\theHpoemline\undefined

There are a lot of similar techniques in the Comprehensive LaTeX Symbol List, preamble, worth a read.

share|improve this answer
6  
About the "consider developing your own .sty file" comment. Then the question becomes "How to organise the .sty file… Since my main.tex is basically just preamble and then \include{chapter1}… etc, I don't gain anything by doing this, really. –  Seamus Jan 13 '12 at 16:38
2  
@Seamus It helped me organize a rather huge preamble. I first started with item 3) made blocks of the preamble into small packages moremath, typography, morelists etc. It gave stability to at least sections of the preamble, which originally had a mix of newcommands, settings and use package. Once it settled I combined everything into a .dtx. When you busy writing you tend to just put things at the bottom of the preamble rather than organize it properly. Once it is in a .dtx the question... how to organize it becomes easier to answer. –  Yiannis Lazarides Jan 13 '12 at 16:56
1  
@Seamus Sorry for the double post to continue, in the dtx you describing what you doing, section{typography}, include microtype to minimize hyphenation and better line breaks, add csquotes..., \def{TODO} for short notes... hope you get the idea. Give it a try will cost you one hour:) –  Yiannis Lazarides Jan 13 '12 at 16:58
    
"code soup" that is almost "spaghetti code" should be "code minestrone". –  Seamus Jul 18 '12 at 10:48

As you've already observed, loading hyperref should happen very late in the preamble. (However, if you load cleveref, you probably already know that it should be loaded after hyperref.) For more information on package loading orderings see, for instance, the question "Which packages should be loaded after hyperref instead of before?"

Without knowing what your document is about, I don't believe it's possible to give very specific recommendations on how your document's preamble should be organized/structured. The following comments and notes are therefore a bit generic.

  • You may want to put the entire preamble content into a .sty file called, say, seamus-preamble-package, to be loaded via \usepackage{seamus-preamble-package} as the one and only instruction in the main document's actual preamble. (Of course, this .sty file needs to be located in a directory that's searched by your TeX implementation.) If nothing else, putting the preamble stuff into a .sty file frees you from having to provide all those \makeatletter ... \makeatother instructions.

  • Computer code being long and unwieldy is not the same as it being inefficient or needlessly complex. If your document is long and complex, there's probably no reason for the preamble to be simple and short. Do check, though, if there are packages that don't need to be loaded at all, if certain package are being invoked with unneeded options, or if there exist some packages that could execute some tasks currently being coded laboriously in the preamble.

  • A general recommendation, which I'd say applies not only for organizing a preamble, is to use comments and whitespace liberally. That way, if you or someone else has to change stuff in the preamble at some later point in time, less time will be wasted figuring out what's going on and what may need to be changed.

  • Depending on how complex the preamble is, it may make sense to write up a miniature table of contents as a "guide" to the preamble's structure. This guide could be as simple as providing a plain listing of the groups of tasks that are being taken care of in the preamble. For instance, this listing could consist of something like the following:

    • Define page layout in main body of text -- incl. appearance of sectioning headers, width and height of text block, line spacing, header and footer lines, position and format of page numbers
    • Select fonts and font-related features
    • Organize layout of table of contents pages
    • Organize appearance of headers in appendix
    • Organize appearance of bibliography and citation methods
    • Load packages related to math, define specialized math-related commands
    • Configure float-related matter -- incl. appearance of captions and the panoply of parameters related to float placement
    • Address all other tasks that don't fall neatly into one of the other categories. E.g., add certain words to a hyphenation exception list, load a package that lets you typeset the euro symbol, etc
    • Load packages related to hyper-referencing and other cross-referencing tasks
  • Especially if you decide to organize the preamble along the themes outlined in the preceding bullet points, it would make sense to keep those instructions that relate to a specific task (say, creating the bibliography via biblatex, or setting the table of content's style via tocloft) close to the commands that load the packages in question.

  • Another recommendation, possibly a bit more controversial: you could load those packages that can be invoked without setting any special options in a single \usepackage instruction.

    • As @MichaelPalmer observes in his comment, a variation on this method is to have a single \usepackage statement but to devote one line to each package being loaded. This lets the reader see clearly what's being loaded, and it also provides a method for adding short comments on each line of associated code.
share|improve this answer
1  
re: load everything with a single \usepackage : I disagree. It makes it hard to replace a package, or comment out a package and things like that… –  Seamus Jan 11 '12 at 17:11
    
Sorry if I didn't express this clearly enough: I did not suggest to load every package via a single \usepackage statement, but only those that needn't be loaded with specific options. I'll rewrite that passage. –  Mico Jan 11 '12 at 17:14
4  
You can use a single \usepackage clause yet still put every package name into a separate line. I do this for all packages that are loaded without options. –  Michael Palmer Jan 11 '12 at 17:28
1  
In which order are packages in the same \usepackage statement loaded? –  Federico Poloni Jan 12 '12 at 10:29
1  
@Mico: sorry, probably my question wasn't clear enough. What I meant is: if I write \usepackage{package1,package2}, does package1 always get loaded before package2? Or viceversa, or is it undefined/implementation-dependent? –  Federico Poloni Jan 12 '12 at 13:12

Preambles that load a lot of packages (or large packages, such as TikZ) can really slow down your workflow. TeX supports format (.fmt) files, which store TeX data structures in serialized form. TeX can reload them and pick up where it left off in processing a given document. By creating a format file, you can avoid re-loading packages every time you build your document.

Creating a format file requires a number of steps (I'm using pdflatex in TeXLive 2011):

  1. Move your preamble from your document (I'll call that doc.tex) to its own file, including the \documentclass declaration. Call the new file preamble.tex.
  2. Add a definition to the bottom of preamble.tex that will indicate it has been loaded: \def\preambleloaded{}

  3. Put the following line at the very beginning of preamble.tex: %&pdflatex.

    This ensures that your preamble loads the LaTeX sources. Without it, the next step will fail. preamble.tex should look something like this:

    %&pdflatex
    \documentclass{...}
    ... 
    \def\preambleloaded{}
    %% end of preamble.tex
    
  4. Run pdflatex with the -ini option to dump the format file: "pdflatex -ini preamble \dump".

  5. Add the following line to the top of doc.tex: %&preamble.

    This line ensures your preamble format file will be loaded.

  6. Now we need to make sure doc.tex inputs preamble.tex if the format file does not exist. In place of all the code you moved to preamble.tex, add this test which only loads preamble.tex if preambleloaded has not been defined:

    \ifx\preambleloaded\undefined
       \input{preamble}
    \fi
    

    \begin{document} should immediately follow the test above. The beginning of doc.tex should look like:

    %&preamble
    \ifx\preambleloaded\undefined
       \input{preamble}
    \fi
    \begin{document}
    ...
    

After the above, you can modify doc.tex all you want and TeX will not re-parse preamble.tex when building doc.tex. If you change preamble.tex, just re-run the pdflatex -ini command to rebuild the format file.

This is a good place to plug Chris Monson's LaTeX Makefile, which will re-make your format file as needed (i.e., make doc will re-build preamble.fmt when preamble.tex changes).

share|improve this answer
    
I tried this, but I get the following error: ! LaTeX Error: Missing \begin{document}. when I run pdflatex -ini preamble \dump –  Seamus Aug 9 '12 at 12:20
    
I had to run pdflatex -ini preamble and then when it got to the end and prompted me, \dump worked. weird. –  Seamus Aug 9 '12 at 12:26
    
You might also need to use the -parse-first-line option, or hunt down the relevant option in texmf.cnf. –  Seamus Aug 9 '12 at 12:38
    
(responding to the first comment) - maybe your shell treats `` as special and you need to escape it? –  Justin Bailey Aug 9 '12 at 22:18
1  
It works if I do pdflatex -ini "preamble.tex\dump". –  Seamus Aug 10 '12 at 9:37

Here's a detail that'll probably be trivial to most, but made me stumble one time: Put the metadata (\author, \title, \date) towards the end of your preamble. Packages like titling depend on that information (This is where I failed). You might want to put them before hyperref though, so that it can automatically gather that data via the pdfusetitle option.

I was just used to putting it first in my preamble because these commands were among the first things I learned in LaTeX, so they stayed at the top, while other things (= packages) were added at the bottom.

Another detail that won't matter in most situations, but can nonetheless easily be done: Put fontenc after all your packages loading fonts in order to avoid loading any unnecessary T1-encoded fonts from the Computer Modern family.

share|improve this answer
5  
You do not seem to have to place \title before hyperref for the pdfusetitle option to notice it. –  N.N. Mar 28 '12 at 9:45

It's a somewhat peripheral matter, but I ordinarily comment \usepackage whenever I've introduced a package for the sake of some specific command or environment. I may not remember those relationships in the future, and commenting helps with debugging, as well with finding solutions that worked in the past.

Examples:

\usepackage{datetime}       % allows \currenttime
\usepackage{rotating}       % allows sidewaystable environment
\usepackage{dpfloat}        % allows use of leftfullpage and fullpage environments, to place successive figures on facing pages

Of course, specifying the purpose of a given package helps me classify it in relation to others — its function is not the same in all documents.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.