In a latex example (using the "article" class), I get this in the .toc file:
\contentsline {section}{\numberline {1}test section without number}{1}{section.1}
The important part here is the \numberline
macro. Redefining it to something empty like
\def\numberline#1{}
will remove all numberings in the toc and not elsewhere.
If you get something like \tocsubsection
instead in the .toc (see other answer), then you can probably do something like:
\let\oldtocsubsection=\tocsubsection
\def\tocsubsection#1#2#3{\oldtocsubsection{#1}{}{#3}}
However, this removes all numbers in the table of contents. If you want to control at which level the numbering disappear, the \contentsline
macro expands to different macros depending on the context, e.g., \l@section
. Those macros in turn use the generic \@dottedtocline
macro. This is the one you need to modify, in which we will conditionally redefine \numberline
.
To have control on the depth at which to stop displaying numbers, let us define a new counter:
\newcounter{sectocnonumdepth}
\setcounter{sectocnonumdepth}{2}
Then the conditional redefinition will be following line (extracted from the code for more readability).
\ifnum #1>\c@sectocnonumdepth \def\numberline##1{}\fi%
I simply copy-pasted the definition of \@dottedtocline
from the latex.ltx
source file, and added the check inside. Here is the code for the whole example:
\newcounter{sectocnonumdepth}
\setcounter{sectocnonumdepth}{2}
\makeatletter
\def\@dottedtocline#1#2#3#4#5{%
\ifnum #1>\c@tocdepth \else
\vskip \z@ \@plus.2\p@
{\ifnum #1>\c@sectocnonumdepth \def\numberline##1{}\fi%
\leftskip #2\relax \rightskip \@tocrmarg \parfillskip -\rightskip
\parindent #2\relax\@afterindenttrue
\interlinepenalty\@M
\leavevmode
\@tempdima #3\relax
\advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
{#4}\nobreak
\leaders\hbox{$\m@th
\mkern \@dotsep mu\hbox{.}\mkern \@dotsep
mu$}\hfill
\nobreak
\hb@xt@\@pnumwidth{\hfil\normalfont \normalcolor #5}%
\par}%
\fi}
\makeatother
Final note: this will make the title of section and subsection to start at the same horizontal position, since there is no number to display. If you want more padding, you can for instance add \quad
to the new definition of \numberline
, or to even use the original definition with just the #1
removed:
\def\numberline##1{\hb@xt@\@tempdima{\hfil}}