# Headers and footers for listing environment?

What I need to be able to do is apply a header and footer when I use the listings environment. I have a few requirements:

• The header and footer should be outside the listing itself, i.e. they are not part of the listing content.
• The amount of space between the header and the listing should be the same as the amount of space between the footer and the listing.
• The amount of space between the listing and the header/footer should not be rubber, i.e. TeX should not be able adjust the header/footer closer to or farther from the listing.
• The header and footer may not be the same for every listing.
• Page breaks should not be possible between the header/footer and the listing.
• Page breaks should be possible within the listing itself.

As far as I can tell I can get most of the way there if use minipage:

\usepackage{listings}

\lstnewenvironment{code}[2][]{
\lstset{language=c++,aboveskip=12pt,belowskip=12pt,#1}
\begin{minipage}[c]{\linewidth}
} {
\end{minipage}
\begin{flushright}
\end{flushright}
}

std::cout << "Hello, World!" << std::endl;
\end{code}


The problem is that minipage doesn't allow page breaks, so the listing cannot span multiple pages. Other solutions I've tried (i.e. a combination of \nopagebreak[4] and \vspace, and \raggedbottom) fail to either (a) prevent page breaks between the header/footer and the listing, or (b) prevent TeX from adjusting the space between the header/footer and the listing. Floats are not an option.

Any ideas about how I can satisfy all of the requirement above?

## migrated from stackoverflow.comJul 11 '12 at 17:43

This question came from our site for professional and enthusiast programmers.

The only package I knew doing things you want is package longtable. It has special headers and footers for tables spanning over more than one page.
The package listings has no headers and footers defined you want, so one way to solve your problem would be to study the code for headers and footers in longtable and change package listings and include there the code for similar header and footers.
Both packages are tricky one so I guess only the maintainer of the packages can help you. Perhaps you ask the maintainer of listings to add such a functionality?