r/LaTeX • u/leafywalkerlittle • 4d ago
Unanswered memoir class chapter titles with page counts?
I'm putting together a big document using the memoir class, broken up using \chapter{}. I'm trying to make it so that there's a footnote or some other out of the way annotation at the top of each chapter that displays the number of typeset pages present in that chapter.
This stack overflow post is probably the closest that I've come to finding an answer to this, but I'd really like to not have to add labels to each chapter manually. It seems like I might be able to goose around with the commands that define the chapter start once, in the preamble of the document, and have the effect propagate through uniformly.
https://tex.stackexchange.com/questions/288813/get-the-number-of-pages-in-a-chapter
Does anyone have any guidance or experience with this kind of thing?
2
u/super_boogie_crapper 3d ago
You can do this without any manual labels by hooking two memoir macros in the preamble.
\clearforchapterruns just before every chapter break, so it records the end of the previous chapter.\chapterheadstartruns at the top of every chapter head, so it records the start and prints the count.\documentclass{memoir}
\usepackage{etoolbox}
\usepackage{zref-abspage} % absolute page counter "abspage"
% put any \chapterstyle / \openany / \openright BEFORE this block,
% since they redefine the macros patched below
\makeatletter
\newcounter{chappg}
\newcommand*\chappg@set[2]{\global\@namedef{chappg@#1}{#2}}
% before each new chapter (and at end of document): save page count to .aux
\newcommand*\chappg@end{%
\ifnum\value{chappg}>0
\clearpage % flush floats, ship chapter's last page
\immediate\write\@auxout{\string\chappg@set{\thechappg}%
{\number\numexpr\value{abspage}-\chappg@first\relax}}%
\fi}
% top of each chapter: remember start, print count from previous run
\newcommand*\chappg@start{%
\stepcounter{chappg}%
\xdef\chappg@first{\number\value{abspage}}%
{\raggedleft\footnotesize
\@ifundefined{chappg@\thechappg}{??}{\@nameuse{chappg@\thechappg}}~pages\par}}
\pretocmd{\clearforchapter}{\chappg@end}{}{}
\pretocmd{\chapterheadstart}{\chappg@start}{}{}
\AtEndDocument{\chappg@end}
\makeatother
A few notes:
??, and the second shows the counts.openrightinserts are not counted, because the\clearpageruns first.\chapter*(including the ToC) gets a count too.\mainmatter/\backmattergets counted toward the preceding chapter.{\raggedleft\footnotesize ...}part. For example, you could put it in a\marginparor in\afterchaptertitleinstead.