wcwidth.py 1.3 KB

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