Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question
    
Welcome to TeX.SX! –  Andrew Swann Oct 27 '13 at 10:10
add comment

1 Answer

up vote 2 down vote accepted

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}
share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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