diff options
author | nfnty <git@nfnty.se> | 2016-12-18 09:38:42 +0100 |
---|---|---|
committer | nfnty <git@nfnty.se> | 2017-01-17 05:59:02 +0100 |
commit | 76791a70467d7223a966aa9f12f5583b01d704a8 (patch) | |
tree | 7a2f7543d439f9d0da695c00622c7b278424d9f6 | |
parent | e26d163debc9f55a89a27f94a43771526d2ff0b7 (diff) | |
download | ranger-76791a70467d7223a966aa9f12f5583b01d704a8.tar.gz |
linting: autopep8
51 files changed, 472 insertions, 421 deletions
diff --git a/examples/plugin_pmount.py b/examples/plugin_pmount.py index ba61b0e5..fe0adffb 100644 --- a/examples/plugin_pmount.py +++ b/examples/plugin_pmount.py @@ -22,11 +22,17 @@ def hook_init(fm): try: fm.execute_console("map {key} shell -p lsblk".format(key=LIST_MOUNTS_KEY)) for disk in "abcdefgh": - fm.execute_console("map {key}{0} chain shell pmount sd{1}; cd /media/sd{1}".format(disk.upper(), disk, key=MOUNT_KEY)) - fm.execute_console("map {key}{0} chain cd; chain shell pumount sd{1}".format(disk.upper(), disk, key=UMOUNT_KEY)) + fm.execute_console("map {key}{0} chain shell pmount sd{1}; cd /media/sd{1}".format( + disk.upper(), disk, key=MOUNT_KEY)) + fm.execute_console("map {key}{0} chain cd; chain shell pumount sd{1}".format( + disk.upper(), disk, key=UMOUNT_KEY)) for part in "123456789": - fm.execute_console("map {key}{0}{1} chain shell pmount sd{0}{1}; cd /media/sd{0}{1}".format(disk, part, key=MOUNT_KEY)) - fm.execute_console("map {key}{0}{1} chain cd; shell pumount sd{0}{1}".format(disk, part, key=UMOUNT_KEY)) + fm.execute_console( + "map {key}{0}{1} chain shell pmount sd{0}{1}; cd /media/sd{0}{1}".format( + disk, part, key=MOUNT_KEY) + ) + fm.execute_console("map {key}{0}{1} chain cd; shell pumount sd{0}{1}".format( + disk, part, key=UMOUNT_KEY)) finally: return old_hook_init(fm) ranger.api.hook_init = hook_init diff --git a/ranger/api/commands.py b/ranger/api/commands.py index 93c50adb..46075f26 100644 --- a/ranger/api/commands.py +++ b/ranger/api/commands.py @@ -16,6 +16,7 @@ _SETTINGS_RE = re.compile(r'^\s*([^\s]+?)=(.*)$') class CommandContainer(object): + def __init__(self): self.commands = {} @@ -58,8 +59,8 @@ class CommandContainer(object): def get_command(self, name, abbrev=True): if abbrev: lst = [cls for cmd, cls in self.commands.items() - if cls.allow_abbrev and cmd.startswith(name) - or cmd == name] + if cls.allow_abbrev and cmd.startswith(name) + or cmd == name] if len(lst) == 0: raise KeyError if len(lst) == 1: @@ -280,7 +281,7 @@ class Command(FileManagerAware): else: _, dirnames, _ = next(os.walk(abs_dirname)) dirnames = [dn for dn in dirnames - if dn.startswith(rel_basename)] + if dn.startswith(rel_basename)] except (OSError, StopIteration): # os.walk found nothing pass @@ -331,24 +332,22 @@ class Command(FileManagerAware): else: # Fall back to old method with "os.walk" _, dirnames, filenames = next(os.walk(abs_dest)) - names = dirnames + filenames - names.sort() + names = sorted(dirnames + filenames) # are we in the middle of the filename? else: if directory.content_loaded: # Take the order from the directory object names = [f.basename for f in directory.files - if f.basename.startswith(rel_basename)] + if f.basename.startswith(rel_basename)] if self.fm.thisfile.basename in names: i = names.index(self.fm.thisfile.basename) names = names[i:] + names[:i] else: # Fall back to old method with "os.walk" _, dirnames, filenames = next(os.walk(abs_dirname)) - names = [name for name in (dirnames + filenames) - if name.startswith(rel_basename)] - names.sort() + names = sorted([name for name in (dirnames + filenames) + if name.startswith(rel_basename)]) except (OSError, StopIteration): # os.walk found nothing pass @@ -370,7 +369,7 @@ class Command(FileManagerAware): 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))] + program.startswith(self.rest(1))] if not programs: return if len(programs) == 1: @@ -430,8 +429,8 @@ class FunctionCommand(Command): raise else: self.fm.notify("Bad arguments for %s.%s: %s, %s" % - (self._object_name, self._function_name, - repr(args), repr(keywords)), bad=True) + (self._object_name, self._function_name, + repr(args), repr(keywords)), bad=True) class AliasCommand(Command): diff --git a/ranger/colorschemes/default.py b/ranger/colorschemes/default.py index d04e5f6a..8d1958c7 100644 --- a/ranger/colorschemes/default.py +++ b/ranger/colorschemes/default.py @@ -35,7 +35,7 @@ class Default(ColorScheme): fg = blue elif context.executable and not \ any((context.media, context.container, - context.fifo, context.socket)): + context.fifo, context.socket)): attr |= bold fg = green if context.socket: diff --git a/ranger/colorschemes/snow.py b/ranger/colorschemes/snow.py index 90090854..95b4bfc3 100644 --- a/ranger/colorschemes/snow.py +++ b/ranger/colorschemes/snow.py @@ -6,6 +6,7 @@ from ranger.gui.color import * class Snow(ColorScheme): + def use(self, context): fg, bg, attr = default_colors diff --git a/ranger/colorschemes/solarized.py b/ranger/colorschemes/solarized.py index 8cdfb5ce..c3c0cad6 100644 --- a/ranger/colorschemes/solarized.py +++ b/ranger/colorschemes/solarized.py @@ -40,7 +40,7 @@ class Solarized(ColorScheme): fg = 33 elif context.executable and not \ any((context.media, context.container, - context.fifo, context.socket)): + context.fifo, context.socket)): fg = 64 attr |= bold if context.socket: diff --git a/ranger/config/commands.py b/ranger/config/commands.py index a384f427..92c9f385 100755 --- a/ranger/config/commands.py +++ b/ranger/config/commands.py @@ -107,6 +107,7 @@ class echo(Command): Display the text in the statusbar. """ + def execute(self): self.fm.notify(self.rest(1)) @@ -146,7 +147,7 @@ class cd(Command): rel_dest = self.rest(1) bookmarks = [v.path for v in self.fm.bookmarks.dct.values() - if rel_dest in v.path] + if rel_dest in v.path] # expand the tilde into the user directory if rel_dest.startswith('~'): @@ -167,7 +168,7 @@ class cd(Command): else: _, dirnames, _ = next(os.walk(abs_dirname)) dirnames = [dn for dn in dirnames - if dn.startswith(rel_basename)] + if dn.startswith(rel_basename)] except (OSError, StopIteration): # os.walk found nothing pass @@ -194,6 +195,7 @@ class chain(Command): Calls multiple commands at once, separated by semicolons. """ + def execute(self): for command in [s.strip() for s in self.rest(1).split(";")]: self.fm.execute_console(command) @@ -240,13 +242,14 @@ class shell(Command): class open_with(Command): + def execute(self): app, flags, mode = self._get_app_flags_mode(self.rest(1)) self.fm.execute_file( - files=[f for f in self.fm.thistab.get_selection()], - app=app, - flags=flags, - mode=mode) + files=[f for f in self.fm.thistab.get_selection()], + app=app, + flags=flags, + mode=mode) def tab(self, tabnum): return self._tab_through_executables() @@ -359,12 +362,12 @@ class set_(Command): return sorted(self.firstpart + setting for setting in settings) if not value and not name_done: return sorted(self.firstpart + setting for setting in settings - if setting.startswith(name)) + if setting.startswith(name)) if not value: # Cycle through colorschemes when name, but no value is specified if name == "colorscheme": return sorted(self.firstpart + colorscheme for colorscheme - in get_all_colorschemes()) + in get_all_colorschemes()) return self.firstpart + str(settings[name]) if bool in settings.types_of(name): if 'true'.startswith(value.lower()): @@ -374,7 +377,7 @@ class set_(Command): # Tab complete colorscheme values if incomplete value is present if name == "colorscheme": return sorted(self.firstpart + colorscheme for colorscheme - in get_all_colorschemes() if colorscheme.startswith(value)) + in get_all_colorschemes() if colorscheme.startswith(value)) class setlocal(set_): @@ -406,6 +409,7 @@ class setintag(setlocal): Sets an option for directories that are tagged with a specific tag. """ + def execute(self): tags = self.arg(1) self.shift() @@ -414,12 +418,14 @@ class setintag(setlocal): class default_linemode(Command): + def execute(self): import re from ranger.container.fsobject import FileSystemObject if len(self.args) < 2: - self.fm.notify("Usage: default_linemode [path=<regexp> | tag=<tag(s)>] <linemode>", bad=True) + self.fm.notify( + "Usage: default_linemode [path=<regexp> | tag=<tag(s)>] <linemode>", bad=True) # Extract options like "path=..." or "tag=..." from the command line arg1 = self.arg(1) @@ -438,7 +444,7 @@ class default_linemode(Command): linemode = self.rest(1) if linemode not in FileSystemObject.linemode_dict: self.fm.notify("Invalid linemode: %s; should be %s" % - (linemode, "/".join(FileSystemObject.linemode_dict)), bad=True) + (linemode, "/".join(FileSystemObject.linemode_dict)), bad=True) # Add the prepared entry to the fm.default_linemodes entry = [method, argument, linemode] @@ -492,6 +498,7 @@ class terminal(Command): Spawns an "x-terminal-emulator" starting in the current directory. """ + def execute(self): from ranger.ext.get_executables import get_term self.fm.run(get_term(), flags='f') @@ -523,7 +530,7 @@ class delete(Command): def is_directory_with_files(f): import os.path return (os.path.isdir(f) and not os.path.islink(f) - and len(os.listdir(f)) > 0) + and len(os.listdir(f)) > 0) if self.rest(1): files = shlex.split(self.rest(1)) @@ -543,8 +550,8 @@ class delete(Command): if confirm != 'never' and (confirm != 'multiple' or many_files): filename_list = files self.fm.ui.console.ask("Confirm deletion of: %s (y/N)" % - ', '.join(files), - partial(self._question_callback, files), ('n', 'N', 'y', 'Y')) + ', '.join(files), + partial(self._question_callback, files), ('n', 'N', 'y', 'Y')) else: # no need for a confirmation, just delete self.fm.delete(files) @@ -586,6 +593,7 @@ class console(Command): Open the console with the given command. """ + def execute(self): position = None if self.arg(1)[0:2] == '-p': @@ -612,9 +620,9 @@ class load_copy_buffer(Command): f = open(fname, 'r') except Exception: return self.fm.notify("Cannot open %s" % - (fname or self.copy_buffer_filename), bad=True) + (fname or self.copy_buffer_filename), bad=True) self.fm.copy_buffer = set(File(g) - for g in f.read().split("\n") if exists(g)) + for g in f.read().split("\n") if exists(g)) f.close() self.fm.ui.redraw_main_column() @@ -633,7 +641,7 @@ class save_copy_buffer(Command): f = open(fname, 'w') except Exception: return self.fm.notify("Cannot open %s" % - (fname or self.copy_buffer_filename), bad=True) + (fname or self.copy_buffer_filename), bad=True) f.write("\n".join(f.path for f in self.fm.copy_buffer)) f.close() @@ -854,6 +862,7 @@ class bulkrename(Command): This shell script is opened in an editor for you to review. After you close it, it will be executed. """ + def execute(self): import sys import tempfile @@ -886,7 +895,7 @@ class bulkrename(Command): script_lines.append("# This file will be executed when you close the editor.\n") script_lines.append("# Please double-check everything, clear the file to abort.\n") script_lines.extend("mv -vi -- %s %s\n" % (esc(old), esc(new)) - for old, new in zip(filenames, new_filenames) if old != new) + for old, new in zip(filenames, new_filenames) if old != new) script_content = "".join(script_lines) if py3: cmdfile.write(script_content.encode("utf-8")) @@ -982,7 +991,9 @@ class help_(Command): self.fm.dump_settings() c = self.fm.ui.console.ask("View [m]an page, [k]ey bindings," - " [c]ommands or [s]ettings? (press q to abort)", callback, list("mkcsq") + [chr(27)]) + " [c]ommands or [s]ettings? (press q to abort)", + callback, + list("mkcsq") + [chr(27)]) class copymap(Command): @@ -1133,20 +1144,20 @@ class scout(Command): Multiple flags can be combined. For example, ":scout -gpt" would create a :filter-like command using globbing. """ - AUTO_OPEN = 'a' - OPEN_ON_ENTER = 'e' - FILTER = 'f' - SM_GLOB = 'g' - IGNORE_CASE = 'i' - KEEP_OPEN = 'k' - SM_LETTERSKIP = 'l' - MARK = 'm' - UNMARK = 'M' - PERM_FILTER = 'p' - SM_REGEX = 'r' - SMART_CASE = 's' - AS_YOU_TYPE = 't' - INVERT = 'v' + AUTO_OPEN = 'a' + OPEN_ON_ENTER = 'e' + FILTER = 'f' + SM_GLOB = 'g' + IGNORE_CASE = 'i' + KEEP_OPEN = 'k' + SM_LETTERSKIP = 'l' + MARK = 'm' + UNMARK = 'M' + PERM_FILTER = 'p' + SM_REGEX = 'r' + SMART_CASE = 's' + AS_YOU_TYPE = 't' + INVERT = 'v' def __init__(self, *args, **kws): Command.__init__(self, *args, **kws) @@ -1155,10 +1166,10 @@ class scout(Command): def execute(self): thisdir = self.fm.thisdir - flags = self.flags + flags = self.flags pattern = self.pattern - regex = self._build_regex() - count = self._count(move=True) + regex = self._build_regex() + count = self._count(move=True) self.fm.thistab.last_search = regex self.fm.set_search_method(order="search") @@ -1219,8 +1230,8 @@ class scout(Command): if self._regex is not None: return self._regex - frmat = "%s" - flags = self.flags + frmat = "%s" + flags = self.flags pattern = self.pattern if pattern == ".": @@ -1262,8 +1273,8 @@ class scout(Command): return self._regex def _count(self, move=False, offset=0): - count = 0 - cwd = self.fm.thisdir + count = 0 + cwd = self.fm.thisdir pattern = self.pattern if not pattern or not cwd.files: @@ -1302,7 +1313,7 @@ class filter_inode_type(Command): l display links """ - FILTER_DIRS = 'd' + FILTER_DIRS = 'd' FILTER_FILES = 'f' FILTER_LINKS = 'l' @@ -1311,9 +1322,11 @@ class filter_inode_type(Command): self.fm.thisdir.inode_type_filter = None else: self.fm.thisdir.inode_type_filter = lambda file: ( - True if ((self.FILTER_DIRS in self.arg(1) and file.is_directory) or - (self.FILTER_FILES in self.arg(1) and file.is_file and not file.is_link) or - (self.FILTER_LINKS in self.arg(1) and file.is_link)) else False) + True if ( + (self.FILTER_DIRS in self.arg(1) and file.is_directory) or + (self.FILTER_FILES in self.arg(1) and file.is_file and not file.is_link) or + (self.FILTER_LINKS in self.arg(1) and file.is_link) + ) else False) self.fm.thisdir.refilter() @@ -1363,6 +1376,7 @@ class stage(Command): Stage selected files for the corresponding version control system """ + def execute(self): from ranger.ext.vcs import VcsError @@ -1383,6 +1397,7 @@ class unstage(Command): Unstage selected files for the corresponding version control system """ + def execute(self): from ranger.ext.vcs import VcsError diff --git a/ranger/container/bookmarks.py b/ranger/container/bookmarks.py index cb15efee..98de84ec 100644 --- a/ranger/container/bookmarks.py +++ b/ranger/container/bookmarks.py @@ -153,7 +153,7 @@ class Bookmarks(object): if os.access(self.path, os.W_OK): f = open(self.path + ".new", 'w') for key, value in self.dct.items(): - if type(key) == str\ + if isinstance(key, str)\ and key in ALLOWED_KEYS: try: f.write("{0}:{1}\n".format(str(key), str(value))) diff --git a/ranger/container/directory.py b/ranger/container/directory.py index f46f9d55..d48bd7ca 100644 --- a/ranger/container/directory.py +++ b/ranger/container/directory.py @@ -87,7 +87,7 @@ def mtimelevel(path, level): mtime = os.stat(path).st_mtime for dirpath, dirnames, filenames in walklevel(path, level): dirlist = [os.path.join("/", dirpath, d) for d in dirnames - if level == -1 or dirpath.count(os.path.sep) - path.count(os.path.sep) <= level] + if level == -1 or dirpath.count(os.path.sep) - path.count(os.path.sep) <= level] mtime = max(mtime, max([-1] + [os.stat(d).st_mtime for d in dirlist])) return mtime @@ -147,13 +147,13 @@ class Directory(FileSystemObject, Accumulator, Loadable): self.marked_items = list() for opt in ('sort_directories_first', 'sort', 'sort_reverse', - 'sort_case_insensitive'): + 'sort_case_insensitive'): self.settings.signal_bind('setopt.' + opt, - self.request_resort, weak=True, autosort=False) + self.request_resort, weak=True, autosort=False) for opt in ('hidden_filter', 'show_hidden'): self.settings.signal_bind('setopt.' + opt, - self.refilter, weak=True, autosort=False) + self.refilter, weak=True, autosort=False) self.settings = LocalSettings(path, self.settings) @@ -279,8 +279,12 @@ class Directory(FileSystemObject, Accumulator, Loadable): if self.flat: filelist = [] for dirpath, dirnames, filenames in walklevel(mypath, self.flat): - dirlist = [os.path.join("/", dirpath, d) for d in dirnames - if self.flat == -1 or dirpath.count(os.path.sep) - mypath.count(os.path.sep) <= self.flat] + dirlist = [ + os.path.join("/", dirpath, d) + for d in dirnames + if self.flat == -1 or + (dirpath.count(os.path.sep) - mypath.count(os.path.sep)) <= self.flat + ] filelist += dirlist filelist += [os.path.join("/", dirpath, f) for f in filenames] filenames = filelist @@ -288,7 +292,7 @@ class Directory(FileSystemObject, Accumulator, Loadable): else: filelist = os.listdir(mypath) filenames = [mypath + (mypath == '/' and fname or '/' + fname) - for fname in filelist] + for fname in filelist] self.load_content_mtime = os.stat(mypath).st_mtime if self._cumulative_size_calculated: @@ -476,7 +480,7 @@ class Directory(FileSystemObject, Accumulator, Loadable): cum = 0 realpath = os.path.realpath for dirpath, dirnames, filenames in os.walk(self.path, - onerror=lambda _: None): + onerror=lambda _: None): for file in filenames: try: if dirpath == self.path: @@ -492,7 +496,7 @@ class Directory(FileSystemObject, Accumulator, Loadable): self._cumulative_size_calculated = True self.size = self._get_cumulative_size() self.infostring = ('-> ' if self.is_link else ' ') + \ - human_readable(self.size) + human_readable(self.size) @lazy_property def size(self): @@ -554,10 +558,10 @@ class Directory(FileSystemObject, Accumulator, Loadable): if forward: generator = ((self.pointer + (x + offset)) % length - for x in range(length - 1)) + for x in range(length - 1)) else: generator = ((self.pointer - (x + offset)) % length - for x in range(length - 1)) + for x in range(length - 1)) for i in generator: _file = self.files[i] diff --git a/ranger/container/file.py b/ranger/container/file.py index 3058b9db..7bb15c84 100644 --- a/ranger/container/file.py +++ b/ranger/container/file.py @@ -6,7 +6,7 @@ from ranger.container.fsobject import FileSystemObject N_FIRST_BYTES = 256 control_characters = set(chr(n) for n in - set(range(0, 9)) | set(range(14, 32))) + set(range(0, 9)) | set(range(14, 32))) # Don't even try to preview files which match this regular expression: PREVIEW_BLACKLIST = re.compile(r""" diff --git a/ranger/container/fsobject.py b/ranger/container/fsobject.py index 9b312e6d..e4571ffb 100644 --- a/ranger/container/fsobject.py +++ b/ranger/container/fsobject.py @@ -2,13 +2,13 @@ # License: GNU GPL version 3, see the file "AUTHORS" for details. CONTAINER_EXTENSIONS = ('7z', 'ace', 'ar', 'arc', 'bz', 'bz2', 'cab', 'cpio', - 'cpt', 'deb', 'dgc', 'dmg', 'gz', 'iso', 'jar', 'msi', 'pkg', 'rar', - 'shar', 'tar', 'tbz', 'tgz', 'xar', 'xpi', 'xz', 'zip') + 'cpt', 'deb', 'dgc', 'dmg', 'gz', 'iso', 'jar', 'msi', 'pkg', 'rar', + 'shar', 'tar', 'tbz', 'tgz', 'xar', 'xpi', 'xz', 'zip') DOCUMENT_EXTENSIONS = ('cfg', 'css', 'cvs', 'djvu', 'doc', 'docx', 'gnm', - 'gnumeric', 'htm', 'html', 'md', 'odf', 'odg', 'odp', 'ods', 'odt', 'pdf', - 'pod', 'ps', 'rtf', 'sxc', 'txt', 'xls', 'xlw', 'xml', 'xslx') + 'gnumeric', 'htm', 'html', 'md', 'odf', 'odg', 'odp', 'ods', 'odt', 'pdf', + 'pod', 'ps', 'rtf', 'sxc', 'txt', 'xls', 'xlw', 'xml', 'xslx') DOCUMENT_BASENAMES = ('bugs', 'bugs', 'changelog', 'copying', 'credits', - 'hacking', 'help', 'install', 'license', 'readme', 'todo') + 'hacking', 'help', 'install', 'license', 'readme', 'todo') BAD_INFO = '?' @@ -40,39 +40,39 @@ def safe_path(path): class FileSystemObject(FileManagerAware, SettingsAware): (basename, - relative_path, - relative_path_lower, - dirname, - extension, - infostring, - path, - permissions, - stat) = (None,) * 9 + relative_path, + relative_path_lower, + dirname, + extension, + infostring, + path, + permissions, + stat) = (None,) * 9 (content_loaded, - force_load, - - is_device, - is_directory, - is_file, - is_fifo, - is_link, - is_socket, - - accessible, - exists, # "exists" currently means "link_target_exists" - loaded, - marked, - runnable, - stopped, - tagged, - - audio, - container, - document, - image, - media, - video) = (False,) * 21 + force_load, + + is_device, + is_directory, + is_file, + is_fifo, + is_link, + is_socket, + + accessible, + exists, # "exists" currently means "link_target_exists" + loaded, + marked, + runnable, + stopped, + tagged, + + audio, + container, + document, + image, + media, + video) = (False,) * 21 size = 0 @@ -165,7 +165,7 @@ class FileSystemObject(FileManagerAware, SettingsAware): for attr in ('video', 'audio', 'image', 'media', 'document', 'container'): exec("%s = lazy_property(" - "lambda self: self.set_mimetype() or self.%s)" % (attr, attr)) + "lambda self: self.set_mimetype() or self.%s)" % (attr, attr)) def __str__(self): """returns a string containing the absolute path""" @@ -191,8 +191,8 @@ class FileSystemObject(FileManagerAware, SettingsAware): self.audio = self._mimetype.startswith('audio') self.media = self.video or self.image or self.audio self.document = self._mimetype.startswith('text') \ - or self.extension in DOCUMENT_EXTENSIONS \ - or self.basename.lower() in DOCUMENT_BASENAMES + or self.extension in DOCUMENT_EXTENSIONS \ + or self.basename.lower() in DOCUMENT_BASENAMES self.container = self.extension in CONTAINER_EXTENSIONS keys = ('video', 'audio', 'image', 'media', 'document', 'container') diff --git a/ranger/container/history.py b/ranger/container/history.py index 4e06d4b2..082a951a 100644 --- a/ranger/container/history.py +++ b/ranger/container/history.py @@ -9,6 +9,7 @@ class HistoryEmptyException(Exception): class History(object): + def __init__(self, maxlen=None, unique=True): assert maxlen is not None, "maxlen cannot be None" if isinstance(maxlen, History): @@ -74,7 +75,7 @@ class History(object): future_length = len(self._history) - self._index - 1 self._history[:self._index] = list( - other_history._history[:other_history._index + 1]) + other_history._history[:other_history._index + 1]) if len(self._history) > self.maxlen: self._history = self._history[-self.maxlen:] diff --git a/ranger/container/settings.py b/ranger/container/settings.py index 1faf5860..9b6a3917 100644 --- a/ranger/container/settings.py +++ b/ranger/container/settings.py @@ -10,10 +10,10 @@ import os.path # Use these priority constants to trigger events at specific points in time # during processing of the signals "setopt" and "setopt.<some_setting_name>" -SIGNAL_PRIORITY_RAW = 2.0 # signal.value will be raw -SIGNAL_PRIORITY_SANITIZE = 1.0 # (Internal) post-processing signal.value -SIGNAL_PRIORITY_BETWEEN = 0.6 # sanitized signal.value, old fm.settings.XYZ -SIGNAL_PRIORITY_SYNC = 0.2 # (Internal) updating fm.settings.XYZ +SIGNAL_PRIORITY_RAW = 2.0 # signal.value will be raw +SIGNAL_PRIORITY_SANITIZE = 1.0 # (Internal) post-processing signal.value +SIGNAL_PRIORITY_BETWEEN = 0.6 # sanitized signal.value, old fm.settings.XYZ +SIGNAL_PRIORITY_SYNC = 0.2 # (Internal) updating fm.settings.XYZ SIGNAL_PRIORITY_AFTER_SYNC = 0.1 # after fm.settings.XYZ was updated @@ -98,6 +98,7 @@ DEFAULT_VALUES = { class Settings(SignalDispatcher, FileManagerAware): + def __init__(self): SignalDispatcher.__init__(self) self.__dict__['_localsettings'] = dict() @@ -106,11 +107,11 @@ class Settings(SignalDispatcher, FileManagerAware): self.__dict__['_settings'] = dict() for name in ALLOWED_SETTINGS: self.signal_bind('setopt.' + name, - self._sanitize, - priority=SIGNAL_PRIORITY_SANITIZE) + self._sanitize, + priority=SIGNAL_PRIORITY_SANITIZE) self.signal_bind('setopt.' + name, - self._raw_set_with_signal, - priority=SIGNAL_PRIORITY_SYNC) + self._raw_set_with_signal, + priority=SIGNAL_PRIORITY_SYNC) def _sanitize(self, signal): name, value = signal.setting, signal.value @@ -122,7 +123,7 @@ class Settings(SignalDispatcher, FileManagerAware): signal.value = [1, 1] else: signal.value = [int(i) if str(i).isdigit() else 1 - for i in value] + for i in value] elif name == 'colorscheme': _colorscheme_name_to_class(signal) @@ -139,7 +140,7 @@ class Settings(SignalDispatcher, FileManagerAware): if self._settings['preview_script'] is None and value \ and self.fm.ui.is_on: self.fm.notify("Preview script undefined or not found!", - bad=True) + bad=True) def set(self, name, value, path=None, tags=None): assert name in ALLOWED_SETTINGS, "No such setting: {0}!".format(name) @@ -151,7 +152,7 @@ class Settings(SignalDispatcher, FileManagerAware): assert not (tags and path), "Can't set a setting for path and tag " \ "at the same time!" kws = dict(setting=name, value=value, previous=previous, - path=path, tags=tags, fm=self.fm) + path=path, tags=tags, fm=self.fm) self.signal_emit('setopt', **kws) self.signal_emit('setopt.' + name, **kws) @@ -259,6 +260,7 @@ class Settings(SignalDispatcher, FileManagerAware): class LocalSettings(): + def __init__(self, path, parent): self.__dict__['_parent'] = parent self.__dict__['_path'] = path diff --git a/ranger/core/actions.py b/ranger/core/actions.py index 8bbf1b62..05529000 100644 --- a/ranger/core/actions.py +++ b/ranger/core/actions.py @@ -74,14 +74,14 @@ class Actions(FileManagerAware, SettingsAware): if mode == self.mode: return if mode == 'visual': - self._visual_start = self.thisdir.pointed_obj - self._visual_start_pos = self.thisdir.pointer + self._visual_start = self.thisdir.pointed_obj + self._visual_start_pos = self.thisdir.pointer self._previous_selection = set(self.thisdir.marked_items) self.mark_files(val=not self._visual_reverse, movedown=False) elif mode == 'normal': if self.mode == 'visual': - self._visual_start = None - self._visual_start_pos = None + self._visual_start = None + self._visual_start_pos = None self._previous_selection = None else: return @@ -91,11 +91,12 @@ class Actions(FileManagerAware, SettingsAware): def set_option_from_string(self, option_name, value, localpath=None, tags=None): if option_name not in ALLOWED_SETTINGS: raise ValueError("The option named `%s' does not exist" % - option_name) + option_name) if not isinstance(value, str): raise ValueError("The value for an option needs to be a string.") - self.settings.set(option_name, self._parse_option_value(option_name, value), localpath, tags) + self.settings.set(option_name, self._parse_option_value( + option_name, value), localpath, tags) def _parse_option_value(self, name, value): types = self.fm.settings.types_of(name) @@ -158,7 +159,7 @@ class Actions(FileManagerAware, SettingsAware): log.debug("Command notify invoked: [Bad: {0}, Text: '{1}']".format(bad, text)) if self.ui and self.ui.is_on: self.ui.status.notify(" ".join(text.split("\n")), - duration=duration, bad=bad) + duration=duration, bad=bad) else: print(text) @@ -209,12 +210,12 @@ class Actions(FileManagerAware, SettingsAware): cmd = cmd_class(string) if cmd.resolve_macros and _MacroTemplate.delimiter in string: macros = dict(('any%d' % i, key_to_string(char)) - for i, char in enumerate(wildcards)) + for i, char in enumerate(wildcards)) if 'any0' in macros: macros['any'] = macros['any0'] try: string = self.substitute_macros(string, additional=macros, - escape=cmd.escape_macros_for_shell) + escape=cmd.escape_macros_for_shell) except ValueError as e: if ranger.arg.debug: raise @@ -260,7 +261,7 @@ class Actions(FileManagerAware, SettingsAware): if self.fm.thistab.get_selection: macros['p'] = [os.path.join(self.fm.thisdir.path, fl.relative_path) - for fl in self.fm.thistab.get_selection()] + for fl in self.fm.thistab.get_selection()] macros['s'] = [fl.relative_path for fl in self.fm.thistab.get_selection()] else: macros['p'] = MACRO_FAIL @@ -273,7 +274,7 @@ class Actions(FileManagerAware, SettingsAware): if self.fm.thisdir.files: macros['t'] = [fl.relative_path for fl in self.fm.thisdir.files - if fl.realpath in (self.fm.tags or [])] + if fl.realpath in (self.fm.tags or [])] else: macros['t'] = MACRO_FAIL @@ -295,7 +296,7 @@ class Actions(FileManagerAware, SettingsAware): macros[i + 'd'] = tabdir.path if tabdir.get_selection(): macros[i + 'p'] = [os.path.join(tabdir.path, fl.relative_path) - for fl in tabdir.get_selection()] + for fl in tabdir.get_selection()] macros[i + 's'] = [fl.path for fl in tabdir.get_selection()] else: macros[i + 'p'] = MACRO_FAIL @@ -329,7 +330,7 @@ class Actions(FileManagerAware, SettingsAware): macros['F'] = MACRO_FAIL if next_tab_dir.get_selection(): macros['P'] = [os.path.join(next_tab.path, fl.path) - for fl in next_tab.get_selection()] + for fl in next_tab.get_selection()] macros['S'] = [fl.path for fl in next_tab.get_selection()] else: macros['P'] = MACRO_FAIL @@ -360,7 +361,7 @@ class Actions(FileManagerAware, SettingsAware): raise else: self.notify('Error in line `%s\':\n %s' % - (line, str(e)), bad=True) + (line, str(e)), bad=True) def execute_file(self, files, **kw): """Uses the "rifle" module to open/execute a file @@ -450,11 +451,11 @@ class Actions(FileManagerAware, SettingsAware): self.open_console('open_with ') elif direction.vertical() and cwd.files: newpos = direction.move( - direction=direction.down(), - override=narg, - maximum=len(cwd), - current=cwd.pointer, - pagesize=self.ui.browser.hei) + direction=direction.down(), + override=narg, + maximum=len(cwd), + current=cwd.pointer, + pagesize=self.ui.browser.hei) cwd.move(to=newpos) if self.mode == 'visual': try: @@ -464,7 +465,7 @@ class Actions(FileManagerAware, SettingsAware): startpos = min(self._visual_start_pos, len(cwd)) # The files between here and _visual_start_pos targets = set(cwd.files[min(startpos, newpos): - max(startpos, newpos) + 1]) + max(startpos, newpos) + 1]) # The selection before activating visual mode old = self._previous_selection # The current selection @@ -680,7 +681,7 @@ class Actions(FileManagerAware, SettingsAware): cwd = self.thisdir direction = Direction(dirarg) pos, selected = direction.select(lst=cwd.files, current=cwd.pointer, - pagesize=self.ui.termsize[0]) + pagesize=self.ui.termsize[0]) cwd.pointer = pos cwd.correct_pointer() for item in selected: @@ -743,7 +744,7 @@ class Actions(FileManagerAware, SettingsAware): def set_search_method(self, order, forward=True): if order in ('search', 'tag', 'size', 'mimetype', 'ctime', - 'mtime', 'atime'): + 'mtime', 'atime'): self.search_method = order # -------------------------- @@ -827,11 +828,11 @@ class Actions(FileManagerAware, SettingsAware): self.ui.browser.draw_info = [] return programs = [program for program in self.rifle.list_commands([target.path], - None)] + None)] if programs: num_digits = max((len(str(program[0])) for program in programs)) program_info = ['%s | %s' % (str(program[0]).rjust(num_digits), - program[1]) for program in programs] + program[1]) for program in programs] self.ui.browser.draw_info = program_info def hide_console_info(self): @@ -855,7 +856,7 @@ class Actions(FileManagerAware, SettingsAware): if not command.__doc__: self.notify("Command has no docstring. Try using python without -OO", - bad=True) + bad=True) return pager = self.ui.open_pager() @@ -905,12 +906,12 @@ class Actions(FileManagerAware, SettingsAware): if version_info[0] == 3: def sha1_encode(self, path): return os.path.join(ranger.arg.cachedir, - sha1(path.encode('utf-8', 'backslashreplace')) - .hexdigest()) + '.jpg' + sha1(path.encode('utf-8', 'backslashreplace')) + .hexdigest()) + '.jpg' else: def sha1_encode(self, path): return os.path.join(ranger.arg.cachedir, - sha1(path).hexdigest()) + '.jpg' + sha1(path).hexdigest()) + '.jpg' def get_preview(self, file, width, height): pager = self.ui.get_pager() @@ -937,18 +938,18 @@ class Actions(FileManagerAware, SettingsAware): return None found = data.get((-1, -1), data.get((width, -1), - data.get((-1, height), data.get((width, height), False)))) + data.get((-1, height), data.get((width, height), False)))) if found is False: try: stat_ = os.stat(self.settings.preview_script) except Exception: self.fm.notify("Preview Script `%s' doesn't exist!" % - self.settings.preview_script, bad=True) + self.settings.preview_script, bad=True) return None if not stat_.st_mode & S_IEXEC: self.fm.notify("Preview Script `%s' is not executable!" % - self.settings.preview_script, bad=True) + self.settings.preview_script, bad=True) return None data['loading'] = True @@ -969,9 +970,9 @@ class Actions(FileManagerAware, SettingsAware): return cacheimg loadable = CommandLoader(args=[self.settings.preview_script, - path, str(width), str(height), cacheimg, - str(self.settings.preview_images)], read=True, - silent=True, descr="Getting preview of %s" % path) + path, str(width), str(height), cacheimg, + str(self.settings.preview_images)], read=True, + silent=True, descr="Getting preview of %s" % path) def on_after(signal): exit = signal.process.poll() @@ -999,7 +1000,7 @@ class Actions(FileManagerAware, SettingsAware): except UnicodeDecodeError: f.close() f = codecs.open(path, 'r', encoding='latin-1', - errors='ignore') + errors='ignore') data[(-1, -1)] = f.read(1024 * 32) f.close() else: @@ -1095,7 +1096,7 @@ class Actions(FileManagerAware, SettingsAware): self.thistab = tab self.change_mode('normal') self.signal_emit('tab.change', old=previous_tab, - new=self.thistab) + new=self.thistab) break def tab_move(self, offset, narg=None): @@ -1265,8 +1266,8 @@ class Actions(FileManagerAware, SettingsAware): direction = Direction(dirarg) offset = 1 pos, selected = direction.select( - override=narg, lst=cwd.files, current=cwd.pointer, - pagesize=self.ui.termsize[0], offset=offset) + override=narg, lst=cwd.files, current=cwd.pointer, + pagesize=self.ui.termsize[0], offset=offset) cwd.pointer = pos cwd.correct_pointer() if mode == 'set': @@ -1329,9 +1330,9 @@ class Actions(FileManagerAware, SettingsAware): join(target_path, item)) else: if not exists(target_path) \ - or stat(source_path).st_ino != stat(target_path).st_ino: + or stat(source_path).st_ino != stat(target_path).st_ino: link(source_path, - next_available_filename(target_path)) + next_available_filename(target_path)) def paste(self, overwrite=False, append=False): """:paste diff --git a/ranger/core/fm.py b/ranger/core/fm.py index 5d630464..1a3a7cb3 100644 --- a/ranger/core/fm.py +++ b/ranger/core/fm.py @@ -81,7 +81,7 @@ class FM(Actions, SignalDispatcher): """If ui/bookmarks are None, they will be initialized here.""" self.tabs = dict((n + 1, Tab(path)) for n, path in - enumerate(self.start_paths)) + enumerate(self.start_paths)) tab_list = self._get_tab_list() if tab_list: self.current_tab = tab_list[0] @@ -101,8 +101,8 @@ class FM(Actions, SignalDispatcher): self.image_displayer = self._get_image_displayer() set_image_displayer() self.settings.signal_bind('setopt.preview_images_method', - set_image_displayer, - priority=settings.SIGNAL_PRIORITY_AFTER_SYNC) + set_image_displayer, + priority=settings.SIGNAL_PRIORITY_AFTER_SYNC) if not ranger.arg.clean and self.tags is None: self.tags = Tags(self.confpath('tagged')) @@ -115,9 +115,9 @@ class FM(Actions, SignalDispatcher): else: bookmarkfile = self.confpath('bookmarks') self.bookmarks = Bookmarks( - bookmarkfile=bookmarkfile, - bookmarktype=Directory, - autosave=self.settings.autosave_bookmarks) + bookmarkfile=bookmarkfile, + bookmarktype=Directory, + autosave=self.settings.autosave_bookmarks) self.bookmarks.load() self.ui.setup_curses() @@ -146,7 +146,7 @@ class FM(Actions, SignalDispatcher): images = [f.relative_path for f in self.thisdir.files if f.image] escaped_filenames = " ".join(shell_quote(f) - for f in images if "\x00" not in f) + for f in images if "\x00" not in f) if images and self.thisfile.relative_path in images and \ "$@" in command: @@ -155,27 +155,27 @@ class FM(Actions, SignalDispatcher): if command[0:5] == 'sxiv ': number = images.index(self.thisfile.relative_path) + 1 new_command = command.replace("sxiv ", - "sxiv -n %d " % number, 1) + "sxiv -n %d " % number, 1) if command[0:4] == 'feh ': new_command = command.replace("feh ", - "feh --start-at %s " % - shell_quote(self.thisfile.relative_path), 1) + "feh --start-at %s " % + shell_quote(self.thisfile.relative_path), 1) if command[0:4] == 'imv ': number = images.index(self.thisfile.relative_path) + 1 new_command = command.replace("imv ", - "imv -n %d " % number, 1) + "imv -n %d " % number, 1) if command[0:5] == 'pqiv ': number = images.index(self.thisfile.relative_path) new_command = command.replace("pqiv ", - "pqiv --action \"goto_file_byindex(%d)\" " % - number, 1) + "pqiv --action \"goto_file_byindex(%d)\" " % + number, 1) if new_command: command = "set -- %s; %s" % (escaped_filenames, - new_command) + new_command) return old_preprocessing_hook(command) self.rifle.hook_command_preprocessing = sxiv_workaround_hook @@ -185,8 +185,8 @@ class FM(Actions, SignalDispatcher): self.run = Runner(ui=self.ui, logfunc=mylogfunc, fm=self) self.settings.signal_bind('setopt.metadata_deep_search', - lambda signal: setattr(signal.fm.metadata, 'deep_search', - signal.value)) + lambda signal: setattr(signal.fm.metadata, 'deep_search', + signal.value)) def destroy(self): debug = ranger.arg.debug @@ -237,7 +237,7 @@ class FM(Actions, SignalDispatcher): self.thistab.thisdir = obj thisfile = property(_get_thisfile, _set_thisfile) - thisdir = property(_get_thisdir, _set_thisdir) + thisdir = property(_get_thisdir, _set_thisdir) def block_input(self, sec=0): self.input_blocked = sec != 0 @@ -284,17 +284,17 @@ class FM(Actions, SignalDispatcher): if which == 'scope' or which == 'all': copy('data/scope.sh', 'scope.sh') os.chmod(self.confpath('scope.sh'), - os.stat(self.confpath('scope.sh')).st_mode | stat.S_IXUSR) + os.stat(self.confpath('scope.sh')).st_mode | stat.S_IXUSR) if which in ('all', 'rifle', 'scope', 'commands', 'commands_full', 'rc'): sys.stderr.write("\n> Please note that configuration files may " - "change as ranger evolves.\n It's completely up to you to " - "keep them up to date.\n") + "change as ranger evolves.\n It's completely up to you to " + "keep them up to date.\n") if os.environ.get('RANGER_LOAD_DEFAULT_RC', 0) != 'FALSE': sys.stderr.write("\n> To stop ranger from loading " - "\033[1mboth\033[0m the default and your custom rc.conf,\n" - " please set the environment variable " - "\033[1mRANGER_LOAD_DEFAULT_RC\033[0m to " - "\033[1mFALSE\033[0m.\n") + "\033[1mboth\033[0m the default and your custom rc.conf,\n" + " please set the environment variable " + "\033[1mRANGER_LOAD_DEFAULT_RC\033[0m to " + "\033[1mFALSE\033[0m.\n") else: sys.stderr.write("Unknown config file `%s'\n" % which) @@ -379,10 +379,10 @@ class FM(Actions, SignalDispatcher): if zombie.poll() is not None: zombies.remove(zombie) - #gc_tick += 1 - #if gc_tick > ranger.TICKS_BEFORE_COLLECTING_GARBAGE: - #gc_tick = 0 - #self.garbage_collect(ranger.TIME_BEFORE_FILE_BECOMES_GARBAGE) + # gc_tick += 1 + # if gc_tick > ranger.TICKS_BEFORE_COLLECTING_GARBAGE: + # gc_tick = 0 + # self.garbage_collect(ranger.TIME_BEFORE_FILE_BECOMES_GARBAGE) except KeyboardInterrupt: # this only happens in --debug mode. By default, interrupts diff --git a/ranger/core/linemode.py b/ranger/core/linemode.py index c7839723..4b29443a 100644 --- a/ranger/core/linemode.py +++ b/ranger/core/linemode.py @@ -84,7 +84,7 @@ class PermissionsLinemode(LinemodeBase): def filetitle(self, file, metadata): return "%s %s %s %s" % (file.get_permission_string(), - file.user, file.group, file.relative_path) + file.user, file.group, file.relative_path) def infostring(self, file, metadata): return "" diff --git a/ranger/core/loader.py b/ranger/core/loader.py index 0cdc5368..191dbf36 100644 --- a/ranger/core/loader.py +++ b/ranger/core/loader.py @@ -95,12 +95,12 @@ class CopyLoader(Loadable, FileManagerAware): tag = self.fm.tags.tags[tf] self.fm.tags.remove(tf) self.fm.tags.tags[tf.replace(f.path, self.original_path - + '/' + f.basename)] = tag + + '/' + f.basename)] = tag self.fm.tags.dump() d = 0 for d in shutil_g.move(src=f.path, - dst=self.original_path, - overwrite=self.overwrite): + dst=self.original_path, + overwrite=self.overwrite): self.percent = float(done + d) / size * 100. yield done += d @@ -113,17 +113,18 @@ class CopyLoader(Loadable, FileManagerAware): if os.path.isdir(f.path) and not os.path.islink(f.path): d = 0 for d in shutil_g.copytree(src=f.path, - dst=os.path.join(self.original_path, f.basename), - symlinks=True, - overwrite=self.overwrite): + dst=os.path.join( + self.original_path, f.basename), + symlinks=True, + overwrite=self.overwrite): self.percent = float(done + d) / size * 100. yield done += d else: d = 0 for d in shutil_g.copy2(f.path, self.original_path, - symlinks=True, - overwrite=self.overwrite): + symlinks=True, + overwrite=self.overwrite): self.percent = float(done + d) / size * 100. yield done += d @@ -142,7 +143,7 @@ class CommandLoader(Loadable, SignalDispatcher, FileManagerAware): process = None def __init__(self, args, descr, silent=False, read=False, input=None, - kill_on_pause=False, popenArgs=None): + kill_on_pause=False, popenArgs=None): SignalDispatcher.__init__(self) Loadable.__init__(self, self.generate(), descr) self.args = args diff --git a/ranger/core/main.py b/ranger/core/main.py index b0e3b600..6d4fdaa6 100644 --- a/ranger/core/main.py +++ b/ranger/core/main.py @@ -84,8 +84,8 @@ def main(): return 1 elif os.path.isfile(target): sys.stderr.write("Warning: Using ranger as a file launcher is " - "deprecated.\nPlease use the standalone file launcher " - "'rifle' instead.\n") + "deprecated.\nPlease use the standalone file launcher " + "'rifle' instead.\n") from ranger.ext.rifle import Rifle fm = FM() @@ -107,7 +107,7 @@ def main(): if arg.list_unused_keys: from ranger.ext.keybinding_parser import (special_keys, - reversed_special_keys) + reversed_special_keys) maps = fm.ui.keymaps['browser'] for key in sorted(special_keys.values(), key=lambda x: str(x)): if key not in maps: @@ -174,7 +174,7 @@ def main(): profile.strip_dirs().sort_stats('cumulative').print_callees() if crash_traceback: print("ranger version: %s, executed with python %s" % - (ranger.__version__, sys.version.split()[0])) + (ranger.__version__, sys.version.split()[0])) print("Locale: %s" % '.'.join(str(s) for s in locale.getlocale())) try: print("Current file: %s" % filepath) @@ -182,7 +182,7 @@ def main(): pass print(crash_traceback) print("ranger crashed. " - "Please report this traceback at:") + "Please report this traceback at:") print("https://github.com/hut/ranger/issues") return 1 return 0 @@ -208,46 +208,46 @@ def parse_arguments(): parser = OptionParser(usage=USAGE, version=VERSION) parser.add_option('-d', '--debug', action='store_true', - help="activate debug mode") + help="activate debug mode") parser.add_option('-c', '--clean', action='store_true', - help="don't touch/require any config files. ") + help="don't touch/require any config files. ") parser.add_option('--logfile', type='string', metavar='file', - help="log file to use, '-' for stderr") + help="log file to use, '-' for stderr") parser.add_option('-r', '--confdir', type='string', - metavar='dir', default=default_confdir, - help="change the configuration directory. (%default)") + metavar='dir', default=default_confdir, + help="change the configuration directory. (%default)") parser.add_option('--copy-config', type='string', metavar='which', - help="copy the default configs to the local config directory. " - "Possible values: all, rc, rifle, commands, commands_full, scope") + help="copy the default configs to the local config directory. " + "Possible values: all, rc, rifle, commands, commands_full, scope") parser.add_option('--fail-unless-cd', action='store_true', - help=SUPPRESS_HELP) # COMPAT + help=SUPPRESS_HELP) # COMPAT parser.add_option('-m', '--mode', type='int', default=0, metavar='n', - help=SUPPRESS_HELP) # COMPAT + help=SUPPRESS_HELP) # COMPAT parser.add_option('-f', '--flags', type='string', default='', - metavar='string', help=SUPPRESS_HELP) # COMPAT + metavar='string', help=SUPPRESS_HELP) # COMPAT parser.add_option('--choosefile', type='string', metavar='TARGET', - help="Makes ranger act like a file chooser. When opening " - "a file, it will quit and write the name of the selected " - "file to TARGET.") + help="Makes ranger act like a file chooser. When opening " + "a file, it will quit and write the name of the selected " + "file to TARGET.") parser.add_option('--choosefiles', type='string', metavar='TARGET', - help="Makes ranger act like a file chooser for multiple files " - "at once. When opening a file, it will quit and write the name " - "of all selected files to TARGET.") + help="Makes ranger act like a file chooser for multiple files " + "at once. When opening a file, it will quit and write the name " + "of all selected files to TARGET.") parser.add_option('--choosedir', type='string', metavar='TARGET', - help="Makes ranger act like a directory chooser. When ranger quits" - ", it will write the name of the last visited directory to TARGET") + help="Makes ranger act like a directory chooser. When ranger quits" + ", it will write the name of the last visited directory to TARGET") parser.add_option('--selectfile', type='string', metavar='filepath', - help="Open ranger with supplied file selected.") + help="Open ranger with supplied file selected.") parser.add_option('--list-unused-keys', action='store_true', - help="List common keys which are not bound to any action.") + help="List common keys which are not bound to any action.") parser.add_option('--list-tagged-files', type='string', default=None, - metavar='tag', - help="List all files which are tagged with the given tag, default: *") + metavar='tag', + help="List all files which are tagged with the given tag, default: *") parser.add_option('--profile', action='store_true', - help="Print statistics of CPU usage on exit.") + help="Print statistics of CPU usage on exit.") parser.add_option('--cmd', action='append', type='string', metavar='COMMAND', - help="Execute COMMAND after the configuration has been read. " - "Use this option multiple times to run multiple commands.") + help="Execute COMMAND after the configuration has been read. " + "Use this option multiple times to run multiple commands.") options, positional = parser.parse_args() arg = OpenStruct(options.__dict__, targets=positional) @@ -256,8 +256,8 @@ def parse_arguments(): if arg.fail_unless_cd: # COMPAT sys.stderr.write("Warning: The option --fail-unless-cd is deprecated.\n" - "It was used to facilitate using ranger as a file launcher.\n" - "Now, please use the standalone file launcher 'rifle' instead.\n") + "It was used to facilitate using ranger as a file launcher.\n" + "Now, please use the standalone file launcher 'rifle' instead.\n") return arg @@ -310,7 +310,7 @@ def load_settings(fm, clean): try: plugindir = fm.confpath('plugins') plugins = [p[:-3] for p in os.listdir(plugindir) - if p.endswith('.py') and not p.startswith('_')] + if p.endswith('.py') and not p.startswith('_')] except Exception: pass else: @@ -350,7 +350,7 @@ def load_settings(fm, clean): fm.settings[setting] = getattr(module, setting) sys.stderr.write( -"""****************************** + """****************************** Warning: The configuration file 'options.py' is deprecated. Please move all settings to the file 'rc.conf', converting lines like "preview_files = False" diff --git a/ranger/core/metadata.py b/ranger/core/metadata.py index 299d2b85..5afa2995 100644 --- a/ranger/core/metadata.py +++ b/ranger/core/metadata.py @@ -20,6 +20,7 @@ from ranger.ext.openstruct import DefaultOpenStruct as ostruct class MetadataManager(object): + def __init__(self): # metadata_cache maps filenames to dicts containing their metadata self.metadata_cache = dict() @@ -124,7 +125,7 @@ class MetadataManager(object): entries = json.load(f) except ValueError: raise ValueError("Failed decoding JSON file %s" % - metafile) + metafile) self.metafile_cache[metafile] = entries return entries else: diff --git a/ranger/core/runner.py b/ranger/core/runner.py index 78d52764..d00ebc80 100644 --- a/ranger/core/runner.py +++ b/ranger/core/runner.py @@ -86,6 +86,7 @@ class Context(object): class Runner(object): + def __init__(self, ui=None, logfunc=None, fm=None): self.ui = ui self.fm = fm @@ -113,8 +114,8 @@ class Runner(object): self._log("Failed to suspend UI") def __call__(self, action=None, try_app_first=False, - app='default', files=None, mode=0, - flags='', wait=True, **popen_kws): + 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, @@ -128,8 +129,8 @@ class Runner(object): # 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) + 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!") @@ -211,7 +212,7 @@ class Runner(object): error = None process = None self.fm.signal_emit('runner.execute.before', - popen_kws=popen_kws, context=context) + popen_kws=popen_kws, context=context) try: if 'f' in context.flags: # This can fail and return False if os.fork() is not @@ -231,12 +232,12 @@ class Runner(object): press_enter() finally: self.fm.signal_emit('runner.execute.after', - popen_kws=popen_kws, context=context, error=error) + 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) + stdin=process.stdout) return process diff --git a/ranger/core/tab.py b/ranger/core/tab.py index fa40a12b..2a3bfeaf 100644 --- a/ranger/core/tab.py +++ b/ranger/core/tab.py @@ -12,6 +12,7 @@ from ranger.ext.signals import SignalDispatcher class Tab(FileManagerAware, SettingsAware): + def __init__(self, path): self.thisdir = None # Current Working Directory self._thisfile = None # Current File @@ -24,10 +25,10 @@ class Tab(FileManagerAware, SettingsAware): # weak references are not equal to the original object when tested with # "==", and this breaks _set_thisfile_from_signal and _on_tab_change. self.fm.signal_bind('move', self._set_thisfile_from_signal, - priority=settings.SIGNAL_PRIORITY_AFTER_SYNC, - weak=(sys.version_info[0] >= 3)) + priority=settings.SIGNAL_PRIORITY_AFTER_SYNC, + weak=(sys.version_info[0] >= 3)) self.fm.signal_bind('tab.change', self._on_tab_change, - weak=(sys.version_info[0] >= 3)) + weak=(sys.version_info[0] >= 3)) def _set_thisfile_from_signal(self, signal): if self == signal.tab: diff --git a/ranger/ext/accumulator.py b/ranger/ext/accumulator.py index 863a59df..9cc2f4e3 100644 --- a/ranger/ext/accumulator.py +++ b/ranger/ext/accumulator.py @@ -5,6 +5,7 @@ from ranger.ext.direction import Direction class Accumulator(object): + def __init__(self): self.pointer = 0 self.pointed_obj = None @@ -15,11 +16,11 @@ class Accumulator(object): if not lst: return self.pointer pointer = direction.move( - direction=direction.down(), - maximum=len(lst), - override=narg, - pagesize=self.get_height(), - current=self.pointer) + direction=direction.down(), + maximum=len(lst), + override=narg, + pagesize=self.get_height(), + current=self.pointer) self.pointer = pointer self.correct_pointer() return pointer diff --git a/ranger/ext/direction.py b/ranger/ext/direction.py index 787da1bf..b5fea6aa 100644 --- a/ranger/ext/direction.py +++ b/ranger/ext/direction.py @@ -20,6 +20,7 @@ False class Direction(dict): + def __init__(self, dictionary=None, **keywords): if dictionary is not None: dict.__init__(self, dictionary) @@ -104,7 +105,7 @@ class Direction(dict): self[key] = n def move(self, direction, override=None, minimum=0, maximum=9999, - current=0, pagesize=1, offset=0): + current=0, pagesize=1, offset=0): """Calculates the new position in a given boundary. Example: @@ -142,7 +143,7 @@ class Direction(dict): def select(self, lst, current, pagesize, override=None, offset=1): dest = self.move(direction=self.down(), override=override, - current=current, pagesize=pagesize, minimum=0, maximum=len(lst) + 1) + current=current, pagesize=pagesize, minimum=0, maximum=len(lst) + 1) selection = lst[min(current, dest):max(current, dest) + offset] return dest + offset - 1, selection diff --git a/ranger/ext/human_readable.py b/ranger/ext/human_readable.py index 31d5d279..50b95b99 100644 --- a/ranger/ext/human_readable.py +++ b/ranger/ext/human_readable.py @@ -19,7 +19,7 @@ def human_readable(byte, separator=' '): if byte <= 0: return '0' if byte < 2**10: - return '%d%sB' % (byte, separator) + return '%d%sB' % (byte, separator) if byte < 2**10 * 999: return '%.3g%sK' % (byte / 2**10.0, separator) if byte < 2**20: diff --git a/ranger/ext/img_display.py b/ranger/ext/img_display.py index 0e6b08fe..5b2632da 100644 --- a/ranger/ext/img_display.py +++ b/ranger/ext/img_display.py @@ -38,6 +38,7 @@ class ImgDisplayUnsupportedException(Exception): class ImageDisplayer(object): """Image display provider functions for drawing images in the terminal""" + def draw(self, path, start_x, start_y, width, height): """Draw an image at the given coordinates.""" pass @@ -66,7 +67,7 @@ class W3MImageDisplayer(ImageDisplayer): self.binary_path = None self.binary_path = self._find_w3mimgdisplay_executable() # may crash self.process = Popen([self.binary_path] + W3MIMGDISPLAY_OPTIONS, - stdin=PIPE, stdout=PIPE, universal_newlines=True) + stdin=PIPE, stdout=PIPE, universal_newlines=True) self.is_initialized = True def _find_w3mimgdisplay_executable(self): @@ -75,8 +76,8 @@ class W3MImageDisplayer(ImageDisplayer): if path is not None and os.path.exists(path): return path raise RuntimeError("No w3mimgdisplay executable found. Please set " - "the path manually by setting the %s environment variable. (see " - "man page)" % W3MIMGDISPLAY_ENV) + "the path manually by setting the %s environment variable. (see " + "man page)" % W3MIMGDISPLAY_ENV) def _get_font_dimensions(self): # Get the height and width of a character displayed in the terminal in @@ -89,7 +90,7 @@ class W3MImageDisplayer(ImageDisplayer): rows, cols, xpixels, ypixels = struct.unpack("HHHH", x) if xpixels == 0 and ypixels == 0: process = Popen([self.binary_path, "-test"], - stdout=PIPE, universal_newlines=True) + stdout=PIPE, universal_newlines=True) output, _ = process.communicate() output = output.split() xpixels, ypixels = int(output[0]), int(output[1]) @@ -103,7 +104,7 @@ class W3MImageDisplayer(ImageDisplayer): if not self.is_initialized or self.process.poll() is not None: self.initialize() self.process.stdin.write(self._generate_w3m_input(path, start_x, - start_y, width, height)) + start_y, width, height)) self.process.stdin.flush() self.process.stdout.readline() @@ -114,12 +115,12 @@ class W3MImageDisplayer(ImageDisplayer): fontw, fonth = self._get_font_dimensions() cmd = "6;{x};{y};{w};{h}\n4;\n3;\n".format( - x=int((start_x - 0.2) * fontw), - y=start_y * fonth, - # y = int((start_y + 1) * fonth), # (for tmux top status bar) - w=int((width + 0.4) * fontw), - h=height * fonth + 1) - # h = (height - 1) * fonth + 1) # (for tmux top status bar) + x=int((start_x - 0.2) * fontw), + y=start_y * fonth, + # y = int((start_y + 1) * fonth), # (for tmux top status bar) + w=int((width + 0.4) * fontw), + h=height * fonth + 1) + # h = (height - 1) * fonth + 1) # (for tmux top status bar) try: self.process.stdin.write(cmd) @@ -168,12 +169,12 @@ class W3MImageDisplayer(ImageDisplayer): height = max_height_pixels return "0;1;{x};{y};{w};{h};;;;;{filename}\n4;\n3;\n".format( - x=int((start_x - 0.2) * fontw), - y=start_y * fonth, - # y = (start_y + 1) * fonth, # (for tmux top status bar) - w=width, - h=height, - filename=path) + x=int((start_x - 0.2) * fontw), + y=start_y * fonth, + # y = (start_y + 1) * fonth, # (for tmux top status bar) + w=width, + h=height, + filename=path) def quit(self): if self.is_initialized and self.process and self.process.poll() is None: @@ -261,7 +262,7 @@ class ITerm2ImageDisplayer(ImageDisplayer, FileManagerAware): """Determine image size using imghdr""" file_handle = open(path, 'rb') file_header = file_handle.read(24) - image_type = imghdr.what(path) + image_type = imghdr.what(path) if len(file_header) != 24: file_handle.close() return 0, 0 diff --git a/ranger/ext/keybinding_parser.py b/ranger/ext/keybinding_parser.py index 6a4cbde9..441949f4 100644 --- a/ranger/ext/keybinding_parser.py +++ b/ranger/ext/keybinding_parser.py @@ -151,6 +151,7 @@ def _unbind_traverse(pointer, keys, pos=0): class KeyMaps(dict): + def __init__(self, keybuffer=None): dict.__init__(self) self.keybuffer = keybuffer @@ -195,7 +196,7 @@ class KeyMaps(dict): pointer = pointer[key] except Exception: raise KeyError("Tried to copy the keybinding `%s'," - " but it was not found." % source) + " but it was not found." % source) self.bind(context, target, copy.deepcopy(pointer)) def unbind(self, context, keys): @@ -206,9 +207,9 @@ class KeyMaps(dict): class KeyBuffer(object): - any_key = ANYKEY - passive_key = PASSIVE_ACTION - quantifier_key = QUANT_KEY + any_key = ANYKEY + passive_key = PASSIVE_ACTION + quantifier_key = QUANT_KEY exclude_from_anykey = [27] def __init__(self, keymap=None): diff --git a/ranger/ext/openstruct.py b/ranger/ext/openstruct.py index 6479d158..4c4f7f13 100644 --- a/ranger/ext/openstruct.py +++ b/ranger/ext/openstruct.py @@ -6,6 +6,7 @@ import collections class OpenStruct(dict): """The fusion of dict and struct""" + def __init__(self, *args, **keywords): dict.__init__(self, *args, **keywords) self.__dict__ = self @@ -13,6 +14,7 @@ class OpenStruct(dict): class DefaultOpenStruct(collections.defaultdict): """The fusion of dict and struct, with default values""" + def __init__(self, *args, **keywords): collections.defaultdict.__init__(self, None, *args, **keywords) self.__dict__ = self diff --git a/ranger/ext/rifle.py b/ranger/ext/rifle.py index 7d1bd59e..2577f468 100755 --- a/ranger/ext/rifle.py +++ b/ranger/ext/rifle.py @@ -142,11 +142,11 @@ class Rifle(object): # get paths for mimetype files self._mimetype_known_files = [ - os.path.expanduser("~/.mime.types")] + os.path.expanduser("~/.mime.types")] if __file__.endswith("ranger/ext/rifle.py"): # Add ranger's default mimetypes when run from ranger directory self._mimetype_known_files.append( - __file__.replace("ext/rifle.py", "data/mime.types")) + __file__.replace("ext/rifle.py", "data/mime.types")) def reload_config(self, config_file=None): """Replace the current configuration with the one in config_file""" @@ -170,7 +170,7 @@ class Rifle(object): self.rules.append((command, tests)) except Exception as e: self.hook_logger("Syntax error in %s line %d (%s)" % - (config_file, lineno, str(e))) + (config_file, lineno, str(e))) f.close() def _eval_condition(self, condition, files, label): @@ -253,7 +253,7 @@ class Rifle(object): if not self._mimetype: process = Popen(["file", "--mime-type", "-Lb", fname], - stdout=PIPE, stderr=PIPE) + stdout=PIPE, stderr=PIPE) mimetype, _ = process.communicate() self._mimetype = mimetype.decode(ENCODING).strip() return self._mimetype @@ -264,7 +264,7 @@ class Rifle(object): self._app_flags += flags self._app_flags = squash_flags(self._app_flags) filenames = "' '".join(f.replace("'", "'\\\''") for f in files - if "\x00" not in f) + if "\x00" not in f) return "set -- '%s'; %s" % (filenames, action) def list_commands(self, files, mimetype=None): @@ -362,7 +362,7 @@ class Rifle(object): term = 'urxvt' if term not in get_executables(): self.hook_logger("Can not determine terminal command. " - "Please set $TERMCMD manually.") + "Please set $TERMCMD manually.") # A fallback terminal that is likely installed: term = 'xterm' os.environ['TERMCMD'] = term @@ -388,7 +388,7 @@ def main(): default_conf_path = conf_path if not os.path.isfile(conf_path): conf_path = os.path.normpath(os.path.join(os.path.dirname(__file__), - '../config/rifle.conf')) + '../config/rifle.conf')) if not os.path.isfile(conf_path): try: # if ranger is installed, get the configuration from ranger @@ -402,16 +402,16 @@ def main(): from optparse import OptionParser parser = OptionParser(usage="%prog [-fhlpw] [files]", version=__version__) parser.add_option('-f', type="string", default="", metavar="FLAGS", - help="use additional flags: f=fork, r=root, t=terminal. " - "Uppercase flag negates respective lowercase flags.") + help="use additional flags: f=fork, r=root, t=terminal. " + "Uppercase flag negates respective lowercase flags.") parser.add_option('-l', action="store_true", - help="list possible ways to open the files (id:label:flags:command)") + help="list possible ways to open the files (id:label:flags:command)") parser.add_option('-p', type='string', default='0', metavar="KEYWORD", - help="pick a method to open the files. KEYWORD is either the " - "number listed by 'rifle -l' or a string that matches a label in " - "the configuration file") + help="pick a method to open the files. KEYWORD is either the " + "number listed by 'rifle -l' or a string that matches a label in " + "the configuration file") parser.add_option('-w', type='string', default=None, metavar="PROGRAM", - help="open the files with PROGRAM") + help="open the files with PROGRAM") options, positional = parser.parse_args() if not positional: parser.print_help() @@ -419,7 +419,7 @@ def main(): if not os.path.isfile(conf_path): sys.stderr.write("Could not find a configuration file.\n" - "Please create one at %s.\n" % default_conf_path) + "Please create one at %s.\n" % default_conf_path) raise SystemExit(1) if options.p.isdigit(): @@ -436,13 +436,13 @@ def main(): # Start up rifle rifle = Rifle(conf_path) rifle.reload_config() - #print(rifle.list_commands(sys.argv[1:])) + # print(rifle.list_commands(sys.argv[1:])) if options.l: for count, cmd, label, flags in rifle.list_commands(positional): print("%d:%s:%s:%s" % (count, label or '', flags, cmd)) else: result = rifle.execute(positional, number=number, label=label, - flags=options.f) + flags=options.f) if result == ASK_COMMAND: # TODO: implement interactive asking for file type? print("Unknown file type: %s" % rifle._get_mimetype(positional[0])) diff --git a/ranger/ext/shell_escape.py b/ranger/ext/shell_escape.py index d57ff339..97401cd6 100644 --- a/ranger/ext/shell_escape.py +++ b/ranger/ext/shell_escape.py @@ -4,9 +4,9 @@ """Functions to escape metacharacters of arguments for shell commands.""" META_CHARS = (' ', "'", '"', '`', '&', '|', ';', '#', - '$', '!', '(', ')', '[', ']', '<', '>', '\t') + '$', '!', '(', ')', '[', ']', '<', '>', '\t') UNESCAPABLE = set(map(chr, list(range(9)) + list(range(10, 32)) - + list(range(127, 256)))) + + list(range(127, 256)))) META_DICT = dict([(mc, '\\' + mc) for mc in META_CHARS]) diff --git a/ranger/ext/shutil_generatorized.py b/ranger/ext/shutil_generatorized.py index b990aded..8c5fc805 100644 --- a/ranger/ext/shutil_generatorized.py +++ b/ranger/ext/shutil_generatorized.py @@ -34,7 +34,7 @@ except NameError: def copyfileobj(fsrc, fdst, length=BLOCK_SIZE): """copy data from file-like object fsrc to file-like object fdst""" done = 0 - while 1: + while True: buf = fsrc.read(length) if not buf: break @@ -198,14 +198,14 @@ def copytree(src, dst, symlinks=False, ignore=None, overwrite=False): elif os.path.isdir(srcname): d = 0 for d in copytree(srcname, dstname, symlinks, - ignore, overwrite): + ignore, overwrite): yield done + d done += d else: # Will raise a SpecialFileError for unsupported file types d = 0 for d in copy2(srcname, dstname, - overwrite=overwrite, symlinks=symlinks): + overwrite=overwrite, symlinks=symlinks): yield done + d done += d # catch the Error from the recursive copytree so that we can diff --git a/ranger/ext/signals.py b/ranger/ext/signals.py index 4167277f..e35eab57 100644 --- a/ranger/ext/signals.py +++ b/ranger/ext/signals.py @@ -102,6 +102,7 @@ class SignalHandler: class SignalDispatcher(object): """This abstract class handles the binding and emitting of signals.""" + def __init__(self): self._signals = dict() diff --git a/ranger/ext/vcs/vcs.py b/ranger/ext/vcs/vcs.py index fa00777a..1d9687da 100644 --- a/ranger/ext/vcs/vcs.py +++ b/ranger/ext/vcs/vcs.py @@ -378,6 +378,7 @@ class VcsRoot(Vcs): # pylint: disable=abstract-method class VcsThread(threading.Thread): # pylint: disable=too-many-instance-attributes """VCS thread""" + def __init__(self, ui): super(VcsThread, self).__init__() self.daemon = True diff --git a/ranger/ext/widestring.py b/ranger/ext/widestring.py index 4890c20b..9d7b9d03 100644 --- a/ranger/ext/widestring.py +++ b/ranger/ext/widestring.py @@ -53,6 +53,7 @@ def string_to_charlist(string): class WideString(object): + def __init__(self, string, chars=None): try: self.string = str(string) @@ -81,7 +82,7 @@ class WideString(object): return WideString(self.string + string) elif isinstance(string, WideString): return WideString(self.string + string.string, - self.chars + string.chars) + self.chars + string.chars) def __radd__(self, string): """ @@ -92,7 +93,7 @@ class WideString(object): return WideString(string + self.string) elif isinstance(string, WideString): return WideString(string.string + self.string, - string.chars + self.chars) + string.chars + self.chars) def __str__(self): return self.string diff --git a/ranger/gui/ansi.py b/ranger/gui/ansi.py index 091406e9..24e378e2 100644 --- a/ranger/gui/ansi.py +++ b/ranger/gui/ansi.py @@ -82,7 +82,8 @@ def text_with_fg_bg_attr(ansi_text): elif n == 49: bg = -1 - elif n >= 90 and n <= 97: # 8 aixterm high intensity colors (light but not bold) + # 8 aixterm high intensity colors (light but not bold) + elif n >= 90 and n <= 97: fg = n - 90 + 8 elif n == 99: fg = -1 diff --git a/ranger/gui/bar.py b/ranger/gui/bar.py index 12c44488..bac8adb5 100644 --- a/ranger/gui/bar.py +++ b/ranger/gui/bar.py @@ -87,6 +87,7 @@ class Bar(object): class BarSide(list): + def __init__(self, base_color_tag): self.base_color_tag = base_color_tag @@ -112,6 +113,7 @@ class BarSide(list): class ColoredString(object): + def __init__(self, string, *lst): self.string = WideString(string) self.lst = lst diff --git a/ranger/gui/color.py b/ranger/gui/color.py index aa3b931c..62870ace 100644 --- a/ranger/gui/color.py +++ b/ranger/gui/color.py @@ -46,21 +46,21 @@ def get_color(fg, bg): return COLOR_PAIRS[key] -black = curses.COLOR_BLACK -blue = curses.COLOR_BLUE -cyan = curses.COLOR_CYAN -green = curses.COLOR_GREEN +black = curses.COLOR_BLACK +blue = curses.COLOR_BLUE +cyan = curses.COLOR_CYAN +green = curses.COLOR_GREEN magenta = curses.COLOR_MAGENTA -red = curses.COLOR_RED -white = curses.COLOR_WHITE -yellow = curses.COLOR_YELLOW +red = curses.COLOR_RED +white = curses.COLOR_WHITE +yellow = curses.COLOR_YELLOW default = -1 -normal = curses.A_NORMAL -bold = curses.A_BOLD -blink = curses.A_BLINK -reverse = curses.A_REVERSE -underline = curses.A_UNDERLINE -invisible = curses.A_INVIS +normal = curses.A_NORMAL +bold = curses.A_BOLD +blink = curses.A_BLINK +reverse = curses.A_REVERSE +underline = curses.A_UNDERLINE +invisible = curses.A_INVIS default_colors = (default, default, normal) diff --git a/ranger/gui/colorscheme.py b/ranger/gui/colorscheme.py index c861a8e8..02333828 100644 --- a/ranger/gui/colorscheme.py +++ b/ranger/gui/colorscheme.py @@ -52,9 +52,9 @@ class ColorScheme(object): context = Context(keys) color = self.use(context) if len(color) != 3 or not all(isinstance(value, int) - for value in color): + for value in color): raise ValueError("Bad Value from colorscheme. Need " - "a tuple of (foreground_color, background_color, attribute).") + "a tuple of (foreground_color, background_color, attribute).") return color @cached_function @@ -123,7 +123,7 @@ def _colorscheme_name_to_class(signal): if usecustom: allow_access_to_confdir(ranger.arg.confdir, True) scheme_module = getattr(__import__(scheme_supermodule, - globals(), locals(), [scheme_name], 0), scheme_name) + globals(), locals(), [scheme_name], 0), scheme_name) if usecustom: allow_access_to_confdir(ranger.arg.confdir, False) if hasattr(scheme_module, 'Scheme') \ diff --git a/ranger/gui/context.py b/ranger/gui/context.py index e577d2be..13598b16 100644 --- a/ranger/gui/context.py +++ b/ranger/gui/context.py @@ -2,28 +2,29 @@ # License: GNU GPL version 3, see the file "AUTHORS" for details. CONTEXT_KEYS = ['reset', 'error', 'badinfo', - 'in_browser', 'in_statusbar', 'in_titlebar', 'in_console', - 'in_pager', 'in_taskview', - 'active_pane', 'inactive_pane', - 'directory', 'file', 'hostname', - 'executable', 'media', 'link', 'fifo', 'socket', 'device', - 'video', 'audio', 'image', 'media', 'document', 'container', - 'selected', 'empty', 'main_column', 'message', 'background', - 'good', 'bad', - 'space', 'permissions', 'owner', 'group', 'mtime', 'nlink', - 'scroll', 'all', 'bot', 'top', 'percentage', 'filter', - 'flat', 'marked', 'tagged', 'tag_marker', 'cut', 'copied', - 'help_markup', # COMPAT - 'seperator', 'key', 'special', 'border', # COMPAT - 'title', 'text', 'highlight', 'bars', 'quotes', 'tab', 'loaded', - 'keybuffer', - 'infostring', - 'vcsfile', 'vcsremote', 'vcsinfo', 'vcscommit', 'vcsdate', - 'vcsconflict', 'vcschanged', 'vcsunknown', 'vcsignored', - 'vcsstaged', 'vcssync', 'vcsnone', 'vcsbehind', 'vcsahead', 'vcsdiverged'] + 'in_browser', 'in_statusbar', 'in_titlebar', 'in_console', + 'in_pager', 'in_taskview', + 'active_pane', 'inactive_pane', + 'directory', 'file', 'hostname', + 'executable', 'media', 'link', 'fifo', 'socket', 'device', + 'video', 'audio', 'image', 'media', 'document', 'container', + 'selected', 'empty', 'main_column', 'message', 'background', + 'good', 'bad', + 'space', 'permissions', 'owner', 'group', 'mtime', 'nlink', + 'scroll', 'all', 'bot', 'top', 'percentage', 'filter', + 'flat', 'marked', 'tagged', 'tag_marker', 'cut', 'copied', + 'help_markup', # COMPAT + 'seperator', 'key', 'special', 'border', # COMPAT + 'title', 'text', 'highlight', 'bars', 'quotes', 'tab', 'loaded', + 'keybuffer', + 'infostring', + 'vcsfile', 'vcsremote', 'vcsinfo', 'vcscommit', 'vcsdate', + 'vcsconflict', 'vcschanged', 'vcsunknown', 'vcsignored', + 'vcsstaged', 'vcssync', 'vcsnone', 'vcsbehind', 'vcsahead', 'vcsdiverged'] class Context(object): + def __init__(self, keys): # set all given keys to True d = self.__dict__ diff --git a/ranger/gui/displayable.py b/ranger/gui/displayable.py index 62eb5300..4c5133d4 100644 --- a/ranger/gui/displayable.py +++ b/ranger/gui/displayable.py @@ -105,7 +105,7 @@ class Displayable(FileManagerAware, CursesShortcuts): x and y should be absolute coordinates. """ return (x >= self.x and x < self.x + self.wid) and \ - (y >= self.y and y < self.y + self.hei) + (y >= self.y and y < self.y + self.hei) def click(self, event): """Called when a mouse key is pressed and self.focused is True. @@ -153,12 +153,12 @@ class Displayable(FileManagerAware, CursesShortcuts): if x < 0 or y < 0: self.fm.notify("Warning: Subwindow origin below zero for <%s> " - "(x = %d, y = %d)" % (self, x, y), bad=True) + "(x = %d, y = %d)" % (self, x, y), bad=True) if x + wid > maxx or y + hei > maxy: self.fm.notify("Warning: Subwindow size out of bounds for <%s> " - "(x = %d, y = %d, hei = %d, wid = %d)" % (self, - x, y, hei, wid), bad=True) + "(x = %d, y = %d, hei = %d, wid = %d)" % (self, + x, y, hei, wid), bad=True) window_is_cleared = False diff --git a/ranger/gui/mouse_event.py b/ranger/gui/mouse_event.py index 1d3ec970..be25463e 100644 --- a/ranger/gui/mouse_event.py +++ b/ranger/gui/mouse_event.py @@ -6,10 +6,10 @@ import curses class MouseEvent(object): PRESSED = [0, - curses.BUTTON1_PRESSED, - curses.BUTTON2_PRESSED, - curses.BUTTON3_PRESSED, - curses.BUTTON4_PRESSED] + curses.BUTTON1_PRESSED, + curses.BUTTON2_PRESSED, + curses.BUTTON3_PRESSED, + curses.BUTTON4_PRESSED] CTRL_SCROLLWHEEL_MULTIPLIER = 5 def __init__(self, getmouse): diff --git a/ranger/gui/ui.py b/ranger/gui/ui.py index f10bc0f2..cb8e5718 100644 --- a/ranger/gui/ui.py +++ b/ranger/gui/ui.py @@ -172,13 +172,13 @@ class UI(DisplayableContainer): keybuffer.add(key) self.fm.hide_bookmarks() self.browser.draw_hints = not keybuffer.finished_parsing \ - and keybuffer.finished_parsing_quantifier + and keybuffer.finished_parsing_quantifier if keybuffer.result is not None: try: self.fm.execute_console(keybuffer.result, - wildcards=keybuffer.wildcards, - quantifier=keybuffer.quantifier) + wildcards=keybuffer.wildcards, + quantifier=keybuffer.quantifier) finally: if keybuffer.finished_parsing: keybuffer.clear() @@ -330,10 +330,10 @@ class UI(DisplayableContainer): cwd = os.sep.join(split[1:]) try: fixed_cwd = cwd.encode('utf-8', 'surrogateescape'). \ - decode('utf-8', 'replace') + decode('utf-8', 'replace') sys.stdout.write("%sranger:%s%s" % - (curses.tigetstr('tsl').decode('latin-1'), fixed_cwd, - curses.tigetstr('fsl').decode('latin-1'))) + (curses.tigetstr('tsl').decode('latin-1'), fixed_cwd, + curses.tigetstr('fsl').decode('latin-1'))) sys.stdout.flush() except Exception: pass @@ -451,7 +451,7 @@ class UI(DisplayableContainer): self.redraw_window() else: raise ValueError("Attempting to set invalid viewmode `%s`, should " - "be one of `%s`." % (value, "`, `".join(self.ALLOWED_VIEWMODES))) + "be one of `%s`." % (value, "`, `".join(self.ALLOWED_VIEWMODES))) viewmode = property(_get_viewmode, _set_viewmode) diff --git a/ranger/gui/widgets/__init__.py b/ranger/gui/widgets/__init__.py index 9a95509c..ae515ae1 100644 --- a/ranger/gui/widgets/__init__.py +++ b/ranger/gui/widgets/__init__.py @@ -7,24 +7,24 @@ class Widget(Displayable): """A class for classification of widgets.""" vcsstatus_symb = { - 'conflict': ('X', ['vcsconflict']), + 'conflict': ('X', ['vcsconflict']), 'untracked': ('+', ['vcschanged']), - 'deleted': ('-', ['vcschanged']), - 'changed': ('*', ['vcschanged']), - 'staged': ('*', ['vcsstaged']), - 'ignored': ('·', ['vcsignored']), - 'sync': ('√', ['vcssync']), - 'none': (' ', []), - 'unknown': ('?', ['vcsunknown']), + 'deleted': ('-', ['vcschanged']), + 'changed': ('*', ['vcschanged']), + 'staged': ('*', ['vcsstaged']), + 'ignored': ('·', ['vcsignored']), + 'sync': ('√', ['vcssync']), + 'none': (' ', []), + 'unknown': ('?', ['vcsunknown']), } vcsremotestatus_symb = { 'diverged': ('Y', ['vcsdiverged']), - 'ahead': ('>', ['vcsahead']), - 'behind': ('<', ['vcsbehind']), - 'sync': ('=', ['vcssync']), - 'none': ('⌂', ['vcsnone']), - 'unknown': ('?', ['vcsunknown']), + 'ahead': ('>', ['vcsahead']), + 'behind': ('<', ['vcsbehind']), + 'sync': ('=', ['vcssync']), + 'none': ('⌂', ['vcsnone']), + 'unknown': ('?', ['vcsunknown']), } ellipsis = {False: '~', True: '…'} diff --git a/ranger/gui/widgets/browsercolumn.py b/ranger/gui/widgets/browsercolumn.py index 829809c0..3fde7f03 100644 --- a/ranger/gui/widgets/browsercolumn.py +++ b/ranger/gui/widgets/browsercolumn.py @@ -20,7 +20,7 @@ from ranger.gui.color import * class BrowserColumn(Pager): main_column = False display_infostring = False - display_vcsstate = True + display_vcsstate = True scroll_begin = 0 target = None last_redraw_time = -1 @@ -45,7 +45,7 @@ class BrowserColumn(Pager): self.original_level = level self.settings.signal_bind('setopt.display_size_in_main_column', - self.request_redraw, weak=True) + self.request_redraw, weak=True) def request_redraw(self): self.need_redraw = True @@ -303,7 +303,7 @@ class BrowserColumn(Pager): text = current_linemode.filetitle(drawn, metadata) if drawn.marked and (self.main_column or - self.settings.display_tags_in_all_columns): + self.settings.display_tags_in_all_columns): text = " " + text # Computing predisplay data. predisplay contains a list of lists @@ -366,13 +366,13 @@ class BrowserColumn(Pager): predisplay_left.append([' ' * space, []]) elif space < 0: raise Exception("Error: there is not enough space to write " - "the text. I have computed spaces wrong.") + "the text. I have computed spaces wrong.") # Computing display data. Now we compute the display_data list # ready to display in curses. It is a list of lists [string, attr] this_color = base_color + list(drawn.mimetype_tuple) + \ - self._draw_directory_color(i, drawn, copied) + self._draw_directory_color(i, drawn, copied) display_data = [] drawn.display_data[key] = display_data @@ -510,11 +510,11 @@ class BrowserColumn(Pager): if projected > upper_limit: return min(dirsize - winsize, - original + (projected - upper_limit)) + original + (projected - upper_limit)) if projected < upper_limit: return max(0, - original - (lower_limit - projected)) + original - (lower_limit - projected)) return original diff --git a/ranger/gui/widgets/console.py b/ranger/gui/widgets/console.py index db04a9c8..85fb92a3 100644 --- a/ranger/gui/widgets/console.py +++ b/ranger/gui/widgets/console.py @@ -269,10 +269,10 @@ class Console(Widget): # Ensure that the pointer is moved utf-char-wise if self.fm.py3: self.pos = direction.move( - direction=direction.right(), - minimum=0, - maximum=len(self.line) + 1, - current=self.pos) + direction=direction.right(), + minimum=0, + maximum=len(self.line) + 1, + current=self.pos) else: if self.fm.py3: uc = list(self.line) @@ -281,10 +281,10 @@ class Console(Widget): uc = list(self.line.decode('utf-8', 'ignore')) upos = len(self.line[:self.pos].decode('utf-8', 'ignore')) newupos = direction.move( - direction=direction.right(), - minimum=0, - maximum=len(uc) + 1, - current=upos) + direction=direction.right(), + minimum=0, + maximum=len(uc) + 1, + current=upos) self.pos = len(''.join(uc[:newupos]).encode('utf-8', 'ignore')) def move_word(self, **keywords): diff --git a/ranger/gui/widgets/pager.py b/ranger/gui/widgets/pager.py index 0c81079b..979c6d62 100644 --- a/ranger/gui/widgets/pager.py +++ b/ranger/gui/widgets/pager.py @@ -81,7 +81,7 @@ class Pager(Widget): if not self.image: line_gen = self._generate_lines( - starty=self.scroll_begin, startx=self.startx) + starty=self.scroll_begin, startx=self.startx) for line, i in zip(line_gen, range(self.hei)): self._draw_line(i, line) @@ -94,7 +94,7 @@ class Pager(Widget): self.need_redraw_image = False try: self.fm.image_displayer.draw(self.image, self.x, self.y, - self.wid, self.hei) + self.wid, self.hei) except ImgDisplayUnsupportedException: self.fm.settings.preview_images = False except Exception as e: @@ -121,31 +121,31 @@ class Pager(Widget): direction = Direction(kw) if direction.horizontal(): self.startx = direction.move( - direction=direction.right(), - override=narg, - maximum=self.max_width, - current=self.startx, - pagesize=self.wid, - offset=-self.wid + 1) + direction=direction.right(), + override=narg, + maximum=self.max_width, + current=self.startx, + pagesize=self.wid, + offset=-self.wid + 1) if direction.vertical(): movement = dict( - direction=direction.down(), - override=narg, - current=self.scroll_begin, - pagesize=self.hei, - offset=-self.hei + 1) + direction=direction.down(), + override=narg, + current=self.scroll_begin, + pagesize=self.hei, + offset=-self.hei + 1) if self.source_is_stream: # For streams, we first pretend that the content ends much later, # in case there are still unread lines. desired_position = direction.move( - maximum=len(self.lines) + 9999, - **movement) + maximum=len(self.lines) + 9999, + **movement) # Then, read the new lines as needed to produce a more accurate # maximum for the movement: self._get_line(desired_position + self.hei) self.scroll_begin = direction.move( - maximum=len(self.lines), - **movement) + maximum=len(self.lines), + **movement) def press(self, key): self.fm.ui.keymaps.use_keymap('pager') diff --git a/ranger/gui/widgets/statusbar.py b/ranger/gui/widgets/statusbar.py index 0ac62d86..87cd7c53 100644 --- a/ranger/gui/widgets/statusbar.py +++ b/ranger/gui/widgets/statusbar.py @@ -37,7 +37,7 @@ class StatusBar(Widget): Widget.__init__(self, win) self.column = column self.settings.signal_bind('setopt.display_size_in_status_bar', - self.request_redraw, weak=True) + self.request_redraw, weak=True) def request_redraw(self): self.need_redraw = True @@ -111,7 +111,7 @@ class StatusBar(Widget): def _draw_message(self): self.win.erase() self.color('in_statusbar', 'message', - self.msg.bad and 'bad' or 'good') + self.msg.bad and 'bad' or 'good') self.addnstr(0, 0, self.msg.text, self.wid) def _draw_hint(self): @@ -262,7 +262,7 @@ class StatusBar(Widget): right.add(human_readable(target.disk_usage, separator='')) else: sumsize = sum(f.size for f in target.marked_items if not - f.is_directory or f._cumulative_size_calculated) + f.is_directory or f._cumulative_size_calculated) right.add(human_readable(sumsize, separator='')) right.add("/" + str(len(target.marked_items))) else: @@ -282,7 +282,7 @@ class StatusBar(Widget): right.add('Mrk', base, 'marked') elif len(target.files): right.add(str(target.pointer + 1) + '/' - + str(len(target.files)) + ' ', base) + + str(len(target.files)) + ' ', base) if max_pos <= 0: right.add('All', base, 'all') elif pos == 0: @@ -291,7 +291,7 @@ class StatusBar(Widget): right.add('Bot', base, 'bot') else: right.add('{0:0.0%}'.format(float(pos) / max_pos), - base, 'percentage') + base, 'percentage') else: right.add('0/0 All', base, 'all') diff --git a/ranger/gui/widgets/taskview.py b/ranger/gui/widgets/taskview.py index f05606c9..f72de94a 100644 --- a/ranger/gui/widgets/taskview.py +++ b/ranger/gui/widgets/taskview.py @@ -53,7 +53,7 @@ class TaskView(Widget, Accumulator): if obj.progressbar_supported and obj.percent >= 0 \ and obj.percent <= 100: self.addstr(y, 0, "%3.2f%% - %s" % - (obj.percent, descr), self.wid) + (obj.percent, descr), self.wid) wid = int(self.wid / 100.0 * obj.percent) self.color_at(y, 0, self.wid, tuple(clr)) self.color_at(y, 0, wid, tuple(clr), 'loaded') diff --git a/ranger/gui/widgets/titlebar.py b/ranger/gui/widgets/titlebar.py index d46fec62..283da3a8 100644 --- a/ranger/gui/widgets/titlebar.py +++ b/ranger/gui/widgets/titlebar.py @@ -42,7 +42,7 @@ class TitleBar(Widget): if self.wid > 2: self.color('in_titlebar', 'throbber') self.addnstr(self.y, self.wid - 2 - self.tab_width, - self.throbber, 1) + self.throbber, 1) def click(self, event): """Handle a MouseEvent""" diff --git a/ranger/gui/widgets/view_base.py b/ranger/gui/widgets/view_base.py index a50fb5ce..bc9a8260 100644 --- a/ranger/gui/widgets/view_base.py +++ b/ranger/gui/widgets/view_base.py @@ -53,7 +53,7 @@ class ViewBase(Widget, DisplayableContainer): try: x = self.main_column.x y = self.main_column.y + self.main_column.target.pointer\ - - self.main_column.scroll_begin + - self.main_column.scroll_begin self.fm.ui.win.move(y, x) except Exception: pass @@ -65,8 +65,8 @@ class ViewBase(Widget, DisplayableContainer): self.need_clear = True sorted_bookmarks = sorted((item for item in self.fm.bookmarks - if self.fm.settings.show_hidden_bookmarks or - '/.' not in item[1].path), key=lambda t: t[0].lower()) + if self.fm.settings.show_hidden_bookmarks or + '/.' not in item[1].path), key=lambda t: t[0].lower()) hei = min(self.hei - 1, len(sorted_bookmarks)) ystart = self.hei - hei @@ -115,7 +115,7 @@ class ViewBase(Widget, DisplayableContainer): hei = min(self.hei - 1, len(hints)) ystart = self.hei - hei self.addnstr(ystart - 1, 0, "key command".ljust(self.wid), - self.wid) + self.wid) try: self.win.chgat(ystart - 1, 0, curses.A_UNDERLINE) except Exception: diff --git a/ranger/gui/widgets/view_miller.py b/ranger/gui/widgets/view_miller.py index 42013fe9..b4db5b08 100644 --- a/ranger/gui/widgets/view_miller.py +++ b/ranger/gui/widgets/view_miller.py @@ -33,11 +33,11 @@ class ViewMiller(ViewBase): for option in ('preview_directories', 'preview_files'): self.settings.signal_bind('setopt.' + option, - self._request_clear_if_has_borders, weak=True) + self._request_clear_if_has_borders, weak=True) self.settings.signal_bind('setopt.column_ratios', self.request_clear) self.settings.signal_bind('setopt.column_ratios', self.rebuild, - priority=settings.SIGNAL_PRIORITY_AFTER_SYNC) + priority=settings.SIGNAL_PRIORITY_AFTER_SYNC) self.old_draw_borders = self.settings.draw_borders @@ -60,8 +60,8 @@ class ViewMiller(ViewBase): last = 0.1 if self.settings.padding_right else 0 if len(self.ratios) >= 2: self.stretch_ratios = self.ratios[:-2] + \ - ((self.ratios[-2] + self.ratios[-1] * 1.0 - last), - (self.ratios[-1] * last)) + ((self.ratios[-2] + self.ratios[-1] * 1.0 - last), + (self.ratios[-1] * last)) offset = 1 - len(ratios) if self.preview: @@ -132,7 +132,7 @@ class ViewMiller(ViewBase): try: win.hline(0, left_start, curses.ACS_HLINE, right_end - left_start) win.hline(self.hei - 1, left_start, curses.ACS_HLINE, - right_end - left_start) + right_end - left_start) win.vline(1, left_start, curses.ACS_VLINE, self.hei - 2) except _curses.error: pass @@ -214,16 +214,16 @@ class ViewMiller(ViewBase): if i == last_i - 1: self.pager.resize(pad, left, hei - pad * 2, - max(1, self.wid - left - pad)) + max(1, self.wid - left - pad)) if cut_off: self.columns[i].resize(pad, left, hei - pad * 2, - max(1, self.wid - left - pad)) + max(1, self.wid - left - pad)) continue try: self.columns[i].resize(pad, left, hei - pad * 2, - max(1, wid - 1)) + max(1, wid - 1)) except KeyError: pass @@ -257,7 +257,7 @@ class ViewMiller(ViewBase): # Show the preview column when it has a preview but has # been hidden (e.g. because of padding_right = False) if not self.columns[-1].visible and self.columns[-1].has_preview() \ - and not self.pager.visible: + and not self.pager.visible: self.columns[-1].visible = True if self.preview and self.is_collapsed != self._collapse(): diff --git a/ranger/gui/widgets/view_multipane.py b/ranger/gui/widgets/view_multipane.py index f8efd80f..abeb31fe 100644 --- a/ranger/gui/widgets/view_multipane.py +++ b/ranger/gui/widgets/view_multipane.py @@ -6,6 +6,7 @@ from ranger.gui.widgets.browsercolumn import BrowserColumn class ViewMultipane(ViewBase): + def __init__(self, win): ViewBase.__init__(self, win) diff --git a/setup.py b/setup.py index 6838cdc0..ce0631f0 100755 --- a/setup.py +++ b/setup.py @@ -39,8 +39,12 @@ if __name__ == '__main__': ('share/doc/ranger/tools', _findall('doc/tools')), ('share/doc/ranger/examples', _findall('examples')), ], - package_data={'ranger': ['data/*', 'config/rc.conf', - 'config/rifle.conf']}, + package_data={ + 'ranger': [ + 'data/*', 'config/rc.conf', + 'config/rifle.conf', + ], + }, packages=('ranger', 'ranger.api', 'ranger.colorschemes', |