---
title: "Segmentation: line breaks, word boundaries and dictionary breaking"
url: https://recursiveai.org/onefont/docs/segmentation/
description: "Dictionary word and line breaking for Thai, Lao, Khmer and Burmese, and Japanese phrase boundaries for CSS word-break: auto-phrase: the method, the data and the known differences."
version: "1.7.0"
source: https://github.com/recursive-ai-oss/onefont-csharp/blob/ae5d7cadd6a519a9396e4df804ae53ec28ef546d/docs/segmentation.md
---

# Segmentation: line breaks, word boundaries and dictionary breaking

`TextSegmentation` finds line break opportunities (UAX #14), grapheme cluster, word and sentence boundaries (UAX #29), all on Unicode 17.0.0
data, and passes the conformance files (`LineBreakTest.txt`, `GraphemeBreakTest.txt`, `WordBreakTest.txt`, `SentenceBreakTest.txt`). Called
without options the methods apply the default rules and nothing else. This page describes the one optional extra, dictionary breaking, and
is written so that another implementation can reproduce it.

## What the rules leave open

Thai, Lao, Khmer and Burmese (Myanmar) are written without spaces between words. Their letters have Line_Break class SA, which UAX #14
rule LB1 resolves "by the implementation" (here: as AL, and as CM for marks, so a run of them has no opportunity at all), and their
Word_Break class is Other or Extend, so UAX #29's default rules put a boundary after every cluster. UAX #29 section 4 says a dictionary
may replace the default word rules for such scripts. Dictionary breaking does that, and only that:

- `GetLineBreakOpportunities(text, options)`, `GetLineBreakOpportunities(text, buffer, options)` and
  `FillLineBreakOpportunities(text, bytes, options)` with `LineBreakOptions.Dictionary = true` run the UAX #14 rules, then set an *allowed*
  opportunity at every word boundary the dictionary finds inside a run of SA letters, wherever the rules left none. Nothing else changes: every
  other position, mandatory breaks included, is as without the option. `null` options and `Dictionary = false` give exactly the plain result.
- `GetWordBoundaries(text, language)`, `FillWordStarts(text, language, starts)` and `GetNextWordBoundary(text, language, index)` give the UAX #29
  word boundaries with the dictionary's words inside SA runs. The overloads without a `language` parameter stay the pure default rules.
  `language` is a BCP 47 tag reserved for tailoring; today the script of each run decides, whatever the tag (and `null`) says.

## The method

**Runs.** A run is a maximal sequence of characters with Line_Break SA (Unicode 17.0.0) of one script: Thai U+0E01..0E3A and 0E40..0E4E; Lao
U+0E81..0EDF where SA; Khmer U+1780..17D3, 17D7, 17DC, 17DD; Burmese U+1000..103F, 1050..108F, 109A..109F, U+A9E0..A9EF and U+AA60..AA7F.
Digits, punctuation and spaces are not SA and end a run. For word boundaries, combining and format characters of other scripts that follow a
run stay with it (UAX #29 rule WB4).

**Where a word may start.** Inside a run, a boundary is only possible before a character that can start a word:

- never before a character whose Grapheme_Cluster_Break is Extend or SpacingMark (UAX #29 GB9, GB9a);
- Thai: never before U+0E30, 0E32, 0E45, 0E46 (following vowels and the repetition mark), nor after U+0E40..0E44 (prefixed vowels);
- Lao: never before U+0EB0, 0EB2, 0EB3, 0EBD, 0EC6, nor after U+0EC0..0EC4;
- Khmer: never after U+17D2 (coeng), nor before U+17D7;
- Burmese: never after U+1039 (virama), nor before a consonant that is followed by U+103A (asat), unless that asat is followed by U+1039
  (a kinzi).

**The cut.** Among the sequences of dictionary words and uncovered pieces that tile the run, with every cut at a possible boundary, choose
the one with the fewest uncovered characters. Among equals, the first word (at each position, left to right) is the longest. An *uncovered
piece* starts at a possible boundary where no word is chosen and extends to the next possible boundary; adjacent uncovered pieces are one
piece, so text that no word explains stays together and gets no cut inside it. Cuts fall before and after a word and before and after an
uncovered piece. The cut is computed for the whole run by dynamic programming from the end of the run; each position tries only the words that
start there (the longest word in the lists is 33 characters), so the work is linear in the run and the memory is linear too (a pooled
`long` and `int` per character).

**Matching.** Words are compared code unit for code unit: no normalization is done, so text whose marks come in another order than the list's
spelling does not match (uncovered pieces then stay together). A word is only taken if it lies inside the run.

## The data

The lists are the word lists of the ICU project's break iterator dictionaries (`thaidict.txt`, `laodict.txt`, `khmerdict.txt`,
`burmesedict.txt`, ICU release 78.1), used under the Unicode License v3 (THIRD-PARTY-NOTICES.md names the commit and the SHA-256 of each file,
and quotes the Lao and Burmese lists' own BSD licences). `tools/gen_dictionary_tables.py` fetches them at that commit, checks the hashes, drops
the words with a character outside the script's 256-code-point block (25 Khmer and 7 Burmese entries) and writes `src/OneFont/Unicode/Dictionaries/*.bin`:
a raw DEFLATE stream of the word count and the words, sorted by code point and front coded (shared prefix length, tail length, tail), one
byte per character (code point minus the block's base). The lists hold 26,383 Thai, 30,550 Lao, 81,003 Khmer and 41,113 Burmese words and add
about 540 KB to the package. A list is read on first use of its script, once per process, into two arrays (one byte per character and an offset per word);
looking up the words at a position narrows a range of the sorted words one character at a time with two binary searches.

## Known differences

- **Browsers.** Chrome 149's line breaking (the sentences recorded by the onefont conformance kit were taken from Chrome for Testing 156) agrees with this
  method for Thai and Burmese (boundary F1 0.96 and 0.97 on held-out Wikipedia text) but not for Lao (0.91) and Khmer (0.77): Chrome's own `Intl.Segmenter`
  also breaks `ມື້ນີ້` into `ມື້|ນີ້` and `ថ្ងៃនេះ` into `ថ្ងៃ|នេះ`, two entries of the very word lists used here, so its Lao and Khmer breaks do not
  come from those lists alone (the stock ICU 78.2 result, run through Node.js 22's `Intl.Segmenter`, does: this method agrees with it at F1 0.96 or better in
  all four scripts, and on all 24 kit sentences). Fourteen of the 24 kit sentences (all Lao and Khmer ones, `thai-4`, `burmese-1`) differ from the
  browser for this reason; the tests pin the stock-dictionary result for them. Chrome also keeps `ฝนตก` and `ရတာ` together in line breaking where
  its segmenter and this method cut after `ฝน` and `ရ`.
- **Compounds.** A list holds compounds (`ທຸກຄົນ`) and their parts (`ທຸກ`, `ຄົນ`); the cut takes the compound when the rest of the run is covered
  equally well, as the stock ICU dictionary segmenter does.
- **Other scripts of the same blocks.** Shan, Karen and other Myanmar-block letters are processed with the Burmese list; most are uncovered and stay together.
  Tai Tham, Cham, Tai Viet and other SA scripts are not covered: they stay as UAX #14 leaves them.
- **UAX #29 section 4 and LB1 are tailored, not changed:** every other boundary class, and every position outside the runs above, is the
  conformance-tested default.

## Agreement with black boxes

Measured on the first 240 code points of 1,443 paragraphs of Thai, Lao, Khmer and Burmese Wikipedia introductions (not committed), odd-numbered
paragraphs (held out: the method was fitted to the even-numbered ones and the 24 kit sentences), counting every position between two letters
of the same script; boundary precision/recall/F1 of this method against the reference:

| Script | Chrome 149 line breaks | ICU 78.2 word segmentation (Node.js 22.22.1) |
|---|---|---|
| Thai | 0.956 / 0.979 / 0.967 | 0.966 / 0.979 / 0.972 |
| Lao | 0.958 / 0.862 / 0.907 | 0.973 / 0.975 / 0.974 |
| Khmer | 0.762 / 0.774 / 0.768 | 0.976 / 0.968 / 0.972 |
| Burmese | 0.985 / 0.962 / 0.973 | 0.991 / 0.961 / 0.976 |

## Limits

- Time and memory are linear in the length of a run; the tests cover a run of 800,000 letters.
- `GetNextWordBoundary(text, language, index)` inside a run costs the rest of the run, because the cut depends on all of it; walk a long run with
  `FillWordStarts` or `GetWordBoundaries`.
- The methods allocate nothing once the lists of the scripts in the text are loaded, apart from pooled buffers; the first call for a script
  inflates its list.
- Only `ArgumentException` (a buffer shorter than the text plus one) and `ArgumentOutOfRangeException` (`index`) leave the methods.

## Japanese phrase boundaries

`TextSegmentation.GetPhraseBoundaries(text, language)` and `FillPhraseStarts(text, language, starts)` find the phrase boundaries CSS Text Level 4 uses
for `word-break: auto-phrase` (and `word-space-transform: auto-phrase`): a phrase is a content word with the particles and auxiliaries attached to it
(a bunsetsu-like unit). `私は|学生です。` is two phrases; `今日は|天気が|いいですね。` is three.

### Which text, which language

- The language is a BCP 47 tag. It is Japanese when its primary subtag is `ja`, compared by ASCII case and followed by the end of the tag, `-` or `_`
  (`ja`, `ja-JP`, `JA_jp`; not `jav`). Any other language, or `null`, gives exactly the word boundaries of `GetWordBoundaries(text, language)` (with dictionary words in Thai, Lao, Khmer and Burmese runs).
- For Japanese the candidates are the UAX #29 word boundaries (UAX #29 section 4.1.1 on the whole text, so the Latin words, digit runs, katakana
  words and white space the default rules keep together or apart stay that way). A candidate is kept unless the model removes it.
- The model decides a candidate only when, with *a* the code point before it and *b* the one after it (an unpaired surrogate is its own code point):
  neither is white space, or outside the text; they are not both katakana (class below); and at least one of them is Japanese: kana, an ideograph, or
  an East Asian punctuation or symbol at U+3000 or above. Every other candidate is kept (a boundary beside white space, inside Latin text, between
  two non-Japanese characters). So a phrase boundary is always a UAX #29 word boundary, never the reverse.

### Line breaking with phrases

`LineBreakOptions.Phrases = true` with a Japanese `LineBreakOptions.Language` runs the UAX #14 rules (and the dictionary, when asked), then clears every *allowed* opportunity at a position the model decides (same test as above: neither neighbour white space, not both katakana, at least one Japanese) when the model does not keep
it as a phrase boundary. An opportunity between two katakana is cleared too (UAX #14 allows it; a katakana run is one UAX #29 word). Mandatory breaks and opportunities at other positions the model does not decide stay. With another language, or `Phrases` off, the result is
exactly the options-less one. The `Fill` form allocates nothing.

### The model

A linear classifier over hashed features of the six code points around the candidate: `w[0..5]` are the code points at offsets -3, -2, -1, 0, +1, +2
from the candidate (`w[2]` is *a*, `w[3]` is *b*; 0 where the text ends). `c[k]` is the character class of `w[k]`:

| class | value | members |
|---|---|---|
| other | 0 | everything not listed |
| hiragana | 1 | U+3041-309F, U+1B001-1B16F, U+1F200 |
| katakana | 2 | U+30A1-30FA, U+30FC-30FF (including the prolonged sound mark), U+31F0-31FF, U+FF66-FF9F, U+32D0-32FE |
| ideograph | 3 | U+2E80-2FDF, U+3005-3007, U+3021-3029, U+3038-303B, U+3400-4DBF, U+4E00-9FFF, U+F900-FAFF, U+20000-323AF |
| Latin | 4 | A-Z a-z, U+C0-24F except U+D7 and U+F7, U+1E00-1EFF, fullwidth Latin letters |
| digit | 5 | 0-9 and fullwidth digits |
| open | 6 | `( [ {`, U+3008 300A 300C 300E 3010 3014 3016 3018 301A 301D, U+FF08 FF3B FF5B FF5F FF62, U+2018 201C AB 2039 |
| close | 7 | `) ] }`, U+3009 300B 300D 300F 3011 3015 3017 3019 301B 301E 301F, U+FF09 FF3D FF5D FF60 FF63, U+2019 201D BB 203A |
| stop | 8 | U+3001 3002 FF0C FF0E FF61 FF64 |
| space | 9 | U+0-20, U+7F-A0, U+2000-200A, U+AD 1680 200B 200C 200D 2028 2029 202F 205F 2060 3000 FEFF (white space and the invisible line-break controls) |
| edge | 10 | no character (0) |
| middle dot | 11 | U+30FB FF65 B7 |
| symbol | 12 | the rest of U+21-7E, U+A1-BF, U+2010-2BFF, U+3000-303F, U+30A0, U+FF00-FFEF |

(The classes are tested in the order space, open, close, stop, middle dot, hiragana, katakana, ideograph, digit, Latin, symbol, other.)

The features, each a hash bucket (`type` first, then the listed values):

- 0-5: `w[k]` for k = 0..5
- 6-10: `(w[k], w[k+1])` for k = 0..4
- 11-14: `(w[k], w[k+1], w[k+2])` for k = 0..3
- 15: `(w[1], w[2], w[3], w[4])`
- 16-18: `(c[k+1], c[k+2])` for k = 0..2
- 19: `(c[1], c[2], c[3], c[4])`; 20: `(c[0] ... c[5])`
- 21: `(c[2], w[3])`; 22: `(w[2], c[3])`
- 23: the bias, no values

The hash of a feature is 32-bit FNV-1a-like arithmetic on `uint`: `h = (2166136261 xor type) * 16777619`, then for each value `h = (h xor value) * 16777619`
(wrapping), and the bucket is `(h xor (h >> 15)) and 0x1FFFF`: a table of 2^17 signed bytes. The sum of the table entries of all 24 features is the score;
the candidate stays a boundary when the score is above 0 (integer arithmetic only, so the result is the same on every platform).

The table ships as `Unicode/PhraseData.g.cs`: for each non-zero entry in increasing bucket order, the distance from the previous non-zero bucket
(first: from 0) as a LEB128 varint, then the weight as one byte (two's complement). It holds 5,292 non-zero weights in 10.6 KB and is expanded to a
128 KB array on first use.

Cost: a constant number of table reads per candidate, no allocation, linear in the text (the UAX #29 walk is linear too). A 800,000-character text
segments in about the time of four 200,000-character ones; `PhraseTests` checks the scaling.

### Training and data

`tools/phrases/fetch.py` downloads Universal Dependencies Japanese-GSD (CC BY-SA 4.0, commit pinned, SHA-256 checked) and `tools/phrases/train.py fit`
trains the weights. A bunsetsu starts at a token whose `BunsetuBILabel` is `B`; the label of a position is 1 when a bunsetsu starts at the character
after it. Training positions are the ones the model decides (above), taken from the train file joined into runs of one to three consecutive sentences
(so sentence ends are followed by more text, as in a paragraph). The fit is an L1-regularised logistic regression (liblinear, C = 2, chosen on the dev
file from C between 0.05 and 5: C = 0.5 loses 0.002 F1, C = 5 gains 0.0002), scaled so the largest weight is 127, with the bias weight shifted in steps of 2 to
the F1-best threshold on dev. scikit-learn, numpy and scipy (current releases) ran the fit on Python 3.13; the library does not depend on them. Corpus credit and licence
are in THIRD-PARTY-NOTICES.md. `tests/testdata/phrases/parity.tsv` holds the reference implementation's decisions for the sample sentences next to it,
and the library's tests compare its own output with them.

### Measured agreement

Boundaries are compared over the positions the model decides. Gold is the corpus' bunsetsu labels. BudouX 0.10.5 (`load_default_japanese_parser`) was
run as an external program, as a black box; no code or data of it is used. UD_Japanese-PUD (Wikipedia and news sentences, translated; not used in training)
stands in for real text. "Ours" is the reference implementation of the model (identical to the library by the parity test).

| text | positions | ours vs gold P / R / F1 | BudouX vs gold P / R / F1 | ours vs BudouX P / R / F1 |
|---|---|---|---|---|
| GSD test (held out) | 18,511 | 0.978 / 0.979 / **0.978** | 0.916 / 0.913 / 0.914 | 0.916 / 0.920 / **0.918** |
| PUD (never seen) | 38,856 | 0.978 / 0.988 / **0.983** | 0.938 / 0.959 / 0.948 | 0.959 / 0.947 / **0.953** |

On the file the fit was selected on, the dev file, F1 is 0.980; on the training-style test positions (runs of up to three sentences) it is 0.980.
Boundaries per 100 positions: ours 21.7 (GSD) and 23.3 (PUD), BudouX 21.6 and 23.6, corpus 21.7 and 23.1.

The agreement with BudouX is below the agreement with the corpus because the two follow different definitions: the corpus' bunsetsu are exact
particle-and-auxiliary units, and BudouX's phrases are what its model learned from another, browser-oriented segmentation. The model here is closer to
the corpus than BudouX is. The remaining disagreement is where the two draw the unit differently; it is not a defect of either.

### Known limits

- Phrases are bunsetsu-like, learned from news and blog text of one treebank. Classical Japanese, dialect, poetry, and text with unusual
  punctuation will segment less well; there is no dictionary and no tailoring.
- Katakana runs are one word in UAX #29 and stay one phrase, so a long katakana compound is never split, and a katakana word followed by hiragana
  or Han splits only as the model decides.
- A boundary is never put inside a UAX #29 word. Digits and Latin letters stay whole with their neighbours the way UAX #29 keeps them.
- Chinese and Korean are not segmented here; the result for them is the UAX #29 word boundaries.
