# Why does docsvlist not work in an environment?

In an experiment to postprocess a table I encountered a discrepancy concerning docsvlist. The same code works (shows a table with a b...) when called directly in the document, but not (shows a table with Γ Γ...) when it is embedded in the enddef of an environment.

I hardly dare to ask whether this is a bug, as TeX has so many surprises for the uninitiated. So, what should I do to make it work inside the enddef.

\documentclass[12pt]{article}
\usepackage{expl3,xparse,ifthen,etoolbox}
\newcounter{Nr}

\NewDocumentEnvironment{Test}{s O{t}}{%
}{%
\setcounter{Nr}{0}
\renewcommand*{\do}[1]{%
\ifnumequal{\value{Nr}}{2}{\\\setcounter{Nr}{0}}{}%
\stepcounter{Nr}%
#1
\ifnumequal{\value{Nr}}{2}{}{&}%
}%
\begin{tabular}{cc}%
\docsvlist{a,b,c,d,e,f,}
\end{tabular}%
}%

\begin{document}
%
\begin{Test}
\end{Test}
\hspace{1cm}
\setcounter{Nr}{0}
\renewcommand*{\do}[1]{%
\ifnumequal{\value{Nr}}{2}{\\\setcounter{Nr}{0}}{}%
\stepcounter{Nr}%
#1%
\ifnumequal{\value{Nr}}{2}{}{&}%
}%
\begin{tabular}{cc}%
\docsvlist{a,b,c,d,e,f,}%
\end{tabular}%
%
\end{document}


It does work in the environment, but you have to use ##1, i.e. the argument of \do, and not #1, which is the 1st argument of the test enviroment, meaning the starred one here, which will 'always' print as Γ then.

Defining commands within other macros needs a doubling of the # character for accessing the 'local' argument, i.e. ##1, ##2 etc. If this inner macro has further macro definitions, ##1 becomes ####1 etc. for the innermost macro.

\documentclass[12pt]{article}
\usepackage{xparse,ifthen,etoolbox}
\newcounter{Nr}

\NewDocumentEnvironment{Test}{s O{t}}{%
}{%
\setcounter{Nr}{0}
\renewcommand*{\do}[1]{%
\ifnumequal{\value{Nr}}{2}{\\\setcounter{Nr}{0}}{}%
\stepcounter{Nr}%
##1%
\ifnumequal{\value{Nr}}{2}{}{&}%
}%
\begin{tabular}{cc}%
\docsvlist{a,b,c,d,e,f,}
\end{tabular}%
}%

\begin{document}
%
\begin{Test}
\end{Test}
\hspace{1cm}
\setcounter{Nr}{0}
\renewcommand*{\do}[1]{%
\ifnumequal{\value{Nr}}{2}{\\\setcounter{Nr}{0}}{}%
\stepcounter{Nr}%
#1%
\ifnumequal{\value{Nr}}{2}{}{&}%
}%
\begin{tabular}{cc}%
\docsvlist{a,b,c,d,e,f,}%
\end{tabular}%
%
\end{document}


Shorter version without ifthen package

\documentclass[12pt]{article}
\usepackage{xparse,etoolbox}
\newcounter{Nr}

\NewDocumentEnvironment{Test}{s O{t}}{%
}{%
\setcounter{Nr}{0}%
\renewcommand*{\do}[1]{%
\ifnum2=\value{Nr}\relax%
\\\setcounter{Nr}{0}%
\fi
\stepcounter{Nr}%
##1%
\ifnum2=\value{Nr}\relax%
\else \unexpanded{&} \fi
}%
\begin{tabular}{cc}%
\docsvlist{a,b,c,d,e,f,}
\end{tabular}%
}%

\begin{document}
%
\begin{Test}
\end{Test}
\end{document}

• @Jack: You're welcome. Happy TeXing – user31729 Feb 24 '18 at 0:06