Debian Codegraph @

src/_pytest/_io/wcwidth.py

raw
1 from __future__ import annotations
2
3 from functools import lru_cache
4 import unicodedata
5
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:
47 """Determine how many columns are needed to display a string in a terminal.
48
49 Returns -1 if the string contains non-printable characters.
50 """
51 width = 0
52 for c in unicodedata.normalize("NFC", s):
53 wc = wcwidth(c)
54 if wc < 0:
55 return -1
56 width += wc
57 return width