[Tex/LaTex] How to wrap floated minted listing in the own environment

environmentsfancyvrblistingsminted

Here's what I'd like to do:

\begin{code}{c}{Hello World in C}% I would prefer the caption to be optional
#include <stdio.h>

int main(void) {
    printf("Hello, world!\n");
    return 0;
}
\end{code}

The result should look like the picture below. (The caption is actually centered on the page but appears so because the image is cropped. Since this is a primitive example, I'm not concerned with prettifying the results.)

code environment example

I am trying to achieve that in my custom class by using minted and the listing environment that it packages:

\newenvironment{code}[2]{%
    \begin{listing}\caption{#2}%
    \begin{minted}{#1}%
}{%
    \end{minted}%
    \end{listing}%
}

I get this error:

Runaway argument?
! File ended while scanning use of \FancyVerbGetLine.
<inserted text> 
                \par 
<*> env.tex

? H
I suspect you have forgotten a `}', causing me
to read past where you wanted me to stop.
I'll try to recover; but if the error is serious,
you'd better type `E' or `X' now and fix your file.

I suppose it has to do with the explanation in this answer, but I'd like to know if it can be done according to the interface shown above.

Best Answer

You have to use the “inner” form of the commands. Rather than listing, I suggest to use the newfloat package:

\documentclass{article}
\usepackage{minted,newfloat}

\DeclareFloatingEnvironment[
  fileext=loc,
  listname=List of codes,
  name=Listing,
  placement=htp,
]{codefloat}

\newenvironment{code}[2][]
 {\codefloat
  \if\relax\detokenize{#1}\relax\else\caption{#1}\fi
  \minted{#2}}
 {\endminted\endcodefloat}

\begin{document}

\begin{code}[Hello World in C]{c}
#include <stdio.h>

int main(void) {
    printf("Hello, world!\n");
    return 0;
}
\end{code}

\end{document}

enter image description here

You may want to have a look at the verbments package:

\documentclass{article}
\usepackage{verbments}

\begin{document}

\begin{pyglist}[language=c,caption=Hello world in C]
#include <stdio.h>

int main(void) {
    printf("Hello, world!\n");
    return 0;
}
\end{pyglist}

\end{document}
Related Question