1 # -*- coding: utf-8 -*- |
|
2 """ |
|
3 sphinx.util.console |
|
4 ~~~~~~~~~~~~~~~~~~~ |
|
5 |
|
6 Format colored console output. |
|
7 |
|
8 :copyright: 2007-2008 by Georg Brandl. |
|
9 :license: BSD. |
|
10 """ |
|
11 |
|
12 import os |
|
13 |
|
14 codes = {} |
|
15 |
|
16 def get_terminal_width(): |
|
17 """Borrowed from the py lib.""" |
|
18 try: |
|
19 import os, termios, fcntl, struct |
|
20 call = fcntl.ioctl(0, termios.TIOCGWINSZ, "\000"*8) |
|
21 height, width = struct.unpack("hhhh", call)[:2] |
|
22 terminal_width = width |
|
23 except (SystemExit, KeyboardInterrupt): |
|
24 raise |
|
25 except: |
|
26 # FALLBACK |
|
27 terminal_width = int(os.environ.get('COLUMNS', 80))-1 |
|
28 return terminal_width |
|
29 |
|
30 _tw = get_terminal_width() |
|
31 |
|
32 def print_and_backspace(text, func): |
|
33 if not codes: |
|
34 # if no coloring, don't output fancy backspaces |
|
35 func(text) |
|
36 else: |
|
37 func(text.ljust(_tw) + _tw * "\b") |
|
38 |
|
39 def color_terminal(): |
|
40 if 'COLORTERM' in os.environ: |
|
41 return True |
|
42 term = os.environ.get('TERM', 'dumb').lower() |
|
43 if 'xterm' in term or 'color' in term: |
|
44 return True |
|
45 return False |
|
46 |
|
47 |
|
48 def nocolor(): |
|
49 codes.clear() |
|
50 |
|
51 def coloron(): |
|
52 codes.update(_orig_codes) |
|
53 |
|
54 def colorize(name, text): |
|
55 return codes.get(name, '') + text + codes.get('reset', '') |
|
56 |
|
57 def create_color_func(name): |
|
58 def inner(text): |
|
59 return colorize(name, text) |
|
60 globals()[name] = inner |
|
61 |
|
62 _attrs = { |
|
63 'reset': '39;49;00m', |
|
64 'bold': '01m', |
|
65 'faint': '02m', |
|
66 'standout': '03m', |
|
67 'underline': '04m', |
|
68 'blink': '05m', |
|
69 } |
|
70 |
|
71 for _name, _value in _attrs.items(): |
|
72 codes[_name] = '\x1b[' + _value |
|
73 |
|
74 _colors = [ |
|
75 ('black', 'darkgray'), |
|
76 ('darkred', 'red'), |
|
77 ('darkgreen', 'green'), |
|
78 ('brown', 'yellow'), |
|
79 ('darkblue', 'blue'), |
|
80 ('purple', 'fuchsia'), |
|
81 ('turquoise', 'teal'), |
|
82 ('lightgray', 'white'), |
|
83 ] |
|
84 |
|
85 for i, (dark, light) in enumerate(_colors): |
|
86 codes[dark] = '\x1b[%im' % (i+30) |
|
87 codes[light] = '\x1b[%i;01m' % (i+30) |
|
88 |
|
89 _orig_codes = codes.copy() |
|
90 |
|
91 for _name in codes: |
|
92 create_color_func(_name) |
|