NewsCrawler.org

Measuring Terminal Character Width with Per-Terminal Correction Tables

/images/mode2027nosupport-zwj-errors.png
/images/mode2027-zwj-errors.png
/images/rich-before-and-after.png
Image: jeffquast.com

The author writes that measuring the width of Unicode characters in terminals has always been difficult. Terminal emulators interpret the Unicode standards differently, down to single codepoints and grapheme widths. For 12 and 6 years the author has improved the Python wcwidth[1] and ucs-detect[2] libraries, and argues that the problem cannot be solved by specifications, implementations and compliance reports alone.

The new wcstwidth() function in wcwidth returns a width corrected for the terminal that calls it, using correction tables built from ucs-detect data for about 35 terminals. For example, wcwidth.wcwidth('🧟♂') returns 2, while wcstwidth('🧟♂', term_program='VTE') returns 8. Correction requires knowing which terminal is running, which is checked through the TERM and TERM_PROGRAM environment variables or by sending the XTVERSION[3] query, supported by 21 terminals. TERM_PROGRAM is not passed over SSH without extra configuration, and terminal multiplexers are excluded from correction tables.

The author presents the Kitty Text Sizing Protocol[4] as a general-purpose complement: wrapping text in its sequence keeps the width of graphemes beyond 2 cells reliable. The author added support for the protocol to the blessed library with does_text_sizing() and text_sized(), and changed ucs-detect to report a score of '100' for Unicode categories when the protocol is supported.

Read the original jeffquast.comDiscussion

Sources

Published: First seen: Читать по-русски

Open as a page