Algorithm Search⌘K

Algorithmcore

Unicode text segmentation

Also called UAX 29, grapheme cluster boundaries, Unicode word boundaries.

Find grapheme cluster, word and sentence boundaries with the ordered rules of UAX 29 on break properties. Some rules look at long contexts on both sides of a position.

Time
Θ(n) worst · best
Space
Θ(1) extra
Where
n = the length of the text in code points
Properties
deterministicofflineiterative

Unicode text segmentation finds the boundaries of grapheme clusters, words and sentences in a string of code points, with the rules of Unicode Standard Annex 29 (UAX 29). Each code point has a break property, such as GCB=Extend for a combining mark or WB=Numeric for a digit. At each position between two code points, a fixed list of rules is tried in order, and the first rule that matches says boundary or no boundary. This is a rule system over character properties. It is a different problem from text segmentation by dynamic programming, which splits a text without spaces into dictionary words. UAX 29 uses no dictionary, so its default word rules do not split Thai or Chinese into words.

In plain words

A program must often cut text into pieces: the characters that a cursor moves over, the words that a double click selects, the sentences that a reader sees. In English, spaces and full stops do most of the work, but they are not enough. An accent can be a separate code point that must stay with its letter. A flag is two code points. "3.14" is one word, but "end.Next" is not one word. A full stop after "Mr" is not always the end of a sentence.

Unicode gives each character a few labels. For each kind of piece, it gives an ordered list of rules. Each rule looks at the labels on both sides of a gap and says "cut" or "do not cut". At each gap, the first rule that fits decides. Some rules look a long way back, for example to count flag letters.

The problem

The input is a string ss of nn code points. A boundary is a position bb with 0≤b≤n0 \le b \le n, the place between s[b−1]s[b-1] and s[b]s[b]. The output, for each of the three kinds of segments, is the sorted list of boundaries. Position 0 and position nn are always boundaries of a non-empty string (rules GB1 and GB2, WB1 and WB2, SB1 and SB2).

The properties are Grapheme_Cluster_Break (GCB), Word_Break (WB) and Sentence_Break (SB), from the files GraphemeBreakProperty.txt, WordBreakProperty.txt and SentenceBreakProperty.txt, plus Indic_Conjunct_Break (InCB) and Extended_Pictographic (ExtPict). Each rule has the form "left × right" or "left ÷ right", where left and right are regular expressions over property values. The left side must match a suffix of s[0…b−1]s[0 \ldots b-1] and the right side a prefix of s[b…n−1]s[b \ldots n-1]. The rule numbers give the order, and the first rule that matches at bb decides. A short summary of the three lists:

  • Grapheme clusters, GB1 to GB999. No boundary inside CR LF (GB3), boundaries around other controls (GB4, GB5), none inside Hangul syllables (GB6 to GB8), none before Extend, ZWJ and SpacingMark or after Prepend (GB9, GB9a, GB9b), none inside Indic conjuncts (GB9c), none inside emoji ZWJ sequences (GB11), and regional indicators in pairs (GB12, GB13). The extended grapheme cluster page lists them in full.
  • Words, WB1 to WB999. WB4 says that Extend, Format and ZWJ are ignored after any code point except sot, CR, LF and Newline: the rule "X (Extend | Format | ZWJ)* → X" makes the rest of the rules see the sequence without them. Then letters stay together (WB5), letters stay together across one MidLetter or MidNumLetQ such as the apostrophe in "can't" (WB6, WB7), digits stay together across one MidNum or MidNumLetQ such as "3.14" (WB11, WB12), letters and digits stay together (WB8 to WB10), and so on. Here AHLetter = (ALetter | Hebrew_Letter) and MidNumLetQ = (MidNumLet | Single_Quote).
  • Sentences, SB1 to SB998. SB4 puts a boundary after each paragraph separator, SB5 ignores Extend and Format, and the main rules are about terminators: ATerm is the full stop, STerm the other terminators. SB8 says "ATerm Close* Sp* × (¬(OLetter | Upper | Lower | ParaSep | SATerm))* Lower": no boundary after a full stop if the next letter is lowercase. SB11 says "SATerm Close* Sp* ParaSep? ÷": otherwise a boundary after the terminator, its closing punctuation and its spaces. The last rule SB998 is "Any × Any", so a sentence boundary is the exception.

Several rules are not pairwise. GB9c, GB11 and GB12 look an unbounded way to the left, WB6 and WB12 look one code point to the right past the next one, and SB8 looks an unbounded way to the right.

The algorithm

The rules are evaluated at each position from left to right. A direct evaluation of the left-hand regular expressions at each position would cost O(n)O(n) per position. Instead, the algorithm keeps a few counters and flags that summarize the text to the left, in the spirit of the state machines of UAX 29 section 6.3. For grapheme clusters three are enough: the number riri of regional indicators that end at the position, a flag pictpict that says whether the text ends with ExtPict Extend* before the last code point, and the state conjconj of the conjunct rule GB9c.

  1. GRAPHEME-BOUNDARIES(s) ▷ s has n >= 1 code points
  2. 1B <- [0]; ri <- 0; ep <- false; pict <- false; conj <- none
  3. 2for i <- 1 to n - 1 do
  4. 3a <- GCB(s[i-1]); b <- GCB(s[i])
  5. 4update pict, ep, ri and conj with s[i-1] ▷ see the rules below
  6. 5if a = CR and b = LF then x <- false ▷ GB3
  7. 6else if a or b is in {Control, CR, LF} then x <- true ▷ GB4, GB5
  8. 7else if (a, b) is a Hangul pair of GB6, GB7 or GB8 then x <- false
  9. 8else if b in {Extend, ZWJ, SpacingMark} or a = Prepend then x <- false ▷ GB9, GB9a, GB9b
  10. 9else if conj = linked and InCB(s[i]) = Consonant then x <- false ▷ GB9c
  11. 10else if pict and a = ZWJ and ExtPict(s[i]) then x <- false ▷ GB11
  12. 11else if a = b = RI and ri is odd then x <- false ▷ GB12, GB13
  13. 12else x <- true ▷ GB999
  14. 13if x then append i to B
  15. 14append n to B
  16. 15return B

The update of line L4, with c=s[i−1]c = s[i-1]:

  • pict←eppict \leftarrow ep, then ep←ExtPict(c)ep \leftarrow \mathrm{ExtPict}(c) or (epep and GCB(cc) = Extend). So epep says that s[0…i−1]s[0 \ldots i-1] ends with ExtPict Extend*, and pictpict says the same of s[0…i−2]s[0 \ldots i-2]. With aa = ZWJ, the left side of GB11 matches exactly when pictpict holds.
  • ri←ri+1ri \leftarrow ri + 1 if GCB(cc) = RI, else ri←0ri \leftarrow 0.
  • conj←conj \leftarrow consonant if InCB(cc) = Consonant; conj←conj \leftarrow linked if InCB(cc) = Linker and conj≠conj \ne none; conjconj unchanged if InCB(cc) = Extend; conj←conj \leftarrow none otherwise.

