14

(I know there are already other questions about centering tables such as this. This question is specific to etoolbox.)

How do I center all tables using etoolbox? I can do

\documentclass[11pt]{article}
\makeatletter
\g@addto@macro{\table}{\centering}
\makeatother

\begin{document}
\begin{table}
\begin{tabular}{lr}
    cat & 123 \\
\end{tabular}
\end{table}
\end{document}

and this works. But why not the following with etoolbox?

\documentclass[11pt]{article}
\usepackage{etoolbox}
\AtBeginEnvironment{table}{\centering}

\begin{document}

\begin{table}
\begin{tabular}{lr}
    cat & 123 \\
\end{tabular}
\end{table}

\end{document}
David Carlisle
  • 757,742
ceiling cat
  • 2,167

2 Answers2

13

Let's see how table is defined in article.cls:

\newenvironment{table}
  {\@float{table}}
  {\end@float}

What's the difference in your two methods? The first is equivalent to having defined

\newenvironment{table}
  {\@float{table}\centering}
  {\end@float}

while the second is mostly equivalent to

\newenvironment{table}
  {\centering\@float{table}}
  {\end@float}

Here's where things go wrong: among the duties of \@float there is calling \@xfloat, which in turn does \@parboxrestore. This command sets LaTeX in a "predictable state" when starting a \parbox or a minipage; in particular it issues commands that set up text justification.

A possible place where acting more sensibly is the last macro called by \@xfloat, that is, \@floatboxreset:

\def\@floatboxreset{%
  \reset@font
  \normalsize
  \@setminipage}

If you say

\addto\@floatboxreset{\centering}

all of your floats will be centered. If you want only tables and not figures, then

\addto\table{\centering}

is good.

Note. Before using \g@addto@macro or \addto, make yourself certain that the macro you want to modify has no argument; for macros with arguments, use \addtocmd (or the similar commands). Better yet, use the facilities provided by xpatch that act on the "correct" command.

egreg
  • 1,121,712
5

You may be surprised, but \AtEndEnvironment{table}{\centering} works and centers all tables - as long as they don't contain paragraph breaks, but you don't need them commonly for working with tabular & Co.

\documentclass[11pt]{article}
\usepackage{etoolbox}
\AtEndEnvironment{table}{\centering}

\begin{document}

\begin{table}
\begin{tabular}{lr}
    cat & 123 \\
\end{tabular}
\end{table}

\end{document}
David Carlisle
  • 757,742
Stefan Kottwitz
  • 231,401
  • Can you expand on why \AtEndEnvironment works? At first glance, this seems very hackish. But, if it works is works. – Keith Prussing Jun 20 '19 at 03:23
  • This didn't work for me in a more complex project, so beware it's fragility. \AtEndEnvironment{table} {\centering\addvspace{\myGlue}} % not centered – Merchako Apr 29 '20 at 17:08