-
-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathhighlighter.py
More file actions
101 lines (85 loc) · 3.04 KB
/
highlighter.py
File metadata and controls
101 lines (85 loc) · 3.04 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
import re
import sublime
import sublime_plugin
from ..lib import package_settings
from ..lib import syntax_paths
from ..lib.view_utils import region_flags_from_strings
__all__ = (
'SyntaxDefRegexCaptureGroupHighlighter',
)
class SyntaxDefRegexCaptureGroupHighlighter(sublime_plugin.ViewEventListener):
@classmethod
def applies_to_primary_view_only(cls):
return False
@classmethod
def is_applicable(cls, settings):
return settings.get('syntax') == syntax_paths.SYNTAX_DEF
def on_selection_modified(self):
prefs = package_settings()
self.view.add_regions(
key='captures',
regions=list(self.get_regex_regions()),
scope=prefs['syntax.captures_highlight_scope'],
flags=region_flags_from_strings(prefs['syntax.captures_highlight_styles']),
)
def get_regex_regions(self):
locations = [
region.begin()
for selection in self.view.sel()
if self.view.match_selector(
selection.begin(),
'source.yaml.sublime.syntax meta.expect-captures'
)
for region in self.view.split_by_newlines(selection)
]
for loc in locations:
# Find the line number.
match = re.search(r'(\d+):', self.view.substr(self.view.line(loc)))
if not match:
continue
n = int(match.group(1))
# Find the associated regexp. Assume it's the preceding one.
try:
regexp_region = [
region
for region in self.view.find_by_selector('source.regexp.oniguruma')
if region.end() < loc
][-1]
except IndexError:
continue
if n == 0:
yield regexp_region
continue
# Find parens that define capture groups.
regexp_offset = regexp_region.begin()
parens = iter(
(match.group(), match.start() + regexp_offset)
for match in re.finditer(r'\(\??|\)', self.view.substr(regexp_region))
if self.view.match_selector(
match.start() + regexp_offset,
'keyword.control.group'
)
)
# Find the start of the nth capture group.
start = None
count = 0
for p, i in parens:
if p == '(': # Not (?
count += 1
if count == n:
start = i
break
# Find the end of that capture group
end = None
depth = 0
for p, i in parens:
if p in {'(', '(?'}:
depth += 1
else:
if depth == 0:
end = i + 1
break
else:
depth -= 1
if end is not None:
yield sublime.Region(start, end)