Legacy grapheme clusters drop GB9a, GB9b and GB9c, so lines L8 and L9 lose those tests.

Word and sentence boundaries follow the same pattern. Their rules before WB4 and SB5 work on the raw code points. After them, the implementation finds the previous code point that is not ignored (walking back over Extend, Format and ZWJ for words, Extend and Format for sentences), and the next one, and tests the remaining rules on those. When the walk back reaches sot or a line or paragraph separator, the first ignored code point stands for itself, as WB4 and SB5 require.

Example

Grapheme clusters of ss = U+0915 U+094D U+0937 U+093F U+1F1EB U+1F1F7 U+1F1E9 (the Devanagari syllable क्षि and three regional indicators), n=7n = 7:

ii s[i−1]s[i-1], s[i]s[i] GCB state after L4 rule result
1 0915, 094D Other, Extend conj = consonant GB9 ×
2 094D, 0937 Extend, Other conj = linked GB9c ×
3 0937, 093F Other, SpacingMark conj = consonant GB9a ×
4 093F, 1F1EB SpacingMark, RI conj = none, ri = 0 GB999 ÷
5 1F1EB, 1F1F7 RI, RI ri = 1 GB12 ×
6 1F1F7, 1F1E9 RI, RI ri = 2 GB999 ÷

The boundaries are 0, 4, 6 and 7: the syllable, the French flag, and a lone regional indicator. The legacy rules give 0, 2, 3, 4, 6 and 7.

Words in "can't 3.14 a_b": the boundaries are 0, 5, 6, 10, 11 and 14, so the segments are "can't", " ", "3.14", " " and "a_b". The apostrophe U+0027 is WB=Single_Quote, part of MidNumLetQ, so WB6 and WB7 keep "can't" together. WB11 and WB12 keep "3.14". U+005F LOW LINE is WB=ExtendNumLet, and WB13a and WB13b keep "a_b". A program that wants only the words drops the segments of spaces and punctuation.

Sentences in "The U.S. team won. it is 3.5 km." form one sentence: after "won." the next letter is lowercase, so SB8 forbids a boundary. In Mr. Smith said: "Go." Then he left. the boundaries are 0, 4, 22 and 35, and the first sentence is "Mr. ", because the default rules do not know abbreviations.

Correctness

For each kind of boundary, the claim is that the procedure returns exactly the positions where the first matching rule of UAX 29 is a ÷ rule. For grapheme clusters, an induction on ii shows that after line L4 the variables describe the left context: riri is the number of RI code points at the end of s[0…i−1]s[0 \ldots i-1], pictpict is true exactly when s[0…i−2]s[0 \ldots i-2] ends with ExtPict Extend*, and conjconj is linked exactly when s[0…i−1]s[0 \ldots i-1] matches the left side of GB9c. With these facts, each line from L5 to L12 is true exactly when its rule matches, and the order of the lines is the order of the rules. The full proof is in proofs/correctness.md. The implementation is also tested on quoted lines of the three conformance files and against a brute-force evaluation of the grapheme rules as regular expressions.

Proof: GRAPHEME-BOUNDARIES returns exactly the grapheme cluster boundaries of the UAX 29 rulesfull

Setup. Let s=s[0]⋯s[n−1]s = s[0] \cdots s[n-1] with n≥1n \ge 1. For a position ii with 1≤i≤n−11 \le i \le n-1, the rules GB3 to GB999 are tried in order, and the first rule whose left side matches a suffix of s[0…i−1]s[0 \ldots i-1] and whose right side matches a prefix of s[i…n−1]s[i \ldots n-1] decides. Rules GB1 and GB2 make 0 and nn boundaries. Write a=GCB(s[i−1])a = \mathrm{GCB}(s[i-1]) and b=GCB(s[i])b = \mathrm{GCB}(s[i]). The right side of every rule from GB3 to GB13 is a single code point, so only the left sides need a context.

Define three predicates of a prefix u=s[0…j−1]u = s[0 \ldots j-1]:

  • E(u)E(u): uu ends with a match of \p{ExtPict} Extend*, where Extend means GCB=Extend.
  • R(u)R(u): the number of GCB=RI code points at the end of uu, that is, the largest rr such that the last rr code points of uu all have GCB=RI.
  • C(u)C(u): the state of uu for GB9c. C(u)C(u) = linked if uu ends with a match of \p{InCB=Consonant} [\p{InCB=Extend}\p{InCB=Linker}]* \p{InCB=Linker} [\p{InCB=Extend}\p{InCB=Linker}]. C(u)C(u) = consonant if uu ends with a match of \p{InCB=Consonant} \p{InCB=Extend}. C(u)C(u) = none otherwise.

The two patterns of CC cannot both match: in the first one a Linker follows the last Consonant, and in the second one it does not. So CC is well defined.

Claim 1 (invariant). After line L4 of the iteration for ii, ep=E(s[0…i−1])ep = E(s[0 \ldots i-1]), pict=E(s[0…i−2])pict = E(s[0 \ldots i-2]), ri=R(s[0…i−1])ri = R(s[0 \ldots i-1]) and conj=C(s[0…i−1])conj = C(s[0 \ldots i-1]). Here s[0…−1]s[0 \ldots -1] is the empty string, and all three predicates of the empty string are false, 0 and none.

Proof. By induction on ii. Before the first iteration, line L1 sets the values of the empty prefix. Assume that before the update of iteration ii the variables hold the values for u=s[0…i−2]u = s[0 \ldots i-2], and let c=s[i−1]c = s[i-1].

  • pict←eppict \leftarrow ep gives pict=E(u)=E(s[0…i−2])pict = E(u) = E(s[0 \ldots i-2]).
  • ucuc ends with ExtPict Extend* if and only if cc is ExtPict (the run of Extend is empty), or cc has GCB=Extend and uu ends with ExtPict Extend*. So ep←ExtPict(c)∨(ep∧GCB(c)=Extend)ep \leftarrow \mathrm{ExtPict}(c) \lor (ep \land \mathrm{GCB}(c) = \mathrm{Extend}) gives E(uc)E(uc).
  • The run of RI at the end of ucuc is the run of uu plus one if cc is RI, and empty otherwise. This is the update of riri.
  • For conjconj: if InCB(cc) = Consonant, the second pattern matches ucuc with an empty Extend run, and the first cannot, because it must end in Extend or Linker. So C(uc)C(uc) = consonant. If InCB(cc) = Linker, then ucuc matches the first pattern exactly when uu ends with Consonant [Extend Linker]*, that is, when C(u)≠C(u) \ne none; so C(uc)C(uc) = linked or none as the update says. If InCB(cc) = Extend, a match for uu extends by cc in either pattern, and a match for ucuc shortens to a match for uu, so C(uc)=C(u)C(uc) = C(u). If cc has no InCB value, no pattern can end at cc, so C(uc)C(uc) = none. □\square

Claim 2. In the iteration for ii, the value of xx set by lines L5 to L12 is true exactly when the first matching rule at ii is a ÷ rule.

