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?
- 73,242
-
3Related: http://tex.stackexchange.com/questions/3090/packages-that-need-to-be-included-in-a-specific-order – Torbjørn T. Jan 11 '12 at 16:06
-
1interesting read that is slightly related: http://markelikalderon.com/2008/07/31/keeping-your-latex-preamble-in-a-git-submodule/ – Tobias Kienzler Jan 11 '12 at 21:34
-
Also related: http://tex.stackexchange.com/questions/27347/sorting-preamble-packages-thematically-while-accounting-for-compulsory-load-orde – lockstep Jan 11 '12 at 23:48
5 Answers
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 are 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 developping 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.
-
8About the "consider developing your own
.styfile" comment. Then the question becomes "How to organise the.styfile… Since mymain.texis basically just preamble and then\include{chapter1}… etc, I don't gain anything by doing this, really. – Seamus Jan 13 '12 at 16:38 -
3@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,morelistsetc. 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.dtxthe question... how to organize it becomes easier to answer. – yannisl Jan 13 '12 at 16:56 -
2@Seamus Sorry for the double post to continue, in the dtx you describing what you doing,
section{typography}, includemicrotypeto 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:) – yannisl Jan 13 '12 at 16:58 -
2"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
.styfile 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.styfile needs to be located in a directory that's searched by your TeX implementation.) If nothing else, putting the preamble stuff into a.styfile frees you from having to provide all those\makeatletter...\makeatotherinstructions.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
eurosymbol, 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 viatocloft) 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
\usepackageinstruction.- As @MichaelPalmer observes in his comment, a variation on this method is to have a single
\usepackagestatement 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.
- As @MichaelPalmer observes in his comment, a variation on this method is to have a single
-
2re: 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 -
1Sorry if I didn't express this clearly enough: I did not suggest to load every package via a single
\usepackagestatement, but only those that needn't be loaded with specific options. I'll rewrite that passage. – Mico Jan 11 '12 at 17:14 -
5You can use a single
\usepackageclause 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
-
2In which order are packages in the same
\usepackagestatement loaded? – Federico Poloni Jan 12 '12 at 10:29 -
@FedericoPoloni: Not knowing which packages the OP actually will be loading, it's not possible to be precise here. In general, the order doesn't matter; for example, AFAICT it doesn't matter if
amsmathis loaded before or afteramssymb. However, if a package does have to be load after some other package, that'll usually be known to the author of the preamble instructions, won't it? – Mico Jan 12 '12 at 11:18 -
2@Mico: sorry, probably my question wasn't clear enough. What I meant is: if I write
\usepackage{package1,package2}, doespackage1always get loaded beforepackage2? Or viceversa, or is it undefined/implementation-dependent? – Federico Poloni Jan 12 '12 at 13:12 -
@FedericoPoloni: I believe they're loaded sequentially in the order specified in the
\usepackage{...}command. Looking at the.logfile(s) generated by the main.texfile(s), I've never seen an exception to this. :-) – Mico Jan 12 '12 at 13:19
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):
- Move your preamble from your document (I'll call that
doc.tex) to its own file, including the\documentclassdeclaration. Call the new filepreamble.tex. Add a definition to the bottom of
preamble.texthat will indicate it has been loaded:\def\preambleloaded{}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.texshould look something like this:%&pdflatex \documentclass{...} ... \def\preambleloaded{} %% end of preamble.texRun
pdflatexwith the-inioption to dump the format file: "pdflatex -ini preamble \dump".Add the following line to the top of
doc.tex:%&preamble.This line ensures your preamble format file will be loaded.
Now we need to make sure
doc.texinputspreamble.texif the format file does not exist. In place of all the code you moved topreamble.tex, add this test which only loadspreamble.texifpreambleloadedhas not been defined:\ifx\preambleloaded\undefined \input{preamble} \fi\begin{document}should immediately follow the test above. The beginning ofdoc.texshould 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).
- 1,921
-
I tried this, but I get the following error:
! LaTeX Error: Missing \begin{document}.when I runpdflatex -ini preamble \dump– Seamus Aug 09 '12 at 12:20 -
I had to run
pdflatex -ini preambleand then when it got to the end and prompted me,\dumpworked. weird. – Seamus Aug 09 '12 at 12:26 -
You might also need to use the
-parse-first-lineoption, or hunt down the relevant option intexmf.cnf. – Seamus Aug 09 '12 at 12:38 -
(responding to the first comment) - maybe your shell treats
\as special and you need to escape it? – Justin Bailey Aug 09 '12 at 22:18 -
2
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.
- 5,927
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.
-
5You do not seem to have to place
\titlebeforehyperreffor the pdfusetitle option to notice it. – N.N. Mar 28 '12 at 09:45