[Tex/LaTex] Why does center not center \halign

horizontal alignmenttables

With the following code:

\documentclass[a4paper]{report}
\begin{document}
\begin{center}
\halign{\vrule \hfil # \hfil & \hfil # \hfil \vrule \cr
a & b \cr\noalign{\hrule}
c & d \cr\noalign{\hrule}
}
\end{center}
\end{document}

I'd expect to get the simple table produced with \halign centered in the page. However, it is not, as the picture below shows.

enter image description here

\centering also has no effect. Why does that happen?

Best Answer

One might be tempted of using low level commands also in LaTeX; however there are some subtleties in them that are not easy to grasp at the beginning.

One of these subtleties is that \halign is a vertical command, so when found it causes vertical mode to start; if TeX is in horizontal mode when it scans \halign, it quits it by issuing \par.

This is proved by the following test file (Plain TeX):

a\def\par{PAR\endgraf\let\par\endgraf}bc\halign{#\cr HALIGN\cr}def
\bye

that outputs

enter image description here

The temporary redefinition of \par is aimed at showing that \par is effectively executed.

When TeX is in vertical mode, it simply stacks boxes without making paragraphs; therefore \centering (which is in effect in center) does nothing, because it only influences paragraphs. Thus your \halign will be printed flush with the left margin, since \tabskip is normally zero. The \tabskip glue in force at the moment \halign is scanned is added the left of every box formed by \halign (one box for every alignment row) and between any two alignment cells unless another \tabskip is specified. Read chapter 22 in the TeXbook for more information, but it's not easy.

How can one make \halign part of a paragraph? By hiding it inside something that can and that can also contain it: a \vbox is usually employed (the most common device for centering tables in Plain TeX is to use $$\vbox{\halign{...}}$$; don't try it in LaTeX). While \vbox doesn't by itself start a paragraph, it doesn't interrupt it either, so

\begin{center}
\leavevmode\vbox{\halign{...}}
\end{center}

will center your alignment.

Use tabular; you'll be on the safe side.

Related Question