Within a document's preamble (or a custom "preamble" package), at times there's the need to take compulsory load orders for certain packages into account. Most packages must be loaded before the hyperref package, some packages (e.g. glossaries, ellipsis) must be loaded after hyperref, and then there's the cleveref package which "basically[...] must be loaded last" (manual, section 2). A (small) document accounting for all this may look like


\usepackage{varioref}% Must be loaded before hyperref
\usepackage{ellipsis}% Must be loaded after hyperref
\usepackage{cleveref}% Must be loaded after any packages that modify
%     LaTeX's referencing system



Some text~\dots\ and some more.


See \vref{chap:foo}.


However, I'd prefer a preamble that is sorted thematically, e.g.


% Special characters and symbols

% Cross-referencing

% Hyperlinks



(I didn't round out the above code snippet to a complete MWE because it would result in unresolved references.)

I understand that sorting by compulsory load order is no big deal for small-to-medium preambles, but at some point (say, 20+ packages) it becomes confusing. Is it possible to sort preamble packages thematically, but still to account for compulsory load orders?

  • Do you want this to happen automatically? Do you mind using Unix utilities or does it have to be completely cross-platform? Sep 3, 2011 at 14:44
  • I'd prefer a completely cross-platform, "(La)TeX internal" solution; I'm aware that this may involve loading additional macros/packages and so may not be regarded as completely "automatic". That said, a good, comprehensible answer involving Unix utilities will get my upvote (I use Windows, though).
    – lockstep
    Sep 3, 2011 at 14:50
  • 1
    If restrictions were more formal, such as of form "X must be loaded before Y", it would be possible to apply topological sorting to the list of packages. But it's difficult to teach "Most packages must be loaded before the hyperref package" to the computer. Sep 3, 2011 at 15:34

1 Answer 1


A simple solution is to make use of the hook \AfterPackage{<package>}{<code>} provided by the scrlfile package (support package in the KOMA-Script bundle):



% programming tools


% glossaries and indices


% hypertext, bookmarks and PDF info


Note that <code> is only executed if <package> is eventually loaded. The star variant of \AfterPackage differs from the non-star variant in that <code> is immediately executed if <package> has already been loaded.

  • 4
    \AfterPackage* is great and covers most of my needs. For packages that should be loaded at the very end, \AtEndPreamble from the etoolbox package is a good addition.
    – lockstep
    Sep 4, 2011 at 8:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .