One more note: From 2020-10-01 LaTeX provides a new hook mechanism, that also allows to add code at the beginning of an environment. See
lthooks-doc.pdf
in an up-to-date LaTeX installation for more information. Unfortunately it cannot be used to add code to floats, unless you patch such an hook into the code of floats. Here is an example, how this can be used to automatically center figures but not tables:
Code: Select all
\documentclass{article}
\usepackage{mwe}
\usepackage{xpatch}
\NewHook{float/begin}
\makeatletter
\xapptocmd{\@floatboxreset}
{\UseHook{float/begin}}
{\typeout{new hook `float/begin' activated}}
{\errmessage{cannot activate new hook `float/begin'}}
\makeatother
\AddToHook{env/figure/before}{\AddToHook{float/begin}[figure]{\centering}}
\AddToHook{env/figure/after}{\RemoveFromHook{float/begin}[figure]}
\begin{document}
\section{Test}
\begin{figure}
\includegraphics[width=.5\textwidth]{example-image}
\caption{automatic centering of figures}
\end{figure}
\end{document}
BTW: Do not use the hook mechanism to change
tabular
. Also do not redefine
tabular
.
tabular
is a generic environment that is used internally at several places average users would not expect, e.g., to typeset the author(s) using
\maketitle
.