Chapterwise page range in the TOC

Can you give me some advice for how to obtain the following format of the TOC?

• Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. Did you try building some minimal working example (MWE) ? if so please post Nov 14, 2013 at 16:31
• Have you seen this? Probably it may solve your problem. Nov 14, 2013 at 17:08
• does the 7 mean that page 8 is blank, or that the last \section from the first \chapter is on page 7?
– user4686
Nov 21, 2013 at 15:32
• It is means that last line of chapter 1 is appearing on page 7. It may be possible that the document will be of two-sided and page 8 may be blank Dec 13, 2013 at 13:15

My solution consists of appropriate labeling (in the very beginning and the very end of each chapter), defining a macro \chaprange that retrives the pages from a pair of labels formatting them to <p1>-<p2> (as requested), and in redefining \addcontentsline. Moreover, there are three macros controlling the page numbering pattern:

1. \chaprangeon activates the functionality;
2. \chaprangeoff temporary disables the functionality;
3. \breakchaprange disables the functionality if the last chapter is not the content ending your document.

The Code

\documentclass{book}
\usepackage{lipsum}

\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newif\if@chap@enddc
\@chap@enddctrue
\let\ltx@@chapter\@chapter
\def\@chapter[#1]#2{%
\ltx@@chapter[#1]{#2}
\expandafter\label{chap:\thechapter}}%
\let\ltx@toc\tableofcontents
\renewcommand\tableofcontents{%
\ltx@toc
\let\ltx@chapter\chapter
\renewcommand{\chapter}{%
\expandafter\label{prenextchap:\thechapter}
\ltx@chapter}}%
\let\ltx@enddocument\enddocument
\renewcommand\enddocument{%
\if@chap@enddc\expandafter\label{prenextchap:\thechapter}\fi
\ltx@enddocument}%
\newcommand\chaprange{%
\expandafter\pageref{chap:\thechapter}--\expandafter\pageref{prenextchap:\thechapter}}%
\edef\@tempa{\detokenize{chapter}}
\edef\@tempb{\detokenize{#2}}
\ifx\@tempa\@tempb
\let\CR@thepage\chaprange
\else
\let\CR@thepage\thepage
\fi
\newcommand\breakchaprange{%
\expandafter\label{prenextchap:\thechapter}
\@chap@enddcfalse}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\makeatother

\begin{document}
\tableofcontents

\mainmatter

\chapter{Title 1}
\lipsum

\section{Subtitle 1}
\lipsum

\chapter{Title 2}
\lipsum\lipsum

\chapter{Title 3}
\lipsum\lipsum\lipsum

\backmatter
\null

\appendix
\end{document}


Important: This code requires three compilation cycles to work properly.

Example output

• Aug/28/'15 Solution available as package chaprange (v0.99a: first test version)