5

I am writing a class based on memoir, which provides \tableofcontents (which lists the ToC within the ToC) and \tableofcontents* (which does not list the ToC within the ToC).

I have seen this question and its many duplicates, but I want to prevent the Table of Contents from itself being listed in the Table of Contents regardless of the user's choice of \tableofcontents* vs. \tableofcontents.

Based on the memoir manual (Section 9.2), I am currently using etoolbox to do

\pretocmd{\tableofcontents}{\begin{KeepFromToc}}{}{<class warning omitted>}
\apptocmd{\tableofcontents}{\end{KeepFromToc}}{}{<class warning omitted>}

which works as expected (both starred and unstarred variants do not write a ToC entry).

Is this a recommended way to do this? Does this method have any bad side effects I've not thought of?

Here is an MWE for any testing you may wish to do:

\documentclass{memoir}
\usepackage{etoolbox}

\pretocmd{\tableofcontents}{\begin{KeepFromToc}}{}{}
\apptocmd{\tableofcontents}{\end{KeepFromToc}}{}{}

\begin{document}

\tableofcontents   
\chapter{Test Chapter}
\section{Test Section}

\end{document}
Paul Gessler
  • 29,607

2 Answers2

4

Without the etoolbox package, you can do something like this:

\documentclass{memoir}

\makeatletter
\let\oldtableofcontents\tableofcontents
\def\tableofcontents{\@ifstar{\oldtableofcontents*}{\oldtableofcontents*}}
\makeatother

\begin{document}

\tableofcontents  
\chapter{Test Chapter}
\section{Test Section}

\end{document}

(of course, in your .cls file you don't need \makeatletter, \makeatother).

Gonzalo Medina
  • 505,128
2

The \tableofcontents command is defined as

> \tableofcontents=macro:
->\@ifstar {\@nameuse {mem@tableofcontents}{01}}{\@nameuse {mem@tableofcontents}{00}}.

I had to use \show\tableofcontents, because the definition is indirect, via

\newlistof{tableofcontents}{toc}{\contentsname}

Thus

\makeatletter
\renewcommand{\tableofcontents}{%
  \@ifstar{\mem@tableofcontents{01}}
          {\mem@tableofcontents{01}}%
}
\makeatother

will do.

Complete example:

\documentclass{memoir}
\makeatletter
\renewcommand{\tableofcontents}{%
  \@ifstar{\mem@tableofcontents{01}}
          {\mem@tableofcontents{01}}%
}
\makeatother

\begin{document}

\tableofcontents
\chapter{Test Chapter}
\section{Test Section}

\end{document}

With \tableofcontents* it would be the same.

egreg
  • 1,121,712