Code Points and Visible Characters in Strings

A text position may count bytes, Unicode code points, or grapheme clusters, which represent many visible character units.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Compare two spellings
  2. Choose what the feature promises
  3. Inspect one string at three levels
  4. Map positions only within one representation

Compare two spellings

Python can store é as one precomposed code point or as e followed by a combining accent. Those strings can look the same and have different code point lengths. Byte length adds another measure, introduced by text encoding.

Choose what the feature promises

A limit on encoded file size needs bytes. A cursor intended to move between visible characters can follow Unicode grapheme-boundary rules. Representing values with units helps specify which limit or index the interface exposes.[1][2]

Inspect one string at three levels

The sequence "e\u0301x" contains three Unicode code points. Encoding it in UTF-8 uses four bytes: one for e, two for the combining acute accent and one for x. A reader generally sees two characters, an accented e followed by x. Truncating after one code point keeps a bare e. Truncating after two bytes leaves the combining mark's UTF-8 representation incomplete. Specify which unit an offset represents. See strings and bytes.

Map positions only within one representation

A search backend might report byte offsets into original stored text while a frontend uses character offsets after normalization. Even a small accented example can shift later positions. For highlighting, either agree on one canonical representation or maintain a mapping from normalized ranges back to the original. Test a combining mark before a matched string and a match near its end. See normalization and text equality.

References

  1. IETF, RFC 3629: UTF-8, a Transformation Format of ISO 10646 ↩
  2. Unicode Consortium, Unicode Standard Annex 29: Unicode Text Segmentation ↩