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.

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

share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

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.

share|improve this answer
    
thanks. works perfectly. –  Andrew Matthews Jan 7 '11 at 3:54
    
Could somebody tell me what this line does? \newbox\examplebox and where are these commands defined? –  Matthias Nov 21 '11 at 15:00
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.