forked from facelessuser/BracketHighlighter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bh_core.py
executable file
·1013 lines (825 loc) · 34.4 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
"""
BracketHighlighter.
Copyright (c) 2013 - 2016 Isaac Muse <[email protected]>
License: MIT
"""
import sublime
import sublime_plugin
from os.path import basename, splitext
from time import time, sleep
import threading
import traceback
import BracketHighlighter.bh_plugin as bh_plugin
import BracketHighlighter.bh_search as bh_search
import BracketHighlighter.bh_regions as bh_regions
import BracketHighlighter.bh_rules as bh_rules
from BracketHighlighter.bh_logging import debug, log
if 'bh_thread' not in globals():
bh_thread = None
bh_match = None
BH_MATCH_TYPE_NONE = 0
BH_MATCH_TYPE_SELECTION = 1
BH_MATCH_TYPE_EDIT = 2
GLOBAL_ENABLE = True
HIGH_VISIBILITY = False
####################
# Match Code
####################
class BhCore(object):
"""Bracket matching class."""
plugin_reload = False
####################
# Match Setup
####################
def __init__(
self, override_thresh=False, count_lines=False,
adj_only=None, no_outside_adj=False, no_block_mode=False,
ignore=None, plugin=None, keycommand=False
):
"""Load settings and setup reload events if settings changes."""
if ignore is None:
ignore = {}
if plugin is None:
plugin = {}
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,
no_outside_adj, no_block_mode, ignore, plugin
)
def setup(
self, override_thresh=False, count_lines=False, adj_only=None,
no_outside_adj=False, no_block_mode=False, ignore=None, plugin=None
):
"""Initialize class settings from settings file and inputs."""
if ignore is None:
ignore = {}
if plugin is None:
plugin = {}
# Init view params
self.refresh_match = False
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.kill_highlight_on_threshold = bool(self.settings.get("kill_highlight_on_threshold", False))
if no_outside_adj is None:
no_outside_adj = self.settings.get('ignore_outside_adjacent_in_plugin', True)
if no_block_mode is None:
no_block_mode = self.settings.get('ignore_block_mode_in_plugin', True)
block_cursor = self.settings.get('block_cursor_mode', False) and not no_block_mode
# Init search object
self.rules = bh_rules.SearchRules(
self.settings.get("brackets", []) + self.settings.get("user_brackets", []),
self.settings.get("scope_brackets", []) + self.settings.get("user_scope_brackets", []),
str(self.settings.get('bracket_string_escape_mode', "string")),
False if no_outside_adj else self.settings.get("bracket_outside_adjacent", False),
block_cursor
)
# Init selection params
self.use_selection_threshold = True
self.selection_threshold = int(self.settings.get("search_threshold", 5000))
self.loaded_modules = set([])
# Init plugin
alter_select = False
self.plugin = None
self.plugin_targets = set([])
if 'command' in plugin:
self.plugin = bh_plugin.BracketPlugin(plugin, self.loaded_modules)
alter_select = True
if 'type' in plugin:
for target in plugin["type"]:
self.plugin_targets.add(target)
# Region selection, highlight, managment
self.regions = bh_regions.BhRegion(alter_select, count_lines)
def refresh_rules(self, language):
"""Reload rules."""
loaded_modules = self.loaded_modules.copy()
self.rules.load_rules(
language,
loaded_modules
)
def init_match(self, num_sels):
"""Reset matching settings for the current view's syntax."""
syntax = self.view.settings().get('syntax')
language = splitext(basename(syntax))[0].lower() if syntax is not None else "plain text"
self.regions.reset(self.view, num_sels)
if language != self.view_tracker[0] or self.view.id() != self.view_tracker[1]:
self.view_tracker = (language, self.view.id())
self.refresh_rules(language)
self.regions.set_show_unmatched(language)
def unique(self, sels):
"""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 sels])
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
####################
# Plugin
####################
def run_plugin(self, name, left, right, regions):
"""Run a bracket plugin."""
lbracket = bh_plugin.BracketRegion(left.begin, left.end)
rbracket = bh_plugin.BracketRegion(right.begin, right.end)
nobracket = False
if (
("__all__" in self.plugin_targets or name in self.plugin_targets) and
self.plugin is not None and
self.plugin.is_enabled()
):
lbracket, rbracket, regions, nobracket, refresh_match = self.plugin.run_command(
self.view, name, lbracket, rbracket, regions
)
left = left.move(lbracket.begin, lbracket.end) if lbracket is not None else None
right = right.move(rbracket.begin, rbracket.end) if rbracket is not None else None
if refresh_match:
self.refresh_match = True
return left, right, regions, nobracket
def highlighting(self, left, right, scope_bracket=False):
"""
Adjust region to highlight.
This is done after all methods that need
to know actual bracket region. At this point, we no longer care about
the actual bracket's region, and we change the highlight region to something
completely different.
"""
if left is not None:
if scope_bracket:
bracket = self.rules.scopes[left.scope]["brackets"][left.type]
bracket_scope = left.scope
else:
bracket = self.rules.brackets[left.type]
bracket_type = left.type
elif right is not None:
if scope_bracket:
bracket = self.rules.scopes[right.scope]["brackets"][right.type]
bracket_scope = right.scope
else:
bracket = self.rules.brackets[right.type]
bracket_type = right.type
else:
return left, right
if not self.rules.highlighting:
return left, right
if bracket.highlighting is not None:
lbracket, rbracket = bracket.highlighting(
self.view,
bracket.name,
self.bracket_style,
bh_plugin.BracketRegion(left.begin, left.end) if left is not None else None,
bh_plugin.BracketRegion(right.begin, right.end) if right is not None else None
)
if scope_bracket:
if lbracket is not None:
left = bh_search.ScopeEntry(lbracket.begin, lbracket.end, bracket_scope, bracket_type)
else:
left = None
if rbracket is not None:
right = bh_search.ScopeEntry(rbracket.begin, rbracket.end, bracket_scope, bracket_type)
else:
right = None
else:
if lbracket is not None:
left = bh_search.BracketEntry(lbracket.begin, lbracket.end, bracket_type)
else:
left = None
if rbracket is not None:
right = bh_search.BracketEntry(rbracket.begin, rbracket.end, bracket_type)
else:
right = None
return left, right
def validate(self, b, bracket_type, scope_bracket=False):
"""Validate bracket."""
match = True
if not self.rules.check_validate:
return match
bracket = self.rules.scopes[b.scope]["brackets"][b.type] if scope_bracket else self.rules.brackets[b.type]
if bracket.validate is not None:
try:
match = bracket.validate(
bracket.name,
bh_plugin.BracketRegion(b.begin, b.end),
bracket_type,
self.search.get_buffer()
)
except Exception:
log("Plugin Bracket Find Error:\n%s" % str(traceback.format_exc()))
return match
def compare(self, first, second, scope_bracket=False):
"""Compare brackets. This function allows bracket plugins to add aditional logic."""
if scope_bracket:
match = first is not None and second is not None
else:
match = first.type == second.type
if not self.rules.check_compare:
return match
if match:
if scope_bracket:
bracket = self.rules.scopes[first.scope]["brackets"][first.type]
else:
bracket = self.rules.brackets[first.type]
try:
if bracket.compare is not None and match:
match = bracket.compare(
bracket.name,
bh_plugin.BracketRegion(first.begin, first.end),
bh_plugin.BracketRegion(second.begin, second.end),
self.search.get_buffer()
)
except Exception:
log("Plugin Compare Error:\n%s" % str(traceback.format_exc()))
return match
def post_match(self, left, right, center, scope_bracket=False):
"""
Peform special logic after a match has been made.
This function allows bracket plugins to add aditional logic.
"""
if left is not None:
if scope_bracket:
bracket = self.rules.scopes[left.scope]["brackets"][left.type]
bracket_scope = left.scope
else:
bracket = self.rules.brackets[left.type]
bracket_type = left.type
elif right is not None:
if scope_bracket:
bracket = self.rules.scopes[right.scope]["brackets"][right.type]
bracket_scope = right.scope
else:
bracket = self.rules.brackets[right.type]
bracket_type = right.type
else:
return left, right
self.bracket_style = bracket.style
if not self.rules.check_post_match:
return left, right
if bracket.post_match is not None:
try:
lbracket, rbracket, self.bracket_style = bracket.post_match(
self.view,
bracket.name,
bracket.style,
bh_plugin.BracketRegion(left.begin, left.end) if left is not None else None,
bh_plugin.BracketRegion(right.begin, right.end) if right is not None else None,
center,
self.search.get_buffer(),
self.search.search_window
)
if scope_bracket:
if lbracket is not None:
left = bh_search.ScopeEntry(lbracket.begin, lbracket.end, bracket_scope, bracket_type)
else:
left = None
if rbracket is not None:
right = bh_search.ScopeEntry(rbracket.begin, rbracket.end, bracket_scope, bracket_type)
else:
right = None
else:
if lbracket is not None:
left = bh_search.BracketEntry(lbracket.begin, lbracket.end, bracket_type)
else:
left = None
if rbracket is not None:
right = bh_search.BracketEntry(rbracket.begin, rbracket.end, bracket_type)
else:
right = None
except Exception:
log("Plugin Post Match Error:\n%s" % str(traceback.format_exc()))
return left, right
####################
# Matching
####################
def match(self, view, force_match=True):
"""Preform matching brackets surround the selection(s)."""
if view is None:
return
# Ensure nothing else calls BH until done
view.settings().set("BracketHighlighterBusy", True)
# Abort if disabled
if not GLOBAL_ENABLE:
for region_key in view.settings().get("bh_regions", []):
view.erase_regions(region_key)
view.settings().set("BracketHighlighterBusy", False)
return
# Handle key command quirks
if self.keycommand:
BhCore.plugin_reload = True
if not self.keycommand and BhCore.plugin_reload:
self.setup()
BhCore.plugin_reload = False
# Setup view
self.view = view
self.refresh_match = False
sels = view.sel()
num_sels = len(sels)
# Abort if selections are beyond the threshold and "kill" is enabled
if not self.ignore_threshold and self.kill_highlight_on_threshold:
if self.use_selection_threshold and num_sels > self.auto_selection_threshold:
self.regions.reset(view, num_sels)
self.regions.highlight(HIGH_VISIBILITY)
view.settings().set("BracketHighlighterBusy", False)
return
# Initialize
if self.unique(sels) or force_match:
# Prepare for match
self.init_match(num_sels)
# Nothing to search for
if not self.rules.enabled:
view.settings().set("BracketHighlighterBusy", False)
return
# Process selections.
multi_select_count = 0
for sel in sels:
if not self.ignore_threshold and multi_select_count >= self.auto_selection_threshold:
# Exceeded threshold, only what must be done
# and break
if not self.regions.alter_select:
break
self.regions.store_sel([sel])
continue
# Subsearch guard for recursive matching of scopes
self.recursive_guard = False
# Prepare for search
self.bracket_style = None
self.search = bh_search.Search(
view, self.rules,
sel, self.selection_threshold if not self.ignore_threshold else None
)
# Find and match
if not self.find_scopes(sel):
self.sub_search_mode = False
self.find_matches(sel)
multi_select_count += 1
# Highlight, focus, and display lines etc.
self.regions.highlight(HIGH_VISIBILITY)
# Free up BH
self.search = None
self.view = None
# Setup thread to do another match to refresh the match
if self.refresh_match:
bh_thread.type = BH_MATCH_TYPE_SELECTION
bh_thread.modified = True
bh_thread.time = time()
view.settings().set("BracketHighlighterBusy", False)
def sub_search(self, sel, scope=None):
"""Search a scope bracket match for bracekts within."""
# Protect against recursive search of scopes
self.recursive_guard = True
# Find brackets inside scope
bracket = None
left, right = self.match_brackets(sel, scope)[:2]
regions = [sublime.Region(sel.a, sel.b)]
if left is not None and right is not None:
bracket = self.rules.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 and not HIGH_VISIBILITY:
left, right = self.highlighting(left, right)
self.regions.save_complete_regions(left, right, regions, self.bracket_style, HIGH_VISIBILITY)
return True
return False
def find_scopes(self, sel, adj_dir=bh_search.BH_ADJACENT_LEFT):
"""Find brackets by scope definition."""
# Search buffer
left, right, bracket, sub_matched = self.match_scope_brackets(sel, adj_dir)
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.regions.store_sel(regions)
return True
if not HIGH_VISIBILITY:
left, right = self.highlighting(left, right, scope_bracket=True)
return self.regions.save_regions(left, right, regions, self.bracket_style, HIGH_VISIBILITY)
def find_matches(self, sel):
"""Find bracket matches."""
bracket = None
left, right, adj_scope = self.match_brackets(sel)
if adj_scope:
return
regions = [sublime.Region(sel.a, sel.b)]
if left is not None and right is not None:
bracket = self.rules.brackets[left.type]
left, right, regions, _ = self.run_plugin(bracket.name, left, right, regions)
if not HIGH_VISIBILITY:
left, right = self.highlighting(left, right)
if not self.regions.save_regions(left, right, regions, self.bracket_style, HIGH_VISIBILITY):
self.regions.store_sel(regions)
def match_scope_brackets(self, sel, adj_dir):
"""
Perform match for scope brackets.
See if scope should be searched, and then check
endcaps to determine if valid scope bracket.
"""
center = sel.b
left = None
right = None
scope_count = 0
before_center = center - 1
bracket_count = 0
partial_find = None
selected_scope = None
bracket = None
adjusted_center = center
# Cannot be inside a bracket pair if cursor is at zero
if center == 0:
if not self.rules.outside_adj and not self.rules.block_cursor:
return left, right, selected_scope, False
for s in self.rules.scopes:
scope = s["name"]
# Identify if the cursor is in a scope with bracket definitions
try:
scope_search = self.search.new_scope_search(
center, before_center, scope, adj_dir
)
except Exception:
# log(str(traceback.format_exc()))
scope_count += 1
continue
# Search the bracket patterns of this scope
# to determine if this scope matches the rules.
bracket_count = 0
for b in s["brackets"]:
left, right = scope_search.get_brackets(b.open, b.close, scope_count, bracket_count)
if left is not None and not self.validate(left, bh_search.BH_SEARCH_OPEN, True):
left = None
if right is not None and not self.validate(right, bh_search.BH_SEARCH_CLOSE, True):
right = None
if not self.compare(left, right, scope_bracket=True):
left, right = None, None
# Track partial matches. If a full match isn't found,
# return the first partial match at the end.
if partial_find is None and bool(left) != bool(right):
partial_find = (left, right)
left = None
right = None
if left and right:
adjusted_center = scope_search.adjusted_center
break
bracket_count += 1
if left and right:
break
scope_count += 1
# Full match not found. Return partial match (if any).
if (left is None or right is None) and partial_find is not None:
left, right = partial_find[0], partial_find[1]
# Make sure cursor in highlighted sub group
if self.rules.block_cursor:
if (
(left and center < left.begin and adjusted_center <= left.begin) or
(right and center >= right.end and adjusted_center >= right.end)
):
left, right = None, None
elif self.rules.outside_adj:
if (
(left and center <= left.begin and adjusted_center <= left.begin) or
(right and center >= right.end and adjusted_center >= right.end)
):
left, right = None, None
else:
if (left and adjusted_center <= left.begin) or (right and adjusted_center >= right.end):
left, right = None, None
if left is not None:
selected_scope = self.rules.scopes[left.scope]["name"]
elif right is not None:
selected_scope = self.rules.scopes[right.scope]["name"]
if left is not None and right is not None:
bracket = self.rules.scopes[left.scope]["brackets"][left.type]
if bracket.sub_search:
self.sub_search_mode = True
self.search.set_search_window((left.begin, right.end))
if self.sub_search(sel, scope):
return left, right, self.rules.brackets[left.type], True
elif bracket.sub_search_only:
left, right, bracket = None, None, None
if self.adj_only:
if self.rules.block_cursor:
left, right = self.block_adjacent_check(left, right, center)
else:
left, right = self.adjacent_check(left, right, center)
left, right = self.post_match(left, right, center, scope_bracket=True)
return left, right, bracket, False
def match_brackets(self, sel, scope=None):
"""Regex bracket matching."""
center = sel.b
left = None
right = None
stack = []
bracket_search = self.search.new_bracket_search(
center, self.sub_search_mode, scope
)
if self.rules.outside_adj and not bracket_search.touch_right and not self.recursive_guard:
if self.find_scopes(sel, bh_search.BH_ADJACENT_RIGHT):
return None, None, True
self.sub_search_mode = False
for o in bracket_search.get_open(bh_search.BH_SEARCH_LEFT):
if not self.validate(o, bh_search.BH_SEARCH_OPEN):
continue
if len(stack) and bracket_search.is_done(bh_search.BH_SEARCH_CLOSE):
if self.compare(o, stack[-1]):
stack.pop()
continue
for c in bracket_search.get_close(bh_search.BH_SEARCH_LEFT):
if not self.validate(c, bh_search.BH_SEARCH_CLOSE):
continue
if o.end <= c.begin:
stack.append(c)
continue
elif len(stack):
bracket_search.remember(bh_search.BH_SEARCH_CLOSE)
break
if len(stack):
b = stack.pop()
if self.compare(o, b):
continue
else:
left = o
break
bracket_search.reset_end_state()
stack = []
# Grab each closest closing right side bracket and attempt to match it.
# If the closing bracket cannot be matched, select it.
for c in bracket_search.get_close(bh_search.BH_SEARCH_RIGHT):
if not self.validate(c, bh_search.BH_SEARCH_CLOSE):
continue
if len(stack) and bracket_search.is_done(bh_search.BH_SEARCH_OPEN):
if self.compare(stack[-1], c):
stack.pop()
continue
for o in bracket_search.get_open(bh_search.BH_SEARCH_RIGHT):
if not self.validate(o, bh_search.BH_SEARCH_OPEN):
continue
if o.end <= c.begin:
stack.append(o)
continue
else:
bracket_search.remember(bh_search.BH_SEARCH_OPEN)
break
if len(stack):
b = stack.pop()
if self.compare(b, c):
continue
else:
if left is None or self.compare(left, c):
right = c
break
if self.adj_only:
if self.rules.block_cursor:
left, right = self.block_adjacent_check(left, right, center)
else:
left, right = self.adjacent_check(left, right, center)
left, right = self.post_match(left, right, center)
return left, right, False
def adjacent_check(self, left, right, center):
"""Check if bracket pair are adjacent to cursor."""
if left and right:
if left.end < center < right.begin:
left, right = None, None
elif (left and left.end < center) or (right and center < right.begin):
left, right = None, None
return left, right
def block_adjacent_check(self, left, right, center):
"""Check if block bracket pair have the cursor directly on a bracket."""
if left and right:
if left.begin < center < right.begin:
left, right = None, None
elif (left and left.begin < center) or (right and center < right.begin):
left, right = None, None
return left, right
####################
# Commands
####################
class BhToggleStringEscapeModeCommand(sublime_plugin.TextCommand):
"""Toggle between regex escape and string escape for brackets in strings."""
def run(self, edit):
"""Perform string escape toggling."""
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):
"""Show bracket string escape mode."""
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 high visibility mode.
Toggle a high visibility mode that
highlights the entire bracket extent.
"""
def run(self):
"""Toggle high visibility."""
global HIGH_VISIBILITY
HIGH_VISIBILITY = not HIGH_VISIBILITY
class BhToggleEnableCommand(sublime_plugin.ApplicationCommand):
"""Toggle global enable for BracketHighlighter."""
def run(self):
"""Toggle BH enable state."""
global GLOBAL_ENABLE
GLOBAL_ENABLE = not GLOBAL_ENABLE
if not GLOBAL_ENABLE:
bh_regions.clear_all_regions()
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,
no_outside_adj=False, no_block_mode=False, ignore=None, plugin=None
):
"""Run BH key command."""
if ignore is None:
ignore = {}
if plugin is None:
plugin = {}
# Override events
bh_thread.ignore_all = True
bh_thread.modified = False
self.bh = BhCore(
threshold,
lines,
adjacent,
no_outside_adj,
no_block_mode,
ignore,
plugin,
True
)
self.view = self.window.active_view()
self.execute()
def execute(self):
"""Trigger actual BH command."""
debug("Key Event")
self.bh.match(self.view)
bh_thread.ignore_all = False
bh_thread.time = time()
class BhAsyncKeyCommand(BhKeyCommand):
"""Call BH key command asynchronously."""
def execute(self):
"""Call execute command asynchronously."""
sublime.set_timeout(self.async_execute, 100)
def async_execute(self):
"""Trigger actual BH command."""
debug("Async Key Event")
self.bh.match(self.view)
bh_thread.ignore_all = False
bh_thread.time = time()
####################
# Debug
####################
class BhDebugCommand(sublime_plugin.ApplicationCommand):
"""Toggle debug commands."""
def run(self, set_value=None):
"""Perform debug toggle."""
settings = sublime.load_settings("bh_core.sublime-settings")
if set_value is None:
value = bool(settings.get("debug_enable", False))
settings.set("debug_enable", not value)
else:
settings.set("debug_enable", set_value)
def is_checked(self):
"""Check if command should be checked in menu."""
return sublime.load_settings("bh_core.sublime-settings").get('debug_enable', False)
def is_enabled(self, set_value=None):
"""Check if command should be enabled."""
if set_value is None:
enabled = True
elif set_value:
enabled = not sublime.load_settings("bh_core.sublime-settings").get('debug_enable', False)
else:
enabled = sublime.load_settings("bh_core.sublime-settings").get('debug_enable', False)
return enabled
####################
# Events
####################
class BhListenerCommand(sublime_plugin.EventListener):
"""
Manage when to kick off bracket matching.
Try and reduce redundant requests by letting the
background thread ensure certain needed match occurs
"""
def on_load(self, view):
"""Search brackets on view load."""
if self.ignore_event(view):
return
bh_thread.type = BH_MATCH_TYPE_SELECTION
sublime.set_timeout(bh_thread.payload, 0)
def on_modified(self, view):
"""Update highlighted brackets when the text changes."""
if self.ignore_event(view):
return
bh_thread.type = BH_MATCH_TYPE_EDIT
bh_thread.modified = True
bh_thread.time = time()
def on_activated(self, view):
"""Highlight brackets when the view gains focus again."""
if self.ignore_event(view):
return
bh_thread.type = BH_MATCH_TYPE_SELECTION
sublime.set_timeout(bh_thread.payload, 0)
def on_selection_modified(self, view):
"""Highlight brackets when the selections change."""
if self.ignore_event(view):
return
if bh_thread.type != BH_MATCH_TYPE_EDIT:
bh_thread.type = BH_MATCH_TYPE_SELECTION
now = time()
if now - bh_thread.time > bh_thread.wait_time:
sublime.set_timeout(bh_thread.payload, 0)
else:
bh_thread.modified = True
bh_thread.time = now
def ignore_event(self, view):
"""
Ignore highlight request.
Ignore request to highlight if the view is a widget,
or if it is too soon to accept an event.
"""
return (view.settings().get('is_widget') or bh_thread.ignore_all)
class BhThread(threading.Thread):
"""BH threading."""
def __init__(self):
"""Setup the thread."""
self.reset()
threading.Thread.__init__(self)
def reset(self):
"""Reset the thread variables."""
self.wait_time = 0.12
self.time = time()
self.modified = False
self.type = BH_MATCH_TYPE_SELECTION
self.ignore_all = False
self.abort = False
def payload(self):
"""Code to run."""
self.modified = False
window = sublime.active_window()
view = window.active_view() if window is not None else None
self.ignore_all = True
if bh_match is not None:
bh_match(view, self.type == BH_MATCH_TYPE_EDIT)
self.ignore_all = False
self.time = time()
def kill(self):
"""Kill thread."""
self.abort = True
while self.is_alive():
pass
self.reset()
def run(self):
"""Thread loop."""
while not self.abort:
if self.modified is True and time() - self.time > self.wait_time:
sublime.set_timeout(self.payload, 0)
sleep(0.5)
####################
# Loading
####################
def init_bh_match():
"""Initialize the match object."""
global bh_match
bh_match = BhCore().match
debug("Match object loaded.")
def plugin_loaded():
"""
General plugin initialization.
Load up uniocode table, initialize settings and match object,
and start event loop. Restart event loop if already loaded.
"""
global HIGH_VISIBILITY
global bh_thread
init_bh_match()
global HIGH_VISIBILITY
if sublime.load_settings("bh_core.sublime-settings").get('high_visibility_enabled_by_default', False):