# How to wrap floated minted listing in my own environment?

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.)

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.

-
Welcome to TeX.SX! –  Andrew Swann Oct 27 '13 at 10:10

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}


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}

-
The verbments package seems to do what I want. Is there any way to alias the pyglist environment to something like code, as in my example? –  ladaghini Oct 27 '13 at 11:56
@ladaghini Just add \newenvironment{code}{\pyglist}{\endpyglist} after \usepackage{verbments} –  egreg Oct 27 '13 at 13:15
@egreg Is it possible to pass options into \pyglist in your example (e.g., change the language type)? I've never seend the \pyglist command before... –  opert May 2 at 21:23
@opert texdoc verbments; you might want to look also at minted or pythontex` –  egreg May 2 at 21:24