Fixed #7496 -- It's now possible to pickle SortedDicts with pickle protocol 2
[django.git] / django / utils / termcolors.py
blob17a600f8999b549591c8281a134b130d873f15b6
1 """
2 termcolors.py
3 """
5 color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
6 foreground = dict([(color_names[x], '3%s' % x) for x in range(8)])
7 background = dict([(color_names[x], '4%s' % x) for x in range(8)])
8 del color_names
10 RESET = '0'
11 opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}
13 def colorize(text='', opts=(), **kwargs):
14 """
15 Returns your text, enclosed in ANSI graphics codes.
17 Depends on the keyword arguments 'fg' and 'bg', and the contents of
18 the opts tuple/list.
20 Returns the RESET code if no parameters are given.
22 Valid colors:
23 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
25 Valid options:
26 'bold'
27 'underscore'
28 'blink'
29 'reverse'
30 'conceal'
31 'noreset' - string will not be auto-terminated with the RESET code
33 Examples:
34 colorize('hello', fg='red', bg='blue', opts=('blink',))
35 colorize()
36 colorize('goodbye', opts=('underscore',))
37 print colorize('first line', fg='red', opts=('noreset',))
38 print 'this should be red too'
39 print colorize('and so should this')
40 print 'this should not be red'
41 """
42 text = str(text)
43 code_list = []
44 if text == '' and len(opts) == 1 and opts[0] == 'reset':
45 return '\x1b[%sm' % RESET
46 for k, v in kwargs.iteritems():
47 if k == 'fg':
48 code_list.append(foreground[v])
49 elif k == 'bg':
50 code_list.append(background[v])
51 for o in opts:
52 if o in opt_dict:
53 code_list.append(opt_dict[o])
54 if 'noreset' not in opts:
55 text = text + '\x1b[%sm' % RESET
56 return ('\x1b[%sm' % ';'.join(code_list)) + text
58 def make_style(opts=(), **kwargs):
59 """
60 Returns a function with default parameters for colorize()
62 Example:
63 bold_red = make_style(opts=('bold',), fg='red')
64 print bold_red('hello')
65 KEYWORD = make_style(fg='yellow')
66 COMMENT = make_style(fg='blue', opts=('bold',))
67 """
68 return lambda text: colorize(text, opts, **kwargs)