1

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 at 14:14
  • Yes, it is indeed for this reason – Fosco May 6 at 14:31
  • @siracusa listing is not a verbatim environment. – egreg May 6 at 14:47
1

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.

enter image description here

  • 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 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 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 at 10:15
  • @FoscoLoregian Without an example of the more complex setup where the thing fails, little can be said. – egreg May 7 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.