color: insert color code after every "\e[0m" (issue5413)
authorYuya Nishihara <yuya@tcha.org>
Sat, 18 Mar 2017 20:11:15 +0900
changeset 31518 43d6ef658874
parent 31517 468bc8a1863d
child 31519 3725986b151a
color: insert color code after every "\e[0m" (issue5413) This assumes the last color wins, tested in ANSI mode. I guess terminfo mode would work in the same way.
mercurial/color.py
tests/test-command-template.t
tests/test-doctest.py
--- a/mercurial/color.py	Sat Mar 18 19:59:47 2017 +0900
+++ b/mercurial/color.py	Sat Mar 18 20:11:15 2017 +0900
@@ -296,6 +296,23 @@
     else:
         return curses.tparm(curses.tigetstr('setaf'), val)
 
+def _mergeeffects(text, start, stop):
+    """Insert start sequence at every occurrence of stop sequence
+
+    >>> s = _mergeeffects('cyan', '[C]', '|')
+    >>> s = _mergeeffects(s + 'yellow', '[Y]', '|')
+    >>> s = _mergeeffects('ma' + s + 'genta', '[M]', '|')
+    >>> s = _mergeeffects('red' + s, '[R]', '|')
+    >>> s
+    '[R]red[M]ma[Y][C]cyan|[R][M][Y]yellow|[R][M]genta|'
+    """
+    parts = []
+    for t in text.split(stop):
+        if not t:
+            continue
+        parts.extend([start, t, stop])
+    return ''.join(parts)
+
 def _render_effects(ui, text, effects):
     'Wrap text in commands to turn on each effect.'
     if not text:
@@ -308,7 +325,7 @@
         start = [str(_effects[e]) for e in ['none'] + effects.split()]
         start = '\033[' + ';'.join(start) + 'm'
         stop = '\033[' + str(_effects['none']) + 'm'
-    return ''.join([start, text, stop])
+    return _mergeeffects(text, start, stop)
 
 def colorlabel(ui, msg, label):
     """add color control code according to the mode"""
--- a/tests/test-command-template.t	Sat Mar 18 19:59:47 2017 +0900
+++ b/tests/test-command-template.t	Sat Mar 18 20:11:15 2017 +0900
@@ -3348,6 +3348,12 @@
   $ hg log --color=always -l 1 --template '{label(red, "text\n")}'
   \x1b[0;31mtext\x1b[0m (esc)
 
+color effects can be nested (issue5413)
+
+  $ hg debugtemplate --color=always \
+  > '{label(red, "red{label(magenta, "ma{label(cyan, "cyan")}{label(yellow, "yellow")}genta")}")}\n'
+  \x1b[0;31mred\x1b[0;35mma\x1b[0;36mcyan\x1b[0m\x1b[0;31m\x1b[0;35m\x1b[0;33myellow\x1b[0m\x1b[0;31m\x1b[0;35mgenta\x1b[0m (esc)
+
 label should be no-op if color is disabled:
 
   $ hg log --color=never -l 1 --template '{label(red, "text\n")}'
--- a/tests/test-doctest.py	Sat Mar 18 19:59:47 2017 +0900
+++ b/tests/test-doctest.py	Sat Mar 18 20:11:15 2017 +0900
@@ -23,6 +23,7 @@
 
 testmod('mercurial.changegroup')
 testmod('mercurial.changelog')
+testmod('mercurial.color')
 testmod('mercurial.config')
 testmod('mercurial.dagparser', optionflags=doctest.NORMALIZE_WHITESPACE)
 testmod('mercurial.dispatch')