[Tex/LaTex] Is \AfterEndPreamble really executing code after any \AtBeginDocument code

babeletoolboxhookslanguages

The babel package loads the (last) language at begin document, thanks to an \AtBeginDocument command (lines 12.256 and 12.257 of its kernel):

\AtBeginDocument{%
\expandafter\selectlanguage\expandafter{\bbl@main@language}}

On the other hand, the \AfterEndPreamble command from the etoolbox package is supposed to execute "code […] at the very end of \begin{document}, after any \AtBeginDocument code."

But it seems not to be the case in the following MCE:

\documentclass[french]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{etoolbox}
\usepackage{babel}
%
\AfterEndPreamble{%
  \title{Quelle crise?}%
}
%
\begin{document}
\maketitle
\end{document}

Indeed, if executed after the french language would be loaded, \title{Quelle crise?} should give a thin space before the "?" as it is the case in the following MCE:

\documentclass[french]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{etoolbox}
\usepackage{babel}
\begin{document}
\title{Quelle crise?}
\maketitle
\end{document}

Best Answer

Babel's language french makes ? active as shorthand. However it is done in \begin{document} in order to avoid disturbing the loading of other packages. However, you have specified \title in the preamble before \begin{document}. It does not matter, that it is executed later. Only the time matters, when the code is read and translated to tokens.

Solution: You can enable shorthands temporarily in the preamble:

\documentclass[french]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{etoolbox}
\usepackage{babel}
%
\shorthandon{?}
\AfterEndPreamble{%
  \title{Quelle crise?}%
}
\shorthandoff{?}
%
\begin{document}
\maketitle
\end{document}

Result

Without \shorthandon{?} the question mark has catcode 12 (other) and it is not treated as babel shorthand. With \shorthandon{?} the question mark is active (catcode 13) and is executed as shorthand at the time of \maketitle. Thus you do not need \AfterEndPreamble here.

Related Question