[Tex/LaTex] LaTeX not recognizing \end found in a \newcommand

macrostablestabu

I'm trying to both start and end a table with \newcommand. I'd like to switch to using \EndTableSetupFourColumns (as it removes several warnings and is easier to understand for other readers) but for some reason LaTeX does not seem to recognize the \end{tabu} found within, so I have to insert it manually as seen below.

This problem seems to be limited to tabu – when I was using tabulars I did not have this issue. I looked through the tabu documentation and could not find anything that would indicate this wouldn't work.

Looking at \end{tabu} in \newcommand shows that it won't work, however, it is something I'd like to work around for code readability, if nothing else.

MWE:

\documentclass{article}

\usepackage[table]{xcolor}
\usepackage{longtable,tabu}

\newcommand{\TableSetupFourColumns}{%
\rowcolors{2}{gray!25}{white}
\begin{tabu} to \textwidth {lccX}
    \rowcolor{gray!50}}

\newcommand{\EndTableSetupFourColumns}{%
\end{tabu}}

\begin{document}

\section{Test 1}
This is text.\par \noindent
\TableSetupFourColumns
    Test            & test  & test  & test\\
\end{tabu}
%\EndTableSetupFourColumns

\end{document}

Best Answer

tabu needs to "see" \end{tabu}; it cannot be hidden in a macro. You're better served by defining a new environment:

\documentclass{article}

\usepackage[table]{xcolor}
\usepackage{longtable,tabu}

\newenvironment{tabu4}
  {\rowcolors{2}{gray!25}{white}
   \begin{tabu} to \textwidth {lccX}
   \rowcolor{gray!50}}
  {\end{tabu}}

\begin{document}

\section{Test 1}
This is text.

\medskip

\noindent
\begin{tabu4}
    Test            & test  & test  & test\\
    Test            & test  & test  & test\\
    Test            & test  & test  & test\\
    Test            & test  & test  & test\\
    Test            & test  & test  & test\\
    Test            & test  & test  & test\\
\end{tabu4}

\end{document}

enter image description here

Related Question