I am trying to create a custom listing environment that will not break over pages and it's a bit of a Chinese finger trap.
The two main options it seems to avoid listings breaking over pages are:
- Use
floatas an option. - Put the listing inside a minipage.
However, option 1 does not work in my case since these listings are often used inside mdframed environments (used as example boxes); when I specify float, it gives a Not in outer par mode error.
Regarding option 2, listings are incompatible with newenvironment so one must use lstnewenvironment, but I have no idea how to wrap a minipage around the listing using the latter definition.
Here's an MWE with my various failed attempts enumerated:
\documentclass{article}
\usepackage{listings}
\usepackage{mdframed}
\usepackage{float}
\lstset{
columns=fullflexible
}
% Works fine but breaks across pages
\lstnewenvironment{unbreaking}%
{\renewcommand\lstlistingname{Unbreaking}
\lstset{basicstyle=\ttfamily}}%
{}
% ERROR: Not in outer par mode
%\lstnewenvironment{unbreaking}%
%{\renewcommand\lstlistingname{Unbreaking}
% \lstset{basicstyle=\ttfamily,float,floatplacement=H}}%
%{}
% ERROR: Emergency stop
%\lstnewenvironment{unbreaking}%
%{\begin{minipage}{5cm}
% \renewcommand\lstlistingname{Unbreaking}%
% \lstset{basicstyle=\ttfamily}}%
%{\end{minipage}}
% ERROR: Not in outer par mode
%\newenvironment{unbreaking}%
%{\begin{lstlisting}[basicstyle=\ttfamily,float,floatplacement=H]}%
%{\end{lstlisting}}
\begin{document}
\begin{mdframed}
Hi, I'm an MWE.
\begin{unbreaking}
a b c
\end{unbreaking}
\end{mdframed}
\end{document}
Help?