I'd like to define a new listings environment where the listing has an \hrule before and after the listing itself. In order to do this I've defined this environment:
\lstnewenvironment{haskell}[1][]
{
\vspace{0.4cm}
\mathligsoff
\hrule
\lstset{language=haskell, basicstyle=\small, #1}
}{
\hrule
\mathligson
\vspace{0.4cm}
}
The problem is that sometimes, when a listing ends up at the bottom of a page, the closing \hrule moves to the next page:

As you can see the highlighted rule ended up at the start of the new page, which is just ugly.
How can I avoid to produce a pagebreak between the listing and the rule at the end? I have already tried to add a \nopagebreak before \hrule but it didn't solve the problem.

tcolorboxto draw the surrounding "box". The general consensus is thattcolorboxhandles that kind of situation better than the native mechanism implemented inlistings. – jub0bs Sep 27 '14 at 12:09