[Tex/LaTex] How to prevent lstlisting from splitting code between pages


Is it possible to prevent lstlisting from splitting a code between pages if it does not fit on one page? Instead splitting I would like to have the code on the next page.

I tried to put all lstlisting inside \begin{figure}[h!]...\end{figure} but the order of code and header is lost.

Best Answer

Define your own listing environment which doesn't allow page breaks




\lipsum[1-4] % some dummy text to get to the bottom of the page

\begin{code}[caption={This is my code. There are many like it, but this one is mine.},
def jacobian(function, variablelist):
    Calculates symbolically the Jacobian of the vector with respect to 
    the provided variables. Returns a square matrix

    for i in range(n):
        for k in range(n):
    return J

def vector(*arglist):
    A shorthand for defining a symbolic column vector. Arguments are 
    supplied as a normal comma-separated list.
    return np.asmatrix(np.array(arglist), dtype=sy.Symbol).transpose()


or use the float option from the package (see documentation)

Related Question