# Nesting of minted and listing

Can the coupling of minted and listing be wrapped into a new environment?

I'm unable to make this code work:

\documentclass[a4paper]{article}

\usepackage{minted}
\usepackage{xparse}
\NewDocumentEnvironment{captionminted}{ o }
{%
\begin{listing}%
\begin{minted}{cpp}%
}%
{%
\end{minted}%
\IfNoValueTF{#1}{}{\caption{#1}}%
\end{listing}%
}

\begin{document}
\begin{captionminted}[abc]
cout << "This is my message: ";
cout << str << endl;
\end{captionminted}
\end{document}


Because of this error message:

! LaTeX Error: Not in outer par mode.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
...

l.3   i
nt i = 0;

• Define a command that avoids to nest the two environments everywhere, one could simply write the code in captionminted and get the code with an optional caption – fosco May 6 '19 at 14:14
• Yes, it is indeed for this reason – fosco May 6 '19 at 14:31
• @siracusa listing is not a verbatim environment. – egreg May 6 '19 at 14:47

You're forgetting \VerbatimEnvironment. I don't think you gain much with this approach, though: you are rather losing flexibility.

\documentclass[a4paper]{article}

\usepackage{minted}
\usepackage{xparse}

\NewDocumentEnvironment{captionminted}{ o }
{%
\VerbatimEnvironment\begin{listing}%
\begin{minted}{cpp}%
}
{%
\end{minted}%
\IfNoValueF{#1}{\caption{#1}}%
\end{listing}%
}

\begin{document}

\begin{captionminted}[abc]
cout << "This is my message: ";
cout << str << endl;
\end{captionminted}

\end{document}


Don't indent verbatim environments: the spaces at the beginning of the lines are not ignored.

• Your MWE seems to work (thank you!) but unfortunately it doesn't seem to apply to my example. I'll need time to produce a second MWE. The code comes from a (pretty messy) beamer file. – fosco May 6 '19 at 15:05
• @FoscoLoregian One more reason not to try to “optimize”. I don't think that in your beamer file you have so many listings that such optimization adds to efficiency. To the contrary, it reduces flexibility. – egreg May 6 '19 at 15:08
• I agree with you, but this is a request in the specs of a freelance job I'm doing. What else shall I do? :-) hand them a opy of the TeXBook doesn't seem a viable option. – fosco May 7 '19 at 10:15
• @FoscoLoregian Without an example of the more complex setup where the thing fails, little can be said. – egreg May 7 '19 at 10:17