-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
fuzzy_file_nav.py
executable file
·812 lines (704 loc) · 31.1 KB
/
fuzzy_file_nav.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
"""
Fuzzy File Navigation
Copyright (c) 2012 Isaac Muse <isaacmuse@gmail.com>
"""
import sublime
import sublime_plugin
import os
import os.path as path
import re
import shutil
from multiconf import get as qualify_settings
PLATFORM = sublime.platform()
FUZZY_SETTINGS = "fuzzy_file_nav.sublime-settings"
if PLATFORM == "windows":
import ctypes
PLATFORM = sublime.platform()
CMD_WIN = r"^(?:(?:(~)|(\.\.))(?:\\|/)|((?:[A-Za-z]{1}:)?(?:\\|/))|([\w\W]*(?:\\|/)))$"
CMD_NIX = r"^(?:(?:(~)|(\.\.))/|(/)|([\w\W]*/))$"
WIN_DRIVE = r"(^[A-Za-z]{1}:(?:\\|/))"
def debug_log(s):
if sublime.load_settings(FUZZY_SETTINGS).get("debug", False):
print "FuzzyFileNav: %s" % s
def status_cwd():
if FuzzyFileNavCommand.status:
sublime.run_command("fuzzy_get_cwd")
sublime.set_timeout(status_cwd, 1000)
def get_root_path():
# Windows doesn't have a root, so just
# return an empty string to represent its root.
return u"" if PLATFORM == "windows" else u"/"
def expanduser(path, default):
return os.path.expanduser(path) if path != None else path
def back_dir(cwd):
prev = path.dirname(cwd)
# On windows, if you try and get the
# dirname of a drive, you get the drive.
# So if the previous directory is the same
# as the current, back out of the drive and
# list all drives.
return get_root_path() if prev == cwd else prev
def get_drives():
# Search through valid drive names and see if they exist.
return [unicode(d + ":") for d in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" if path.exists(d + ":")]
def back_to_root(cwd):
root = ""
if PLATFORM != "windows":
# Linux/Unix: just return root
root = "/"
else:
# Windows: try and find root drive from path
# otherwise return "" to signal fuzzy nav to
# list all drives.
m = re.match(WIN_DRIVE, cwd)
if m:
root = m.group(1)
return unicode(root)
class FuzzyPanelText(object):
content = ""
@classmethod
def set_content(cls, txt):
cls.content = txt
@classmethod
def get_content(cls):
txt = cls.content
return txt
@classmethod
def clear_content(cls):
cls.content = ""
class FuzzyEventListener(sublime_plugin.EventListener):
def on_activated(self, view):
# New window gained activation? Reset fuzzy command state
if FuzzyFileNavCommand.active and view.window() and view.window().id() != FuzzyFileNavCommand.win_id:
FuzzyFileNavCommand.reset()
# View has not been assinged yet for since fuzzy nav panel appeared; assign it
if FuzzyFileNavCommand.active and (FuzzyFileNavCommand.view == None or FuzzyFileNavCommand.view.id() != view.id()):
FuzzyFileNavCommand.view = view
def on_query_context(self, view, key, operator, operand, match_all):
active = FuzzyFileNavCommand.active == True
if active and FuzzyFileNavCommand.view != None and FuzzyFileNavCommand.view.id() == view.id():
FuzzyPanelText.set_content(view.substr(view.line(view.sel()[0])))
full_name = path.join(FuzzyFileNavCommand.cwd, FuzzyPanelText.get_content())
empty = (FuzzyPanelText.get_content() == "")
# See if this is the auto-complete path command
if key in ["fuzzy_path_complete", "fuzzy_path_complete_back", "fuzzy_toggle_hidden", "fuzzy_bookmarks_load", "fuzzy_get_cwd", "fuzzy_cwv"]:
return active
elif key in ["fuzzy_reveal", "fuzzy_search"]:
if path.exists(FuzzyFileNavCommand.cwd):
return active
else:
sublime.status_message("%s does not exist!" % FuzzyFileNavCommand.cwd)
elif key == "fuzzy_delete":
if not empty and path.exists(full_name):
return active
elif not empty:
sublime.status_message("%s does not exist!" % full_name)
elif key in ["fuzzy_make_file", "fuzzy_make_folder"]:
if not empty and not path.exists(full_name):
return active
elif not empty:
sublime.status_message("%s already exists!" % full_name)
elif key == "fuzzy_save_as":
if not empty and (not path.exists(full_name) or not path.isdir(full_name)):
return active
elif not empty:
sublime.status_message("%s is a directory!" % full_name)
elif key == "fuzzy_copy":
if not empty and path.exists(full_name):
return active
elif not empty:
sublime.status_message("%s does not exist!" % full_name)
elif key == "fuzzy_cut":
if path.exists(FuzzyFileNavCommand.cwd):
return active
else:
sublime.status_message("%s does not exist!" % FuzzyFileNavCommand.cwd)
elif key == "fuzzy_paste":
if path.exists(FuzzyFileNavCommand.cwd) and len(FuzzyClipboardCommand.clips):
return active
else:
sublime.status_message("%s does not exist!" % FuzzyFileNavCommand.cwd)
return False
def on_modified(self, view):
if FuzzyFileNavCommand.active and FuzzyFileNavCommand.view != None and FuzzyFileNavCommand.view.id() == view.id():
sel = view.sel()[0]
win = view.window()
line_text = view.substr(view.line(sel))
FuzzyPathCompleteCommand.update_autocomplete(line_text)
regex = CMD_WIN if PLATFORM == "windows" else CMD_NIX
m = re.match(regex, line_text)
if m:
if m.group(1):
# Go Home
FuzzyFileNavCommand.fuzzy_reload = True
home = qualify_settings(sublime.load_settings(FUZZY_SETTINGS), "home", u"", expanduser)
home = get_root_path() if not path.exists(home) or not path.isdir(home) else home
win.run_command("fuzzy_file_nav", {"start": home})
elif m.group(2):
# Back a directory
FuzzyFileNavCommand.fuzzy_reload = True
win.run_command("fuzzy_file_nav", {"start": back_dir(FuzzyFileNavCommand.cwd)})
elif m.group(3):
# Go to root of drive/computer
if PLATFORM == "windows" and re.match(WIN_DRIVE, line_text):
if path.exists(line_text):
new_path = line_text.upper()
else:
new_path = back_to_root(FuzzyFileNavCommand.cwd)
FuzzyFileNavCommand.fuzzy_reload = True
win.run_command("fuzzy_file_nav", {"start": new_path})
elif m.group(4):
# Load folder
new_path = path.join(FuzzyFileNavCommand.cwd, m.group(4))
if path.exists(new_path) and path.isdir(new_path):
FuzzyFileNavCommand.fuzzy_reload = True
win.run_command("fuzzy_file_nav", {"start": new_path})
class FuzzyCurrentWorkingViewCommand(sublime_plugin.TextCommand):
def run(self, edit):
name = None
win = sublime.active_window()
if win is not None:
cwv = win.active_view()
if cwv is not None:
file_name = cwv.file_name()
if file_name is not None:
name = path.basename(file_name)
if name is not None:
view = FuzzyFileNavCommand.view
edit = view.begin_edit()
view.replace(edit, sublime.Region(0, view.size()), name)
view.end_edit(edit)
sels = view.sel()
sels.clear()
sels.add(sublime.Region(view.size()))
class FuzzyRevealCommand(sublime_plugin.WindowCommand):
def run(self):
file_name = FuzzyPanelText.get_content()
FuzzyPanelText.clear_content()
if path.exists(path.join(FuzzyFileNavCommand.cwd, file_name)):
self.window.run_command("open_dir", {"dir": FuzzyFileNavCommand.cwd, "file": file_name})
else:
self.window.run_command("open_dir", {"dir": FuzzyFileNavCommand.cwd, "file": ""})
class FuzzySearchFolderCommand(sublime_plugin.WindowCommand):
def run(self):
file_name = FuzzyPanelText.get_content()
FuzzyPanelText.clear_content()
folder = path.join(FuzzyFileNavCommand.cwd, file_name)
if path.exists(folder) and path.isdir(folder):
self.window.run_command("show_panel", {"panel": "find_in_files", "where": folder})
else:
self.window.run_command("show_panel", {"panel": "find_in_files", "where": FuzzyFileNavCommand.cwd})
class FuzzyClipboardCommand(sublime_plugin.WindowCommand):
clips = []
action = None
def run(self, action):
self.cls = FuzzyClipboardCommand
if action in ["cut", "copy"]:
if len(self.cls.clips):
self.cls.clear_entries()
full_name = path.join(FuzzyFileNavCommand.cwd, FuzzyPanelText.get_content())
FuzzyPanelText.clear_content()
self.cls.add_entry(full_name)
self.cls.set_action(action)
FuzzyFileNavCommand.fuzzy_reload = True
self.window.run_command("fuzzy_file_nav", {"start": FuzzyFileNavCommand.cwd})
elif action == "paste":
self.paste()
def paste(self):
error = False
self.to_path = path.join(FuzzyFileNavCommand.cwd, FuzzyPanelText.get_content())
FuzzyPanelText.clear_content()
move = (self.cls.action == "cut")
self.from_path = self.cls.clips[0]
self.cls.clear_entries()
multi_file = (
bool(sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_after_action", False)) and
"paste" not in sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_exceptions", [])
)
if not multi_file:
self.window.run_command("hide_overlay")
FuzzyFileNavCommand.reset()
else:
FuzzyFileNavCommand.fuzzy_reload = True
if path.exists(self.from_path):
if path.isdir(self.from_path):
self.action = shutil.copytree if not bool(move) else shutil.move
error = self.dir_copy()
else:
self.action = shutil.copyfile if not bool(move) else shutil.move
error = self.file_copy()
if multi_file:
if error:
FuzzyFileNavCommand.reset()
else:
self.window.run_command("fuzzy_file_nav", {"start": FuzzyFileNavCommand.cwd})
def dir_copy(self):
error = False
try:
if path.exists(self.to_path):
if path.isdir(self.to_path):
self.action(self.from_path, path.join(self.to_path, path.basename(self.from_path)))
else:
error = True
sublime.error_message("%s already exists!" % self.to_path)
elif path.exists(path.dirname(self.to_path)):
self.action(self.from_path, self.to_path)
else:
error = True
sublime.error_message("Cannot copy %s" % self.from_path)
except:
error = True
sublime.error_message("Cannot copy %s" % self.from_path)
return error
def file_copy(self):
error = False
try:
if path.exists(self.to_path):
if path.isdir(self.to_path):
file_name = path.join(self.to_path, path.basename(self.from_path))
if path.exists(file_name):
if not sublime.ok_cancel_dialog("%s exists!\n\nOverwrite file?" % file_name):
return
self.action(self.from_path, file_name)
elif sublime.ok_cancel_dialog("%s exists!\n\nOverwrite file?" % self.to_path):
self.action(self.from_path, self.to_path)
elif path.exists(path.dirname(self.to_path)):
self.action(self.from_path, self.to_path)
else:
error = True
sublime.error_message("Cannot copy %s" % self.from_path)
except:
error = True
sublime.error_message("Cannot copy %s" % self.from_path)
return error
@classmethod
def add_entry(cls, entry):
if not entry in cls.clips:
cls.clips.append(entry)
@classmethod
def set_action(cls, action):
cls.action = action
@classmethod
def clear_entries(cls):
cls.clips = []
cls.action = None
class FuzzyDeleteCommand(sublime_plugin.WindowCommand):
def run(self):
error = False
full_name = path.join(FuzzyFileNavCommand.cwd, FuzzyPanelText.get_content())
FuzzyPanelText.clear_content()
multi_file = (
bool(sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_after_action", False)) and
"delete" not in sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_exceptions", [])
)
if not multi_file:
self.window.run_command("hide_overlay")
FuzzyFileNavCommand.reset()
else:
FuzzyFileNavCommand.fuzzy_reload = True
if sublime.ok_cancel_dialog("Delete %s?\n\nWarning: this is permanent!" % full_name):
try:
if path.isdir(full_name):
shutil.rmtree(full_name)
else:
os.remove(full_name)
except:
error = True
sublime.error_message("Error deleting %d!" % full_name)
if multi_file:
if error:
FuzzyFileNavCommand.reset()
else:
self.window.run_command("fuzzy_file_nav", {"start": FuzzyFileNavCommand.cwd})
class FuzzySaveFileCommand(sublime_plugin.WindowCommand):
def save(self):
if self.view.is_loading():
sublime.set_timeout(self.save, 100)
else:
edit = self.view.begin_edit()
self.view.replace(
edit,
sublime.Region(0, self.view.size()),
self.bfr
)
self.view.end_edit(edit)
sels = self.view.sel()
sels.clear()
map(lambda x: self.view.sel().add(x), self.current_sels)
self.window.focus_view(self.view)
self.view.set_viewport_position(self.position)
self.view.run_command("save")
if self.multi_file:
self.window.run_command("fuzzy_file_nav", {"start": FuzzyFileNavCommand.cwd})
def run(self):
full_name = path.join(FuzzyFileNavCommand.cwd, FuzzyPanelText.get_content())
file_exists = path.exists(full_name)
if file_exists:
if not sublime.ok_cancel_dialog("%s exists!\n\nOverwrite file?" % full_name):
return
FuzzyPanelText.clear_content()
self.multi_file = (
bool(sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_after_action", False)) and
"saveas" not in sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_exceptions", [])
)
active_view = self.window.active_view()
if active_view is None:
return
self.bfr = active_view.substr(sublime.Region(0, active_view.size()))
self.current_sels = [sublime.Region(s.begin(), s.end()) for s in active_view.sel()]
self.position = active_view.viewport_position()
if not self.multi_file:
self.window.run_command("hide_overlay")
FuzzyFileNavCommand.reset()
else:
FuzzyFileNavCommand.fuzzy_reload = True
try:
if not file_exists:
with open(full_name, "a"):
pass
active_view.set_scratch(True)
self.window.run_command("close")
self.view = self.window.open_file(full_name)
sublime.set_timeout(self.save, 100)
except:
sublime.error_message("Could not create %s!" % full_name)
if self.multi_file:
FuzzyFileNavCommand.reset()
class FuzzyMakeFileCommand(sublime_plugin.WindowCommand):
def run(self):
error = False
full_name = path.join(FuzzyFileNavCommand.cwd, FuzzyPanelText.get_content())
FuzzyPanelText.clear_content()
multi_file = (
bool(sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_after_action", False)) and
"mkfile" not in sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_exceptions", [])
)
if not multi_file:
self.window.run_command("hide_overlay")
FuzzyFileNavCommand.reset()
else:
FuzzyFileNavCommand.fuzzy_reload = True
try:
with open(full_name, "a"):
pass
self.window.open_file(full_name)
except:
error = True
sublime.error_message("Could not create %s!" % full_name)
if multi_file:
if error:
FuzzyFileNavCommand.reset()
else:
self.window.run_command("fuzzy_file_nav", {"start": FuzzyFileNavCommand.cwd})
class FuzzyMakeFolderCommand(sublime_plugin.WindowCommand):
def run(self):
error = False
full_name = path.join(FuzzyFileNavCommand.cwd, FuzzyPanelText.get_content())
FuzzyPanelText.clear_content()
multi_file = (
bool(sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_after_action", False)) and
"mkdir" not in sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_exceptions", [])
)
if not multi_file:
self.window.run_command("hide_overlay")
FuzzyFileNavCommand.reset()
else:
FuzzyFileNavCommand.fuzzy_reload = True
try:
os.makedirs(full_name)
except:
error = True
sublime.error_message("Could not create %d!" % full_name)
if multi_file:
if error:
FuzzyFileNavCommand.reset()
else:
self.window.run_command("fuzzy_file_nav", {"start": FuzzyFileNavCommand.cwd})
class FuzzyBookmarksLoadCommand(sublime_plugin.WindowCommand):
def run(self):
if FuzzyFileNavCommand.active:
self.window.run_command("hide_overlay")
self.display = []
# Search through bookmarks
bookmarks = sublime.load_settings(FUZZY_SETTINGS).get("bookmarks", [])
for bm in bookmarks:
# Only show bookmarks that are for this host and/or platform
target = qualify_settings(bm, "path", None, expanduser)
# Make sure bookmards point to valid locations
if target != None and ((path.exists(target) and path.isdir(target)) or (PLATFORM == "windows" and target == u"")):
self.display.append([bm.get("name", target), target])
if len(self.display) > 0:
# Display bookmarks if valid ones were found
self.window.run_command("hide_overlay")
FuzzyFileNavCommand.reset()
self.window.show_quick_panel(self.display, self.check_selection)
def check_selection(self, value):
if value > -1:
# Load fuzzy nav with bookmarked shortcut
self.window.run_command("fuzzy_file_nav", {"start": self.display[value][1]})
class FuzzyGetCwdCommand(sublime_plugin.ApplicationCommand):
def run(self):
if FuzzyFileNavCommand.active:
sublime.status_message("CWD: " + FuzzyFileNavCommand.cwd)
class FuzzyToggleHiddenCommand(sublime_plugin.WindowCommand):
def run(self, show=None):
if FuzzyFileNavCommand.active:
FuzzyFileNavCommand.fuzzy_reload = True
if show == None:
FuzzyFileNavCommand.hide_hidden = not FuzzyFileNavCommand.hide_hidden
elif bool(show):
FuzzyFileNavCommand.hide_hidden = True
else:
FuzzyFileNavCommand.hide_hidden = False
self.window.run_command("fuzzy_file_nav", {"start": FuzzyFileNavCommand.cwd})
class FuzzyStartFromFileCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]):
if FuzzyFileNavCommand.active:
self.window.run_command("hide_overlay")
name = self.get_target(paths)
actions = set(["home", "bookmarks", "root"])
# Check if you can retrieve a file name (means it exists on disk).
if name is None:
view = self.window.active_view()
name = view.file_name() if view != None else None
if name:
# Buffer/view has a file name, so it exists on disk; naviagte its parent directory.
self.window.run_command(
"fuzzy_file_nav",
{
"start": path.dirname(name) if not path.isdir(name) else name
}
)
else:
action = sublime.load_settings(FUZZY_SETTINGS).get("start_from_here_default_action", "bookmarks")
if action in actions:
# Load special action
getattr(self, action)()
else:
# Invalid action; just load bookmarks
self.window.run_command("fuzzy_bookmarks_load")
def get_target(self, paths=[]):
target = None
if len(paths) and path.exists(paths[0]):
target = paths[0]
return target
def home(self):
home = qualify_settings(sublime.load_settings(FUZZY_SETTINGS), "home", u"", expanduser)
home = get_root_path() if not path.exists(home) or not path.isdir(home) else home
self.window.run_command("fuzzy_file_nav", {"start": home})
def root(self):
self.window.run_command("fuzzy_file_nav")
def bookmarks(self):
self.window.run_command("fuzzy_bookmarks_load")
class FuzzyPathCompleteCommand(sublime_plugin.WindowCommand):
last = None
in_progress = False
text = None
def run(self, back=False):
def nix_common_chars(current_complete, l, case_insensitive):
common = current_complete
while True:
match = True
cmn_len = len(current_complete)
if len(l[0]) > cmn_len:
common += l[0][cmn_len].lower() if case_insensitive else l[0][cmn_len]
cmn_len += 1
else:
break
for item in l:
value = item.lower() if case_insensitive else item
if not value.startswith(common):
match = False
break
if not match:
break
else:
current_complete = common
selection = l[0][0:len(current_complete)]
del l[:]
l.append(selection)
cls = FuzzyPathCompleteCommand
view = FuzzyFileNavCommand.view
complete = []
settings = sublime.load_settings(FUZZY_SETTINGS)
nix_path_complete = bool(settings.get("nix_style_path_complete", False))
case_insensitive = PLATFORM == "windows" or not nix_path_complete
if view != None:
sel = view.sel()[0]
if cls.text == None:
cls.text = view.substr(view.line(sel))
debug_log("completion text - " + cls.text)
current = cls.text.lower() if case_insensitive else cls.text
for item in FuzzyFileNavCommand.files:
# Windows is case insensitive
i = item.lower() if case_insensitive else item
# See if current input matches the beginning of some of the entries
if i.startswith(current):
if path.isdir(path.join(FuzzyFileNavCommand.cwd, item)):
item = item[0:len(item) - 1]
complete.append(item)
complete_len = len(complete)
if nix_path_complete and complete_len:
nix_common_chars(current, complete, case_insensitive)
complete_len = len(complete)
# If only one entry matches, auto-complete it
if (nix_path_complete and complete_len == 1) or (not nix_path_complete and complete_len):
if nix_path_complete:
cls.last = 0
else:
last = cls.last
if back:
cls.last = complete_len - 1 if last == None or last < 1 else last - 1
else:
cls.last = 0 if last == None or last >= complete_len - 1 else last + 1
cls.in_progress = True
edit = view.begin_edit()
view.replace(edit, sublime.Region(0, view.size()), complete[cls.last])
view.end_edit(edit)
sels = view.sel()
sels.clear()
sels.add(sublime.Region(view.size()))
else:
cls.last = None
cls.text = None
@classmethod
def update_autocomplete(cls, text):
if text != cls.text and cls.last != None:
if not cls.in_progress:
cls.text = None
cls.last = None
else:
cls.in_progress = False
@classmethod
def reset_autocomplete(cls):
cls.last = None
cls.in_progress = False
cls.text = None
class FuzzyFileNavCommand(sublime_plugin.WindowCommand):
active = False
win_id = None
view = None
fuzzy_reload = False
hide_hidden = False
cwd = ""
status = False
@classmethod
def reset(cls):
cls.active = False
cls.win_id = None
cls.view = None
cls.status = False
cls.hide_hidden = not bool(sublime.load_settings(FUZZY_SETTINGS).get("show_system_hidden_files", False))
# FuzzyClipboardCommand.clear_entries()
@classmethod
def set_hidden(cls, value):
cls.hide_hidden = value
def run(self, start=None):
if FuzzyFileNavCommand.active:
self.window.run_command("hide_overlay")
self.cls = FuzzyFileNavCommand
previous = self.cls.cwd
self.cls.active = True
self.cls.win_id = self.window.id()
self.regex_exclude = sublime.load_settings(FUZZY_SETTINGS).get("regex_exclude", [])
FuzzyPathCompleteCommand.reset_autocomplete()
debug_log("start - %s" % start if start is not None else "None")
# Check if a start destination has been given
# and ensure it is valid.
directory = get_root_path() if start == None or not path.exists(start) or not path.isdir(start) else unicode(start)
self.cls.cwd = directory if PLATFORM == "windows" and directory == u"" else path.normpath(directory)
debug_log("cwd - %s" % self.cls.cwd)
# Get and display options.
try:
self.display_files(self.cls.cwd)
except:
if self.cls.fuzzy_reload:
# Reloading, so fuzzy panel must be up, so preserve previous state
self.cls.fuzzy_reload = False
self.cls.cwd = previous
else:
# Not reloading, so go ahead and reset the state
self.cls.reset()
sublime.status_message("%s is not accessible!" % self.cls.cwd)
def get_files(self, cwd):
# Get files/drives (windows).
files = get_drives() if PLATFORM == "windows" and cwd == u"" else os.listdir(cwd)
folders = []
documents = []
for f in files:
valid = True
full_path = path.join(cwd, f)
# Check exclusion to omit files.
if self.hide_hidden:
if valid:
if not PLATFORM == "windows":
if f.startswith('.') and f != "..":
valid = False
else:
attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(full_path))
if attrs != -1 and bool(attrs & 2):
valid = False
if valid:
for regex in self.regex_exclude:
if re.match(regex, f):
valid = False
# Store file/folder info.
if valid:
if not path.isdir(full_path):
documents.append(f)
else:
folders.append(f + ("\\" if PLATFORM == "windows" else "/"))
return [u".."] + sorted(folders) + sorted(documents)
def display_files(self, cwd):
# Get the folders children
self.cls.status = True
status_cwd()
self.cls.files = self.get_files(cwd)
# Make sure panel is down before loading a new one.
self.window.run_command("hide_overlay")
self.cls.view = None
self.window.show_quick_panel(self.cls.files, self.check_selection)
def check_selection(self, selection):
if selection > -1:
self.cls.fuzzy_reload = False
# The first selection is the "go up a directory" option.
directory = back_dir(self.cls.cwd) if selection == 0 else path.join(self.cls.cwd, self.cls.files[selection])
self.cls.cwd = directory if PLATFORM == "windows" and directory == u"" else path.normpath(directory)
# Check if the option is a folder or if we are at the root (needed for windows)
try:
if (path.isdir(self.cls.cwd) or self.cls.cwd == get_root_path()):
# List directories content
self.display_files(self.cls.cwd)
else:
# Open file
new_view = self.window.open_file(self.cls.cwd)
if new_view is not None:
self.window.focus_view(new_view)
# If multi-file open is set, leave panel open after opening file
if (
bool(sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_after_action", False)) and
"open" not in sublime.load_settings(FUZZY_SETTINGS).get("keep_panel_open_exceptions", [])
):
self.cls.cwd = path.normpath(back_dir(self.cls.cwd))
self.display_files(self.cls.cwd)
else:
self.cls.reset()
except:
# Inaccessible folder try backing up
sublime.status_message("%s is not accessible!" % self.cls.cwd)
self.cls.cwd = back_dir(self.cls.cwd)
self.window.run_command("hide_overlay")
self.display_files(self.cls.cwd)
elif not self.cls.fuzzy_reload:
# Reset if not reloading
self.cls.reset()
else:
# Reset reload flag if reloading
self.cls.fuzzy_reload = False
def init_hidden():
setting = sublime.load_settings(FUZZY_SETTINGS)
show_hidden = not bool(setting.get("show_system_hidden_files", False))
FuzzyFileNavCommand.set_hidden(show_hidden)
setting.clear_on_change('reload')
setting.add_on_change('reload', init_hidden)
init_hidden()