def execute(self): command = os.environ.get("TERMCMD", os.environ.get("TERM")) if command not in get_executables(): command = "x-terminal-emulator" if command not in get_executables(): command = "xterm" self.fm.run(command, flags="f")
def execute(self): command = os.environ.get('TERMCMD', os.environ.get('TERM')) if command not in get_executables(): command = 'x-terminal-emulator' if command not in get_executables(): command = 'xterm' self.fm.run(command, flags='d')
def _eval_condition2( # pylint: disable=too-many-return-statements,too-many-branches self, rule, files, label): # This function evaluates the condition, after _eval_condition() handled # negation of conditions starting with a "!". if not files: return False function = rule[0] argument = rule[1] if len(rule) > 1 else '' if function == 'ext': if os.path.isfile(files[0]): partitions = os.path.basename(files[0]).rpartition('.') if not partitions[0]: return False return bool(re.search('^(' + argument + ')$', partitions[2].lower())) elif function == 'name': return bool(re.search(argument, os.path.basename(files[0]))) elif function == 'match': return bool(re.search(argument, files[0])) elif function == 'file': return os.path.isfile(files[0]) elif function == 'directory': return os.path.isdir(files[0]) elif function == 'path': return bool(re.search(argument, os.path.abspath(files[0]))) elif function == 'mime': return bool(re.search(argument, self.get_mimetype(files[0]))) elif function == 'has': if argument.startswith("$"): if argument[1:] in os.environ: return os.environ[argument[1:]] in get_executables() return False else: return argument in get_executables() elif function == 'terminal': return _is_terminal() elif function == 'number': if argument.isdigit(): self._skip = int(argument) return True elif function == 'label': self._app_label = argument if label: return argument == label return True elif function == 'flag': self._app_flags = argument return True elif function == 'X': return ('WAYLAND_DISPLAY' in os.environ or sys.platform == 'darwin' or 'DISPLAY' in os.environ) elif function == 'env': return bool(os.environ.get(argument)) elif function == 'else': return True return None
def _eval_condition2( # pylint: disable=too-many-return-statements,too-many-branches self, rule, files, label): # This function evaluates the condition, after _eval_condition() handled # negation of conditions starting with a "!". if not files: return False function = rule[0] argument = rule[1] if len(rule) > 1 else '' if function == 'ext': if os.path.isfile(files[0]): partitions = os.path.basename(files[0]).rpartition('.') if not partitions[0]: return False return bool(re.search('^(' + argument + ')$', partitions[2].lower())) elif function == 'name': return bool(re.search(argument, os.path.basename(files[0]))) elif function == 'match': return bool(re.search(argument, files[0])) elif function == 'file': return os.path.isfile(files[0]) elif function == 'directory': return os.path.isdir(files[0]) elif function == 'path': return bool(re.search(argument, os.path.abspath(files[0]))) elif function == 'mime': return bool(re.search(argument, self.get_mimetype(files[0]))) elif function == 'has': if argument.startswith("$"): if argument[1:] in os.environ: return os.environ[argument[1:]] in get_executables() return False else: return argument in get_executables() elif function == 'terminal': return _is_terminal() elif function == 'number': if argument.isdigit(): self._skip = int(argument) return True elif function == 'label': self._app_label = argument if label: return argument == label return True elif function == 'flag': self._app_flags = argument return True elif function == 'X': return sys.platform == 'darwin' or 'DISPLAY' in os.environ elif function == 'env': return bool(os.environ.get(argument)) elif function == 'else': return True return None
def execute(self): import os from ranger.ext.get_executables import get_executables command = os.environ.get('TERMCMD', os.environ.get('TERM')) if command not in get_executables(): command = 'urxvtc' if command not in get_executables(): command = 'urxvtc' self.fm.run(command, flags='f')
def execute(self): import os from ranger.ext.get_executables import get_executables command = os.environ.get('TERMCMD', os.environ.get('TERM')) if command not in get_executables(): command = 'x-terminal-emulator' if command not in get_executables(): command = 'xterm' self.fm.run(command, flags='f')
def execute(self): import os from ranger.ext.get_executables import get_executables command = os.environ.get('TERMCMD', os.environ.get('TERM')) if command not in get_executables(): command = 'sakura' if command not in get_executables(): command = 'sakura' self.fm.run(command, flags='f')
def execute(self): import re import subprocess from ranger.ext.get_executables import get_executables self.SEARCH_RESULTS.clear() if "fdfind" in get_executables(): fd = "fdfind" elif "fd" in get_executables(): fd = "fd" else: self.fm.notify("Couldn't find fd in the PATH.", bad=True) return if self.arg(1): if self.arg(1)[:2] == "-d": depth = self.arg(1) target = self.rest(2) else: depth = "-d1" target = self.rest(1) else: self.fm.notify(":fd_search needs a query.", bad=True) return hidden = "--hidden" if self.fm.settings.show_hidden else "" exclude = "--no-ignore-vcs --exclude '.git' --exclude '*.py[co]' --exclude '__pycache__'" command = "{} --follow {} {} {} --print0 {}".format( fd, depth, hidden, exclude, target) fd = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, _ = fd.communicate() if fd.returncode == 0: results = filter(None, stdout.split("\0")) if not self.fm.settings.show_hidden and self.fm.settings.hidden_filter: hidden_filter = re.compile(self.fm.settings.hidden_filter) results = filter( lambda res: not hidden_filter.search(os.path.basename(res) ), results) results = map( lambda res: os.path.abspath( os.path.join(self.fm.thisdir.path, res)), results, ) self.SEARCH_RESULTS.extend(sorted(results, key=str.lower)) if len(self.SEARCH_RESULTS) > 0: self.fm.notify("Found {} result{}.".format( len(self.SEARCH_RESULTS), ("s" if len(self.SEARCH_RESULTS) > 1 else ""), )) self.fm.select_file(self.SEARCH_RESULTS[0]) else: self.fm.notify("No results found.")
def execute(self): import os from ranger.ext.get_executables import get_executables command = os.environ.get("TERMCMD", os.environ.get("TERM")) if command not in get_executables(): command = "x-terminal-emulator" if command not in get_executables(): # command = 'xterm' command = "urxvt" self.fm.run(command, flags="f")
def _eval_condition2(self, rule, files, label): # This function evaluates the condition, after _eval_condition() handled # negation of conditions starting with a "!". if not files: return False function = rule[0] argument = rule[1] if len(rule) > 1 else '' if function == 'ext': extension = os.path.basename(files[0]).rsplit('.', 1)[-1].lower() return bool(re.search('^(' + argument + ')$', extension)) elif function == 'name': return bool(re.search(argument, os.path.basename(files[0]))) elif function == 'match': return bool(re.search(argument, files[0])) elif function == 'file': return os.path.isfile(files[0]) elif function == 'directory': return os.path.isdir(files[0]) elif function == 'path': return bool(re.search(argument, os.path.abspath(files[0]))) elif function == 'mime': return bool(re.search(argument, self._get_mimetype(files[0]))) elif function == 'has': if argument.startswith("$"): if argument[1:] in os.environ: return os.environ[argument[1:]] in get_executables() return False else: return argument in get_executables() elif function == 'terminal': return _is_terminal() elif function == 'number': if argument.isdigit(): self._skip = int(argument) return True elif function == 'label': self._app_label = argument if label: return argument == label return True elif function == 'flag': self._app_flags = argument return True elif function == 'X': return 'DISPLAY' in os.environ elif function == 'env': return bool(os.environ.get(argument)) elif function == 'else': return True
def execute(self): import subprocess import os from ranger.ext.get_executables import get_executables if 'fzf' not in get_executables(): self.fm.notify('Could not find fzf in the PATH.', bad=True) return fd = None if 'fdfind' in get_executables(): fd = 'fdfind' elif 'fd' in get_executables(): fd = 'fd' if fd is not None: hidden = ('--hidden' if self.fm.settings.show_hidden else '') exclude = "--no-ignore-vcs --exclude '.git' --exclude '*.py[co]' --exclude '__pycache__'" only_directories = ('--type directory' if self.quantifier else '') fzf_default_command = '{} --follow {} {} {} --color=always'.format( fd, hidden, exclude, only_directories) else: hidden = ('-false' if self.fm.settings.show_hidden else r"-path '*/\.*' -prune") exclude = r"\( -name '\.git' -o -iname '\.*py[co]' -o -fstype 'dev' -o -fstype 'proc' \) -prune" only_directories = ('-type d' if self.quantifier else '') fzf_default_command = 'find -L . -mindepth 1 {} -o {} -o {} -print | cut -b3-'.format( hidden, exclude, only_directories) env = os.environ.copy() env['FZF_DEFAULT_COMMAND'] = fzf_default_command env['FZF_DEFAULT_OPTS'] = '--height=40% --layout=reverse --ansi --preview="{}"'.format( ''' ( batcat --color=always {} || bat --color=always {} || cat {} || tree -ahpCL 3 -I '.git' -I '*.py[co]' -I '__pycache__' {} ) 2>/dev/null | head -n 100 ''') fzf = self.fm.execute_command('fzf --no-multi', env=env, universal_newlines=True, stdout=subprocess.PIPE) stdout, _ = fzf.communicate() if fzf.returncode == 0: selected = os.path.abspath(stdout.strip()) if os.path.isdir(selected): self.fm.cd(selected) else: self.fm.select_file(selected)
def _eval_condition2(self, rule, files, label): # This function evaluates the condition, after _eval_condition() handled # negation of conditions starting with a "!". if not files: return False function = rule[0] argument = rule[1] if len(rule) > 1 else "" if function == "ext": extension = os.path.basename(files[0]).rsplit(".", 1)[-1].lower() return bool(re.search("^(" + argument + ")$", extension)) elif function == "name": return bool(re.search(argument, os.path.basename(files[0]))) elif function == "match": return bool(re.search(argument, files[0])) elif function == "file": return os.path.isfile(files[0]) elif function == "directory": return os.path.isdir(files[0]) elif function == "path": return bool(re.search(argument, os.path.abspath(files[0]))) elif function == "mime": return bool(re.search(argument, self._get_mimetype(files[0]))) elif function == "has": if argument.startswith("$"): if argument[1:] in os.environ: return os.environ[argument[1:]] in get_executables() return False else: return argument in get_executables() elif function == "terminal": return _is_terminal() elif function == "number": if argument.isdigit(): self._skip = int(argument) return True elif function == "label": self._app_label = argument if label: return argument == label return True elif function == "flag": self._app_flags = argument return True elif function == "X": return "DISPLAY" in os.environ elif function == "else": return True
def execute(self): import subprocess import os from ranger.ext.get_executables import get_executables # Only show directory self.quantifier = True if 'fzf' not in get_executables(): self.fm.notify('Could not find fzf in the PATH.', bad=True) return fd = None if 'fdfind' in get_executables(): fd = 'fdfind' elif 'fd' in get_executables(): fd = 'fd' if fd is not None: hidden = ('--hidden' if self.fm.settings.show_hidden else '') exclude = "--no-ignore-vcs --exclude={.wine,.git,.idea,.vscode,.sass-cache,node_modules,build,.local,.steam,.m2,.rangerdir,.ssh,.ghidra,.mozilla} --exclude '*.py[co]' --exclude '__pycache__'" fzf_default_command = '{} --follow {} {} --color=always'.format( fd, hidden, exclude) else: hidden = ('-false' if self.fm.settings.show_hidden else r"-path '*/\.*' -prune") exclude = r"\( -name '\.git' -o -iname '\.*py[co]' -o -fstype 'dev' -o -fstype 'proc' \) -prune" fzf_default_command = 'find -L . -mindepth 1 {} -o {} -o -print | cut -b3-'.format( hidden, exclude) env = os.environ.copy() env['FZF_DEFAULT_COMMAND'] = fzf_default_command # Modified for fish shell env['FZF_DEFAULT_OPTS'] = "--height=100% --layout=reverse --ansi \ --bind alt-k:preview-up,alt-j:preview-down,ctrl-y:preview-up,ctrl-e:preview-down,ctrl-b:preview-page-up,ctrl-f:preview-page-down \ --preview=\"tree 3 -I '.git' -I '*.py[co]' -I '__pycache__' {}\"" fzf = self.fm.execute_command('fzf --no-multi', env=env, universal_newlines=True, stdout=subprocess.PIPE) stdout, _ = fzf.communicate() if fzf.returncode == 0: selected = os.path.abspath(stdout.strip()) if os.path.isdir(selected): self.fm.cd(selected) else: self.fm.select_file(selected)
def execute(self): import subprocess import os from ranger.ext.get_executables import get_executables if 'fzf' not in get_executables(): self.fm.notify('Could not find fzf in the PATH.', bad=True) return env = os.environ.copy() env['FZF_DEFAULT_COMMAND'] = 'fd' env['FZF_DEFAULT_OPTS'] = '--height=40% --layout=reverse --ansi --preview="{}"'.format(''' ( batcat --color=always {} || bat --color=always {} || cat {} || tree -ahpCL 3 -I '.git' -I '*.py[co]' -I '__pycache__' {} ) 2>/dev/null | head -n 100 ''') fzf = self.fm.execute_command('fzf --no-multi', env=env, universal_newlines=True, stdout=subprocess.PIPE) stdout, _ = fzf.communicate() if fzf.returncode == 0: selected = os.path.abspath(stdout.strip()) if os.path.isdir(selected): self.fm.cd(selected) else: self.fm.select_file(selected)
def execute(self): import subprocess from ranger.ext.get_executables import get_executables if not 'fd' in get_executables(): self.fm.notify("Couldn't find fd on the PATH.", bad=True) return if self.arg(1): if self.arg(1)[:2] == '-d': depth = self.arg(1) target = self.rest(2) else: depth = '-d1' target = self.rest(1) else: self.fm.notify(":fd_search needs a query.", bad=True) return # For convenience, change which dict is used as result_sep to change # fd's behavior from splitting results by \0, which allows for newlines # in your filenames to splitting results by \n, which allows for \0 in # filenames. null_sep = {'arg': '-0', 'split': '\0'} nl_sep = {'arg': '', 'split': '\n'} result_sep = null_sep process = subprocess.Popen(['fd', result_sep['arg'], depth, target], universal_newlines=True, stdout=subprocess.PIPE) (search_results, _err) = process.communicate() global fd_deq fd_deq = deque((self.fm.thisdir.path + os.sep + rel for rel in sorted( search_results.split(result_sep['split']), key=str.lower) if rel != '')) if len(fd_deq) > 0: self.fm.select_file(fd_deq[0])
def execute(self): if 'xclip' not in get_executables(): self.fm.notify('xclip is not found.', bad=True) return arg = self.rest(1) if arg: if not os.path.isfile(arg): self.fm.notify('{} is not a file.'.format(arg)) return file = File(arg) else: file = self.fm.thisfile if not file.is_file: self.fm.notify('{} is not a file.'.format(file.relative_path)) return relative_path = file.relative_path cmd = ['xclip', '-selection', 'clipboard'] if not file.is_binary(): with open(file.path, 'rb') as fd: subprocess.check_call(cmd, stdin=fd) elif file.image: cmd += ['-t', file.mimetype, file.path] subprocess.check_call(cmd) self.fm.notify( 'Content of {} is copied to x clipboard'.format(relative_path)) else: self.fm.notify('{} is not an image file or a text file.'.format( relative_path))
def execute(self): import subprocess import os from ranger.ext.get_executables import get_executables if 'fzf' not in get_executables(): self.fm.notify('Could not find fzf in the PATH.', bad=True) return env = os.environ.copy() env['FZF_DEFAULT_OPTS'] = '--height=100% --layout=reverse --ansi --preview="{}"'.format( ''' cat {} 2>/dev/null | head -n 100 ''') fzf = self.fm.execute_command( "fdfind . '/media' '/home' -H | fzf -e -i", env=env, universal_newlines=True, stdout=subprocess.PIPE) stdout, _ = fzf.communicate() if fzf.returncode == 0: selected = os.path.abspath(stdout.strip()) if os.path.isdir(selected): self.fm.cd(selected) else: self.fm.select_file(selected)
def execute(self): import subprocess from ranger.ext.get_executables import get_executables if not 'fd' in get_executables(): self.fm.notify("Couldn't find fd on the PATH.", bad=True) return if self.arg(1): if self.arg(1)[:2] == '-d': depth = self.arg(1) target = self.rest(2) else: depth = '-d1' target = self.rest(1) else: self.fm.notify(":fd_search needs a query.", bad=True) return # For convenience, change which dict is used as result_sep to change # fd's behavior from splitting results by \0, which allows for newlines # in your filenames to splitting results by \n, which allows for \0 in # filenames. null_sep = {'arg': '-0', 'split': '\0'} nl_sep = {'arg': '', 'split': '\n'} result_sep = null_sep process = subprocess.Popen(['fd', result_sep['arg'], depth, target], universal_newlines=True, stdout=subprocess.PIPE) (search_results, _err) = process.communicate() global fd_deq fd_deq = deque((self.fm.thisdir.path + os.sep + rel for rel in sorted(search_results.split(result_sep['split']), key=str.lower) if rel != '')) if len(fd_deq) > 0: self.fm.select_file(fd_deq[0])
def tab(self): from ranger.ext.get_executables import get_executables if self.arg(1) and self.arg(1)[0] == "-": command = self.rest(2) else: command = self.rest(1) start = self.line[0 : len(self.line) - len(command)] try: position_of_last_space = command.rindex(" ") except ValueError: return (start + program + " " for program in get_executables() if program.startswith(command)) if position_of_last_space == len(command) - 1: selection = self.fm.thistab.get_selection() if len(selection) == 1: return self.line + selection[0].shell_escaped_basename + " " else: return self.line + "%s " else: before_word, start_of_word = self.line.rsplit(" ", 1) return ( before_word + " " + file.shell_escaped_basename for file in self.fm.thisdir.files if file.shell_escaped_basename.startswith(start_of_word) )
def execute(self): import os from ranger.ext.get_executables import get_executables command = os.environ.get('TERMCMD', os.environ.get('TERM')) current_path = os.getcwd() if command not in get_executables(): command = 'urxvt -cd {0}'.format(current_path) self.fm.run(command, flags='f')
def execute(self): import subprocess from ranger.container.file import File from ranger.ext.get_executables import get_executables clipboard_managers = { 'xclip': [ ['xclip', '-selection', 'primary'], ['xclip', '-selection', 'clipboard'], ], 'xsel': [ ['xsel', '--primary'], ['xsel', '--clipboard'], ], 'wl-copy': [ ['wl-copy'], ], 'pbcopy': [ ['pbcopy'], ], } ordered_managers = ['pbcopy', 'wl-copy', 'xclip', 'xsel'] executables = get_executables() for manager in ordered_managers: if manager in executables: clipboard_commands = clipboard_managers[manager] break else: self.fm.notify('Could not find a clipboard manager in the PATH.', bad=True) return arg = self.rest(1) if arg: if not os.path.isfile(arg): self.fm.notify("'{}' is not a file.".format(arg), bad=True) return file = File(arg) else: file = self.fm.thisfile if not file.is_file: self.fm.notify("'{}' is not a file.".format( file.relative_path), bad=True) return if not file.is_binary(): for command in clipboard_commands: with open(file.path, mode='r') as fd: self.fm.execute_command(command, universal_newlines=True, stdin=fd) self.fm.notify( "The content of '{}' is copied to the clipboard.".format( file.relative_path)) else: self.fm.notify("'{}' is not a text file.".format( file.relative_path))
def _tab_through_executables(self): from ranger.ext.get_executables import get_executables programs = [program for program in get_executables() if \ program.startswith(self.rest(1))] if not programs: return if len(programs) == 1: return self.start(1) + programs[0] programs.sort() return (self.start(1) + program for program in programs)
def either(self, context, *args): for app in args: try: application_handler = getattr(self, 'app_' + app) except AttributeError: if app in get_executables(): return _generic_app(app, context) continue if self._meets_dependencies(application_handler): return application_handler(context)
def apply(self, app, context): if not app: app = 'default' try: handler = getattr(self, 'app_' + app) except AttributeError: if app in get_executables(): return _generic_app(app, context) handler = self.app_default return handler(context)
def _apply_flags(self, action, flags): # FIXME: Flags do not work properly when pipes are in the command. if "r" in flags: action = "sudo " + action if "t" in flags: if "TERMCMD" not in os.environ: term = os.environ["TERM"] if term.startswith("rxvt-unicode"): term = "urxvt" if term not in get_executables(): self.hook_logger("Can not determine terminal command. " "Please set $TERMCMD manually.") os.environ["TERMCMD"] = term action = "$TERMCMD -e %s" % action if "f" in flags: if "setsid" in get_executables(): action = "setsid %s > /dev/null 2> /dev/null &" % action else: action = "nohup %s > /dev/null 2> /dev/null &" % action return action
def _apply_flags(self, action, flags): # FIXME: Flags do not work properly when pipes are in the command. if 'r' in flags: action = 'sudo ' + action if 't' in flags: if 'TERMCMD' not in os.environ: term = os.environ['TERM'] if term.startswith('rxvt-unicode'): term = 'urxvt' if term not in get_executables(): self.hook_logger("Can not determine terminal command. " "Please set $TERMCMD manually.") os.environ['TERMCMD'] = term action = "$TERMCMD -e %s" % action if 'f' in flags: if 'setsid' in get_executables(): action = "setsid %s > /dev/null 2> /dev/null &" % action else: action = "nohup %s > /dev/null 2> /dev/null &" % action return action
def app_editor(self, c): try: default_editor = os.environ['EDITOR'] except KeyError: pass else: parts = default_editor.split() exe_name = os.path.basename(parts[0]) if exe_name in get_executables(): return tuple(parts) + tuple(c) return self.either(c, 'vim', 'emacs', 'nano')
def execute(self, files, number=0, label=None, flags=None, mimetype=None): """ Executes the given list of files. By default, this executes the first command where all conditions apply, but by specifying number=N you can run the 1+Nth command. If a label is specified, only rules with this label will be considered. If you specify the mimetype, rifle will not try to determine it itself. By specifying a flag, you extend the flag that is defined in the rule. Uppercase flags negate the respective lowercase flags. For example: if the flag in the rule is "pw" and you specify "Pf", then the "p" flag is negated and the "f" flag is added, resulting in "wf". """ command = None found_at_least_one = None # Determine command for count, cmd, lbl, flags in self.list_commands(files, mimetype): if label and label == lbl or not label and count == number: cmd = self.hook_command_preprocessing(cmd) command = self._build_command(files, cmd, flags) break else: found_at_least_one = True else: if label and label in get_executables(): cmd = '%s -- "$@"' % label command = self._build_command(files, cmd, flags) # Execute command if command is None: if found_at_least_one: if label: self.hook_logger("Label '%s' is undefined" % label) else: self.hook_logger("Method number %d is undefined." % number) else: self.hook_logger("No action found.") else: if 'PAGER' not in os.environ: os.environ['PAGER'] = DEFAULT_PAGER if 'EDITOR' not in os.environ: os.environ['EDITOR'] = DEFAULT_EDITOR command = self.hook_command_postprocessing(command) self.hook_before_executing(command, self._mimetype, self._app_flags) try: p = Popen(command, env=self.hook_environment(os.environ), shell=True) p.wait() finally: self.hook_after_executing(command, self._mimetype, self._app_flags)
def execute(self): import subprocess from ranger.ext.get_executables import get_executables if self.arg(1): search_string = self.rest(1) else: self.fm.notify("Usage: find_in_file <search string>", bad=True) return if "fzf" not in get_executables(): self.fm.notify("Could not find fzf in the PATH.", bad=True) return if "rg" not in get_executables(): self.fm.notify("Could not find rg in the PATH.", bad=True) return search = "--smart-case --files-with-matches --no-messages '%s'" % search_string highlight = "highlight -O ansi -l {} 2> /dev/null" rgMatches = ( "rg --colors 'match:bg:yellow' --ignore-case --pretty --context 10 '%s'" ) % search_string rgEmpty = "rg --ignore-case --pretty --context 10 '%s' {}" % search_string interactive_search_command = ( 'rg {} | fzf --no-multi --preview "{} | {} || {}"'.format( search, highlight, rgMatches, rgEmpty)) rg_with_fzf = self.fm.execute_command(interactive_search_command, universal_newlines=True, stdout=subprocess.PIPE) stdout, _ = rg_with_fzf.communicate() if rg_with_fzf.returncode == 0: selected = os.path.abspath(stdout.strip()) if os.path.isdir(selected): self.fm.cd(selected) else: self.fm.select_file(selected)
def _meets_dependencies(self, fnc): try: deps = fnc.dependencies except AttributeError: return True for dep in deps: if hasattr(dep, 'dependencies') \ and not self._meets_dependencies(dep): return False if dep not in get_executables(): return False return True
def command(self) -> str: """ Uses fd (https://github.com/sharkdp/fd) if it is available. """ fd = None if 'fdfind' in get_executables(): fd = 'fdfind' elif 'fd' in get_executables(): fd = 'fd' if fd is not None: hidden = ('--hidden' if self.fm.settings.show_hidden else '') exclude = "--no-ignore-vcs --exclude '.git' --exclude '*.py[co]' --exclude '__pycache__'" only_directories = ('--type directory' if self.quantifier else '') fzf_default_command = '{} --follow {} {} {} --color=always'.format( fd, hidden, exclude, only_directories) else: hidden = ('-false' if self.fm.settings.show_hidden else r"-path '*/\.*' -prune") exclude = r"\( -name '\.git' -o -iname '\.*py[co]' -o -fstype 'dev' -o -fstype 'proc' \) -prune" only_directories = ('-type d' if self.quantifier else '') fzf_default_command = 'find -L . -mindepth 1 {} -o {} -o {} -print | cut -b3-'.format( hidden, exclude, only_directories) return fzf_default_command
def clipboards(): from ranger.ext.get_executables import get_executables clipboard_managers = { "xclip": [["xclip", "-selection", "clipboard", "-o"]], "xsel": [["xsel", "-b", "-o"]], "pbpaste": [["pbpaste"]], } ordered_managers = ["pbpaste", "xclip", "xsel"] executables = get_executables() for manager in ordered_managers: if manager in executables: return clipboard_managers[manager] return []
def execute(self) -> None: """ Run Pywal with a given image, alpha, and background color. :return: None """ if 'wal' not in get_executables(): self.fm.notify('Could not find pywal in PATH.', bad=True) return (image_filename, alpha, background) = self._get_arguments() self.fm.notify(f'Running pywal using {image_filename}.') self.fm.execute_command(f'wal -i "{image_filename}" ' f'-a {alpha} -b "{background}"')
def execute(self): """Execute the command.""" trash_cmd = 'trash-put' if trash_cmd not in get_executables(): self.fm.notify(f"Couldn't find {trash_cmd} on the PATH.", bad=True) return files = [f.relative_path for f in self.fm.thistab.get_selection()] if not files: self.fm.notify("No file selected for deletion", bad=True) return self.fm.ui.console.ask( f"Confirm deletion of: {files} (y/N)", partial(self._question_callback, files), ('n', 'N', 'y', 'Y'), )
def _meets_dependencies(self, fnc): try: deps = fnc.dependencies except AttributeError: return True for dep in deps: if dep == 'X': if 'DISPLAY' not in os.environ or not os.environ['DISPLAY']: return False continue if hasattr(dep, 'dependencies') \ and not self._meets_dependencies(dep): return False if dep not in get_executables(): return False return True
def tab(self): if self.arg(1) and self.arg(1)[0] == '-': command = self.rest(2) else: command = self.rest(1) start = self.line[0:len(self.line) - len(command)] try: position_of_last_space = command.rindex(" ") except ValueError: return (start + program + ' ' for program \ in get_executables() if program.startswith(command)) if position_of_last_space == len(command) - 1: return self.line + '%s ' else: before_word, start_of_word = self.line.rsplit(' ', 1) return (before_word + ' ' + file.shell_escaped_basename \ for file in self.fm.env.cwd.files \ if file.shell_escaped_basename.startswith(start_of_word))
def clipboards(): from ranger.ext.get_executables import get_executables clipboard_managers = { 'xclip': [ ['xclip'], ['xclip', '-selection', 'clipboard'], ], 'xsel': [ ['xsel'], ['xsel', '-b'], ], 'pbcopy': [ ['pbcopy'], ], } ordered_managers = ['pbcopy', 'xclip', 'xsel'] executables = get_executables() for manager in ordered_managers: if manager in executables: return clipboard_managers[manager] return []
def sxiv_open_with(self, files, number=0, label=None, flags="", mimetype=None): """ Hooking for sxiv_select option from rifle menu, which handle call of not exist programm and run command sxiv_select. """ cmd = "" for count, cmd, lbl, _flags in self.list_commands(files, mimetype): if label and label == lbl or not label and count == number: cmd = self.hook_command_preprocessing(cmd) break else: from ranger.ext.get_executables import get_executables if label and label in get_executables(): cmd = '%s "$@"' % label if cmd == "sxiv_select": sxiv_obj = sxiv_select("") sxiv_obj.execute() else: global old_execute old_execute(self, files, number, label, flags, mimetype)
def execute(self): from ranger.ext.get_executables import get_executables from ranger.core.filter_stack import SIMPLE_FILTERS import subprocess tag = self.arg(1) if not 'exiftool' in get_executables(): self.fm.notify("Couldn't find exif_filter on the PATH.", bad=True) return if not tag: self.fm.notify(":exif_filter needs a query.", bad=True) return process = subprocess.Popen(['/home/nexor/.local/bin/sit', tag], universal_newlines=True, stdout=subprocess.PIPE) i = 0 for l in iter(lambda: process.stdout.readline(), ''): self.fm.thisdir.filter_stack.append(SIMPLE_FILTERS['name'](l[2:])) if not i % 5: self.fm.thisdir.refilter() i += 1 self.fm.thisdir.refilter()
def apply(self, app, context): if not app: app = 'default' try: handler = getattr(self, 'app_' + app) except AttributeError: if app in get_executables(): return [app] + list(context) handler = self.app_default arguments = handler(context) # flatten if isinstance(arguments, str): return (arguments, ) if arguments is None: return None result = [] for obj in arguments: if isinstance(obj, (tuple, list, Context)): result.extend(obj) else: result.append(obj) return result
def execute(self): if 'fzf' not in get_executables(): self.fm.notify('Could not find fzf in the PATH.', bad=True) return env = os.environ.copy() command = self.command if isinstance(self.command, str) \ else self.command() options = "--ansi --preview='_preview_path {}'" + " " + self.options env['FZF_DEFAULT_COMMAND'] = command env['FZF_DEFAULT_OPTS'] += " " + options fzf = self.fm.execute_command('fzf --no-multi', env=env, universal_newlines=True, stdout=subprocess.PIPE) stdout, _ = fzf.communicate() if fzf.returncode == 0: selected = os.path.abspath(stdout.strip()) if os.path.isdir(selected): self.fm.cd(selected) else: self.fm.select_file(selected)
def _eval_condition2(self, rule, files, label): # This function evaluates the condition, after _eval_condition() handled # negation of conditions starting with a "!". function = rule[0] argument = rule[1] if len(rule) > 1 else '' if not files: return False if function == 'ext': extension = os.path.basename(files[0]).rsplit('.', 1)[-1] return bool(re.search('^' + argument + '$', extension)) if function == 'name': return bool(re.search(argument, os.path.basename(files[0]))) if function == 'path': return bool(re.search(argument, os.path.abspath(files[0]))) if function == 'mime': return bool(re.search(argument, self._get_mimetype(files[0]))) if function == 'has': return argument in get_executables() if function == 'terminal': return _is_terminal() if function == 'number': if argument.isdigit(): self._skip = int(argument) return True if function == 'label': self._app_label = argument if label: return argument == label return True if function == 'flag': self._app_flags = argument return True if function == 'X': return 'DISPLAY' in os.environ if function == 'else': return True
def tab(self, tabnum): from ranger.ext.get_executables import get_executables if self.arg(1) and self.arg(1)[0] == '-': command = self.rest(2) else: command = self.rest(1) start = self.line[0:len(self.line) - len(command)] try: position_of_last_space = command.rindex(" ") except ValueError: return (start + program + ' ' for program in get_executables() if program.startswith(command)) if position_of_last_space == len(command) - 1: selection = self.fm.thistab.get_selection() if len(selection) == 1: return self.line + selection[0].shell_escaped_basename + ' ' return self.line + '%s ' before_word, start_of_word = self.line.rsplit(' ', 1) return (before_word + ' ' + file.shell_escaped_basename for file in self.fm.thisdir.files or [] if file.shell_escaped_basename.startswith(start_of_word))
def executables(self): """For compatibility. Calls get_executables()""" return get_executables()
def __call__( # pylint: disable=too-many-branches,too-many-statements # pylint: disable=too-many-arguments,too-many-locals self, action=None, try_app_first=False, app='default', files=None, mode=0, flags='', wait=True, **popen_kws): """Run the application in the way specified by the options. Returns False if nothing can be done, None if there was an error, otherwise the process object returned by Popen(). This function tries to find an action if none is defined. """ # Find an action if none was supplied by # creating a Context object and passing it to # an Application object. context = Context(app=app, files=files, mode=mode, fm=self.fm, flags=flags, wait=wait, popen_kws=popen_kws, file=files and files[0] or None) if action is None: return self._log("No way of determining the action!") # Preconditions context.squash_flags() popen_kws = context.popen_kws # shortcut toggle_ui = True pipe_output = False wait_for_enter = False devnull = None if 'shell' not in popen_kws: popen_kws['shell'] = isinstance(action, str) # Set default shell for Popen if popen_kws['shell']: # This doesn't work with fish, see #300 if 'fish' not in os.environ['SHELL']: popen_kws['executable'] = os.environ['SHELL'] if 'stdout' not in popen_kws: popen_kws['stdout'] = sys.stdout if 'stderr' not in popen_kws: popen_kws['stderr'] = sys.stderr # Evaluate the flags to determine keywords # for Popen() and other variables if 'p' in context.flags: popen_kws['stdout'] = PIPE popen_kws['stderr'] = PIPE toggle_ui = False pipe_output = True context.wait = False if 's' in context.flags: devnull_writable = open(os.devnull, 'w') devnull_readable = open(os.devnull, 'r') for key in ('stdout', 'stderr'): popen_kws[key] = devnull_writable toggle_ui = False popen_kws['stdin'] = devnull_readable if 'f' in context.flags: toggle_ui = False context.wait = False if 'w' in context.flags: if not pipe_output and context.wait: # <-- sanity check wait_for_enter = True if 'r' in context.flags: # TODO: make 'r' flag work with pipes if 'sudo' not in get_executables(): return self._log("Can not run with 'r' flag, sudo is not installed!") f_flag = ('f' in context.flags) if isinstance(action, str): action = 'sudo ' + (f_flag and '-b ' or '') + action else: action = ['sudo'] + (f_flag and ['-b'] or []) + action toggle_ui = True context.wait = True if 't' in context.flags: if 'DISPLAY' not in os.environ: return self._log("Can not run with 't' flag, no display found!") term = get_term() if isinstance(action, str): action = term + ' -e ' + action else: action = [term, '-e'] + action toggle_ui = False context.wait = False popen_kws['args'] = action # Finally, run it if toggle_ui: self._activate_ui(False) try: error = None process = None self.fm.signal_emit('runner.execute.before', popen_kws=popen_kws, context=context) try: if 'f' in context.flags: # This can fail and return False if os.fork() is not # supported, but we assume it is, since curses is used. Popen_forked(**popen_kws) else: process = Popen(**popen_kws) except OSError as ex: error = ex self._log("Failed to run: %s\n%s" % (str(action), str(ex))) else: if context.wait: process.wait() elif process: self.zombies.add(process) if wait_for_enter: press_enter() finally: self.fm.signal_emit('runner.execute.after', popen_kws=popen_kws, context=context, error=error) if devnull: devnull.close() if toggle_ui: self._activate_ui(True) if pipe_output and process: return self(action='less', app='pager', # pylint: disable=lost-exception try_app_first=True, stdin=process.stdout) return process # pylint: disable=lost-exception
def __call__(self, action=None, try_app_first=False, app='default', files=None, mode=0, flags='', wait=True, **popen_kws): """ Run the application in the way specified by the options. Returns False if nothing can be done, None if there was an error, otherwise the process object returned by Popen(). This function tries to find an action if none is defined. """ # Find an action if none was supplied by # creating a Context object and passing it to # an Application object. context = Context(app=app, files=files, mode=mode, fm=self.fm, flags=flags, wait=wait, popen_kws=popen_kws, file=files and files[0] or None) if action is None: return self._log("No way of determining the action!") # Preconditions context.squash_flags() popen_kws = context.popen_kws # shortcut toggle_ui = True pipe_output = False wait_for_enter = False devnull = None if 'shell' not in popen_kws: popen_kws['shell'] = isinstance(action, str) if 'stdout' not in popen_kws: popen_kws['stdout'] = sys.stdout if 'stderr' not in popen_kws: popen_kws['stderr'] = sys.stderr # Evaluate the flags to determine keywords # for Popen() and other variables if 'p' in context.flags: popen_kws['stdout'] = PIPE popen_kws['stderr'] = PIPE toggle_ui = False pipe_output = True context.wait = False if 's' in context.flags or 'd' in context.flags: devnull_writable = open(os.devnull, 'w') devnull_readable = open(os.devnull, 'r') for key in ('stdout', 'stderr'): popen_kws[key] = devnull_writable popen_kws['stdin'] = devnull_readable if 'd' in context.flags: toggle_ui = False context.wait = False if 'w' in context.flags: if not pipe_output and context.wait: # <-- sanity check wait_for_enter = True if 'r' in context.flags: if 'sudo' not in get_executables(): return self._log("Can not run with 'r' flag, sudo is not installed!") dflag = ('d' in context.flags) if isinstance(action, str): action = 'sudo ' + (dflag and '-b ' or '') + action else: action = ['sudo'] + (dflag and ['-b'] or []) + action toggle_ui = True context.wait = True if 't' in context.flags: if 'DISPLAY' not in os.environ: return self._log("Can not run with 't' flag, no display found!") term = os.environ.get('TERMCMD', os.environ.get('TERM')) if term not in get_executables(): term = 'x-terminal-emulator' if term not in get_executables(): term = 'xterm' if isinstance(action, str): action = term + ' -e ' + action else: action = [term, '-e'] + action toggle_ui = False context.wait = False popen_kws['args'] = action # Finally, run it if toggle_ui: self._activate_ui(False) try: error = None process = None self.fm.signal_emit('runner.execute.before', popen_kws=popen_kws, context=context) try: process = Popen(**popen_kws) except Exception as e: error = e self._log("Failed to run: %s\n%s" % (str(action), str(e))) else: if context.wait: process.wait() else: self.zombies.add(process) if wait_for_enter: press_enter() finally: self.fm.signal_emit('runner.execute.after', popen_kws=popen_kws, context=context, error=error) if devnull: devnull.close() if toggle_ui: self._activate_ui(True) if pipe_output and process: return self(action='less', app='pager', try_app_first=True, stdin=process.stdout) return process
def execute(self, files, number=0, label=None, flags="", mimetype=None): """Executes the given list of files. By default, this executes the first command where all conditions apply, but by specifying number=N you can run the 1+Nth command. If a label is specified, only rules with this label will be considered. If you specify the mimetype, rifle will not try to determine it itself. By specifying a flag, you extend the flag that is defined in the rule. Uppercase flags negate the respective lowercase flags. For example: if the flag in the rule is "pw" and you specify "Pf", then the "p" flag is negated and the "f" flag is added, resulting in "wf". """ command = None found_at_least_one = None # Determine command for count, cmd, lbl, flgs in self.list_commands(files, mimetype): if label and label == lbl or not label and count == number: cmd = self.hook_command_preprocessing(cmd) if cmd == ASK_COMMAND: return ASK_COMMAND command = self._build_command(files, cmd, flags + flgs) flags = self._app_flags break else: found_at_least_one = True else: if label and label in get_executables(): cmd = '%s "$@"' % label command = self._build_command(files, cmd, flags) # Execute command if command is None: if found_at_least_one: if label: self.hook_logger("Label '%s' is undefined" % label) else: self.hook_logger("Method number %d is undefined." % number) else: self.hook_logger("No action found.") else: if 'PAGER' not in os.environ: os.environ['PAGER'] = DEFAULT_PAGER if 'EDITOR' not in os.environ: os.environ['EDITOR'] = DEFAULT_EDITOR command = self.hook_command_postprocessing(command) self.hook_before_executing(command, self._mimetype, self._app_flags) try: if 'r' in flags: prefix = ['sudo', '-E', 'su', '-mc'] else: prefix = ['/bin/sh', '-c'] cmd = prefix + [command] if 't' in flags: if 'TERMCMD' not in os.environ: term = os.environ['TERM'] if term.startswith('rxvt-unicode'): term = 'urxvt' if term not in get_executables(): self.hook_logger("Can not determine terminal command. " "Please set $TERMCMD manually.") # A fallback terminal that is likely installed: term = 'xterm' os.environ['TERMCMD'] = term cmd = [os.environ['TERMCMD'], '-e'] + cmd if 'f' in flags or 't' in flags: Popen_forked(cmd, env=self.hook_environment(os.environ)) else: p = Popen(cmd, env=self.hook_environment(os.environ)) p.wait() finally: self.hook_after_executing(command, self._mimetype, self._app_flags)
def execute(self, files, # noqa: E501 pylint: disable=too-many-branches,too-many-statements,too-many-locals number=0, label=None, flags="", mimetype=None): """Executes the given list of files. By default, this executes the first command where all conditions apply, but by specifying number=N you can run the 1+Nth command. If a label is specified, only rules with this label will be considered. If you specify the mimetype, rifle will not try to determine it itself. By specifying a flag, you extend the flag that is defined in the rule. Uppercase flags negate the respective lowercase flags. For example: if the flag in the rule is "pw" and you specify "Pf", then the "p" flag is negated and the "f" flag is added, resulting in "wf". """ command = None found_at_least_one = None # Determine command for count, cmd, lbl, flgs in self.list_commands(files, mimetype): if label and label == lbl or not label and count == number: cmd = self.hook_command_preprocessing(cmd) if cmd == ASK_COMMAND: return ASK_COMMAND command = self._build_command(files, cmd, flags + flgs) flags = self._app_flags break else: found_at_least_one = True else: if label and label in get_executables(): cmd = '%s "$@"' % label command = self._build_command(files, cmd, flags) # Execute command if command is None: # pylint: disable=too-many-nested-blocks if found_at_least_one: if label: self.hook_logger("Label '%s' is undefined" % label) else: self.hook_logger("Method number %d is undefined." % number) else: self.hook_logger("No action found.") else: if 'PAGER' not in os.environ: os.environ['PAGER'] = DEFAULT_PAGER if 'EDITOR' not in os.environ: os.environ['EDITOR'] = os.environ.get('VISUAL', DEFAULT_EDITOR) command = self.hook_command_postprocessing(command) self.hook_before_executing(command, self._mimetype, self._app_flags) try: if 'r' in flags: prefix = ['sudo', '-E', 'su', 'root', '-mc'] else: prefix = ['/bin/sh', '-c'] cmd = prefix + [command] if 't' in flags: term = os.environ.get('TERMCMD', os.environ['TERM']) # Handle aliases of xterm and urxvt, rxvt and st and # termite # Match 'xterm', 'xterm-256color' if term in ['xterm', 'xterm-256color']: term = 'xterm' if term in ['xterm-kitty']: term = 'kitty' if term in ['xterm-termite']: term = 'termite' if term in ['st', 'st-256color']: term = 'st' if term in ['urxvt', 'rxvt-unicode', 'rxvt-unicode-256color']: term = 'urxvt' if term in ['rxvt', 'rxvt-256color']: if 'rxvt' in get_executables(): term = 'rxvt' else: term = 'urxvt' if term not in get_executables(): self.hook_logger("Can not determine terminal command, " "using rifle to determine fallback. " "Please set $TERMCMD manually or " "change fallbacks in rifle.conf.") self._mimetype = 'ranger/x-terminal-emulator' self.execute( files=[command.split(';')[1].split('--')[0].strip()] + files, flags='f', mimetype='ranger/x-terminal-emulator') return None # Choose correct cmdflag accordingly if term in ['xfce4-terminal', 'mate-terminal', 'terminator']: cmdflag = '-x' elif term in ['xterm', 'urxvt', 'rxvt', 'lxterminal', 'konsole', 'lilyterm', 'cool-retro-term', 'terminology', 'pantheon-terminal', 'termite', 'st', 'stterm']: cmdflag = '-e' elif term in ['gnome-terminal', 'kitty']: cmdflag = '--' elif term in ['tilda', ]: cmdflag = '-c' else: cmdflag = '-e' os.environ['TERMCMD'] = term # These terms don't work with the '/bin/sh set --' scheme. # A temporary fix. if term in ['tilda', 'pantheon-terminal', 'terminology', 'termite']: target = command.split(';')[0].split('--')[1].strip() app = command.split(';')[1].split('--')[0].strip() cmd = [os.environ['TERMCMD'], cmdflag, '%s %s' % (app, target)] elif term in ['guake']: cmd = [os.environ['TERMCMD'], '-n', '${PWD}', cmdflag] + cmd else: cmd = [os.environ['TERMCMD'], cmdflag] + cmd # self.hook_logger('cmd: %s' %cmd) if 'f' in flags or 't' in flags: Popen_forked(cmd, env=self.hook_environment(os.environ)) else: process = Popen(cmd, env=self.hook_environment(os.environ)) process.wait() finally: self.hook_after_executing(command, self._mimetype, self._app_flags) return None
def _is_app(self, arg): return self.fm.apps.has(arg) or \ (not self._is_flags(arg) and arg in get_executables())