# Chapters that openleft unless the chapter is only one page long

I'm using the memoir class, and would like new chapters to begin on the left-hand page, unless the chapters in question are only one page long. Neither openleft nor openany give this behavior. I am not opposed to using another class, or using sections instead of chapters, if I can get this behavior by doing so.

-

The implementation of this behaviour needs to know the length of a chapter. Then it can put references at the begin and end of the chapter and can calculate the number of pages.

Class memoir (or the standard LaTeX classes) use \chapter to mark up the start of a chapter. However there is no markup that ends a chapter. Therefore the end of a chapter must be guessed. For example, a chapter ends at:

• the next \chapter,
• the next \part,
• the end of document.

The solution uses an absolute page number and absolute chapter numbers to avoid trouble with non-unique page and chapter numbers (starred chapters, …). I am using package zref for the references, because it offers more control, what is written (only the absolute page number is needed as reference data) and how it is written. Deferred writing does not work after the last page is output, therefore the immediate wrapper of zref is used. Deferred writing at the next shipout (see \label) is not necessary, because we know the page number being at the begin of the page.

\documentclass{memoir}

\usepackage{zref-abspage}
\usepackage{atveryend}

\makeatletter
% Because of starred chapters we need an extra chapter counter
% for identifying a chapter. \thechapter is not unique in general.
\newcounter{abschap}
\renewcommand*{\theabschap}[1]{abschap.\the\value{abschap}.#1}

\renewcommand*{\clearforchapter}{%
\EndChapter
\stepcounter{abschap}%
\zref@refused{\theabschap{beg}}%
\zref@refused{\theabschap{end}}%
\def\ClearChapter{\cleartoverso}%
\zref@ifrefundefined{\theabschap{beg}}{%
}{%
\zref@ifrefundefined{\theabschap{end}}{%
}{%
\ifnum\numexpr
\zref@extract{\theabschap{end}}{abspage}%
-\zref@extract{\theabschap{beg}}{abspage}%
= 1 %
\let\ClearChapter\@empty
\fi
}%
}%
\ClearChapter
\zref@wrapper@immediate{%
\zref@labelbyprops{\theabschap{beg}}{abspage}%
}%
}
\newcommand*{\EndChapter}{%
% flush floats
\clearpage
% Set an anchor after the last page with contents of the current
% chapter.
\zref@wrapper@immediate{%
\@ifundefined{\theabschap{end}}{%
\zref@labelbyprops{\theabschap{end}}{abspage}%
\global\expandafter\let\csname\theabschap{end}\endcsname\@empty
}{}%
}%
}
\AfterLastShipout{\EndChapter}
\newcommand*{\org@part}{}
\let\org@part\part
\renewcommand*{\part}{%
\EndChapter
\org@part
}
\makeatother

\begin{document}
Title\newpage
\tableofcontents
\chapter{A}
Short.
\chapter{B}
Long\newpage
Page B.2
\chapter{C}
Short.
\chapter{D}
Long\newpage
Page D.2\newpage
Page D.3
\chapter{E}
Short.
\end{document}

-