##// END OF EJS Templates
color: add basic documentation to 'debugcolor'...
Pierre-Yves David -
r30282:7a53458f default
parent child Browse files
Show More
@@ -1,689 +1,690 b''
1 # color.py color output for Mercurial commands
1 # color.py color output for Mercurial commands
2 #
2 #
3 # Copyright (C) 2007 Kevin Christen <kevin.christen@gmail.com>
3 # Copyright (C) 2007 Kevin Christen <kevin.christen@gmail.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 '''colorize output from some commands
8 '''colorize output from some commands
9
9
10 The color extension colorizes output from several Mercurial commands.
10 The color extension colorizes output from several Mercurial commands.
11 For example, the diff command shows additions in green and deletions
11 For example, the diff command shows additions in green and deletions
12 in red, while the status command shows modified files in magenta. Many
12 in red, while the status command shows modified files in magenta. Many
13 other commands have analogous colors. It is possible to customize
13 other commands have analogous colors. It is possible to customize
14 these colors.
14 these colors.
15
15
16 Effects
16 Effects
17 -------
17 -------
18
18
19 Other effects in addition to color, like bold and underlined text, are
19 Other effects in addition to color, like bold and underlined text, are
20 also available. By default, the terminfo database is used to find the
20 also available. By default, the terminfo database is used to find the
21 terminal codes used to change color and effect. If terminfo is not
21 terminal codes used to change color and effect. If terminfo is not
22 available, then effects are rendered with the ECMA-48 SGR control
22 available, then effects are rendered with the ECMA-48 SGR control
23 function (aka ANSI escape codes).
23 function (aka ANSI escape codes).
24
24
25 The available effects in terminfo mode are 'blink', 'bold', 'dim',
25 The available effects in terminfo mode are 'blink', 'bold', 'dim',
26 'inverse', 'invisible', 'italic', 'standout', and 'underline'; in
26 'inverse', 'invisible', 'italic', 'standout', and 'underline'; in
27 ECMA-48 mode, the options are 'bold', 'inverse', 'italic', and
27 ECMA-48 mode, the options are 'bold', 'inverse', 'italic', and
28 'underline'. How each is rendered depends on the terminal emulator.
28 'underline'. How each is rendered depends on the terminal emulator.
29 Some may not be available for a given terminal type, and will be
29 Some may not be available for a given terminal type, and will be
30 silently ignored.
30 silently ignored.
31
31
32 If the terminfo entry for your terminal is missing codes for an effect
32 If the terminfo entry for your terminal is missing codes for an effect
33 or has the wrong codes, you can add or override those codes in your
33 or has the wrong codes, you can add or override those codes in your
34 configuration::
34 configuration::
35
35
36 [color]
36 [color]
37 terminfo.dim = \E[2m
37 terminfo.dim = \E[2m
38
38
39 where '\E' is substituted with an escape character.
39 where '\E' is substituted with an escape character.
40
40
41 Labels
41 Labels
42 ------
42 ------
43
43
44 Text receives color effects depending on the labels that it has. Many
44 Text receives color effects depending on the labels that it has. Many
45 default Mercurial commands emit labelled text. You can also define
45 default Mercurial commands emit labelled text. You can also define
46 your own labels in templates using the label function, see :hg:`help
46 your own labels in templates using the label function, see :hg:`help
47 templates`. A single portion of text may have more than one label. In
47 templates`. A single portion of text may have more than one label. In
48 that case, effects given to the last label will override any other
48 that case, effects given to the last label will override any other
49 effects. This includes the special "none" effect, which nullifies
49 effects. This includes the special "none" effect, which nullifies
50 other effects.
50 other effects.
51
51
52 Labels are normally invisible. In order to see these labels and their
52 Labels are normally invisible. In order to see these labels and their
53 position in the text, use the global --color=debug option. The same
53 position in the text, use the global --color=debug option. The same
54 anchor text may be associated to multiple labels, e.g.
54 anchor text may be associated to multiple labels, e.g.
55
55
56 [log.changeset changeset.secret|changeset: 22611:6f0a53c8f587]
56 [log.changeset changeset.secret|changeset: 22611:6f0a53c8f587]
57
57
58 The following are the default effects for some default labels. Default
58 The following are the default effects for some default labels. Default
59 effects may be overridden from your configuration file::
59 effects may be overridden from your configuration file::
60
60
61 [color]
61 [color]
62 status.modified = blue bold underline red_background
62 status.modified = blue bold underline red_background
63 status.added = green bold
63 status.added = green bold
64 status.removed = red bold blue_background
64 status.removed = red bold blue_background
65 status.deleted = cyan bold underline
65 status.deleted = cyan bold underline
66 status.unknown = magenta bold underline
66 status.unknown = magenta bold underline
67 status.ignored = black bold
67 status.ignored = black bold
68
68
69 # 'none' turns off all effects
69 # 'none' turns off all effects
70 status.clean = none
70 status.clean = none
71 status.copied = none
71 status.copied = none
72
72
73 qseries.applied = blue bold underline
73 qseries.applied = blue bold underline
74 qseries.unapplied = black bold
74 qseries.unapplied = black bold
75 qseries.missing = red bold
75 qseries.missing = red bold
76
76
77 diff.diffline = bold
77 diff.diffline = bold
78 diff.extended = cyan bold
78 diff.extended = cyan bold
79 diff.file_a = red bold
79 diff.file_a = red bold
80 diff.file_b = green bold
80 diff.file_b = green bold
81 diff.hunk = magenta
81 diff.hunk = magenta
82 diff.deleted = red
82 diff.deleted = red
83 diff.inserted = green
83 diff.inserted = green
84 diff.changed = white
84 diff.changed = white
85 diff.tab =
85 diff.tab =
86 diff.trailingwhitespace = bold red_background
86 diff.trailingwhitespace = bold red_background
87
87
88 # Blank so it inherits the style of the surrounding label
88 # Blank so it inherits the style of the surrounding label
89 changeset.public =
89 changeset.public =
90 changeset.draft =
90 changeset.draft =
91 changeset.secret =
91 changeset.secret =
92
92
93 resolve.unresolved = red bold
93 resolve.unresolved = red bold
94 resolve.resolved = green bold
94 resolve.resolved = green bold
95
95
96 bookmarks.active = green
96 bookmarks.active = green
97
97
98 branches.active = none
98 branches.active = none
99 branches.closed = black bold
99 branches.closed = black bold
100 branches.current = green
100 branches.current = green
101 branches.inactive = none
101 branches.inactive = none
102
102
103 tags.normal = green
103 tags.normal = green
104 tags.local = black bold
104 tags.local = black bold
105
105
106 rebase.rebased = blue
106 rebase.rebased = blue
107 rebase.remaining = red bold
107 rebase.remaining = red bold
108
108
109 shelve.age = cyan
109 shelve.age = cyan
110 shelve.newest = green bold
110 shelve.newest = green bold
111 shelve.name = blue bold
111 shelve.name = blue bold
112
112
113 histedit.remaining = red bold
113 histedit.remaining = red bold
114
114
115 Custom colors
115 Custom colors
116 -------------
116 -------------
117
117
118 Because there are only eight standard colors, this module allows you
118 Because there are only eight standard colors, this module allows you
119 to define color names for other color slots which might be available
119 to define color names for other color slots which might be available
120 for your terminal type, assuming terminfo mode. For instance::
120 for your terminal type, assuming terminfo mode. For instance::
121
121
122 color.brightblue = 12
122 color.brightblue = 12
123 color.pink = 207
123 color.pink = 207
124 color.orange = 202
124 color.orange = 202
125
125
126 to set 'brightblue' to color slot 12 (useful for 16 color terminals
126 to set 'brightblue' to color slot 12 (useful for 16 color terminals
127 that have brighter colors defined in the upper eight) and, 'pink' and
127 that have brighter colors defined in the upper eight) and, 'pink' and
128 'orange' to colors in 256-color xterm's default color cube. These
128 'orange' to colors in 256-color xterm's default color cube. These
129 defined colors may then be used as any of the pre-defined eight,
129 defined colors may then be used as any of the pre-defined eight,
130 including appending '_background' to set the background to that color.
130 including appending '_background' to set the background to that color.
131
131
132 Modes
132 Modes
133 -----
133 -----
134
134
135 By default, the color extension will use ANSI mode (or win32 mode on
135 By default, the color extension will use ANSI mode (or win32 mode on
136 Windows) if it detects a terminal. To override auto mode (to enable
136 Windows) if it detects a terminal. To override auto mode (to enable
137 terminfo mode, for example), set the following configuration option::
137 terminfo mode, for example), set the following configuration option::
138
138
139 [color]
139 [color]
140 mode = terminfo
140 mode = terminfo
141
141
142 Any value other than 'ansi', 'win32', 'terminfo', or 'auto' will
142 Any value other than 'ansi', 'win32', 'terminfo', or 'auto' will
143 disable color.
143 disable color.
144
144
145 Note that on some systems, terminfo mode may cause problems when using
145 Note that on some systems, terminfo mode may cause problems when using
146 color with the pager extension and less -R. less with the -R option
146 color with the pager extension and less -R. less with the -R option
147 will only display ECMA-48 color codes, and terminfo mode may sometimes
147 will only display ECMA-48 color codes, and terminfo mode may sometimes
148 emit codes that less doesn't understand. You can work around this by
148 emit codes that less doesn't understand. You can work around this by
149 either using ansi mode (or auto mode), or by using less -r (which will
149 either using ansi mode (or auto mode), or by using less -r (which will
150 pass through all terminal control codes, not just color control
150 pass through all terminal control codes, not just color control
151 codes).
151 codes).
152
152
153 On some systems (such as MSYS in Windows), the terminal may support
153 On some systems (such as MSYS in Windows), the terminal may support
154 a different color mode than the pager (activated via the "pager"
154 a different color mode than the pager (activated via the "pager"
155 extension). It is possible to define separate modes depending on whether
155 extension). It is possible to define separate modes depending on whether
156 the pager is active::
156 the pager is active::
157
157
158 [color]
158 [color]
159 mode = auto
159 mode = auto
160 pagermode = ansi
160 pagermode = ansi
161
161
162 If ``pagermode`` is not defined, the ``mode`` will be used.
162 If ``pagermode`` is not defined, the ``mode`` will be used.
163 '''
163 '''
164
164
165 from __future__ import absolute_import
165 from __future__ import absolute_import
166
166
167 import os
167 import os
168
168
169 from mercurial.i18n import _
169 from mercurial.i18n import _
170 from mercurial import (
170 from mercurial import (
171 cmdutil,
171 cmdutil,
172 commands,
172 commands,
173 dispatch,
173 dispatch,
174 extensions,
174 extensions,
175 subrepo,
175 subrepo,
176 ui as uimod,
176 ui as uimod,
177 util,
177 util,
178 )
178 )
179
179
180 cmdtable = {}
180 cmdtable = {}
181 command = cmdutil.command(cmdtable)
181 command = cmdutil.command(cmdtable)
182 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
182 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
183 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
183 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
184 # be specifying the version(s) of Mercurial they are tested with, or
184 # be specifying the version(s) of Mercurial they are tested with, or
185 # leave the attribute unspecified.
185 # leave the attribute unspecified.
186 testedwith = 'ships-with-hg-core'
186 testedwith = 'ships-with-hg-core'
187
187
188 # start and stop parameters for effects
188 # start and stop parameters for effects
189 _effects = {'none': 0, 'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
189 _effects = {'none': 0, 'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
190 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37, 'bold': 1,
190 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37, 'bold': 1,
191 'italic': 3, 'underline': 4, 'inverse': 7, 'dim': 2,
191 'italic': 3, 'underline': 4, 'inverse': 7, 'dim': 2,
192 'black_background': 40, 'red_background': 41,
192 'black_background': 40, 'red_background': 41,
193 'green_background': 42, 'yellow_background': 43,
193 'green_background': 42, 'yellow_background': 43,
194 'blue_background': 44, 'purple_background': 45,
194 'blue_background': 44, 'purple_background': 45,
195 'cyan_background': 46, 'white_background': 47}
195 'cyan_background': 46, 'white_background': 47}
196
196
197 def _terminfosetup(ui, mode):
197 def _terminfosetup(ui, mode):
198 '''Initialize terminfo data and the terminal if we're in terminfo mode.'''
198 '''Initialize terminfo data and the terminal if we're in terminfo mode.'''
199
199
200 global _terminfo_params
200 global _terminfo_params
201 # If we failed to load curses, we go ahead and return.
201 # If we failed to load curses, we go ahead and return.
202 if not _terminfo_params:
202 if not _terminfo_params:
203 return
203 return
204 # Otherwise, see what the config file says.
204 # Otherwise, see what the config file says.
205 if mode not in ('auto', 'terminfo'):
205 if mode not in ('auto', 'terminfo'):
206 return
206 return
207
207
208 _terminfo_params.update((key[6:], (False, int(val), ''))
208 _terminfo_params.update((key[6:], (False, int(val), ''))
209 for key, val in ui.configitems('color')
209 for key, val in ui.configitems('color')
210 if key.startswith('color.'))
210 if key.startswith('color.'))
211 _terminfo_params.update((key[9:], (True, '', val.replace('\\E', '\x1b')))
211 _terminfo_params.update((key[9:], (True, '', val.replace('\\E', '\x1b')))
212 for key, val in ui.configitems('color')
212 for key, val in ui.configitems('color')
213 if key.startswith('terminfo.'))
213 if key.startswith('terminfo.'))
214
214
215 try:
215 try:
216 curses.setupterm()
216 curses.setupterm()
217 except curses.error as e:
217 except curses.error as e:
218 _terminfo_params = {}
218 _terminfo_params = {}
219 return
219 return
220
220
221 for key, (b, e, c) in _terminfo_params.items():
221 for key, (b, e, c) in _terminfo_params.items():
222 if not b:
222 if not b:
223 continue
223 continue
224 if not c and not curses.tigetstr(e):
224 if not c and not curses.tigetstr(e):
225 # Most terminals don't support dim, invis, etc, so don't be
225 # Most terminals don't support dim, invis, etc, so don't be
226 # noisy and use ui.debug().
226 # noisy and use ui.debug().
227 ui.debug("no terminfo entry for %s\n" % e)
227 ui.debug("no terminfo entry for %s\n" % e)
228 del _terminfo_params[key]
228 del _terminfo_params[key]
229 if not curses.tigetstr('setaf') or not curses.tigetstr('setab'):
229 if not curses.tigetstr('setaf') or not curses.tigetstr('setab'):
230 # Only warn about missing terminfo entries if we explicitly asked for
230 # Only warn about missing terminfo entries if we explicitly asked for
231 # terminfo mode.
231 # terminfo mode.
232 if mode == "terminfo":
232 if mode == "terminfo":
233 ui.warn(_("no terminfo entry for setab/setaf: reverting to "
233 ui.warn(_("no terminfo entry for setab/setaf: reverting to "
234 "ECMA-48 color\n"))
234 "ECMA-48 color\n"))
235 _terminfo_params = {}
235 _terminfo_params = {}
236
236
237 def _modesetup(ui, coloropt):
237 def _modesetup(ui, coloropt):
238 global _terminfo_params
238 global _terminfo_params
239
239
240 if coloropt == 'debug':
240 if coloropt == 'debug':
241 return 'debug'
241 return 'debug'
242
242
243 auto = (coloropt == 'auto')
243 auto = (coloropt == 'auto')
244 always = not auto and util.parsebool(coloropt)
244 always = not auto and util.parsebool(coloropt)
245 if not always and not auto:
245 if not always and not auto:
246 return None
246 return None
247
247
248 formatted = always or (os.environ.get('TERM') != 'dumb' and ui.formatted())
248 formatted = always or (os.environ.get('TERM') != 'dumb' and ui.formatted())
249
249
250 mode = ui.config('color', 'mode', 'auto')
250 mode = ui.config('color', 'mode', 'auto')
251
251
252 # If pager is active, color.pagermode overrides color.mode.
252 # If pager is active, color.pagermode overrides color.mode.
253 if getattr(ui, 'pageractive', False):
253 if getattr(ui, 'pageractive', False):
254 mode = ui.config('color', 'pagermode', mode)
254 mode = ui.config('color', 'pagermode', mode)
255
255
256 realmode = mode
256 realmode = mode
257 if mode == 'auto':
257 if mode == 'auto':
258 if os.name == 'nt':
258 if os.name == 'nt':
259 term = os.environ.get('TERM')
259 term = os.environ.get('TERM')
260 # TERM won't be defined in a vanilla cmd.exe environment.
260 # TERM won't be defined in a vanilla cmd.exe environment.
261
261
262 # UNIX-like environments on Windows such as Cygwin and MSYS will
262 # UNIX-like environments on Windows such as Cygwin and MSYS will
263 # set TERM. They appear to make a best effort attempt at setting it
263 # set TERM. They appear to make a best effort attempt at setting it
264 # to something appropriate. However, not all environments with TERM
264 # to something appropriate. However, not all environments with TERM
265 # defined support ANSI. Since "ansi" could result in terminal
265 # defined support ANSI. Since "ansi" could result in terminal
266 # gibberish, we error on the side of selecting "win32". However, if
266 # gibberish, we error on the side of selecting "win32". However, if
267 # w32effects is not defined, we almost certainly don't support
267 # w32effects is not defined, we almost certainly don't support
268 # "win32", so don't even try.
268 # "win32", so don't even try.
269 if (term and 'xterm' in term) or not w32effects:
269 if (term and 'xterm' in term) or not w32effects:
270 realmode = 'ansi'
270 realmode = 'ansi'
271 else:
271 else:
272 realmode = 'win32'
272 realmode = 'win32'
273 else:
273 else:
274 realmode = 'ansi'
274 realmode = 'ansi'
275
275
276 def modewarn():
276 def modewarn():
277 # only warn if color.mode was explicitly set and we're in
277 # only warn if color.mode was explicitly set and we're in
278 # an interactive terminal
278 # an interactive terminal
279 if mode == realmode and ui.interactive():
279 if mode == realmode and ui.interactive():
280 ui.warn(_('warning: failed to set color mode to %s\n') % mode)
280 ui.warn(_('warning: failed to set color mode to %s\n') % mode)
281
281
282 if realmode == 'win32':
282 if realmode == 'win32':
283 _terminfo_params = {}
283 _terminfo_params = {}
284 if not w32effects:
284 if not w32effects:
285 modewarn()
285 modewarn()
286 return None
286 return None
287 _effects.update(w32effects)
287 _effects.update(w32effects)
288 elif realmode == 'ansi':
288 elif realmode == 'ansi':
289 _terminfo_params = {}
289 _terminfo_params = {}
290 elif realmode == 'terminfo':
290 elif realmode == 'terminfo':
291 _terminfosetup(ui, mode)
291 _terminfosetup(ui, mode)
292 if not _terminfo_params:
292 if not _terminfo_params:
293 ## FIXME Shouldn't we return None in this case too?
293 ## FIXME Shouldn't we return None in this case too?
294 modewarn()
294 modewarn()
295 realmode = 'ansi'
295 realmode = 'ansi'
296 else:
296 else:
297 return None
297 return None
298
298
299 if always or (auto and formatted):
299 if always or (auto and formatted):
300 return realmode
300 return realmode
301 return None
301 return None
302
302
303 try:
303 try:
304 import curses
304 import curses
305 # Mapping from effect name to terminfo attribute name (or raw code) or
305 # Mapping from effect name to terminfo attribute name (or raw code) or
306 # color number. This will also force-load the curses module.
306 # color number. This will also force-load the curses module.
307 _terminfo_params = {'none': (True, 'sgr0', ''),
307 _terminfo_params = {'none': (True, 'sgr0', ''),
308 'standout': (True, 'smso', ''),
308 'standout': (True, 'smso', ''),
309 'underline': (True, 'smul', ''),
309 'underline': (True, 'smul', ''),
310 'reverse': (True, 'rev', ''),
310 'reverse': (True, 'rev', ''),
311 'inverse': (True, 'rev', ''),
311 'inverse': (True, 'rev', ''),
312 'blink': (True, 'blink', ''),
312 'blink': (True, 'blink', ''),
313 'dim': (True, 'dim', ''),
313 'dim': (True, 'dim', ''),
314 'bold': (True, 'bold', ''),
314 'bold': (True, 'bold', ''),
315 'invisible': (True, 'invis', ''),
315 'invisible': (True, 'invis', ''),
316 'italic': (True, 'sitm', ''),
316 'italic': (True, 'sitm', ''),
317 'black': (False, curses.COLOR_BLACK, ''),
317 'black': (False, curses.COLOR_BLACK, ''),
318 'red': (False, curses.COLOR_RED, ''),
318 'red': (False, curses.COLOR_RED, ''),
319 'green': (False, curses.COLOR_GREEN, ''),
319 'green': (False, curses.COLOR_GREEN, ''),
320 'yellow': (False, curses.COLOR_YELLOW, ''),
320 'yellow': (False, curses.COLOR_YELLOW, ''),
321 'blue': (False, curses.COLOR_BLUE, ''),
321 'blue': (False, curses.COLOR_BLUE, ''),
322 'magenta': (False, curses.COLOR_MAGENTA, ''),
322 'magenta': (False, curses.COLOR_MAGENTA, ''),
323 'cyan': (False, curses.COLOR_CYAN, ''),
323 'cyan': (False, curses.COLOR_CYAN, ''),
324 'white': (False, curses.COLOR_WHITE, '')}
324 'white': (False, curses.COLOR_WHITE, '')}
325 except ImportError:
325 except ImportError:
326 _terminfo_params = {}
326 _terminfo_params = {}
327
327
328 _styles = {'grep.match': 'red bold',
328 _styles = {'grep.match': 'red bold',
329 'grep.linenumber': 'green',
329 'grep.linenumber': 'green',
330 'grep.rev': 'green',
330 'grep.rev': 'green',
331 'grep.change': 'green',
331 'grep.change': 'green',
332 'grep.sep': 'cyan',
332 'grep.sep': 'cyan',
333 'grep.filename': 'magenta',
333 'grep.filename': 'magenta',
334 'grep.user': 'magenta',
334 'grep.user': 'magenta',
335 'grep.date': 'magenta',
335 'grep.date': 'magenta',
336 'bookmarks.active': 'green',
336 'bookmarks.active': 'green',
337 'branches.active': 'none',
337 'branches.active': 'none',
338 'branches.closed': 'black bold',
338 'branches.closed': 'black bold',
339 'branches.current': 'green',
339 'branches.current': 'green',
340 'branches.inactive': 'none',
340 'branches.inactive': 'none',
341 'diff.changed': 'white',
341 'diff.changed': 'white',
342 'diff.deleted': 'red',
342 'diff.deleted': 'red',
343 'diff.diffline': 'bold',
343 'diff.diffline': 'bold',
344 'diff.extended': 'cyan bold',
344 'diff.extended': 'cyan bold',
345 'diff.file_a': 'red bold',
345 'diff.file_a': 'red bold',
346 'diff.file_b': 'green bold',
346 'diff.file_b': 'green bold',
347 'diff.hunk': 'magenta',
347 'diff.hunk': 'magenta',
348 'diff.inserted': 'green',
348 'diff.inserted': 'green',
349 'diff.tab': '',
349 'diff.tab': '',
350 'diff.trailingwhitespace': 'bold red_background',
350 'diff.trailingwhitespace': 'bold red_background',
351 'changeset.public' : '',
351 'changeset.public' : '',
352 'changeset.draft' : '',
352 'changeset.draft' : '',
353 'changeset.secret' : '',
353 'changeset.secret' : '',
354 'diffstat.deleted': 'red',
354 'diffstat.deleted': 'red',
355 'diffstat.inserted': 'green',
355 'diffstat.inserted': 'green',
356 'histedit.remaining': 'red bold',
356 'histedit.remaining': 'red bold',
357 'ui.prompt': 'yellow',
357 'ui.prompt': 'yellow',
358 'log.changeset': 'yellow',
358 'log.changeset': 'yellow',
359 'patchbomb.finalsummary': '',
359 'patchbomb.finalsummary': '',
360 'patchbomb.from': 'magenta',
360 'patchbomb.from': 'magenta',
361 'patchbomb.to': 'cyan',
361 'patchbomb.to': 'cyan',
362 'patchbomb.subject': 'green',
362 'patchbomb.subject': 'green',
363 'patchbomb.diffstats': '',
363 'patchbomb.diffstats': '',
364 'rebase.rebased': 'blue',
364 'rebase.rebased': 'blue',
365 'rebase.remaining': 'red bold',
365 'rebase.remaining': 'red bold',
366 'resolve.resolved': 'green bold',
366 'resolve.resolved': 'green bold',
367 'resolve.unresolved': 'red bold',
367 'resolve.unresolved': 'red bold',
368 'shelve.age': 'cyan',
368 'shelve.age': 'cyan',
369 'shelve.newest': 'green bold',
369 'shelve.newest': 'green bold',
370 'shelve.name': 'blue bold',
370 'shelve.name': 'blue bold',
371 'status.added': 'green bold',
371 'status.added': 'green bold',
372 'status.clean': 'none',
372 'status.clean': 'none',
373 'status.copied': 'none',
373 'status.copied': 'none',
374 'status.deleted': 'cyan bold underline',
374 'status.deleted': 'cyan bold underline',
375 'status.ignored': 'black bold',
375 'status.ignored': 'black bold',
376 'status.modified': 'blue bold',
376 'status.modified': 'blue bold',
377 'status.removed': 'red bold',
377 'status.removed': 'red bold',
378 'status.unknown': 'magenta bold underline',
378 'status.unknown': 'magenta bold underline',
379 'tags.normal': 'green',
379 'tags.normal': 'green',
380 'tags.local': 'black bold'}
380 'tags.local': 'black bold'}
381
381
382
382
383 def _effect_str(effect):
383 def _effect_str(effect):
384 '''Helper function for render_effects().'''
384 '''Helper function for render_effects().'''
385
385
386 bg = False
386 bg = False
387 if effect.endswith('_background'):
387 if effect.endswith('_background'):
388 bg = True
388 bg = True
389 effect = effect[:-11]
389 effect = effect[:-11]
390 try:
390 try:
391 attr, val, termcode = _terminfo_params[effect]
391 attr, val, termcode = _terminfo_params[effect]
392 except KeyError:
392 except KeyError:
393 return ''
393 return ''
394 if attr:
394 if attr:
395 if termcode:
395 if termcode:
396 return termcode
396 return termcode
397 else:
397 else:
398 return curses.tigetstr(val)
398 return curses.tigetstr(val)
399 elif bg:
399 elif bg:
400 return curses.tparm(curses.tigetstr('setab'), val)
400 return curses.tparm(curses.tigetstr('setab'), val)
401 else:
401 else:
402 return curses.tparm(curses.tigetstr('setaf'), val)
402 return curses.tparm(curses.tigetstr('setaf'), val)
403
403
404 def render_effects(text, effects):
404 def render_effects(text, effects):
405 'Wrap text in commands to turn on each effect.'
405 'Wrap text in commands to turn on each effect.'
406 if not text:
406 if not text:
407 return text
407 return text
408 if not _terminfo_params:
408 if not _terminfo_params:
409 start = [str(_effects[e]) for e in ['none'] + effects.split()]
409 start = [str(_effects[e]) for e in ['none'] + effects.split()]
410 start = '\033[' + ';'.join(start) + 'm'
410 start = '\033[' + ';'.join(start) + 'm'
411 stop = '\033[' + str(_effects['none']) + 'm'
411 stop = '\033[' + str(_effects['none']) + 'm'
412 else:
412 else:
413 start = ''.join(_effect_str(effect)
413 start = ''.join(_effect_str(effect)
414 for effect in ['none'] + effects.split())
414 for effect in ['none'] + effects.split())
415 stop = _effect_str('none')
415 stop = _effect_str('none')
416 return ''.join([start, text, stop])
416 return ''.join([start, text, stop])
417
417
418 def extstyles():
418 def extstyles():
419 for name, ext in extensions.extensions():
419 for name, ext in extensions.extensions():
420 _styles.update(getattr(ext, 'colortable', {}))
420 _styles.update(getattr(ext, 'colortable', {}))
421
421
422 def valideffect(effect):
422 def valideffect(effect):
423 'Determine if the effect is valid or not.'
423 'Determine if the effect is valid or not.'
424 good = False
424 good = False
425 if not _terminfo_params and effect in _effects:
425 if not _terminfo_params and effect in _effects:
426 good = True
426 good = True
427 elif effect in _terminfo_params or effect[:-11] in _terminfo_params:
427 elif effect in _terminfo_params or effect[:-11] in _terminfo_params:
428 good = True
428 good = True
429 return good
429 return good
430
430
431 def configstyles(ui):
431 def configstyles(ui):
432 for status, cfgeffects in ui.configitems('color'):
432 for status, cfgeffects in ui.configitems('color'):
433 if '.' not in status or status.startswith(('color.', 'terminfo.')):
433 if '.' not in status or status.startswith(('color.', 'terminfo.')):
434 continue
434 continue
435 cfgeffects = ui.configlist('color', status)
435 cfgeffects = ui.configlist('color', status)
436 if cfgeffects:
436 if cfgeffects:
437 good = []
437 good = []
438 for e in cfgeffects:
438 for e in cfgeffects:
439 if valideffect(e):
439 if valideffect(e):
440 good.append(e)
440 good.append(e)
441 else:
441 else:
442 ui.warn(_("ignoring unknown color/effect %r "
442 ui.warn(_("ignoring unknown color/effect %r "
443 "(configured in color.%s)\n")
443 "(configured in color.%s)\n")
444 % (e, status))
444 % (e, status))
445 _styles[status] = ' '.join(good)
445 _styles[status] = ' '.join(good)
446
446
447 class colorui(uimod.ui):
447 class colorui(uimod.ui):
448 _colormode = 'ansi'
448 _colormode = 'ansi'
449 def write(self, *args, **opts):
449 def write(self, *args, **opts):
450 if self._colormode is None:
450 if self._colormode is None:
451 return super(colorui, self).write(*args, **opts)
451 return super(colorui, self).write(*args, **opts)
452
452
453 label = opts.get('label', '')
453 label = opts.get('label', '')
454 if self._buffers and not opts.get('prompt', False):
454 if self._buffers and not opts.get('prompt', False):
455 if self._bufferapplylabels:
455 if self._bufferapplylabels:
456 self._buffers[-1].extend(self.label(a, label) for a in args)
456 self._buffers[-1].extend(self.label(a, label) for a in args)
457 else:
457 else:
458 self._buffers[-1].extend(args)
458 self._buffers[-1].extend(args)
459 elif self._colormode == 'win32':
459 elif self._colormode == 'win32':
460 for a in args:
460 for a in args:
461 win32print(a, super(colorui, self).write, **opts)
461 win32print(a, super(colorui, self).write, **opts)
462 else:
462 else:
463 return super(colorui, self).write(
463 return super(colorui, self).write(
464 *[self.label(a, label) for a in args], **opts)
464 *[self.label(a, label) for a in args], **opts)
465
465
466 def write_err(self, *args, **opts):
466 def write_err(self, *args, **opts):
467 if self._colormode is None:
467 if self._colormode is None:
468 return super(colorui, self).write_err(*args, **opts)
468 return super(colorui, self).write_err(*args, **opts)
469
469
470 label = opts.get('label', '')
470 label = opts.get('label', '')
471 if self._bufferstates and self._bufferstates[-1][0]:
471 if self._bufferstates and self._bufferstates[-1][0]:
472 return self.write(*args, **opts)
472 return self.write(*args, **opts)
473 if self._colormode == 'win32':
473 if self._colormode == 'win32':
474 for a in args:
474 for a in args:
475 win32print(a, super(colorui, self).write_err, **opts)
475 win32print(a, super(colorui, self).write_err, **opts)
476 else:
476 else:
477 return super(colorui, self).write_err(
477 return super(colorui, self).write_err(
478 *[self.label(a, label) for a in args], **opts)
478 *[self.label(a, label) for a in args], **opts)
479
479
480 def showlabel(self, msg, label):
480 def showlabel(self, msg, label):
481 if label and msg:
481 if label and msg:
482 if msg[-1] == '\n':
482 if msg[-1] == '\n':
483 return "[%s|%s]\n" % (label, msg[:-1])
483 return "[%s|%s]\n" % (label, msg[:-1])
484 else:
484 else:
485 return "[%s|%s]" % (label, msg)
485 return "[%s|%s]" % (label, msg)
486 else:
486 else:
487 return msg
487 return msg
488
488
489 def label(self, msg, label):
489 def label(self, msg, label):
490 if self._colormode is None:
490 if self._colormode is None:
491 return super(colorui, self).label(msg, label)
491 return super(colorui, self).label(msg, label)
492
492
493 if self._colormode == 'debug':
493 if self._colormode == 'debug':
494 return self.showlabel(msg, label)
494 return self.showlabel(msg, label)
495
495
496 effects = []
496 effects = []
497 for l in label.split():
497 for l in label.split():
498 s = _styles.get(l, '')
498 s = _styles.get(l, '')
499 if s:
499 if s:
500 effects.append(s)
500 effects.append(s)
501 elif valideffect(l):
501 elif valideffect(l):
502 effects.append(l)
502 effects.append(l)
503 effects = ' '.join(effects)
503 effects = ' '.join(effects)
504 if effects:
504 if effects:
505 return '\n'.join([render_effects(s, effects)
505 return '\n'.join([render_effects(s, effects)
506 for s in msg.split('\n')])
506 for s in msg.split('\n')])
507 return msg
507 return msg
508
508
509 def uisetup(ui):
509 def uisetup(ui):
510 if ui.plain():
510 if ui.plain():
511 return
511 return
512 if not isinstance(ui, colorui):
512 if not isinstance(ui, colorui):
513 colorui.__bases__ = (ui.__class__,)
513 colorui.__bases__ = (ui.__class__,)
514 ui.__class__ = colorui
514 ui.__class__ = colorui
515 def colorcmd(orig, ui_, opts, cmd, cmdfunc):
515 def colorcmd(orig, ui_, opts, cmd, cmdfunc):
516 mode = _modesetup(ui_, opts['color'])
516 mode = _modesetup(ui_, opts['color'])
517 colorui._colormode = mode
517 colorui._colormode = mode
518 if mode and mode != 'debug':
518 if mode and mode != 'debug':
519 extstyles()
519 extstyles()
520 configstyles(ui_)
520 configstyles(ui_)
521 return orig(ui_, opts, cmd, cmdfunc)
521 return orig(ui_, opts, cmd, cmdfunc)
522 def colorgit(orig, gitsub, commands, env=None, stream=False, cwd=None):
522 def colorgit(orig, gitsub, commands, env=None, stream=False, cwd=None):
523 if gitsub.ui._colormode and len(commands) and commands[0] == "diff":
523 if gitsub.ui._colormode and len(commands) and commands[0] == "diff":
524 # insert the argument in the front,
524 # insert the argument in the front,
525 # the end of git diff arguments is used for paths
525 # the end of git diff arguments is used for paths
526 commands.insert(1, '--color')
526 commands.insert(1, '--color')
527 return orig(gitsub, commands, env, stream, cwd)
527 return orig(gitsub, commands, env, stream, cwd)
528 extensions.wrapfunction(dispatch, '_runcommand', colorcmd)
528 extensions.wrapfunction(dispatch, '_runcommand', colorcmd)
529 extensions.wrapfunction(subrepo.gitsubrepo, '_gitnodir', colorgit)
529 extensions.wrapfunction(subrepo.gitsubrepo, '_gitnodir', colorgit)
530
530
531 def extsetup(ui):
531 def extsetup(ui):
532 commands.globalopts.append(
532 commands.globalopts.append(
533 ('', 'color', 'auto',
533 ('', 'color', 'auto',
534 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
534 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
535 # and should not be translated
535 # and should not be translated
536 _("when to colorize (boolean, always, auto, never, or debug)"),
536 _("when to colorize (boolean, always, auto, never, or debug)"),
537 _('TYPE')))
537 _('TYPE')))
538
538
539 @command('debugcolor', [], 'hg debugcolor')
539 @command('debugcolor', [], 'hg debugcolor')
540 def debugcolor(ui, repo, **opts):
540 def debugcolor(ui, repo, **opts):
541 """show available colors and effects"""
541 global _styles
542 global _styles
542 _styles = {}
543 _styles = {}
543 for effect in _effects.keys():
544 for effect in _effects.keys():
544 _styles[effect] = effect
545 _styles[effect] = effect
545 if _terminfo_params:
546 if _terminfo_params:
546 for k, v in ui.configitems('color'):
547 for k, v in ui.configitems('color'):
547 if k.startswith('color.'):
548 if k.startswith('color.'):
548 _styles[k] = k[6:]
549 _styles[k] = k[6:]
549 elif k.startswith('terminfo.'):
550 elif k.startswith('terminfo.'):
550 _styles[k] = k[9:]
551 _styles[k] = k[9:]
551 ui.write(('color mode: %s\n') % ui._colormode)
552 ui.write(('color mode: %s\n') % ui._colormode)
552 ui.write(_('available colors:\n'))
553 ui.write(_('available colors:\n'))
553 for colorname, label in _styles.items():
554 for colorname, label in _styles.items():
554 ui.write(('%s\n') % colorname, label=label)
555 ui.write(('%s\n') % colorname, label=label)
555
556
556 if os.name != 'nt':
557 if os.name != 'nt':
557 w32effects = None
558 w32effects = None
558 else:
559 else:
559 import ctypes
560 import ctypes
560 import re
561 import re
561
562
562 _kernel32 = ctypes.windll.kernel32
563 _kernel32 = ctypes.windll.kernel32
563
564
564 _WORD = ctypes.c_ushort
565 _WORD = ctypes.c_ushort
565
566
566 _INVALID_HANDLE_VALUE = -1
567 _INVALID_HANDLE_VALUE = -1
567
568
568 class _COORD(ctypes.Structure):
569 class _COORD(ctypes.Structure):
569 _fields_ = [('X', ctypes.c_short),
570 _fields_ = [('X', ctypes.c_short),
570 ('Y', ctypes.c_short)]
571 ('Y', ctypes.c_short)]
571
572
572 class _SMALL_RECT(ctypes.Structure):
573 class _SMALL_RECT(ctypes.Structure):
573 _fields_ = [('Left', ctypes.c_short),
574 _fields_ = [('Left', ctypes.c_short),
574 ('Top', ctypes.c_short),
575 ('Top', ctypes.c_short),
575 ('Right', ctypes.c_short),
576 ('Right', ctypes.c_short),
576 ('Bottom', ctypes.c_short)]
577 ('Bottom', ctypes.c_short)]
577
578
578 class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
579 class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
579 _fields_ = [('dwSize', _COORD),
580 _fields_ = [('dwSize', _COORD),
580 ('dwCursorPosition', _COORD),
581 ('dwCursorPosition', _COORD),
581 ('wAttributes', _WORD),
582 ('wAttributes', _WORD),
582 ('srWindow', _SMALL_RECT),
583 ('srWindow', _SMALL_RECT),
583 ('dwMaximumWindowSize', _COORD)]
584 ('dwMaximumWindowSize', _COORD)]
584
585
585 _STD_OUTPUT_HANDLE = 0xfffffff5 # (DWORD)-11
586 _STD_OUTPUT_HANDLE = 0xfffffff5 # (DWORD)-11
586 _STD_ERROR_HANDLE = 0xfffffff4 # (DWORD)-12
587 _STD_ERROR_HANDLE = 0xfffffff4 # (DWORD)-12
587
588
588 _FOREGROUND_BLUE = 0x0001
589 _FOREGROUND_BLUE = 0x0001
589 _FOREGROUND_GREEN = 0x0002
590 _FOREGROUND_GREEN = 0x0002
590 _FOREGROUND_RED = 0x0004
591 _FOREGROUND_RED = 0x0004
591 _FOREGROUND_INTENSITY = 0x0008
592 _FOREGROUND_INTENSITY = 0x0008
592
593
593 _BACKGROUND_BLUE = 0x0010
594 _BACKGROUND_BLUE = 0x0010
594 _BACKGROUND_GREEN = 0x0020
595 _BACKGROUND_GREEN = 0x0020
595 _BACKGROUND_RED = 0x0040
596 _BACKGROUND_RED = 0x0040
596 _BACKGROUND_INTENSITY = 0x0080
597 _BACKGROUND_INTENSITY = 0x0080
597
598
598 _COMMON_LVB_REVERSE_VIDEO = 0x4000
599 _COMMON_LVB_REVERSE_VIDEO = 0x4000
599 _COMMON_LVB_UNDERSCORE = 0x8000
600 _COMMON_LVB_UNDERSCORE = 0x8000
600
601
601 # http://msdn.microsoft.com/en-us/library/ms682088%28VS.85%29.aspx
602 # http://msdn.microsoft.com/en-us/library/ms682088%28VS.85%29.aspx
602 w32effects = {
603 w32effects = {
603 'none': -1,
604 'none': -1,
604 'black': 0,
605 'black': 0,
605 'red': _FOREGROUND_RED,
606 'red': _FOREGROUND_RED,
606 'green': _FOREGROUND_GREEN,
607 'green': _FOREGROUND_GREEN,
607 'yellow': _FOREGROUND_RED | _FOREGROUND_GREEN,
608 'yellow': _FOREGROUND_RED | _FOREGROUND_GREEN,
608 'blue': _FOREGROUND_BLUE,
609 'blue': _FOREGROUND_BLUE,
609 'magenta': _FOREGROUND_BLUE | _FOREGROUND_RED,
610 'magenta': _FOREGROUND_BLUE | _FOREGROUND_RED,
610 'cyan': _FOREGROUND_BLUE | _FOREGROUND_GREEN,
611 'cyan': _FOREGROUND_BLUE | _FOREGROUND_GREEN,
611 'white': _FOREGROUND_RED | _FOREGROUND_GREEN | _FOREGROUND_BLUE,
612 'white': _FOREGROUND_RED | _FOREGROUND_GREEN | _FOREGROUND_BLUE,
612 'bold': _FOREGROUND_INTENSITY,
613 'bold': _FOREGROUND_INTENSITY,
613 'black_background': 0x100, # unused value > 0x0f
614 'black_background': 0x100, # unused value > 0x0f
614 'red_background': _BACKGROUND_RED,
615 'red_background': _BACKGROUND_RED,
615 'green_background': _BACKGROUND_GREEN,
616 'green_background': _BACKGROUND_GREEN,
616 'yellow_background': _BACKGROUND_RED | _BACKGROUND_GREEN,
617 'yellow_background': _BACKGROUND_RED | _BACKGROUND_GREEN,
617 'blue_background': _BACKGROUND_BLUE,
618 'blue_background': _BACKGROUND_BLUE,
618 'purple_background': _BACKGROUND_BLUE | _BACKGROUND_RED,
619 'purple_background': _BACKGROUND_BLUE | _BACKGROUND_RED,
619 'cyan_background': _BACKGROUND_BLUE | _BACKGROUND_GREEN,
620 'cyan_background': _BACKGROUND_BLUE | _BACKGROUND_GREEN,
620 'white_background': (_BACKGROUND_RED | _BACKGROUND_GREEN |
621 'white_background': (_BACKGROUND_RED | _BACKGROUND_GREEN |
621 _BACKGROUND_BLUE),
622 _BACKGROUND_BLUE),
622 'bold_background': _BACKGROUND_INTENSITY,
623 'bold_background': _BACKGROUND_INTENSITY,
623 'underline': _COMMON_LVB_UNDERSCORE, # double-byte charsets only
624 'underline': _COMMON_LVB_UNDERSCORE, # double-byte charsets only
624 'inverse': _COMMON_LVB_REVERSE_VIDEO, # double-byte charsets only
625 'inverse': _COMMON_LVB_REVERSE_VIDEO, # double-byte charsets only
625 }
626 }
626
627
627 passthrough = set([_FOREGROUND_INTENSITY,
628 passthrough = set([_FOREGROUND_INTENSITY,
628 _BACKGROUND_INTENSITY,
629 _BACKGROUND_INTENSITY,
629 _COMMON_LVB_UNDERSCORE,
630 _COMMON_LVB_UNDERSCORE,
630 _COMMON_LVB_REVERSE_VIDEO])
631 _COMMON_LVB_REVERSE_VIDEO])
631
632
632 stdout = _kernel32.GetStdHandle(
633 stdout = _kernel32.GetStdHandle(
633 _STD_OUTPUT_HANDLE) # don't close the handle returned
634 _STD_OUTPUT_HANDLE) # don't close the handle returned
634 if stdout is None or stdout == _INVALID_HANDLE_VALUE:
635 if stdout is None or stdout == _INVALID_HANDLE_VALUE:
635 w32effects = None
636 w32effects = None
636 else:
637 else:
637 csbi = _CONSOLE_SCREEN_BUFFER_INFO()
638 csbi = _CONSOLE_SCREEN_BUFFER_INFO()
638 if not _kernel32.GetConsoleScreenBufferInfo(
639 if not _kernel32.GetConsoleScreenBufferInfo(
639 stdout, ctypes.byref(csbi)):
640 stdout, ctypes.byref(csbi)):
640 # stdout may not support GetConsoleScreenBufferInfo()
641 # stdout may not support GetConsoleScreenBufferInfo()
641 # when called from subprocess or redirected
642 # when called from subprocess or redirected
642 w32effects = None
643 w32effects = None
643 else:
644 else:
644 origattr = csbi.wAttributes
645 origattr = csbi.wAttributes
645 ansire = re.compile('\033\[([^m]*)m([^\033]*)(.*)',
646 ansire = re.compile('\033\[([^m]*)m([^\033]*)(.*)',
646 re.MULTILINE | re.DOTALL)
647 re.MULTILINE | re.DOTALL)
647
648
648 def win32print(text, orig, **opts):
649 def win32print(text, orig, **opts):
649 label = opts.get('label', '')
650 label = opts.get('label', '')
650 attr = origattr
651 attr = origattr
651
652
652 def mapcolor(val, attr):
653 def mapcolor(val, attr):
653 if val == -1:
654 if val == -1:
654 return origattr
655 return origattr
655 elif val in passthrough:
656 elif val in passthrough:
656 return attr | val
657 return attr | val
657 elif val > 0x0f:
658 elif val > 0x0f:
658 return (val & 0x70) | (attr & 0x8f)
659 return (val & 0x70) | (attr & 0x8f)
659 else:
660 else:
660 return (val & 0x07) | (attr & 0xf8)
661 return (val & 0x07) | (attr & 0xf8)
661
662
662 # determine console attributes based on labels
663 # determine console attributes based on labels
663 for l in label.split():
664 for l in label.split():
664 style = _styles.get(l, '')
665 style = _styles.get(l, '')
665 for effect in style.split():
666 for effect in style.split():
666 try:
667 try:
667 attr = mapcolor(w32effects[effect], attr)
668 attr = mapcolor(w32effects[effect], attr)
668 except KeyError:
669 except KeyError:
669 # w32effects could not have certain attributes so we skip
670 # w32effects could not have certain attributes so we skip
670 # them if not found
671 # them if not found
671 pass
672 pass
672 # hack to ensure regexp finds data
673 # hack to ensure regexp finds data
673 if not text.startswith('\033['):
674 if not text.startswith('\033['):
674 text = '\033[m' + text
675 text = '\033[m' + text
675
676
676 # Look for ANSI-like codes embedded in text
677 # Look for ANSI-like codes embedded in text
677 m = re.match(ansire, text)
678 m = re.match(ansire, text)
678
679
679 try:
680 try:
680 while m:
681 while m:
681 for sattr in m.group(1).split(';'):
682 for sattr in m.group(1).split(';'):
682 if sattr:
683 if sattr:
683 attr = mapcolor(int(sattr), attr)
684 attr = mapcolor(int(sattr), attr)
684 _kernel32.SetConsoleTextAttribute(stdout, attr)
685 _kernel32.SetConsoleTextAttribute(stdout, attr)
685 orig(m.group(2), **opts)
686 orig(m.group(2), **opts)
686 m = re.match(ansire, m.group(3))
687 m = re.match(ansire, m.group(3))
687 finally:
688 finally:
688 # Explicitly reset original attributes
689 # Explicitly reset original attributes
689 _kernel32.SetConsoleTextAttribute(stdout, origattr)
690 _kernel32.SetConsoleTextAttribute(stdout, origattr)
General Comments 0
You need to be logged in to leave comments. Login now