[Tex/LaTex] using fancyvrb Verbatim environment from within newenvironment

fancyvrbverbatim

As with this question, I want to use a verbatim environment from within an environment definition, but I want the listings to be numbered, so I think I need to use fancyvrb. It appears that fancyvrb has no equivalent to \verbatim and \endverbatim. I can't see how to use it within an environment definition. Here's what I have (based on verbatim package):

\newenvironment{example}[2]{%
    \program%
    \caption{#2}%
    \label{#1}%
    \vskip.7\baselineskip
    \scriptsize
    \verbatim%
}{%
    \endverbatim\normalsize
    \vskip-.5\baselineskip
    \endprogram
}

I'd like to use a fancyvrb environment, defined like so:

\DefineVerbatimEnvironment%
{Example}{Verbatim}
{numbers=left,fontsize=\scriptsize, stepnumber=3,
frame=lines,framerule=0.8mm}

to do this:

\newenvironment{example}[2]{%
    \program%
    \caption{#2}%
    \label{#1}%
    \vskip.7\baselineskip
    \scriptsize
    \begin{Example}%
}{%
    \end{Example}\normalsize
    \vskip-.5\baselineskip
    \endprogram
}

I get the following error:

Runaway argument?
  ! File ended while scanning use of \FancyVerbGetLine.

I'm probably doing something silly, but would some patient person point out to me what it is?

Best Answer

the same is possible with the listing environment

\documentclass{article}
\usepackage{fancyvrb,caption,floatrow}
\DeclareNewFloatType{example}{placement=t,%within=section,
   fileext=exa,name=Example}
\captionsetup[example]{font=sf,labelfont=bf,skip=\smallskipamount}

\newenvironment{Example}[2]
{\VerbatimEnvironment
 \captionof{example}{#2}\ifx\relax#1\relax\else\label{#1}\fi%
\begin{Verbatim}[numbers=left,fontsize=\scriptsize, stepnumber=3,
                 frame=lines,framerule=0.4mm]}
{\end{Verbatim}}

\begin{document}

\begin{Example}{TheLabel}{The caption}
foo
bar
\end{Example}

\begin{Example}{}{Another caption}
foo
bar
baz
\end{Example}

See Example~\ref{TheLabel}

\end{document}

enter image description here

Related Question