Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 6 down vote accepted

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.

share|improve this answer
    
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 Feb 20 '12 at 17:31
    
@lockstep This is supposed to work without titletoc. But loading it with no special setting gives the same result. –  egreg Feb 20 '12 at 17:38
    
Stupid me. And your patch does work for section entries in the book class. Upvoted. –  lockstep Feb 20 '12 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. –  Jukka Suomela Feb 20 '12 at 17:52

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.