Proof. Each line tests the left and right sides of its rules.

  • L5 is GB3, CR × LF. L6 is GB4 and GB5: (Control | CR | LF) ÷ and ÷ (Control | CR | LF). L7 is GB6, GB7 and GB8, which are pairs of GCB values.
  • L8 is GB9 (× (Extend | ZWJ)), GB9a (× SpacingMark) and GB9b (Prepend ×).
  • L9 is GB9c: the left side matches a suffix of s[0…i−1]s[0 \ldots i-1] if and only if C(s[0…i−1])C(s[0 \ldots i-1]) = linked, which is conjconj = linked by Claim 1.
  • L10 is GB11: the left side \p{ExtPict} Extend* ZWJ matches a suffix of s[0…i−1]s[0 \ldots i-1] if and only if s[i−1]s[i-1] is ZWJ and E(s[0…i−2])E(s[0 \ldots i-2]) holds, which is aa = ZWJ and pictpict by Claim 1.
  • L11 is GB12 and GB13. Their left sides are sot (RI RI)* RI and [^RI] (RI RI)* RI. Together they match exactly when the run of RI at the end of s[0…i−1]s[0 \ldots i-1] has odd length, which is riri odd by Claim 1. The test aa = RI is implied by riri odd and kept for clarity.
  • L12 is GB999, Any ÷ Any, which always matches.

The lines form an if and else-if chain in the order of the rule numbers, so the first line whose test holds belongs to the first rule that matches. Its value of xx is false for a × rule and true for a ÷ rule. □\square

Claim 3. GRAPHEME-BOUNDARIES(ss) returns the sorted list of all grapheme cluster boundaries of ss.

Proof. Line L1 puts 0 in BB (GB1). By Claim 2, line L13 appends ii exactly when ii is a boundary, for each ii from 1 to n−1n - 1 in increasing order. Line L14 appends nn (GB2). So BB holds each boundary once, in increasing order. □\square

Legacy clusters. With extended = false, lines L8 and L9 lose the tests for GB9a, GB9b and GB9c. The legacy rule list is the extended list without these three rules, so the same proof applies with the shorter chain.

Word and sentence boundaries. The implementation follows the same scheme: the rules before WB4 and SB5 are tested on the raw neighbours, and the later rules on the neighbours after the ignored code points are skipped. The rule "X (Extend | Format | ZWJ)* → X" of WB4 means that a later rule sees the last code point XX before the run, unless XX is sot, CR, LF or Newline, where the first ignored code point stands for itself. The helper that walks back stops at those code points, so each later rule is tested on the sequence that WB4 defines. The same holds for SB5 with Extend and Format, and the stops sot and ParaSep. Each rule is then a test of its left and right sides on that sequence, in the order of the rule numbers, so the argument of Claim 2 applies.

Termination. The loop of line L2 runs n−1n - 1 times, and each iteration does a fixed number of table lookups and comparisons. For words and sentences, each walk back or forward stops at the ends of the string, so each position takes at most O(n)O(n) steps and the procedure stops.

Complexity

In the word-RAM model, a property lookup is O(1)O(1): a table indexed by code point, or a binary search over a fixed number of ranges. The constant is large in practice, and real implementations use two-stage tables.

  • Grapheme clusters. GRAPHEME-BOUNDARIES does O(1)O(1) work per position, so it takes Θ(n)\Theta(n) time and O(1)O(1) extra space besides the output.
  • Words and sentences. All left contexts of the rules are regular languages, and the right contexts are regular too. UAX 29 section 6.3 notes that the rules can be compiled into state machines. With counters for the RI run, the run of ignored code points and the chain SATerm Close* Sp*, and one backward pass that records for each position whether the next letter after it is Lower (for SB8), the time is Θ(n)\Theta(n). The direct code in the implementation walks back over runs and forward for SB8 at each position, which is O(n2)O(n^2) in the worst case, for example on a long run of spaces after a full stop.
  • Space. O(1)O(1) extra for the state, O(n)O(n) for the property array if it is stored.
claim value
grapheme boundaries Θ(n)\Theta(n) time, O(1)O(1) extra space
word and sentence boundaries with state Θ(n)\Theta(n) time
direct evaluation of the rules at each position O(n2)O(n^2) time

Properties

  • First match wins. The rules are an ordered list, not a set. Changing the order changes the result: GB4 before GB9 puts a boundary between LF and a combining mark.
  • Not a pair table. The decision at a position can depend on text far away: on the parity of a run of regional indicators (GB12, GB13, WB15, WB16), on a conjunct (GB9c), or on the next letter after any amount of punctuation (SB8).
  • Independent rule sets. Word boundaries are not always grapheme cluster boundaries. In U+0061 U+1F1E6 U+200D U+1F1E7 U+1F1E8 U+0062, the word rules ignore the ZWJ and pair U+1F1E6 with U+1F1E7, so position 4 is a word boundary, but the grapheme rules end a cluster after the ZWJ and pair U+1F1E7 with U+1F1E8.
  • Default rules. These are the default boundaries. UAX 29 allows tailoring, for example dictionary-based word breaking for Thai, or a list of abbreviations for sentences.
  • Stable over versions in spirit, not in detail. New characters and new rules change results: GB9c is new in Unicode 15.1, and the emoji rules changed several times.

Variants and improvements

  • State machines and regular expressions. UAX 29 section 6.3 describes the compilation of the rules into a state machine, a deterministic finite automaton over property values. ICU builds its break iterators from rule files in this way. A regular expression engine with \X matches one extended grapheme cluster.
  • Replacing the ignore rules. Section 6.2 shows how to rewrite WB4 and SB5 into rules that do not need the "X Extend* → X" step, which makes the rules pairwise in more places.
  • Backward and random access. Editors need the boundary before or after a given offset. Starting at an arbitrary offset needs a safe starting point; the annex discusses this in its implementation notes.
  • Tailoring. CLDR adds language rules, for example suppressions for sentence breaks after common abbreviations. Dictionary-based word breaking for languages without spaces is a separate method; see text segmentation by dynamic programming.

When to use it

Use grapheme clusters for anything a user sees as one character: cursor movement, deletion, selection, and the truncation of a string for display. Never cut a string for display at an arbitrary code point or byte offset. Use the word rules for double-click selection, "whole word" search and word counts in languages with spaces. Use the sentence rules as a first pass, and add tailoring for abbreviations when the result matters. For line wrapping, use the line breaking algorithm instead: word boundaries are not line break opportunities.

Pitfalls

  • Pairwise tables. A table indexed by the properties of the two neighbours gets GB12, GB13 and GB9c wrong. The test test_grapheme_conformance_lines has regional indicator lines that catch this.
  • The exceptions of WB4 and SB5. An Extend code point after LF or at the start of the text is not ignored. The line ÷ 000D × 000A ÷ 0061 ÷ 000A ÷ 0308 ÷ checks this for graphemes, and the sentence line ÷ 2060 × 0061 × 2060 × 002E × 2060 × 000D ÷ 2060 × 000A ÷ 2060 ÷ checks it for sentences.
  • Old data. GB9c is new in Unicode 15.1. Code written for older versions splits Devanagari conjuncts. The check test_legacy_clusters_differ shows the difference.
  • Counting characters with len. In Python, len counts code points; in Java and JavaScript, the length counts UTF-16 code units. Neither is the number of grapheme clusters.
  • Abbreviations. The default sentence rules end a sentence after "Mr." followed by an uppercase letter. This is expected behaviour, not a bug of the implementation.
  • Words as dictionary words. The default word rules do not split "日本語" into words; they need a dictionary.

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.

