-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathrr_replacer.py
More file actions
executable file
·887 lines (774 loc) · 34.3 KB
/
rr_replacer.py
File metadata and controls
executable file
·887 lines (774 loc) · 34.3 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
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
"""
Reg Replace.
Licensed under MIT
Copyright (c) 2011 - 2016 Isaac Muse <isaacmuse@gmail.com>
"""
import sublime
import backrefs
from RegReplace.rr_plugin import Plugin
from backrefs import bre
import re
import traceback
import string
from RegReplace.rr_notify import error
from collections import deque
try:
import regex
from backrefs import bregex
REGEX_SUPPORT = True
except ImportError:
regex = None
bregex = None
REGEX_SUPPORT = False
FORMAT_REPLACE = backrefs.__version_info__ >= (2, 1, 0)
class RegexInputFormatter(string.Formatter):
"""Regex input formatter."""
def __init__(self, engine):
"""Initialize."""
self._engine = engine
self.implicit = -1
self.explicit = False
super(RegexInputFormatter, self).__init__()
def convert_field(self, value, conversion):
"""Convert to escaped format."""
if conversion is not None and conversion == 'e':
return self._engine.escape(value)
return super(RegexInputFormatter, self).convert_field(value, conversion)
def get_value(self, key, args, kwargs):
"""Get value."""
if key == '':
if not self.explicit:
self.implicit += 1
key = self.implicit
else:
raise ValueError("Cannot change from explicit index to implicit!")
elif self.implicit >= 0:
raise ValueError("Cannot change from implict to explicit indexing!")
return super(RegexInputFormatter, self).get_value(key, args, kwargs)
class ScopeRepl(object):
"""
Replace object for scopes.
Call on_replace event if there is a plugin to run.
"""
def __init__(self, has_plugin, replace, expand, replace_event):
"""Initialize."""
self.has_plugin = has_plugin
self.replace = replace
self.expand = expand
self.replace_event = replace_event
def repl(self, m):
"""Apply replace."""
return self.replace_event(m) if self.has_plugin else self.expand(m, self.replace)
class FindReplace(object):
"""Find and replace using regex."""
def __init__(self, view, edit, find_only, full_file, selection_only, max_sweeps, action):
"""Initialize find replace object."""
Plugin.purge()
self.view = view
self.edit = edit
self.find_only = find_only
self.full_file = full_file
self.selection_only = selection_only
self.max_sweeps = max_sweeps
self.action = action
self.target_regions = []
self.plugin = None
settings = sublime.load_settings('reg_replace.sublime-settings')
self.extend = bool(settings.get("extended_back_references", False))
self.use_regex = bool(settings.get('use_regex_module', False)) and REGEX_SUPPORT
self.sel_input_max_size = int(settings.get('selection_input_max_size', 256))
self.sel_input_max_count = int(settings.get('selection_input_max_count', 10))
self.use_format = (self.extend or self.use_regex) and FORMAT_REPLACE
if self.use_regex:
regex_version = int(settings.get('regex_module_version', 0))
if regex_version > 1:
regex_version = 0
self.regex_version_flag = bregex.VERSION1 if regex_version else bregex.VERSION0
else:
self.regex_version_flag = 0
self.extend_module = bregex if self.use_regex else bre
self.normal_module = regex if self.use_regex else re
def view_replace(self, region, replacement):
"""
Replace in the view.
Account for tab settings that can interfere with the replace.
"""
self.view.replace(self.edit, region, replacement)
def close(self):
"""Clean up for the object. Mainly clean up the tracked loaded plugins."""
Plugin.purge()
def on_replace(self, m):
"""Run the associated plugin on the replace event."""
try:
module = Plugin.load(self.plugin)
text = module.replace(m, **self.plugin_args)
except Exception:
text = m.group(0)
print(str(traceback.format_exc()))
return text
def filter_by_selection(self, regions, extractions=None):
"""Filter results by what is included in selected region."""
new_regions = []
new_extractions = []
idx = 0
sels = self.view.sel()
for region in regions:
for sel in sels:
if region.begin() >= sel.begin() and region.end() <= sel.end():
new_regions.append(region)
if extractions is not None:
new_extractions.append(extractions[idx])
break
idx += 1
return (new_regions, new_extractions) if extractions is not None else (new_regions, None)
def get_sel_point(self):
"""See if there is a cursor and get the first selections starting point."""
sel = self.view.sel()
pt = None if len(sel) == 0 else sel[0].begin()
return pt
def qualify_by_scope(self, region, pattern):
"""Qualify the match with scopes."""
for entry in pattern:
# Is there something to qualify?
if len(entry) > 0:
# Initialize qualification parameters
qualify = True
pt = region.begin()
end = region.end()
# Disqualify if entirely of scope
if entry.startswith('-!'):
entry = entry.lstrip('-!')
qualify = False
while pt < end:
if self.view.score_selector(pt, entry) == 0:
qualify = True
break
pt += 1
# Disqualify if one or more instances of scope
elif entry.startswith('-'):
entry = entry.lstrip('-')
while pt < end:
if self.view.score_selector(pt, entry):
qualify = False
break
pt += 1
# Qualify if entirely of scope
elif entry.startswith('!'):
entry = entry.lstrip('!')
while pt < end:
if self.view.score_selector(pt, entry) == 0:
qualify = False
break
pt += 1
# Qualify if one or more instances of scope
else:
qualify = False
while pt < end:
if self.view.score_selector(pt, entry):
qualify = True
break
pt += 1
# If qualification of one fails, bail
if qualify is False:
return qualify
# Qualification completed successfully
return True
def greedy_replace(self, replace, regions, scope_filter):
"""Perform a greedy replace."""
# Initialize replace
replaced = 0
count = len(regions) - 1
# Step through all targets and qualify them for replacement
tabs_to_spaces = self.view.settings().get('translate_tabs_to_spaces', False)
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', False)
for region in reversed(regions):
# Does the scope qualify?
qualify = self.qualify_by_scope(region, scope_filter) if scope_filter is not None else True
if qualify:
replaced += 1
if self.find_only or self.action is not None:
# If "find only" or replace action is overridden, just track regions
self.target_regions.append(region)
else:
# Apply replace
self.view_replace(region, replace[count])
count -= 1
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', True)
return replaced
def non_greedy_replace(self, replace, regions, scope_filter):
"""Perform a non-greedy replace."""
# Initialize replace
replaced = 0
last_region = len(regions) - 1
selected_region = None
selection_index = 0
# See if there is a cursor and get the first selections starting point
pt = self.get_sel_point()
# Initialize with first qualifying region for wrapping and the case of no cursor in view
count = 0
for region in regions:
# Does the scope qualify?
qualify = self.qualify_by_scope(region, scope_filter) if scope_filter is not None else True
if qualify:
# Update as new replacement candidate
selected_region = region
selection_index = count
break
else:
count += 1
# If regions were already swept till the end, skip calculation relative to cursor
if selected_region is not None and count < last_region and pt is not None:
# Try and find the first qualifying match contained withing the first selection or after
reverse_count = last_region
for region in reversed(regions):
# Make sure we are not checking previously checked regions
# And check if region contained after start of selection?
if reverse_count >= count and region.end() - 1 >= pt:
# Does the scope qualify?
qualify = self.qualify_by_scope(region, scope_filter) if scope_filter is not None else True
if qualify:
# Update as new replacement candidate
selected_region = region
selection_index = reverse_count
# Walk backwards through replace index
reverse_count -= 1
else:
break
# Did we find a suitable region?
if selected_region is not None:
# Show Instance
replaced += 1
self.view.show(selected_region.begin())
if self.find_only or self.action is not None:
# If "find only" or replace action is overridden, just track regions
self.target_regions.append(selected_region)
else:
# Apply replace
tabs_to_spaces = self.view.settings().get('translate_tabs_to_spaces', False)
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', False)
self.view_replace(selected_region, replace[selection_index])
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', True)
return replaced
def expand(self, m, replace):
"""Apply replace."""
if self.extend:
return self.template(m)
elif self.format:
return m.expandf(replace)
else:
return m.expand(replace)
def regex_findall(self, find, flags, replace, extractions, literal=False, sel=None):
"""Find all with regex."""
regions = deque()
offset = 0
if sel is not None:
offset = sel.begin()
bfr = self.view.substr(sublime.Region(offset, sel.end()))
else:
bfr = self.view.substr(sublime.Region(0, self.view.size()))
if self.extend:
flags |= self.extend_module.MULTILINE
else:
flags |= self.normal_module.MULTILINE
if literal:
find = self.normal_module.escape(find)
if self.extend and not literal:
pattern = self.extend_module.compile_search(find, flags | self.regex_version_flag)
if not self.plugin:
self.template = self.extend_module.compile_replace(
pattern, replace, (self.extend_module.FORMAT if self.format else 0)
)
else:
pattern = self.normal_module.compile(find, flags | self.regex_version_flag)
if self.use_regex:
reverse = bool(pattern.flags & regex.REVERSE)
else:
reverse = False
for m in pattern.finditer(bfr):
if reverse:
regions.appendleft(sublime.Region(offset + m.start(0), offset + m.end(0)))
if literal:
extractions.appendleft(replace)
elif self.plugin is not None:
extractions.appendleft(self.on_replace(m))
else:
extractions.appendleft(self.expand(m, replace))
else:
regions.append(sublime.Region(offset + m.start(0), offset + m.end(0)))
if literal:
extractions.append(replace)
elif self.plugin is not None:
extractions.append(self.on_replace(m))
else:
extractions.append(self.expand(m, replace))
return regions
def apply(self, pattern):
"""Normal find and replace."""
# Initialize replacement variables
regions = []
flags = 0
replaced = 0
# Grab pattern definitions
find = pattern['find']
replace = pattern.get('replace', r'\g<0>')
selection_inputs = pattern.get('selection_inputs', False)
greedy = bool(pattern.get('greedy', True))
scope_filter = pattern.get('scope_filter', [])
self.format = bool(pattern.get('format_replace', False)) and self.use_format
self.plugin = pattern.get("plugin", None)
self.plugin_args = pattern.get("args", {})
literal = pattern.get('literal', False)
literal_ignorecase = literal and bool(pattern.get('literal_ignorecase', False))
# Ignore Case?
if literal_ignorecase:
if self.extend:
flags |= self.extend_module.IGNORECASE
else:
flags |= self.normal_module.IGNORECASE
find, sels, sel_start, sel_size, errors = self.process_selections(
find, self.selection_only, selection_inputs, literal
)
if errors:
return replace
# Find and format replacements
extractions = deque()
try:
# regions = self.view.find_all(find, flags, replace, extractions)
if self.selection_only and not self.full_file:
for sel in sels:
regions += self.regex_findall(find, flags, replace, extractions, literal, sel)
else:
regions = self.regex_findall(find, flags, replace, extractions, literal)
except Exception as err:
print(str(traceback.format_exc()))
error('REGEX ERROR: %s' % str(err))
return replaced
if self.selection_only and self.full_file:
regions, extractions = self.filter_by_selection(regions, extractions)
# Where there any regions found?
if len(regions) > 0:
# Greedy or non-greedy search? Get replaced instances.
if greedy:
replaced = self.greedy_replace(extractions, regions, scope_filter)
else:
replaced = self.non_greedy_replace(extractions, regions, scope_filter)
if self.selection_only:
new_sels = []
count = 0
offset = 0
for s in sels:
r = sublime.Region(sel_start[count] + offset, s.end())
new_sels.append(r)
offset += r.size() - sel_size[count]
count += 1
sels.clear()
sels.add_all(new_sels)
return replaced
def apply_scope_regex(self, string, pattern, replace, greedy_replace, multi, start, sub_regions):
"""Apply regex on a scope."""
replaced = 0
extraction = string
scope_repl = ScopeRepl(self.plugin, replace, self.expand, self.on_replace)
if self.extend and not self.plugin:
self.template = self.extend_module.compile_replace(
pattern, replace, (self.extend_module.FORMAT if self.format else 0)
)
if multi and not self.find_only and self.action is None:
extraction, replaced = self.apply_multi_pass_scope_regex(
pattern, extraction, scope_repl.repl, greedy_replace
)
elif self.find_only or self.action is not None:
replaced = self.scope_find(pattern, string, start, sub_regions, greedy_replace)
else:
extraction, replaced = self.scope_sub(pattern, scope_repl.repl, extraction, greedy_replace)
return extraction, replaced
def apply_multi_pass_scope_regex(self, pattern, extraction, repl, greedy_replace):
"""Use a multi-pass scope regex."""
count = 0
total_replaced = 0
while count < self.max_sweeps:
count += 1
extraction, multi_replaced = self.scope_sub(pattern, repl, extraction, greedy_replace)
if multi_replaced == 0:
break
total_replaced += multi_replaced
return extraction, total_replaced
def scope_find(self, pattern, string, offset, sub_regions, greedy_replace):
"""Find in scopes."""
if self.use_regex:
reverse = bool(pattern.flags & regex.REVERSE)
else:
reverse = False
replaced = 0
for m in pattern.finditer(string):
if reverse:
sub_regions.appendleft(sublime.Region(offset + m.start(0), offset + m.end(0)))
else:
sub_regions.append(sublime.Region(offset + m.start(0), offset + m.end(0)))
replaced += 1
if not greedy_replace:
break
return replaced
def scope_sub(self, pattern, replace, string, greedy_replace):
"""Substitute replace."""
if self.use_regex:
reverse = bool(pattern.flags & regex.REVERSE)
else:
reverse = False
offset = len(string) if reverse else 0
text = deque()
replaced = 0
for m in pattern.finditer(string):
if reverse:
text.appendleft(string[m.end(0):offset])
text.appendleft(replace(m))
offset = m.start(0)
else:
text.append(string[offset:m.start(0)])
text.append(replace(m))
offset = m.end(0)
replaced += 1
if not greedy_replace:
break
if reverse:
text.appendleft(string[:offset])
else:
text.append(string[offset:])
return ''.join(text), replaced
def greedy_scope_literal_replace(self, regions, find, replace, greedy_replace):
"""Greedy literal scope replace."""
total_replaced = 0
tabs_to_spaces = self.view.settings().get('translate_tabs_to_spaces', False)
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', False)
for region in reversed(regions):
sub_regions = deque()
start = region.begin()
extraction = self.view.substr(region)
if self.find_only or self.action is not None:
replace_count = self.scope_find(find, extraction, start, sub_regions, greedy_replace)
else:
extraction, replace_count = self.scope_sub(find, replace, extraction, greedy_replace)
sub_regions = deque([region])
if replace_count > 0:
total_replaced += 1
if self.find_only or self.action is not None:
self.target_regions.extend(sub_regions)
else:
self.view_replace(region, extraction)
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', True)
return total_replaced
def non_greedy_scope_literal_replace(self, regions, find, replace, greedy_replace):
"""Non greedy literal scope replace."""
# Initialize replace
total_replaced = 0
last_region = len(regions) - 1
selected_region = None
selected_sub_regions = None
selected_extraction = None
# See if there is a cursor and get the first selections starting point
pt = self.get_sel_point()
# Initialize with first qualifying region for wrapping and the case of no cursor in view
count = 0
for region in regions:
sub_regions = deque()
start = region.begin()
extraction = self.view.substr(region)
if self.find_only or self.action is not None:
replace_count = self.scope_find(find, extraction, start, sub_regions, greedy_replace)
else:
extraction, replace_count = self.scope_sub(find, replace, extraction, greedy_replace)
if replace_count > 0:
selected_region = region
selected_sub_regions = sub_regions
selected_extraction = extraction
break
else:
count += 1
# If regions were already swept till the end, skip calculation relative to cursor
if selected_region is not None and count < last_region and pt is not None:
# Try and find the first qualifying match contained withing the first selection or after
reverse_count = last_region
for region in reversed(regions):
sub_regions = deque()
start = region.begin()
# Make sure we are not checking previously checked regions
# And check if region contained after start of selection?
if reverse_count >= count and region.end() - 1 >= pt:
extraction = self.view.substr(region)
if self.find_only or self.action is not None:
replace_count = self.scope_find(find, extraction, start, sub_regions, greedy_replace)
else:
extraction, replace_count = self.scope_sub(find, replace, extraction, greedy_replace)
if replace_count > 0:
selected_region = region
selected_sub_regions = sub_regions
selected_extraction = extraction
reverse_count -= 1
else:
break
# Did we find a suitable region?
if selected_region is not None:
# Show Instance
total_replaced += 1
self.view.show(selected_region.begin())
if self.find_only or self.action is not None:
# If "find only" or replace action is overridden, just track regions
self.target_regions.extend(selected_sub_regions)
else:
# Apply replace
tabs_to_spaces = self.view.settings().get('translate_tabs_to_spaces', False)
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', False)
self.view_replace(selected_region, selected_extraction)
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', True)
return total_replaced
def greedy_scope_replace(self, regions, re_find, replace, greedy_replace, multi):
"""Greedy scope replace."""
total_replaced = 0
tabs_to_spaces = self.view.settings().get('translate_tabs_to_spaces', False)
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', False)
try:
for region in reversed(regions):
sub_regions = deque()
replaced = 0
string = self.view.substr(region)
extraction, replaced = self.apply_scope_regex(
string, re_find, replace, greedy_replace, multi, region.begin(), sub_regions
)
if replaced > 0:
total_replaced += 1
if self.find_only or self.action is not None:
self.target_regions.extend(sub_regions)
else:
self.view_replace(region, extraction)
except Exception as err:
print(str(traceback.format_exc()))
error('REGEX ERROR: %s' % str(err))
return total_replaced
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', True)
return total_replaced
def non_greedy_scope_replace(self, regions, re_find, replace, greedy_replace, multi):
"""Non greedy scope replace."""
# Initialize replace
total_replaced = 0
replaced = 0
last_region = len(regions) - 1
selected_region = None
selected_sub_regions = None
selected_extraction = None
# See if there is a cursor and get the first selections starting point
pt = self.get_sel_point()
# Initialize with first qualifying region for wrapping and the case of no cursor in view
count = 0
try:
for region in regions:
sub_regions = deque()
string = self.view.substr(region)
extraction, replaced = self.apply_scope_regex(
string, re_find, replace, greedy_replace, multi, region.begin(), sub_regions
)
if replaced > 0:
selected_region = region
selected_sub_regions = sub_regions
selected_extraction = extraction
break
else:
count += 1
except Exception as err:
print(str(traceback.format_exc()))
error('REGEX ERROR: %s' % str(err))
return total_replaced
try:
# If regions were already swept till the end, skip calculation relative to cursor
if selected_region is not None and count < last_region and pt is not None:
# Try and find the first qualifying match contained withing the first selection or after
reverse_count = last_region
for region in reversed(regions):
sub_regions = deque()
# Make sure we are not checking previously checked regions
# And check if region contained after start of selection?
if reverse_count >= count and region.end() - 1 >= pt:
string = self.view.substr(region)
extraction, replaced = self.apply_scope_regex(
string, re_find, replace, greedy_replace, multi, region.begin(), sub_regions
)
if replaced > 0:
selected_region = region
selected_sub_regions = sub_regions
selected_extraction = extraction
reverse_count -= 1
else:
break
except Exception as err:
print(str(traceback.format_exc()))
error('REGEX ERROR: %s' % str(err))
return total_replaced
# Did we find a suitable region?
if selected_region is not None:
# Show Instance
total_replaced += 1
self.view.show(selected_region.begin())
if self.find_only or self.action is not None:
# If "find only" or replace action is overridden, just track regions
self.target_regions.extend(selected_sub_regions)
else:
# Apply replace
tabs_to_spaces = self.view.settings().get('translate_tabs_to_spaces', False)
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', False)
self.view_replace(selected_region, selected_extraction)
if tabs_to_spaces:
self.view.settings().set('translate_tabs_to_spaces', True)
return total_replaced
def select_scope_regions(self, regions, greedy_scope):
"""Select scope region."""
if greedy_scope:
# Greedy scope; return all scopes
replaced = len(regions)
self.target_regions += regions
else:
# Non-greedy scope; return first valid scope
# If cannot find first valid scope after cursor
number_regions = len(regions)
selected_region = None
first_region = 0
last_region = number_regions - 1
pt = self.get_sel_point()
# Find first scope
if number_regions > 0:
selected_region = regions[0]
# Walk backwards seeing which scope is valid
# Quit if you reach the already selected first scope
if selected_region is not None and last_region > first_region and pt is not None:
reverse_count = last_region
for region in reversed(regions):
if reverse_count >= first_region and region.end() - 1 >= pt:
selected_region = region
reverse_count -= 1
else:
break
# Store the scope if we found one
if selected_region is not None:
replaced += 1
self.view.show(selected_region.begin())
self.target_regions += [selected_region]
return replaced
def process_selections(self, orig_find, selection_only, selection_inputs, literal):
"""Process selections if necessary."""
sel_start = []
sel_size = []
find = orig_find
errors = False
sels = self.view.sel()
if selection_only and selection_inputs:
error("Cannot use 'selection_inputs' with global option 'selection_only'!")
errors = True
elif selection_only:
sel_start = []
sel_size = []
for s in sels:
sel_start.append(s.begin())
sel_size.append(s.size())
elif selection_inputs:
try:
sel_inputs = []
count = 0
for s in sels:
assert s.size() <= self.sel_input_max_size, "Exceeded max selection size"
engine = self.normal_module
if not literal and self.extend:
engine = self.extend_module
sel_inputs.append(self.view.substr(s))
count += 1
assert count <= self.sel_input_max_count
find = RegexInputFormatter(engine).format(orig_find, *sel_inputs, sel=sel_inputs)
except Exception:
print(str(traceback.format_exc()))
error('Failed to process selection inputs.')
errors = True
return find, sels, sel_start, sel_size, errors
def scope_apply(self, pattern):
"""Find and replace based on scope."""
# Initialize replacement variables
replaced = 0
regions = []
# Grab pattern definitions
scope = pattern['scope']
find = pattern.get('find')
replace = pattern.get('replace', r'\g<0>')
selection_inputs = pattern.get('selection_inputs', False)
greedy_scope = bool(pattern.get('greedy_scope', True))
greedy_replace = bool(pattern.get('greedy', True))
literal = pattern.get('literal', False)
literal_ignorecase = literal and bool(pattern.get('literal_ignorecase', False))
multi = bool(pattern.get('multi_pass', False))
self.format = bool(pattern.get('format_replace', False)) and self.use_format
self.plugin = pattern.get("plugin", None)
self.plugin_args = pattern.get("args", {})
if scope is None or scope == '':
return replace
find, sels, sel_start, sel_size, errors = self.process_selections(
find, self.selection_only, selection_inputs, literal
)
if errors:
return replace
regions = self.view.find_by_selector(scope)
if self.selection_only:
regions = self.filter_by_selection(regions)[0]
# Find supplied?
if find is not None:
if not literal:
try:
if self.extend:
re_find = self.extend_module.compile_search(find, self.regex_version_flag)
else:
re_find = self.normal_module.compile(find, self.regex_version_flag)
except Exception as err:
print(str(traceback.format_exc()))
error('REGEX ERROR: %s' % str(err))
return replaced
# Greedy Scope?
if greedy_scope:
replaced = self.greedy_scope_replace(regions, re_find, replace, greedy_replace, multi)
else:
replaced = self.non_greedy_scope_replace(regions, re_find, replace, greedy_replace, multi)
else:
try:
re_find = self.normal_module.compile(
self.normal_module.escape(find),
(self.normal_module.I if literal_ignorecase else 0) | self.regex_version_flag
)
except Exception as err:
print(str(traceback.format_exc()))
error('REGEX ERROR: %s' % str(err))
return replaced
if greedy_scope:
replaced = self.greedy_scope_literal_replace(regions, re_find, replace, greedy_replace)
else:
replaced = self.non_greedy_scope_literal_replace(regions, re_find, replace, greedy_replace)
else:
replaced = self.select_scope_regions(regions, greedy_scope)
if self.selection_only:
new_sels = []
count = 0
offset = 0
for s in sels:
r = sublime.Region(sel_start[count] + offset, s.end())
new_sels.append(r)
offset += r.size() - sel_size[count]
count += 1
sels.clear()
sels.add_all(new_sels)
return replaced
def search(self, pattern, scope=False):
"""Search with the given patter."""
return self.scope_apply(pattern) if scope else self.apply(pattern)