6

Consider the following MWE:

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

\usepackage{etoolbox}

\newcounter{totchapters}

\providecommand\totchap{}

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

\pretocmd{\chapter}{\addtocounter{totchapters}{\value{chapter}}\setcounter{chapter}{0}}{}{}

\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.

5

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}
6

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
  • 2
    @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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.