# Using longtable inside xparse \NewDocumentEnvironment

I am trying to create a wrapper for the longtable environment and it works fine with the standard \newenvironment command. Now I want to use \NewDocumentEnvironment from the xparse package to allow more optional arguments. But the result looks different, there appears an additional cell below the table. Maybe it's caused by a linebreak from the \NewDocumentEnvironment command because the error doesn't appear when I move the \end{longtable} from the end-code-block to the start-code-block of the environment definition (like I did in the example in myxparsetable2 environment).

I created a minimal example. The error appears with myxparsetable1.

\documentclass{scrartcl}
\usepackage{xparse}
\usepackage{longtable}

\NewDocumentEnvironment{myxparsetable1}{m}
{\begin{longtable}{#1}}
{\end{longtable}}

\NewDocumentEnvironment{myxparsetable2}{}
{%
\begin{longtable}{|c|c|c|} \hline%
col1 & col2 & col3 \\ \hline%
\end{longtable}%
}
{}

\newenvironment{mytable}[1]
{\begin{longtable}{#1}}
{\end{longtable}}

\begin{document}

Normal longtable:
\begin{longtable}{|c|c|c|} \hline
col1 & col2 & col3 \\ \hline
\end{longtable}

Custom mytable
\begin{mytable}{|c|c|c|} \hline
col1 & col2 & col3 \\ \hline
\end{mytable}

Custom myxparsetable1
\begin{myxparsetable1}{|c|c|c|} \hline
col1 & col2 & col3 \\ \hline
\end{myxparsetable1}

Custom myxparsetable2
\begin{myxparsetable2}
\end{myxparsetable2}

\end{document}


And here is the output:

• It's a known problem: with \NewDocumentEnvironment{foo}, the macro \endfoo, that's internally used by LaTeX when \end{foo} is found, is \protected, so LaTeX starts a new row before realizing that the table should end. For the time being, use \newenvironment for environments involving tables. – egreg Jul 15 '14 at 14:13
• Thanks for your fast and good answer. Do you know a way to use more than one optional argument with \newenvironment? Thanks Martin – Martin Jul 15 '14 at 14:15
• I forgot to say “Welcome to TeX.SX”! – egreg Jul 15 '14 at 14:28

It's a known problem: with \NewDocumentEnvironment{foo}, the macro \endfoo, that's internally used by LaTeX when \end{foo} is processed is “protected” and, because of this, LaTeX can't see that the alignment is to be ended until it has already started a new row.

The situation is mostly similar to having \multicolumn not as the first item in a cell.

What can I offer, if you want to scan multiple arguments for \begin{foo}, a kludge:

\newenvironment{myxparsetable}{}{\end{longtable}}
\RenewDocumentCommand{\myxparsetable}{mO{}o}{%
...something with #2 and #3...
\begin{longtable}{#1}
}

• That works fine for me! Thank you very much for your help. – Martin Jul 15 '14 at 14:49