forked from aziz/SublimeFileBrowser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dired.py
664 lines (554 loc) · 23.6 KB
/
dired.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sublime
from sublime import Region
from sublime_plugin import WindowCommand, TextCommand
import os, re, shutil, tempfile, subprocess, itertools
from os.path import basename, dirname, isdir, isfile, exists, join, isabs, normpath, normcase
ST3 = int(sublime.version()) >= 3000
ECODING = 'UTF-8'
if ST3:
from .common import RE_FILE, DiredBaseCommand
from . import prompt
from .show import show
MARK_OPTIONS = sublime.DRAW_NO_OUTLINE
PARENT_SYM = "⠤"
try:
import Default.send2trash as send2trash
except ImportError:
send2trash = None
else:
import locale
from common import RE_FILE, DiredBaseCommand
import prompt
from show import show
MARK_OPTIONS = 0
PARENT_SYM = "⠤".decode(ECODING)
try:
import send2trash
except ImportError:
send2trash = None
# Each dired view stores its path in its local settings as 'dired_path'.
COMMANDS_HELP = """\
Browse Shortcuts:
+---------------------------+------------------------+
| Command | Shortcut |
|---------------------------+------------------------|
| Help page | ? |
| Toggle mark | m |
| Toggle mark and move down | shift+down |
| Toggle mark and move up | shift+up |
| Toggle all marks | t |
| Unmark all | u |
| Mark by extension | * |
| Rename | R |
| Move | M |
| Delete | D |
| Send to trash | s |
| Create directory | cd |
| Create file | cf |
| Open file/view directory | enter/o |
| Open in Finder/Explorer | \ |
| Open in new window | w |
| Go to parent directory | backspace |
| Go to directory | g |
| Go to first | super+up / ctrl+home |
| Go to last | super+down / ctrl+end |
| Move to previous | k/up |
| Move to next | j/down |
| Jump to | / |
| Refresh view | r |
| Toggle hidden files | h |
| Quicklook for Mac | space |
+---------------------------+------------------------+
In Rename Mode:
+--------------------------+-------------+
| Command | Shortcut |
|--------------------------|-------------|
| Apply changes | enter |
| Discard changes | escape |
+--------------------------+-------------+
"""
def reuse_view():
return sublime.load_settings('dired.sublime-settings').get('dired_reuse_view', False)
def sort_nicely(l):
""" Sort the given list in the way that humans expect.
Source: http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
"""
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
l.sort(key=alphanum_key)
def without_hidden(names):
"""
Returns list of names without hidden directories and files
"""
return [name for name in names if not name.startswith('.')]
class DiredCommand(WindowCommand):
"""
Prompt for a directory to display and display it.
"""
def run(self, immediate=False):
if immediate:
show(self.window, self._determine_path())
else:
prompt.start('Directory:', self.window, self._determine_path(), self._show)
def _show(self, path):
show(self.window, path)
def _determine_path(self):
# Use the current view's directory if it has one.
view = self.window.active_view()
path = view and view.file_name()
if path:
return dirname(path)
# Use the first project folder if there is one.
if ST3:
data = self.window.project_data()
if data and 'folders' in data:
folders = data['folders']
if folders:
return folders[0]['path']
# Use the user's home directory.
return os.path.expanduser('~')
class DiredRefreshCommand(TextCommand, DiredBaseCommand):
"""
Populates or repopulates a dired view.
"""
def run(self, edit, goto=None):
"""
goto
Optional filename to put the cursor on.
"""
print(self.view.settings())
status = " 𝌆 [?: Help] " if ST3 else " [?: Help] "
show_hidden = self.view.settings().get('dired_show_hidden_files', True)
status += 'Hidden: ON' if show_hidden else 'Hidden: OFF'
self.view.set_status("__FileBrowser__", status)
path = self.path
try:
names = os.listdir(path)
if not show_hidden:
names = without_hidden(names)
sort_nicely(names)
except WindowsError as e:
self.view.run_command("dired_up")
self.view.set_read_only(False)
self.view.insert(edit, self.view.line(self.view.sel()[0]).b,
'\t<%s>' % str(e).split(':')[0]
.replace('[Error 5] ', 'Access denied'))
self.view.set_read_only(True)
else:
self.continue_refreshing(edit, path, names, goto)
def continue_refreshing(self, edit, path, names, goto=None):
f = []
# generating dirs list first
for name in names:
if isdir(join(path, name)):
try:
name = "▸ ".decode(ECODING) + name + os.sep
except:
name = "▸ " + name + os.sep
f.append(name)
# generating files list
for name in names:
if not isdir(join(path, name)):
try:
name = "≡ ".decode(ECODING) + name
except:
name = "≡ " + name
f.append(name)
marked = set(self.get_marked())
text = [ path ]
try:
text.append(len(path)*('—'.decode(ECODING)))
except:
text.append(len(path)*('—'))
if not f or self.show_parent():
text.append(PARENT_SYM)
text.extend(f)
self.view.set_read_only(False)
self.view.erase(edit, Region(0, self.view.size()))
self.view.insert(edit, 0, '\n'.join(text))
self.view.set_syntax_file('Packages/FileBrowser/dired.hidden-tmLanguage')
self.view.settings().set('dired_count', len(f))
if marked:
# Even if we have the same filenames, they may have moved so we have to manually
# find them again.
regions = []
for line in self.view.lines(self.fileregion()):
filename = self._remove_ui(RE_FILE.match(self.view.substr(line)).group(1))
if filename in marked:
name_region = Region(line.a + 2, line.b) # do not mark UI elements
regions.append(name_region)
self.view.add_regions('marked', regions, 'dired.marked', '', MARK_OPTIONS)
else:
self.view.erase_regions('marked')
self.view.set_read_only(True)
# Place the cursor.
if f:
pt = self.fileregion(with_parent_link=True).a
if goto:
if isdir(join(path, goto)) and not goto.endswith(os.sep):
try:
goto = "▸ ".decode(ECODING) + goto + os.sep
except:
goto = "▸ " + goto + os.sep
else:
try:
goto = "≡ ".decode(ECODING) + goto
except:
goto = "≡ " + goto
try:
line = f.index(goto) + (3 if self.show_parent() else 2)
pt = self.view.text_point(line, 2)
except ValueError:
pass
self.view.sel().clear()
self.view.sel().add(Region(pt, pt))
self.view.show_at_center(Region(pt, pt))
else: # empty folder?
pt = self.view.text_point(2, 0)
self.view.sel().clear()
self.view.sel().add(Region(pt, pt))
class DiredNextLineCommand(TextCommand, DiredBaseCommand):
def run(self, edit, forward=None):
self.move(forward)
class DiredSelect(TextCommand, DiredBaseCommand):
def run(self, edit, new_view=False):
path = self.path
filenames = self.get_selected()
# If reuse view is turned on and the only item is a directory, refresh the existing view.
if not new_view and reuse_view():
if len(filenames) == 1 and isdir(join(path, filenames[0])):
fqn = join(path, filenames[0])
show(self.view.window(), fqn, view_id=self.view.id())
return
elif len(filenames) == 1 and filenames[0] == PARENT_SYM:
self.view.window().run_command("dired_up")
return
for filename in filenames:
fqn = join(path, filename)
if '<' not in fqn: # ignore 'item <error>'
if isdir(fqn):
show(self.view.window(), fqn, ignore_existing=new_view)
else:
self.view.window().open_file(fqn)
class DiredCreateCommand(TextCommand, DiredBaseCommand):
def run(self, edit, which=None):
assert which in ('file', 'directory'), "which: " + which
# Is there a better way to do this? Why isn't there some kind of context? I assume
# the command instance is global and really shouldn't have instance information.
callback = getattr(self, 'on_done_' + which, None)
self.view.window().show_input_panel(which.capitalize() + ':', '', callback, None, None)
def on_done_file(self, value):
self._on_done('file', value)
def on_done_directory(self, value):
self._on_done('directory', value)
def _on_done(self, which, value):
value = value.strip()
if not value:
return
fqn = join(self.path, value)
if exists(fqn):
sublime.error_message('{0} already exists'.format(fqn))
return
if which == 'directory':
os.makedirs(fqn)
else:
open(fqn, 'wb')
self.view.run_command('dired_refresh', {'goto': value})
class DiredMarkExtensionCommand(TextCommand, DiredBaseCommand):
def run(self, edit):
filergn = self.fileregion()
if filergn.empty():
return
ext = self.view.substr(self.view.line(self.view.sel()[0].a)).split('.')[-1]
pv = self.view.window().show_input_panel('Extension:', ext, self.on_done, None, None)
pv.run_command("select_all")
def on_done(self, ext):
ext = ext.strip()
if not ext:
return
if not ext.startswith('.'):
ext = '.' + ext
def _markfunc(oldmark, filename):
return filename.endswith(ext) and True or oldmark
self._mark(mark=_markfunc, regions=self.fileregion())
class DiredMarkCommand(TextCommand, DiredBaseCommand):
"""
Marks or unmarks files.
The mark can be set to '*' to mark a file, ' ' to unmark a file, or 't' to toggle the
mark.
By default only selected files are marked, but if markall is True all files are
marked/unmarked and the selection is ignored.
If there is no selection and mark is '*', the cursor is moved to the next line so
successive files can be marked by repeating the mark key binding (e.g. 'm').
"""
def run(self, edit, mark=True, markall=False, forward=True):
assert mark in (True, False, 'toggle')
filergn = self.fileregion()
if filergn.empty():
return
# If markall is set, mark/unmark all files. Otherwise only those that are selected.
if markall:
regions = [ filergn ]
else:
regions = self.view.sel()
def _toggle(oldmark, filename):
return not oldmark
if mark == 'toggle':
# Special internal case.
mark = _toggle
self._mark(mark=mark, regions=regions)
# If there is no selection, move the cursor forward so the user can keep pressing 'm'
# to mark successive files.
if not markall and len(self.view.sel()) == 1 and self.view.sel()[0].empty():
self.move(forward)
class DiredDeleteCommand(TextCommand, DiredBaseCommand):
def run(self, edit, trash=False):
files = self.get_marked() or self.get_selected()
if files:
# Yes, I know this is English. Not sure how Sublime is translating.
if len(files) == 1:
msg = "Delete {0}?".format(files[0])
else:
msg = "Delete {0} items?".format(len(files))
if trash and not send2trash:
msg = "Cannot send to trash.\nPermanently " + msg[0].lower() + msg[1:]
trash = False
if trash or sublime.ok_cancel_dialog(msg):
for filename in files:
fqn = join(self.path, filename)
if trash and send2trash:
send2trash.send2trash(fqn)
elif isdir(fqn):
shutil.rmtree(fqn)
else:
os.remove(fqn)
self.view.run_command('dired_refresh')
class DiredMoveCommand(TextCommand, DiredBaseCommand):
def run(self, edit, **kwargs):
if kwargs and kwargs["to"]:
self.move_to_extreme(kwargs["to"])
return
elif kwargs and kwargs["duplicate"]:
self.items = self._get_items(self.path)
self.cursor = self.view.substr(self.view.line(self.view.sel()[0].a))[2:]
self._duplicate(duplicate=kwargs["duplicate"])
else:
files = self.get_marked() or self.get_selected()
if files:
prompt.start('Move to:', self.view.window(), self.path, self._move)
def _get_items(self, path):
files = self.get_marked() or self.get_selected()
path = normpath(normcase(path))
for filename in files:
fqn = normpath(normcase(join(self.path, filename)))
yield fqn
def _move(self, path):
if not isabs(path):
path = join(self.path, path)
if not isdir(path):
sublime.error_message('Not a valid directory: {0}'.format(path))
return
for fqn in self._get_items(path):
if fqn != path:
shutil.move(fqn, path)
self.view.run_command('dired_refresh')
def _duplicate(self, duplicate=''):
fqn = next(self.items)
for i in itertools.count(2):
p, n = os.path.split(fqn)
cfp = "{1} {0}.{2}".format(i, join(p, n.split('.')[0]), '.'.join(n.split('.')[1:]))
if os.path.isfile(cfp) or os.path.isdir(cfp):
pass
else:
break
if duplicate == 'rename':
prompt.start('New name:', self.view.window(), os.path.basename(cfp), self._copy_duplicate, rename=(fqn, cfp, self.cursor))
else:
self._copy_duplicate(fqn, cfp, 0)
def _copy_duplicate(self, fqn, cfp, int):
if isdir(fqn):
if not isdir(cfp):
shutil.copytree(fqn, cfp)
else:
print(*("", "Skip! Folder with this name exists already:", cfp), sep='\n', end='\n\n')
else:
if not isfile(cfp):
shutil.copy2(fqn, cfp)
else:
print(*("", "Skip! File with this name exists already:", cfp), sep='\n', end='\n\n')
try:
if int == 0:
self._duplicate()
elif int == 1:
self._duplicate(duplicate='rename')
except StopIteration:
self.view.run_command('dired_refresh', {"goto": self.cursor})
class DiredRenameCommand(TextCommand, DiredBaseCommand):
def run(self, edit):
if self.filecount():
# Store the original filenames so we can compare later.
self.view.settings().set('rename', self.get_all())
self.view.settings().set('dired_rename_mode', True)
self.view.set_read_only(False)
self.set_ui_in_rename_mode(edit)
if ST3:
self.view.set_status("__FileBrowser__", " 𝌆 [enter: Apply changes] [escape: Discard changes] ")
else:
self.view.set_status("__FileBrowser__", " [enter: Apply changes] [escape: Discard changes] ")
# Mark the original filename lines so we can make sure they are in the same
# place.
r = self.fileregion()
self.view.add_regions('rename', [ r ], '', '', MARK_OPTIONS)
class DiredRenameCancelCommand(TextCommand, DiredBaseCommand):
"""
Cancel rename mode.
"""
def run(self, edit):
self.view.settings().erase('rename')
self.view.settings().set('dired_rename_mode', False)
goto_file_name = self.get_selected()[0]
if goto_file_name.endswith(os.sep):
goto_file_name = goto_file_name[0:-1]
self.view.run_command('dired_refresh', {"goto": goto_file_name})
class DiredRenameCommitCommand(TextCommand, DiredBaseCommand):
def run(self, edit):
if not self.view.settings().has('rename'):
# Shouldn't happen, but we want to cleanup when things go wrong.
self.view.run_command('dired_refresh')
return
before = self.view.settings().get('rename')
# We marked the set of files with a region. Make sure the region still has the same
# number of files.
after = []
for region in self.view.get_regions('rename'):
for line in self.view.lines(region):
after.append(self._remove_ui(self.view.substr(line).strip()))
if len(after) != len(before):
sublime.error_message('You cannot add or remove lines')
return
if len(set(after)) != len(after):
sublime.error_message('There are duplicate filenames')
return
diffs = [ (b, a) for (b, a) in zip(before, after) if b != a ]
if diffs:
existing = set(before)
while diffs:
b, a = diffs.pop(0)
if a in existing:
# There is already a file with this name. Give it a temporary name (in
# case of cycles like "x->z and z->x") and put it back on the list.
tmp = tempfile.NamedTemporaryFile(delete=False, dir=self.path).name
os.unlink(tmp)
diffs.append((tmp, a))
a = tmp
print('dired rename: {0} --> {1}'.format(b, a))
os.rename(join(self.path, b), join(self.path, a))
existing.remove(b)
existing.add(a)
self.view.erase_regions('rename')
self.view.settings().erase('rename')
self.view.settings().set('dired_rename_mode', False)
goto_file_name = self.get_selected()[0]
if goto_file_name.endswith(os.sep):
goto_file_name = goto_file_name[0:-1]
self.view.run_command('dired_refresh', {"goto": goto_file_name})
class DiredUpCommand(TextCommand, DiredBaseCommand):
def run(self, edit):
parent = dirname(self.path.rstrip(os.sep))
if parent != os.sep:
parent += os.sep
if parent == self.path:
return
view_id = (self.view.id() if reuse_view() else None)
show(self.view.window(), parent, view_id, goto=basename(self.path.rstrip(os.sep)))
class DiredGotoCommand(TextCommand, DiredBaseCommand):
"""
Prompt for a new directory.
"""
def run(self, edit):
prompt.start('Goto:', self.view.window(), self.path, self.goto)
def goto(self, path):
show(self.view.window(), path, view_id=self.view.id())
class DiredQuickLookCommand(TextCommand, DiredBaseCommand):
"""
quick look current file in mac in mac
"""
def run(self, edit):
files = self.get_marked() or self.get_selected()
if "⠤" in files:
files.remove("⠤")
cmd = ["qlmanage", "-p"]
for filename in files:
fqn = join(self.path, filename)
cmd.append(fqn)
subprocess.call(cmd)
class DiredOpenExternalCommand(TextCommand, DiredBaseCommand):
"""
open dir/file in external file explorer
"""
def run(self, edit):
self.view.window().run_command("open_dir", {"dir": self.path})
class DiredOpenInNewWindowCommand(TextCommand, DiredBaseCommand):
def run(self, edit):
items = []
files = self.get_marked() or self.get_selected()
if ST3: # sublime.executable_path() is not available in ST2
executable_path = sublime.executable_path()
if sublime.platform() == 'osx':
app_path = executable_path[:executable_path.rfind(".app/")+5]
executable_path = app_path+"Contents/SharedSupport/bin/subl"
items.append(executable_path)
items.append("-n")
for filename in files:
fqn = join(self.path, filename)
items.append(fqn)
subprocess.Popen(items, cwd=self.path)
else: # ST2
items.append("-n")
for filename in files:
fqn = join(self.path, filename)
items.append(fqn)
if sublime.platform() == 'osx':
try:
subprocess.Popen(['subl'] + items, cwd=self.path)
except:
try:
subprocess.Popen(['sublime'] + items, cwd=self.path)
except:
subprocess.Popen(['/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl'] + items, cwd=self.path)
elif sublime.platform() == 'windows':
try:
subprocess.Popen(['subl'] + items, cwd=self.path, shell=True)
except:
try:
subprocess.Popen(['sublime'] + items, cwd=self.path, shell=True)
except:
subprocess.Popen(['sublime_text.exe'] + items, cwd=self.path, shell=True)
else:
try:
subprocess.Popen(['subl'] + items, cwd=self.path)
except:
subprocess.Popen(['sublime'] + items, cwd=self.path)
class DiredHelpCommand(TextCommand):
def run(self, edit):
view = self.view.window().new_file()
view.set_name("Browse: shortcuts")
view.set_scratch(True)
view.settings().set('color_scheme','Packages/FileBrowser/dired.hidden-tmTheme')
view.settings().set('line_numbers',False)
view.run_command('dired_show_help')
sublime.active_window().focus_view(view)
class DiredShowHelpCommand(TextCommand):
def run(self, edit):
self.view.erase(edit, Region(0, self.view.size()))
self.view.insert(edit, 0, COMMANDS_HELP)
self.view.sel().clear()
self.view.set_read_only(True)
class DiredToggleHiddenFilesCommand(TextCommand):
def run(self, edit):
show = self.view.settings().get('dired_show_hidden_files', True)
self.view.settings().set('dired_show_hidden_files', not show)
self.view.run_command('dired_refresh')