unicode_text_segmentation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-text-segmentation/. The authors are listed in prov/DB4AFE.jsonl.

"""Default grapheme cluster, word and sentence boundaries of UAX 29 revision 45 (Unicode 16.0.0).

Boundaries are offsets in code points from 0 to n. Position b is between s[b-1] and s[b].
The property tables are small hand-built parts of the Unicode Character Database 16.0.0.
Code points that are not in a table get the default value of the file (Other, None, False).
"""

from bisect import bisect_right

# Grapheme_Cluster_Break (GCB). Ranges copied from GraphemeBreakProperty-16.0.0.txt
# (Date: 2024-05-31, 18:09:38 GMT), one range per data line:
#   0000..0009 ; Control       000A ; LF       000D ; CR
#   0300..036F ; Extend        0600..0605 ; Prepend
#   0903 ; SpacingMark         093C ; Extend   093E..0940 ; SpacingMark   094D ; Extend
#   0A03 ; SpacingMark         0D4E ; Prepend
#   1100..115F ; L             1160..11A7 ; V   11A8..11FF ; T
#   200B ; Control             200C ; Extend   200D ; ZWJ   2060..2064 ; Control
#   AC00 ; LV                  AC01..AC1B ; LVT
#   1F1E6..1F1FF ; Regional_Indicator          1F3FB..1F3FF ; Extend
# The file gives "@missing ... Other" for all other code points.
_GCB = [
    (0x0000, 0x0009, "Control"), (0x000A, 0x000A, "LF"), (0x000D, 0x000D, "CR"),
    (0x0300, 0x036F, "Extend"), (0x0600, 0x0605, "Prepend"),
    (0x0903, 0x0903, "SpacingMark"), (0x093C, 0x093C, "Extend"),
    (0x093E, 0x0940, "SpacingMark"), (0x094D, 0x094D, "Extend"),
    (0x0A03, 0x0A03, "SpacingMark"), (0x0D4E, 0x0D4E, "Prepend"),
    (0x1100, 0x115F, "L"), (0x1160, 0x11A7, "V"), (0x11A8, 0x11FF, "T"),
    (0x200B, 0x200B, "Control"), (0x200C, 0x200C, "Extend"), (0x200D, 0x200D, "ZWJ"),
    (0x2060, 0x2064, "Control"), (0xAC00, 0xAC00, "LV"), (0xAC01, 0xAC1B, "LVT"),
    (0x1F1E6, 0x1F1FF, "RI"), (0x1F3FB, 0x1F3FF, "Extend"),
]

# Indic_Conjunct_Break (InCB). Ranges copied from DerivedCoreProperties-16.0.0.txt:
#   0300..036F ; InCB; Extend     0915..0939 ; InCB; Consonant
#   093C ; InCB; Extend           094D ; InCB; Linker      200D ; InCB; Extend
# "@missing: 0000..10FFFF; InCB; None".
_INCB = [
    (0x0300, 0x036F, "Extend"), (0x0915, 0x0939, "Consonant"), (0x093C, 0x093C, "Extend"),
    (0x094D, 0x094D, "Linker"), (0x200D, 0x200D, "Extend"),
]

# Extended_Pictographic. Ranges copied from emoji-data-16.0.0.txt (Date: 2024-05-01):
#   00A9 ; 231A..231B ; 26FE..2701 ; 1F6D1..1F6D2
# The code points 1F467, 1F468, 1F469 and 1F476 are Extended_Pictographic in the same file,
# inside longer ranges that are not copied here, so they are listed one by one.
_PICT = [
    (0x00A9, 0x00A9, True), (0x231A, 0x231B, True), (0x26FE, 0x2701, True),
    (0x1F467, 0x1F469, True), (0x1F476, 0x1F476, True), (0x1F6D1, 0x1F6D2, True),
]

# Word_Break (WB). Ranges copied from WordBreakProperty-16.0.0.txt (Date: 2024-07-29, 16:27:36 GMT):
#   000A ; LF   000D ; CR   0020 ; WSegSpace   0022 ; Double_Quote   0027 ; Single_Quote
#   002C ; MidNum   002E ; MidNumLet   0030..0039 ; Numeric   003A ; MidLetter   003B ; MidNum
#   0041..005A ; ALetter   005F ; ExtendNumLet   0061..007A ; ALetter   0300..036F ; Extend
#   05D0..05EA ; Hebrew_Letter   0641..064A ; ALetter   200D ; ZWJ   2060..2064 ; Format
#   3000 ; WSegSpace   3031..3035 ; Katakana   1F1E6..1F1FF ; Regional_Indicator
#   1F3FB..1F3FF ; Extend
_WB = [
    (0x000A, 0x000A, "LF"), (0x000D, 0x000D, "CR"), (0x0020, 0x0020, "WSegSpace"),
    (0x0022, 0x0022, "Double_Quote"), (0x0027, 0x0027, "Single_Quote"),
    (0x002C, 0x002C, "MidNum"), (0x002E, 0x002E, "MidNumLet"), (0x0030, 0x0039, "Numeric"),
    (0x003A, 0x003A, "MidLetter"), (0x003B, 0x003B, "MidNum"), (0x0041, 0x005A, "ALetter"),
    (0x005F, 0x005F, "ExtendNumLet"), (0x0061, 0x007A, "ALetter"), (0x0300, 0x036F, "Extend"),
    (0x05D0, 0x05EA, "Hebrew_Letter"), (0x0641, 0x064A, "ALetter"), (0x200D, 0x200D, "ZWJ"),
    (0x2060, 0x2064, "Format"), (0x3000, 0x3000, "WSegSpace"), (0x3031, 0x3035, "Katakana"),
    (0x1F1E6, 0x1F1FF, "RI"), (0x1F3FB, 0x1F3FF, "Extend"),
]

# Sentence_Break (SB). Ranges copied from SentenceBreakProperty-16.0.0.txt (Date: 2024-07-29, 16:27:32 GMT):
#   000A ; LF   000D ; CR   0020 ; Sp   0021 ; STerm   0022 ; Close   0027 ; Close   0028 ; Close
#   0029 ; Close   002C ; SContinue   002E ; ATerm   0030..0039 ; Numeric   003F ; STerm
#   0041..005A ; Upper   0061..007A ; Lower   00A0 ; Sp   0300..036F ; Extend   0641..064A ; OLetter
#   200C..200D ; Extend   2018 ; Close   2019 ; Close   201B..201C ; Close   201D ; Close
#   2060..2064 ; Format   3002 ; STerm   4E00..A014 ; OLetter
_SB = [
    (0x000A, 0x000A, "LF"), (0x000D, 0x000D, "CR"), (0x0020, 0x0020, "Sp"),
    (0x0021, 0x0021, "STerm"), (0x0022, 0x0022, "Close"), (0x0027, 0x0029, "Close"),
    (0x002C, 0x002C, "SContinue"), (0x002E, 0x002E, "ATerm"), (0x0030, 0x0039, "Numeric"),
    (0x003F, 0x003F, "STerm"), (0x0041, 0x005A, "Upper"), (0x0061, 0x007A, "Lower"),
    (0x00A0, 0x00A0, "Sp"), (0x0300, 0x036F, "Extend"), (0x0641, 0x064A, "OLetter"),
    (0x200C, 0x200D, "Extend"), (0x2018, 0x2019, "Close"), (0x201B, 0x201D, "Close"),
    (0x2060, 0x2064, "Format"), (0x3002, 0x3002, "STerm"), (0x4E00, 0xA014, "OLetter"),
]


