# How to renew \chapter command to include endnotes (i.e., \printnotes)

I'm using the pagenote package to put my endnotes at the end of every chapter. For example, see the accepted answer for this question: How does one get endnotes at the end of every chapter?

In short:

\chapter{First Chapter}
some text
\printnotes*


How can I renew the \chapter command so that I don't have to include \printnotes* at the end of every chapter?

I don't want to make the \printnotes* command happen before the \chapter command because then I'll get notes before the first chapter (which doesn't make sense).

-
LaTeX doesn't know when a chapter ends, but only when a new one starts, which is not exactly the same thing, as you discovered. –  egreg Nov 22 '12 at 15:55
@egreg That is what I'm trying to avoid. If I have to manually enter the \printnotes command at the end of every chapter, I know I'll forget it somewhere. –  Jeremy Nov 22 '12 at 16:51
What if a chapter has no endnotes? What about the final chapter? What about a bibliography added with biblatex which emits \chapter*? And so on. I don't think that your book has so many chapters that checking for \printnotes* at their end is overwhelming. :) –  egreg Nov 22 '12 at 16:54
@egreg You have a point there. I may have to reconsider what I want to do. –  Jeremy Nov 22 '12 at 17:00

Here is a solution using the \pretocmd provided by the etoolbox package.

\documentclass{book}
\usepackage{etoolbox}
\usepackage{pagenote}
\makepagenote
\begin{document}

\chapter{Chap 1}

\pretocmd{\chapter}{\printnotes*}{}{}

\chapter{Chap 2}
\chapter{Chap 3}
\chapter{Chap 4}
\printnotes*

\end{document}


As you can see the command may be used after the initial \chapter.

Edit #1

As I've made the correction on the code above, another \printnotes* command is required at the end of the final chapter.

Edit #2

It might feel more convenient to automate the process in the preamble itself with the help of logic.

\documentclass{book}

\usepackage{etoolbox}
\usepackage{pagenote}
\makepagenote

\renewcommand*{\notedivision}{\section*{\notesname\ to chapter~\thechapter}}

\pretocmd{\chapter}{%
\ifnum\value{chapter}>0\relax\printnotes*\fi%
}{}{}
%\pretocmd{\backmatter}{\printnotes*}{}{}
\AtEndDocument{\printnotes*}

\begin{document}

\chapter{Chap 1}
\chapter{Chap 2}
\chapter{Chap 3}

\end{document}


In the presence of backmatter the line \pretocmd{\backmatter}{\printnotes*}{}{} can be uncommented while \AtEndDocument may be omitted.

-
\AtEndDocument is probably wrong if the book has some backmatter material. –  egreg Nov 22 '12 at 17:03
It's actually meant to be commented out if \backmatter been used. Maybe its not very clear in the code. –  mkota Nov 22 '12 at 17:05
I'd use \ifnum\value{chapter}>0\relax\printnotes*\fi as \thechapter may be not (completely) numerical. –  Qrrbrbirlbel Nov 22 '12 at 17:13
@Qrrbrbirlbel Thanks! Changed. –  mkota Nov 22 '12 at 17:17