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}

2 Answers 2

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.

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}
2
  • Can you expand on why \AtEndEnvironment works? At first glance, this seems very hackish. But, if it works is works. Jun 20, 2019 at 3: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, 2020 at 17:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .