# Creating a custom environment

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.

-

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

\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 –  Tomas Dec 5 '12 at 18:47