5

This question continues my another.

I have to use weird margins and line spacing for my academic wirting. MWE:

\documentclass[
               pagesize,
               usegeometry = on,
               DIV = calc,% for the line spacing, KOMA-Script manual, page 40
               ngerman
              ]{scrartcl}

\usepackage[
            left = 25mm,
            bottom = 20mm,
            right = 45mm,
            top = 20mm
           ]{geometry}
\usepackage[onehalfspacing]{setspace}% for the line spacing, KOMA-Script manual, page 40
\usepackage{
            babel,
            csquotes
           }
\usepackage[
            backend = biber,
            sortlocale = auto,
            sorting = nyt,
            style = ext-authoryear-comp
           ]{biblatex}

% for the line spacing, KOMA-Script manual, page 40:
\AfterTOCHead{\singlespacing}
\KOMAoptions{DIV = last}
% adjusting the bibliography
\AtBeginBibliography{\renewcommand*{\mkbibnamegiven}{\textsc}}% small caps for the author name
\AtBeginBibliography{\renewcommand*{\mkbibnamefamily}{\textsc}}% small caps for the author surname
\DeclareFieldFormat{biblabeldate}{#1}% year without the surrounding brackets
\DeclareDelimFormat[bib]{nameyeardelim}{\addcomma\space}% comma before the year
% changes the type @online
\DefineBibliographyStrings{german}{
                                   urlfrom = {verfügbar unter},
                                   urlseen = {zuletzt geprüft am}
                                  }
% changes the format of the fields url and urldate
\DeclareFieldFormat{url}{\bibstring{urlfrom}\addcolon\space\url{#1}}
\DeclareFieldFormat{urldate}{\mkbibbrackets{\bibstring{urlseen}\addcolon\space#1}}
\renewbibmacro*{url+urldate}{% changes the default order of the fields url and urldate
                             \usebibmacro{urldate}%
                             \newunit
                             \usebibmacro{url}%
                            }

\begin{filecontents}{\jobname.bib}

  @ONLINE{Chemie,
          EDITOR   = {LUMITOS GmbH},
          LOCATION = {Berlin},
          URL      = {http://www.chemie.de/lexikon/Kerosin.html},
          TITLE    = {Kerosin},
          URLDATE  = {2018-06-22},
         }

\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}

  Text. Text. Text. Text. Text. Text. Text. Text. Text. Text. Text. Text. Text \autocite{Chemie}.
  \printbibliography

\end{document}

The result:

breaking

How can I improve the breaking?

Thank you for your help and effort in advance!

18

This is a general problem of automatically generated bibliographies. Some bits of the bibliography entry may turn out to be unbreakable and if they happen to occur in the wrong place, overfull or underfull boxes are the result. And while this is a general problem, there is no universal good solution that works at all possible levels of the problem.

Since questions about line breaking in the bibliography pop up from time to time, I decided to extend this answer a bit. The answer is split into two parts. The first part discusses some common specific issues that make line breaking in the bibliography tricky. The second part focusses on general methods to improve line breaking in bibliographies.

Specific issues

URLs and DOIs

One of the most common causes of bad line breaks in the bibliography (and elsewhere) are URLs. By default the url package (which is the de facto standard for URL typesetting in LaTeX and is loaded for example by hyperref and biblatex; it provides the command \url) only breaks URLs at places where it is aesthetically pleasing: For example after /, ) and other punctuation like ., ;, :. By default \url also does not break at hyphens (-) to avoid the (false) impression that \url hyphenated the URL. That may not be enough for longer URLs that consist of long strings of letters and numbers as is more and more common nowadays. Since biblatex typesets DOIs with commands that are very similar to the commands used for URLs, the same applies for DOIs.

There are some ways to get better results in terms of overfull/underfull boxes with URLs and DOIs.

  1. Try to remove clutter from the URL to make it as compact as possible. Sometimes the URLs you get by copying-and-pasting from your browser contain additional unneeded bits like session identifiers, it may be possible to remove those without impacting the validity of the link. Sometimes websites offer a 'share' function that may have a more compact link (which may or may not contain some additional/unneeded tracking bit).

    For example the URL of this page is shown as

    https://tex.stackexchange.com/questions/442308/how-to-adjust-the-breaking-in-the-bibliography
    

    in my browser. Trial and error shows that the last bit of text in the URL is actually irrelevant and

    https://tex.stackexchange.com/questions/442308/
    

    takes us to the same page. When I click on the "share" button, I get an even shorter link

    https://tex.stackexchange.com/q/442308/35864
    

    Again, a test shows that the URL works without the last bit and can be shortened to

    https://tex.stackexchange.com/q/442308/
    

    Indeed the 35864 in the longer link is my StackExchange user ID. That additional bit in the URL is used to track who posted the link and SE use it to track various badges (and no doubt for other internal data harvesting).

    When you manipulate the URL it is imperative to check that it still works. It is always (regardless of whether you modified the URL or not) a good idea to check if the URL still works a few days later maybe even with a different browser to make sure that the link you got was not a single-use or time-limited URL.

  2. biblatex offers you a finer control over URL breaking in the bibliography. (That might also mean that some methods you find for line breaking URLs may not work with biblatex.) You can change the values of the counters biburlnumpenalty, biburlucpenalty and biburllcpenalty to allow breaks after numbers, uppercase letters and lowercase letters, respectively. See Line breaks of long URLs in biblatex bibliography? for a good example and URL line breaks with biblatex for some background info, more is at (Another) problem with url hyphenation in bibliography, Avoiding inelegant splits on URLs.

    Recently, biblatex introduced the possibility to add a small stretchable space between characters to improve line breaking. See BibLaTeX long URL extending into border despite using biburllcpenalty (and https://github.com/plk/biblatex/issues/850).

  3. If you don't want to play around with the values of biburlnumpenalty etc. yourself and just want all URLs to break everywhere, you can load the xurl package. If you load xurl after biblatex it will automatically also affect bibliographies typeset with biblatex.

ISBNs and other long numbers

Unhyphenated ISBNs and long electronic page numbers/article identifiers can also cause issues with line breaks, because LaTeX does not hyphenate/break numbers.

ISBNs can usually be separated into chunks with hyphens and LaTeX would allow line breaks after those hyphens, so it is recommended use the hyphenated form of the ISBN. If you don't want to add all required hyphens manually and your bibliography manager/tool can't do that for you automatically, Biber's --isbn-normalise option can help. See Automatically validate and format ISBNs (and Some lines not broken in BibLaTeX bibliography).

For other numbers, one may have to tweak the field format to introduce something like seqsplit's \seqsplit command: Too long line in Bibliography, not URL, line break needed.

Tricky words (e.g. technical terms, proper nouns)

Sometimes TeX simply does not know how to hyphenate some of the technical terms or proper nouns in the titles of the works you cite. (Geographical names can be particularly tricky.) If TeX doesn't break the line next to a word like this, you may want to check if TeX knows how to hyphenate it with \showhyphens (Display hyphenation options for a specific word): Just write \showhyphens{<word>} and check the .log file to see if TeX can hyphenate the word. If it can, you should see -s at possible break points. If there are no possible break points, you can introduce them manually locally with \- or globally, see for example Breaking words at the end of line. A list of known hyphenation exceptions for US English is available on CTAN as hyphenex.

Words with hyphens

Words containing hyphens are a special case: TeX will break words containing a hyphen only at the hyphen and nowhere else. Possible workarounds are discussed at Adequate hyphenation of words already containing a hyphen and https://stackoverflow.com/q/2193307.

Dates

Initial state of the corrected MWE (see code below): The "2018]" bit of "[Zuletzt geprüft am: 22. 06. 2018]" protrudes into the margin

The specific issue here is that the entire date "22. 06. 2018" (and the following "].") is a single unbreakable unit. That unit is too long to fit into the first line, but if pushed into the second line in its entirety, the first line would be too sparsely populated for TeX's liking. A possible solution here would be to allow the date to break with

\DefineBibliographyExtras{german}{%
  \protected\def\mkbibdateshort#1#2#3{%
    \iffieldundef{#3}
      {}
      {\mkdayzeros{\thefield{#3}}\adddot
       \iffieldundef{#2}{}{\addthinspace}}%
    \iffieldundef{#2}
      {}
      {\mkmonthzeros{\thefield{#2}}%
       \iffieldundef{#1}
         {}
         {\iffieldundef{#3}{/}{\adddot\addthinspace}}}%
    \iffieldbibstring{#1}
      {\bibstring{\thefield{#1}}}
      {\dateeraprintpre{#1}\mkyearzeros{\thefield{#1}}}}}

But of course that only works for this particular case and it might be undesirable to have the date break across lines (there is after all a reason for the default of non-breaking dates).

"22. 06. 2018" broken in "22. 06." and "2018" so that the margin is preserved

General solutions

Before we continue, for German texts you definitely want to load \usepackage[T1]{fontenc} if you are using pdfLaTeX (i.e. not when you use XeLaTeX or LuaLaTeX) to enable proper hyphenation of words containing umlauts and other accented characters. Additionally you may want to consider \usepackage{lmodern} instead of the standard Computer European font you get by default, cf. Latin Modern vs cm-super?.

For more generic solutions you can try (in increasing order of effect size and probably decreasing order of desirability)

  1. Load microtype. That package enables use of certain microtypography features that can greatly improve line breaking. Of course microtypography can't solve all (especially big) problems. It doesn't help here, the unbreakable chunk is too large.

    the date still protrudes into right margin - but only the "018]", compared to the initial state the "2" of "2018" is now inside the text area

    Even though microtype did not solve the problem here, it brought a tiny improvement: Initially the entire 2018]. protruded into the margin, now the 2 is inside the text area and only the 018]. crashes the frame.

  2. You can increase \emergencystretch, see What is the meaning of \fussy, \sloppy, \emergencystretch, \tolerance, \hbadness? and Line breaking of URLs in bibliographies, How to use \sloppy for just some references?. In the example

    \begingroup
    \setlength{\emergencystretch}{.5em}
    \printbibliography
    \endgroup
    

    worked. But that value may need to be adjusted for other cases and needs to be found by try and error. Values that are too high may cause unpleasant results.

    slightly larger interword space so that "Zuletzt geprüft am" aligns with the margin, "22. 06. 2018" is in the next line

    The nice thing about \emergencystretch is that it does not influence the line breaking of 'good' paragraphs, i.e. of those that already break and hyphenate nicely (according to TeX's understanding).

  3. Use the option block=space. This places a slightly larger space after each logical block in the bibliography. That space is allowed to grow and shrink and can thus influence the line breaking.

    slightly larger interword space so that "Zuletzt geprüft am" aligns with the margin, "22. 06. 2018" is in the next line

    This happened to work here, because the space required to make the first line 'full enough' for TeX is not very large.

    There is a subtle difference between the output for block=space and the \emergencystretch solution. If you look really closely you will see that not all spaces have the same length with block=space - only the space between "blocks" (units defined by the bibliography driver) is stretched out further than usual. With \emergencystretch all spaces are stretched out equally.

  4. Use \RaggedRight of ragged2e for the bibliography, see also Is there a trick to beautify bibliography?.

    \usepackage{ragged2e}
    ...
    \begingroup
    \RaggedRight
    \printbibliography
    \endgroup
    

    "Zuletzt geprüft am:" does not align with the right margin, interword spaces are not enlarged, "22. 06. 2018" is in the next line, overall impression is ragged right/left aligned

    Note that this typesets the bibliography left aligned (in Word speak) and not justified any more. Note how the line ends do not meet with the frame at the margin. It is incidental to this example that the two lines ends seem to line up here, in general that need not and will not be the case.

  5. Load biblatex with the block=ragged option

    Very ragged right

    This is even more radical than \RaggedRight's left alignment.

Full MWE with all solutions present but commented out

\documentclass[
               pagesize,
               usegeometry = on,
               DIV = calc,
               ngerman
              ]{scrartcl}
\usepackage[T1]{fontenc}
\usepackage[
            left = 25mm,
            bottom = 20mm,
            right = 45mm,
            top = 20mm,
            showframe,% to show the frame for the margins
           ]{geometry}
\usepackage[onehalfspacing]{setspace}
\usepackage{
            babel,
            csquotes
           }
\usepackage[
            backend = biber,
            style = ext-authoryear-comp,
            %block=space,% point 2
            %block=ragged,% point 5
           ]{biblatex}

\AfterTOCHead{\singlespacing}
\KOMAoptions{DIV = last}
\AtBeginBibliography{%
  \renewcommand*{\mkbibnamefamily}{\textsc}%
  \renewcommand*{\mkbibnamegiven}{\textsc}%
}

\DeclareFieldFormat{biblabeldate}{#1}
\DeclareDelimFormat[bib]{nameyeardelim}{\addcomma\space}

\DefineBibliographyStrings{german}{
  urlfrom = {verfügbar unter},
  urlseen = {zuletzt geprüft am},
}


\DeclareFieldFormat{url}{\bibstring{urlfrom}\addcolon\space\url{#1}}
\DeclareFieldFormat{urldate}{\mkbibbrackets{\bibstring{urlseen}\addcolon\space#1}}
\renewbibmacro*{url+urldate}{%
  \usebibmacro{urldate}%
  \newunit
  \usebibmacro{url}%
}
\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@ONLINE{Chemie,
  EDITOR   = {{LUMITOS GmbH}},% this is needed to avoid the name being split into given and family parts
  LOCATION = {Berlin},
  URL      = {http://www.chemie.de/lexikon/Kerosin.html},
  TITLE    = {Kerosin},
  URLDATE  = {2018-06-22},
}
\end{filecontents}
\addbibresource{\jobname.bib}


% for breakable date, remove the \iffalse and \fi to test
\iffalse
\DefineBibliographyExtras{german}{%
  \protected\def\mkbibdateshort#1#2#3{%
    \iffieldundef{#3}
      {}
      {\mkdayzeros{\thefield{#3}}\adddot
       \iffieldundef{#2}{}{\addthinspace}}%
    \iffieldundef{#2}
      {}
      {\mkmonthzeros{\thefield{#2}}%
       \iffieldundef{#1}
         {}
         {\iffieldundef{#3}{/}{\adddot\addthinspace}}}%
    \iffieldbibstring{#1}
      {\bibstring{\thefield{#1}}}
      {\dateeraprintpre{#1}\mkyearzeros{\thefield{#1}}}}}
\fi

% point 1
%\usepackage{microtype}

% for point 4
%\usepackage{ragged2e}

\begin{document}
  Text. Text. Text. Text. Text. Text. Text. Text. Text. Text. Text. Text. Text \autocite{Chemie}.

\printbibliography

% point 3
%\begingroup
%\setlength{\emergencystretch}{.5em}
%\printbibliography
%\endgroup

% point 4
%\begingroup
%\RaggedRight
%\printbibliography
%\endgroup
\end{document}

I removed your comments to make mine more visible and show where the % is needed to avoid unwanted space, see What is the use of percent signs (%) at the end of lines?. Note also that I removed the default settings sortlocale=auto and sorting=nyt and that I added the necessary braces for the corporate author "LUMITOS GmbH", see Using a 'corporate author' in the "author" field of a bibliographic entry (spelling out the name in full).

  • 1
    This is a stellar explanation. Can I persuade you to adapt it for TUGboat? A quick perusal of bib-related articles doesn't turn up any good item on "fine tuning". (Send email to tugboat at tug.org .) – barbara beeton Mar 18 at 18:01
  • @barbarabeeton I'd love to. Since the answer here relies on a lot of links, turning it into a proper article will probably take a bit of work and I'm a bit snowed under at the moment, so I unfortunately can't promise anything anytime soon. I will keep it in mind, but feel free to poke me about this again if I forget. – moewe Mar 18 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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