Forcing linebreaks in \url
(converting a previous comment to an answer)
A quick google search (alas, too quick) reveals one solution. Use the [hyphens]
option with the url
package:
\PassOptionsToPackage{hyphens}{url}\usepackage{hyperref}
Some recommendations also include inserting \sloppy
in case latex is trying too hard to align things.
The package url
defines a command \def\UrlOrds{\do\*\do\-\do\~\do\'\do\"\do\-}%
which can be added to the default url break characters at which a line can be broken. Below, the line \g@addto@macro
appends the list of characters defined in \UrlOrds
to the \UrlBreaks
macro.
\documentclass{article}
\textwidth=8cm
\parindent=0pt
\usepackage{url}
\makeatletter
\g@addto@macro{\UrlBreaks}{\UrlOrds}
\makeatother
\begin{document}
\rule{\linewidth}{1pt}
foo bar baz \url{very-long-url-very-long-url-very-long-url-very-long-url-very-long-url-}
\end{document}
The same effect could be obtained by using the more usual \renewcommand
on \UrlBreaks
, but this would remove the characters that were already defined in \UrlBreaks
.
Edit:
If you load package etoolbox
you can reduce these 3 lines:
\makeatletter
\g@addto@macro{\UrlBreaks}{\UrlOrds}
\makeatother
to this oneliner:
\gappto{\UrlBreaks}{\UrlOrds}
Herbert Voß created (December 2017) the package xurl
.
This package allows urls to break everywhere, can be compiled simply with pdflatex
, and has the same options as url
(indeed, it loads url
package).
Here an MWE:
% arara: pdflatex
\documentclass{article}
\parindent=0pt
\usepackage{xurl}
\begin{document}
\rule{\linewidth}{1pt}
An example of everywhere breaking url:
\url{very-long-url-very-long-url-very-long-url-very-long-url-very-long-url}
Another example of everywhere breaking url:
\url{very-long-url-very-long-url-very-long-url-very-long-url-very-long-url}
A third example:
\url{very-long-url-very-long-url-very-long-url-very-long-url-very-long-url}
\end{document}
Here the output:
Update: since version 0.05 (December 2018) the package author have added support for biblatex
which has its own url handling.
If you load xurl
after biblatex
this is done by default.
If you want to avoid it, load xurl
before biblatex
or use the option nobiblatex
:
\usepackage[nobiblatex]{xurl}
For more info, see package documentation.