Algorithmcore
Unicode line breaking algorithm
Also called UAX 14, line break opportunities.
Find the positions where a line may or must break, with the ordered rules LB1 to LB31 of UAX 14 on line break classes. A line breaker then picks some of these positions.
- Time
- Θ(n) worst · best
- Space
- Θ(n) extra
- Where
- n = the length of the text in code points
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
The Unicode line breaking algorithm finds the positions in a text where a line may break, and the positions where it must break. It is Unicode Standard Annex 14 (UAX 14). Each code point has a line break class, such as AL for letters, NU for digits, OP for opening punctuation or SP for the space. At each position between two code points, a fixed list of rules is tried in order, and the first rule that matches decides: no break (×), a break opportunity (÷) or a mandatory break (!). The output is a set of break opportunities, not a layout. A line breaker, such as the greedy method or Knuth and Plass, then picks the breaks it takes from this set.
In plain words
When a program wraps text to fit a width, it must know where a line can end. Between two words is usually fine, inside a word is not, and many cases are less clear. A closing bracket must stay with the text before it. A currency sign must stay with its number, and "12.50" must not split at the full stop. A space before a French closing guillemet must not leave the guillemet alone at the start of the next line. In Chinese, a line can break after most characters, but not before a comma. The algorithm gives each character a class and has a long list of rules, each of which says "break here" or "do not break here" for a pattern of classes. The first rule that fits wins. The result is the places where a break is allowed, and those where a new line is required.
The problem
The input is a string of code points with . Each code point has a value of the Line_Break property, from the file LineBreak.txt. The output is the list of positions with at which a break is allowed, each marked as mandatory or not. Position is between and .
The rules have the form "left side, action, right side", for example OP SP* × (rule LB14: no break after an opening bracket, even after spaces) or SP ÷ (rule LB18: break after spaces). The left side is a pattern on the text before the position and the right side a pattern on the text after it. At each position, the rules are tried in the order of their numbers, and the action of the first one whose two sides both match is the answer. Rule LB2 says there is no break at the start of the text, rule LB3 says there is always a break at the end, and rule LB31 (ALL ÷, ÷ ALL) makes a break wherever no earlier rule matched.
Two rules are not of this form. Rule LB1 resolves some classes that the algorithm does not handle directly: AI, SG and XX become AL, CJ becomes NS, and SA (Thai, Lao and other scripts that need a dictionary) becomes CM for marks and AL for the rest. Rules LB9 and LB10 handle combining marks: after LB4 to LB8a, a sequence X (CM | ZWJ)* counts as one character of class X, unless X is BK, CR, LF, NL, SP or ZW, and any CM or ZWJ that remains counts as AL. The rules from LB11 on see these units.
The algorithm
Most rules look at one class on each side of the position. Some look further: LB14, LB15a, LB16 and LB17 skip back over spaces, LB25 matches numbers such as NU (SY | IS)* CL × PO, LB30a counts regional indicators, and LB15c, LB19a, LB20a and LB28a need a code point two places away. All these contexts are either a fixed number of units, or a run of one class that can be found by a single step back.
LINE-BREAKS(s) ▷ s has n >= 1 code points- 1
c[i] <- the class of s[i] after LB1, for i <- 0 to n - 1 - 2
U <- the units of LB9 and LB10; unit[i] <- the unit of s[i] - 3
B <- empty list - 4
for i <- 1 to n - 1 do - 5
if c[i-1] in {BK, LF, NL} or (c[i-1] = CR and c[i] ≠ LF) then append (i, mandatory) to B ▷ LB4, LB5 - 6
else if c[i-1] = CR or c[i] in {BK, CR, LF, NL, SP, ZW} then do nothing ▷ LB5, LB6, LB7 - 7
else if s[0 .. i-1] ends with ZW SP* then append (i, allowed) to B ▷ LB8 - 8
else if c[i-1] = ZWJ or unit[i] = unit[i-1] then do nothing ▷ LB8a, LB9 - 9
else if the first rule of LB11 to LB31 that matches at the unit border unit[i] is ÷ then append (i, allowed) to B - 10
append (n, mandatory) to B; return B
Line L9 is a chain of tests in rule order. Each test looks at the classes of the units and with , and some tests also look at , , , or back over a run of SP, SY or IS units. The implementation keeps the length of the run of RI units that ends at each unit, so LB30a takes constant time. Some rules need more than the class. LB15a and LB15b need the general category (Pi or Pf) of a quotation mark, and LB19a, LB21a and LB30 need the East Asian Width, through the set $EastAsian of the code points with width F, W or H.
Example
Take the text He said « oui » to $(12.50) for well-known goods. The algorithm gives these pieces, with a break opportunity after each one:
He | said | « oui » | to | $(12.50) | for | well- | known | goods.
- After each space, LB18 (
SP ÷) gives a break, and LB7 (× SP) keeps each space with the word before it. - After
«, there is no break. The guillemet U+00AB has class QU and category Pi, and LB15a says(sot | BK | CR | LF | NL | OP | QU | GL | SP | ZW) [\p{Pi}&QU] SP* ×. Before», LB15b gives no break, because U+00BB is QU with category Pf and a space follows it. - In
$(12.50), LB25 givesPR × OP NU, LB14 givesOP ×, LB15d gives× ISbefore the full stop, LB25 givesIS × NUafter it, and LB13 gives× CPbefore the closing parenthesis. - In
well-known, LB21 (× HY) keeps the hyphen withwell, and LB31 allows a break after it. LB20a does not apply, because this hyphen does not start a word. - The end of the text is a mandatory break by LB3.
LineBreakTest.txt has the line × 0073 × 0074 × 0061 × 0072 × 0074 × 0020 ÷ 002E × 0037 × 0038 × 0039 × 0020 ÷ 0065 × 006E × 0064 ÷, that is start .789 end. Here LB15c (SP ÷ IS NU) gives a break before .789, and LB25 keeps .789 together.
Correctness
The rules define the answer: at each position, the action of the first matching rule. The algorithm is correct if, at each position, its chain of tests gives the action of that rule. Lines L5 to L8 test the rules LB4 to LB9 in order, on the code points, as the annex writes them. Each test in line L9 holds exactly when the left and right patterns of its rule match at the unit border, and the tests come in rule order, so the first test that holds belongs to the first rule that matches. The proof checks this for the rules with long contexts. The test file compares the implementation with the lines of LineBreakTest.txt, and with a second implementation that stores each rule as a pair of regular expressions and tries them in order on random strings.
Proof: LINE-BREAKS returns exactly the break opportunities of the rules LB1 to LB31full
Setup. Let with . By UAX 14, the result at a position with is the action of the first rule, in the order LB4 to LB31, whose left side matches a suffix of and whose right side matches a prefix of . The action is ! (mandatory break), ÷ (break allowed) or × (no break). LB2 forbids a break at position 0 and LB3 makes a break at position . The rules work on the classes after LB1, and the rules from LB11 on work on the text as LB9 and LB10 change it. In the patterns, matches only the start of the text and only the end.
Line L1 applies LB1 to each code point, so is the resolved class of . Line L10 adds the mandatory break at of LB3 and adds nothing at 0, as LB2 says.
Claim 1. For , if one of the rules LB4 to LB9 matches at , lines L5 to L8 give the action of the first of them. If none matches, the iteration reaches line L9.
Proof. The rules are LB4 BK !, LB5 CR × LF, CR !, LF !, NL !, LB6 × (BK | CR | LF | NL), LB7 × SP and × ZW, LB8 ZW SP* ÷, LB8a ZWJ ×, and LB9, which gives × between X (CM | ZWJ)* and a following CM or ZWJ when X is not BK, CR, LF, NL, SP or ZW.
- Line L5 holds when is BK, LF or NL, or is CR with LF. These are the cases where LB4 or one of the ! rules of LB5 matches, and no earlier rule matches, because
CR × LFneeds $c[i] = $ LF. So L5 gives !. - If L5 does not hold and $c[i-1] = $ CR, then $c[i] = $ LF and LB5 gives ×. Else, LB6 and LB7 match exactly when is in {BK, CR, LF, NL, SP, ZW}. This is line L6.
- At line L7 no earlier rule matches. The left side
ZW SP*matches a suffix of if and only if the last code point before the run of SP that ends at is ZW. The loop before L7 finds this code point. - At line L8, LB8a matches if $c[i-1] = $ ZWJ. The function that builds the units puts a CM or ZWJ into the unit of exactly when is not BK, CR, LF, NL, SP or ZW. In that case is the end of a sequence
X (CM | ZWJ)*, where X is the first code point of the unit, and X is not of an excluded class: either X has its own class, which is not excluded, or X is a CM or ZWJ that starts a unit and counts as AL. Conversely, if LB9 matches, the code point before the run of CM and ZWJ is a valid X, and every CM or ZWJ of the run, and too, joins its unit. So unit = unit if and only if LB9 matches.
So each of L5 to L8 holds exactly when its rules match and no earlier rule does.
The units. By Claim 1, line L9 runs only where starts a unit. Let be the units and $k = $ unit. LB9 says that each unit counts as its first code point X for the later rules, and LB10 says that a unit that starts with CM or ZWJ counts as AL. The unit records exactly this class, together with the first code point, whose general category and East Asian Width the rules LB15a, LB15b, LB19, LB19a, LB21a, LB28a, LB30 and LB30b read. So the rules LB11 to LB31 at position are the same rules on the string at the border between and .
Claim 2 (runs). Let be a set of classes and a class not in . The left side P Q* matches a suffix of if and only if the unit just before the longest run of units of that ends at has class .
Proof. Let the longest run be . A match P Q* places P at some unit with in . Then because the run is the longest, and because has class and all of are in . So . Conversely, if has class P, the units match.
The function back finds for = {SP} in LB14, LB15a, LB16 and LB17, and for = {SY, IS} in LB25, where LB25 first steps over one CL or CP for the rules NU (SY | IS)* (CL | CP) × (PO | PR). The pattern of LB15a puts a context before the quotation mark, and the test reads it at , or when .
Claim 3 (regional indicators). The left side of LB30a, sot (RI RI)* RI or [^RI] (RI RI)* RI, matches a suffix of if and only if the longest run of RI units that ends at has odd length.
Proof. Both patterns end with an odd run of RI that has a non-RI unit or the start of the text before it, so the run is the longest run. Conversely, a longest run of odd length matches one of the two patterns.
The list ri of the implementation holds the length of the longest run of RI units that ends at each unit, by the recurrence if and are both RI, and or otherwise.
Claim 4. At a unit border that line L9 reaches, rule_break returns the action of the first rule among LB11 to LB31 that matches.
Proof. Each test in rule_break belongs to a rule, the tests come in the order of the rules, and each test returns the action of its rule. Each test holds if and only if both sides of its rule match:
- The tests of one class on each side compare the classes of and , and where the rule says so, the category Pi or Pf, membership in
$EastAsian, U+2010 or U+25CC. - The tests with a fixed context also look at , or , or report no match when the unit does not exist. Where the pattern allows or (LB15a, LB15b, LB19a, LB20a), the test treats a missing unit as a match.
- The tests with runs are correct by Claims 2 and 3.
Some tests cover several rules with the same action, such as the rules of LB25 with ×. Merging rules with the same action that follow each other does not change which action comes first. So the first test that holds gives the action of the first rule that matches. LB31 matches every position, so the function always returns.
By Claims 1 and 4, every position from 1 to gets the action of the first matching rule, and line L10 handles position . The output lists the positions with action ÷ or !, in increasing order, with ! marked as mandatory. This is the result that UAX 14 defines.
Termination. Lines L1 and L2 make one pass over . The loop of L4 runs times. Each step back over a run stops at the start of the text, and each test of rule_break takes a bounded number of steps apart from these runs. So the algorithm stops on every input.
Complexity
Line L1 and line L2 take time. For each position, line L9 makes a constant number of tests, except the steps back over a run of SP, SY or IS units. A step back over spaces happens only at the position after the last space of a run, because positions before a space stop at line L6. A step back over SY or IS units happens only at a position where the next unit is not SY or IS, because LB13 and LB15d decide the positions before them. So each run is walked once from its end, and the total time is . The classes and the units take extra space. A streaming form keeps only a bounded window plus counters for the runs, so it needs space if the output goes out as it is found.
Properties
- The result is a function of the classes, the categories Pi and Pf, and the East Asian Width. It does not depend on fonts, widths or the line length.
- Position is always a mandatory break and position 0 is never a break. The other mandatory breaks are the ends of the lines of the input, such as the positions after a line feed.
- CR LF counts as one hard break, after the LF.
- Spaces stay at the end of a line: there is never a break before a space (LB7), so a break comes after the last space of a run.
- A break never falls inside a sequence
X CM*of a base and its combining marks, except where X is a space or a control (LB9). - Rules from LB11 on look only at the units of LB9 and LB10, so a combining mark is transparent to them.
Variants and improvements
- Older revisions of UAX 14 gave a pair table: for each pair of classes before and after the position, an action, plus special handling for spaces and combining marks. Section 7 of revision 53 now says "Deleted. (Formerly was: Pair Table-Based Implementation)", because several rules need more context than a pair.
- Tailoring is allowed for many rules and classes. Common tailorings resolve AI to ID in an East Asian context, resolve CJ to ID for loose Japanese line breaking, or keep words together in Korean. The CSS properties line-break and word-break select such tailorings.
- For SA scripts (Thai, Lao, Khmer, Myanmar) a real implementation finds the word boundaries with a dictionary, for example with text segmentation by dynamic programming, and adds them as break opportunities.
- Hyphenation adds break opportunities inside words, each with a hyphen and a penalty, for line breakers that use the box, glue and penalty model.
- The rules can be compiled into a regular expression or a state machine over the classes, as for the rules of UAX 29.
When to use it
Use it in every program that wraps Unicode text: editors, terminals, browsers, e-book readers and typesetting systems. It gives the candidate positions, and a line breaker such as the greedy method or Knuth-Plass chooses among them by width. Text inside code or identifiers can need other rules, and dictionary scripts need a word segmenter in addition.
Pitfalls
- The algorithm does not choose line breaks. A program that breaks at every opportunity puts each word on its own line.
- Do not measure the trailing spaces of a line. They stay on the line before the break and do not count for the width in most layouts.
- Without a dictionary, LB1 resolves SA to AL, so a Thai sentence gets no break opportunities between its words and must be cut at the margin by force.
- A combining mark after a space does not attach to the space. By LB10 it counts as AL, and LB18 allows a break between the space and the mark.
- Quotation marks need care. LB19 forbids a break before a QU that is not Pi and after a QU that is not Pf. For the other cases, LB19a forbids the break unless East Asian characters are on both sides of the quotation mark. Code that treats all QU the same gives wrong breaks in Chinese text.
- Apply the rules to the text in logical order, before the bidirectional algorithm reorders each line for display.
- The rules change with each version of Unicode. Revision 53 added LB20a and LB19a. Keep the version of the rules and of LineBreak.txt the same, and run LineBreakTest.txt of that version.
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/unicode-line-breaking-algorithm/. The authors are listed in prov/D4NEZV.jsonl.
"""Line break opportunities by the rules LB1 to LB31 of UAX 14 (Unicode 16.0.0).
The algorithm finds the positions where a line may break and the positions where it
must break. It does not choose the breaks of a paragraph: a line breaker such as the
greedy method or Knuth-Plass picks some of these positions.
The class table is a short subset of LineBreak-16.0.0.txt (Date: 2024-07-29, 16:26:55
GMT). The class values are copied from the file; code points outside the subset get the
default XX of the @missing line, which LB1 resolves to AL. The East Asian width and the
general category (for Pi, Pf and Cn) come from unicodedata.
"""
import bisect
import unicodedata
# (first, last, class) from LineBreak-16.0.0.txt.
_LB_RANGES = [
(0x0009, 0x0009, "BA"), (0x000A, 0x000A, "LF"), (0x000D, 0x000D, "CR"), (0x0020, 0x0020, "SP"),
(0x0021, 0x0021, "EX"), (0x0022, 0x0022, "QU"), (0x0023, 0x0023, "AL"), (0x0024, 0x0024, "PR"),
(0x0025, 0x0025, "PO"), (0x0027, 0x0027, "QU"), (0x0028, 0x0028, "OP"), (0x0029, 0x0029, "CP"),
(0x002B, 0x002B, "PR"), (0x002C, 0x002C, "IS"), (0x002D, 0x002D, "HY"), (0x002E, 0x002E, "IS"),
(0x002F, 0x002F, "SY"), (0x0030, 0x0039, "NU"), (0x003A, 0x003B, "IS"), (0x003F, 0x003F, "EX"),
(0x0041, 0x005A, "AL"), (0x005B, 0x005B, "OP"), (0x005D, 0x005D, "CP"), (0x0061, 0x007A, "AL"),
(0x007B, 0x007B, "OP"), (0x007D, 0x007D, "CL"), (0x00A0, 0x00A0, "GL"), (0x00AB, 0x00AB, "QU"),
(0x00AD, 0x00AD, "BA"), (0x00BB, 0x00BB, "QU"), (0x0100, 0x017F, "AL"), (0x0300, 0x034E, "CM"),
(0x034F, 0x034F, "GL"), (0x0350, 0x035B, "CM"), (0x035C, 0x0362, "GL"), (0x0363, 0x036F, "CM"),
(0x05BE, 0x05BE, "BA"), (0x05D0, 0x05EA, "HL"), (0x0E01, 0x0E30, "SA"), (0x200B, 0x200B, "ZW"),
(0x200D, 0x200D, "ZWJ"), (0x2010, 0x2010, "BA"), (0x2014, 0x2014, "B2"), (0x2018, 0x2019, "QU"),
(0x201B, 0x201D, "QU"), (0x2060, 0x2060, "WJ"), (0x25CC, 0x25CD, "AL"), (0x3000, 0x3000, "BA"),
(0x3001, 0x3002, "CL"), (0x4E00, 0x9FFF, "ID"), (0xAC00, 0xAC00, "H2"), (0xAC01, 0xAC1B, "H3"),
(0xFF08, 0xFF08, "OP"), (0xFF09, 0xFF09, "CL"), (0xFF0C, 0xFF0C, "CL"), (0x1F000, 0x1F02F, "ID"),
(0x1F1E6, 0x1F1FF, "RI"), (0x1F3FB, 0x1F3FF, "EM"), (0x1F466, 0x1F478, "EB"),
(0x1F6CD, 0x1F6D7, "ID"), (0x20000, 0x2A6DF, "ID"),
]
_STARTS = [r[0] for r in _LB_RANGES]
# One line of emoji-data.txt 16.0.0 (Date: 2024-05-01), for rule LB30b:
# 1F005..1F0CE ; Extended_Pictographic
_PICT = [(0x1F005, 0x1F0CE)]
HARD = ("BK", "CR", "LF", "NL")
DOTTED_CIRCLE = "◌"
HYPHEN = "‐"
def line_break_class(c: str) -> str:
"""The Line_Break value of c in the subset, XX if c is not in it."""
cp = ord(c)
k = bisect.bisect_right(_STARTS, cp) - 1
if k >= 0 and _LB_RANGES[k][0] <= cp <= _LB_RANGES[k][1]:
return _LB_RANGES[k][2]
return "XX"
def resolve(c: str, lb=line_break_class) -> str:
"""Rule LB1: resolve AI, SG, XX, SA and CJ."""
v = lb(c)
if v in ("AI", "SG", "XX"):
return "AL"
if v == "SA":
return "CM" if unicodedata.category(c) in ("Mn", "Mc") else "AL"
if v == "CJ":
return "NS"
return v
def east_asian(c: str) -> bool:
"""Membership in $EastAsian: East_Asian_Width F, W or H."""
return unicodedata.east_asian_width(c) in ("F", "W", "H")
def _pict_unassigned(c: str) -> bool:
cp = ord(c)
return any(a <= cp <= b for a, b in _PICT) and unicodedata.category(c) == "Cn"
def units(s: str, c: list) -> tuple:
"""Rules LB9 and LB10. X (CM | ZWJ)* is treated as X when X is not BK, CR, LF, NL, SP
or ZW; any other CM or ZWJ is treated as AL. Return the units as (class, char) and the
unit index of each code point."""
out, unit_of = [], []
for i, ch in enumerate(s):
if c[i] in ("CM", "ZWJ"):
if out and out[-1][0] not in HARD + ("SP", "ZW"):
unit_of.append(len(out) - 1)
continue
out.append(("AL", ch))
else:
out.append((c[i], ch))
unit_of.append(len(out) - 1)
return out, unit_of
def ri_runs(u: list) -> list:
"""r[k] is the number of RI units that end at unit k, so that LB30a takes O(1) time."""
r = []
for k, (cl, _) in enumerate(u):
r.append(r[-1] + 1 if cl == "RI" and k > 0 and u[k - 1][0] == "RI" else int(cl == "RI"))
return r
def rule_break(u: list, k: int, ri: list) -> bool:
"""Rules LB11 to LB31 between the units u[k-1] and u[k]. True means a break.
ri is the list of ri_runs(u)."""
n = len(u)
def cls(j):
return u[j][0] if 0 <= j < n else None
def back(j, skip):
while j >= 0 and u[j][0] in skip:
j -= 1
return j
def cat(j):
return unicodedata.category(u[j][1])
def ea(j):
return east_asian(u[j][1])
def ak(j): # (AK | U+25CC | AS) of LB28a
return 0 <= j < n and (u[j][0] in ("AK", "AS") or u[j][1] == DOTTED_CIRCLE)
a, b = u[k - 1][0], u[k][0]
j = back(k - 1, ("SP",)) # the unit before the spaces that end at k-1
if a == "WJ" or b == "WJ": # LB11
return False
if a == "GL": # LB12
return False
if b == "GL" and a not in ("SP", "BA", "HY"): # LB12a
return False
if b in ("CL", "CP", "EX", "SY"): # LB13
return False
if j >= 0 and u[j][0] == "OP": # LB14
return False
if j >= 0 and u[j][0] == "QU" and cat(j) == "Pi" and \
(j == 0 or cls(j - 1) in HARD + ("OP", "QU", "GL", "SP", "ZW")): # LB15a
return False
if b == "QU" and cat(k) == "Pf" and \
cls(k + 1) in (None, "SP", "GL", "WJ", "CL", "QU", "CP", "EX", "IS", "SY", "ZW") + HARD: # LB15b
return False
if a == "SP" and b == "IS" and cls(k + 1) == "NU": # LB15c
return True
if b == "IS": # LB15d
return False
if b == "NS" and j >= 0 and u[j][0] in ("CL", "CP"): # LB16
return False
if b == "B2" and j >= 0 and u[j][0] == "B2": # LB17
return False
if a == "SP": # LB18
return True
if (b == "QU" and cat(k) != "Pi") or (a == "QU" and cat(k - 1) != "Pf"): # LB19
return False
if b == "QU" and (not ea(k - 1) or k + 1 == n or not ea(k + 1)): # LB19a
return False
if a == "QU" and (not ea(k) or k - 1 == 0 or not ea(k - 2)):
return False
if a == "CB" or b == "CB": # LB20
return True
if (a == "HY" or u[k - 1][1] == HYPHEN) and b == "AL" and \
(k - 1 == 0 or cls(k - 2) in HARD + ("SP", "ZW", "CB", "GL")): # LB20a
return False
if b in ("BA", "HY", "NS") or a == "BB": # LB21
return False
if cls(k - 2) == "HL" and (a == "HY" or (a == "BA" and not ea(k - 1))) and b != "HL": # LB21a
return False
if a == "SY" and b == "HL": # LB21b
return False
if b == "IN": # LB22
return False
if (a in ("AL", "HL") and b == "NU") or (a == "NU" and b in ("AL", "HL")): # LB23
return False
if (a == "PR" and b in ("ID", "EB", "EM")) or (a in ("ID", "EB", "EM") and b == "PO"): # LB23a
return False
if (a in ("PR", "PO") and b in ("AL", "HL")) or (a in ("AL", "HL") and b in ("PR", "PO")): # LB24
return False
# LB25: NU (SY|IS)* (CL|CP)? x (PO|PR), NU (SY|IS)* x NU, (PO|PR) x OP IS? NU,
# (PO|PR|HY|IS) x NU.
m = k - 2 if a in ("CL", "CP") else k - 1
m = back(m, ("SY", "IS"))
if m >= 0 and u[m][0] == "NU" and (b in ("PO", "PR") or (b == "NU" and a not in ("CL", "CP"))):
return False
if a in ("PO", "PR") and b == "OP" and \
(cls(k + 1) == "NU" or (cls(k + 1) == "IS" and cls(k + 2) == "NU")):
return False
if a in ("PO", "PR", "HY", "IS") and b == "NU":
return False
if (a == "JL" and b in ("JL", "JV", "H2", "H3")) or (a in ("JV", "H2") and b in ("JV", "JT")) \
or (a in ("JT", "H3") and b == "JT"): # LB26
return False
if (a in ("JL", "JV", "JT", "H2", "H3") and b == "PO") or \
(a == "PR" and b in ("JL", "JV", "JT", "H2", "H3")): # LB27
return False
if a in ("AL", "HL") and b in ("AL", "HL"): # LB28
return False
if (a == "AP" and ak(k)) or (ak(k - 1) and b in ("VF", "VI")) or \
(a == "VI" and ak(k - 2) and (b == "AK" or u[k][1] == DOTTED_CIRCLE)) or \
(ak(k - 1) and ak(k) and cls(k + 1) == "VF"): # LB28a
return False
if a == "IS" and b in ("AL", "HL"): # LB29
return False
if (a in ("AL", "HL", "NU") and b == "OP" and not ea(k)) or \
(a == "CP" and not ea(k - 1) and b in ("AL", "HL", "NU")): # LB30
return False
if a == "RI" and b == "RI" and ri[k - 1] % 2 == 1: # LB30a
return False
if b == "EM" and (a == "EB" or _pict_unassigned(u[k - 1][1])): # LB30b
return False
return True # LB31
def line_breaks(s: str, lb=line_break_class) -> list:
"""Return (position, mandatory) for every break opportunity, in increasing order.
Position p is between s[p-1] and s[p]. Position 0 is never a break (LB2) and
position len(s) always is (LB3). lb maps a character to its Line_Break value.
"""
n = len(s)
if n == 0:
return []
c = [resolve(ch, lb) for ch in s] # @line L1
u, unit_of = units(s, c) # @line L2
ri = ri_runs(u)
out = [] # @line L3
for i in range(1, n): # @line L4
a, b = c[i - 1], c[i]
if a in ("BK", "LF", "NL") or (a == "CR" and b != "LF"): # @line L5
out.append((i, True))
continue
if a == "CR" or b in HARD + ("SP", "ZW"): # @line L6
continue
j = i - 1
while j >= 0 and c[j] == "SP":
j -= 1
if j >= 0 and c[j] == "ZW": # @line L7
out.append((i, False))
continue
if a == "ZWJ" or unit_of[i] == unit_of[i - 1]: # @line L8
continue
if rule_break(u, unit_of[i], ri): # @line L9
out.append((i, False))
out.append((n, True)) # @line L10
return out
def break_positions(s: str, lb=line_break_class) -> list:
"""The positions of all break opportunities, mandatory or not."""
return [p for p, _ in line_breaks(s, lb)]
def segments(s: str, lb=line_break_class) -> list:
"""Split s at every break opportunity."""
out, prev = [], 0
for p in break_positions(s, lb):
out.append(s[prev:p])
prev = p
return out
test_unicode_line_breaking_algorithm.py 208 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-line-breaking-algorithm/. The authors are listed in prov/D4NEZV.jsonl.
# East Asian width and the general category come from unicodedata (unidata_version 16.0.0
# with Python 3.14). The tests use only characters that are assigned in Unicode 3.2, with
# two exceptions: the emoji code points of the LB30a and LB30b tests, and the unassigned
# U+1F02C of a LineBreakTest line. Their classes come from the table in the implementation.
import random
import re
import unicodedata
from unicode_line_breaking_algorithm import (break_positions, line_break_class, line_breaks,
resolve, segments)
# Lines copied from LineBreakTest-16.0.0.txt (Date: 2024-07-05), without the comments.
CONFORMANCE = [
"× 0076 × 006F × 0075 × 0073 × 0020 ÷ 006D × 0065 × 0020 ÷ 0068 × 0065 × 0075 × 0072 × 0074 × 0065 × 007A × 002C × 0020 ÷ 0076 × 006F × 0075 × 0073 × 0020 ÷ 0064 × 0069 × 0074 × 0065 × 0073 × 0020 × 003A × 0020 ÷ 00AB × 0020 × 0045 × 0078 × 0063 × 0075 × 0073 × 0065 × 007A × 002D ÷ 006D × 006F × 0069 × 002C × 0020 × 00BB × 0020 ÷ 0065 × 0074 × 0020 ÷ 0076 × 006F × 0075 × 0073 × 0020 ÷ 0063 × 0072 × 006F × 0079 × 0065 × 007A × 0020 ÷ 0071 × 0075 × 0065 × 0020 ÷ 0063 × 0065 × 006C × 0061 × 0020 ÷ 0073 × 0075 × 0066 × 0066 × 0069 × 0074 × 0020 × 003F ÷",
"× 006A × 2019 × 0061 × 0069 × 0020 ÷ 0064 × 0069 × 0074 × 0020 × 003A × 0020 ÷ 00AB × 0020 × 0045 × 0078 × 0063 × 0075 × 0073 × 0065 × 007A × 002D ÷ 006D × 006F × 0069 × 002E × 0020 × 00BB × 0020 ÷ 0049 × 006C × 0020 ÷ 006D × 0065 × 0020 ÷ 0073 × 0065 × 006D × 0062 × 006C × 0065 × 0020 ÷ 0064 × 006F × 006E × 0063 × 0020 ÷ 0071 × 0075 × 0065 × 0020 ÷ 0063 × 2019 × 0065 × 0073 × 0074 × 0020 ÷ 0061 × 0073 × 0073 × 0065 × 007A × 002E ÷",
"× 0050 × 0061 × 0073 × 0020 ÷ 0075 × 006E × 0065 × 0020 ÷ 0063 × 0069 × 0074 × 0061 × 0074 × 0069 × 006F × 006E × 0020 ÷ 00BB × 005A × 0069 × 0074 × 0061 × 0074 × 00AB × 0020 ÷ 0050 × 0061 × 0073 × 0020 ÷ 0075 × 006E × 0065 × 0020 ÷ 0063 × 0069 × 0074 × 0061 × 0074 × 0069 × 006F × 006E × 0020 ÷ 006E × 006F × 006E × 0020 ÷ 0070 × 006C × 0075 × 0073 ÷",
"× 00AB × 0020 × 0043 × 0069 × 0074 × 0061 × 0074 × 0069 × 006F × 006E × 0020 × 00BB × 200B ÷ 004B × 0065 × 0069 × 006E × 0020 ÷ 005A × 0069 × 0074 × 0061 × 0074 × 200B ÷ 00AB × 0020 × 0041 × 0075 × 0074 × 0072 × 0065 × 0020 ÷ 0063 × 0069 × 0074 × 0061 × 0074 × 0069 × 006F × 006E × 0020 × 00BB ÷",
"× 0073 × 0074 × 0061 × 0072 × 0074 × 0020 ÷ 002E × 0037 × 0038 × 0039 × 0020 ÷ 0065 × 006E × 0064 ÷",
"× 0074 × 0068 × 0065 × 0020 ÷ 0033 × 006D × 0073 × 0020 ÷ 0070 × 006F × 0073 × 0073 × 0065 × 0073 × 0073 × 0069 × 0076 × 0065 × 0020 ÷ 0070 × 0072 × 006F × 006E × 006F × 006D × 0069 × 006E × 0061 × 006C × 0020 ÷ 0073 × 0075 × 0066 × 0066 × 0069 × 0078 × 0020 ÷ 0028 × 0020 × 002D × 0161 × 0075 × 0020 × 0029 ÷",
"× 004D × 0061 × 0063 × 0020 ÷ 0050 × 0072 × 006F × 0020 ÷ 002D × 0074 × 0069 × 0065 × 0074 × 006F × 006B × 006F × 006E × 0065 ÷",
"× 6BD5 ÷ 58EB ÷ 608C ÷ FF08 × 0031 × 0039 × 0030 × 0031 ÷ 5E74 ÷ 2014 ÷ 0031 × 0039 × 0033 × 0036 ÷ 5E74 × FF09 × FF0C ÷ 671D ÷ 9C9C ÷ 7C4D ÷ 7EA2 ÷ 519B ÷ 5C06 ÷ 9886 ÷",
"× 1F02C × 1F3FF ÷",
]
def parse_test_line(line):
tokens = line.split()
assert tokens[0] == "×"
text, breaks = [], []
for k in range(1, len(tokens), 2):
text.append(chr(int(tokens[k], 16)))
if tokens[k + 1] == "÷":
breaks.append(len(text))
return "".join(text), breaks
def test_conformance_lines():
for line in CONFORMANCE:
s, expected = parse_test_line(line)
assert break_positions(s) == expected, line
def test_class_table_and_lb1():
assert line_break_class("a") == "AL" and line_break_class(",") == "IS"
assert line_break_class("Ω") == "XX" and resolve("Ω") == "AL"
assert line_break_class("ก") == "SA" and resolve("ก") == "AL"
assert line_break_class("́") == "CM" and line_break_class("א") == "HL"
def test_mandatory_breaks_and_crlf():
assert line_breaks("a\r\nb") == [(3, True), (4, True)]
assert line_breaks("a\rb\nc") == [(2, True), (4, True), (5, True)]
assert line_breaks("ab") == [(2, True)]
assert line_breaks("") == []
def test_small_rules():
assert segments("one two") == ["one ", "two"] # LB7 and LB18
assert segments("a b") == ["a ", "b"] # LB7: no break before a space
assert segments("abcd") == ["ab", "cd"] # LB8
assert segments("a b") == ["a b"] # LB12
assert segments("ab") == ["ab"] # LB11
assert segments("( a)") == ["( a)"] # LB14 and LB13
assert segments("well-known") == ["well-", "known"] # LB21 then a break after HY
assert segments("-5") == ["-5"] # LB25 HY x NU
assert segments("$(12.50)%") == ["$(12.50)%"] # LB25
assert segments("一丁") == ["一", "丁"] # LB31 between ideographs
assert segments("一、丁") == ["一、", "丁"] # LB13 before CL
assert segments("áb") == ["áb"] # LB9
assert segments(" ́a") == [" ", "́a"] # LB10 then LB18
assert segments("\U0001F1E6\U0001F1E6\U0001F1E6") == ["\U0001F1E6\U0001F1E6", "\U0001F1E6"] # LB30a
assert segments("\U0001F466\U0001F3FB") == ["\U0001F466\U0001F3FB"] # LB30b
assert segments("א־a") == ["א־a"] # LB21a
assert segments("א־ב") == ["א־", "ב"] # LB21a does not hold before HL
# A second implementation: each rule is data, a regular expression for the left side and
# one for the right side, tried in order on a token string.
FLAGS = "ifedhn"
def _flags(ch):
cat = unicodedata.category(ch)
return "".join([
"i" if cat == "Pi" else "-",
"f" if cat == "Pf" else "-",
"e" if unicodedata.east_asian_width(ch) in ("F", "W", "H") else "-",
"d" if ch == "◌" else "-",
"h" if ch == "‐" else "-",
# [\p{ExtPict}&\p{Cn}]: emoji-data.txt 16.0.0 has 1F005..1F0CE ; Extended_Pictographic.
"n" if 0x1F005 <= ord(ch) <= 0x1F0CE and cat == "Cn" else "-",
])
def T(*classes, **flag):
pat = "".join(flag.get(f, ".") for f in FLAGS)
name = "(?:%s)" % "|".join(classes) if classes else "[A-Z0-9]+"
return "<%s\\.%s>" % (name, pat)
def NOT(*classes):
return "<(?!(?:%s)\\.)[A-Z0-9]+\\.[^>]*>" % "|".join(classes)
def ANYOF(*pats):
return "(?:%s)" % "|".join(pats)
ANY = T()
HARD = ("BK", "CR", "LF", "NL")
SPS = "(?:%s)*" % T("SP")
NUM = T("NU") + "(?:%s)*" % T("SY", "IS")
AKD = ANYOF(T("AK", "AS"), T(d="d"))
X, B, M = "x", "b", "m"
RAW_RULES = [
(T("BK"), ANY, M), (T("CR"), T("LF"), X), (T("CR"), ANY, M), (T("LF", "NL"), ANY, M),
(ANY, T(*HARD), X), (ANY, T("SP", "ZW"), X), (T("ZW") + SPS, ANY, B), (T("ZWJ"), ANY, X),
(NOT(*HARD, "SP", "ZW") + "(?:%s)*" % T("CM", "ZWJ"), T("CM", "ZWJ"), X),
]
RULES = [
(ANY, T("WJ"), X), (T("WJ"), ANY, X), (T("GL"), ANY, X), (NOT("SP", "BA", "HY"), T("GL"), X),
(ANY, T("CL", "CP", "EX", "SY"), X), (T("OP") + SPS, ANY, X),
(ANYOF("^", T(*HARD, "OP", "QU", "GL", "SP", "ZW")) + T("QU", i="i") + SPS, ANY, X),
(ANY, T("QU", f="f") + ANYOF(T("SP", "GL", "WJ", "CL", "QU", "CP", "EX", "IS", "SY", *HARD, "ZW"), "$"), X),
(T("SP"), T("IS") + T("NU"), B), (ANY, T("IS"), X), (T("CL", "CP") + SPS, T("NS"), X),
(T("B2") + SPS, T("B2"), X), (T("SP"), ANY, B),
(ANY, T("QU", i="-"), X), (T("QU", f="-"), ANY, X),
(T(e="-"), T("QU"), X), (ANY, T("QU") + ANYOF(T(e="-"), "$"), X), (T("QU"), T(e="-"), X),
(ANYOF("^", T(e="-")) + T("QU"), ANY, X),
(ANY, T("CB"), B), (T("CB"), ANY, B),
(ANYOF("^", T(*HARD, "SP", "ZW", "CB", "GL")) + ANYOF(T("HY"), T(h="h")), T("AL"), X),
(ANY, T("BA", "HY", "NS"), X), (T("BB"), ANY, X),
(T("HL") + ANYOF(T("HY"), T("BA", e="-")), NOT("HL"), X), (T("SY"), T("HL"), X),
(ANY, T("IN"), X),
(T("AL", "HL"), T("NU"), X), (T("NU"), T("AL", "HL"), X),
(T("PR"), T("ID", "EB", "EM"), X), (T("ID", "EB", "EM"), T("PO"), X),
(T("PR", "PO"), T("AL", "HL"), X), (T("AL", "HL"), T("PR", "PO"), X),
(NUM + T("CL", "CP"), T("PO", "PR"), X), (NUM, T("PO", "PR"), X),
(T("PO", "PR"), T("OP") + T("NU"), X), (T("PO", "PR"), T("OP") + T("IS") + T("NU"), X),
(T("PO", "PR", "HY", "IS"), T("NU"), X), (NUM, T("NU"), X),
(T("JL"), T("JL", "JV", "H2", "H3"), X), (T("JV", "H2"), T("JV", "JT"), X), (T("JT", "H3"), T("JT"), X),
(T("JL", "JV", "JT", "H2", "H3"), T("PO"), X), (T("PR"), T("JL", "JV", "JT", "H2", "H3"), X),
(T("AL", "HL"), T("AL", "HL"), X),
(T("AP"), AKD, X), (AKD, T("VF", "VI"), X), (AKD + T("VI"), ANYOF(T("AK"), T(d="d")), X),
(AKD, AKD + T("VF"), X),
(T("IS"), T("AL", "HL"), X),
(T("AL", "HL", "NU"), T("OP", e="-"), X), (T("CP", e="-"), T("AL", "HL", "NU"), X),
(ANYOF("^", NOT("RI")) + "(?:%s%s)*" % (T("RI"), T("RI")) + T("RI"), T("RI"), X),
(T("EB"), T("EM"), X), (T(n="n"), T("EM"), X),
]
def _apply(rules, left, right):
for lpat, rpat, action in rules:
if re.search("(?:%s)$" % lpat, left) and re.match(rpat, right):
return action
return None
def reference_breaks(s, lb=line_break_class):
raw = [resolve(ch, lb) for ch in s]
tok = ["<%s.%s>" % (c, _flags(ch)) for c, ch in zip(raw, s)]
# LB9 and LB10, written from the rule text: a CM or ZWJ joins the previous code point
# unless that one is BK, CR, LF, NL, SP or ZW.
unit_tok, start = [], []
for i, c in enumerate(raw):
if c in ("CM", "ZWJ") and i > 0 and raw[i - 1] not in HARD + ("SP", "ZW"):
continue
unit_tok.append(tok[i] if c not in ("CM", "ZWJ") else "<AL.%s>" % _flags(s[i]))
start.append(i)
out = []
for p in range(1, len(s)):
act = _apply(RAW_RULES, "".join(tok[:p]), "".join(tok[p:]))
if act is None:
k = start.index(p)
act = _apply(RULES, "".join(unit_tok[:k]), "".join(unit_tok[k:])) or B
if act != X:
out.append((p, act == M))
return out + [(len(s), True)] if s else []
MADE_UP = {"B": "BB", "C": "CB", "I": "IN", "N": "NS", "K": "BK", "L": "NL", "J": "JL",
"V": "JV", "T": "JT", "k": "AK", "p": "AP", "s": "AS", "f": "VF", "v": "VI",
"E": "EB", "M": "EM", "R": "RI", "S": "SY", "H": "HL"}
def made_up_classes(c):
return MADE_UP.get(c) or line_break_class(c)
def test_against_rule_table_reference():
rng = random.Random(1414)
real = ("a1 ()}!?,./-$%+\"'«»‘’“” ́"
"‐" + chr(0x2014) + "א־一、 ()가각◌"
"\n\r\tกΑ")
alphabet = real + "".join(MADE_UP)
for _ in range(700):
s = "".join(rng.choice(alphabet) for _ in range(rng.randint(1, 9)))
assert line_breaks(s, made_up_classes) == reference_breaks(s, made_up_classes), repr(s)
def test_reference_agrees_on_conformance_lines():
for line in CONFORMANCE:
s, expected = parse_test_line(line)
assert [p for p, _ in reference_breaks(s)] == expected
History
UAX 14 was published in 1999 with Unicode 3.0.0. The annex says that it started with 29 line break classes and 23 rules that could be written as a pair table, with some special handling for combining marks and spaces. Now it has 48 classes and more than 40 rules, and many of them use a context that can be several characters away from the position. In Unicode 5.0 the rules were renumbered to reduce the number of letter suffixes on the rule numbers. Revision 53, for Unicode 16.0.0, added LB20a to keep a word-initial hyphen with its word, and changed LB19 and added LB19a for quotation marks in Simplified Chinese.
References
- Robin Leroy (editor), Unicode Standard Annex 14, Unicode Line Breaking Algorithm, revision 53, 2024-09-02, Sections 5 (Line Breaking Properties), 6.1 and 6.2 (the rules LB1 to LB31), 10 (Testing), 11 (History) and Modifications
- LineBreak-16.0.0.txt, Unicode Character Database, the Line_Break property of each code point
- LineBreakTest-16.0.0.txt, Unicode Character Database, the conformance test lines
- emoji-data-16.0.0.txt, Unicode Character Database, the Extended_Pictographic property (rule LB30b)
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 D4NEZV Edit this page History Report an error Markdown