__init__.py (1807B)
1 import os.path 2 import ranger.api 3 import ranger.core.fm 4 import ranger.ext.signals 5 from subprocess import Popen, PIPE, run 6 7 hook_init_prev = ranger.api.hook_init 8 9 def hook_init(fm): 10 def zoxide_add(signal): 11 Popen(["zoxide", "add", signal.new.path]) 12 13 fm.signal_bind("cd", zoxide_add) 14 fm.commands.alias("zi", "z -i") 15 return hook_init_prev(fm) 16 17 18 ranger.api.hook_init = hook_init 19 20 class z(ranger.api.commands.Command): 21 """ 22 :z 23 24 Jump around with zoxide (z) 25 """ 26 def execute(self): 27 results = self.query(self.args[1:]) 28 29 input_path = ' '.join(self.args[1:]) 30 if not results and os.path.isdir(input_path): 31 self.fm.cd(input_path) 32 return 33 34 if not results: 35 return 36 37 if os.path.isdir(results[0]): 38 self.fm.cd(results[0]) 39 40 def query(self, args): 41 try: 42 zoxide = self.fm.execute_command(f"zoxide query {' '.join(self.args[1:])}", 43 stdout=PIPE 44 ) 45 stdout, stderr = zoxide.communicate() 46 47 if zoxide.returncode == 0: 48 output = stdout.decode("utf-8").strip() 49 return output.splitlines() 50 elif zoxide.returncode == 1: # nothing found 51 return None 52 elif zoxide.returncode == 130: # user cancelled 53 return None 54 else: 55 output = stderr.decode("utf-8").strip() or f"zoxide: unexpected error (exit code {zoxide.returncode})" 56 self.fm.notify(output, bad=True) 57 except Exception as e: 58 self.fm.notify(e, bad=True) 59 60 def tab(self, tabnum): 61 results = self.query(self.args[1:]) 62 return ["z {}".format(x) for x in results] 63