# command in {after} section of environment behaving oddly

In its simplest form, I'm trying to do an environment which wraps the filecontents environment, and does some stuff after the file is written.

\usepackage[autocompile]{gregoriotex}
\newenvironment{chant}{
\filecontents[overwrite]{chant.gabc}
}{
\endfilecontents
\gregorioscore{chant}
}


Usage looks like this:

\begin{document}
\begin{greg}
(c3)V. Ju(h)be(h) dom(h)ne(g_') be(h)ne(h)dí(h)ce(d)re.(d.) (::)
\end{greg}
\end{document}


Everything works fine, up to a point.

• The chant.gabc gets written.
• Gregorio parses the gabc file and writes chant-5_2_1.gtex.

But then when the PDF is generated, a literal line shows up in the PDF output file saying:

\input chant-5_2_1.gtex\relax


This is obviously just writing a command sequence as a literal string. This should be the command to insert the chant score. If I put the same \gregorioscore{chant} outside of the environment definition, it writes the chant score correctly.

So what am I doing wrong in the {after} section, that is causing it to write the command sequence as a literal string, instead of interpreting it, and is there a way to get it to print the actual chant score correctly?

filecontents changes catcodes and this changes are still active as you don't have a group.

\documentclass{article}
\usepackage[autocompile]{gregoriotex}
\newenvironment{chant}{
\begingroup
\filecontents[overwrite]{chant.gabc}
}{
\endfilecontents
\endgroup
\gregorioscore{chant}
}
\begin{document}
\begin{chant}
(c3)V. Ju(h)be(h) dom(h)ne(g_') be(h)ne(h)dí(h)ce(d)re.(d.) (::)
\end{chant}
\end{document}