4

I'm using the following syntax for my code snippets

\begin{minipage}{\textwidth}
\begin{lstlisting}[caption=<something>, label=<something>]
The REST Endpoint URL 
   is http://api.flickr.com/services/rest/

To request the flickr.test.echo service, 
   invoke like this:
   http://api.flickr.com/services/rest/
      ?method=flickr.test.echo&name=value

By default, REST requests will send a REST response.
\end{lstlisting}
\end{minipage}

and I would like to have

\begin{code}[<caption>, <label>]
... code ...
\end{code}

which would behave exactly the same.

So I tried this thing but it won't compile and I can't spot the problem

\newenvironment{code}[2][]%
    {
        \minipage{\textwidth} 
        \lstset{
            basicstyle=\ttfamily,
            breaklines=true,
            captionpos=b,
            frame=bottomline,
            extendedchars=true
        }
        \begin{lstlisting}[caption=#1, label=#2]
    }
    {
        \end{lstlisting}
        \endminipage
    }

Error when running pdflatex

! Package inputenc Error: Unicode char \u8:�\expandafter not set up for use with LaTeX.

See the inputenc package documentation for explanation.
Type  H <return>  for immediate help.
5

You need to use \lstnewenvironment, provided by listings specifically for this purpose (see the listings documentation; section 4.16 Environments, p 40):

enter image description here

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\lstnewenvironment{code}[2][]%
  {%
    %\minipage{\textwidth} 
    \lstset{
      basicstyle=\ttfamily,
      breaklines=true,
      captionpos=b,
      frame=bottomline,
      extendedchars=true,
      caption=#1,
      label=#2
    }
  }
  {
    %\endminipage
  }
\begin{document}
\begin{code}[My code]{mycode}
  Here is some code
\end{code}

Here is some text. Also see Listing~\ref{morecode}.

\begin{code}[More code]{morecode}
  Here is some more code
\end{code}
\end{document}

No need for using a minipage of width \textwidth, unless you want to avoid breaking across pages.

  • I actually need that minipage... But the rest works like a charm. Thank you – user219882 Dec 5 '12 at 18:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.