def _lookup(ranges, default):
    starts = [lo for lo, _, _ in ranges]

    def get(c: str):
        cp = ord(c)
        k = bisect_right(starts, cp) - 1
        if k >= 0 and ranges[k][0] <= cp <= ranges[k][1]:
            return ranges[k][2]
        return default

    return get


gcb = _lookup(_GCB, "Other")
incb = _lookup(_INCB, "None")
ext_pict = _lookup(_PICT, False)
wb = _lookup(_WB, "Other")
sb = _lookup(_SB, "Other")

_CONTROL = ("Control", "CR", "LF")


def grapheme_boundaries(s: str, extended: bool = True) -> list[int]:
    """Return the extended grapheme cluster boundaries of s (rules GB1 to GB999).

    With extended=False, return the legacy grapheme cluster boundaries: GB9a, GB9b and
    GB9c are not used.
    """
    n = len(s)
    if n == 0:
        return [0]
    bounds = [0]  # @line L1
    ri = 0  # number of RI code points that end right before position i
    ep = False  # the text so far ends with ExtPict Extend*
    pict = False  # the text before s[i-1] ends with ExtPict Extend*
    conj = 0  # 0: none, 1: Consonant [Extend Linker]* without Linker, 2: with a Linker
    for i in range(1, n):  # @line L2
        c = s[i - 1]
        a, b = gcb(c), gcb(s[i])  # @line L3
        pict = ep  # @line L4
        ep = ext_pict(c) or (ep and a == "Extend")
        ri = ri + 1 if a == "RI" else 0
        k = incb(c)
        if k == "Consonant":
            conj = 1
        elif k == "Linker" and conj:
            conj = 2
        elif k != "Extend":
            conj = 0
        if a == "CR" and b == "LF":  # @line L5
            brk = False
        elif a in _CONTROL or b in _CONTROL:  # @line L6
            brk = True
        elif ((a == "L" and b in ("L", "V", "LV", "LVT"))  # @line L7
              or (a in ("LV", "V") and b in ("V", "T"))
              or (a in ("LVT", "T") and b == "T")):
            brk = False
        elif b in ("Extend", "ZWJ") or (extended and (b == "SpacingMark" or a == "Prepend")):  # @line L8
            brk = False
        elif extended and conj == 2 and incb(s[i]) == "Consonant":  # @line L9
            brk = False
        elif pict and a == "ZWJ" and ext_pict(s[i]):  # @line L10
            brk = False
        elif a == "RI" and b == "RI" and ri % 2 == 1:  # @line L11
            brk = False
        else:  # @line L12
            brk = True
        if brk:  # @line L13
            bounds.append(i)
    bounds.append(n)  # @line L14
    return bounds  # @line L15


def grapheme_clusters(s: str, extended: bool = True) -> list[str]:
    b = grapheme_boundaries(s, extended)
    return [s[b[j]:b[j + 1]] for j in range(len(b) - 1)]


# ---------------------------------------------------------------- words

_AH = ("ALetter", "Hebrew_Letter")
_MIDLETQ = ("MidLetter", "MidNumLet", "Single_Quote")
_MIDNUMQ = ("MidNum", "MidNumLet", "Single_Quote")
_WB_IGNORE = ("Extend", "Format", "ZWJ")
_WB_NEWLINE = ("Newline", "CR", "LF")


def _prev_index(p, i, ignore, stops):
    """Index of the code point that stands for the text before position i after the
    rule X (ignore)* -> X (WB4 or SB5). Return -1 at the start of the text."""
    j = i - 1
    while j >= 0 and p[j] in ignore:
        j -= 1
    if j < 0 or p[j] in stops:
        # The ignored code points after sot or a line separator are not absorbed:
        # the first of them stands for itself.
        return j + 1 if j + 1 < i else j
    return j


def _next_index(p, i, ignore):
    """Index of the first code point at or after i that is not ignored, or len(p)."""
    while i < len(p) and p[i] in ignore:
        i += 1
    return i


def word_boundaries(s: str) -> list[int]:
    """Return the default word boundaries of s (rules WB1 to WB999)."""
    n = len(s)
    if n == 0:
        return [0]
    p = [wb(c) for c in s]
    pict = [ext_pict(c) for c in s]
    bounds = [0]
    for i in range(1, n):
        a, b = p[i - 1], p[i]
        if a == "CR" and b == "LF":  # WB3
            brk = False
        elif a in _WB_NEWLINE or b in _WB_NEWLINE:  # WB3a, WB3b
            brk = True
        elif a == "ZWJ" and pict[i]:  # WB3c
            brk = False
        elif a == "WSegSpace" and b == "WSegSpace":  # WB3d
            brk = False
        elif b in _WB_IGNORE:  # WB4
            brk = False
        else:
            brk = _word_rules(p, i)
        if brk:
            bounds.append(i)
    bounds.append(n)
    return bounds


def _word_rules(p, i):
    """WB5 to WB999 at position i, on the sequence after WB4. p[i] is not ignored."""
    j = _prev_index(p, i, _WB_IGNORE, _WB_NEWLINE)
    a = p[j]
    b = p[i]
    jj = _prev_index(p, j, _WB_IGNORE, _WB_NEWLINE) if j > 0 else -1
    aa = p[jj] if jj >= 0 else None
    k = _next_index(p, i + 1, _WB_IGNORE)
    c = p[k] if k < len(p) else None
    if a in _AH and b in _AH:  # WB5
        return False
    if a in _AH and b in _MIDLETQ and c in _AH:  # WB6
        return False
    if aa in _AH and a in _MIDLETQ and b in _AH:  # WB7
        return False
    if a == "Hebrew_Letter" and b == "Single_Quote":  # WB7a
        return False
    if a == "Hebrew_Letter" and b == "Double_Quote" and c == "Hebrew_Letter":  # WB7b
        return False
    if aa == "Hebrew_Letter" and a == "Double_Quote" and b == "Hebrew_Letter":  # WB7c
        return False
    if a == "Numeric" and b == "Numeric":  # WB8
        return False
    if a in _AH and b == "Numeric":  # WB9
        return False
    if a == "Numeric" and b in _AH:  # WB10
        return False
    if aa == "Numeric" and a in _MIDNUMQ and b == "Numeric":  # WB11
        return False
    if a == "Numeric" and b in _MIDNUMQ and c == "Numeric":  # WB12
        return False
    if a == "Katakana" and b == "Katakana":  # WB13
        return False
    if a in _AH + ("Numeric", "Katakana", "ExtendNumLet") and b == "ExtendNumLet":  # WB13a
        return False
    if a == "ExtendNumLet" and b in _AH + ("Numeric", "Katakana"):  # WB13b
        return False
    if a == "RI" and b == "RI":  # WB15, WB16
        count = 0
        t = j
        while t >= 0 and p[t] == "RI":
            count += 1
            t = _prev_index(p, t, _WB_IGNORE, _WB_NEWLINE) if t > 0 else -1
        if count % 2 == 1:
            return False
    return True  # WB999


