[Tex/LaTex] Table of Contents with Chapter and Appendix

appendiceschaptersnamingtable of contentstocloft

I'm using this code to get word Chapter in TOC before each chapter.

\documentclass[a4paper]{book}
\usepackage{tocloft,calc}

\renewcommand{\cftchappresnum}{Chapter }
\AtBeginDocument{\addtolength\cftchapnumwidth{\widthof{\bfseries Chapter }}}

\begin{document}
\tableofcontents

\include{Intro}


\cleardoublepage
\begin{appendices}
\renewcommand{\thesection}{\arabic{section}}
\include{Appendix}
\end{appendices}

\end{document}

This code also adds Chapter word before appendix. I wonder how to get word Appendix before the appendix in TOC.

Best Answer

You have to do the changes while reading the .toc file: this is an example of how to do it. The double \unexpanded is because the toc entry is first written in the .aux file and then in the .toc, so we have to protect it twice. One could add several \protect, but this is surely easier to write.

\documentclass[a4paper]{book}
\usepackage{tocloft,calc}

\newcommand{\setupname}[1]{%
  \addtocontents{toc}{%
    \unexpanded{\unexpanded{%
      \renewcommand{\cftchappresnum}{#1 }%
      \setlength\cftchapnumwidth{\widthof{\bfseries #1 }}%
      \addtolength\cftchapnumwidth{\fixedchapnumwidth}%
    }}%
  }%
}
\AtBeginDocument{\edef\fixedchapnumwidth{\the\cftchapnumwidth}}

\begin{document}
\frontmatter
\tableofcontents

\mainmatter

\setupname{Chapter}
\chapter{Title}

text

\chapter{Another}

text

\appendix
\setupname{Appendix}
\chapter{Title}

text

\end{document}

The \setupname command might be integrated in \mainmatter and in \appendix, but this is left as an exercise. :)