[Tex/LaTex] Table of contents: section titles ragged right

horizontal alignmenttable of contents

In the standard book class, if there are very long section titles, \tableofcontents tries to produce justified text.

How can I produce a table of contents so that the section titles are typeset flush left, ragged right?

That is, I would like to produce something like this (note that the page numbers should be aligned):

1.2.2  Short title  . . . . . 42
1.2.3  Long section title
       can be wrapped . . . . 44
1.2.4  Another short title  . 45

(The default output is almost identical, except that Latex uses hyphenation and variable inter-word spacing to make sure that the right margins are aligned for all multi-line section titles.)

I assumed that I could easily use the titletoc package—just re-define the toc entries and add \raggedright somewhere. However, none of my attempts were successful.

Best Answer

You can try with

\usepackage{etoolbox}
\makeatletter
\patchcmd{\@dottedtocline}
  {\rightskip\@tocrmarg}
  {\rightskip\@tocrmarg plus 4em \hyphenpenalty\@M}
  {}{}
\makeatother

In this way you'll get ragged right text and no hyphenation.