-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsspecific.py
104 lines (88 loc) · 3.75 KB
/
csspecific.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
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
import sublime_plugin
import sublime
import re
# : element_name [ HASH | class | attrib | pseudo ]*
# | [ HASH | class | attrib | pseudo ]+
class CsspecificCommand(sublime_plugin.TextCommand):
def run(self, edit):
v = self.view
ident = "[a-zA-Z_](?:[a-zA-Z0-9_\\-]*)" # an identifier
reTag = re.compile(ident)
reId = re.compile("#" + ident)
reClass = re.compile("\\." + ident)
reType = re.compile("\\[\\s*\\S.*?\\]")
rePseudo = re.compile(":" + ident + "(?:\\(.*?\\))?")
rePseudoTag = re.compile(":(?:link|visited|active|hover|focus|first-letter|first-line|first-child|before|after|lang)")
reStar = re.compile("\\*")
for sel in v.sel():
if not sel.empty():
intersect = True
break
else:
intersect = False
output = []
for rules in v.find_by_selector('meta.selector.css'):
skip = False
if intersect:
skip = True
for sel in v.sel():
if rules.intersects(sel):
skip = False
break
if skip:
continue
for rule in re.split("\\s*,\\s*", v.substr(rules)):
score = 0
for selector in re.split("\\s*[+> ]+\\s*", rule):
while len(selector):
while True:
match = reTag.match(selector)
if match:
score += 1
break
match = reId.match(selector)
if match:
score += 100
break
match = reClass.match(selector)
if match:
score += 10
break
match = reType.match(selector)
if match:
score += 10
break
match = rePseudo.match(selector)
if match:
if (rePseudoTag.match(selector)):
score += 1
else:
score += 10
break
match = reStar.match(selector)
break
if match:
token = match.group(0)
selector = selector[len(token):]
else:
output.append("Couldn't match %s" % selector)
break
output.append("/* %03d */ %s" % (score, rule))
self.panel("\n".join(output))
def panel(self, output, **kwargs):
if not hasattr(self, 'output_view'):
self.output_view = self.get_window().get_output_panel("csspecific")
self.output_view.set_read_only(False)
self._output_to_view(self.output_view, output, clear=True, **kwargs)
self.output_view.set_read_only(True)
self.get_window().run_command("show_panel", {"panel": "output.csspecific"})
def _output_to_view(self, output_file, output, clear=False):
output_file.set_syntax_file("Packages/CSS/CSS.tmLanguage")
edit = output_file.begin_edit()
if clear:
region = sublime.Region(0, self.output_view.size())
output_file.erase(edit, region)
output_file.insert(edit, 0, output)
output_file.end_edit(edit)
def get_window(self):
return self.view.window()