Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork252
Expand file tree
/
Copy pathparse.py
More file actions
109 lines (92 loc) · 2.86 KB
/
parse.py
File metadata and controls
109 lines (92 loc) · 2.86 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
importre
fromfunctoolsimportpartial
fromtypingimportAny
fromcollections.abcimportCallable
fromcurtsies.formatstringimportfmtstr,FmtStr
fromcurtsies.termformatconstantsimport (
FG_COLORS,
BG_COLORS,
colorsasCURTSIES_COLORS,
)
from ..configimportCOLOR_LETTERS
from ..lazyreimportLazyReCompile
COLORS=CURTSIES_COLORS+ ("default",)
CNAMES=dict(zip(COLOR_LETTERS,COLORS))
# hack for finding the "inverse"
INVERSE_COLORS= {
CURTSIES_COLORS[idx]:CURTSIES_COLORS[
(idx+ (len(CURTSIES_COLORS)//2))%len(CURTSIES_COLORS)
]
foridxinrange(len(CURTSIES_COLORS))
}
INVERSE_COLORS["default"]=INVERSE_COLORS[CURTSIES_COLORS[0]]
deffunc_for_letter(
letter_color_code:str,default:str="k"
)->Callable[...,FmtStr]:
"""Returns FmtStr constructor for a bpython-style color code"""
ifletter_color_code=="d":
letter_color_code=default
elifletter_color_code=="D":
letter_color_code=default.upper()
returnpartial(
fmtstr,
fg=CNAMES[letter_color_code.lower()],
bold=letter_color_code.isupper(),
)
defcolor_for_letter(letter_color_code:str,default:str="k")->str:
ifletter_color_code=="d":
letter_color_code=default
returnCNAMES[letter_color_code.lower()]
defparse(s:str)->FmtStr:
"""Returns a FmtStr object from a bpython-formatted colored string"""
rest=s
stuff= []
whilerest:
start,rest=peel_off_string(rest)
stuff.append(start)
return (
sum((fs_from_match(d)fordinstuff[1:]),fs_from_match(stuff[0]))
iflen(stuff)>0
elseFmtStr()
)
deffs_from_match(d:dict[str,Any])->FmtStr:
atts= {}
color="default"
ifd["fg"]:
# this isn't according to spec as I understand it
ifd["fg"].isupper():
d["bold"]=True
# TODO figure out why boldness isn't based on presence of \x02
color=CNAMES[d["fg"].lower()]
ifcolor!="default":
atts["fg"]=FG_COLORS[color]
ifd["bg"]:
ifd["bg"]=="I":
# hack for finding the "inverse"
color=INVERSE_COLORS[color]
else:
color=CNAMES[d["bg"].lower()]
ifcolor!="default":
atts["bg"]=BG_COLORS[color]
ifd["bold"]:
atts["bold"]=True
returnfmtstr(d["string"],**atts)
peel_off_string_re=LazyReCompile(
r"""(?P<colormarker>\x01
(?P<fg>[krgybmcwdKRGYBMCWD]?)
(?P<bg>[krgybmcwdKRGYBMCWDI]?)?)
(?P<bold>\x02?)
\x03
(?P<string>[^\x04]*)
\x04
(?P<rest>.*)
""",
re.VERBOSE|re.DOTALL,
)
defpeel_off_string(s:str)->tuple[dict[str,Any],str]:
m=peel_off_string_re.match(s)
assertm,repr(s)
d=m.groupdict()
rest=d["rest"]
deld["rest"]
returnd,rest