-
Notifications
You must be signed in to change notification settings - Fork 594
/
vt_fmt.py
executable file
·73 lines (55 loc) · 1.54 KB
/
vt_fmt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/python3
import argparse
import re
COLORS = [
'BLACK',
'RED',
'GREEN',
'YELLOW',
'BLUE',
'PURPLE',
'CYAN',
'WHITE',
]
def re_match(exp, text):
return re.compile(exp).match(text) is not None
def vt_fmt(text):
curLiteral = False
chars = ""
i = 0
while i < len(text):
if text[i:i+5].lower() == '\\x1b[':
if curLiteral:
chars += '\"'
if i > 0:
chars += ' '
i += 5
code = text[i:text.find('m', i)]
i += len(code)
if re_match('^4[0-7];3[0-7]$', code):
chars += 'VT_COL(' + COLORS[int(code[1])] + ', ' + COLORS[int(code[4])] + ')'
elif re_match('^4[0-7]$', code):
chars += 'VT_BGCOL(' + COLORS[int(code[1])] + ')'
elif re_match('^3[0-7]$', code):
chars += 'VT_FGCOL(' + COLORS[int(code[1])] + ')'
elif len(code) == 0:
chars += 'VT_RST'
else:
raise Exception('Invalid String')
curLiteral = False
else:
if not curLiteral:
chars += ' \"'
chars += text[i]
curLiteral = True
i += 1
if curLiteral:
chars += '\"'
return chars
def main():
parser = argparse.ArgumentParser(description='Properly formats VT macros')
parser.add_argument('string', help='String to format')
args = parser.parse_args()
print(vt_fmt(args.string))
if __name__ == "__main__":
main()