-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickLineNavigator.py
More file actions
2399 lines (2197 loc) · 99 KB
/
Copy pathQuickLineNavigator.py
File metadata and controls
2399 lines (2197 loc) · 99 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
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
import sublime
import sublime_plugin
import os
import re
import json
import threading
import time
import queue
import subprocess
import unicodedata
from collections import defaultdict
SETTINGS_FILE = "Default.sublime-settings"
SUPPORTED_ENCODINGS = ['utf-8', 'gbk', 'gb2312', 'utf-16', 'latin1', 'cp1252', 'shift_jis']
DEFAULT_BLACKLIST = ['.exe', '.dll', '.so', '.dylib', '.a', '.lib', '.obj', '.o', '.bin', '.class', '.jar', '.war', '.ear', '.pyc', '.pyo', '.pyd', '.db', '.sqlite', '.sqlite3', '.dat', '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.ico', '.webp', '.svg', '.mp3', '.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.wav', '.m4a', '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz', '.iso', '.img', '.dmg', '.deb', '.rpm', '.msi', '.ttf', '.otf', '.woff', '.woff2', '.eot', '.sublime-workspace', '.sublime-project', '.git', '.svn', '.hg', '.tmp', '.cache', '.log', '.swp', '.swo', '.swn', '.bak', '~']
HIGHLIGHT_SCOPES = ['region.redish', 'region.bluish', 'region.yellowish', 'region.greenish', 'region.purplish', 'region.orangish', 'selection']
HIGHLIGHT_ICONS = ['dot', 'circle', 'cross', 'bookmark', 'dot', 'circle', 'bookmark']
KEYWORD_EMOJIS = ['🟥', '🟦', '🟨', '🟩', '🟪', '🟧', '⬜']
class KeywordStateManager:
def __init__(self):
self.active_panel = None
self.stored_keywords = ""
self.debug_enabled = True
self.is_panel_switching = False
def debug_print(self, message):
if self.debug_enabled:
print("🔍 [KeywordState] {0}".format(message))
def has_active_panel(self):
result = self.active_panel is not None
return result
def get_active_panel_text(self):
if not self.active_panel or not self.active_panel.get('input_view'):
return ""
input_view = self.active_panel['input_view']
if input_view and input_view.is_valid():
return input_view.substr(sublime.Region(0, input_view.size()))
return ""
def set_active_panel(self, panel_info):
self.active_panel = panel_info
cid = panel_info.get('command_id', 'Unknown')
scope = panel_info.get('scope', 'None')
self.debug_print("set_active_panel(): command={0}, scope={1}".format(cid, scope))
def clear_active_panel(self):
self.active_panel = None
self.debug_print("clear_active_panel()")
def handle_esc_clear(self):
self.debug_print("handle_esc_clear(): Clearing stored keywords")
self.stored_keywords = ""
self.clear_active_panel()
def reset_panel_flags(self):
self.is_panel_switching = False
def get_initial_text_for_new_panel(self, selected_text=""):
if selected_text:
formatted = TextUtils.format_keyword_for_input(selected_text)
result = self._ensure_trailing_space(formatted)
self.debug_print("Using selected text: '{0}'".format(result))
return result
if self.is_panel_switching:
result = self._ensure_trailing_space(self.stored_keywords)
self.debug_print("Switching: using stored keywords: '{0}'".format(result))
return result
self.debug_print("Fresh run: not using stored keywords")
return ""
def save_current_keywords(self, text):
if text:
self.stored_keywords = text
self.debug_print("save_current_keywords(): '{0}'".format(text))
def handle_panel_append_selection(self, selected_text, current_text):
if not selected_text:
return current_text
formatted_selected = TextUtils.format_keyword_for_input(selected_text)
current_keywords = TextUtils.parse_keywords(current_text)
if formatted_selected in current_keywords or selected_text in current_keywords:
self.debug_print("Keyword already exists, not appending")
return current_text
if current_text and not current_text.endswith(' '):
new_text = "{0} {1}".format(current_text, formatted_selected)
else:
new_text = "{0}{1}".format(current_text, formatted_selected)
return self._ensure_trailing_space(new_text)
def prepare_cross_scope_append(self, selected_text, stored_keywords):
if not selected_text:
return self._ensure_trailing_space(stored_keywords or "")
normalized_existing = {kw.strip().lower() for kw in TextUtils.parse_keywords(stored_keywords or "")}
normalized_selected = selected_text.strip().lower()
if normalized_selected in normalized_existing:
self.debug_print("Cross-scope append: Keyword already exists (case-insensitive), not appending")
return self._ensure_trailing_space(stored_keywords or "")
formatted_selected = TextUtils.format_keyword_for_input(selected_text)
if stored_keywords and not stored_keywords.endswith(' '):
new_text = "{0} {1}".format(stored_keywords, formatted_selected)
else:
new_text = "{0}{1}".format(stored_keywords or "", formatted_selected)
result = self._ensure_trailing_space(new_text)
self.debug_print("Cross-scope append -> '{0}'".format(result))
return result
def _ensure_trailing_space(self, text):
if not text or text.endswith(' '):
return text
keywords = TextUtils.parse_keywords(text)
if keywords:
return text + ' '
return text
class Settings:
def __init__(self):
self._settings = sublime.load_settings(SETTINGS_FILE)
self._cache = {}
def get(self, key, default=None):
if key not in self._cache:
self._cache[key] = self._settings.get(key, default)
return self._cache[key]
def set(self, key, value):
self._cache[key] = value
self._settings.set(key, value)
sublime.save_settings(SETTINGS_FILE)
def clear_cache(self):
self._cache.clear()
def update_user_settings(self, key, value):
user_path = os.path.join(sublime.packages_path(), "User", SETTINGS_FILE)
settings_data = {}
if os.path.exists(user_path):
try:
with open(user_path, 'r', encoding='utf-8') as f:
settings_data = json.load(f)
except:
pass
settings_data[key] = value
os.makedirs(os.path.dirname(user_path), exist_ok=True)
with open(user_path, 'w', encoding='utf-8') as f:
json.dump(settings_data, f, indent=4, ensure_ascii=False)
self.set(key, value)
class FileFilter:
def __init__(self, settings, scope, window=None):
self.settings = settings
self.scope = scope
self.window = window
self.enabled = self._get_filter_enabled()
self.whitelist = settings.get("file_extensions", [])
self.blacklist = settings.get("file_extensions_blacklist", [])
def _get_filter_enabled(self):
if self.window and hasattr(self.window, 'extension_filters_temp_override'):
return self.window.extension_filters_temp_override
scope_map = {
'file': 'extension_filters_file',
'folder': 'extension_filters_folder',
'project': 'extension_filters_project',
'open_files': 'extension_filters_open_files'
}
if self.scope in scope_map:
scope_setting = self.settings.get(scope_map[self.scope])
if scope_setting is not None:
return scope_setting
return self.settings.get("extension_filters", True)
def should_process(self, filename):
if not filename:
return False
basename = os.path.basename(filename)
_, ext = os.path.splitext(filename.lower())
if ext in {'.git', '.svn', '.hg', '.sublime-workspace', '.sublime-project'} or basename.startswith('.'):
return False
if ext in DEFAULT_BLACKLIST:
return False
if not self.enabled:
return True
if self.blacklist:
blacklist_set = {('.' + e.lstrip('.').lower() if e and e != '.' else e) for e in self.blacklist}
if ext in blacklist_set:
return False
if not self.whitelist:
return True
allow_all = False
allow_no_ext = False
whitelist_set = set()
for e in self.whitelist:
e = e.strip().lower()
if e == ".":
allow_all = True
break
elif e == "":
allow_no_ext = True
else:
whitelist_set.add('.' + e.lstrip('.'))
if allow_all:
return True
if ext == "" and allow_no_ext:
return True
return ext in whitelist_set
class FileScanEstimator:
CACHE_TTL = 15
_cache = {}
@classmethod
def _make_cache_key(cls, folders, file_filter):
try:
folders_key = tuple(sorted(folders))
except Exception:
folders_key = tuple(folders) if folders else tuple()
wl = tuple(sorted((file_filter.whitelist or [])))
bl = tuple(sorted((file_filter.blacklist or [])))
return (folders_key, bool(file_filter.enabled), wl, bl)
@classmethod
def count_filtered_files(cls, folders, settings, scope, window=None, timeout=0.8, max_files=200000, cache_ttl=None):
if not folders:
return 0, False
file_filter = FileFilter(settings, scope, window)
key = cls._make_cache_key(folders, file_filter)
now = time.time()
ttl = cls.CACHE_TTL if cache_ttl is None else cache_ttl
if ttl and key in cls._cache:
ts, value = cls._cache[key]
if (now - ts) <= ttl:
return value
start = now
count = 0
approx = False
try:
for root in folders:
if not root or not os.path.isdir(root):
continue
for dirpath, dirnames, filenames in os.walk(root):
for fname in filenames:
fpath = os.path.join(dirpath, fname)
if file_filter.should_process(fpath):
count += 1
if count >= max_files or (time.time() - start) > timeout:
approx = True
raise StopIteration
except StopIteration:
pass
except Exception:
approx = True
if ttl:
cls._cache[key] = (time.time(), (count, approx))
return count, approx
class TextUtils:
@staticmethod
def display_width(s):
if not s:
return 0
if len(s) == 1:
ch = s[0]
if ord(ch) < 128:
return 1
elif ('\U0001F300' <= ch <= '\U0001F9FF' or
'\U0001F000' <= ch <= '\U0001F0FF' or
'\U0001F100' <= ch <= '\U0001F1FF' or
'\U0001F200' <= ch <= '\U0001F2FF' or
'\U0001F600' <= ch <= '\U0001F64F' or
'\U0001F680' <= ch <= '\U0001F6FF' or
'\U0001F700' <= ch <= '\U0001F77F' or
'\U00002600' <= ch <= '\U000027BF' or
'\U0001FA00' <= ch <= '\U0001FA6F' or
'\U0001FA70' <= ch <= '\U0001FAFF'):
return 2
else:
ea_width = unicodedata.east_asian_width(ch)
return 2 if ea_width in ('F', 'W', 'A') else 1
if all(ord(c) < 128 for c in s):
return len(s)
width = 0
for ch in s:
if ('\U0001F300' <= ch <= '\U0001F9FF' or
'\U0001F000' <= ch <= '\U0001F0FF' or
'\U0001F100' <= ch <= '\U0001F1FF' or
'\U0001F200' <= ch <= '\U0001F2FF' or
'\U0001F600' <= ch <= '\U0001F64F' or
'\U0001F680' <= ch <= '\U0001F6FF' or
'\U0001F700' <= ch <= '\U0001F77F' or
'\U00002600' <= ch <= '\U000027BF' or
'\U0001FA00' <= ch <= '\U0001FA6F' or
'\U0001FA70' <= ch <= '\U0001FAFF'):
width += 2
else:
ea_width = unicodedata.east_asian_width(ch)
width += 2 if ea_width in ('F', 'W', 'A') else 1
return width
@staticmethod
def parse_keywords(input_text):
if not input_text:
return []
keywords = []
current = ""
in_backticks = False
i = 0
while i < len(input_text):
char = input_text[i]
if char == '`' and not in_backticks:
if current.strip():
keywords.append(current.strip())
current = ""
in_backticks = True
i += 1
continue
elif char == '`' and in_backticks:
in_backticks = False
if current.strip():
keywords.append(current.strip())
current = ""
i += 1
continue
elif char == ' ' and not in_backticks:
if current.strip():
keywords.append(current.strip())
current = ""
i += 1
continue
else:
current += char
i += 1
if current.strip():
keywords.append(current.strip())
final_keywords = []
for kw in keywords:
if kw and ('\r' in kw or '\n' in kw):
lines = kw.replace('\r\n', '\n').replace('\r', '\n').split('\n')
for line in lines:
line = line.strip()
if line:
final_keywords.append(line)
elif kw:
final_keywords.append(kw)
return final_keywords
@staticmethod
def format_keyword_for_input(keyword):
if '`' in keyword:
return '"{}"'.format(keyword)
elif ' ' in keyword or "'" in keyword:
return '`{}`'.format(keyword)
return keyword
class UgrepExecutor:
def __init__(self):
self.path = self._find_executable()
self.output_pattern = re.compile(r'^([^:]+):(\d+):(.*)$')
self.windows_pattern = re.compile(r'^([A-Za-z]:[^:]+):(\d+):(.*)$')
def _find_executable(self):
try:
import shutil
found = shutil.which("ugrep")
if found:
print("🔧 Found ugrep at: {}".format(found))
return found
except Exception as e:
print("🔧 Error finding ugrep: {}".format(e))
print("⚠️ ugrep not found in PATH. Install ugrep for better performance.")
print(" See: https://github.com/Genivia/ugrep#install")
return None
def search(self, paths, keywords, file_filter):
if not self.path:
return []
cmd = [self.path, "-n", "-H", "--color=never", "-r", "-I", "-i", "-F"]
if not file_filter.enabled:
critical_blacklist = ["*.sublime-workspace", "*.sublime-project", "*.git", "*.svn", "*.hg", "*.exe", "*.dll", "*.so", "*.dylib", "*.bin"]
for pattern in critical_blacklist:
cmd.extend(["--exclude", pattern])
else:
self._apply_filters(cmd, file_filter)
if not keywords:
cmd.remove("-F")
cmd.extend(["-e", r"^\s*\S"])
else:
self._add_keywords(cmd, keywords)
cmd.extend(paths if isinstance(paths, list) else [paths])
print(" 🔧 Ugrep: {0}".format(" ".join(str(arg) for arg in cmd)))
output, error = self._execute(cmd)
if error:
print(" ❌ Ugrep error: {0}".format(error))
results = self._parse_output(output)
print(" ✅ Ugrep found {0} lines".format(len(results)))
if file_filter.enabled and self._needs_post_filter(file_filter):
results = self._post_filter(results, file_filter)
print(" 🔧 Post-filtered to {0} lines".format(len(results)))
return results
def _add_keywords(self, cmd, keywords):
keywords = [kw for kw in keywords if kw]
if not keywords:
return
if len(keywords) == 1:
cmd.append(keywords[0])
else:
cmd.extend(["-e", keywords[0]])
for kw in keywords[1:]:
cmd.extend(["--and", "-e", kw])
def _apply_filters(self, cmd, file_filter):
applied_whitelist = False
if file_filter.whitelist:
allow_all = False
allow_no_ext = False
valid_exts = []
for ext in file_filter.whitelist:
ext = ext.strip().lower()
if ext == ".":
allow_all = True
break
elif ext == "":
allow_no_ext = True
else:
valid_exts.append("*{0}".format('.' + ext.lstrip('.')))
if not allow_all and valid_exts and not allow_no_ext:
for pattern in valid_exts:
cmd.extend(["--include", pattern])
applied_whitelist = True
blacklist = set()
if not applied_whitelist:
blacklist.update(["*{0}".format(ext) for ext in DEFAULT_BLACKLIST])
if file_filter.blacklist:
for ext in file_filter.blacklist:
ext = ext.strip().lower()
if ext and ext != ".":
blacklist.add("*{0}".format('.' + ext.lstrip('.')))
for pattern in blacklist:
cmd.extend(["--exclude", pattern])
def _execute(self, cmd):
try:
kwargs = {}
if sublime.platform() == "windows":
if hasattr(subprocess, 'CREATE_NO_WINDOW'):
kwargs['creationflags'] = subprocess.CREATE_NO_WINDOW
else:
kwargs['creationflags'] = 0x08000000
if hasattr(subprocess, 'run'):
result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore', timeout=30, **kwargs)
return result.stdout, result.stderr
else:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, **kwargs)
stdout, stderr = process.communicate(timeout=30)
if isinstance(stdout, bytes):
stdout = stdout.decode('utf-8', errors='ignore')
if isinstance(stderr, bytes):
stderr = stderr.decode('utf-8', errors='ignore')
return stdout, stderr
except subprocess.TimeoutExpired:
if 'process' in locals():
process.kill()
process.communicate()
return "", "Timeout after 30 seconds"
except OSError as e:
if e.errno == 2:
return "", "ugrep not found"
elif e.errno == 13:
return "", "Permission denied"
else:
return "", "System error: {0}".format(str(e))
except Exception as e:
return "", "Error: {0}".format(str(e))
def _parse_output(self, output):
results = []
for line in output.splitlines():
line = line.strip()
if not line:
continue
match = self.windows_pattern.match(line) or self.output_pattern.match(line)
if match:
results.append({
'file': match.group(1),
'line_number': int(match.group(2)),
'line': match.group(3),
'display': match.group(3).strip(),
'point': int(match.group(2))
})
return results
def _needs_post_filter(self, file_filter):
if file_filter.whitelist:
has_empty = any(ext.strip() == "" for ext in file_filter.whitelist)
has_others = any(ext.strip() != "" and ext.strip() != "." for ext in file_filter.whitelist)
return has_empty and has_others
return False
def _post_filter(self, results, file_filter):
filtered = []
for item in results:
filename = item.get('file', '')
_, ext = os.path.splitext(filename)
if ext == "" or file_filter.should_process(filename):
filtered.append(item)
return filtered
class ShowSearchEngineStatusCommand(sublime_plugin.WindowCommand):
def run(self):
ugrep_executor = UgrepExecutor()
status_lines = ["QuickLineNavigator Search Engine Status:"]
status_lines.append("-" * 40)
if ugrep_executor.path:
status_lines.append("✅ ugrep: Available at {}".format(ugrep_executor.path))
try:
result = subprocess.run([ugrep_executor.path, "--version"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
version_line = result.stdout.split('\n')[0] if result.stdout else "Unknown version"
status_lines.append(" Version: {}".format(version_line))
except:
pass
status_lines.append(" Performance: Optimized for large projects")
else:
status_lines.append("⚠️ ugrep: Not available")
status_lines.append(" Using: Python fallback search")
status_lines.append(" Performance: Good for small to medium projects")
status_lines.append("")
status_lines.append("To install ugrep:")
status_lines.append("• Windows: choco install ugrep")
status_lines.append("• macOS: brew install ugrep")
status_lines.append("• Linux: apt install ugrep")
output_view = self.window.create_output_panel("search_engine_status")
output_view.run_command("append", {"characters": "\n".join(status_lines)})
self.window.run_command("show_panel", {"panel": "output.search_engine_status"})
class SearchEngine:
def __init__(self, settings, scope, window=None):
self.settings = settings
self.scope = scope
self.window = window
self.file_filter = FileFilter(settings, scope, window)
self.ugrep = UgrepExecutor()
if not self.ugrep.path and not getattr(SearchEngine, '_ugrep_warning_shown', False):
self._show_ugrep_installation_info()
SearchEngine._ugrep_warning_shown = True
def _line_matches(self, display_text, keywords):
if not keywords:
return True
return all(re.search(re.escape(kw), display_text, re.IGNORECASE) for kw in keywords)
def _show_ugrep_installation_info(self):
def show_dialog():
message = (
"QuickLineNavigator can use 'ugrep' for faster searching.\n\n"
"To install ugrep:\n"
"• Windows: Download from https://github.com/Genivia/ugrep/releases\n"
"• macOS: brew install ugrep\n"
"• Linux: apt install ugrep (or equivalent)\n\n"
"The plugin will work with built-in Python search if ugrep is not available."
)
if sublime.ok_cancel_dialog(message, "Open Installation Guide"):
import webbrowser
webbrowser.open("https://github.com/Genivia/ugrep#install")
sublime.set_timeout(show_dialog, 1000)
def search(self, paths, keywords, original_keywords=""):
if not paths:
return []
start_time = time.time()
if self.ugrep.path:
results = self.ugrep.search(paths, keywords, self.file_filter)
else:
results = self._python_search(paths, keywords)
duration = time.time() - start_time
self._print_stats(len(results), paths, keywords, original_keywords, duration)
return results
def _python_search(self, paths, keywords):
if self.scope == "file":
return self._search_file(paths[0], keywords)
elif self.scope == "open_files":
return self._search_open_files(paths, keywords)
else:
return self._search_folders(paths, keywords)
def _search_file(self, file_path, keywords):
if not self.window:
return []
view = None
for v in self.window.views():
if v.file_name() == file_path:
view = v
break
if not view:
return []
results = []
for region in view.lines(sublime.Region(0, view.size())):
line_text = view.substr(region)
display_text = line_text.strip()
if not display_text:
continue
if not self._line_matches(display_text, keywords):
continue
line_num = view.rowcol(region.begin())[0] + 1
results.append({
'file': file_path,
'line_number': line_num,
'line': line_text,
'display': display_text,
'point': region.begin()
})
return results
def _search_open_files(self, file_paths, keywords):
if not self.window:
return []
results = []
for file_path in file_paths:
results.extend(self._search_file(file_path, keywords))
return results
def _search_folders(self, folders, keywords):
all_files = []
for folder in folders:
try:
for root, dirs, files in os.walk(folder):
for fname in files:
fpath = os.path.join(root, fname)
if os.path.isfile(fpath) and self.file_filter.should_process(fpath):
all_files.append(fpath)
except:
continue
results = []
for file_path in all_files:
try:
if os.path.getsize(file_path) > 10 * 1024 * 1024:
continue
lines = []
with open(file_path, 'rb') as f:
raw_content = f.read(10 * 1024 * 1024)
for encoding in SUPPORTED_ENCODINGS:
try:
text = raw_content.decode(encoding)
lines = text.splitlines()
break
except:
continue
for line_num, line in enumerate(lines[:10000], 1):
display_text = line.strip()
if not display_text:
continue
if not self._line_matches(display_text, keywords):
continue
results.append({
'file': file_path,
'line_number': line_num,
'line': line,
'display': display_text,
'point': line_num
})
except:
continue
return results
def _print_stats(self, results_count, paths, keywords, original, duration, files_with_results=None):
scope_name = UIText.get_scope_display_name(self.scope)
print("🎯 {0} Search Complete".format(scope_name))
if keywords:
keyword_display = []
for i, kw in enumerate(keywords):
emoji = KEYWORD_EMOJIS[i % len(KEYWORD_EMOJIS)]
keyword_display.append("{0}{1}".format(emoji, kw))
print(" 📍 Keywords: {0}".format(" ".join(keyword_display)))
else:
print(" 📍 Keywords: {0}".format(original or "All lines"))
if self.scope in ["folder", "project"]:
print(" 📁 Folders: {0}".format(len(paths)))
try:
filtered_count, approx = FileScanEstimator.count_filtered_files(
paths, self.settings, self.scope, self.window, timeout=0.8, max_files=200000
)
filtered_str = "~{}".format(filtered_count) if approx else str(filtered_count)
matched_str = str(files_with_results if files_with_results is not None else 0)
print(" 📊 Files: {0} of {1} filtered".format(matched_str, filtered_str))
except Exception:
if files_with_results is not None:
print(" 📊 Files: {0}".format(files_with_results))
else:
print(" 📊 Files: N/A")
elif self.scope == "file":
print(" 📄 File: {0}".format(os.path.basename(paths[0]) if paths else "Unknown"))
elif self.scope == "open_files":
total_open = len(paths)
if files_with_results is not None and files_with_results != total_open:
print(" 📊 Files: {0} of {1} open".format(files_with_results, total_open))
else:
print(" 📊 Files: {0}".format(total_open))
print(" 📝 Results: {0} lines".format(results_count))
print(" ⏱️ Time: {0:.3f}s".format(duration))
class Highlighter:
def __init__(self):
self.key_base = "QuickLineNavKeyword"
self.keys_by_view = defaultdict(set)
self.cache = {}
def highlight(self, view, keywords):
if not view or not view.is_valid():
return
keywords = [kw for kw in keywords if kw and kw.strip()]
if not keywords:
self.clear(view)
return
view_id = view.id()
cache_key = tuple(keywords)
if self.cache.get(view_id) == cache_key:
return
if view.is_loading() or view.size() == 0:
sublime.set_timeout(lambda: self.highlight(view, keywords), 100)
return
self.clear(view)
for i, keyword in enumerate(keywords):
if not keyword:
continue
try:
regions = view.find_all(keyword, sublime.IGNORECASE | sublime.LITERAL)
if regions:
key = "{key}_{index}".format(key=self.key_base, index=i)
scope = HIGHLIGHT_SCOPES[i % len(HIGHLIGHT_SCOPES)]
icon = HIGHLIGHT_ICONS[i % len(HIGHLIGHT_ICONS)]
view.add_regions(
key, regions, scope, icon, sublime.DRAW_NO_OUTLINE
)
self.keys_by_view[view_id].add(key)
except Exception as e:
print("Error highlighting keyword '{}': {}".format(keyword, e))
continue
if self.keys_by_view.get(view_id):
self.cache[view_id] = cache_key
def clear(self, view):
if not view or not view.is_valid():
return
view_id = view.id()
for key in list(self.keys_by_view.get(view_id, [])):
try:
view.erase_regions(key)
except:
pass
self.keys_by_view.pop(view_id, None)
self.cache.pop(view_id, None)
def clear_all(self):
for window in sublime.windows():
for v in window.views():
self.clear(v)
self.cache.clear()
def sweep_view(self, view, max_keys=128):
if not view or not view.is_valid():
return
for i in range(max_keys):
try:
view.erase_regions("{key}_{index}".format(key=self.key_base, index=i))
except:
pass
class DisplayFormatter:
BREAK_CHARS = {
' ', ',', '.', ';', ':', '!', '?', '-', '_', '/', '\\', '|',
'(', ')', '[', ']', '{', '}', '<', '>', '"', "'", '`', '~',
'@', '#', '$', '%', '^', '&', '*', '+', '=',
',', '。', ';', ':', '!', '?', '、', '—', '…',
'(', ')', '【', '】', '{', '}', '《', '》', '「', '」', '『', '』',
'·', '~', '-', '_', '/', '\', '|',
'+', '=', '*', '&', '%', '$', '#', '@',
' '
}
def __init__(self, settings):
self.settings = settings
self.show_line_numbers = settings.get("show_line_numbers", True)
self.max_length = settings.get("max_display_length", 120)
self._width_cache = {}
self._emoji_cache = {}
self._format_cache = {}
self._segment_cache = {}
self._keyword_patterns = {}
self.total_to_format = 0
self.current_formatted = 0
self._char_width_cache = {}
self._last_keywords_key = None
def _char_width(self, ch):
cw = self._char_width_cache.get(ch)
if cw is not None:
return cw
w = TextUtils.display_width(ch)
if len(self._char_width_cache) < 10000:
self._char_width_cache[ch] = w
return w
def _prepare_line_metrics(self, text, keyword_info):
width_ps = [0] * (len(text) + 1)
for i, ch in enumerate(text):
width_ps[i+1] = width_ps[i] + self._char_width(ch)
lower = text.lower()
match_pos_map = {}
total_matches = 0
for kw, kw_lower in zip(keyword_info['keywords'], keyword_info['lower_keywords']):
pos_list = []
start = 0
step = max(1, len(kw_lower))
while True:
idx = lower.find(kw_lower, start)
if idx == -1:
break
pos_list.append(idx)
start = idx + step
match_pos_map[kw_lower] = pos_list
total_matches += len(pos_list)
return {
'width_ps': width_ps,
'lower': lower,
'match_pos_map': match_pos_map,
'total_matches': total_matches
}
def _span_width(self, width_ps, start, end):
return width_ps[end] - width_ps[start]
def _count_overhead(self, match_pos_map, lower_keywords, start, end, kw_lens):
import bisect
extra = 0
for kw_lower, kw_len in zip(lower_keywords, kw_lens):
pos_list = match_pos_map.get(kw_lower, [])
if not pos_list:
continue
right_bound = max(start, end - kw_len)
lo = bisect.bisect_left(pos_list, start)
hi = bisect.bisect_right(pos_list, right_bound)
extra += (hi - lo) * 2
return extra
def format_results(self, results, keywords, scope):
if not results:
return [], []
if len(self._format_cache) > 5000:
self.clear_caches()
kw_key = tuple(keywords) if keywords else ()
if kw_key != self._last_keywords_key:
self._prepare_keyword_patterns(keywords)
self._last_keywords_key = kw_key
keyword_info = self._prepare_keyword_info_cached(keywords)
formatted = []
expanded_results = []
display_index = 0
for i, item in enumerate(results):
cache_key = (
item.get('file', ''),
item.get('line_number', -1),
hash(item['line'][:50]) if len(item['line']) > 50 else item['line']
)
if cache_key in self._format_cache:
cached = self._format_cache[cache_key]
updated_formatted = []
updated_expanded = []
for j, (fmt_item, exp_item) in enumerate(zip(cached['formatted'], cached['expanded'])):
current_display_index = display_index + j
updated_sub_line = self._format_sub_line_simple(
exp_item, current_display_index, keyword_info, scope,
exp_item.get('segment_index', 0),
exp_item.get('total_segments', 1)
)
updated_formatted.append([fmt_item[0], updated_sub_line])
updated_expanded.append(exp_item)
display_index += len(cached['formatted'])
formatted.extend(updated_formatted)
expanded_results.extend(updated_expanded)
continue
fmt_items, exp_items = self._format_single_fast(item, display_index, keyword_info, scope)
display_index += len(fmt_items)
if len(self._format_cache) < 5000:
original_formatted = [[fi[0], fi[1]] for fi in fmt_items]
self._format_cache[cache_key] = {
'formatted': original_formatted,
'expanded': exp_items
}
formatted.extend(fmt_items)
expanded_results.extend(exp_items)
return formatted, expanded_results
def _format_single_fast(self, item, start_display_index, keyword_info, scope):
line = item['line']
line_stripped = line.strip()
strip_offset = len(line) - len(line.lstrip())
if not line_stripped:
return [], []
metrics = self._prepare_line_metrics(line_stripped, keyword_info)
kw_lens = [len(kw) for kw in keyword_info['lower_keywords']]
base_width = self._span_width(metrics['width_ps'], 0, len(line_stripped))
est_extra = self._count_overhead(metrics['match_pos_map'], keyword_info['lower_keywords'], 0, len(line_stripped), kw_lens)
est_total = base_width + est_extra
formatted_items = []
expanded_items = []
if est_total <= self.max_length:
line_with_emojis = self._apply_emoji_highlights_fast(line_stripped, keyword_info)
sub_line = self._format_sub_line_simple(item, start_display_index, keyword_info, scope)
formatted_items.append([line_with_emojis, sub_line])
expanded_item = {
'file': item.get('file'),
'line_number': item.get('line_number'),
'line': item.get('line'),
'display': item.get('display'),
'point': item.get('point'),
'strip_offset': strip_offset,
'is_single_segment': True
}
expanded_items.append(expanded_item)
return formatted_items, expanded_items
segments = []
start = 0
text_len = len(line_stripped)
while start < text_len:
left = start + 1
right = text_len
best_end = start + 1
while left <= right:
mid = (left + right) // 2
seg_width = self._span_width(metrics['width_ps'], start, mid)
seg_extra = self._count_overhead(metrics['match_pos_map'], keyword_info['lower_keywords'], start, mid, kw_lens)
total_w = seg_width + seg_extra
if total_w <= self.max_length:
best_end = mid
left = mid + 1
else:
right = mid - 1
if best_end >= text_len:
segments.append((start, text_len))
break
actual_end = self._find_best_break_forward(line_stripped, start, best_end, keyword_info)
if actual_end > best_end:
seg_width = self._span_width(metrics['width_ps'], start, actual_end)
seg_extra = self._count_overhead(metrics['match_pos_map'], keyword_info['lower_keywords'], start, actual_end, kw_lens)
if seg_width + seg_extra > self.max_length:
actual_end = self._find_best_break_backward(line_stripped, start, best_end)
if actual_end <= start:
actual_end = min(start + 1, text_len)
segments.append((start, actual_end))
start = actual_end
for seg_index, (seg_start, seg_end) in enumerate(segments):
seg_text = line_stripped[seg_start:seg_end]
seg_with_emojis = self._apply_emoji_highlights_fast(seg_text, keyword_info)
current_display_index = start_display_index + seg_index
sub_line = self._format_sub_line_simple(
item, current_display_index, keyword_info, scope, seg_index, len(segments)
)
formatted_items.append([seg_with_emojis, sub_line])
expanded_item = {
'file': item.get('file'),
'line_number': item.get('line_number'),
'line': item.get('line'),
'display': item.get('display'),
'point': item.get('point'),
'segment_start': seg_start,
'segment_end': seg_end,
'segment_index': seg_index,
'total_segments': len(segments),
'strip_offset': strip_offset,