Hooks – Using LaTeX Hooks in Historical Versions of TeX Live

hookslthooks

At the end of 2020, LaTeX added support for a general hook management system. The system allows me to execute \maketitle at the beginning of a document if I am in the preamble, or immediately if I am in the document:

\AddToHook{begindocument/end}{\maketitle}

LaTeX hooks are only available in TeX Live 2021 and later. However, I need my code to work at least in unupdated TeX Live 2020 (to support Overleaf) and ideally in TeX Live ≥ 2018. Pragmatically, I could rewrite my code as follows:

\ifx\@onlypreamble\@notprerr
  % We are in the document
  \maketitle
\else
  % We are in the preamble
  \RequirePackage{etoolbox}
  \AfterEndPreamble{\maketitle}
\fi

However, I would like to gradually convert my code to use LaTeX hooks and using compatibility code will only accumulate technical debt, which I would like to avoid.

Does there exist a polyfill package that adds (limited) support for LaTeX hooks and that would allow me to use LaTeX hooks in historical TeX Live versions? Like this:

\RequirePackage{lthooks-polyfill}
\AddToHook{begindocument/end}{\maketitle}

If not, what is the suggested migration path from code that does not use hooks to code that uses hooks and stays compatible with historical releases of TeX Live?

Best Answer

Polyfills exist for features of the LaTeX kernel that came into existence by pulling a useful LaTeX package into the kernel. However, the concept of hooks is brand new and was inspired by a ragtag of different LaTeX packages: etoolbox, filehook, atbegshi, atveryend, and others.

As Ulrike points out in the comments below the original question, the \AfterEndPreamble command from the etoolbox package resembles the begindocument/end hook but only works in the preamble. Therefore, the answer seems to be a no: Although parts of the functionality of LaTeX hooks are available in different LaTeX packages, no comprehensive polyfill exists.

LaTeX hooks have been available since LaTeX 2020-10-01. Therefore, one migration path would be to write different code for LaTeX before and after 2020-10-01:

\providecommand\IfFormatAtLeastTF{\@ifl@t@r\fmtversion}
\IfFormatAtLeastTF{2020-10-01}%
  {\AddToHook{begindocument/end}{\maketitle}}%
  {%
    \ifx\@onlypreamble\@notprerr
      % We are in the document
      \maketitle
    \else
      % We are in the preamble
      \RequirePackage{etoolbox}
      \AfterEndPreamble{\maketitle}
    \fi
  }

Alternatively, you can roll the LaTeX format forward by loading a current latexrelease.sty file, as noted by David in the comments below the original question and in Joseph's answer, or wait until you no longer need to support TeX Live < 2021.

Related Question