[comp.text.tex] A "code" environment with caption.

mathas_a@maths.su.oz.au ( Andrew ) (06/11/90)

Here is a solution. It doesn't call the caption "Code
Fragment 1" as you wanted. I tried redefining the figure
counter as follows
    \def\thefigure{Code fragment \arabic{figure}.}
but this gives "Figure Code Fragment 1" which isn't nice.
Notice what the main problem is here: you have to end
your code fragment with a \end{verbatim} and an \end{code}
because verbatim only stops when it finds an \end{verbatim}.
Unless you really want to use a figure environment, I'd go 
for something like solution 2 because tables and figures 
(where the \caption has to live) have a nasty habit of 
floating to the wrong part of a page.

Solution 1:

\documentstyle[12pt]{report}

\newenvironment{code}[1]%
    {\def\CAPTION{#1}\begin{figure}[h]\begin{verbatim}}%
    {\caption{\CAPTION}\end{figure}}


\begin{document}
   Some innocent innocuous pieces of tex
   blaah    

   \begin{code}{A lovely caption}
    Some code ##!&^%&*^%!()*&!

    09840938234#$!%$#!
   \end{verbatim}\end{code}

   More innocent text.

\end{document}                       


Solution 2:
\documentstyle[12pt]{report}

\newcounter{Code}

\newenvironment{code}[1]%
    {\def\CAPTION{#1}\begin{verbatim}}%
    {\addtocounter{Code}{1}%
     \centerline{Code fragment \theCode.\qquad\CAPTION}}


\begin{document}
   Some innocent innocuous pieces of tex
   blaah    

   \begin{code}{A lovely caption}
    Some code ##!&^%&*^%!()*&!

    09840938234#$!%$#!
   \end{verbatim}\end{code}

   More innocent text.

\end{document}                       


Have fun!

    Andrew                  - smile at a stranger today and help make
                              the world a better place. while you're,
                                 at it, why not also hug a friend!

spqr@ecs.soton.ac.uk (Sebastian Rahtz) (06/13/90)

In article <1990Jun11.145827.26313@metro.ucc.su.OZ.AU> mathas_a@maths.su.oz.au ( Andrew ) writes:

   Notice what the main problem is here: you have to end
   your code fragment with a \end{verbatim} and an \end{code}
   because verbatim only stops when it finds an \end{verbatim}.
people who spend lots of time hacking at enhancements of LaTeX's
verbatim environment would probably be interested in  Rainer Schoepf's
rewrite of the whole thing, which *does* permit its inclusion in new
environments. I think Don Hosek has the package at Claremont; it is
certainly part of the UK TeX Archive. 

Sebastian Rahtz

--
Sebastian Rahtz                        S.Rahtz@uk.ac.soton.ecs (JANET)
Computer Science                       S.Rahtz@ecs.soton.ac.uk (Bitnet)
Southampton S09 5NH, UK                S.Rahtz@sot-ecs.uucp    (uucp)