74

I have some long URLs which doesn't contain special "line break characters" like "-" or "/". How can I automatically break these URLs?

\documentclass{scrreprt}

\usepackage[ngerman]{babel}                    
\usepackage[latin1]{inputenc}                
\usepackage[T1]{fontenc}
\usepackage[backend=biber]{biblatex}
\usepackage{url}
\usepackage{dingbat}  % for \carriagereturn symbol
\makeatletter
\g@addto@macro{\UrlBreaks}{\UrlOrds}
\g@addto@macro{\UrlBreaks}{%
\do\/\do\d%
}
\makeatother

\begin{filecontents}{bachelorarbeit_lit.bib}
@ONLINE{java96,
    author = {{Joe Black}},
    title = {Foobar 1.0},
    year = {1996},
    month = {1},
    url = {http://www.aaa.bb.cccc.dh/uploads/dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd.pdf},
    urldate = {2011-03-02},
    sortname = {Sun},
    keywords = {www}
}
\end{filecontents}

\bibliography{bachelorarbeit_lit}

\begin{document}
Test \cite{java96}
\printbibliography
\end{document}

edit

I don't know why but it still doesn't work. Is there an option to automatically break long URLs. I don't care where the break is but it should be done automatically. Even if I manually specify the "breaking character" it doesn't work (as the example shows).

Johannes_B
  • 24,235
  • 10
  • 93
  • 248
user4811
  • 4,185
  • 3
    Have you seen http://tex.stackexchange.com/questions/102152/insert-hyphenation-point-in-bibtex-using-pdflatex-and-hyperref/102168#102168? Or http://tex.stackexchange.com/questions/126702/url-linebreaks-w-o-sloppy Does it help? – Mensch Sep 20 '13 at 00:43
  • I have played now some time with this problem but the other solutions don't help. – user4811 Sep 20 '13 at 13:13

4 Answers4

103

Hacking \UrlBreaks is not needed for \url inside the bibliography of biblatex. Package biblatex uses \biburlsetup and has already added lots of characters. The breaking at some character classes is controlled by counters. From the documentation of biblatex, "4.10.3 User-definable Lengths and Counters":

biburlnumpenalty: If this counter is set to a value greater than zero, biblatex will permit linebreaks after numbers in all strings formatted with the \url command from the url package. This will affect URLs and DOIs in the bibliography. The breakpoints will be penalized by the value of this counter. If URLs and/or DOIs in the bibliography run into the margin, try setting this counter to a value greater than zero but less than 10000 (you normally want to use a high value like 9000). Setting the counter to zero disables this feature. This is the default setting.

biburlucpenalty: Similar to biburlnumpenalty, except that it will add a breakpoint after all uppercase letters.

biburllcpenalty: Similar to biburlnumpenalty, except that it will add a breakpoint after all lowercase letters.

An example:

\RequirePackage{filecontents}
\begin{filecontents}{bachelorarbeit_lit.bib}
@ONLINE{java96,
    author = {{Joe Black}},
    title = {Foobar 1.0},
    year = {1996},
    month = {1},
    url = {http://www.aaa.bb.cccc.dh/uploads/dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd.pdf},
    urldate = {2011-03-02},
    sortname = {Sun},
    keywords = {www}
}
\end{filecontents}

\documentclass{scrreprt}

\usepackage[ngerman]{babel}                    
\usepackage[latin1]{inputenc}                
\usepackage[T1]{fontenc}

\usepackage[backend=biber]{biblatex}
\usepackage{url}

%%% --- The following two lines are what needs to be added --- %%%
\setcounter{biburllcpenalty}{7000}
\setcounter{biburlucpenalty}{8000}

\bibliography{bachelorarbeit_lit}

\begin{document}
Test \cite{java96}
\printbibliography
\end{document}

Result

yo'
  • 51,322
Heiko Oberdiek
  • 271,626
  • 1
    I use bibtex as the backend, but the given code does not work on mactex. In MikTex, I was able to compile. Any solution for mactex? – max Oct 30 '16 at 14:58
  • 1
    @max I just run the example using option backend=bibtex and using bibtex instead of biber and it just worked. I cannot test on MacTeX. But since you have a working and non-working case, you can investigate, compare versions, ... – Heiko Oberdiek Oct 30 '16 at 15:11
  • I manually updated the distribution and now it is working. Thanks :) – max Nov 08 '16 at 03:18
  • Nice solution. I was using the \sloppy (and similar) command but the problem was that it didn't insert a line break inside strings containing only letters which lead to a partial fix. – rbaleksandar Mar 09 '17 at 17:00
  • Coming to this 10 years late... Is the same functionality provided for DOI links that are automatically generated from a doi bibtex entry? It's certainly not automatically line breaking for me. – NoseKnowsAll May 18 '22 at 00:54
  • @NoseKnowsAll All kind of URL links (doi, url, ...) should be supported, because they are using \url or \href with \nolinkurl that all expand to the macro \Url of package url with its penaly settings that are set by biblatex by its internal setup hooks (\biburlsetup). I suggest that you ask a new question with a minimal example that shows the problems of line breaking of the DOI links with your settings. – Heiko Oberdiek May 18 '22 at 17:40
  • what is the package library for biburllcpenalty ? I am getting following error: ! Package biblatex Error: '\bibliographystyle' invalid for 'biblatex'. – alper Sep 16 '22 at 13:59
27

There is another way (SHORTER) of doing that: just put the entry below before the \begin{document}:

\usepackage{url}
\def\UrlBreaks{\do\/\do-}

This allows to have your customized (or required!) bibliography style (e.g. \bibliographystyle{IEEEtran}) unchanged.

schmi
  • 523
  • 5
  • 9
2

For some reason the accepted answer did not work for me (maybe old package versions, which I can't update by myself here at work). Anyway, since I use LuaLaTeX to compile my document, here another solution (found at https://yingtongli.me/blog/2016/01/08/breaking-urls-anywhere-in-lualatex-even.html):

Create a document betterurl.lua with following content:

function betterurl(text)
  label = text:gsub(".", "%1\\allowbreak{}")

  label = label:gsub("~", "\\textasciitilde")
  label = label:gsub("&", "\\&")
  label = label:gsub("/", "/")
  label = label:gsub("-", "-")

  url = text

  tex.print("\\href{" .. url .. "}{" .. label .. "}")

end

and add

\RequirePackage{luacode}
  \luaexec{require("path/to/betterurl")}
  \renewcommand{\url}[1]{\luadirect{
    betterurl(\luastringN{#1})
  }}

to your preamble. Note that you do not need to add the file extension .lua.

This is the result:

enter image description here

der_grund
  • 235
  • So far, this is the only option that displayed everything correctly, but when clicking, the link, an "-" is inserted, so the URL is wrong - so still not working well. Note: For TeXstudio, use Menu > Tools > Commands > LuaLaTeX. And I put it after "\usepackage{url}", otherwise it will throw errors. – Matthias Luh Jun 23 '23 at 15:50
0

All this didn't work for me.
My solution works, but it's not pretty - kind of a last resort (visually it fits, but it isn't automatic).

Be aware that I used the bibtex format, which could be the problem too.

You can directly define the url inside your references.bib (or however you named it).
You might have something like this:

@misc{a_very_consice_key,
  title = {A very nice title},
  urldate = {2023-11-19},
  howpublished = {https://www.example.com/aaaaaaaaa/bbbbbbbbb/ccccccccc/ddddddddd},
}

Do this:

@misc{a_very_consice_key,
  title = {A very nice title},
  urldate = {2023-11-19},
  howpublished = {\url{https://www.example.com/aaaaaaaaa/bbbbbbbbb/ccccccccc/ddddddddd}},
}

this already works ... but might add \texttt{} formatting that doesn't fit the rest of your literature (for me it didn't fit), so I added a few things.

in your packages.tex (or whereever you define your packages):

\usepackage{hyperref}  % <- I had that 
\usepackage{xurl}      % <- I added that 

It works without it too (changes the breakpoints a little - maybe you need it)

Now we define a new command (I have it in my definitions.tex)

\newcommand{\normalurl}[1]{%
    \begingroup
    \let\UrlFont\relax
    \urlstyle{same} % use current font style
    \url{#1}%
    \endgroup
}

...and use our new \normalurl command instead of the \url command inside of our .bib file:

@misc{a_very_consice_key,
  title = {A very nice title},
  urldate = {2023-11-19},
  howpublished = {\normalurl{https://www.example.com/aaaaaaaaa/bbbbbbbbb/ccccccccc/ddddddddd}},
}

I don't understand why this is a problem at all. Maybe someone with more experience can create a function from this that doesn't break \url and just automatically fixes the urls inside the bibliography?

Can't really have random dashes (-) in URLs. Especially if the biber package adds \hrefs after the fact.

Rasalas
  • 101
  • 2
    If you are indeed using biblatex (as the other answers assume, but is not entirely clere here), then howpublished is not the best field for the URL. All good biblatex styles support a url field for URLs and the formatting of those URLs can be configured as shown in the other answer. This can even be combined with a simple \urlstyle{same} in the preamble to lose the \ttfamily look. biblatex will not insert dashes that weren't there when URLs are broken and will link to the correct URL at all times. – moewe Nov 26 '23 at 10:50
  • whoops, I was wondering about that too "Why is that not 'url'?", but I blindly trusted Zotero.

    Turned out, I exported as bibtex. I still have that problem though (somewhere else). Maybe does the same mistake as me and ends up here. I'm going to put a disclaimer at the top...

    – Rasalas Nov 26 '23 at 12:27