Note though that there are some nice packages dealing with TOC's which could well be upset by the following. Besides, I am assuming a standard \tableofcontents command as in the article class.
\documentclass{article}
\usepackage[french]{babel} % for testing
\usepackage{hyperref} % for testing
\newif\iftoctitledone
\makeatletter
\def\printcontentsnameifnotalreadydone{%
\iftoctitledone\else
\section *{\contentsname \@mkboth {\MakeUppercase \contentsname }
{\MakeUppercase \contentsname }}\fi
\toctitledonetrue}
\AtBeginDocument{%
\let\mygoodoldcontentsline\contentsline
\def\contentsline{\printcontentsnameifnotalreadydone\mygoodoldcontentsline}
\renewcommand\tableofcontents{\@starttoc {toc}}
}
\makeatother
\begin{document}
\tableofcontents
% \section{test}
nothing
\end{document}
The same in another style, slightly more elegant.
\documentclass{article}
\usepackage[french]{babel} % for testing
\usepackage{hyperref} % for testing
\makeatletter
\def\printcontentsnameifnotalreadydone{%
\section *{\contentsname \@mkboth {\MakeUppercase \contentsname }
{\MakeUppercase \contentsname }}%
\def\printcontentsnameifnotalreadydone{}}
\AtBeginDocument{%
\let\mygoodoldcontentsline\contentsline
\def\contentsline{\printcontentsnameifnotalreadydone\mygoodoldcontentsline}
\renewcommand\tableofcontents{\@starttoc {toc}}
}
\makeatother
\begin{document}
\tableofcontents
% \section{A}
% a
% \section{B}
% b
% \subsection{C}
nothing
\end{document}
\tableofcontentswill print "Contents" (or rather\contentsname) whatever what. So it must be patched. Then it is not enough to check if the.tocfile exists, as for example Babel writes to the.tocfile. One could imagine patch\addcontentslineso that on its first use it writes something to theauxfile which we can test in the\tableofcontentspatch. Or patching\contentslineitself. In brief, this is a bit complicated. – jfbu Jan 23 at 9:00.tocfile is empty or not. I'm not an expert of conditional statements in latex but maybe you can file some information here – Pouya Jan 23 at 9:03.tocfile.\select@language {french}for example. So it is not enough to check if the.tocfile exists, and if it exists if it is empty. – jfbu Jan 23 at 9:06\addcontentslineand\contentslinethey are replaced byhyperref, I think in the preamble (I forgot). So the patching can be done at begin document, I think. I would go for\contentsline. – jfbu Jan 23 at 9:11