[Tex/LaTex] Minted in new environment

environmentsminted

I tried to create a new environment in which I wanted to use minted. Somehow it didn't really work and I found these two posts: 1. 2.

I then copied the code and tried to modify it for my needs. I want to be able to use \begin{code}{label}. This is what I have:

\newenvironment{code}[2]
{\VerbatimEnvironment
\minted@resetoptions
\setkeys{minted@opt}{frame=lines}% from fancyvrb
\renewcommand{\minted@proglang}[1]{#1}
\begin{figure}[htp]%% default placing
    \centering
    \label{#2}
    \begin{VerbatimOut}{\jobname.pyg}}
    {\end{VerbatimOut}
    \minted@pygmentize{\minted@proglang{}}
    \DeleteFile{\jobname.pyg}
\end{figure}}
\makeatother

I get several "FancyVerb" errors and undefined control sequences.

EDIT

Basically I want to define a new environment that produces the following:

\begin{minted}
    [
    frame=lines,
    framesep=2mm,
    linenos,
    label=TestLabel
    ]
    {java}
    while(true){
    //Do stuff
    }
    \end{minted}

by just using \begin{code}{TestLabel}...\end{code}
enter image description here

Best Answer

I think you're overcomplicating things:

\documentclass{article}
\usepackage{minted}
\usepackage{lipsum}

\newenvironment{code}[4][htp]
 {\VerbatimEnvironment
  \begin{figure}[#1]
  \centering
  \caption{#3}\label{#4}
  \begin{minted}[frame=lines]{#2}}
 {\end{minted}\end{figure}}

\begin{document}

\lipsum[1]

\begin{code}{latex}{A caption}{label1}
Test of \LaTeX code
\end{code}

\lipsum[2]

\begin{code}[bp]{latex}{A caption}{label2}
Test of \LaTeX code
\end{code}

\lipsum

\end{document}

enter image description here

Another version, where the argument refers to label=; I also changed figure into the more proper listing environment.

\documentclass{article}
\usepackage{minted}
\usepackage{lipsum}

\newenvironment{code}[2][htp]
 {\VerbatimEnvironment
  \begin{listing}[#1]
  \centering
  \begin{minted}[frame=lines,framesep=2mm,linenos,label=#2]{java}}
 {\end{minted}\end{listing}}

\begin{document}

\lipsum[1]

\begin{code}{Code 1}
while(true){
    //Do stuff
}
\end{code}

\lipsum[2]

\begin{code}[bp]{Code 2}
while(true){
    //Do stuff
}
\end{code}

\lipsum

\end{document}

enter image description here

Related Question