# ---------------------------------------------------------------- sentences

_SB_IGNORE = ("Extend", "Format")
_PARASEP = ("Sep", "CR", "LF")
_SATERM = ("STerm", "ATerm")


def sentence_boundaries(s: str) -> list[int]:
    """Return the default sentence boundaries of s (rules SB1 to SB998)."""
    n = len(s)
    if n == 0:
        return [0]
    p = [sb(c) for c in s]
    bounds = [0]
    for i in range(1, n):
        a, b = p[i - 1], p[i]
        if a == "CR" and b == "LF":  # SB3
            brk = False
        elif a in _PARASEP:  # SB4
            brk = True
        elif b in _SB_IGNORE:  # SB5
            brk = False
        else:
            brk = _sentence_rules(p, i)
        if brk:
            bounds.append(i)
    bounds.append(n)
    return bounds


def _sentence_rules(p, i):
    """SB6 to SB998 at position i, on the sequence after SB5. p[i] is not ignored."""
    prev = lambda t: _prev_index(p, t, _SB_IGNORE, _PARASEP) if t > 0 else -1  # noqa: E731
    j = prev(i)
    a, b = p[j], p[i]
    jj = prev(j)
    aa = p[jj] if jj >= 0 else None
    if a == "ATerm" and b == "Numeric":  # SB6
        return False
    if aa in ("Upper", "Lower") and a == "ATerm" and b == "Upper":  # SB7
        return False
    # Match SATerm Close* Sp* ending right before i.
    t = j
    sp = 0
    while t >= 0 and p[t] == "Sp":
        sp += 1
        t = prev(t)
    close = 0
    while t >= 0 and p[t] == "Close":
        close += 1
        t = prev(t)
    term = p[t] if t >= 0 and p[t] in _SATERM else None
    if term is None:
        return False  # SB998
    if term == "ATerm":  # SB8
        k = i
        while k < len(p) and p[k] not in ("OLetter", "Upper", "Lower") + _PARASEP + _SATERM:
            k += 1
        if k < len(p) and p[k] == "Lower":
            return False
    if b in ("SContinue",) + _SATERM:  # SB8a
        return False
    if sp == 0 and b in ("Close", "Sp") + _PARASEP:  # SB9
        return False
    if b in ("Sp",) + _PARASEP:  # SB10
        return False
    return True  # SB11


def segments(s: str, bounds: list[int]) -> list[str]:
    return [s[bounds[j]:bounds[j + 1]] for j in range(len(bounds) - 1)]
test_unicode_text_segmentation.py 313 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-text-segmentation/. The authors are listed in prov/DB4AFE.jsonl.

import random
import re

from unicode_text_segmentation import (
    ext_pict,
    gcb,
    grapheme_boundaries,
    grapheme_clusters,
    incb,
    sentence_boundaries,
    word_boundaries,
)

# Lines copied from GraphemeBreakTest-16.0.0.txt (Date: 2024-05-02, 15:02:48 GMT),
# https://www.unicode.org/Public/16.0.0/ucd/auxiliary/GraphemeBreakTest.txt.
# Only the part before the tab and "#" is copied. The first group is file lines 24 to 61
# (consecutive data lines). The second group is from the hand-written lines at the end of the file.
GRAPHEME_LINES = """\
÷ 0020 ÷ 0020 ÷
÷ 0020 × 0308 ÷ 0020 ÷
÷ 0020 ÷ 000D ÷
÷ 0020 × 0308 ÷ 000D ÷
÷ 0020 ÷ 000A ÷
÷ 0020 × 0308 ÷ 000A ÷
÷ 0020 ÷ 0001 ÷
÷ 0020 × 0308 ÷ 0001 ÷
÷ 0020 × 200C ÷
÷ 0020 × 0308 × 200C ÷
÷ 0020 ÷ 1F1E6 ÷
÷ 0020 × 0308 ÷ 1F1E6 ÷
÷ 0020 ÷ 0600 ÷
÷ 0020 × 0308 ÷ 0600 ÷
÷ 0020 × 0A03 ÷
÷ 0020 × 0308 × 0A03 ÷
÷ 0020 ÷ 1100 ÷
÷ 0020 × 0308 ÷ 1100 ÷
÷ 0020 ÷ 1160 ÷
÷ 0020 × 0308 ÷ 1160 ÷
÷ 0020 ÷ 11A8 ÷
÷ 0020 × 0308 ÷ 11A8 ÷
÷ 0020 ÷ AC00 ÷
÷ 0020 × 0308 ÷ AC00 ÷
÷ 0020 ÷ AC01 ÷
÷ 0020 × 0308 ÷ AC01 ÷
÷ 0020 × 0903 ÷
÷ 0020 × 0308 × 0903 ÷
÷ 0020 ÷ 0904 ÷
÷ 0020 × 0308 ÷ 0904 ÷
÷ 0020 ÷ 0D4E ÷
÷ 0020 × 0308 ÷ 0D4E ÷
÷ 0020 ÷ 0915 ÷
÷ 0020 × 0308 ÷ 0915 ÷
÷ 0020 ÷ 231A ÷
÷ 0020 × 0308 ÷ 231A ÷
÷ 0020 × 0300 ÷
÷ 0020 × 0308 × 0300 ÷
÷ 000D × 000A ÷ 0061 ÷ 000A ÷ 0308 ÷
÷ 0061 × 0308 ÷
÷ 0020 × 200D ÷ 0646 ÷
÷ 0646 × 200D ÷ 0020 ÷
÷ 1100 × 1100 ÷
÷ AC00 × 11A8 ÷ 1100 ÷
÷ AC01 × 11A8 ÷ 1100 ÷
÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷
÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷
÷ 0061 ÷ 1F1E6 × 1F1E7 × 200D ÷ 1F1E8 ÷ 0062 ÷
÷ 0061 ÷ 1F1E6 × 200D ÷ 1F1E7 × 1F1E8 ÷ 0062 ÷
÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 × 1F1E9 ÷ 0062 ÷
÷ 0061 × 200D ÷
÷ 0061 × 0308 ÷ 0062 ÷
÷ 0061 × 0903 ÷ 0062 ÷
÷ 0061 ÷ 0600 × 0062 ÷
÷ 1F476 × 1F3FF ÷ 1F476 ÷
÷ 0061 × 1F3FF ÷ 1F476 ÷
÷ 0061 × 1F3FF ÷ 1F476 × 200D × 1F6D1 ÷
÷ 1F476 × 1F3FF × 0308 × 200D × 1F476 × 1F3FF ÷
÷ 1F6D1 × 200D × 1F6D1 ÷
÷ 0061 × 200D ÷ 1F6D1 ÷
÷ 2701 × 200D × 2701 ÷
÷ 0061 × 200D ÷ 2701 ÷
÷ 0915 ÷ 0924 ÷
÷ 0915 × 094D × 0924 ÷
÷ 0915 × 094D × 094D × 0924 ÷
÷ 0915 × 094D × 200D × 0924 ÷
÷ 0915 × 093C × 200D × 094D × 0924 ÷
÷ 0915 × 093C × 094D × 200D × 0924 ÷
÷ 0915 × 094D × 0924 × 094D × 092F ÷
÷ 0915 × 094D ÷ 0061 ÷
÷ 0061 × 094D ÷ 0924 ÷
÷ 003F × 094D ÷ 0924 ÷
÷ 0378 × 094D ÷
÷ 0378 × 200D ÷
÷ 0378 ÷ 0378 ÷
"""

