##// END OF EJS Templates
Add 2 lines accidentally removed in previous commit
Fernando Perez -
Show More
@@ -1,180 +1,182 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for coloring text in ANSI terminals.
2 """Tools for coloring text in ANSI terminals.
3
3
4 $Id: ColorANSI.py 2167 2007-03-21 06:57:50Z fperez $"""
4 $Id: ColorANSI.py 2167 2007-03-21 06:57:50Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 from IPython import Release
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
15 __license__ = Release.license
16
16
17 __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
17 __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
18
18
19 import os
19 import os
20
20
21 from IPython.ipstruct import Struct
21 from IPython.ipstruct import Struct
22
22
23 def make_color_table(in_class):
23 def make_color_table(in_class):
24 """Build a set of color attributes in a class.
24 """Build a set of color attributes in a class.
25
25
26 Helper function for building the *TermColors classes."""
26 Helper function for building the *TermColors classes."""
27
27
28 color_templates = (
28 color_templates = (
29 # Dark colors
29 # Dark colors
30 ("Black" , "0;30"),
30 ("Black" , "0;30"),
31 ("Red" , "0;31"),
31 ("Red" , "0;31"),
32 ("Green" , "0;32"),
32 ("Green" , "0;32"),
33 ("Brown" , "0;33"),
33 ("Brown" , "0;33"),
34 ("Blue" , "0;34"),
34 ("Blue" , "0;34"),
35 ("Purple" , "0;35"),
35 ("Purple" , "0;35"),
36 ("Cyan" , "0;36"),
36 ("Cyan" , "0;36"),
37 ("LightGray" , "0;37"),
37 ("LightGray" , "0;37"),
38 # Light colors
38 # Light colors
39 ("DarkGray" , "1;30"),
39 ("DarkGray" , "1;30"),
40 ("LightRed" , "1;31"),
40 ("LightRed" , "1;31"),
41 ("LightGreen" , "1;32"),
41 ("LightGreen" , "1;32"),
42 ("Yellow" , "1;33"),
42 ("Yellow" , "1;33"),
43 ("LightBlue" , "1;34"),
43 ("LightBlue" , "1;34"),
44 ("LightPurple" , "1;35"),
44 ("LightPurple" , "1;35"),
45 ("LightCyan" , "1;36"),
45 ("LightCyan" , "1;36"),
46 ("White" , "1;37"),
46 ("White" , "1;37"),
47 # Blinking colors. Probably should not be used in anything serious.
47 # Blinking colors. Probably should not be used in anything serious.
48 ("BlinkBlack" , "5;30"),
48 ("BlinkBlack" , "5;30"),
49 ("BlinkRed" , "5;31"),
49 ("BlinkRed" , "5;31"),
50 ("BlinkGreen" , "5;32"),
50 ("BlinkGreen" , "5;32"),
51 ("BlinkYellow" , "5;33"),
51 ("BlinkYellow" , "5;33"),
52 ("BlinkBlue" , "5;34"),
52 ("BlinkBlue" , "5;34"),
53 ("BlinkPurple" , "5;35"),
53 ("BlinkPurple" , "5;35"),
54 ("BlinkCyan" , "5;36"),
54 ("BlinkCyan" , "5;36"),
55 ("BlinkLightGray", "5;37"),
55 ("BlinkLightGray", "5;37"),
56 )
56 )
57
57
58 for name,value in color_templates:
59 setattr(in_class,name,in_class._base % value)
58
60
59 class TermColors:
61 class TermColors:
60 """Color escape sequences.
62 """Color escape sequences.
61
63
62 This class defines the escape sequences for all the standard (ANSI?)
64 This class defines the escape sequences for all the standard (ANSI?)
63 colors in terminals. Also defines a NoColor escape which is just the null
65 colors in terminals. Also defines a NoColor escape which is just the null
64 string, suitable for defining 'dummy' color schemes in terminals which get
66 string, suitable for defining 'dummy' color schemes in terminals which get
65 confused by color escapes.
67 confused by color escapes.
66
68
67 This class should be used as a mixin for building color schemes."""
69 This class should be used as a mixin for building color schemes."""
68
70
69 NoColor = '' # for color schemes in color-less terminals.
71 NoColor = '' # for color schemes in color-less terminals.
70 Normal = '\033[0m' # Reset normal coloring
72 Normal = '\033[0m' # Reset normal coloring
71 _base = '\033[%sm' # Template for all other colors
73 _base = '\033[%sm' # Template for all other colors
72
74
73 # Build the actual color table as a set of class attributes:
75 # Build the actual color table as a set of class attributes:
74 make_color_table(TermColors)
76 make_color_table(TermColors)
75
77
76 class InputTermColors:
78 class InputTermColors:
77 """Color escape sequences for input prompts.
79 """Color escape sequences for input prompts.
78
80
79 This class is similar to TermColors, but the escapes are wrapped in \001
81 This class is similar to TermColors, but the escapes are wrapped in \001
80 and \002 so that readline can properly know the length of each line and
82 and \002 so that readline can properly know the length of each line and
81 can wrap lines accordingly. Use this class for any colored text which
83 can wrap lines accordingly. Use this class for any colored text which
82 needs to be used in input prompts, such as in calls to raw_input().
84 needs to be used in input prompts, such as in calls to raw_input().
83
85
84 This class defines the escape sequences for all the standard (ANSI?)
86 This class defines the escape sequences for all the standard (ANSI?)
85 colors in terminals. Also defines a NoColor escape which is just the null
87 colors in terminals. Also defines a NoColor escape which is just the null
86 string, suitable for defining 'dummy' color schemes in terminals which get
88 string, suitable for defining 'dummy' color schemes in terminals which get
87 confused by color escapes.
89 confused by color escapes.
88
90
89 This class should be used as a mixin for building color schemes."""
91 This class should be used as a mixin for building color schemes."""
90
92
91 NoColor = '' # for color schemes in color-less terminals.
93 NoColor = '' # for color schemes in color-less terminals.
92
94
93 if os.name == 'nt' and os.environ.get('TERM','dumb') == 'emacs':
95 if os.name == 'nt' and os.environ.get('TERM','dumb') == 'emacs':
94 # (X)emacs on W32 gets confused with \001 and \002 so we remove them
96 # (X)emacs on W32 gets confused with \001 and \002 so we remove them
95 Normal = '\033[0m' # Reset normal coloring
97 Normal = '\033[0m' # Reset normal coloring
96 _base = '\033[%sm' # Template for all other colors
98 _base = '\033[%sm' # Template for all other colors
97 else:
99 else:
98 Normal = '\001\033[0m\002' # Reset normal coloring
100 Normal = '\001\033[0m\002' # Reset normal coloring
99 _base = '\001\033[%sm\002' # Template for all other colors
101 _base = '\001\033[%sm\002' # Template for all other colors
100
102
101 # Build the actual color table as a set of class attributes:
103 # Build the actual color table as a set of class attributes:
102 make_color_table(InputTermColors)
104 make_color_table(InputTermColors)
103
105
104 class ColorScheme:
106 class ColorScheme:
105 """Generic color scheme class. Just a name and a Struct."""
107 """Generic color scheme class. Just a name and a Struct."""
106 def __init__(self,__scheme_name_,colordict=None,**colormap):
108 def __init__(self,__scheme_name_,colordict=None,**colormap):
107 self.name = __scheme_name_
109 self.name = __scheme_name_
108 if colordict is None:
110 if colordict is None:
109 self.colors = Struct(**colormap)
111 self.colors = Struct(**colormap)
110 else:
112 else:
111 self.colors = Struct(colordict)
113 self.colors = Struct(colordict)
112
114
113 def copy(self,name=None):
115 def copy(self,name=None):
114 """Return a full copy of the object, optionally renaming it."""
116 """Return a full copy of the object, optionally renaming it."""
115 if name is None:
117 if name is None:
116 name = self.name
118 name = self.name
117 return ColorScheme(name,self.colors.__dict__)
119 return ColorScheme(name,self.colors.__dict__)
118
120
119 class ColorSchemeTable(dict):
121 class ColorSchemeTable(dict):
120 """General class to handle tables of color schemes.
122 """General class to handle tables of color schemes.
121
123
122 It's basically a dict of color schemes with a couple of shorthand
124 It's basically a dict of color schemes with a couple of shorthand
123 attributes and some convenient methods.
125 attributes and some convenient methods.
124
126
125 active_scheme_name -> obvious
127 active_scheme_name -> obvious
126 active_colors -> actual color table of the active scheme"""
128 active_colors -> actual color table of the active scheme"""
127
129
128 def __init__(self,scheme_list=None,default_scheme=''):
130 def __init__(self,scheme_list=None,default_scheme=''):
129 """Create a table of color schemes.
131 """Create a table of color schemes.
130
132
131 The table can be created empty and manually filled or it can be
133 The table can be created empty and manually filled or it can be
132 created with a list of valid color schemes AND the specification for
134 created with a list of valid color schemes AND the specification for
133 the default active scheme.
135 the default active scheme.
134 """
136 """
135
137
136 # create object attributes to be set later
138 # create object attributes to be set later
137 self.active_scheme_name = ''
139 self.active_scheme_name = ''
138 self.active_colors = None
140 self.active_colors = None
139
141
140 if scheme_list:
142 if scheme_list:
141 if default_scheme == '':
143 if default_scheme == '':
142 raise ValueError,'you must specify the default color scheme'
144 raise ValueError,'you must specify the default color scheme'
143 for scheme in scheme_list:
145 for scheme in scheme_list:
144 self.add_scheme(scheme)
146 self.add_scheme(scheme)
145 self.set_active_scheme(default_scheme)
147 self.set_active_scheme(default_scheme)
146
148
147 def copy(self):
149 def copy(self):
148 """Return full copy of object"""
150 """Return full copy of object"""
149 return ColorSchemeTable(self.values(),self.active_scheme_name)
151 return ColorSchemeTable(self.values(),self.active_scheme_name)
150
152
151 def add_scheme(self,new_scheme):
153 def add_scheme(self,new_scheme):
152 """Add a new color scheme to the table."""
154 """Add a new color scheme to the table."""
153 if not isinstance(new_scheme,ColorScheme):
155 if not isinstance(new_scheme,ColorScheme):
154 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
156 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
155 self[new_scheme.name] = new_scheme
157 self[new_scheme.name] = new_scheme
156
158
157 def set_active_scheme(self,scheme,case_sensitive=0):
159 def set_active_scheme(self,scheme,case_sensitive=0):
158 """Set the currently active scheme.
160 """Set the currently active scheme.
159
161
160 Names are by default compared in a case-insensitive way, but this can
162 Names are by default compared in a case-insensitive way, but this can
161 be changed by setting the parameter case_sensitive to true."""
163 be changed by setting the parameter case_sensitive to true."""
162
164
163 scheme_names = self.keys()
165 scheme_names = self.keys()
164 if case_sensitive:
166 if case_sensitive:
165 valid_schemes = scheme_names
167 valid_schemes = scheme_names
166 scheme_test = scheme
168 scheme_test = scheme
167 else:
169 else:
168 valid_schemes = [s.lower() for s in scheme_names]
170 valid_schemes = [s.lower() for s in scheme_names]
169 scheme_test = scheme.lower()
171 scheme_test = scheme.lower()
170 try:
172 try:
171 scheme_idx = valid_schemes.index(scheme_test)
173 scheme_idx = valid_schemes.index(scheme_test)
172 except ValueError:
174 except ValueError:
173 raise ValueError,'Unrecognized color scheme: ' + scheme + \
175 raise ValueError,'Unrecognized color scheme: ' + scheme + \
174 '\nValid schemes: '+str(scheme_names).replace("'', ",'')
176 '\nValid schemes: '+str(scheme_names).replace("'', ",'')
175 else:
177 else:
176 active = scheme_names[scheme_idx]
178 active = scheme_names[scheme_idx]
177 self.active_scheme_name = active
179 self.active_scheme_name = active
178 self.active_colors = self[active].colors
180 self.active_colors = self[active].colors
179 # Now allow using '' as an index for the current active scheme
181 # Now allow using '' as an index for the current active scheme
180 self[''] = self[active]
182 self[''] = self[active]
General Comments 0
You need to be logged in to leave comments. Login now