The issue is that \NewDocumentEnvironment
has an argument more than \NewDocumentCommand
, that argument defines what should be done in the \end
part of said environment. So the syntax is:
xxxxxxxxxx
\NewDocumentEnvironment {<name>} {<args>}
{<begin>}
{<end>}
(this is analogue to \newenvironment
, that also allows you to define the action in \begin
and \end
).
Now when you call your environment fooenv
it’ll do the \NewDocumentEnvironment{barenv}
definition, and that one will grab an argument more than you provide (in your example that argument is H
). Now the environments do what you tell them to, and on \end{barenv}
the H
is reinserted (as that’s the definition for the \end
-part now).
Please note that I’d say using \NewDocumentEnvironment
to define a nested environment seems wrong. What I’d do is define it globally, but also define a toggle that’ll throw an error if you don’t use it nested in fooenv
.
Consider the following example: