[Tex/LaTex] Adding \dotfill manually with \addcontentsline

table of contentstemplates

I am using a custom documentclass (based on JHEP), where there are no dots in table of contents automatically for subsections. I am adding section names manually to TOC. Is it possible to add somehow \dotfill to TOC like

\addcontentsline{toc}{subsection}{Section name\dotfill}

This does not work, dots do not reach page number. They go until the half of the line or so…

Also, tocloft package gives errors, cannot use it.

MWE:

\documentclass{JHEP}
\author{A.U. Thor}
\title{Dotty}
\abstract{Not enough dots}

\usepackage{hyperref}
\begin{document}
\tableofcontents
\addcontentsline{toc}{subsection}{Section name\dotfill}
\end{document}

enter image description here

Best Answer

The following patch (via etoolbox) re-inserts the removed ToC-dots - yes, the document class specifically redefines \@tocline and removes the dots:

enter image description here

\documentclass{JHEP}
\usepackage{etoolbox}
\makeatletter
\patchcmd{\@tocline}{\hfill}{%
  \leaders\hbox{$\m@th
    \mkern \@dotsep mu\hbox{.}\mkern \@dotsep
  mu$}\hfill}{}{}
\makeatother
\author{A.U. Thor}
\title{Dotty}
\abstract{Not enough dots}

\usepackage{hyperref}
\begin{document}
\tableofcontents
\addcontentsline{toc}{subsection}{Section name}
\end{document}

The above patch will insert dots in the ToC for \subsection, \subsubsection, \paragraph and \subparagraph (depending on the value of tocdepth), but not \section. For this you could add

\makeatletter
\patchcmd{\l@section}{\hfil}{%
  \leaders\hbox{$\m@th
    \mkern \@dotsep mu\hbox{.}\mkern \@dotsep
  mu$}\hfill}{}{}
\makeatother

to the preamble as well. For more on leaders, see Want to fill line with repeating string.