biblatex can not be loaded in \AtEndPreamble
MWE:
\documentclass{article}
\usepackage{etoolbox}
\AtEndPreamble{\usepackage{biblatex}}
\begin{document}
foo
\end{document}
Error Message
Many. The first error message is
/usr/local/texlive/2020/texmf-dist/tex/latex/biblatex/biblatex.sty:503: Undefined control sequence.
<argument> ...atibility@endpreambleonly \ifnum \blx@hyperref
=\thr@@ \else \ifnum \blx@...
l.503 \let\do\noexpand}
and the others are in the .log file test.log
Solution
See https://github.com/CTeX-org/forum/issues/190, changing \AtEndPreamble{...} (\AddToHook{begindocument/before}{...}) to \AddToHook{env/document/before}{...} will fix it.
\documentclass{article}
\AddToHook{env/document/begin}{\usepackage{biblatex}}
\begin{document}
foo
\end{document}
Thanks for reporting this issue.
Apologies if I tell you something you know already, but as far as I can tell the problem is that biblatex itself has quite some code in \AtEndPreamble. The assumption being that that code is executed after the entire .sty has been loaded. If we load biblatex inside \AtEndPreamble biblatex's own \AtEndPreamble code is executed immediately violating that assumption and causing errors.
I could 'fix' this by moving all \AtEndPreamble calls in biblatex.sty to the end of the file. But I'm not sure that this is something we want to do. I think loading complex packages like biblatex in \AtEndPreamble is too tricky with all the timing issues and is not something we should encourage. That is also the sentiment shared in https://tex.stackexchange.com/q/305095/35864 (though I must admit I cannot reproduce how the .aux file is problematic here).
https://tex.stackexchange.com/questions/305095/loading-biblatex-from-within-the-atendpreamble-hook
Sorry, I don't know it has been reported since 5 years ago…
Neither did I :-). It hadn't been reported here and I only found this after I googled for \AtEndPreamble and biblatex.
Note that if you want to load biblatex in \AtEndPreamble, you also need to use all its preamble commands (at least \addbibresource, but also every other command you might want to use like \DeclareFieldFormat) in \AtEndPreamble, which might become a bit messy.