0

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:

  1. Use float as an option.
  2. 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?

siracusa
  • 13,411
badroit
  • 7,557

1 Answers1

2

After posting the question, I noticed the following related question that happened to involve the same case of wrapping a minipage around a listing environment, where @clemens in a comment provides the following solution:

\documentclass{article}
\usepackage{listings}
\usepackage{mdframed}
\usepackage{float}


\lstset{
    columns=fullflexible
}

\lstnewenvironment{unbreaking}%
{\noindent\minipage{\linewidth}\renewcommand\lstlistingname{Unbreaking}
 \lstset{basicstyle=\ttfamily}}%
{\endminipage}

\begin{document}

\begin{mdframed}
Hi, I'm an MWE.

\begin{unbreaking}
a b c
\end{unbreaking}
\end{mdframed}

\end{document}
badroit
  • 7,557