12

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.

2 Answers 2

9

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.

5
  • If I replace tocstyle with titletoc plus your patch in my example, it seems that subsection entries are set ragged right, but section entries aren't.
    – lockstep
    Commented Feb 20, 2012 at 17:31
  • @lockstep This is supposed to work without titletoc. But loading it with no special setting gives the same result.
    – egreg
    Commented Feb 20, 2012 at 17:38
  • Stupid me. And your patch does work for section entries in the book class. Upvoted.
    – lockstep
    Commented Feb 20, 2012 at 17:43
  • I accepted this answer, as it seems to produce slightly better results than the tocstyle version—in particular, this version does not try to squeeze too much text on one line. In the tocstyle solution, the right margin of the section titles seemed to be a bit too close to the page numbers in some cases. Commented Feb 20, 2012 at 17:52
  • I still get hyphenations :(
    – yegor256
    Commented Feb 14, 2021 at 3:32
6

You may use the package tocstyle (Alpha version) which is included in KOMA-Script.

\documentclass{article}

\usepackage{tocstyle}
\usetocstyle{standard}
\settocfeature{raggedhook}{\raggedright}

\newcommand*{\sometext}{%
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit,
  vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur dictum gravida
  mauris. Nam arcu libero, nonummy eget, consectetuer id, vulputate a, magna.
  Donec vehicula augue eu neque.%
}

\begin{document}

\tableofcontents

\section{\sometext}

\subsection{\sometext}

\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .