[Tex/LaTex] How to get long \texttt sections to break

line-breakingtypewriter

I often format path names with \texttt which can be very long. Usually Tex will not break this text. The line will just create a hbox overflow. It looks like this:

................
...C:\documents and settings
................
................
................
................
................
................
................

How do I get Tex to create a line break?

Best Answer

If you are using the default LaTeX fonts (or a small number of others), you can enable hyphenation within \texttt using the hyphenat package:

\documentclass[twocolumn]{article}
\usepackage{lipsum}
\usepackage[htt]{hyphenat}
\begin{document}
\texttt{\lipsum[1]}
\end{document}

Note that this still won't do a great job of formatting arbitrary strings because it will be relying on the hyphenation patterns in use.

If your problem is about typesetting paths specifically, another option (arguably better) is to load the url package and use its \path{...} command:

\documentclass[twocolumn]{article}
\usepackage{url}
\begin{document}
Here is a long path: \path{/usr/local/texlive/2010/texmf-dist/tex/latex/biblatex/biblatex.sty}
\end{document}

This can have limitations with non-ASCII characters, however. If you get really stuck, you can force a line to end using \newline (aka \\) or \linebreak. These differ in important ways: \newline will cause the paragraph to end the line abruptly at that point, whereas \linebreak will still attempt to fill the line completely for justification purposes. This is illustrated in the following example:

\documentclass[twocolumn]{article}
\begin{document}
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis.
Curabitur dictum grav$\bullet$\newline ida mauris. 
Nam arcu libero, nonummy eget, consectetuer id, vulputate a, magna.
\bigskip

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis.
Curabitur dictum grav$\bullet$\linebreak ida mauris. 
Nam arcu libero, nonummy eget, consectetuer id, vulputate a, magna.
\end{document}

enter image description here