[Tex/LaTex] prevent page break a couple of lines after figure

floatspage-breaking

I am writing a document which consists of the repeating format: text, figure, then a larger paragraph. How can I prevent a page break between both of the text and figure environments, whilst not removing the ability to automatically break the page within the body of the second text?

\nopagebreak doesn't seem to have any effect after the figure environment. (And I assume confining it to a minipage would not allow page-breaking in this second paragraph.)

I'm fine with white space at the end of a page, but I'd rather each repeating group not necessarily start on a new page.

Best Answer

May be that what the OP is looking for is simply a version of, say, the center environment which prohibits page breaks above and below itself; this is easy to accomplish. For example, the following MWE defines an environment named centernopagebreaks that locally redefines the appropriate parameters and then invokes the center environment.

Note: While testing this example, I’ve noticed that the \captionof command inserts a legal breakpoint between the figure and its caption. I’ve made up for this by wrapping everything up in a minipage environment, but isn’t this a bug?

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{caption}
\usepackage{mwe}

\makeatletter
\newenvironment*{centernopagebreaks}{%
  \@beginparpenalty \@M
  \@endparpenalty   \@M
  \@itempenalty     \@M
  \center
}{\endcenter}
\makeatother

\begin{document}
\lipsum[2]
\begin{centernopagebreaks}
    \begin{minipage}[b]{\textwidth}
        \centering
        \includegraphics{image}
        \par\special{comment: Why no penalty below write and rule?}
        \captionof{figure}{An image}
        \label{fig;img}
    \end{minipage}
\end{centernopagebreaks}
\lipsum[1]

% % If you can read the logging info provided by (core) TeX,
% % uncomment the following lines to check the penalties.
% \showboxbreadth = 1000
% \showboxdepth = 5
% \showlists
\end{document}

I don’t think that it is meaningful to show the output; rather, you should uncomment the diagnostic commands and check that the penalties reported in the transcript file are correct.