0

How to add numberless chapters to the table of contents with titlesec avoiding \addcontentsline after \chapter?

\documentclass[a4paper]{report}
\usepackage{titlesec,titletoc}


\titleformat{name=\chapter}[display]
 {\normalfont\huge}
 {\chaptername\ \thechapter}
 {1ex}
 {}

\titleformat{name=\chapter,numberless}[display]
  {\normalfont\huge}
  {}
  {0pt}
  {}

\begin{document}

\tableofcontents

\chapter*{xx}
\addcontentsline{toc}{chapter}{xy}

\chapter{xy}

\end{document}
\end{document}
sergiokapone
  • 5,578
  • 1
  • 16
  • 39

1 Answers1

1

You can redefine \chapter using xparse, a bit like in this answer of egreg. Note that I only do the redefinition after \tableofcontents has been used, otherwise you would see “Contents” twice in a row, since the \tableofcontents is introduced as a \chapter* (\tableofcontents would add its own title to the table of contents).

\documentclass{report}
\usepackage[a5paper,landscape]{geometry} % small page size for the screenshot
\usepackage{titlesec,titletoc,xparse}
\usepackage{lipsum}

\titleformat{name=\chapter}[display]
 {\normalfont\huge}
 {\chaptername\ \thechapter}
 {1ex}
 {}

\titleformat{name=\chapter,numberless}[display]
  {\normalfont\huge}
  {}
  {0pt}
  {}

\let\latexchapter\chapter

\newcommand*{\redefineChapter}{%
  \RenewDocumentCommand{\chapter}{ s O{##3} m }{%
    \IfBooleanTF{##1}
      {\latexchapter*{##3}%
       \addcontentsline{toc}{chapter}{##2}}
      {\latexchapter[##2]{##3}}%
  }%
}

\begin{document}

\tableofcontents
\redefineChapter

\chapter*{An unnumbered chapter}
\lipsum[1]

\chapter{A numbered chapter}
\lipsum[1]

\end{document}

enter image description here

With this code, you can even use \chapter* with an optional argument in order to specify a special variant of the title for the table of contents:

\chapter*[Title in the toc]{An unnumbered chapter}

enter image description here

frougon
  • 24,283
  • 1
  • 32
  • 55