[Tex/LaTex] Custom table of contents with appendices, how to get ‘Chapter’ and ‘Appendix’

appendicestable of contentstitletoc

I try to generate a table of contents which hopefully should look something like

Chapter 1 First chapter ….

Chapter 2 Second chapter ….

Appendix A First appendix ….

Appendix B Second appendix ….

So far I have tried the following,

\documentclass{book}
\usepackage{titlesec}
\usepackage{titletoc}
\usepackage[titletoc]{appendix}

\titlecontents{chapter}%
 [0em]% 
 {\addvspace{2em}}%
 {\bfseries\chaptername\ \thecontentslabel\quad}% 
 {\hspace{-0em}}% 
 {\hfill\contentspage}% 
 [\addvspace{0pt}]% 

\usepackage{lipsum}
%
\begin{document}
\tableofcontents
\chapter{First chapter}\lipsum[1]
\section{First section}\lipsum[2]
\subsection{First subsection}\lipsum[3]
\chapter{Second chapter}\lipsum[4]
\section{Second section}\lipsum[5]
\subsection{Second subsection}\lipsum[6]
\subsection{Third subsection}\lipsum[7]
%appendices 
\begin{appendices}
\chapter{First appendix}\lipsum[1]
\section{Some section}\lipsum[2]
\subsection{Some subsection}\lipsum[3]
\subsection{Some subsection}\lipsum[4]
\chapter{Second appendix}\lipsum[5]
\section{Some section}\lipsum[6]
\subsection{Some subsection}\lipsum[7]
\end{appendices}
%
\end{document}

But this seems to give the output

Table of contents

So, it is clear that there have to be something like if 'appendix', write Appendix, but I do not know how to put this into LaTeX logic. However it seems to be even more problems to my approach. Do anyone know how to solve this? Or have tricks how to create nice looking table of contents?

Best Answer

In the arguments of \titlecontents, replace \chaptername with \@chapapp. Also, at the beginning of the appendices environment a changed definition of \@chapapp (to \appendixname) must be forwarded to the .toc file. Last, but not least, remove the titletoc option from the appendix package.

\documentclass{book}
\usepackage{titlesec}
\usepackage{titletoc}
\usepackage{appendix}

\makeatletter

\titlecontents{chapter}%
 [0em]% 
 {\addvspace{2em}}%
 {\bfseries\@chapapp\ \thecontentslabel\quad}% 
 {\hspace{-0em}}% 
 {\hfill\contentspage}% 
 [\addvspace{0pt}]% 

\g@addto@macro\appendices{%
  \addtocontents{toc}{\protect\renewcommand{\protect\@chapapp}{\appendixname}}%
}

\makeatother

\usepackage{lipsum}
%
\begin{document}
\tableofcontents
\chapter{First chapter}\lipsum[1]
\section{First section}\lipsum[2]
\subsection{First subsection}\lipsum[3]
\chapter{Second chapter}\lipsum[4]
\section{Second section}\lipsum[5]
\subsection{Second subsection}\lipsum[6]
\subsection{Third subsection}\lipsum[7]
%appendices 
\begin{appendices}
\chapter{First appendix}\lipsum[1]
\section{Some section}\lipsum[2]
\subsection{Some subsection}\lipsum[3]
\subsection{Some subsection}\lipsum[4]
\chapter{Second appendix}\lipsum[5]
\section{Some section}\lipsum[6]
\subsection{Some subsection}\lipsum[7]
\end{appendices}
%
\end{document}

enter image description here