# Chapter count not increasing

Consider the following MWE:

\documentclass[12pt,twoside,letterpaper]{report}

\usepackage{etoolbox}

\newcounter{totchapters}

\providecommand\totchap{}

\makeatletter
\AtEndDocument{%
\immediate\write\@mainaux{%
\string\gdef\string\totchap{\number\value{totchapters}}%
}%
}
\makeatother

\begin{document}
\totchap    \chapter{one}
\chapter{two}
\chapter{three}
\chapter{four}
\end{document}


I am trying to gain access to the total number of chapters in a document. I got inspiration from https://tex.stackexchange.com/a/55583/10898. But for some reason or the other the chapter counter is affected and no longer increasing. Why is that the case and how can it be fixed? Note that I would like to use this total to make calculations.

You can change the code to use \stepcounter{totchapters} rather than

\addtocounter{totchapters}{\value{chapter}}


Perhaps I have misunderstood the original intent, but here's a complete MWE that works as expected

% arara: pdflatex
\documentclass{report}

\usepackage{etoolbox}

\newcounter{totchapters}

\providecommand\totchap{}

\makeatletter
\AtEndDocument{%
%\stepcounter{totchapters}%
\immediate\write\@mainaux{%
\string\gdef\string\totchap{\number\value{totchapters}}%
}%
}
\makeatother

\pretocmd{\chapter}{\stepcounter{totchapters}}{}{}

\begin{document}
\totchap\
\chapter{one}
\chapter{two}
\chapter{three}
\chapter{four}
\end{document}

• Can I use \totchap in calculations? For example, 5/\totchap. – azetina May 8 '13 at 19:15
• – cmhughes May 8 '13 at 19:23
• Something like \number\numexpr\totchap+3\relax I suppose. – azetina May 8 '13 at 19:27
• Why using a new counter? Doesn't \immediate\write\@mainaux{\gdef\string\totchap{\number\value{chapter}} do the same? – egreg May 8 '13 at 22:22

The totcount does this without any redefinition.

\documentclass[12pt,twoside,letterpaper]{report}

\usepackage{totcount}
\regtotcounter{chapter}

\begin{document}
This document has \total{chapter} chapters.

\chapter{one}
\chapter{two}
\chapter{three}
\chapter{four}
\end{document}


The first page will show

This document has 4 chapters.

• Can you use \total{chapter} to make arithmetic calculations? – azetina May 8 '13 at 21:47
• @azetina If you define \newcommand{\numtotal}[1]{\value{#1@totc}} you can use \numtotal{chapter} (or any other registered counter) in the context of a <number>. The returned value is -1 at the first run (totcount uses the .aux file for its workings). – egreg May 8 '13 at 22:04
• @egreg Is there a way to have access to the total number of chapters per part? – pluton Jul 21 '13 at 2:50
• @pluton This would be the subject for a new question – egreg Jul 21 '13 at 9:23