# Lines copied from WordBreakTest-16.0.0.txt (Date: 2024-04-30, 21:48:43 GMT), from the
# hand-written lines and the last block of the file.
WORD_LINES = """\
÷ 0031 ÷ 002C × 200D ÷
÷ 0031 × 002C × 0308 × 0031 ÷ 0027 ÷
÷ 0031 × 002E × 2060 × 0031 ÷ 0027 ÷
÷ 0031 ÷ 002E × 2060 ÷ 05D0 ÷
÷ 0020 × 200D ÷ 0646 ÷
÷ 0646 × 200D ÷ 0020 ÷
÷ 05D0 × 0027 ÷
÷ 05D0 × 0022 × 05D0 ÷
÷ 3031 × 3031 ÷
÷ 0041 × 005F × 0030 × 005F × 3031 × 005F ÷
÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷
÷ 0061 ÷ 1F1E6 × 1F1E7 × 200D ÷ 1F1E8 ÷ 0062 ÷
÷ 0061 ÷ 1F1E6 × 200D × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷
÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 × 1F1E9 ÷ 0062 ÷
÷ 1F6D1 × 200D × 1F6D1 ÷
÷ 0061 × 200D × 1F6D1 ÷
÷ 2701 × 200D × 2701 ÷
÷ 0061 × 200D × 2701 ÷
÷ 1F476 × 1F3FF × 0308 × 200D × 1F476 × 1F3FF ÷
÷ 200D × 1F6D1 × 1F3FF ÷
÷ 200D × 1F6D1 ÷
÷ 0061 × 0308 × 200D × 0308 × 0062 ÷
÷ 0061 ÷ 0020 × 0020 ÷ 0062 ÷
÷ 0061 ÷ 003A ÷ 003A ÷ 0031 ÷
÷ 0031 ÷ 002C ÷ 003A ÷ 0031 ÷
÷ 0031 × 005F × 0061 ÷ 002E ÷ 002C ÷ 0031 ÷
÷ 0061 × 005F × 0061 ÷ 002C ÷ 002C ÷ 0061 ÷
"""

# Lines copied from SentenceBreakTest-16.0.0.txt (16.0.0), from the hand-written lines.
SENTENCE_LINES = """\
÷ 0061 × 0308 ÷
÷ 0020 × 200D × 0646 ÷
÷ 0646 × 200D × 0020 ÷
÷ 0028 × 0022 × 0047 × 006F × 002E × 0022 × 0029 × 0020 ÷ 0028 × 0048 × 0065 × 0020 × 0064 × 0069 × 0064 × 002E × 0029 ÷
÷ 0028 × 201C × 0047 × 006F × 003F × 201D × 0029 × 0020 ÷ 0028 × 0048 × 0065 × 0020 × 0064 × 0069 × 0064 × 002E × 0029 ÷
÷ 0055 × 002E × 0053 × 002E × 0041 × 0300 × 002E × 0020 × 0069 × 0073 ÷
÷ 0055 × 002E × 0053 × 002E × 0041 × 0300 × 003F × 0020 ÷ 0048 × 0065 ÷
÷ 0055 × 002E × 0053 × 002E × 0041 × 0300 × 002E ÷
÷ 0033 × 002E × 0034 ÷
÷ 0063 × 002E × 0064 ÷
÷ 0043 × 002E × 0064 ÷
÷ 0063 × 002E × 0044 ÷
÷ 0043 × 002E × 0044 ÷
÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 × 0074 × 0068 × 0065 ÷
÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 ÷ 0054 × 0068 × 0065 ÷
÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 × 2018 × 0028 × 0074 × 0068 × 0065 ÷
÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 ÷ 2018 × 0028 × 0054 × 0068 × 0065 ÷
÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 × 0308 × 0074 × 0068 × 0065 ÷
÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 00A0 × 0308 ÷ 0054 × 0068 × 0065 ÷
÷ 0065 × 0074 × 0063 × 002E × 0029 × 2019 × 0308 ÷ 0054 × 0068 × 0065 ÷
÷ 0065 × 0074 × 0063 × 002E × 0029 × 000A ÷ 0308 × 0054 × 0068 × 0065 ÷
÷ 0074 × 0068 × 0065 × 0020 × 0072 × 0065 × 0073 × 0070 × 002E × 0020 × 006C × 0065 × 0061 × 0064 × 0065 × 0072 × 0073 × 0020 × 0061 × 0072 × 0065 ÷
÷ 5B57 × 002E ÷ 5B57 ÷
÷ 0065 × 0074 × 0063 × 002E ÷ 5B83 ÷
÷ 0065 × 0074 × 0063 × 002E × 3002 ÷
÷ 5B57 × 3002 ÷ 5B83 ÷
÷ 0021 × 0020 × 0020 ÷
÷ 0061 × 002E ÷
÷ 0061 × 002E × 000D × 000A ÷
÷ 0061 × 002E × 000D × 000A ÷ 0020 ÷
÷ 0061 × 002E × 000D × 000A ÷ 0061 ÷
÷ 0041 × 002E × 000D × 000A ÷ 0041 ÷
÷ 2060 × 0061 × 2060 × 002E × 2060 × 000D ÷ 2060 × 000A ÷ 2060 ÷
"""


def parse(line: str) -> tuple[str, list[int]]:
    """Turn a test line into the string and the list of its boundaries."""
    chars: list[str] = []
    bounds: list[int] = []
    for tok in line.split():
        if tok == "÷":
            bounds.append(len(chars))
        elif tok == "×":
            pass
        else:
            chars.append(chr(int(tok, 16)))
    return "".join(chars), bounds


def check_lines(lines: str, fn) -> int:
    count = 0
    for line in lines.splitlines():
        s, expected = parse(line)
        assert fn(s) == expected, line
        count += 1
    return count


def test_grapheme_conformance_lines():
    assert check_lines(GRAPHEME_LINES, grapheme_boundaries) >= 70


def test_word_conformance_lines():
    assert check_lines(WORD_LINES, word_boundaries) >= 25


