[Tex/LaTex] Example of contentsline

indexingtable of contentsthesis

I would like to learn how to use the command contentsline; to do this I wrote the code:

\documentclass{article}
\usepackage[utf8]{inputenc}


\begin{document}

\maketitle

\tableofcontents
\clearpage

\section{Paragrafo 1}
Questo è il paragrafo 1

\subsection{Sottoparagrafo 1.1}
Questo è il sottoparagrafo 1.1

\contentsline{chapter}{Prefazione}{2}

\section{Paragrafo 2}
Questo è il paragrafo 2

\end{document}

The result is strange: contentsline has no effect on the table of contents. Can you show me an example of the use of contentsline please?

Best Answer

If you want to add a specific entry to your ToC at the chapter level, you should use \addcontentsline{toc}{chapter}{Prefazione} in your example. The page will be the current page (so the page this macro is executed on). You could add arbitrary stuff to your ToC with \addtocontents (mainly used for formatting instructions).

To add a specific entry with a forced page number, you could use \addtocontents{toc}{\string\contentsline{section}{Foobar}{100}}. Don't use chapter here, as article doesn't have this layer and it would result in errors.

The \contentsline macro is used internally to typeset each entry of the ToC. It is defined to call the macro \l@#1 (build with \csname l@#1\endcsname), so if \contentsline{chapter} is encountered, the \l@chapter macro will be called. This one grabs the other two arguments of \contentsline and typesets the chapter entry.

In article the macro \l@chapter wouldn't be defined though, so your \contentsline{chapter} would call \relax (as each undefined macro name build with \csname equals a \relax). For that reason the other two arguments you specify are just typeset, as they are never actually grabbed.