Steering browser line breaks with invisible characters

Vincent Bernat

Good ty­pog­ra­phy is dif­fi­cult to achieve on the web. Com­pared to type­set­ting en­gines like LaTeX or Typst, the web still lacks a good line-break­ing al­go­rithm. The CSS di­rec­tive text-wrap: pretty tries to im­prove the sit­u­a­tion but is still not im­ple­mented in Fire­fox and pro­duces eerie nar­rower para­graphs with Sa­fari. Var­i­ous good im­ple­men­ta­tions of the Knuth-Plass al­go­rithm ex­ist in Java­Script, but they ei­ther re­flow the text or de­lay its dis­play. In­stead, I taught my static site gen­er­a­tor to man­u­ally in­sert soft hy­phens and non-break­ing spa­ces at tac­ti­cal lo­ca­tions to achieve a pre­dictable, okay­ish result.

🎟️ Spe­cial time-lim­ited offer

The ar­ti­cles on this blog are flushed left and ragged right, but for this one, you can change how the para­graphs are set:

  • ;
  • , , or ;
  • (as your browser does not sup­port it, it shouldn’t change anything).

Comparison with existing solutions#

Let’s bench­mark with a short para­graph in French from Jules Verne’s “L’Île mys­té­rieuse”:

Le ma­rin pressa la main du re­por­ter, dont il ne pou­vait se faire en­tendre, et d’une fa­çon qui si­gni­fiait : « At­ten­dez ! » puis, il ren­tra dans le cou­loir. Un ins­tant après, il res­sor­tait avec un fa­got al­lumé, il le pro­je­tait dans les té­nèbres, et il pous­sait des sif­fle­ments aigus.

The an­i­ma­tions be­low show the ren­dered lay­out for the three main web en­gines.1 Hover the an­i­ma­tions and they will pause. Move the mouse near the ver­ti­cal red bars to ad­just the para­graph widths. En­able or dis­able CSS di­rec­tives with the check­boxes below.

The im­ages be­low show the ren­dered lay­out for the three main web en­gines. You need Java­Script to an­i­mate the para­graph widths and com­pare the ef­fects of the var­i­ous features.

Let’s try Fire­fox 160 first. The most no­table “de­fect” for this para­graph is the word “ai­gus”: it may stay alone on the last line—or even be hy­phen­ated. This is a “runt.”2 With hy­phen­ation dis­abled, runts are rarer, but the lay­out in­tro­duces “bad rags”: a large blank space be­tween the end of a line and the right mar­gin, like in the sec­ond line when the para­graph width is 825 pix­els. When the para­graph is jus­ti­fied, bad rags are trans­lated into larger spa­ces be­tween words. These traits make your text look poor and should be avoided.3

🖼 Line-breaking in Firefox 160

Un­like Fire­fox, Chromium 157 im­ple­ments text-wrap: pretty. It ad­justs para­graphs end­ing with a word alone on the last line by ad­just­ing the break points for the last four lines to hold two last words to­gether, like “sif­fle­ments ai­gus” in our example.

🖼 Line-breaking in Chromium 157

Like Fire­fox, Web­Kit­GTK 2.544 may hy­phen­ate “ai­gus,” leav­ing a very short runt on the last line. With text-wrap: pretty and with­out jus­ti­fi­ca­tion, it of­ten cre­ates shorter para­graphs. When en­abling both pretty wrap­ping and jus­ti­fi­ca­tion, Web­Kit­GTK per­forms worse than any other browser in this ex­am­ple as it in­serts too much space.

🖼 Line-breaking in WebKitGTK 2.54

My so­lu­tion is to in­sert soft hy­phens (U+00AD), ex­cept near the end of the para­graph, and to in­sert non-break­ing spa­ces (U+00A0) to meet the min­i­mal re­quire­ment to pre­vent a runt. In my case, I set the limit to 8 char­ac­ters, punc­tu­a­tion included.

The an­i­ma­tion be­low marks each non-break­ing space with a pur­ple tri­an­gle and ev­ery soft hy­phen with a ver­ti­cal red line.5 With hyphens: manual, the browser may in­sert a line break any­where a soft hy­phen is present.

🖼 Line-breaking in Firefox 160 with preprocessed text

