[Tex/LaTex] How to make section name uppercase in ToC

capitalizationtable of contentstocloft

Is there another way to change section names in ToC to uppercase besides Uppercase sections and subsections on ToC
Cause this one doesn't work for me very well.
Can it be done with tocloft package?

Best Answer

Update: for a solution working with hyperref, see below.

An option, patching \l@section:

\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\patchcmd{\l@section}{#1}{\MakeUppercase{#1}}{}{}
\makeatother

\begin{document}

\tableofcontents
\section{A test section}
\section{Another test section}

\end{document}

enter image description here

If your section titles contain math or commands (such as \label), it's best to use \MakeTextUppercase from the textcase package:

\documentclass{article}
\usepackage{textcase}
\usepackage{etoolbox}

\makeatletter
\patchcmd{\l@section}{#1}{\MakeTextUppercase{#1}}{}{}
\makeatother

\begin{document}

\tableofcontents
\section{A test section $a=b$}\label{sec:test}
\section{Another test section with a reference:~\protect\ref{sec:test}}

\end{document}

enter image description here

The solutions above won't work if the hyperref package is used. In this case, one can tamper with \contentsline (this borrows some code from Heiko Oberdiek's answer to this question in comp.text.tex):

\documentclass{article}
\usepackage{textcase}
\usepackage{hyperref}

\makeatletter
\let\oldcontentsline\contentsline
\def\contentsline#1#2{%
  \expandafter\ifx\csname l@#1\endcsname\l@section
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
  {%
    \oldcontentsline{#1}{\MakeTextUppercase{#2}}%
  }{%
    \oldcontentsline{#1}{#2}%
  }%
}
\makeatother
\begin{document}

\tableofcontents
\section{A test section $a=b$}\label{sec:test}
\section{Another test section with a reference:~\ref{sec:test}}

\end{document}

enter image description here

The above approach also works using \MakeUppercase instead of \MakeTextUppercase; if this is so, then textcase is not necessary.