[PATCH] color: add support for terminfo-based attributes and color
Danek Duvall
duvall at comfychair.org
Fri Aug 28 21:37:10 UTC 2009
# HG changeset patch
# User Danek Duvall <duvall at comfychair.org>
# Date 1251013866 25200
# Node ID 9ec9b668799019e85504d91ef357f82f9f969188
# Parent 37042e8b3b342b2e380d8be3e3f7692584c92d33
color: add support for terminfo-based attributes and color
Using terminfo instead of hard-coding ECMA-48 control sequences provides a
greater assurance that the terminal codes are correct for the current
terminal type; not everything supports the ANSI escape codes.
It also allows us to use a wider range of colors when a terminal emulator
supports it (such as 16- or 256-color xterm), and a few more non-color
attributes, such as the ever-popular blink.
diff --git a/hgext/color.py b/hgext/color.py
--- a/hgext/color.py
+++ b/hgext/color.py
@@ -18,16 +18,19 @@
'''colorize output from some commands
-This extension modifies the status command to add color to its output
-to reflect file status, the qseries command to add color to reflect
-patch status (applied, unapplied, missing), and to diff-related
-commands to highlight additions, removals, diff headers, and trailing
-whitespace.
+This extension modifies the status command to add color to its output to
+reflect file status, the qseries command to add color to reflect patch status
+(applied, unapplied, missing), and to diff-related commands to highlight
+additions, removals, diff headers, and trailing whitespace.
-Other effects in addition to color, like bold and underlined text, are
-also available. Effects are rendered with the ECMA-48 SGR control
-function (aka ANSI escape codes). This module also provides the
-render_text function, which can be used to add effects to any text.
+Other effects in addition to color, like bold and underlined text, are also
+available. By default, the terminfo database is used to find the terminal
+codes used to change color and effect. If 'terminfo' is set to False in the
+[config] section of the .hgrc, then the ECMA-48 SGR control functions (aka ANSI
+escape codes) are used.
+
+This module also provides the render_text function, which can be used to add
+effects to any text.
Default effects may be overridden from the .hgrc file::
@@ -56,6 +59,26 @@ Default effects may be overridden from t
diff.inserted = green
diff.changed = white
diff.trailingwhitespace = bold red_background
+
+The available effects in terminfo mode are 'blink', 'bold', 'dim', 'inverse',
+'invisible', 'italic', 'standout', and 'underline'; in ECMA-48 mode, the
+options are 'bold', 'inverse', 'italic', and 'underline'. How each is rendered
+depends on the terminal emulator. Some may not be available for a given
+terminal type, and will be silently ignored.
+
+Because there are only eight standard colors, this module allows you to define
+color names for other color slots which might be available for your terminal
+type, assuming terminfo mode. For instance:
+
+ color.brightblue = 12
+ color.pink = 207
+ color.orange = 202
+
+to set 'brightblue' to color slot 12 (useful for 16 color terminals that have
+brighter colors defined in the upper eight) and, 'pink' and 'orange' to colors
+in 256-color xterm's default color cube. These defined colors may then be used
+as any of the pre-defined eight, including appending '_background' to set the
+background to that color.
'''
import os, sys
@@ -63,6 +86,7 @@ import itertools
from mercurial import cmdutil, commands, extensions, error
from mercurial.i18n import _
+import curses
# start and stop parameters for effects
_effect_params = {'none': 0,
@@ -87,11 +111,61 @@ _effect_params = {'none': 0,
'cyan_background': 46,
'white_background': 47}
+try:
+ # Mapping from effect name to terminfo attribute name or color number.
+ # This will also force-load the curses module.
+ _terminfo_params = {'none': (True, 'sgr0'),
+ 'standout': (True, 'smso'),
+ 'underline': (True, 'smul'),
+ 'reverse': (True, 'rev'),
+ 'inverse': (True, 'rev'),
+ 'blink': (True, 'blink'),
+ 'dim': (True, 'dim'),
+ 'bold': (True, 'bold'),
+ 'invisible': (True, 'invis'),
+ 'italic': (True, 'sitm'),
+ 'black': (False, curses.COLOR_BLACK),
+ 'red': (False, curses.COLOR_RED),
+ 'green': (False, curses.COLOR_GREEN),
+ 'yellow': (False, curses.COLOR_YELLOW),
+ 'blue': (False, curses.COLOR_BLUE),
+ 'magenta': (False, curses.COLOR_MAGENTA),
+ 'cyan': (False, curses.COLOR_CYAN),
+ 'white': (False, curses.COLOR_WHITE)}
+
+ # If True, use terminfo-based color; if False use ECMA-48 codes directly.
+ # Disable if we were unable to load the curses module.
+ _terminfo = True
+except ImportError:
+ _terminfo = False
+
+def _effect_str(effect):
+ '''Helper function for render_effects().'''
+
+ bg = False
+ if effect.endswith('_background'):
+ bg = True
+ effect = effect[:-11]
+ attr, val = _terminfo_params[effect]
+ if attr:
+ return curses.tigetstr(val)
+ elif bg:
+ return curses.tparm(curses.tigetstr('setab'), val)
+ else:
+ return curses.tparm(curses.tigetstr('setaf'), val)
+
def render_effects(text, effects):
'Wrap text in commands to turn on each effect.'
- start = [str(_effect_params[e]) for e in ['none'] + effects]
- start = '\033[' + ';'.join(start) + 'm'
- stop = '\033[' + str(_effect_params['none']) + 'm'
+ if not _terminfo:
+ start = [str(_effect_params[e]) for e in ['none'] + effects]
+ start = '\033[' + ';'.join(start) + 'm'
+ stop = '\033[' + str(_effect_params['none']) + 'm'
+ else:
+ start = ''.join([
+ _effect_str(effect)
+ for effect in ['none'] + effects
+ ])
+ stop = _effect_str('none')
return ''.join([start, text, stop])
def colorstatus(orig, ui, repo, *pats, **opts):
@@ -225,6 +299,9 @@ def uisetup(ui):
'''Initialize the extension.'''
global _ui
_ui = ui
+
+ _terminfosetup(ui)
+
_setupcmd(ui, 'diff', commands.table, colordiff, _diff_effects)
_setupcmd(ui, 'incoming', commands.table, None, _diff_effects)
_setupcmd(ui, 'log', commands.table, None, _diff_effects)
@@ -232,6 +309,39 @@ def uisetup(ui):
_setupcmd(ui, 'tip', commands.table, None, _diff_effects)
_setupcmd(ui, 'status', commands.table, colorstatus, _status_effects)
+def _terminfosetup(ui):
+ '''Initialize terminfo data and the terminal if we're in terminfo mode.'''
+
+ global _terminfo
+ # If we failed to load curses, we go ahead and return.
+ if _terminfo is False:
+ return
+ # Otherwise, see what the config file says.
+ _terminfo = ui.configbool('color', 'terminfo', default=None)
+ if _terminfo is False:
+ return
+
+ _terminfo_params.update(dict((
+ (key[6:], (False, int(val)))
+ for key, val in ui.configitems('color')
+ if key.startswith('color.')
+ )))
+
+ _terminfo = True
+ curses.setupterm()
+ for key, (b, e) in _terminfo_params.items():
+ if not b:
+ continue
+ if not curses.tigetstr(e):
+ # Most terminals don't support dim, invis, etc, so don't be
+ # noisy and use ui.debug().
+ ui.debug(_("No terminfo entry for %s\n") % e)
+ del _terminfo_params[key]
+ if not curses.tigetstr('setaf') or not curses.tigetstr('setab'):
+ ui.warn(_("No terminfo entry for setab/setaf: reverting to "
+ "ECMA-48 color\n"))
+ _terminfo = False
+
def extsetup():
try:
mq = extensions.find('mq')
@@ -277,7 +387,10 @@ def _setupcmd(ui, cmd, table, func, effe
if effects:
good = []
for e in effects:
- if e in _effect_params:
+ if not _terminfo and e in _effect_params:
+ good.append(e)
+ elif _terminfo and (e in _terminfo_params or
+ e[:-11] in _terminfo_params):
good.append(e)
else:
ui.warn(_("ignoring unknown color/effect %r "
More information about the Mercurial-devel
mailing list