Determine how many columns are needed to display a character in a terminal. Returns -1 if the character is not printable. Returns 0, 1 or 2 for other characters.
(c: str)
| 6 | |
| 7 | @lru_cache(100) |
| 8 | def wcwidth(c: str) -> int: |
| 9 | """Determine how many columns are needed to display a character in a terminal. |
| 10 | |
| 11 | Returns -1 if the character is not printable. |
| 12 | Returns 0, 1 or 2 for other characters. |
| 13 | """ |
| 14 | o = ord(c) |
| 15 | |
| 16 | # ASCII fast path. |
| 17 | if 0x20 <= o < 0x07F: |
| 18 | return 1 |
| 19 | |
| 20 | # Some Cf/Zp/Zl characters which should be zero-width. |
| 21 | if ( |
| 22 | o == 0x0000 |
| 23 | or 0x200B <= o <= 0x200F |
| 24 | or 0x2028 <= o <= 0x202E |
| 25 | or 0x2060 <= o <= 0x2063 |
| 26 | ): |
| 27 | return 0 |
| 28 | |
| 29 | category = unicodedata.category(c) |
| 30 | |
| 31 | # Control characters. |
| 32 | if category == "Cc": |
| 33 | return -1 |
| 34 | |
| 35 | # Combining characters with zero width. |
| 36 | if category in ("Me", "Mn"): |
| 37 | return 0 |
| 38 | |
| 39 | # Full/Wide east asian characters. |
| 40 | if unicodedata.east_asian_width(c) in ("F", "W"): |
| 41 | return 2 |
| 42 | |
| 43 | return 1 |
| 44 | |
| 45 | |
| 46 | def wcswidth(s: str) -> int: |
no outgoing calls
searching dependent graphs…