Debian Codegraph @

doc/tools/rocqrst/repl/ansicolors.py

raw symbols SCIP
1 ##########################################################################
2 ## # The Rocq Prover / The Rocq Development Team ##
3 ## v # Copyright INRIA, CNRS and contributors ##
4 ## <O___,, # (see version control and CREDITS file for authors & dates) ##
5 ## \VV/ ###############################################################
6 ## // # This file is distributed under the terms of the ##
7 ## # GNU Lesser General Public License Version 2.1 ##
8 ## # (see LICENSE file for the text of the license) ##
9 ##########################################################################
10 """
11 Parse Rocq's ANSI output.
12 ========================
13
14 Translated to Python from Rocq's terminal.ml.
15 """
16
17 # pylint: disable=too-many-return-statements, too-many-branches
18
19 def parse_color(style, offset):
20 color = style[offset] % 10
21 if color == 0:
22 return ("black", 1)
23 elif color == 1:
24 return ("red", 1)
25 elif color == 2:
26 return ("green", 1)
27 elif color == 3:
28 return ("yellow", 1)
29 elif color == 4:
30 return ("blue", 1)
31 elif color == 5:
32 return ("magenta", 1)
33 elif color == 6:
34 return ("cyan", 1)
35 elif color == 7:
36 return ("white", 1)
37 elif color == 9:
38 return ("default", 1)
39 elif color == 8:
40 nxt = style[offset + 1]
41 if nxt == 5:
42 return ("index-{}".format(style[offset + 1]), 2)
43 elif nxt == 2:
44 return ("rgb-{}-{}-{}".format(*style[offset+1:offset+4]), 4)
45 else:
46 raise ValueError("{}, {}".format(style, offset))
47 else:
48 raise ValueError()
49
50 def parse_style(style, offset, acc):
51 offset = 0
52 while offset < len(style):
53 head = style[offset]
54
55 if head == 0:
56 acc.append("reset")
57 elif head == 1:
58 acc.append("bold")
59 elif head == 3:
60 acc.append("italic")
61 elif head == 4:
62 acc.append("underline")
63 elif head == 7:
64 acc.append("negative")
65 elif head == 22:
66 acc.append("no-bold")
67 elif head == 23:
68 acc.append("no-italic")
69 elif head == 24:
70 acc.append("no-underline")
71 elif head == 27:
72 acc.append("no-negative")
73 else:
74 color, suboffset = parse_color(style, offset)
75 offset += suboffset - 1
76 if 30 <= head < 40:
77 acc.append("fg-{}".format(color))
78 elif 40 <= head < 50:
79 acc.append("bg-{}".format(color))
80 elif 90 <= head < 100:
81 acc.append("fg-light-{}".format(color))
82 elif 100 <= head < 110:
83 acc.append("bg-light-{}".format(color))
84
85 offset += 1
86
87 def parse_ansi(code):
88 """Parse an ansi code into a collection of CSS classes.
89
90 :param code: A sequence of ‘;’-separated ANSI codes. Do not include the
91 leading ‘^[[’ or the final ‘m’
92 """
93 classes = []
94 if code == "37":
95 pass # ignore white fg
96 else:
97 parse_style([int(c) for c in code.split(';')], 0, classes)
98 return ["ansi-" + cls for cls in classes]
99
100 if __name__ == '__main__':
101 # As produced by Rocq with ‘Check nat.’
102 print(parse_ansi("92;49;22;23;24;27"))