[Tex/LaTex] Stop listings going over page breaks

listingsmarkdownpage-breakingpandoc

I am using Pandoc to generate Tex from Markdown. It automatically generates listings when it comes across the appropriate Markdown (code indented four spaces). It then uses the listings package to instantiate those listings in Tex. The resulting code is:

\begin{lstlisting}[language=bash]
    # java -version
    java version "1.7.0_09-icedtea"
    OpenJDK Runtime Environment (rhel-2.3.3.el6_3.1-i386)
    OpenJDK Client VM (build 23.2-b09, mixed mode)
\end{lstlisting}

Sometimes these code listings extend across a page break and I'd prefer if they were bumped to the next page if this happens. I've looked around and seen a few suggestions about adding a minipage to the listing but since my Tex is being auto-generated via Pandoc it's not clear how I can do that without manually editing the resulting Tex document to add the minipages before and after the lstlistings.

So I am looking for:

  1. A way to bump the listings to the next page automatically, or
  2. A way to tell LaTex to redefine the lstlisting to have minipages before and after it.

EDIT: I should have added for those unfamiliar with Pandoc that the template it uses to generate Tex is here.

Thanks!

Best Answer

As pointed out by Werner the normal way to prevent listings to do any package breaks is the option float. However this can't be done globally without changing the internals of listing.

Another hack would be to surround the environment listings with a non breakable box. This can be achieved with the facilities of the package etoolbox and the provided commands \BeforeEnvironment and \AfterEnvironment:

\BeforeBeginEnvironment{listings}{\par\noindent\begin{minipage}{\linewidth}}
\AfterEndEnvironment{listings}{\end{minipage}\par\addvspace{\topskip}}

Of course instead of minipage you can use any other environment.