[Tex/LaTex] Create environment inside another environment

environmentstablestabularx

Why can't I define an environment, that encloses another tabularx environment inside it?

For example, why can't I do this:

\newenvironment{customTabular}{
    % This is the begin code
    \begin{tabularx}{\linewidth}{l l X}
}
{
    % This is the end code
    \end{customTabular}
}

and then use it like:

\begin{customTabular}
        Blah & Blah & Blah\\
\end{customeTabular}

Best Answer

The tabular extensions are all based on hacking TeX's alignment system which requires some expansion intricacies (that's as much as I understand about it). One trick which sometimes works is to use the control sequences one level below the LaTeX abstraction. This works:

\documentclass{article}
\usepackage{tabularx}
\newenvironment{customTabular}{
    % This is the begin code
    \begingroup
    \tabularx{\linewidth}{l l X}
}
{
    % This is the end code
    \endtabularx
    \endgroup
}
\begin{document}
\begin{customTabular}
        Blah & Blah & Blah\\
\end{customTabular}
\end{document}

Edit: The \begingroup...\endgroup are in there because \begin{tabularx} begins a group then expands \tabularx. But since \begin{customTabular} begins its own group you don't need it for this simple case. I suppose if you wanted to have extra code after \endtabular that would not be affected by the contents of the environment you would need it.

Related Question