# Defining a new environment that contains tabularx inside another environment (e.g., center)

I'm trying to define a new environment that encloses a tabularx environment within some other environment to provide some formatting (such as center to centre the whole thing). The following was my attempt, but it generates the familiar ! File ended while scanning use of \TX@get@body error. However, I am already using the \tabularx command in my definition, which is usually the fix for this error.

The following is my 'MWE' attempt that is broken:

\documentclass{article}
\usepackage{tabularx}
\newenvironment{CT}{%
\begin{center}\tabularx{200pt}{XX}}{%
\endtabularx\end{center}}
\begin{document}
\begin{CT}
One & Two
\end{CT}
\end{document}


If I delete the \begin{center} and \end{center} then it runs, while the following is perfectly ok:

\documentclass{article}
\usepackage{tabularx}
\begin{document}
\begin{center}
\begin{tabularx}{200pt}{XX}
One & Two
\end{tabularx}
\end{center}
\end{document}


I guess the issue is some subtlety about how \tabularx behaves within \newenvironment and how it goes looking for the matching \endtabularx.

• Use \center and \endcenter – egreg Dec 1 '20 at 8:48
• Thanks. That works. (I'm not used to using those alternatives to the center environment.) – Martyn Quick Dec 1 '20 at 8:49

The first thing that \tabularx does is

\edef\TX@{\@currenvir}%


i.e. it saves the current environment name under the name \TX@; then the target width is set, and then it goes on grabbing the tokens which make the tabular. I won't post the code here but the crucial issue is that the scanning mechanism basically keeps collecting tokens until it finds \end{current_environment}. With your code

\newenvironment{CT}
{%
\begin{center}%
\tabularx{200pt}{XX}
}
{%
\endtabularx
\end{center}%
}


the expansion of \begin{CT} results at some point in \begin{center}, which sets \@currenvir to center. Then \tabularx starts, sets \TX@ to center, and collects tokens (without expanding them) until it finds \end{center}. However, your code does not contain \end{center} but rather \end{CT}. The collecting mechanism has no idea that the \end{center} is hidden in \end{CT}, so it keeps collecting stuff until it reaches the end of file.

The solution, as egreg already mentioned in a comment, is to use \center and \endcenter

\newenvironment{CT}
{%
\center
\tabularx{200pt}{XX}
}
{%
\endtabularx
\endcenter
}