forked from facelessuser/BracketHighlighter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bh_core.py
executable file
·1415 lines (1185 loc) · 48.3 KB
/
bh_core.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from os.path import basename, exists, join, normpath
import sublime
import sublime_plugin
from time import time, sleep
import thread
import ure
from bh_plugin import BracketPlugin, BracketRegion, ImportModule
from collections import namedtuple
import traceback
BH_MATCH_TYPE_NONE = 0
BH_MATCH_TYPE_SELECTION = 1
BH_MATCH_TYPE_EDIT = 2
DEFAULT_STYLES = {
"default": {
"icon": "dot",
"color": "brackethighlighter.default",
"style": "underline"
},
"unmatched": {
"icon": "question",
"color": "brackethighlighter.unmatched",
"style": "outline"
}
}
HV_RSVD_VALUES = ["__default__", "__bracket__"]
HIGH_VISIBILITY = False
GLOBAL_ENABLE = True
def bh_logging(msg):
print("BracketHighlighter: %s" % msg)
def bh_debug(msg):
if sublime.load_settings("bh_core.sublime-settings").get('debug_enable', False):
bh_logging(msg)
def underline(regions):
"""
Convert sublime regions into underline regions
"""
r = []
for region in regions:
start = region.begin()
end = region.end()
while start < end:
r.append(sublime.Region(start))
start += 1
return r
def load_modules(obj, loaded):
"""
Load bracket plugin modules
"""
plib = obj.get("plugin_library")
if plib is None:
return
try:
module = ImportModule.import_module(plib, loaded)
obj["compare"] = getattr(module, "compare", None)
obj["post_match"] = getattr(module, "post_match", None)
loaded.add(plib)
except:
bh_logging("Could not load module %s\n%s" % (plib, str(traceback.format_exc())))
raise
def select_bracket_style(option):
"""
Configure style of region based on option
"""
style = sublime.HIDE_ON_MINIMAP
if option == "outline":
style |= sublime.DRAW_OUTLINED
elif option == "none":
style |= sublime.HIDDEN
elif option == "underline":
style |= sublime.DRAW_EMPTY_AS_OVERWRITE
return style
def select_bracket_icons(option, icon_path):
"""
Configure custom gutter icons if they can be located.
"""
icon = ""
small_icon = ""
open_icon = ""
small_open_icon = ""
close_icon = ""
small_close_icon = ""
# Icon exist?
if not option == "none" and not option == "":
if exists(normpath(join(sublime.packages_path(), icon_path, option + ".png"))):
icon = "../%s/%s" % (icon_path, option)
if exists(normpath(join(sublime.packages_path(), icon_path, option + "_small.png"))):
small_icon = "../%s/%s" % (icon_path, option + "_small")
if exists(normpath(join(sublime.packages_path(), icon_path, option + "_open.png"))):
open_icon = "../%s/%s" % (icon_path, option + "_open")
else:
open_icon = icon
if exists(normpath(join(sublime.packages_path(), icon_path, option + "_open_small.png"))):
small_open_icon = "../%s/%s" % (icon_path, option + "_open_small")
else:
small_open_icon = small_icon
if exists(normpath(join(sublime.packages_path(), icon_path, option + "_close.png"))):
close_icon = "../%s/%s" % (icon_path, option + "_close")
else:
close_icon = icon
if exists(normpath(join(sublime.packages_path(), icon_path, option + "_close_small.png"))):
small_close_icon = "../%s/%s" % (icon_path, option + "_close_small")
else:
small_close_icon = small_icon
return icon, small_icon, open_icon, small_open_icon, close_icon, small_close_icon
def exclude_bracket(enabled, filter_type, language_list, language):
"""
Exclude or include brackets based on filter lists.
"""
exclude = True
if enabled:
# Black list languages
if filter_type == 'blacklist':
exclude = False
if language != None:
for item in language_list:
if language == item.lower():
exclude = True
break
#White list languages
elif filter_type == 'whitelist':
if language != None:
for item in language_list:
if language == item.lower():
exclude = False
break
return exclude
class BhEventMgr(object):
"""
Object to manage when bracket events should be launched.
"""
@classmethod
def load(cls):
"""
Initialize variables for determining
when to initiate a bracket matching event.
"""
cls.wait_time = 0.12
cls.time = time()
cls.modified = False
cls.type = BH_MATCH_TYPE_SELECTION
cls.ignore_all = False
BhEventMgr.load()
class BhThreadMgr(object):
"""
Object to help track when a new thread needs to be started.
"""
restart = False
class BhEntry(object):
"""
Generic object for bracket regions.
"""
def move(self, begin, end):
"""
Create a new object with the points moved to the specified locations.
"""
return self._replace(begin=begin, end=end)
def size(self):
"""
Size of bracket selection.
"""
return abs(self.begin - self.end)
def toregion(self):
"""
Convert to sublime Region.
"""
return sublime.Region(self.begin, self.end)
class BracketEntry(namedtuple('BracketEntry', ['begin', 'end', 'type'], verbose=False), BhEntry):
"""
Bracket object.
"""
pass
class ScopeEntry(namedtuple('ScopeEntry', ['begin', 'end', 'scope', 'type'], verbose=False), BhEntry):
"""
Scope bracket object.
"""
pass
class BracketSearchSide(object):
"""
Userful structure to specify bracket matching direction.
"""
left = 0
right = 1
class BracektSearchType(object):
"""
Userful structure to specify bracket matching direction.
"""
opening = 0
closing = 1
class BracketSearch(object):
"""
Object that performs regex search on the view's buffer and finds brackets.
"""
def __init__(self, bfr, window, center, pattern, scope_check, scope):
"""
Prepare the search object
"""
self.center = center
self.pattern = pattern
self.bfr = bfr
self.scope = scope
self.scope_check = scope_check
self.prev_match = [None, None]
self.return_prev = [False, False]
self.done = [False, False]
self.start = [None, None]
self.left = [[], []]
self.right = [[], []]
self.findall(window)
def reset_end_state(self):
"""
Reset the the current search flags etc.
This is usually done before searching the other direction.
"""
self.start = [None, None]
self.done = [False, False]
self.prev_match = [None, None]
self.return_prev = [False, False]
def remember(self, match_type):
"""
Remember the current match.
Don't get the next bracket on the next
request, but return the current one again.
"""
self.return_prev[match_type] = True
self.done[match_type] = False
def findall(self, window):
"""
Find all of the brackets and sort them
to "left of the cursor" and "right of the cursor"
"""
for m in self.pattern.finditer(self.bfr, window[0], window[1]):
g = m.lastindex
try:
start = m.start(g)
end = m.end(g)
except:
continue
match_type = int(not bool(g % 2))
bracket_id = (g / 2) - match_type
if not self.scope_check(start, bracket_id, self.scope):
if (end <= self.center if match_type else start < self.center):
self.left[match_type].append(BracketEntry(start, end, bracket_id))
elif (end > self.center if match_type else start >= self.center):
self.right[match_type].append(BracketEntry(start, end, bracket_id))
def get_open(self, bracket_code):
"""
Get opening bracket. Accepts a bracket code that
determines which side of the cursor the next match is returned from.
"""
for b in self._get_bracket(bracket_code, BracektSearchType.opening):
yield b
def get_close(self, bracket_code):
"""
Get closing bracket. Accepts a bracket code that
determines which side of the cursor the next match is returned from.
"""
for b in self._get_bracket(bracket_code, BracektSearchType.closing):
yield b
def is_done(self, match_type):
"""
Retrieve done flag.
"""
return self.done[match_type]
def _get_bracket(self, bracket_code, match_type):
"""
Get the next bracket. Accepts bracket code that determines
which side of the cursor the next match is returned from and
the match type which determines whether a opening or closing
bracket is desired.
"""
if self.done[match_type]:
return
if self.return_prev[match_type]:
self.return_prev[match_type] = False
yield self.prev_match[match_type]
if bracket_code == BracketSearchSide.left:
if self.start[match_type] is None:
self.start[match_type] = len(self.left[match_type])
for x in reversed(range(0, self.start[match_type])):
b = self.left[match_type][x]
self.prev_match[match_type] = b
self.start[match_type] -= 1
yield b
else:
if self.start[match_type] is None:
self.start[match_type] = 0
for x in range(self.start[match_type], len(self.right[match_type])):
b = self.right[match_type][x]
self.prev_match[match_type] = b
self.start[match_type] += 1
yield b
self.done[match_type] = True
class BracketDefinition(object):
"""
Normal bracket definition.
"""
def __init__(self, bracket):
"""
Setup the bracket object by reading the passed in dictionary.
"""
self.name = bracket["name"]
self.style = bracket.get("style", "default")
self.compare = bracket.get("compare")
sub_search = bracket.get("find_in_sub_search", "false")
self.find_in_sub_search_only = sub_search == "only"
self.find_in_sub_search = sub_search == "true" or self.find_in_sub_search_only
self.post_match = bracket.get("post_match")
self.scope_exclude_exceptions = bracket.get("scope_exclude_exceptions", [])
self.scope_exclude = bracket.get("scope_exclude", [])
self.ignore_string_escape = bracket.get("ignore_string_escape", False)
class ScopeDefinition(object):
"""
Scope bracket definition.
"""
def __init__(self, bracket):
"""
Setup the bracket object by reading the passed in dictionary.
"""
self.style = bracket.get("style", "default")
self.open = ure.compile("\\A" + bracket.get("open", "."), ure.MULTILINE | ure.IGNORECASE)
self.close = ure.compile(bracket.get("close", ".") + "\\Z", ure.MULTILINE | ure.IGNORECASE)
self.name = bracket["name"]
sub_search = bracket.get("sub_bracket_search", "false")
self.sub_search_only = sub_search == "only"
self.sub_search = self.sub_search_only == True or sub_search == "true"
self.compare = bracket.get("compare")
self.post_match = bracket.get("post_match")
self.scopes = bracket["scopes"]
class StyleDefinition(object):
"""
Styling definition.
"""
def __init__(self, name, style, default_highlight, icon_path):
"""
Setup the style object by reading the
passed in dictionary. And other parameters.
"""
self.name = name
self.selections = []
self.open_selections = []
self.close_selections = []
self.center_selections = []
self.color = style.get("color", default_highlight["color"])
self.style = select_bracket_style(style.get("style", default_highlight["style"]))
self.underline = self.style & sublime.DRAW_EMPTY_AS_OVERWRITE
(
self.icon, self.small_icon, self.open_icon,
self.small_open_icon, self.close_icon, self.small_close_icon
) = select_bracket_icons(style.get("icon", default_highlight["icon"]), icon_path)
self.no_icon = ""
class BhToggleStringEscapeModeCommand(sublime_plugin.TextCommand):
"""
Toggle between regex escape and
string escape for brackets in strings.
"""
def run(self, edit):
default_mode = sublime.load_settings("bh_core.sublime-settings").get('bracket_string_escape_mode', 'string')
if self.view.settings().get('bracket_string_escape_mode', default_mode) == "regex":
self.view.settings().set('bracket_string_escape_mode', "string")
sublime.status_message("Bracket String Escape Mode: string")
else:
self.view.settings().set('bracket_string_escape_mode', "regex")
sublime.status_message("Bracket String Escape Mode: regex")
class BhShowStringEscapeModeCommand(sublime_plugin.TextCommand):
"""
Shoe current string escape mode for sub brackets in strings.
"""
def run(self, edit):
default_mode = sublime.load_settings("BracketHighlighter.sublime-settings").get('bracket_string_escape_mode', 'string')
sublime.status_message("Bracket String Escape Mode: %s" % self.view.settings().get('bracket_string_escape_mode', default_mode))
class BhToggleHighVisibilityCommand(sublime_plugin.ApplicationCommand):
"""
Toggle a high visibility mode that
highlights the entire bracket extent.
"""
def run(self):
global HIGH_VISIBILITY
HIGH_VISIBILITY = not HIGH_VISIBILITY
class BhToggleEnableCommand(sublime_plugin.ApplicationCommand):
"""
Toggle global enable for BracketHighlighter.
"""
def run(self):
global GLOBAL_ENABLE
GLOBAL_ENABLE = not GLOBAL_ENABLE
class BhKeyCommand(sublime_plugin.WindowCommand):
"""
Command to process shortcuts, menu calls, and command palette calls.
This is how BhCore is called with different options.
"""
def run(self, threshold=True, lines=False, adjacent=False, ignore={}, plugin={}):
# Override events
BhEventMgr.ignore_all = True
BhEventMgr.modified = False
self.bh = BhCore(
threshold,
lines,
adjacent,
ignore,
plugin,
True
)
self.view = self.window.active_view()
sublime.set_timeout(self.execute, 100)
def execute(self):
bh_debug("Key Event")
self.bh.match(self.view)
BhEventMgr.ignore_all = False
BhEventMgr.time = time()
class BhCore(object):
"""
Bracket matching class.
"""
plugin_reload = False
def __init__(self, override_thresh=False, count_lines=False, adj_only=None, ignore={}, plugin={}, keycommand=False):
"""
Load settings and setup reload events if settings changes.
"""
self.settings = sublime.load_settings("bh_core.sublime-settings")
self.keycommand = keycommand
if not keycommand:
self.settings.clear_on_change('reload')
self.settings.add_on_change('reload', self.setup)
self.setup(override_thresh, count_lines, adj_only, ignore, plugin)
def setup(self, override_thresh=False, count_lines=False, adj_only=None, ignore={}, plugin={}):
"""
Initialize class settings from settings file and inputs.
"""
# Init view params
self.last_id_view = None
self.last_id_sel = None
self.view_tracker = (None, None)
self.ignore_threshold = override_thresh or bool(self.settings.get("ignore_threshold", False))
self.adj_only = adj_only if adj_only is not None else bool(self.settings.get("match_only_adjacent", False))
self.auto_selection_threshold = int(self.settings.get("auto_selection_threshold", 10))
self.no_multi_select_icons = bool(self.settings.get("no_multi_select_icons", False))
self.count_lines = count_lines
self.default_string_escape_mode = str(self.settings.get('bracket_string_escape_mode', "string"))
self.show_unmatched = bool(self.settings.get("show_unmatched", True))
# Init bracket objects
self.bracket_types = self.settings.get("brackets", [])
self.scope_types = self.settings.get("scope_brackets", [])
# Init selection params
self.use_selection_threshold = True
self.selection_threshold = int(self.settings.get("search_threshold", 5000))
self.new_select = False
self.loaded_modules = set([])
# High Visibility options
self.hv_style = select_bracket_style(self.settings.get("high_visibility_style", "outline"))
self.hv_underline = self.hv_style & sublime.DRAW_EMPTY_AS_OVERWRITE
self.hv_color = self.settings.get("high_visibility_color", HV_RSVD_VALUES[1])
# Init plugin
self.plugin = None
self.transform = set([])
if 'command' in plugin:
self.plugin = BracketPlugin(plugin, self.loaded_modules)
self.new_select = True
if 'type' in plugin:
for t in plugin["type"]:
self.transform.add(t)
def init_bracket_regions(self):
"""
Load up styled regions for brackets to use.
"""
self.bracket_regions = {}
styles = self.settings.get("bracket_styles", DEFAULT_STYLES)
icon_path = self.settings.get("icon_path", "Theme - Default").replace('\\', '/').strip('/')
# Make sure default and unmatched styles in styles
for key, value in DEFAULT_STYLES.items():
if key not in styles:
styles[key] = value
continue
for k, v in value.items():
if k not in styles[key]:
styles[key][k] = v
# Initialize styles
default_settings = styles["default"]
for k, v in styles.items():
self.bracket_regions[k] = StyleDefinition(k, v, default_settings, icon_path)
def is_valid_definition(self, params, language):
"""
Ensure bracket definition should be and can be loaded.
"""
return (
not exclude_bracket(
params.get("enabled", True),
params.get("language_filter", "blacklist"),
params.get("language_list", []),
language
) and
params["open"] is not None and params["close"] is not None
)
def init_brackets(self, language):
"""
Initialize bracket match definition objects from settings file.
"""
self.find_regex = []
self.sub_find_regex = []
self.index_open = {}
self.index_close = {}
self.brackets = []
self.scopes = []
self.view_tracker = (language, self.view.id())
self.enabled = False
self.sels = []
self.multi_select = False
scopes = {}
loaded_modules = self.loaded_modules.copy()
for params in self.bracket_types:
if self.is_valid_definition(params, language):
try:
load_modules(params, loaded_modules)
entry = BracketDefinition(params)
self.brackets.append(entry)
if not entry.find_in_sub_search_only:
self.find_regex.append(params["open"])
self.find_regex.append(params["close"])
else:
self.find_regex.append(r"([^\s\S])")
self.find_regex.append(r"([^\s\S])")
if entry.find_in_sub_search:
self.sub_find_regex.append(params["open"])
self.sub_find_regex.append(params["close"])
else:
self.sub_find_regex.append(r"([^\s\S])")
self.sub_find_regex.append(r"([^\s\S])")
except Exception, e:
bh_logging(e)
scope_count = 0
for params in self.scope_types:
if self.is_valid_definition(params, language):
try:
load_modules(params, loaded_modules)
entry = ScopeDefinition(params)
for x in entry.scopes:
if x not in scopes:
scopes[x] = scope_count
scope_count += 1
self.scopes.append({"name": x, "brackets": [entry]})
else:
self.scopes[scopes[x]]["brackets"].append(entry)
except Exception, e:
bh_logging(e)
if len(self.brackets):
bh_debug(
"Search patterns:\n" +
"(?:%s)\n" % '|'.join(self.find_regex) +
"(?:%s)" % '|'.join(self.sub_find_regex)
)
self.sub_pattern = ure.compile("(?:%s)" % '|'.join(self.sub_find_regex), ure.MULTILINE | ure.IGNORECASE)
self.pattern = ure.compile("(?:%s)" % '|'.join(self.find_regex), ure.MULTILINE | ure.IGNORECASE)
self.enabled = True
def init_match(self):
"""
Initialize matching for the current view's syntax.
"""
self.chars = 0
self.lines = 0
syntax = self.view.settings().get('syntax')
language = basename(syntax).replace('.tmLanguage', '').lower() if syntax != None else "plain text"
if language != self.view_tracker[0] or self.view.id() != self.view_tracker[1]:
self.init_bracket_regions()
self.init_brackets(language)
else:
for r in self.bracket_regions.values():
r.selections = []
r.open_selections = []
r.close_selections = []
r.center_selections = []
def unique(self):
"""
Check if the current selection(s) is different from the last.
"""
id_view = self.view.id()
id_sel = "".join([str(sel.a) for sel in self.view.sel()])
is_unique = False
if id_view != self.last_id_view or id_sel != self.last_id_sel:
self.last_id_view = id_view
self.last_id_sel = id_sel
is_unique = True
return is_unique
def store_sel(self, regions):
"""
Store the current selection selection to be set at the end.
"""
if self.new_select:
for region in regions:
self.sels.append(region)
def change_sel(self):
"""
Change the view's selections.
"""
if self.new_select and len(self.sels) > 0:
if self.multi_select == False:
self.view.show(self.sels[0])
self.view.sel().clear()
map(lambda x: self.view.sel().add(x), self.sels)
def hv_highlight_color(self, b_value):
"""
High visibility highlight decesions.
"""
color = self.hv_color
if self.hv_color == HV_RSVD_VALUES[0]:
color = self.bracket_regions["default"].color
elif self.hv_color == HV_RSVD_VALUES[1]:
color = b_value
return color
def highlight_regions(self, name, icon_type, selections, bracket, regions):
"""
Apply the highlightes for the highlight region.
"""
if len(selections):
self.view.add_regions(
name,
getattr(bracket, selections),
self.hv_highlight_color(bracket.color) if HIGH_VISIBILITY else bracket.color,
getattr(bracket, icon_type),
self.hv_style if HIGH_VISIBILITY else bracket.style
)
regions.append(name)
def highlight(self, view):
"""
Highlight all bracket regions.
"""
for region_key in self.view.settings().get("bh_regions", []):
self.view.erase_regions(region_key)
regions = []
icon_type = "no_icon"
open_icon_type = "no_icon"
close_icon_type = "no_icon"
if not self.no_multi_select_icons or not self.multi_select:
icon_type = "small_icon" if self.view.line_height() < 16 else "icon"
open_icon_type = "small_open_icon" if self.view.line_height() < 16 else "open_icon"
close_icon_type = "small_close_icon" if self.view.line_height() < 16 else "close_icon"
for name, r in self.bracket_regions.items():
self.highlight_regions("bh_" + name, icon_type, "selections", r, regions)
self.highlight_regions("bh_" + name + "_center", "no_icon", "center_selections", r, regions)
self.highlight_regions("bh_" + name + "_open", open_icon_type, "open_selections", r, regions)
self.highlight_regions("bh_" + name + "_close", close_icon_type, "close_selections", r, regions)
# Track which regions were set in the view so that they can be cleaned up later.
self.view.settings().set("bh_regions", regions)
def get_search_bfr(self, sel):
"""
Read in the view's buffer for scanning for brackets etc.
"""
# Determine how much of the buffer to search
view_min = 0
view_max = self.view.size()
if not self.ignore_threshold:
left_delta = sel.a - view_min
right_delta = view_max - sel.a
limit = self.selection_threshold / 2
rpad = limit - left_delta if left_delta < limit else 0
lpad = limit - right_delta if right_delta < limit else 0
llimit = limit + lpad
rlimit = limit + rpad
self.search_window = (
sel.a - llimit if left_delta >= llimit else view_min,
sel.a + rlimit if right_delta >= rlimit else view_max
)
else:
self.search_window = (0, view_max)
# Search Buffer
return self.view.substr(sublime.Region(0, view_max))
def match(self, view, force_match=True):
"""
Preform matching brackets surround the selection(s)
"""
if view == None:
return
view.settings().set("BracketHighlighterBusy", True)
if not GLOBAL_ENABLE:
for region_key in view.settings().get("bh_regions", []):
view.erase_regions(region_key)
view.settings().set("BracketHighlighterBusy", False)
return
if self.keycommand:
BhCore.plugin_reload = True
if not self.keycommand and BhCore.plugin_reload:
self.setup()
BhCore.plugin_reload = False
# Setup views
self.view = view
self.last_view = view
num_sels = len(view.sel())
self.multi_select = (num_sels > 1)
if self.unique() or force_match:
# Initialize
self.init_match()
# Nothing to search for
if not self.enabled:
view.settings().set("BracketHighlighterBusy", False)
return
# Abort if selections are beyond the threshold
if self.use_selection_threshold and num_sels >= self.selection_threshold:
self.highlight(view)
view.settings().set("BracketHighlighterBusy", False)
return
multi_select_count = 0
# Process selections.
for sel in view.sel():
bfr = self.get_search_bfr(sel)
if not self.ignore_threshold and multi_select_count >= self.auto_selection_threshold:
self.store_sel([sel])
multi_select_count += 1
continue
if not self.find_scopes(bfr, sel):
self.sub_search_mode = False
self.find_matches(bfr, sel)
multi_select_count += 1
# Highlight, focus, and display lines etc.
self.change_sel()
self.highlight(view)
if self.count_lines:
sublime.status_message('In Block: Lines ' + str(self.lines) + ', Chars ' + str(self.chars))
view.settings().set("BracketHighlighterBusy", False)
def save_incomplete_regions(self, left, right, regions):
"""
Store single incomplete brackets for highlighting.
"""
found = left if left is not None else right
bracket = self.bracket_regions["unmatched"]
if bracket.underline:
bracket.selections += underline((found.toregion(),))
else:
bracket.selections += [found.toregion()]
self.store_sel(regions)
def save_regions(self, left, right, regions):
"""
Saved matched regions. Perform any special considerations for region formatting.
"""
bracket = self.bracket_regions.get(self.bracket_style, self.bracket_regions["default"])
lines = abs(self.view.rowcol(right.begin)[0] - self.view.rowcol(left.end)[0] + 1)
if self.count_lines:
self.chars += abs(right.begin - left.end)
self.lines += lines
if HIGH_VISIBILITY:
if lines <= 1:
if self.hv_underline:
bracket.selections += underline((sublime.Region(left.begin, right.end),))
else:
bracket.selections += [sublime.Region(left.begin, right.end)]
else:
bracket.open_selections += [sublime.Region(left.begin)]
if self.hv_underline:
bracket.center_selections += underline((sublime.Region(left.begin + 1, right.end - 1),))
else:
bracket.center_selections += [sublime.Region(left.begin, right.end)]
bracket.close_selections += [sublime.Region(right.begin)]
elif bracket.underline:
if lines <= 1:
bracket.selections += underline((left.toregion(), right.toregion()))
else:
bracket.open_selections += [sublime.Region(left.begin)]
bracket.close_selections += [sublime.Region(right.begin)]
if left.size():
bracket.center_selections += underline((sublime.Region(left.begin + 1, left.end),))
if right.size():
bracket.center_selections += underline((sublime.Region(right.begin + 1, right.end),))
else:
if lines <= 1:
bracket.selections += [left.toregion(), right.toregion()]
else:
bracket.open_selections += [left.toregion()]
bracket.close_selections += [right.toregion()]
self.store_sel(regions)
def sub_search(self, sel, search_window, bfr, scope=None):
"""
Search a scope bracket match for bracekts within.
"""
bracket = None
left, right = self.match_brackets(bfr, search_window, sel, scope)
regions = [sublime.Region(sel.a, sel.b)]
if left is not None and right is not None:
bracket = self.brackets[left.type]
left, right, regions, nobracket = self.run_plugin(bracket.name, left, right, regions)
if nobracket:
return True
# Matched brackets
if left is not None and right is not None and bracket is not None:
self.save_regions(left, right, regions)
return True
return False
def find_scopes(self, bfr, sel):
"""
Find brackets by scope definition.
"""
# Search buffer
left, right, bracket, sub_matched = self.match_scope_brackets(bfr, sel)
if sub_matched:
return True
regions = [sublime.Region(sel.a, sel.b)]
if left is not None and right is not None:
left, right, regions, _ = self.run_plugin(bracket.name, left, right, regions)
if left is None and right is None:
self.store_sel(regions)
return True
if left is not None and right is not None:
self.save_regions(left, right, regions)
return True
elif (left is not None or right is not None) and self.show_invalid:
self.save_incomplete_regions(left, right, regions)
return True
return False
def find_matches(self, bfr, sel):
"""
Find bracket matches
"""
bracket = None
left, right = self.match_brackets(bfr, self.search_window, sel)
regions = [sublime.Region(sel.a, sel.b)]
if left is not None and right is not None:
bracket = self.brackets[left.type]
left, right, regions, _ = self.run_plugin(bracket.name, left, right, regions)
# Matched brackets
if left is not None and right is not None and bracket is not None:
self.save_regions(left, right, regions)
# Unmatched brackets
elif (left is not None or right is not None) and self.show_unmatched:
self.save_incomplete_regions(left, right, regions)
else:
self.store_sel(regions)
def escaped(self, pt, ignore_string_escape, scope):
"""
Check if sub bracket in string scope is escaped.
"""