This repository has been archived by the owner on Sep 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
netranger.py
2141 lines (1816 loc) · 76.4 KB
/
netranger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import, print_function
import datetime
import fnmatch
import os
import re
from collections import defaultdict
from sys import platform
from netranger import Vim, default, preview
from netranger.api import NETRApi
from netranger.colortbl import colorhexstr2ind, colorind2hexstr, colorname2ind
from netranger.config import elipsis_note, file_sz_display_wid
from netranger.enum import Enum
from netranger.fs import FSTarget, LocalFS, Rclone
from netranger.rifle import Rifle
from netranger.shell import Shell
from netranger.ui import AskUI, HelpUI, NewUI, SortUI
if platform == "win32":
from os import getenv
else:
import pwd
import grp
class Node(object):
"""General node.
Inherited by header nodes or entry nodes.
"""
State = Enum('NodeState', 'NORMAL, PICKED, UNDEROP')
ToggleOpRes = Enum('NodeToggleOpRes', 'INVALID, ON, OFF')
def __init__(self, fullpath, name, highlight, level=0):
self.fullpath = fullpath
self.name = name
self.set_highlight(highlight)
self.level = level
self.state = Node.State.NORMAL
self.is_cursor_on = False
def set_highlight(self, highlight):
self.vim_hi_group = 'NETR' + highlight
self.highlight = default.color[highlight]
@property
def highlight_content(self):
return Vim.ColorMsg(self.name, self.highlight, self.is_cursor_on)
@property
def is_DIR(self):
return False
@property
def is_INFO(self):
return False
def cursor_on(self):
self.is_cursor_on = True
def cursor_off(self):
self.is_cursor_on = False
def toggle_pick(self):
return Node.ToggleOpRes.INVALID
def re_stat(self):
pass
class FooterNode(Node):
def __init__(self):
super(FooterNode, self).__init__("", "", 'footer')
@property
def is_INFO(self):
return True
class HeaderNode(Node):
def __init__(self, fullpath):
super(HeaderNode, self).__init__(fullpath,
Shell.abbrevuser(fullpath),
'cwd',
level=0)
self.re_stat()
def re_stat(self):
self.stat = os.stat(self.fullpath)
@property
def highlight_content(self):
return Vim.ColorMsg(self.name, self.highlight, False)
@property
def is_INFO(self):
return True
class EntryNode(Node):
"""Content node."""
def abbrev_name(self, width):
""" Return abbreviation of self.name such that it fits into `width`
(terminal) columns.
"""
if self.linkto is not None:
name = self.name + ' -> ' + self.linkto
else:
name = self.name
sz = Vim.strwidth(name)
if width >= sz:
# Conceptually, we should add (width - sz) spaces to meet the
# desired width. (sz-len(name)) compensates for extra columns
# occupied by wide-characters.
return name.ljust(width - (sz - len(name)))
else:
ext_beg = name.rfind('.')
if ext_beg > 0:
name, ext = name[:ext_beg], elipsis_note + name[ext_beg:]
sz = Vim.strwidth(name)
else:
ext = elipsis_note
if sz == len(name):
abbrev_name = name[:width - len(ext)]
else:
abbrev_name = self._bisect_trunc(name, width - len(ext))
return f'{abbrev_name}{ext}'
def _bisect_trunc(self, s, w):
"""
Using bisection to find the longest substring that is of width less or
equal to w.
"""
from itertools import accumulate
length = list(accumulate([Vim.strwidth(c) for c in s]))
if w < length[0]:
return elipsis_note * w
left = 0
right = len(s) - 1
while left < right:
middle = left + (right - left) // 2 + 1
if length[middle] == w:
# Partial s is of lenth w, return such substring
return s[:middle + 1]
elif length[middle] > w:
right = middle - 1
else:
left = middle
# No substring of s is of exactly width w, pad left spaces with elipsis_note
return s[:left + 1] + elipsis_note * (w - length[left])
@property
def highlight_content(self):
width = self.buf.winwidth
level_pad = ' ' * self.level
size_info = self.size.rjust(file_sz_display_wid + 1)
left = level_pad
right = size_info
def c(msg):
return Vim.ColorMsg(msg, self.highlight, self.is_cursor_on)
if NETRApi.HasHooker('node_highlight_content_l',
'node_highlight_content_r'):
left_extra = ''
left_extra_len = 0
for hooker in NETRApi.Hookers['node_highlight_content_l']:
l_s, l_h = hooker(self)
left_extra_len += Vim.strwidth(l_s)
left_extra += Vim.ColorMsg(l_s, l_h, False)
right_extra = ''
right_extra_len = 0
for hooker in NETRApi.Hookers['node_highlight_content_r']:
r_s, r_h = hooker(self)
right_extra_len += Vim.strwidth(r_s)
right_extra += Vim.ColorMsg(r_s, r_h, False)
# Calling c and concatenation multiple times is rather expensive.
# Hence we avoid it if possible.
if left_extra_len or right_extra_len:
return c(left) + left_extra + c(
self.abbrev_name(width - len(left) - len(right) -
left_extra_len -
right_extra_len)) + c(right) + right_extra
return c(
f'{left}{self.abbrev_name(width - len(left) - len(right))}{right}')
@property
def mtime(self):
if self.stat:
return str(datetime.datetime.fromtimestamp(
self.stat.st_mtime))[:19]
else:
return ''
def __init__(self, fullpath, name, level=0, buf=None):
self.fullpath = fullpath
self.buf = buf
self.re_stat(lazy=Vim.Var('NETRLazyLoadStat'))
highlight = self.decide_hi()
super(EntryNode, self).__init__(fullpath, name, highlight, level=level)
self.ori_highlight = highlight
def re_stat(self, lazy=False):
self.linkto = None
if os.path.islink(self.fullpath):
try:
self.linkto = os.readlink(self.fullpath)
except (OSError, FileNotFoundError, PermissionError):
pass
if not lazy:
try:
self.stat = os.stat(self.fullpath)
except (OSError, FileNotFoundError, PermissionError):
self.stat = None
else:
self.stat = None
if self.stat:
try:
self.size = LocalFS.size_str(self.fullpath, self.stat)
except (OSError, FileNotFoundError, PermissionError):
self.size = '?'
self.acl = LocalFS.acl_str(self.stat)
try:
if platform == "win32":
self.user = getenv("USERNAME")
self.group = getenv("USERDOMAIN")
else:
self.user = pwd.getpwuid(self.stat.st_uid)[0]
self.group = grp.getgrgid(self.stat.st_gid)[0]
except KeyError:
self.user = self.stat.st_uid
self.group = self.stat.st_gid
else:
self.size = ''
self.acl = ''
self.user = ''
self.group = ''
def decide_hi(self):
if self.linkto is not None:
if os.path.exists(self.fullpath):
return 'link'
else:
return 'brokenlink'
elif self.is_DIR:
return 'dir'
elif os.access(self.fullpath, os.X_OK):
return 'exe'
else:
return 'file'
def rename(self, name):
ori = self.fullpath
dirname = os.path.dirname(self.fullpath)
self.fullpath = os.path.join(dirname, name)
self.name = name
return ori
def change_dirname(self, oridirname, dirname):
self.fullpath = os.path.join(dirname,
self.fullpath[len(oridirname) + 1:])
def toggle_pick(self):
if self.state == Node.State.NORMAL:
self.state = Node.State.PICKED
self.set_highlight('pick')
return Node.ToggleOpRes.ON
elif self.state == Node.State.PICKED:
self.state = Node.State.NORMAL
self.set_highlight(self.ori_highlight)
return Node.ToggleOpRes.OFF
else:
return Node.ToggleOpRes.INVALID
def cut(self):
if self.state == Node.State.UNDEROP:
return
self.state = Node.State.UNDEROP
self.set_highlight('cut')
def copy(self):
if self.state == Node.State.UNDEROP:
return
self.state = Node.State.UNDEROP
self.set_highlight('copy')
def reset_highlight(self):
self.state = Node.State.NORMAL
self.set_highlight(self.ori_highlight)
class DirNode(EntryNode):
"""Content node for directory."""
def __init__(self, *args, **kwargs):
self.expanded = False
super(DirNode, self).__init__(*args, **kwargs)
@property
def is_DIR(self):
return True
class NetRangerBuf(object):
"""Main (mvc) model/view.
Each netranger buffer corresponds to a directory and keeps a list of
file/directory nodes and display them in a vim buffer.
"""
@property
def highlight_content(self):
return [n.highlight_content for n in self.nodes]
@property
def plain_content(self):
return [n.name for n in self.nodes]
@property
def cur_node(self):
return self.nodes[self.clineno]
@property
def non_info_nodes(self):
return self.nodes[1:-1]
@property
def is_remote(self):
return self.fs.is_remote
def ensure_remote_downloaded(self):
self.fs.ensure_remote_downloaded(self.cur_node.fullpath)
def nodes_plus_header_footer(self, nodes):
return [self._header_node] + nodes + [self._footer_node]
def __init__(self, controler, wd, fs):
self._controler = controler
self.wd = wd
self.last_vim_pwd = self.wd
self.fs = fs
self._num_fs_op = 0
self._pending_on_cursormoved_post = 0
self._last_on_curosormoved_lineno = -1
self.content_outdated = False
self._highlight_outdated = False
self._sort_outdated = False
if Vim.Var('NETRAutochdir'):
Vim.command('lcd ' + wd)
self._header_node = HeaderNode(wd)
self._footer_node = FooterNode()
self.nodes = self.nodes_plus_header_footer(self.create_nodes(self.wd))
self.clineno = 1
self.nodes[self.clineno].cursor_on()
# For lazy redraw in update_nodes_and_redraw, we detect the mtime
# change of the working directory and all expanded subdirectories.
self._expanded_nodes = set([self._header_node])
self._pseudo_header_lineno = None
self._pseudo_footer_lineno = None
self.winwidth = Vim.CurWinWidth()
self.is_editing = False
self._vim_buf_handle = Vim.current.buffer
self._redraw()
def fs_busy(self, echo=True):
"""
Return True if num_fs_op>0. See Netranger.inc_num_fs_op.
"""
if self._num_fs_op > 0:
if echo:
Vim.ErrorMsg(
'Previous operation that might change the view is not done'
' yet. Try again later')
return True
else:
return False
def inc_num_fs_op(self):
""" Increase num_fs_op by 1. See Netranger.inc_num_fs_op. """
self._num_fs_op += 1
def dec_num_fs_op(self):
""" Decrease num_fs_op by 1. See Netranger.inc_num_fs_op. """
self._num_fs_op -= 1
def abbrev_cwd(self, width):
""" Return the shortend name for header that fits the width. """
res = self.wd.replace(Shell.userhome, '~')
if len(res) <= width:
return res.ljust(width)
sp = res.split('/')
szm1 = len(sp) - 1
total = 2 * (szm1) + len(sp[-1])
for i in range(szm1 - 1, -1, -1):
if total + len(sp[i]) - 1 > width:
for j in range(i + 1):
# [:1] ensures that we get at most the first character of
# sp[j] if it's not empty.
sp[j] = sp[j][:1]
return '/'.join(sp).ljust(width)
else:
total += len(sp[i]) - 1
def redraw_header_content(self):
self._header_node.name = self.abbrev_cwd(self.winwidth).strip()
self._vim_buf_handle[0] = self._header_node.highlight_content
def redraw_footer_content(self):
""" Set the buffer's last line to the footer node's content. """
meta = ''
cur_node = self.cur_node
if not cur_node.is_INFO:
cur_node.re_stat()
meta = f' {cur_node.acl} {cur_node.user} {cur_node.group} {cur_node.mtime}'
self._footer_node.name = meta.strip()
self._vim_buf_handle[-1] = self._footer_node.highlight_content
def redraw_pedueo_header_footer(self):
# Recover content for the last line occupied by pseudo header/footer
# ignore error when buffer no longer has the first/last line
if self._pseudo_header_lineno is not None:
try:
self._vim_buf_handle[self._pseudo_header_lineno] = self.nodes[
self._pseudo_header_lineno].highlight_content
except IndexError:
pass
if self._pseudo_footer_lineno is not None:
try:
self._vim_buf_handle[self._pseudo_footer_lineno] = self.nodes[
self._pseudo_footer_lineno].highlight_content
except IndexError:
pass
# if current line is at the header/footer we need to keep the current
# line to be the 2nd/penultimate visible line
first_visible_line = int(Vim.eval('line("w0")')) - 1
if first_visible_line > 0 and first_visible_line == self.clineno:
Vim.command("normal! ")
first_visible_line -= 1
last_visible_line = int(Vim.eval('line("w$")')) - 1
if last_visible_line < len(self._vim_buf_handle
) - 1 and last_visible_line == self.clineno:
Vim.command("normal! ")
last_visible_line += 1
first_visible_line += 1
# Set the pseudo header/footer
if first_visible_line > 0:
self._pseudo_header_lineno = first_visible_line
self._vim_buf_handle[
first_visible_line] = self._header_node.highlight_content
else:
self._pseudo_header_lineno = None
if last_visible_line < len(self._vim_buf_handle) - 1:
self._pseudo_footer_lineno = last_visible_line
self._vim_buf_handle[
last_visible_line] = self._footer_node.highlight_content
else:
self._pseudo_footer_lineno = None
def create_nodes(self, wd, level=0):
nodes = self._create_nodes_with_file_names(self.fs.ls(wd), wd, level)
return self.sort_nodes(nodes)
def _create_nodes_with_file_names(self, files, dirpath, level):
""" Return the nodes for given filenames. """
files = [f for f in files if not self._controler.should_ignore(f)]
return [self.create_node(dirpath, f, level) for f in files]
def create_node(self, dirname, basename, level):
""" Return the node for the given filename. """
fullpath = os.path.join(dirname, basename)
if os.path.isdir(fullpath):
return DirNode(fullpath, basename, level=level, buf=self)
else:
return EntryNode(fullpath, basename, level=level, buf=self)
def _create_nodes_if_not_exist(self, nodes, dirpath, level,
cheap_remote_ls):
""" Return missing nodes in dirpath that is not in input nodes. """
old_paths = set([node.fullpath for node in nodes])
new_paths = set([
os.path.join(dirpath, name)
for name in self.fs.ls(dirpath, cheap_remote_ls)
])
file_names = [
os.path.basename(path) for path in new_paths.difference(old_paths)
]
return self._create_nodes_with_file_names(file_names, dirpath, level)
def _sync_nodes_from_fs(self, wd, nodes, level, cheap_remote_ls):
res = self._create_nodes_if_not_exist(self.nodes, wd, level,
cheap_remote_ls)
fs_files = set(self.fs.ls(wd, cheap_remote_ls))
ind = 0
sz = len(nodes)
while ind < sz:
cur_node = nodes[ind]
# The children of an invalid node will all be invalid
# Hence, we will start with the next valid node
if self._controler.should_ignore(
cur_node.name) or cur_node.name not in fs_files:
ind = self.next_lesseq_level_ind(ind, nodes=nodes)
continue
res.append(cur_node)
# Recursively update expanded subnodes
if cur_node.is_DIR and cur_node.expanded:
next_ind = self.find_next_ind(
nodes, ind + 1, lambda beg, new: new.level < beg.level)
res += self._sync_nodes_from_fs(cur_node.fullpath,
nodes[ind + 1:next_ind],
level + 1, cheap_remote_ls)
ind = next_ind
continue
ind += 1
return res
def update_nodes_and_redraw(self,
force_redraw=False,
cheap_remote_ls=False):
""" Update the nodes to reflect the filesystem change.
1. Check the mtime of wd or any expanded subdir changed. If so, set
content_outdated true, which could also be set manually (e.g.
NETRToggleShowHidden).
2. For each file/directory in the file system, including those in
expanded directories, if no current node corresponds to it, add
a new node to the node list so that it will be visible next time.
3. For each current node, including nodes in expanded directories, if
condition: no files/directories corresponds to it or it should be
ignore, remove it from the node list so that it will be invisible
next time.
"""
for node in self._expanded_nodes:
if os.access(node.fullpath, os.R_OK):
ori_mtime = node.stat.st_mtime if node.stat else -1
node.re_stat()
new_mtime = node.stat.st_mtime
if new_mtime > ori_mtime:
self.content_outdated = True
if not self.content_outdated and not force_redraw:
return
self.content_outdated = False
new_nodes = self._sync_nodes_from_fs(self.wd, self.non_info_nodes, 0,
cheap_remote_ls)
ori_node = self.cur_node
ori_clineno = self.clineno
self.nodes = self.nodes_plus_header_footer(self.sort_nodes(new_nodes))
self._redraw()
self.set_clineno_by_node(ori_node, ori_clineno)
def reverse_sorted_nodes(self, nodes):
""" Reverse the sorted nodes with regard to their levels. """
rev = []
prev_level = -1
cur_ind = 0
for node in nodes:
if node.level <= prev_level:
for i, n in enumerate(rev):
if n.level == node.level:
rev.insert(i, node)
cur_ind = i + 1
break
else:
rev.insert(cur_ind, node)
cur_ind += 1
prev_level = node.level
return rev
def _sort_prep(self):
""" Mark the buffer as sort outdated so that it will be sorted when
entered again. """
self._sort_outdated = True
self._last_node_id = self.nodes[self.clineno]
def sort(self):
""" Sort the nodes. """
if not self._sort_outdated:
return
self._sort_outdated = False
for node in self.nodes:
node.re_stat()
self.nodes = self.nodes_plus_header_footer(
self.sort_nodes(self.non_info_nodes))
self._redraw()
self.set_clineno_by_node(self._last_node_id)
def sort_nodes(self, nodes):
"""Sort the nodes by their path and SortUI.sort_fn.
Information of ancestor are accumulated for subnodes as prefix.
To sort directories before files, ' '(ascii 32) is put into the
prefix for directories and '~' (ascii 127) is put into the
prefix for files. An additional ' ' is put before ' ' or '~' to
handle tricky case like 'dir, dir/z, dir2', without which will
results in 'dir, dir2, dir/z'.
"""
sort_fn = SortUI.get_sort_fn()
reverse = SortUI.reverse
sorted_nodes = []
prefix = ''
prefix_end_ind = [0]
for i in range(len(nodes)):
cur_node = nodes[i]
prev_node = nodes[i - 1]
if cur_node.level > prev_node.level:
# cur_node must be a DirNode, hence the same as in the folloing
# "cur_node.is_DIR" case
prefix += f' {sort_fn(prev_node)}{prev_node.name}'
prefix_end_ind.append(len(prefix))
else:
prefix_end_ind = prefix_end_ind[:cur_node.level + 1]
prefix = prefix[:prefix_end_ind[-1]]
if cur_node.is_DIR:
sorted_nodes.append(
(f'{prefix} {sort_fn(cur_node)}{cur_node.name}',
cur_node))
else:
sorted_nodes.append(
(f'{prefix} ~{sort_fn(cur_node)}{cur_node.name}',
cur_node))
sorted_nodes = sorted(sorted_nodes, key=lambda x: x[0])
sorted_nodes = [node[1] for node in sorted_nodes]
if reverse:
sorted_nodes = self.reverse_sorted_nodes(sorted_nodes)
return sorted_nodes
def _redraw(self, plain=False):
""" Redraw the buffer.
Note that we delegate the job for rendering the forground highlight of
the cursor line to on_cursormoved by calling _move_vim_cursor.
"""
for hooker in NETRApi.Hookers['render_begin']:
hooker(self)
with self.SetBufferApiGuard():
if plain:
self._vim_buf_handle[:] = self.plain_content
else:
self._vim_buf_handle[:] = self.highlight_content
if self._vim_buf_handle.number is self._vim_buf_handle.number:
self._move_vim_cursor(self.clineno)
for hooker in NETRApi.Hookers['render_end']:
hooker(self)
def _move_vim_cursor(self, lineno):
""" Will trigger on_cursormoved through CursorMoved autocmd. """
Vim.command(f'call cursor({lineno + 1},1)')
def on_cursormoved(self):
""" Handle for CursorMoved autocmd.
1. Make the node in the previous cursor line background highlight.
2. Make the node in the current cursor line foreground highlight.
3. Set cline_no to the current cursor line.
4. Enforce throttling by avoiding calling on_cursormoved_post
frequently. See on_cursormoved_post for details.
"""
new_lineno = int(Vim.eval("line('.')")) - 1
# Do not stay on footer
if new_lineno == len(self.nodes) - 1:
Vim.command('normal! k')
new_lineno -= 1
if new_lineno == self.clineno:
self.nodes[new_lineno].cursor_on()
self.redraw_lines([new_lineno])
else:
oc = self.clineno
self.clineno = new_lineno
if oc < len(self.nodes):
self.nodes[oc].cursor_off()
self.nodes[new_lineno].cursor_on()
self.redraw_lines([oc, new_lineno])
self._pending_on_cursormoved_post += 1
def on_cursormoved_post(self):
""" Run heavy-duty tasks for CursorMoved autocmd. Each
on_cursormoved_post is delayed by some time, if during this time, more
CursorMoved event happens, only the last event will be served. """
self._pending_on_cursormoved_post -= 1
if self._pending_on_cursormoved_post > 0:
return
# The line self.vim_set_line... below triggers on_cursormoved event,
# which in term triggers on_cursormoved_post. This test is to avoid
# such call loop.
if self.clineno == self._last_on_curosormoved_lineno:
return
self._last_on_curosormoved_lineno = self.clineno
# Avoid rerender if the current vim buffer is not the same as
# self._vim_buf_handle.
if self._vim_buf_handle.number != Vim.current.buffer.number\
or self.is_editing:
return
if self._controler._is_previewing:
self.preview_on()
with self.SetBufferApiGuard():
self.redraw_header_content()
self.redraw_footer_content()
self.redraw_pedueo_header_footer()
self._vim_buf_handle[self.clineno] = self.nodes[
self.clineno].highlight_content
def set_clineno_by_lineno(self, lineno):
""" Set cursor line by number. """
self._move_vim_cursor(lineno)
def set_clineno_by_path(self, path):
""" Set cursor line by full path. """
for ind, node in enumerate(self.nodes):
if node.fullpath == path:
self._move_vim_cursor(ind)
break
def set_clineno_by_node(self, node, ori_clineno=0):
""" Set cursor line by node reference. """
if node in self.nodes:
index = self.nodes.index(node)
self._move_vim_cursor(index)
self.clineno = index
else:
ori_clineno = min(ori_clineno, len(Vim.current.buffer) - 1)
self._move_vim_cursor(ori_clineno)
self.clineno = ori_clineno
def SetBufferApiGuard(self):
""" Context for setting buffer content.
1. Set/restore modifiable
2. vim.buffer[...] = ... api might moves cursor of all windows
displaying the buffer. We prevent this by save/restore all the
window cursor position.
"""
class G(object):
def __enter__(g):
self._vim_buf_handle.options['modifiable'] = True
g.win_cursor = []
for w in Vim.windows:
if w.buffer == self._vim_buf_handle:
g.win_cursor.append((w, w.cursor))
return g
def __exit__(g, type, value, traceback):
for w, c in g.win_cursor:
w.cursor = (min(c[0], len(self._vim_buf_handle) - 1), c[1])
self._vim_buf_handle.options['modifiable'] = False
return G()
def redraw_lines(self, linenos):
""" Redraw the highlight of nodes by line numbers. """
sz = min(len(self.nodes), len(self._vim_buf_handle))
with self.SetBufferApiGuard():
for i in linenos:
if i < sz:
self._vim_buf_handle[i] = self.nodes[i].highlight_content
def redraw_if_winwidth_changed(self, force=False):
""" Redraw the buffer highlight if the window widhth changed. """
if self.is_editing and not force:
return
winwidth = Vim.CurWinWidth()
if self.winwidth != winwidth:
# print('hi', self.wd, 'real: ', winwidth, 'saved: ', self.winwidth)
self.winwidth = winwidth
with self.SetBufferApiGuard():
self.redraw_header_content()
for i, node in enumerate(self.nodes):
self._vim_buf_handle[i] = node.highlight_content
self.redraw_pedueo_header_footer()
def reset_highlight(self, nodes):
""" Reset the highlight of the nodes and add them to
highlight_outdated_nodes to redraw when the buffer is entered again.
"""
for node in nodes:
node.reset_highlight()
self._highlight_outdated = True
def redraw_if_highlight_outdated(self):
""" Redraw the highlight of nodes in highlight_outdated_nodes.
"""
if self._highlight_outdated:
with self.SetBufferApiGuard():
self._vim_buf_handle[:] = self.highlight_content
self._highlight_outdated = False
def redraw_cur_line(self):
""" Redraw the highlight of the current node. """
self.redraw_lines([self.clineno])
def VimCD(self):
""" Perform :cd. """
target_dir = self.cur_node.fullpath
if not os.path.isdir(target_dir):
target_dir = os.path.dirname(target_dir)
Vim.command(f'silent lcd {target_dir}')
self.last_vim_pwd = target_dir
def _record_previewee(self, bufnr, winid):
Vim.current.window.vars['netranger_last_previewee'] = [
self.cur_node.is_DIR, bufnr, winid
]
def _close_last_previewee(self):
info = Vim.WindowVar('netranger_last_previewee', [])
if len(info) == 0:
return
is_DIR, bufnr, winid = info
win_nr = int(Vim.eval(f'win_id2win({winid})'))
if win_nr == 0:
return
if is_DIR:
Vim.command(f'{win_nr}hide')
else:
if Vim.eval(f'getbufvar({bufnr}, "&buftype")') == 'terminal':
Vim.command(f'bwipeout! {bufnr}')
elif Vim.eval(f'getbufvar({bufnr}, "&modified")') == '1':
Vim.command(f'{win_nr}hide')
elif len(Vim.eval(f'win_findbuf({bufnr})')) > 1:
Vim.command(f'{win_nr}hide')
else:
Vim.command(f'bwipeout! {bufnr}')
def preview_on(self):
""" Turn preview panel on. """
if Vim.WindowVar('netranger_is_previewee', False):
return
if Vim.eval('get(g:, "NETRCustomNopreview",{->0})()') != '0':
return
previewer_win = Vim.current.window
Vim.current.window.vars['netranger_is_previewer'] = True
self._close_last_previewee()
cur_node = self.cur_node
total_width = Vim.CurWinWidth()
preview_width = int(total_width * Vim.Var('NETRPreviewSize') / 2)
preview_close_on_tableave = False
if cur_node.is_INFO:
self.redraw_if_winwidth_changed()
return
elif cur_node.is_DIR:
with self._controler.DisableOnWinEnter():
if not os.access(cur_node.fullpath, os.X_OK):
Vim.ErrorMsg(f'Permission Denied: {cur_node.name}')
return
Vim.command(
f'rightbelow vert {preview_width} vsplit {cur_node.fullpath}'
)
self._controler.cur_buf.redraw_if_winwidth_changed(force=True)
else:
with self._controler.DisableOnWinEnter():
Vim.command(f'rightbelow vert {preview_width} new')
preview_close_on_tableave = self._controler.preview(
cur_node.fullpath, total_width, preview_width)
with self._controler.DisableOnWinEnter():
Vim.current.window.vars['netranger_is_previewee'] = True
previewee_bufnr = Vim.eval('bufnr()')
previewee_winid = Vim.eval('win_getid()')
Vim.current.window = previewer_win
if preview_close_on_tableave:
Vim.command('augroup NETRPREVIEW')
Vim.command(f'autocmd TabLeave <buffer> ++once \
py3 ranger._bufs[{self._vim_buf_handle.number}]._close_last_previewee()'
)
Vim.command('augroup END')
else:
Vim.command('silent! autocmd! NETRPREVIEW TabLeave <buffer>')
self._record_previewee(previewee_bufnr, previewee_winid)
# Update the previewer window width. Note that it is not done above as
# DisableOnWinEnter prevent this from happening through
# autocmd.
self.redraw_if_winwidth_changed()
cur_width = Vim.CurWinWidth()
for w in Vim.current.tabpage.windows:
if 'netranger_is_previewer' in w.vars:
w.width = cur_width
def preview_off(self):
""" Turn preview panel off. """
self._close_last_previewee()
self.redraw_if_winwidth_changed()
def _expand_node(self, node, level):
if not node.is_DIR:
return []
try:
node.expanded = True
self._expanded_nodes.add(node)
if level == 1:
return self.create_nodes(node.fullpath, node.level + 1)
else:
res = []
for n in self.create_nodes(node.fullpath, node.level + 1):
res += [n] + self._expand_node(n, level - 1)
return res
except PermissionError:
Vim.ErrorMsg(f'Permission Denied. Not Expanding: {node.name}')
return []
def toggle_expand(self, maxlevel=1):
"""Create subnodes for the target directory.
Also record the mtime of the target directory so that we can
redraw in update_nodes_and_redraw if the subdirectory is changed.
"""
cur_node = self.cur_node
if not cur_node.is_DIR:
return
if cur_node.expanded:
end_ind = self.next_lesseq_level_ind(self.clineno)
for i in range(self.clineno, end_ind):
if self.nodes[i].is_DIR and self.nodes[i].expanded:
self._expanded_nodes.remove(self.nodes[i])
self._controler.remove_pick_cut_copy(
self, self.nodes[self.clineno + 1:end_ind])
del self.nodes[self.clineno + 1:end_ind]
cur_node.expanded = False
else:
self.nodes[self.clineno + 1:self.clineno + 1] = self._expand_node(
self.cur_node, maxlevel)
self._redraw()
def edit(self):
""" Enter edit mode. """
self.is_editing = True
self._redraw(plain=True)
for i, node in enumerate(self.nodes):
Vim.command(f'call matchaddpos("{node.vim_hi_group}", [{i+1}])')
Vim.command('setlocal buftype=acwrite')
Vim.command('setlocal modifiable')
Vim.command('let old_undolevels = &undolevels')
Vim.command('set undolevels=-1')
Vim.command('exe "normal a \<BS>\<Esc>"')
Vim.command('let &undolevels = old_undolevels')
Vim.command('unlet old_undolevels')
def save(self):
"""Rename the files according to current buffer content.
Retur false if called but is_editing is false. Otherwise return
true.
"""
if not self.is_editing:
return False
self.is_editing = False