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 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.
share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
I actually need that minipage... But the rest works like a charm. Thank you –  Tomas Dec 5 '12 at 18:47

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.