Such an ap­proach can­not match a proper line-break­ing al­go­rithm, but it works in Fire­fox, pre­vents the short­ened para­graphs in Sa­fari, and some­times pro­vides bet­ter re­sults than what Chromium did, as it al­lows hy­phen­ation of “sif‐fle‐ments.” More­over, all browsers will break lines at the same places: with hyphens: auto, each browser uses its own hy­phen­ation dic­tio­nary and Sa­fari ig­nores hyphenate-limit-chars, while the spec­i­fi­ca­tion for text-wrap: pretty leaves the al­go­rithm to each browser.

Implementation#

My cus­tom static site gen­er­a­tor in­cludes a step to al­ter HTML files: add a ta­ble of con­tents, turn foot­notes to side­notes, add links for the print ver­sion, in­clude the script and CSS files re­quired to ren­der the page, etc. This looks like a good place to fix the HTML code to hy­phen­ate words and in­sert non-break­ing spaces.

I also add a bit of ty­po­graphic sugar: I con­vert the straight sin­gle quotes '…' and dou­ble quotes "…" to their curly equiv­a­lents: ‘…’ and “…”; I turn an el­lip­sis ... into its ded­i­cated equiv­a­lent …; I add a nar­row non-break­ing space be­fore a dou­ble punc­tu­a­tion or be­tween two groups of dig­its in French, like in “Ça fait donc 501 622 731.”

We could im­ple­ment these trans­for­ma­tions with reg­u­lar ex­pres­sions and a hy­phen­ation li­brary like Pyphen:

NNBSP = "\u202f" # NARROW NO-BREAK SPACE
SHY = "\u00ad"   # SOFT HYPHEN
NBSP = "\u00a0"  # NO-BREAK SPACE

opening_quote = re.compile(r"""(?<![^\s(\[{])(['"])(?!\s)""")
closing_quote = re.compile(r"""(?<=[^\s(\[{])(['"])""")
space_before_punct = re.compile(r"\s([:;!?%»])")
space_after_punct = re.compile(r"«\s")
last_chars = re.compile(r"(?:[^\s\xad][\s\xad]*){1,8}$")
word = re.compile(r"\w+")

def typography(text: str, lang: str) -> str:
    r"""Apply typographic rules to text.

    >>> typography('"Don\'t panic," he said.', "en_US")
    '“Don’t panic,”\xa0he\xa0said.'
    >>> typography("« Attendez ! »", "fr")
    '«\u202fAt\xadtendez\u202f!\u202f»'
    """
    text = opening_quote.sub(lambda m: "‘" if m[1] == "'" else "“", text)
    text = closing_quote.sub(lambda m: "’" if m[1] == "'" else "”", text)
    text = space_before_punct.sub(NNBSP + r"\1", text)
    text = space_after_punct.sub("«" + NNBSP, text)
    text = text.replace("...", "…")
    # Hyphenation
    hyphenator = pyphen.Pyphen(lang=lang, left=2, right=3)
    text = word.sub(lambda m: hyphenator.inserted(m[0], SHY), text)
    # No line break in the last 8 characters
    text = last_chars.sub(
        lambda m: m[0].replace(SHY, "").replace(" ", NBSP), text
    )
    return text

How­ever, it breaks if we have HTML tags in the middle:

<p>I have read "<a href="https://en.wikipedia.org/wiki/Dune_(novel)">Dune</a>".</p>

The naive reg­u­lar ex­pres­sion trans­forms the quotes of the href at­tribute. If we ap­ply the reg­u­lar ex­pres­sion to each text node, we get I have read “Dune“.

Dealing with HTML#

While we could tune the reg­u­lar ex­pres­sions, this ap­proach is quite frag­ile. We need to ap­ply the trans­for­ma­tions to the plain text and stitch the HTML markup back into the re­sult. I use the lxml li­brary to parse and ma­nip­u­late HTML. It­er­at­ing over each block and ex­tract­ing the text is straight­for­ward, but we lose all the in­ner markup:

for block in root.iter("p", "li", "h1", "h2", "h3"):
    text = typography("".join(block.itertext()), "en_US")