def test_sentence_conformance_lines():
    assert check_lines(SENTENCE_LINES, sentence_boundaries) >= 30


def test_check_values():
    assert len(grapheme_clusters("é")) == 1
    assert len(grapheme_clusters("\r\n")) == 1
    assert len(grapheme_clusters("각")) == 1
    assert len(grapheme_clusters("👨‍👩‍👧")) == 1
    assert grapheme_clusters("🇫🇷🇩🇪") == ["🇫🇷", "🇩🇪"]
    assert len(grapheme_clusters("क्षि")) == 1


def test_legacy_clusters_differ():
    s = "क्षि"
    assert grapheme_boundaries(s) == [0, 4]
    assert grapheme_boundaries(s, extended=False) == [0, 2, 3, 4]


def test_empty_and_single():
    for fn in (grapheme_boundaries, word_boundaries, sentence_boundaries):
        assert fn("") == [0]
        assert fn("a") == [0, 1]


# A brute-force reference for the grapheme rules: each rule is written as a pair of regular
# expressions, one for the text left of the position and one for the text right of it, as in
# UAX 29. Each code point becomes a token of three letters: its GCB value, its InCB value and
# whether it is Extended_Pictographic. The first rule whose two sides match decides.
_G = {"Other": "o", "CR": "r", "LF": "n", "Control": "c", "Extend": "e", "ZWJ": "z",
      "RI": "i", "Prepend": "p", "SpacingMark": "s", "L": "l", "V": "v", "T": "t",
      "LV": "w", "LVT": "x"}
_I = {"None": "-", "Consonant": "C", "Extend": "E", "Linker": "L"}


def _tok(c: str) -> str:
    return _G[gcb(c)] + _I[incb(c)] + ("P" if ext_pict(c) else "-")


def T(g=".", i=".", p=".") -> str:
    return "(?:" + g + i + p + ")"


ANY = T()
_RULES = [
    (T("r") + r"\Z", "^" + T("n"), False),  # GB3
    (T("[crn]") + r"\Z", "", True),  # GB4
    ("", "^" + T("[crn]"), True),  # GB5
    (T("l") + r"\Z", "^" + T("[lvwx]"), False),  # GB6
    (T("[wv]") + r"\Z", "^" + T("[vt]"), False),  # GB7
    (T("[xt]") + r"\Z", "^" + T("t"), False),  # GB8
    ("", "^" + T("[ez]"), False),  # GB9
    ("", "^" + T("s"), False),  # GB9a
    (T("p") + r"\Z", "", False),  # GB9b
    (T(".", "C") + T(".", "[EL]") + "*" + T(".", "L") + T(".", "[EL]") + r"*\Z",
     "^" + T(".", "C"), False),  # GB9c
    (T(".", ".", "P") + T("e") + "*" + T("z") + r"\Z", "^" + T(".", ".", "P"), False),  # GB11
    ("^(?:" + T("i") + T("i") + ")*" + T("i") + r"\Z", "^" + T("i"), False),  # GB12
    ("(?:^|" + "(?!" + T("i") + ")" + ANY + ")(?:" + T("i") + T("i") + ")*" + T("i") + r"\Z",
     "^" + T("i"), False),  # GB13
]


def brute_grapheme_boundaries(s: str) -> list[int]:
    toks = [_tok(c) for c in s]
    n = len(s)
    out = [0] if n else [0]
    for b in range(1, n):
        left, right = "".join(toks[:b]), "".join(toks[b:])
        brk = True
        for lpat, rpat, decision in _RULES:
            if (lpat == "" or re.search(lpat, left)) and (rpat == "" or re.match(rpat, right)):
                brk = decision
                break
        if brk:
            out.append(b)
    if n:
        out.append(n)
    return out


def test_grapheme_against_regex_rules():
    pool = ["\r", "\n", "\x01", "a", " ", "̈", "‍", "‌", "ः", "؀",
            "ᄀ", "ᅠ", "ᆨ", "가", "각", "क", "त", "्",
            "़", "\U0001F1E6", "\U0001F1E7", "⌚", "\U0001F476", "\U0001F3FF"]
    rng = random.Random(29)
    for _ in range(1500):
        s = "".join(rng.choice(pool) for _ in range(rng.randint(0, 9)))
        assert grapheme_boundaries(s) == brute_grapheme_boundaries(s), [hex(ord(c)) for c in s]


def test_boundaries_are_sorted_and_cover_the_text():
    rng = random.Random(45)
    pool = list("aZ1., :'\"\r\n?!()") + ["̈", "‍", "⁠", "א", "〱", "字"]
    for _ in range(500):
        s = "".join(rng.choice(pool) for _ in range(rng.randint(1, 15)))
        for fn in (grapheme_boundaries, word_boundaries, sentence_boundaries):
            b = fn(s)
            assert b[0] == 0 and b[-1] == len(s)
            assert all(b[k] < b[k + 1] for k in range(len(b) - 1))


def test_word_boundary_inside_a_grapheme_cluster():
    # The rules are separate: RI ZWJ RI is one RI pair for words (WB4 drops the ZWJ),
    # but for graphemes the ZWJ ends the first cluster, so the pairs fall differently.
    s, expected = parse("÷ 0061 ÷ 1F1E6 × 200D × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷")
    assert word_boundaries(s) == expected == [0, 1, 4, 5, 6]
    assert grapheme_boundaries(s) == [0, 1, 3, 5, 6]
    others = 0
    for line in WORD_LINES.splitlines():
        s, _ = parse(line)
        if set(word_boundaries(s)) <= set(grapheme_boundaries(s)):
            others += 1
    assert others == len(WORD_LINES.splitlines()) - 1

History

UAX 29 gets a new revision with each version of the Unicode Standard, and the rules change with the character repertoire. The annex keeps the legacy form of grapheme clusters for compatibility with older implementations. The emoji rules changed several times, and the current GB11 uses the Extended_Pictographic property. GB9c for Indic conjuncts, with the new property Indic_Conjunct_Break, came in Unicode 15.1 (2023). Revision 45 is the version for Unicode 16.0.0.

References

  1. Josh Hadley (editor), Unicode Standard Annex 29, Unicode Text Segmentation, revision 45, 2024-08-28, Sections 3.1.1 (grapheme rules GB1 to GB999), 4.1 and 4.1.1 (word rules WB1 to WB999), 5.1 and 5.1.1 (sentence rules SB1 to SB998), 6.2 (Replacing Ignore Rules), 6.3 (State Machines) and 7 (Testing)
  2. Unicode Character Database 16.0.0, auxiliary folder, GraphemeBreakProperty.txt, WordBreakProperty.txt, SentenceBreakProperty.txt and the test files GraphemeBreakTest.txt, WordBreakTest.txt and SentenceBreakTest.txt
  3. emoji-data-16.0.0.txt, Unicode Character Database, the Extended_Pictographic property
  4. The Unicode Consortium, The Unicode Standard, Version 16.0.0, 2024, Chapter 3, definitions D60 and D61 (grapheme clusters as defined by UAX 29)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example