view rcg.py @ 11:6627edb46f36

add "color line" option to reference python implementation
author paulo@thepaulopc
date Sat, 06 Nov 2010 00:17:34 -0700
parents df03fa355b60
children e618a3ff2027
line source
1 #!/usr/bin/env python
3 import sys
4 import re
5 import getopt
7 #x = "\x1B[1;31;49m" + x
8 #x = START + c["white"][0] + ";" + c["blue"][1] + END + x + CLEAR
10 START = "\x1B["
11 BOLD = "1;"
12 END = "m"
13 CLEAR = START + "0" + END
15 c = {
16 # color : (fg, bg)
17 "black" : ("30", "40"),
18 "red" : ("31", "41"),
19 "green" : ("32", "42"),
20 "brown" : ("33", "43"),
21 "blue" : ("34", "44"),
22 "magenta" : ("35", "45"),
23 "cyan" : ("36", "46"),
24 "white" : ("37", "47"),
25 "default" : ("39", "49"),
26 }
28 bold = False
29 fg = None
30 bg = None
31 colorLine = False
33 (optvals, args) = getopt.getopt(sys.argv[1:], "f:b:Bl")
35 for (opt, val) in optvals:
36 if opt == '-B':
37 bold = True
38 elif opt == '-f':
39 fg = val
40 elif opt == '-b':
41 bg = val
42 elif opt == '-l':
43 colorLine = True
45 if len(args) > 0:
46 for line in sys.stdin:
47 repl = START
48 if bold:
49 repl += BOLD
50 if fg is not None:
51 repl += c[fg][0]
52 if bg is not None:
53 repl += ';' + c[bg][1]
54 repl += END + r'\1' + CLEAR
56 x = line
58 if colorLine == False:
59 x = re.sub(r'(' + args[0] + r')', repl, line)
60 else:
61 if re.search(args[0], line) != None:
62 last_char = line[-1]
63 x = repl.replace(r'\1', line[:-1])
64 x += last_char
66 sys.stdout.write(x)
67 sys.stdout.flush()