1

It is known that the package scrhack should be loaded as late as possible to avoid some errors. See here for such a problem.

However, when writing a document class or a package, I would like to require packages (without necessarily requiring conflicting packages).

An example illustrates my problem:

% MyTheme.cls
\NeedsTeXFormat{LaTeX2e}[1996/12/01]
\newcommand{\classname}{MastersDoctoralThesis}
\ProvidesClass{\classname}[2020/08/24 v1.7 LaTeXTemplates.com]
\providecommand{\baseclass}{book}
\LoadClass{\baseclass}
\RequirePackage{scrhack}
% main.tex
\documentclass{MyTheme}
\usepackage{listings}
\usepackage[outputdir=build]{minted}

\begin{document}
Test
\end{document}

This will create the following error:

scrhack Error: extension `lol' already in use.

The problem is solved if I remove \RequirePackage{scrhack} in MyTheme.cls, or if I add \RequirePackage{minted} before \RequirePackage{scrhack}. However, I prefer to keep the dependency on scrhack explicit, and don't want to create unnecessary dependencies.

...but how? Is it possible to somehow request a package with \RequirePackage, but delay loading it?

4
  • Please complete your class code so we can compile the hole thing ...
    – Mensch
    Sep 28, 2022 at 18:46
  • @Mensch Updated my question with a minimal document class.
    – normanius
    Sep 28, 2022 at 19:02
  • In the meanwhile, I found that adding \AtBeginDocument{\usepackage{scrhack}} in the document class solves my problem.
    – normanius
    Sep 28, 2022 at 19:04
  • 2
    don't load packages in \AtBeginDocument, hyperref e.g. will simply error if loaded so late. Better use \AddToHook{begindocument/before}{...} Sep 28, 2022 at 19:11

1 Answer 1

1

I figured out that using \AtBeginDocument{\usepackage{packagename}} delays the loading of required packages. Some comments pointed out even more appropriate hooks.

The following document class also requires the scrhack package, but does not cause the problem stated in the OP.

% MyTheme.cls
\NeedsTeXFormat{LaTeX2e}[1996/12/01]
\newcommand{\classname}{MastersDoctoralThesis}
\ProvidesClass{\classname}[2020/08/24 v1.7 LaTeXTemplates.com]
\providecommand{\baseclass}{book}
\LoadClass{\baseclass}

% Deferred loading of package scrhack
% Alternative 1:
\AddToHook{begindocument/before}{\usepackage{scrhack}}

% Alternative 2: Uses package etoolbox
\usepackage{etoolbox}
\AtEndPreamble{\usepackage{biblatex}}

% Alternative 3: Load package at begin{document}, which might be 
% too late for some packages (as has been noted by Ulrike Fischer)
\AtBeginDocument{\usepackage{scrhack}}
2
  • See also this related post.
    – normanius
    Sep 28, 2022 at 19:10
  • 2
    There is also the \AtEndPreamble hook from etoolbox, which executes a bit earlier than \AtBeginDocument.
    – Marijn
    Sep 28, 2022 at 21:30

You must log in to answer this question.

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