[Tex/LaTex] LaTeX contents page: hiding specific page numbers automatically

formattingtable of contents

Is it possible to have a contents page in LaTeX that doesn't show a page number of a particular subsection, if the one immediately before it shares the same page number?

e.g. If there are 3 subsections on the same page, is it possible in the contents page to show the page number only at the 1st line?

I'm also using the titletoc package in a way similar to the following:

\documentclass{article}

\usepackage{titletoc}
\titlecontents{section}[0pt]{\thecontentspage\quad\thecontentslabel\quad}{}{}{}
\titlecontents{subsection}[0pt]{\thecontentspage\quad\thecontentslabel\quad}{}{}{}
\titlecontents{subsubsection}[0pt]{\thecontentspage\quad\thecontentslabel\quad}{}{}{}

\begin{document}

\tableofcontents

\section{FIRST}
\subsection{FIRST first}
\subsection{FIRST third}
\newpage
\subsubsection{FIRST third b}
\section{SECOND}
\subsection{SECOND first}

\end{document}

It doesn't include dots and shows the page numbers to the left of the section/subsection/subsubsection numbers.

Best Answer

Solution for the use with titletoc. Self-commented code, you have to put the code block after \usepackage{titletoc} but before \begin{document}.

\documentclass{article}

\usepackage{titletoc}
\titlecontents{section}[0pt]{\thecontentspage \quad \thecontentslabel \quad}{}{}{}
\titlecontents{subsection}[0pt]{\thecontentspage \quad \thecontentslabel \quad}{}{}{}
\titlecontents{subsubsection}[0pt]{\thecontentspage \quad \thecontentslabel \quad}{}{}{}

% START HERE
\makeatletter
\AtBeginDocument{
\g@addto@macro{\tableofcontents}{\let\l@lastnumber\relax}
\let\old@ttl@tocentry\ttl@tocentry
\def\ttl@tocentry#1#2#3#4#5#6#7#8{%
  \edef\l@thisnumber{#8}% store current page number
  \old@ttl@tocentry{#1}{#2}{#3}{#4}{#5}{#6}{#7}{%
    \ifnum\ttl@b>1\relax% the value here determines which levels will ALWAYS have page numbers
      \ifx\l@thisnumber\l@lastnumber% if the numbers are the same
        \leavevmode\phantom{\l@thisnumber}%
      \else% if the numbers differ
        \l@thisnumber
      \fi
    \else% if the level has to have the page number always
      \l@thisnumber
    \fi}%
  \edef\l@lastnumber{#8}% save the page number for the next ToC line
}
}
\makeatother
% END HERE

\begin{document}

\tableofcontents
\listoftables

\section{FIRST}
\subsection{FIRST first}
\subsection{FIRST second}
\subsection{FIRST third}
\subsubsection{FIRST third a}
\newpage
\subsubsection{FIRST third b}
\subsubsection{FIRST third c}
\subsection{FIRST fourth}
\section{SECOND}
\subsection{SECOND first}

\end{document}