[Tex/LaTex] verbatim useable with a newenvironment definition

environmentsverbatim

I'm trying to create a simple newenvironment allowing me to display source code in a verbatim text block with a caption, numbering etc. The solution I'm after is with the in-built LaTeX verbatim environment.

I would have used the fancyvrb package, that seems to allow that kind of thing, but I can't update my MiKTeX installation due to proxy authentication issues. Instead I'm after a way to do it with just the built in verbatim environment. When I get home, I can adapt it to use fancyvrb (so I am still interested in answers relating to that), but for now, I'm after a temporary solution to get me through the day. ;^)

Here's what I imagine the newenvironment command would be like:

\usepackage{float}
\floatstyle{boxed}
\newfloat{program}{h}{lop}
\floatname{program}{Example}

\newenvironment{example}[2]{%
    \begin{program}%
    \label{#1}%
    \caption{#2}%
    \scriptsize
    \begin{verbatim}%
}{%
    \end{verbatim}%
    \end{program}%
}

It fails later-on, complaining about overfull \hboxes, which I assume means that it's still trying to typeset the rest of my document as though it were in verbatim mode.

Can I use verbatim env in this way? Got a workaround (given that my MiKTeX package repo is pretty small)?

Best Answer

This works for me.

\documentclass{article}
\usepackage{verbatim}
\usepackage{float}
\floatstyle{boxed}
\newfloat{program}{h}{lop}
\floatname{program}{Example}

\newbox\examplebox
\newenvironment{example}[2]{%
    \program
    \caption{#2}%
    \label{#1}%
    \verbatim
}{%
    \endverbatim
    \vskip-.7\baselineskip
    \endprogram
}
\begin{document}
\begin{example}{foo}{caption}
foo
bar
baz
\end{example}
\end{document}

Note that you need to have the \label after the \caption. The \verbatim macro as reimplemented by the verbatim package seems to be looking for \end{foo} where foo is the name of the current environment. This is why it uses \program, \verbatim, \endverbatim, and \endprogram.

The \vskip isn't necessary, but you end up with extra space without it.

Related Question