In a document I'm writing I have a nested tabular structure that I want to capture as a macro for reuse. I'd like to define the nesting using a new environment but it doesn't seem to work. I have tried three approaches: using \newenvironment, using \NewEnviron and using a normal macro. The macro works but the environments do not.
Here's a small example showing a simplified version of what I'm doing and the issues I'm running into:
\documentclass{article}
\usepackage{environ}
\newenvironment{testTabA}{%
\multicolumn{3}{l}\begingroup
\begin{tabular}{ll}
}{%
\end{tabular}
\endgroup \\
}
\NewEnviron{testTabB}{%
\multicolumn{3}{l}{%
\begin{tabular}{ll}
\BODY
\end{tabular}
} \\
}
\newcommand\testTabC[1]{%
\multicolumn{3}{l}{%
\begin{tabular}{ll}
#1
\end{tabular}
} \\
}
\begin{document}
% No macros: This works
\begin{tabular}{lll}
1 & 2 & 3 \\
\multicolumn{3}{l}{
\begin{tabular}{ll}
a & b \\
\end{tabular}
} \\
\end{tabular}
% newenvironment: This fails with "Misplaced \omit"
\begin{tabular}{lll}
1 & 2 & 3 \\
\begin{testTabA}
a & b \\
\end{testTabA}
\end{tabular}
% NewEnviron: This fails with "Argument of \testTabB has an extra }"
\begin{tabular}{lll}
1 & 2 & 3 \\
\begin{testTabB}
a & b \\
\end{testTabB}
\end{tabular}
% Macro: This works
\begin{tabular}{lll}
1 & 2 & 3 \\
\testTabC{
a & b \\
}
\end{tabular}
\end{document}
As a fairly new user of TeX, I have no idea what's happening. Can anyone explain why the environment examples are behaving as they are?
\multicolumnshould come first in a cell (after expansion); using it hidden in an environment will never work, because\begindoes assignments and this closes the “window” where\multicolumncan be used. – egreg Jan 06 '14 at 11:42\multicolumn{3}{l}\begingroupthen the 3rd argument to multicolumn is (just)\begingroupand anything that happens after that is accidental artefact of the expansion. – David Carlisle Jan 06 '14 at 11:46{\ifnum0=`}\fisomewhere, would that work? – David Roe Jan 06 '14 at 12:25}\fi is used to "hide" the inner&` but as egreg says the definition of \begin is non-expandable so you are doomed, unless you locally redefine \begin to be expandable. the blkarray pakage allows for block "environments" that essentially hide \multicolumn as you wish but it is massively fragile code that I wouldn't really suggest using, you could always have a look at its source for ideas though:-) – David Carlisle Jan 06 '14 at 12:41\ifnum0construction would cause TeX to look for the end group and pass everything to\multicolumn(or whatever it comes after), rather than just the begin group? – David Roe Jan 06 '14 at 12:56