1"""
2Generates a dictionary of ANSI escape codes.
3
4http://en.wikipedia.org/wiki/ANSI_escape_code
5
6Uses colorama as an optional dependency to support color on Windows
7"""
8
9import sys
10
11try:
12 import colorama
13except ImportError:
14 pass
15else:
16 if sys.platform == "win32":
17 colorama.init(strip=False)
18
19__all__ = ("escape_codes", "parse_colors")
20
21
22# Returns escape codes from format codes
23def esc(*codes: int) -> str:
24 return "\033[" + ";".join(str(code) for code in codes) + "m"
25
26
27escape_codes = {
28 "reset": esc(0),
29 "bold": esc(1),
30 "thin": esc(2),
31}
32
33escape_codes_foreground = {
34 "black": 30,
35 "red": 31,
36 "green": 32,
37 "yellow": 33,
38 "blue": 34,
39 "purple": 35,
40 "cyan": 36,
41 "white": 37,
42 "light_black": 90,
43 "light_red": 91,
44 "light_green": 92,
45 "light_yellow": 93,
46 "light_blue": 94,
47 "light_purple": 95,
48 "light_cyan": 96,
49 "light_white": 97,
50}
51
52escape_codes_background = {
53 "black": 40,
54 "red": 41,
55 "green": 42,
56 "yellow": 43,
57 "blue": 44,
58 "purple": 45,
59 "cyan": 46,
60 "white": 47,
61 "light_black": 100,
62 "light_red": 101,
63 "light_green": 102,
64 "light_yellow": 103,
65 "light_blue": 104,
66 "light_purple": 105,
67 "light_cyan": 106,
68 "light_white": 107,
69 # Bold background colors don't exist,
70 # but we used to provide these names.
71 "bold_black": 100,
72 "bold_red": 101,
73 "bold_green": 102,
74 "bold_yellow": 103,
75 "bold_blue": 104,
76 "bold_purple": 105,
77 "bold_cyan": 106,
78 "bold_white": 107,
79}
80
81# Foreground without prefix
82for name, code in escape_codes_foreground.items():
83 escape_codes["%s" % name] = esc(code)
84 escape_codes["bold_%s" % name] = esc(1, code)
85 escape_codes["thin_%s" % name] = esc(2, code)
86
87# Foreground with fg_ prefix
88for name, code in escape_codes_foreground.items():
89 escape_codes["fg_%s" % name] = esc(code)
90 escape_codes["fg_bold_%s" % name] = esc(1, code)
91 escape_codes["fg_thin_%s" % name] = esc(2, code)
92
93# Background with bg_ prefix
94for name, code in escape_codes_background.items():
95 escape_codes["bg_%s" % name] = esc(code)
96
97# 256 colour support
98for code in range(256):
99 escape_codes["fg_%d" % code] = esc(38, 5, code)
100 escape_codes["bg_%d" % code] = esc(48, 5, code)
101
102
103def parse_colors(string: str) -> str:
104 """Return escape codes from a color sequence string."""
105 return "".join(escape_codes[n] for n in string.split(",") if n)