[Tex/LaTex] Changing the table of contents width

horizontal alignmenttable of contentstocloft

In setting up a table of contents, by default the TOC spans the entire width of the page, regardless of the length of the section titles. I would like to have the entire TOC be only as wide as it needs to be, with the option of including a small additional space (1-4em) between the longest section title and the page number. I would also like to have all the page numbers on the right lined up (i.e. not ragged). Is there a way to do this?

I have to imagine this is possible with tocloft, but I can't seem to find the right settings. I am doing my best to avoid package bloat (which is getting hard to manage), so I would be extra appreciative of solutions using tocloft.

Edit: Here is a MWE

\documentclass[12pt]{article}
\usepackage{setspace, tocloft}

%Modifies line spacing of the ToC
\setlength\cftparskip{-1.2pt}
\setlength\cftbeforesecskip{1.3pt}
\setlength\cftaftertoctitleskip{2pt}

%Makes dots after sections/subsections: Sections 1., 2.1., etc
\makeatletter
\renewcommand{\@seccntformat}[1]{\csname the#1\endcsname.\quad}
\makeatother

%Makes the dots (above) appear in ToC
\let \savenumberline \numberline
\def \numberline#1{\savenumberline{#1.}}

\begin{document}
\tableofcontents
\begin{section}{Section 1}
\begin{subsection}{Section 1.1}\end{subsection}
\begin{subsection}{Section 1.2}\end{subsection}
\end{section}
\begin{section}{Section 2}\end{section}
\end{document}

Which produces:enter image description here

As mentioned above, I would like to control the width between the end of the section titles and the beginning of the page numbers, keeping the page numbers vertically aligned.

Best Answer

Simply add these lines to your preamble

\renewcommand{\cftsecafterpnum}{\hspace*{7.5em}}
\renewcommand{\cftsubsecafterpnum}{\hspace*{7.5em}}

and adjust 7.5em to your needs.

MWE

\documentclass[12pt]{article}
\usepackage{setspace, tocloft}

%Modifies line spacing of the ToC
\setlength\cftparskip{-1.2pt}
\setlength\cftbeforesecskip{1.3pt}
\setlength\cftaftertoctitleskip{2pt}

\renewcommand{\cftsecafterpnum}{\hspace*{7.5em}}
\renewcommand{\cftsubsecafterpnum}{\hspace*{7.5em}}

%Makes dots after sections/subsections: Sections 1., 2.1., etc
\makeatletter
\renewcommand{\@seccntformat}[1]{\csname the#1\endcsname.\quad}
\makeatother

%Makes the dots (above) appear in ToC
\let \savenumberline \numberline
\def \numberline#1{\savenumberline{#1.}}

\begin{document}
\tableofcontents
\begin{section}{Section 1}
\begin{subsection}{Section 1.1}\end{subsection}
\begin{subsection}{Section 1.2}\end{subsection}
\end{section}
\begin{section}{Section 2}\end{section}
\end{document} 

Output

enter image description here

A remark

If you want to add dots after sections and subsections numbers, you can use

\renewcommand{\cftsecaftersnum}{.}
\renewcommand{\cftsubsecaftersnum}{.}

instead of

\let \savenumberline \numberline
\def \numberline#1{\savenumberline{#1.}}