Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

(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}
share|improve this question

2 Answers 2

up vote 9 down vote accepted

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.

share|improve this answer

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}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.