Algorithmcore
Liang's hyphenation algorithm
Also called Knuth-Liang hyphenation, pattern-based hyphenation.
Match all hyphenation patterns of a language against the word, take the largest digit at each gap, and allow a break where it is odd.
- Solves
- Hyphenation
- Time
- O(k l^2) worstΘ(k) best
- Space
- Θ(k) extraO(P) trie
- Where
- P = the total length of the patterns; k = the number of letters of the word; l = the length of the longest pattern
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Franklin Mark Liang, 1983
Liang's hyphenation algorithm decides where a word may be hyphenated from a set of short letter patterns. Each pattern holds a digit in each gap between its letters. The algorithm finds every pattern that occurs in the word, takes the largest digit at each gap, and allows a hyphen where this value is odd. Franklin Liang designed it in 1983 for TeX82, and TeX and many other programs still use it. With about 4500 patterns in a table of about 25K bytes, his English set finds 89 percent of the hyphens of his word list with almost no errors (a measurement on that list).
In plain words
Think of each pattern as a small vote on a few gaps of a word. The pattern "hy3ph" says: when you see the letters h, y, p, h together, the gap between y and p gets a 3. An odd number is a vote for a hyphen and an even number is a vote against it. Larger numbers beat smaller ones, so a later pattern can overrule an earlier rule with an exception.
To hyphenate a word, put a dot at each end, find every pattern that occurs anywhere in it, and write the largest number at each gap. Then put a hyphen at each odd gap that is not too near the ends. A trie of the patterns makes the search fast.
The problem
The input is a word of letters, a set of patterns, and the limits and (\lefthyphenmin and \righthyphenmin; plain TeX uses 2 and 3). A pattern is a string of letters with a digit in each of its gaps; a missing digit is 0. The letter "." stands for the edge of the word, so ".ach4" matches only at the start. The output is the set of positions (, a hyphen before letter ) whose value is odd and with and . The value of a gap is the largest digit that any occurrence of a pattern in ".." places on it, or 0. This is a method for the hyphenation problem.
The algorithm
The patterns are stored in a trie whose node for the letters holds the digits when is a pattern.
LIANG-HYPHENATE(word, trie, λ, ρ)- 1
u ← "." + lowercase(word) + "." - 2
v[0 .. |u|] ← 0 - 3
for i ← 0 to |u| - 1 do ▷ every start position - 4
node ← root of trie - 5
for j ← i to |u| - 1 do - 6
node ← child of node on u[j] - 7
if node = nil then break ▷ no pattern starts with u[i .. j] - 8
if node holds digits d[0 .. j - i + 1] then - 9
for t ← 0 to j - i + 1 do v[i + t] ← max(v[i + t], d[t]) - 10
return the positions p with v[p + 1] odd, λ ≤ p and k - p ≥ ρ
Line L1 adds the edge marks. The outer loop of line L3 tries each start position, and the walk of lines L5 to L7 follows the letters of from there down the trie, so it visits exactly the patterns that occur at , from short to long. It stops as soon as no pattern can be longer. Line L9 raises each gap that the pattern covers to the digit of the pattern. Gap of is the gap before letter of the word, which gives the shift in line L10.
TeX also keeps an exception list, set with \hyphenation; a word in this list gets its listed positions, and the patterns are not used.
Example
The patterns of TeXbook Appendix H are hy3ph, he2n, hena4, hen5at, 1na, n2at, 1tio, 2io and o2n. The word is "hyphenation", so = .hyphenation. The patterns that occur, and the gaps of the word they set (gap is before letter , counting from 0):
| start in | pattern | letters it covers | digits it sets |
|---|---|---|---|
| 1 | hy3ph | h y p h | gap 2 = 3 |
| 4 | he2n | h e n | gap 5 = 2 |
| 4 | hena4 | h e n a | gap 7 = 4 |
| 4 | hen5at | h e n a t | gap 6 = 5 |
| 6 | 1na | n a | gap 5 = 1 |
| 6 | n2at | n a t | gap 6 = 2 |
| 8 | 1tio | t i o | gap 7 = 1 |
| 9 | 2io | i o | gap 8 = 2 |
| 10 | o2n | o n | gap 10 = 2 |
At start 4 the walk visits he, hen, hena and henat in one pass and finds three patterns on the way. The largest digit per gap gives, for the gaps 1 to 10 (before y, p, h, e, n, a, t, i, o, n):
| gap | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| value | 0 | 3 | 0 | 0 | 2 | 5 | 4 | 2 | 0 | 2 |
The odd gaps are 2 and 6, both inside the limits and , so the result is hy-phen-ation. The gap 7 (before "tion") gets 1 from 1tio but 4 from hena4, and the even value wins, so "a-tion" is not allowed. The dictionary has a hyphen there, so this is a miss, the safe kind of mistake. The run takes 33 trie steps for the 13 start positions.
Correctness
The claim is that line L9 leaves in exactly the value of each gap, the largest digit of all patterns that occur in and cover it. The invariant of the inner loop is that, before line L6 at step , node is the trie node of . So the walk from meets every pattern that starts at , and stops only when no pattern can start with . Each update is a maximum with a digit of a real occurrence, so no value is too large, and every occurrence is met, so none is too small. The full proof is in the proof file.
Proof: The trie walk gives the largest digit of every matching patternfull
Claim. Let be a finite set of patterns, each given as a nonempty string of letters (the mark "." counts as a letter) and a list of values in , one per gap. If two entries have the same letters, merge them into one whose values are the maxima, gap by gap. Let be the word with "." at both ends, and for a gap of (, gap is just before ) let
Then lines L1 to L9 stop and leave for every gap . Line L10 then returns exactly the positions of the word with , odd, and , where is the length of the word, is lefthyphenmin and is righthyphenmin.
Setup. The trie has one node for each prefix of the letters of a pattern, the root for the empty prefix. The child of the node for on the letter is the node for , if is a prefix of some pattern. The node for holds the values exactly when is the letters of a pattern. Merging duplicates in add gives the maxima of the claim, so each node holds at most one list.
Lemma (one start). For a fixed start , the inner loop of lines L5 to L9 visits, in order of length, exactly the patterns with , and for each it raises to at least for .
Proof. We show by induction on that, if the loop reaches the step , then before line L6 the variable node is the node for . For , line L4 sets it to the root, the node for the empty string. At step , line L6 moves to the child on . If this child does not exist, no pattern has as a prefix, so no pattern that starts at is longer than , and line L7 stops the loop without missing any. Otherwise the new node is the node for , which proves the step. At the node for , line L8 finds values exactly when is a pattern , and then line L9 applies for . The loop also stops when passes the end of , and no pattern that starts at can be longer than .
Proof of the claim. The array starts at 0 (line L2). Every update of line L9 is a maximum with the value of a pattern that occurs in and covers the gap with , so at all times . Conversely, take an occurrence of at and a gap with . The outer loop (line L3) runs every start from 0 to , and by the lemma the walk from visits and raises to at least . Values only grow. So at the end , and hence .
The code returns , so its entry is , the gap of just before , which is the gap of the word just before its letter . Line L10 keeps the gaps inside the word () whose value is odd and that leave at least letters before and letters after. This is the rule of the claim.
Termination. The outer loop runs times and the inner loop at most times for the start , so there are at most trie steps, and line L9 runs at most times per visited pattern.
Note on the exceptions. When the word is in the exception list, hyphen_positions returns the listed positions and does not use the patterns. This matches the rule of TeX that the \hyphenation list overrides the patterns, and it needs no proof beyond the code.
Complexity
In the word RAM with a child lookup in time (an array per node or a packed trie):
- Time. Line L3 runs times. The walk from is at most as deep as the trie, so it takes at most steps, where is the length of the longest pattern. Line L9 costs at most updates per pattern found, and at most patterns start at each . So the time is trie steps plus updates in the worst case. If no bound on is known, the walk is bounded by and the trie steps by ; the test
test_trie_steps_are_at_most_quadraticchecks this bound. The best case is , when no letter of starts a pattern. Table 5 of Liang lists TeX82 patterns of length at most 8, so for English the cost is linear in with a small constant. - Space. The array takes . The trie takes nodes for patterns of total length .
Properties
- Order free. The value of a gap is a maximum, so the result does not depend on the order of the patterns or of the start positions.
- Exceptions by levels. A pattern with a larger digit overrules all smaller ones on its gap. Odd levels allow and even levels forbid, so the patterns form a list of rules with exceptions and exceptions to exceptions.
- Works on unknown words. The patterns describe parts of words, so they also give results for words that were not in the training list. These results can be wrong.
- Deterministic and static. The result depends only on the word and the patterns.
Variants and improvements
- Automaton search. Build an Aho-Corasick automaton of the patterns. One pass over then reports all occurrences, in time for occurrences. TeX uses the simpler walk, because words are short.
- Packed storage. TeX82 stores the pattern trie as a packed trie with suffix compression, so that each step is one table lookup.
- Several languages. TeX3 keeps one pattern set per language and selects it with \language.
- Breaks that change the spelling. Some pattern libraries for word processors add a way to give a replacement text at a break, for words such as the old German "Zuk-ker" from "Zucker".
- Learning the patterns. The patterns are not written by hand. Hyphenation pattern generation learns them from a hyphenated word list.
When to use it
Use it when the program must hyphenate any word, including words that no list holds, in little space. It needs a pattern set for the language; such sets exist for many languages in the TeX distributions. Use a lookup in a hyphenated word list instead when the words are known in advance and every hyphen must be correct, for example in a fixed glossary. Use a list of exceptions together with the patterns to fix the errors that matter.
Pitfalls
- Missing the edge marks. If line L1 does not add ".", the patterns that start or end with "." never match, and words lose the hyphens that depend on their first or last letters. The patterns of
test_against_brute_force_on_random_patternsinclude edge marks, so this test catches the error. - Stopping at the first pattern. If the walk of line L5 stops when line L8 finds a pattern, it misses the longer patterns at the same start. In the example, it would stop at he2n and miss hena4 and hen5at, and give "hy-phenation".
- Adding or overwriting instead of the maximum. Line L9 must take the maximum. With the last digit or the sum, the result depends on the order of the patterns.
- Off by one in the gaps. Gap of is the gap before letter of the word (line L10). With the hyphens move one letter to the left.
- Applying the limits to . and count letters of the word, not of with its two marks.
- Duplicates. When a pattern set lists the same letters twice, the digits must be merged by the maximum per gap, not replaced.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/liang-hyphenation/. The authors are listed in prov/6YQPVW.jsonl.
"""Liang's hyphenation algorithm, as in TeX82.
A pattern is a string of letters with a digit (0 to 9) in each gap, for
example "hy3ph" or ".ach4". A missing digit is 0. The mark "." stands for
the edge of the word. To hyphenate a word, put "." at both ends, find every
pattern that occurs in it, and at each gap take the largest digit of all
patterns that cover the gap. An odd value allows a hyphen, an even value
forbids it. Then remove the breaks that are too near the ends of the word
(lefthyphenmin and righthyphenmin of TeX).
The patterns are kept in a trie of nested dicts. The page packed-trie gives
the compact table that TeX uses for the same lookup.
"""
from typing import Dict, Iterable, List, Optional, Tuple
def parse_pattern(p: str) -> Tuple[str, List[int]]:
"""Split a pattern into its letters and its gap values.
parse_pattern("hy3ph") == ("hyph", [0, 0, 3, 0, 0]). The list has one
value per gap: before the first letter, between letters, and after the
last letter.
"""
letters: List[str] = []
values: List[int] = [0]
for ch in p:
if ch.isdigit():
values[-1] = int(ch)
else:
letters.append(ch)
values.append(0)
return "".join(letters), values
class PatternTrie:
"""A trie of patterns. Each node is a dict; the key None holds the values."""
def __init__(self, patterns: Iterable[str] = ()) -> None:
self.root: Dict = {}
self.count = 0
for p in patterns:
self.add(p)
def add(self, p: str) -> None:
letters, values = parse_pattern(p)
node = self.root
for ch in letters:
node = node.setdefault(ch, {})
if None in node:
# the same letters twice: keep the larger digit in each gap
node[None] = [max(a, b) for a, b in zip(node[None], values)]
else:
node[None] = values
self.count += 1
def hyphenation_values(word: str, trie: PatternTrie, stats: Optional[dict] = None) -> List[int]:
"""The gap values of the word: v[k] is the value of the gap before word[k].
The list has len(word) + 1 entries; v[0] and v[len(word)] are the gaps
at the edges. If stats is a dict, stats["steps"] counts the trie steps.
"""
w = "." + word.lower() + "." # @line L1
v = [0] * (len(w) + 1) # @line L2
steps = 0
for i in range(len(w)): # @line L3
node = trie.root # @line L4
for j in range(i, len(w)): # @line L5
steps += 1
node = node.get(w[j]) # @line L6
if node is None:
break # @line L7
values = node.get(None)
if values is not None: # @line L8
for t, d in enumerate(values):
if d > v[i + t]:
v[i + t] = d # @line L9
if stats is not None:
stats["steps"] = steps
# gap k of the word (before word[k]) is gap k + 1 of w
return v[1 : len(word) + 2]
def hyphen_positions(
word: str,
trie: PatternTrie,
left: int = 2,
right: int = 3,
exceptions: Optional[Dict[str, List[int]]] = None,
) -> List[int]:
"""The positions k (a hyphen goes before word[k]) that the patterns allow.
left and right are lefthyphenmin and righthyphenmin; plain TeX uses 2
and 3. exceptions maps a lowercase word to its positions, as the
\\hyphenation list of TeX does, and overrides the patterns.
"""
if exceptions is not None and word.lower() in exceptions:
return list(exceptions[word.lower()])
v = hyphenation_values(word, trie)
n = len(word)
return [k for k in range(1, n) if v[k] % 2 == 1 and k >= left and n - k >= right] # @line L10
def hyphenate(word: str, trie: PatternTrie, left: int = 2, right: int = 3, exceptions=None) -> str:
"""The word with "-" at each allowed position, for examples."""
pos = set(hyphen_positions(word, trie, left, right, exceptions))
return "".join(("-" if k in pos else "") + ch for k, ch in enumerate(word))
test_liang_hyphenation.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/liang-hyphenation/. The authors are listed in prov/6YQPVW.jsonl.
import random
from liang_hyphenation import PatternTrie, hyphen_positions, hyphenate, hyphenation_values, parse_pattern
# The nine patterns of the example in The TeXbook, Appendix H.
TEXBOOK = ["hy3ph", "he2n", "hena4", "hen5at", "1na", "n2at", "1tio", "2io", "o2n"]
def brute_force_values(word, patterns):
"""Try every pattern at every start position of .word. and take the maxima."""
w = "." + word.lower() + "."
v = [0] * (len(w) + 1)
for p in patterns:
letters, values = parse_pattern(p)
for i in range(len(w) - len(letters) + 1):
if w[i : i + len(letters)] == letters:
for t, d in enumerate(values):
v[i + t] = max(v[i + t], d)
return v[1 : len(word) + 2]
def test_parse_pattern():
assert parse_pattern("hy3ph") == ("hyph", [0, 0, 3, 0, 0])
assert parse_pattern("1na") == ("na", [1, 0, 0])
assert parse_pattern(".ach4") == (".ach", [0, 0, 0, 0, 4])
assert parse_pattern("hen5at") == ("henat", [0, 0, 0, 5, 0, 0])
def test_texbook_example():
trie = PatternTrie(TEXBOOK)
v = hyphenation_values("hyphenation", trie)
# the values between the letters h y p h e n a t i o n
assert v[1:11] == [0, 3, 0, 0, 2, 5, 4, 2, 0, 2]
assert v[0] == 0 and v[11] == 0
assert hyphen_positions("hyphenation", trie) == [2, 6]
assert hyphenate("hyphenation", trie) == "hy-phen-ation"
assert v == brute_force_values("hyphenation", TEXBOOK)
def test_edge_limits_apply_after_the_patterns():
trie = PatternTrie(TEXBOOK)
# with lefthyphenmin 3 the odd value 3 after "hy" no longer gives a break
assert hyphen_positions("hyphenation", trie, left=3) == [6]
# with righthyphenmin 6 the break before "ation" (5 letters) goes too
assert hyphen_positions("hyphenation", trie, right=6) == [2]
# "nation": 1na gives an odd value before the first letter, which is never a break
assert hyphenation_values("nation", trie)[0] == 1
assert hyphenation_values("nation", trie) == [1, 2, 1, 2, 0, 2, 0]
assert hyphen_positions("nation", trie, left=1, right=1) == [2]
assert hyphenate("nation", trie, left=1, right=1) == "na-tion"
# plain TeX values: righthyphenmin 3 keeps "tion" (4 letters) after the break
assert hyphenate("nation", trie) == "na-tion"
def test_exceptions_override_patterns():
trie = PatternTrie(TEXBOOK)
exc = {"hyphenation": [2, 6, 8]}
assert hyphenate("Hyphenation", trie, exceptions=exc) == "Hy-phen-at-ion"
def test_duplicate_letters_keep_the_larger_digit():
trie = PatternTrie(["a1b", "a3b", "2ab"])
assert trie.count == 1
assert hyphenation_values("ab", trie) == [2, 3, 0]
def random_pattern(rng, alphabet):
k = rng.randint(1, 4)
letters = [rng.choice(alphabet) for _ in range(k)]
if rng.random() < 0.2:
letters[0] = "."
if rng.random() < 0.2 and k > 1:
letters[-1] = "."
out = []
for t in range(k + 1):
if rng.random() < 0.4:
out.append(str(rng.randint(1, 5)))
if t < k:
out.append(letters[t])
return "".join(out)
def test_against_brute_force_on_random_patterns():
rng = random.Random(2024)
alphabet = "abc"
for _ in range(300):
pats = [random_pattern(rng, alphabet) for _ in range(rng.randint(1, 12))]
trie = PatternTrie(pats)
for _ in range(5):
word = "".join(rng.choice(alphabet) for _ in range(rng.randint(1, 9)))
assert hyphenation_values(word, trie) == brute_force_values(word, pats)
def test_trie_steps_are_at_most_quadratic():
trie = PatternTrie(["a1a"] + ["a" * k for k in range(1, 12)])
for k in range(1, 30):
stats = {}
hyphenation_values("a" * k, trie, stats)
n = k + 2
assert stats["steps"] <= n * (n + 1) // 2
History
The first TeX used rules on letter classes and a list of about 300 exceptions, and found about 40 percent of the hyphens of a pocket dictionary with about 1 percent errors (Liang's measurement). Liang, a student of Donald Knuth at Stanford, replaced it with the pattern method and wrote patgen to learn the patterns. His thesis of 1983 reports 4447 distinct patterns for TeX82, in a packed trie of 5943 locations, that find 89.3 percent of the hyphens of his copy of Webster's Pocket Dictionary with essentially no errors. These numbers are measurements on that one word list. The method became part of TeX82 and is described in Appendix H of the TeXbook.
References
- Franklin Mark Liang, Word Hy-phen-a-tion by Com-put-er, PhD thesis, Stanford University, August 1983, report STAN-CS-83-977, Chapter 3 (hyphenation by patterns, the rule of the largest digit) and Table 5 (the TeX82 patterns)
- Donald E. Knuth, The TeXbook, Computers and Typesetting volume A, Addison-Wesley, Appendix H, Hyphenation (the example with hyphenation and the patterns command)
- Donald E. Knuth, TeX: The Program, Computers and Typesetting volume B, Addison-Wesley, 1986, the parts on hyphenation and on the initialization of the pattern memory
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6YQPVW Edit this page History Report an error Markdown