| 1 |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. |
| 2 |
''' |
| 3 |
This module generates ANSI character codes to printing colors to terminals. |
| 4 |
See: http://en.wikipedia.org/wiki/ANSI_escape_code |
| 5 |
''' |
| 6 |
|
| 7 |
CSI = '\033[' |
| 8 |
OSC = '\033]' |
| 9 |
BEL = '\a' |
| 10 |
|
| 11 |
|
| 12 |
def code_to_chars(code): |
| 13 |
return CSI + str(code) + 'm' |
| 14 |
|
| 15 |
def set_title(title): |
| 16 |
return OSC + '2;' + title + BEL |
| 17 |
|
| 18 |
def clear_screen(mode=2): |
| 19 |
return CSI + str(mode) + 'J' |
| 20 |
|
| 21 |
def clear_line(mode=2): |
| 22 |
return CSI + str(mode) + 'K' |
| 23 |
|
| 24 |
|
| 25 |
class AnsiCodes(object): |
| 26 |
def __init__(self): |
| 27 |
# the subclasses declare class attributes which are numbers. |
| 28 |
# Upon instantiation we define instance attributes, which are the same |
| 29 |
# as the class attributes but wrapped with the ANSI escape sequence |
| 30 |
for name in dir(self): |
| 31 |
if not name.startswith('_'): |
| 32 |
value = getattr(self, name) |
| 33 |
setattr(self, name, code_to_chars(value)) |
| 34 |
|
| 35 |
|
| 36 |
class AnsiCursor(object): |
| 37 |
def UP(self, n=1): |
| 38 |
return CSI + str(n) + 'A' |
| 39 |
def DOWN(self, n=1): |
| 40 |
return CSI + str(n) + 'B' |
| 41 |
def FORWARD(self, n=1): |
| 42 |
return CSI + str(n) + 'C' |
| 43 |
def BACK(self, n=1): |
| 44 |
return CSI + str(n) + 'D' |
| 45 |
def POS(self, x=1, y=1): |
| 46 |
return CSI + str(y) + ';' + str(x) + 'H' |
| 47 |
|
| 48 |
|
| 49 |
class AnsiFore(AnsiCodes): |
| 50 |
BLACK = 30 |
| 51 |
RED = 31 |
| 52 |
GREEN = 32 |
| 53 |
YELLOW = 33 |
| 54 |
BLUE = 34 |
| 55 |
MAGENTA = 35 |
| 56 |
CYAN = 36 |
| 57 |
WHITE = 37 |
| 58 |
RESET = 39 |
| 59 |
|
| 60 |
# These are fairly well supported, but not part of the standard. |
| 61 |
LIGHTBLACK_EX = 90 |
| 62 |
LIGHTRED_EX = 91 |
| 63 |
LIGHTGREEN_EX = 92 |
| 64 |
LIGHTYELLOW_EX = 93 |
| 65 |
LIGHTBLUE_EX = 94 |
| 66 |
LIGHTMAGENTA_EX = 95 |
| 67 |
LIGHTCYAN_EX = 96 |
| 68 |
LIGHTWHITE_EX = 97 |
| 69 |
|
| 70 |
|
| 71 |
class AnsiBack(AnsiCodes): |
| 72 |
BLACK = 40 |
| 73 |
RED = 41 |
| 74 |
GREEN = 42 |
| 75 |
YELLOW = 43 |
| 76 |
BLUE = 44 |
| 77 |
MAGENTA = 45 |
| 78 |
CYAN = 46 |
| 79 |
WHITE = 47 |
| 80 |
RESET = 49 |
| 81 |
|
| 82 |
# These are fairly well supported, but not part of the standard. |
| 83 |
LIGHTBLACK_EX = 100 |
| 84 |
LIGHTRED_EX = 101 |
| 85 |
LIGHTGREEN_EX = 102 |
| 86 |
LIGHTYELLOW_EX = 103 |
| 87 |
LIGHTBLUE_EX = 104 |
| 88 |
LIGHTMAGENTA_EX = 105 |
| 89 |
LIGHTCYAN_EX = 106 |
| 90 |
LIGHTWHITE_EX = 107 |
| 91 |
|
| 92 |
|
| 93 |
class AnsiStyle(AnsiCodes): |
| 94 |
BRIGHT = 1 |
| 95 |
DIM = 2 |
| 96 |
NORMAL = 22 |
| 97 |
RESET_ALL = 0 |
| 98 |
|
| 99 |
Fore = AnsiFore() |
| 100 |
Back = AnsiBack() |
| 101 |
Style = AnsiStyle() |
| 102 |
Cursor = AnsiCursor() |