[Tex/LaTex] How to include Table of contents chapter wise

table of contents

How to get the table of contents chapter wise (beginning of each chapter with sections and subsections with page numbers) and the main table of contents containing only chapter title with page range not sections and subsections tiles.

Best Answer

Here's one possible solution using the titletoc package for the partial ToCs and a variation of this answer to Chapterwise page range in the TOC to generate the page ranges in the main ToC.

Use the \MiniToC after the \chapter command for chapters in which you want to typeset a partial ToC.

The code has to be compiled three times to get the right numbers for the page ranges in the main ToC.

\documentclass{report}
\usepackage{titletoc}
\usepackage{letltxmacro}
\usepackage{etoolbox}
\usepackage{lipsum}

\newcommand\MiniToC{%
  \setcounter{tocdepth}{2}
  \startcontents
  \printcontents{}{1}{\section*{\contentsname}\vskip-3.5ex\hrulefill\vskip1ex}
  \vskip-0.5ex\noindent\hrulefill
  \setcounter{tocdepth}{0}
}
\setcounter{tocdepth}{0}

\makeatletter
\newif\if@chap@enddc
\@chap@enddctrue
\LetLtxMacro\ltx@@chapter\@chapter
\renewcommand\@chapter[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
}
\def\chaprange{%
  \expandafter\pageref{chap:\thechapter}--\expandafter\pageref{prenextchap:\thechapter}}

\let\ltx@addcontentsline\addcontentsline
\def\CR@addcontentsline#1#2#3{%
  \addtocontents{#1}{\protect\contentsline{#2}{#3}{\chaprange}}
}

\def\ToggleChaprange{\let\addcontentsline\CR@addcontentsline}
\def\BypassChaprange{\let\addcontentsline\ltx@addcontentsline}
\def\BreakChaprange{%
  \expandafter\label{prenextchap:\thechapter}
  \let\addcontentsline\ltx@addcontentsline
  \@chap@enddcfalse
}
\makeatother

\pretocmd{\section}{\BypassChaprange}{}{}
\pretocmd{\chapter}{\ToggleChaprange}{}{}

\begin{document}

\tableofcontents

\chapter{Test chapter one}
\MiniToC
\section{A test section}
\subsection{A test subsection}
\subsubsection{A test subsubsection}
\lipsum[1-30]

\chapter{Test chapter two}
\MiniToC

\section{A test section}
\subsection{A test subsection}
\subsubsection{A test subsubsection}
\lipsum[1-20]

\chapter{Test chapter three}
\MiniToC

\section{A test section}
\subsection{A test subsection}
\subsubsection{A test subsubsection}
\lipsum[1-10]

\end{document}

An image of the main ToC:

enter image description here

An image of the partial ToC for the first chapter:

enter image description here

Related Question