In­stead, we need to keep track of the po­si­tion of each group of let­ters in a depth-first walk of the HTML tree. For ex­am­ple, we split the text from the pre­vi­ous HTML spec­i­men into three slots:

slots = [
    ["p.text", 0, 'I have read "'],
    ["a.text", 13, "Dune"],
    ["a.tail", 17, '".'],
]
text = "".join(slot[2] for slot in slots)

We trans­late mod­i­fi­ca­tions to the text into a list of sub­sti­tu­tions: start po­si­tion, end po­si­tion, and new text.

changes = []
for m in opening_quote.finditer(text):
    start, end = m.span(1)
    changes.append((start, end, "‘" if m[1] == "'" else "“"))
for m in closing_quote.finditer(text):
    start, end = m.span(1)
    changes.append((start, end, "’" if m[1] == "'" else "”"))
# changes = [(12, 13, "“"), (17, 18, "”")]

To ap­ply a sub­sti­tu­tion, we lo­cate the slot it ap­plies to and up­date the text.6

for start, end, new in changes:
    slot = next(slot for slot in reversed(slots) if slot[1] <= start)
    offset = start - slot[1]
    slot[2] = slot[2][:offset] + new + slot[2][offset + end - start :]
# slots = [["p.text", 0, "I have read “"],
#  ["a.text", 13, "Dune"], 
#  ["a.tail", 17, "”."]]

We can stitch the mod­i­fi­ca­tions back into the HTML tree with a sec­ond depth-first walk, amend­ing the text nodes when they are dif­fer­ent from what we recorded in the slots.

Faster with Cython#

For this task, Python is not the fastest lan­guage on this side of the gal­axy.7 But we can sig­nif­i­cantly speed up some parts of the code with Cython, a com­piler to turn Python code into C ex­tensions.

I con­verted the reg­u­lar ex­pres­sions to hand-writ­ten loops, stole the Liang hy­phen­ation al­go­rithm from Pyphen, and moved them to Cython us­ing the pure Python syn­tax along with the code keep­ing track of the HTML struc­ture. As a re­sult, the code is four times faster! 🚀

Inline code#

I han­dle in­line code a bit dif­fer­ently: I in­sert zero-width spa­ces be­fore some mark­ers: ., _, /, =, and :. This lets the browser split a long IPv6 ad­dress, like 2a01:​e0e:​c03c:​f44e:​dabc:​7337:38fa:​ff40, or a Python method name, like xxhash.​xxh3_128_​hexdigest(), at those mark­ers. As far as I know, this is not some­thing pos­si­ble with just CSS.

Copy/paste#

When copy­ing text, some browsers may keep the soft hy­phens or zero-width spa­ces. This is an­noy­ing when past­ing into a ter­mi­nal. We can in­ter­cept the “copy” event and strip these spe­cial char­ac­ters from the text/​plain ver­sion recorded in the clipboard:

document.addEventListener("copy", (event) => {
  const selection = document.getSelection();
  const raw = selection.toString();
  const text = raw
    // SOFT HYPHEN, ZERO WIDTH SPACE
    .replace(/[\u00ad\u200b]/g, "")
    // NO-BREAK SPACE, NARROW NO-BREAK SPACE
    .replace(/[\u00a0\u202f]/g, " ");
  if (text === raw) return;
  const div = document.createElement("div");
  for (let i = 0; i < selection.rangeCount; i++)
    div.appendChild(selection.getRangeAt(i).cloneContents());
  event.clipboardData.setData("text/plain", text);
  event.clipboardData.setData("text/html", div.innerHTML);
  event.preventDefault();
});

Soft hy­phens don’t in­ter­fere with other fea­tures, like browsers’ find-in-page or in­dex­ing by Pagefind.

Is it worth it?#

As with ver­ti­cal rhythm, no one would no­tice this small ar­range­ment if it weren’t for this ar­ti­cle. But, you know what? I no­tice it, and it makes me happy. So I’ll keep spend­ing time on point­less stuff like this be­cause it soothes me. 🍃

I have never been as self-conscious about my handwriting as when I was inking
in the caption for this comic.
xkcd: Kerning

Note

Maytham Al­su­dany re­viewed a first draft of this ar­ti­cle. Any er­rors are still mine!