1

I am looking to modify the table of contents without a package, to change the number formatting for different sectioning levels. Below is an example:

\def\numberline#1{\csname #1@numberline\endcsname}
\def\section@numberline{\thesection.\space}
\def\subsection@numberline{\hb@[email protected]{\thesubsection.\hfil}}

This requires the argument of \numberline in \@sect being redefined, but also seems to require removal of \protect before \numberline. So, I have used etoolbox as follows:

\patchcmd{\@sect}{\protect\numberline{\csname the#1\endcsname}}{\numberline{#1}}{}{}

However, the resulting toc file then reads:

\contentsline {section}{1. Test}{1}{}%
\contentsline {subsection}{\hbox to.5in{1.1.\hfil }Test}{1}{}%

But I would like to the toc file to read as normal (when \protect is still used):

\contentsline {section}{\numberline{section}Test}{1}{}%
\contentsline {subsection}{\numberline{subsection}Test}{1}{}%

MWE:

\documentclass{article}
\usepackage{etoolbox}
\makeatletter
\def\numberline#1{\csname #1@numberline\endcsname}
\def\section@numberline{\thesection.\space}
\def\subsection@numberline{\hb@[email protected]{\thesubsection.\hfil}}
\patchcmd{\@sect}{\protect\numberline{\csname the#1\endcsname}}{\numberline{#1}}{}{}
\makeatother
\begin{document}
\tableofcontents
\section{Test}
\subsection{Test}
\end{document}

Thank you!

1
  • It's easy enough to achieve your desired .toc file (simply use \RenewDocumentCommand{\numberline}{m}{\csname #1@numberline\endcsname}), but the values of \thesection and \thesubsection is not available/correct when the ToC is set, so \numberline{section} and \numberline{subsection} will print incorrect values. Commented Jul 21 at 17:23

1 Answer 1

2

I'd use a different approach:

\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\newcommand{\newnumberline}[2]{\csname #1@numberline\endcsname{#2}}
\newcommand{\section@numberline}[1]{#1. }
\newcommand{\subsection@numberline}[1]{\hb@[email protected]{#1.\hfil}}
\patchcmd{\@sect}
  {\protect\numberline}
  {\protect\newnumberline{#1}}
  {}{}
\makeatother

\begin{document}

\tableofcontents

\section{Test}

\subsection{Test}

\end{document}

Here \newnumberline has two arguments, the first one is passed to \csname and the result is what you expected.

output

The .toc file is

\contentsline {section}{\newnumberline {section}{1}Test}{1}{}%
\contentsline {subsection}{\newnumberline {subsection}{1.1}Test}{1}{}%
1
  • Thank you! This is great. Commented Jul 21 at 17:36

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.