[gedit-plugins] Use PEP whitespaces
- From: Jesse van den Kieboom <jessevdk src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [gedit-plugins] Use PEP whitespaces
- Date: Thu, 16 Aug 2012 08:41:34 +0000 (UTC)
commit 5941ac2acdca09c6010456907f5c517292b5a003
Author: Jesse van den Kieboom <jesse vandenkieboom epfl ch>
Date: Thu Aug 16 10:41:16 2012 +0200
Use PEP whitespaces
plugins/commander/commander/__init__.py | 36 +-
plugins/commander/commander/commands/__init__.py | 600 ++++++------
.../commander/commander/commands/accel_group.py | 144 ++--
plugins/commander/commander/commands/completion.py | 246 +++---
plugins/commander/commander/commands/exceptions.py | 10 +-
plugins/commander/commander/commands/method.py | 147 ++--
plugins/commander/commander/commands/module.py | 173 ++--
plugins/commander/commander/commands/result.py | 54 +-
.../commander/commands/rollbackimporter.py | 41 +-
plugins/commander/commander/entry.py | 1072 ++++++++++----------
plugins/commander/commander/history.py | 114 ++-
plugins/commander/commander/info.py | 446 ++++----
plugins/commander/commander/modules.py | 2 +
plugins/commander/commander/transparentwindow.py | 74 +-
plugins/commander/commander/utils.py | 58 +-
plugins/commander/commander/windowactivatable.py | 86 +-
16 files changed, 1663 insertions(+), 1640 deletions(-)
---
diff --git a/plugins/commander/commander/__init__.py b/plugins/commander/commander/__init__.py
index badc7d2..5f35ca8 100644
--- a/plugins/commander/commander/__init__.py
+++ b/plugins/commander/commander/__init__.py
@@ -25,33 +25,35 @@ import sys
path = os.path.dirname(__file__)
if not path in sys.path:
- sys.path.insert(0, path)
+ sys.path.insert(0, path)
from windowactivatable import WindowActivatable
import commander.commands as commands
from gi.repository import GObject, GLib, Gedit
class CommanderPlugin(GObject.Object, Gedit.AppActivatable):
- __gtype_name__ = "CommanderPlugin"
+ __gtype_name__ = "CommanderPlugin"
- app = GObject.property(type=Gedit.App)
+ app = GObject.property(type=Gedit.App)
- def __init__(self):
- GObject.Object.__init__(self)
+ def __init__(self):
+ GObject.Object.__init__(self)
- def do_activate(self):
- self._path = os.path.dirname(__file__)
+ def do_activate(self):
+ self._path = os.path.dirname(__file__)
- if not self._path in sys.path:
- sys.path.insert(0, self._path)
+ if not self._path in sys.path:
+ sys.path.insert(0, self._path)
- commands.Commands().set_dirs([
- os.path.join(GLib.get_user_config_dir(), 'gedit/commander/modules'),
- os.path.join(self.plugin_info.get_data_dir(), 'modules')
- ])
+ commands.Commands().set_dirs([
+ os.path.join(GLib.get_user_config_dir(), 'gedit/commander/modules'),
+ os.path.join(self.plugin_info.get_data_dir(), 'modules')
+ ])
- def deactivate(self):
- commands.Commands().stop()
+ def deactivate(self):
+ commands.Commands().stop()
- if self._path in sys.path:
- sys.path.remove(self._path)
+ if self._path in sys.path:
+ sys.path.remove(self._path)
+
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/commands/__init__.py b/plugins/commander/commander/commands/__init__.py
index d30ca0f..feeab1c 100644
--- a/plugins/commander/commander/commands/__init__.py
+++ b/plugins/commander/commander/commands/__init__.py
@@ -41,420 +41,422 @@ __all__ = ['is_commander_module', 'Commands', 'Accelerator']
import commander.modules
def attrs(**kwargs):
- def generator(f):
- for k in kwargs:
- setattr(f, k, kwargs[k])
+ def generator(f):
+ for k in kwargs:
+ setattr(f, k, kwargs[k])
- return f
+ return f
- return generator
+ return generator
def autocomplete(d={}, **kwargs):
- ret = {}
+ ret = {}
- for dic in (d, kwargs):
- for k in dic:
- if type(dic[k]) == types.FunctionType:
- ret[k] = dic[k]
+ for dic in (d, kwargs):
+ for k in dic:
+ if type(dic[k]) == types.FunctionType:
+ ret[k] = dic[k]
- return attrs(autocomplete=ret)
+ return attrs(autocomplete=ret)
def accelerator(*args, **kwargs):
- return attrs(accelerator=Accelerator(args, kwargs))
+ return attrs(accelerator=Accelerator(args, kwargs))
def is_commander_module(mod):
- if type(mod) == types.ModuleType:
- return mod and ('__commander_module__' in mod.__dict__)
- else:
- mod = str(mod)
- return mod.endswith('.py') or (os.path.isdir(mod) and os.path.isfile(os.path.join(mod, '__init__.py')))
+ if type(mod) == types.ModuleType:
+ return mod and ('__commander_module__' in mod.__dict__)
+ else:
+ mod = str(mod)
+ return mod.endswith('.py') or (os.path.isdir(mod) and os.path.isfile(os.path.join(mod, '__init__.py')))
class Singleton(object):
- _instance = None
+ _instance = None
- def __new__(cls, *args, **kwargs):
- if not cls._instance:
- cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
- cls._instance.__init_once__()
+ def __new__(cls, *args, **kwargs):
+ if not cls._instance:
+ cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
+ cls._instance.__init_once__()
- return cls._instance
+ return cls._instance
class Commands(Singleton):
- class Continuated:
- def __init__(self, generator):
- self.generator = generator
- self.retval = None
+ class Continuated:
+ def __init__(self, generator):
+ self.generator = generator
+ self.retval = None
- def autocomplete_func(self):
- if self.retval == result.Result.PROMPT:
- return self.retval.autocomplete
- else:
- return {}
+ def autocomplete_func(self):
+ if self.retval == result.Result.PROMPT:
+ return self.retval.autocomplete
+ else:
+ return {}
- def args(self):
- return [], True
+ def args(self):
+ return [], True
- class State:
- def __init__(self):
- self.clear()
+ class State:
+ def __init__(self):
+ self.clear()
- def clear(self):
- self.stack = []
+ def clear(self):
+ self.stack = []
- def top(self):
- return self.stack[0]
+ def top(self):
+ return self.stack[0]
- def run(self, ret):
- ct = self.top()
+ def run(self, ret):
+ ct = self.top()
- if ret:
- ct.retval = ct.generator.send(ret)
- else:
- ct.retval = ct.generator.next()
+ if ret:
+ ct.retval = ct.generator.send(ret)
+ else:
+ ct.retval = ct.generator.next()
- return ct.retval
+ return ct.retval
- def push(self, gen):
- self.stack.insert(0, Commands.Continuated(gen))
+ def push(self, gen):
+ self.stack.insert(0, Commands.Continuated(gen))
- def pop(self):
- if not self.stack:
- return
+ def pop(self):
+ if not self.stack:
+ return
- try:
- self.stack[0].generator.close()
- except GeneratorExit:
- pass
+ try:
+ self.stack[0].generator.close()
+ except GeneratorExit:
+ pass
- del self.stack[0]
+ del self.stack[0]
- def __len__(self):
- return len(self.stack)
+ def __len__(self):
+ return len(self.stack)
- def __nonzero__(self):
- return len(self) != 0
+ def __nonzero__(self):
+ return len(self) != 0
- def __init_once__(self):
- self._modules = None
- self._dirs = []
- self._monitors = []
- self._accel_group = None
+ def __init_once__(self):
+ self._modules = None
+ self._dirs = []
+ self._monitors = []
+ self._accel_group = None
- self._timeouts = {}
+ self._timeouts = {}
- self._stack = []
+ self._stack = []
- def set_dirs(self, dirs):
- self._dirs = dirs
+ def set_dirs(self, dirs):
+ self._dirs = dirs
- def stop(self):
- for mon in self._monitors:
- mon.cancel()
+ def stop(self):
+ for mon in self._monitors:
+ mon.cancel()
- self._monitors = []
- self._modules = None
+ self._monitors = []
+ self._modules = None
- for k in self._timeouts:
- GObject.source_remove(self._timeouts[k])
+ for k in self._timeouts:
+ GObject.source_remove(self._timeouts[k])
- self._timeouts = {}
+ self._timeouts = {}
- def accelerator_activated(self, accel, mod, state, entry):
- self.run(state, mod.execute('', [], entry, 0, accel.arguments))
+ def accelerator_activated(self, accel, mod, state, entry):
+ self.run(state, mod.execute('', [], entry, 0, accel.arguments))
- def scan_accelerators(self, modules=None):
- if modules == None:
- self._accel_group = AccelGroup()
- modules = self.modules()
+ def scan_accelerators(self, modules=None):
+ if modules == None:
+ self._accel_group = AccelGroup()
+ modules = self.modules()
- recurse_mods = []
+ recurse_mods = []
- for mod in modules:
- if type(mod) == types.ModuleType:
- recurse_mods.append(mod)
- else:
- accel = mod.accelerator()
+ for mod in modules:
+ if type(mod) == types.ModuleType:
+ recurse_mods.append(mod)
+ else:
+ accel = mod.accelerator()
- if accel != None:
- self._accel_group.add(accel, self.accelerator_activated, mod)
+ if accel != None:
+ self._accel_group.add(accel, self.accelerator_activated, mod)
- for mod in recurse_mods:
- self.scan_accelerators(mod.commands())
+ for mod in recurse_mods:
+ self.scan_accelerators(mod.commands())
- def accelerator_group(self):
- if not self._accel_group:
- self.scan_accelerators()
+ def accelerator_group(self):
+ if not self._accel_group:
+ self.scan_accelerators()
- return self._accel_group
+ return self._accel_group
- def modules(self):
- self.ensure()
- return list(self._modules)
+ def modules(self):
+ self.ensure()
+ return list(self._modules)
- def add_monitor(self, d):
- gfile = Gio.file_new_for_path(d)
- monitor = None
+ def add_monitor(self, d):
+ gfile = Gio.file_new_for_path(d)
+ monitor = None
- try:
- monitor = gfile.monitor_directory(Gio.FileMonitorFlags.NONE, None)
- except Gio.Error, e:
- # Could not create monitor, this happens on systems where file monitoring is
- # not supported, but we don't really care
- pass
+ try:
+ monitor = gfile.monitor_directory(Gio.FileMonitorFlags.NONE, None)
+ except Gio.Error, e:
+ # Could not create monitor, this happens on systems where file monitoring is
+ # not supported, but we don't really care
+ pass
- if monitor:
- monitor.connect('changed', self.on_monitor_changed)
- self._monitors.append(monitor)
+ if monitor:
+ monitor.connect('changed', self.on_monitor_changed)
+ self._monitors.append(monitor)
- def scan(self, d):
- files = []
+ def scan(self, d):
+ files = []
- try:
- files = os.listdir(d)
- except OSError:
- pass
+ try:
+ files = os.listdir(d)
+ except OSError:
+ pass
- for f in files:
- full = os.path.join(d, f)
+ for f in files:
+ full = os.path.join(d, f)
- # Test for python files or modules
- if is_commander_module(full):
- if self.add_module(full) and os.path.isdir(full):
- # Add monitor on the module directory if module was
- # successfully added. TODO: recursively add monitors
- self.add_monitor(full)
+ # Test for python files or modules
+ if is_commander_module(full):
+ if self.add_module(full) and os.path.isdir(full):
+ # Add monitor on the module directory if module was
+ # successfully added. TODO: recursively add monitors
+ self.add_monitor(full)
- # Add a monitor on the scanned directory itself
- self.add_monitor(d)
+ # Add a monitor on the scanned directory itself
+ self.add_monitor(d)
- def module_name(self, filename):
- # Module name is the basename without the .py
- return os.path.basename(os.path.splitext(filename)[0])
+ def module_name(self, filename):
+ # Module name is the basename without the .py
+ return os.path.basename(os.path.splitext(filename)[0])
- def add_module(self, filename):
- base = self.module_name(filename)
+ def add_module(self, filename):
+ base = self.module_name(filename)
- # Check if module already exists
- if base in self._modules:
- return
+ # Check if module already exists
+ if base in self._modules:
+ return
- # Create new 'empty' module
- mod = module.Module(base, os.path.dirname(filename))
- bisect.insort_right(self._modules, mod)
+ # Create new 'empty' module
+ mod = module.Module(base, os.path.dirname(filename))
+ bisect.insort_right(self._modules, mod)
- # Reload the module
- self.reload_module(mod)
- return True
+ # Reload the module
+ self.reload_module(mod)
+ return True
- def ensure(self):
- # Ensure that modules have been scanned
- if self._modules != None:
- return
+ def ensure(self):
+ # Ensure that modules have been scanned
+ if self._modules != None:
+ return
- self._modules = []
+ self._modules = []
- for d in self._dirs:
- self.scan(d)
+ for d in self._dirs:
+ self.scan(d)
- def _run_generator(self, state, ret=None):
- try:
- # Determine first use
- retval = state.run(ret)
+ def _run_generator(self, state, ret=None):
+ try:
+ # Determine first use
+ retval = state.run(ret)
- if not retval or (isinstance(retval, result.Result) and (retval == result.DONE or retval == result.HIDE)):
- state.pop()
+ if not retval or (isinstance(retval, result.Result) and (retval == result.DONE or retval == result.HIDE)):
+ state.pop()
- if state:
- return self._run_generator(state)
+ if state:
+ return self._run_generator(state)
- return self.run(state, retval)
+ return self.run(state, retval)
- except StopIteration:
- state.pop()
+ except StopIteration:
+ state.pop()
- if state:
- return self.run(state)
- except Exception, e:
- # Something error like, we throw on the parent generator
- state.pop()
+ if state:
+ return self.run(state)
+ except Exception, e:
+ # Something error like, we throw on the parent generator
+ state.pop()
- if state:
- state.top().generator.throw(type(e), e)
- else:
- # Re raise it for the top most to show the error
- raise
+ if state:
+ state.top().generator.throw(type(e), e)
+ else:
+ # Re raise it for the top most to show the error
+ raise
- return None
+ return None
- def run(self, state, ret=None):
- if type(ret) == types.GeneratorType:
- # Ok, this is cool stuff, generators can ask and susped execution
- # of commands, for instance to prompt for some more information
- state.push(ret)
+ def run(self, state, ret=None):
+ if type(ret) == types.GeneratorType:
+ # Ok, this is cool stuff, generators can ask and susped execution
+ # of commands, for instance to prompt for some more information
+ state.push(ret)
- return self._run_generator(state)
- elif not isinstance(ret, result.Result) and len(state) > 1:
- # Basicly, send it to the previous?
- state.pop()
+ return self._run_generator(state)
+ elif not isinstance(ret, result.Result) and len(state) > 1:
+ # Basicly, send it to the previous?
+ state.pop()
- return self._run_generator(state, ret)
- else:
- return ret
+ return self._run_generator(state, ret)
+ else:
+ return ret
- def execute(self, state, argstr, words, wordsstr, entry, modifier):
- self.ensure()
+ def execute(self, state, argstr, words, wordsstr, entry, modifier):
+ self.ensure()
- if state:
- return self._run_generator(state, [argstr, words, modifier])
+ if state:
+ return self._run_generator(state, [argstr, words, modifier])
- cmd = completion.single_command(wordsstr, 0)
+ cmd = completion.single_command(wordsstr, 0)
- if not cmd:
- raise exceptions.Execute('Could not find command: ' + wordsstr[0])
+ if not cmd:
+ raise exceptions.Execute('Could not find command: ' + wordsstr[0])
- if len(words) > 1:
- argstr = argstr[words[1].start(0):]
- else:
- argstr = ''
+ if len(words) > 1:
+ argstr = argstr[words[1].start(0):]
+ else:
+ argstr = ''
- # Execute command
- return self.run(state, cmd.execute(argstr, wordsstr[1:], entry, modifier))
+ # Execute command
+ return self.run(state, cmd.execute(argstr, wordsstr[1:], entry, modifier))
- def invoke(self, entry, modifier, command, args, argstr=None):
- self.ensure()
+ def invoke(self, entry, modifier, command, args, argstr=None):
+ self.ensure()
- cmd = completion.single_command([command], 0)
+ cmd = completion.single_command([command], 0)
- if not cmd:
- raise exceptions.Execute('Could not find command: ' + command)
+ if not cmd:
+ raise exceptions.Execute('Could not find command: ' + command)
- if argstr == None:
- argstr = ' '.join(args)
+ if argstr == None:
+ argstr = ' '.join(args)
- ret = cmd.execute(argstr, args, entry, modifier)
+ ret = cmd.execute(argstr, args, entry, modifier)
- if type(ret) == types.GeneratorType:
- raise exceptions.Execute('Cannot invoke commands that yield (yet)')
- else:
- return ret
+ if type(ret) == types.GeneratorType:
+ raise exceptions.Execute('Cannot invoke commands that yield (yet)')
+ else:
+ return ret
- def resolve_module(self, path, load=True):
- if not self._modules or not is_commander_module(path):
- return None
+ def resolve_module(self, path, load=True):
+ if not self._modules or not is_commander_module(path):
+ return None
- # Strip off __init__.py for module kind of modules
- if path.endswith('__init__.py'):
- path = os.path.dirname(path)
+ # Strip off __init__.py for module kind of modules
+ if path.endswith('__init__.py'):
+ path = os.path.dirname(path)
- base = self.module_name(path)
+ base = self.module_name(path)
- # Find module
- idx = bisect.bisect_left(self._modules, base)
- mod = None
+ # Find module
+ idx = bisect.bisect_left(self._modules, base)
+ mod = None
- if idx < len(self._modules):
- mod = self._modules[idx]
+ if idx < len(self._modules):
+ mod = self._modules[idx]
- if not mod or mod.name != base:
- if load:
- self.add_module(path)
+ if not mod or mod.name != base:
+ if load:
+ self.add_module(path)
- return None
+ return None
- return mod
+ return mod
- def remove_module_accelerators(self, modules):
- recurse_mods = []
+ def remove_module_accelerators(self, modules):
+ recurse_mods = []
- for mod in modules:
- if type(mod) == types.ModuleType:
- recurse_mods.append(mod)
- else:
- accel = mod.accelerator()
+ for mod in modules:
+ if type(mod) == types.ModuleType:
+ recurse_mods.append(mod)
+ else:
+ accel = mod.accelerator()
- if accel != None:
- self._accel_group.remove(accel)
+ if accel != None:
+ self._accel_group.remove(accel)
- for mod in recurse_mods:
- self.remove_module_accelerators(mod.commands())
+ for mod in recurse_mods:
+ self.remove_module_accelerators(mod.commands())
- def remove_module(self, mod):
- # Remove roots
- for r in mod.roots():
- if r in self._modules:
- self._modules.remove(r)
+ def remove_module(self, mod):
+ # Remove roots
+ for r in mod.roots():
+ if r in self._modules:
+ self._modules.remove(r)
- # Remove accelerators
- if self._accel_group:
- self.remove_module_accelerators([mod])
+ # Remove accelerators
+ if self._accel_group:
+ self.remove_module_accelerators([mod])
- if mod.name in commander.modules.__dict__:
- del commander.modules.__dict__[mod.name]
+ if mod.name in commander.modules.__dict__:
+ del commander.modules.__dict__[mod.name]
- def reload_module(self, mod):
- if isinstance(mod, basestring):
- mod = self.resolve_module(mod)
+ def reload_module(self, mod):
+ if isinstance(mod, basestring):
+ mod = self.resolve_module(mod)
- if not mod or not self._modules:
- return
+ if not mod or not self._modules:
+ return
- # Remove roots
- self.remove_module(mod)
+ # Remove roots
+ self.remove_module(mod)
- # Now, try to reload the module
- try:
- mod.reload()
- except Exception, e:
- # Reload failed, we remove the module
- print 'Failed to reload module (%s):' % (mod.name,), e
+ # Now, try to reload the module
+ try:
+ mod.reload()
+ except Exception, e:
+ # Reload failed, we remove the module
+ print 'Failed to reload module (%s):' % (mod.name,), e
- self._modules.remove(mod)
- return
+ self._modules.remove(mod)
+ return
- # Insert roots
- for r in mod.roots():
- bisect.insort(self._modules, r)
+ # Insert roots
+ for r in mod.roots():
+ bisect.insort(self._modules, r)
- commander.modules.__dict__[mod.name] = mod.mod
+ commander.modules.__dict__[mod.name] = mod.mod
- if self._accel_group:
- self.scan_accelerators([mod])
+ if self._accel_group:
+ self.scan_accelerators([mod])
- def on_timeout_delete(self, path, mod):
- if not path in self._timeouts:
- return False
+ def on_timeout_delete(self, path, mod):
+ if not path in self._timeouts:
+ return False
- # Remove the module
- mod.unload()
- self.remove_module(mod)
- self._modules.remove(mod)
+ # Remove the module
+ mod.unload()
+ self.remove_module(mod)
+ self._modules.remove(mod)
- return False
+ return False
- def on_monitor_changed(self, monitor, gfile1, gfile2, evnt):
- if evnt == Gio.FileMonitorEvent.CHANGED:
- # Reload the module
- self.reload_module(gfile1.get_path())
- elif evnt == Gio.FileMonitorEvent.DELETED:
- path = gfile1.get_path()
- mod = self.resolve_module(path, False)
+ def on_monitor_changed(self, monitor, gfile1, gfile2, evnt):
+ if evnt == Gio.FileMonitorEvent.CHANGED:
+ # Reload the module
+ self.reload_module(gfile1.get_path())
+ elif evnt == Gio.FileMonitorEvent.DELETED:
+ path = gfile1.get_path()
+ mod = self.resolve_module(path, False)
- if not mod:
- return
+ if not mod:
+ return
- if path in self._timeouts:
- GObject.source_remove(self._timeouts[path])
+ if path in self._timeouts:
+ GObject.source_remove(self._timeouts[path])
- # We add a timeout because a common save strategy causes a
- # DELETE/CREATE event chain
- self._timeouts[path] = GObject.timeout_add(500, self.on_timeout_delete, path, mod)
- elif evnt == Gio.FileMonitorEvent.CREATED:
- path = gfile1.get_path()
+ # We add a timeout because a common save strategy causes a
+ # DELETE/CREATE event chain
+ self._timeouts[path] = GObject.timeout_add(500, self.on_timeout_delete, path, mod)
+ elif evnt == Gio.FileMonitorEvent.CREATED:
+ path = gfile1.get_path()
- # Check if this CREATE followed a previous DELETE
- if path in self._timeouts:
- GObject.source_remove(self._timeouts[path])
- del self._timeouts[path]
+ # Check if this CREATE followed a previous DELETE
+ if path in self._timeouts:
+ GObject.source_remove(self._timeouts[path])
+ del self._timeouts[path]
- # Reload the module
- self.reload_module(path)
+ # Reload the module
+ self.reload_module(path)
+
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/commands/accel_group.py b/plugins/commander/commander/commands/accel_group.py
index a02137d..73c2121 100644
--- a/plugins/commander/commander/commands/accel_group.py
+++ b/plugins/commander/commander/commands/accel_group.py
@@ -22,104 +22,106 @@
from gi.repository import Gtk
class Accelerator:
- def __init__(self, accelerators, arguments={}):
- if not hasattr(accelerators, '__iter__'):
- accelerators = [accelerators]
+ def __init__(self, accelerators, arguments={}):
+ if not hasattr(accelerators, '__iter__'):
+ accelerators = [accelerators]
- self.accelerators = accelerators
- self.arguments = arguments
+ self.accelerators = accelerators
+ self.arguments = arguments
class AccelCallback:
- def __init__(self, accel, callback, data):
- self.accelerator = accel
- self.callback = callback
- self.data = data
+ def __init__(self, accel, callback, data):
+ self.accelerator = accel
+ self.callback = callback
+ self.data = data
- def activate(self, state, entry):
- self.callback(self.accelerator, self.data, state, entry)
+ def activate(self, state, entry):
+ self.callback(self.accelerator, self.data, state, entry)
class AccelGroup:
- def __init__(self, parent=None, name='', accelerators={}):
- self.accelerators = dict(accelerators)
- self.parent = parent
- self.name = name
+ def __init__(self, parent=None, name='', accelerators={}):
+ self.accelerators = dict(accelerators)
+ self.parent = parent
+ self.name = name
- def add(self, accel, callback, data=None):
- num = len(accel.accelerators)
- mapping = self.accelerators
+ def add(self, accel, callback, data=None):
+ num = len(accel.accelerators)
+ mapping = self.accelerators
- for i in range(num):
- parsed = Gtk.accelerator_parse(accel.accelerators[i])
+ for i in range(num):
+ parsed = Gtk.accelerator_parse(accel.accelerators[i])
- if not Gtk.accelerator_valid(*parsed):
- return
+ if not Gtk.accelerator_valid(*parsed):
+ return
- named = Gtk.accelerator_name(*parsed)
- inmap = named in mapping
+ named = Gtk.accelerator_name(*parsed)
+ inmap = named in mapping
- if i == num - 1 and inmap:
- # Last one cannot be in the map
- return
- elif inmap and isinstance(mapping[named], AccelCallback):
- # It's already mapped...
- return
- else:
- if not inmap:
- mapping[named] = {}
+ if i == num - 1 and inmap:
+ # Last one cannot be in the map
+ return
+ elif inmap and isinstance(mapping[named], AccelCallback):
+ # It's already mapped...
+ return
+ else:
+ if not inmap:
+ mapping[named] = {}
- if i == num - 1:
- mapping[named] = AccelCallback(accel, callback, data)
+ if i == num - 1:
+ mapping[named] = AccelCallback(accel, callback, data)
- mapping = mapping[named]
+ mapping = mapping[named]
- def remove_real(self, accelerators, accels):
- if not accels:
- return
+ def remove_real(self, accelerators, accels):
+ if not accels:
+ return
- parsed = Gtk.accelerator_parse(accels[0])
+ parsed = Gtk.accelerator_parse(accels[0])
- if not Gtk.accelerator_valid(*parsed):
- return
+ if not Gtk.accelerator_valid(*parsed):
+ return
- named = Gtk.accelerator_name(*parsed)
+ named = Gtk.accelerator_name(*parsed)
- if not named in accelerators:
- return
+ if not named in accelerators:
+ return
- if len(accels) == 1:
- del accelerators[named]
- else:
- self.remove_real(accelerators[named], accels[1:])
+ if len(accels) == 1:
+ del accelerators[named]
+ else:
+ self.remove_real(accelerators[named], accels[1:])
- if not accelerators[named]:
- del accelerators[named]
+ if not accelerators[named]:
+ del accelerators[named]
- def remove(self, accel):
- self.remove_real(self.accelerators, accel.accelerators)
+ def remove(self, accel):
+ self.remove_real(self.accelerators, accel.accelerators)
- def activate(self, key, mod):
- named = Gtk.accelerator_name(key, mod)
+ def activate(self, key, mod):
+ named = Gtk.accelerator_name(key, mod)
- if not named in self.accelerators:
- return None
+ if not named in self.accelerators:
+ return None
- accel = self.accelerators[named]
+ accel = self.accelerators[named]
- if isinstance(accel, AccelCallback):
- return accel
- else:
- return AccelGroup(self, named, accel)
+ if isinstance(accel, AccelCallback):
+ return accel
+ else:
+ return AccelGroup(self, named, accel)
- def full_name(self):
- name = ''
+ def full_name(self):
+ name = ''
- if self.parent:
- name = self.parent.full_name()
+ if self.parent:
+ name = self.parent.full_name()
- if self.name:
- if name:
- name += ', '
+ if self.name:
+ if name:
+ name += ', '
- name += self.name
+ name += self.name
- return name
+ return name
+
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/commands/completion.py b/plugins/commander/commander/commands/completion.py
index 18788d6..f24c240 100644
--- a/plugins/commander/commander/commands/completion.py
+++ b/plugins/commander/commander/commands/completion.py
@@ -30,190 +30,192 @@ from xml.sax import saxutils
__all__ = ['command', 'filename']
def _common_prefix_part(first, second):
- length = min(len(first), len(second))
+ length = min(len(first), len(second))
- for i in range(0, length):
- if first[i] != second[i]:
- return first[:i]
+ for i in range(0, length):
+ if first[i] != second[i]:
+ return first[:i]
- return first[:length]
+ return first[:length]
def common_prefix(args, sep=None):
- # A common prefix can be something like
- # first: some-thing
- # second: sho-tar
- # res: s-t
- args = list(args)
+ # A common prefix can be something like
+ # first: some-thing
+ # second: sho-tar
+ # res: s-t
+ args = list(args)
- if not args:
- return ''
+ if not args:
+ return ''
- if len(args) == 1:
- return str(args[0])
+ if len(args) == 1:
+ return str(args[0])
- first = str(args[0])
- second = str(args[1])
+ first = str(args[0])
+ second = str(args[1])
- if not sep:
- ret = _common_prefix_part(first, second)
- else:
- first = first.split(sep)
- second = second.split(sep)
- ret = []
+ if not sep:
+ ret = _common_prefix_part(first, second)
+ else:
+ first = first.split(sep)
+ second = second.split(sep)
+ ret = []
- for i in range(0, min(len(first), len(second))):
- ret.append(_common_prefix_part(first[i], second[i]))
+ for i in range(0, min(len(first), len(second))):
+ ret.append(_common_prefix_part(first[i], second[i]))
- ret = sep.join(ret)
+ ret = sep.join(ret)
- del args[0]
- args[0] = ret
+ del args[0]
+ args[0] = ret
- return common_prefix(args, sep)
+ return common_prefix(args, sep)
def _expand_commands(cmds):
- if not cmds:
- cmds.extend(commands.Commands().modules())
- return
+ if not cmds:
+ cmds.extend(commands.Commands().modules())
+ return
- old = list(cmds)
- del cmds[:]
+ old = list(cmds)
+ del cmds[:]
- # Expand 'commands' to all the respective subcommands
+ # Expand 'commands' to all the respective subcommands
- for cmd in old:
- for c in cmd.commands():
- bisect.insort(cmds, c)
+ for cmd in old:
+ for c in cmd.commands():
+ bisect.insort(cmds, c)
def _filter_command(cmd, subs):
- parts = cmd.name.split('-')
+ parts = cmd.name.split('-')
- if len(subs) > len(parts):
- return False
+ if len(subs) > len(parts):
+ return False
- for i in xrange(0, len(subs)):
- if not parts[i].startswith(subs[i]):
- return False
+ for i in xrange(0, len(subs)):
+ if not parts[i].startswith(subs[i]):
+ return False
- return True
+ return True
def _filter_commands(cmds, subs):
- # See what parts of cmds still match the parts in subs
- idx = bisect.bisect_left(cmds, subs[0])
- ret = []
+ # See what parts of cmds still match the parts in subs
+ idx = bisect.bisect_left(cmds, subs[0])
+ ret = []
- while idx < len(cmds):
- if not cmds[idx].name.startswith(subs[0]):
- break
+ while idx < len(cmds):
+ if not cmds[idx].name.startswith(subs[0]):
+ break
- if _filter_command(cmds[idx], subs):
- ret.append(cmds[idx])
+ if _filter_command(cmds[idx], subs):
+ ret.append(cmds[idx])
- idx += 1
+ idx += 1
- return ret
+ return ret
def single_command(words, idx):
- ret = command(words, idx)
+ ret = command(words, idx)
- if not ret:
- return None
+ if not ret:
+ return None
- ret[0] = filter(lambda x: x.method, ret[0])
+ ret[0] = filter(lambda x: x.method, ret[0])
- if not ret[0]:
- return None
+ if not ret[0]:
+ return None
- return ret[0][0]
+ return ret[0][0]
def command(words, idx):
- s = words[idx].strip()
+ s = words[idx].strip()
- parts = s.split('.')
- cmds = []
+ parts = s.split('.')
+ cmds = []
- for i in parts:
- # Expand all the parents to their child commands
- _expand_commands(cmds)
+ for i in parts:
+ # Expand all the parents to their child commands
+ _expand_commands(cmds)
- if not cmds:
- return None
+ if not cmds:
+ return None
- subs = i.split('-')
- cmds = _filter_commands(cmds, subs)
+ subs = i.split('-')
+ cmds = _filter_commands(cmds, subs)
- if not cmds:
- return None
+ if not cmds:
+ return None
- if not cmds:
- return None
+ if not cmds:
+ return None
- if len(parts) == 1:
- completed = common_prefix(cmds)
- else:
- completed = '.'.join(parts[0:-1]) + '.' + common_prefix(cmds, '-')
+ if len(parts) == 1:
+ completed = common_prefix(cmds)
+ else:
+ completed = '.'.join(parts[0:-1]) + '.' + common_prefix(cmds, '-')
- return [cmds, completed]
+ return [cmds, completed]
def _file_color(path):
- if os.path.isdir(path):
- format = '<span color="#799ec6">%s</span>'
- else:
- format = '%s'
+ if os.path.isdir(path):
+ format = '<span color="#799ec6">%s</span>'
+ else:
+ format = '%s'
- return format % (saxutils.escape(os.path.basename(path)),)
+ return format % (saxutils.escape(os.path.basename(path)),)
def _sort_nicely(l):
- convert = lambda text: int(text) if text.isdigit() else text
- alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
+ convert = lambda text: int(text) if text.isdigit() else text
+ alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
- l.sort(key=alphanum_key)
+ l.sort(key=alphanum_key)
def filename(words, idx, view):
- prefix = os.path.dirname(words[idx])
- partial = os.path.expanduser(words[idx])
+ prefix = os.path.dirname(words[idx])
+ partial = os.path.expanduser(words[idx])
- doc = view.get_buffer()
+ doc = view.get_buffer()
- if not doc.is_untitled():
- root = os.path.dirname(doc.get_location().get_path())
- else:
- root = os.path.expanduser('~/')
+ if not doc.is_untitled():
+ root = os.path.dirname(doc.get_location().get_path())
+ else:
+ root = os.path.expanduser('~/')
- if not os.path.isabs(partial):
- partial = os.path.join(root, partial)
+ if not os.path.isabs(partial):
+ partial = os.path.join(root, partial)
- dirname = os.path.dirname(partial)
+ dirname = os.path.dirname(partial)
- try:
- files = os.listdir(dirname)
- except OSError:
- return None
+ try:
+ files = os.listdir(dirname)
+ except OSError:
+ return None
- base = os.path.basename(partial)
- ret = []
- real = []
+ base = os.path.basename(partial)
+ ret = []
+ real = []
- for f in files:
- if f.startswith(base) and (base or not f.startswith('.')):
- real.append(os.path.join(dirname, f))
- ret.append(os.path.join(prefix, f))
+ for f in files:
+ if f.startswith(base) and (base or not f.startswith('.')):
+ real.append(os.path.join(dirname, f))
+ ret.append(os.path.join(prefix, f))
- _sort_nicely(real)
+ _sort_nicely(real)
- if len(ret) == 1:
- if os.path.isdir(real[0]):
- after = '/'
- else:
- after = ' '
+ if len(ret) == 1:
+ if os.path.isdir(real[0]):
+ after = '/'
+ else:
+ after = ' '
- return ret, ret[0], after
- else:
- return map(lambda x: _file_color(x), real), common_prefix(ret)
+ return ret, ret[0], after
+ else:
+ return map(lambda x: _file_color(x), real), common_prefix(ret)
def words(ret):
- def decorator(words, idx):
- rr = filter(lambda x: x.startswith(words[idx]), ret)
- return rr, common_prefix(rr)
+ def decorator(words, idx):
+ rr = filter(lambda x: x.startswith(words[idx]), ret)
+ return rr, common_prefix(rr)
- return decorator
+ return decorator
+
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/commands/exceptions.py b/plugins/commander/commander/commands/exceptions.py
index 3296d92..964b842 100644
--- a/plugins/commander/commander/commands/exceptions.py
+++ b/plugins/commander/commander/commands/exceptions.py
@@ -20,8 +20,10 @@
# Boston, MA 02111-1307, USA.
class Execute(Exception):
- def __init__(self, msg):
- self.msg = msg
+ def __init__(self, msg):
+ self.msg = msg
- def __str__(self):
- return self.msg
+ def __str__(self):
+ return self.msg
+
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/commands/method.py b/plugins/commander/commander/commands/method.py
index 6843693..38456b4 100644
--- a/plugins/commander/commander/commands/method.py
+++ b/plugins/commander/commander/commands/method.py
@@ -26,100 +26,101 @@ import sys
import commander.utils as utils
class Method:
- def __init__(self, method, name, parent):
- self.method = method
- self.name = name.replace('_', '-')
- self.parent = parent
- self._func_props = None
+ def __init__(self, method, name, parent):
+ self.method = method
+ self.name = name.replace('_', '-')
+ self.parent = parent
+ self._func_props = None
- def __str__(self):
- return self.name
+ def __str__(self):
+ return self.name
- def autocomplete_func(self):
- if hasattr(self.method, 'autocomplete'):
- return getattr(self.method, 'autocomplete')
+ def autocomplete_func(self):
+ if hasattr(self.method, 'autocomplete'):
+ return getattr(self.method, 'autocomplete')
- return None
+ return None
- def accelerator(self):
- if hasattr(self.method, 'accelerator'):
- return getattr(self.method, 'accelerator')
+ def accelerator(self):
+ if hasattr(self.method, 'accelerator'):
+ return getattr(self.method, 'accelerator')
- return None
+ return None
- def args(self):
- fp = self.func_props()
+ def args(self):
+ fp = self.func_props()
- return fp.args, fp.varargs
+ return fp.args, fp.varargs
- def func_props(self):
- if not self._func_props:
- # Introspect the function arguments
- self._func_props = utils.getargspec(self.method)
+ def func_props(self):
+ if not self._func_props:
+ # Introspect the function arguments
+ self._func_props = utils.getargspec(self.method)
- return self._func_props
+ return self._func_props
- def commands(self):
- return []
+ def commands(self):
+ return []
- def cancel(self, view):
- if self.parent:
- self.parent.cancel(view, self)
+ def cancel(self, view):
+ if self.parent:
+ self.parent.cancel(view, self)
- def cancel_continuation(self, view):
- if self.parent:
- self.parent.continuation(view, self)
+ def cancel_continuation(self, view):
+ if self.parent:
+ self.parent.continuation(view, self)
- def doc(self):
- if self.method.__doc__:
- return self.method.__doc__
- else:
- return ''
+ def doc(self):
+ if self.method.__doc__:
+ return self.method.__doc__
+ else:
+ return ''
- def oneline_doc(self):
- return self.doc().split("\n")[0]
+ def oneline_doc(self):
+ return self.doc().split("\n")[0]
- def execute(self, argstr, words, entry, modifier, kk = {}):
- fp = self.func_props()
+ def execute(self, argstr, words, entry, modifier, kk = {}):
+ fp = self.func_props()
- kwargs = {'argstr': argstr, 'args': words, 'entry': entry, 'view': entry.view(), 'modifier': modifier, 'window': entry.view().get_toplevel()}
- oargs = list(fp.args)
- args = []
- idx = 0
+ kwargs = {'argstr': argstr, 'args': words, 'entry': entry, 'view': entry.view(), 'modifier': modifier, 'window': entry.view().get_toplevel()}
+ oargs = list(fp.args)
+ args = []
+ idx = 0
- if fp.defaults:
- numdef = len(fp.defaults)
- else:
- numdef = 0
+ if fp.defaults:
+ numdef = len(fp.defaults)
+ else:
+ numdef = 0
- for k in fp.args:
- if k in kwargs:
- args.append(kwargs[k])
- oargs.remove(k)
- del kwargs[k]
- elif idx >= len(words):
- if numdef < len(oargs):
- raise exceptions.Execute('Invalid number of arguments (need %s)' % (oargs[0],))
- else:
- args.append(words[idx])
- oargs.remove(k)
- idx += 1
+ for k in fp.args:
+ if k in kwargs:
+ args.append(kwargs[k])
+ oargs.remove(k)
+ del kwargs[k]
+ elif idx >= len(words):
+ if numdef < len(oargs):
+ raise exceptions.Execute('Invalid number of arguments (need %s)' % (oargs[0],))
+ else:
+ args.append(words[idx])
+ oargs.remove(k)
+ idx += 1
- # Append the rest if it can handle varargs
- if fp.varargs and idx < len(words):
- args.extend(words[idx:])
+ # Append the rest if it can handle varargs
+ if fp.varargs and idx < len(words):
+ args.extend(words[idx:])
- if not fp.keywords:
- kwargs = {}
+ if not fp.keywords:
+ kwargs = {}
- for k in kk:
- kwargs[k] = kk[k]
+ for k in kk:
+ kwargs[k] = kk[k]
- return self.method(*args, **kwargs)
+ return self.method(*args, **kwargs)
- def __cmp__(self, other):
- if isinstance(other, Method):
- return cmp(self.name, other.name)
- else:
- return cmp(self.name, other)
+ def __cmp__(self, other):
+ if isinstance(other, Method):
+ return cmp(self.name, other.name)
+ else:
+ return cmp(self.name, other)
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/commands/module.py b/plugins/commander/commander/commands/module.py
index 2dbb2ec..dfc7f53 100644
--- a/plugins/commander/commander/commands/module.py
+++ b/plugins/commander/commander/commands/module.py
@@ -30,123 +30,124 @@ import method
import rollbackimporter
class Module(method.Method):
- def __init__(self, base, mod, parent=None):
- method.Method.__init__(self, None, base, parent)
+ def __init__(self, base, mod, parent=None):
+ method.Method.__init__(self, None, base, parent)
- self._commands = None
- self._dirname = None
- self._roots = None
+ self._commands = None
+ self._dirname = None
+ self._roots = None
- if type(mod) == types.ModuleType:
- self.mod = mod
+ if type(mod) == types.ModuleType:
+ self.mod = mod
- if '__default__' in mod.__dict__:
- self.method = mod.__dict__['__default__']
- else:
- self.method = None
- else:
- self.mod = None
- self._dirname = mod
- self._rollback = rollbackimporter.RollbackImporter()
+ if '__default__' in mod.__dict__:
+ self.method = mod.__dict__['__default__']
+ else:
+ self.method = None
+ else:
+ self.mod = None
+ self._dirname = mod
+ self._rollback = rollbackimporter.RollbackImporter()
- def commands(self):
- if self._commands == None:
- self.scan_commands()
+ def commands(self):
+ if self._commands == None:
+ self.scan_commands()
- return self._commands
+ return self._commands
- def clear(self):
- self._commands = None
+ def clear(self):
+ self._commands = None
- def roots(self):
- if self._roots == None:
- if not self.mod:
- return []
+ def roots(self):
+ if self._roots == None:
+ if not self.mod:
+ return []
- dic = self.mod.__dict__
+ dic = self.mod.__dict__
- if '__root__' in dic:
- root = dic['__root__']
- else:
- root = []
+ if '__root__' in dic:
+ root = dic['__root__']
+ else:
+ root = []
- root = filter(lambda x: x in dic and type(dic[x]) == types.FunctionType, root)
- self._roots = map(lambda x: method.Method(dic[x], x, self.mod), root)
+ root = filter(lambda x: x in dic and type(dic[x]) == types.FunctionType, root)
+ self._roots = map(lambda x: method.Method(dic[x], x, self.mod), root)
- return self._roots
+ return self._roots
- def scan_commands(self):
- self._commands = []
+ def scan_commands(self):
+ self._commands = []
- if self.mod == None:
- return
+ if self.mod == None:
+ return
- dic = self.mod.__dict__
+ dic = self.mod.__dict__
- if '__root__' in dic:
- root = dic['__root__']
- else:
- root = []
+ if '__root__' in dic:
+ root = dic['__root__']
+ else:
+ root = []
- for k in dic:
- if k.startswith('_') or k in root:
- continue
+ for k in dic:
+ if k.startswith('_') or k in root:
+ continue
- item = dic[k]
+ item = dic[k]
- if type(item) == types.FunctionType:
- bisect.insort(self._commands, method.Method(item, k, self))
- elif type(item) == types.ModuleType and utils.is_commander_module(item):
- mod = Module(k, item, self)
- bisect.insort(self._commands, mod)
+ if type(item) == types.FunctionType:
+ bisect.insort(self._commands, method.Method(item, k, self))
+ elif type(item) == types.ModuleType and utils.is_commander_module(item):
+ mod = Module(k, item, self)
+ bisect.insort(self._commands, mod)
- # Insert root functions into this module
- for r in mod.roots():
- bisect.insert(self._commands, r)
+ # Insert root functions into this module
+ for r in mod.roots():
+ bisect.insert(self._commands, r)
- def unload(self):
- self._commands = None
+ def unload(self):
+ self._commands = None
- if not self._dirname:
- return False
+ if not self._dirname:
+ return False
- self._rollback.uninstall()
- self.mod = None
+ self._rollback.uninstall()
+ self.mod = None
- return True
+ return True
- def reload(self):
- if not self.unload():
- return
+ def reload(self):
+ if not self.unload():
+ return
- if self.name in sys.modules:
- raise Exception('Module already exists...')
+ if self.name in sys.modules:
+ raise Exception('Module already exists...')
- oldpath = list(sys.path)
+ oldpath = list(sys.path)
- try:
- sys.path.insert(0, self._dirname)
+ try:
+ sys.path.insert(0, self._dirname)
- self._rollback.monitor()
- self.mod = __import__(self.name, globals(), locals(), [], 0)
- self._rollback.cancel()
+ self._rollback.monitor()
+ self.mod = __import__(self.name, globals(), locals(), [], 0)
+ self._rollback.cancel()
- if not utils.is_commander_module(self.mod):
- raise Exception('Module is not a commander module...')
+ if not utils.is_commander_module(self.mod):
+ raise Exception('Module is not a commander module...')
- if '__default__' in self.mod.__dict__:
- self.method = self.mod.__dict__['__default__']
- else:
- self.method = None
+ if '__default__' in self.mod.__dict__:
+ self.method = self.mod.__dict__['__default__']
+ else:
+ self.method = None
- self._func_props = None
- except:
- sys.path = oldpath
- self._rollback.uninstall()
+ self._func_props = None
+ except:
+ sys.path = oldpath
+ self._rollback.uninstall()
- if self.name in sys.modules:
- del sys.modules[self.name]
- raise
+ if self.name in sys.modules:
+ del sys.modules[self.name]
+ raise
- sys.path = oldpath
+ sys.path = oldpath
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/commands/result.py b/plugins/commander/commander/commands/result.py
index 0cea88a..aa10bd2 100644
--- a/plugins/commander/commander/commands/result.py
+++ b/plugins/commander/commander/commands/result.py
@@ -20,43 +20,45 @@
# Boston, MA 02111-1307, USA.
class Result(object):
- HIDE = 1
- DONE = 2
- PROMPT = 3
- SUSPEND = 4
+ HIDE = 1
+ DONE = 2
+ PROMPT = 3
+ SUSPEND = 4
- def __init__(self, value):
- self._value = value
+ def __init__(self, value):
+ self._value = value
- def __int__(self):
- return self._value
+ def __int__(self):
+ return self._value
- def __cmp__(self, other):
- if isinstance(other, int) or isinstance(other, Result):
- return cmp(int(self), int(other))
- else:
- return 1
+ def __cmp__(self, other):
+ if isinstance(other, int) or isinstance(other, Result):
+ return cmp(int(self), int(other))
+ else:
+ return 1
# Easy shortcuts
HIDE = Result(Result.HIDE)
DONE = Result(Result.DONE)
class Prompt(Result):
- def __init__(self, prompt, autocomplete={}):
- Result.__init__(self, Result.PROMPT)
+ def __init__(self, prompt, autocomplete={}):
+ Result.__init__(self, Result.PROMPT)
- self.prompt = prompt
- self.autocomplete = autocomplete
+ self.prompt = prompt
+ self.autocomplete = autocomplete
class Suspend(Result):
- def __init__(self):
- Result.__init__(self, Result.SUSPEND)
- self._callbacks = []
+ def __init__(self):
+ Result.__init__(self, Result.SUSPEND)
+ self._callbacks = []
- def register(self, cb, *args):
- self._callbacks.append([cb, args])
+ def register(self, cb, *args):
+ self._callbacks.append([cb, args])
- def resume(self):
- for cb in self._callbacks:
- args = cb[1]
- cb[0](*args)
+ def resume(self):
+ for cb in self._callbacks:
+ args = cb[1]
+ cb[0](*args)
+
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/commands/rollbackimporter.py b/plugins/commander/commander/commands/rollbackimporter.py
index 8dce690..f9722bc 100644
--- a/plugins/commander/commander/commands/rollbackimporter.py
+++ b/plugins/commander/commander/commands/rollbackimporter.py
@@ -23,33 +23,34 @@ import sys
import utils
class RollbackImporter:
- def __init__(self):
- "Creates an instance and installs as the global importer"
- self._new_modules = []
- self._original_import = __builtins__['__import__']
+ def __init__(self):
+ "Creates an instance and installs as the global importer"
+ self._new_modules = []
+ self._original_import = __builtins__['__import__']
- def monitor(self):
- __builtins__['__import__'] = self._import
+ def monitor(self):
+ __builtins__['__import__'] = self._import
- def cancel(self):
- __builtins__['__import__'] = self._original_import
+ def cancel(self):
+ __builtins__['__import__'] = self._original_import
- def _import(self, name, globals=None, locals=None, fromlist=[], level=-1):
- maybe = not name in sys.modules
+ def _import(self, name, globals=None, locals=None, fromlist=[], level=-1):
+ maybe = not name in sys.modules
- mod = apply(self._original_import, (name, globals, locals, fromlist, level))
+ mod = apply(self._original_import, (name, globals, locals, fromlist, level))
- if maybe and utils.is_commander_module(mod):
- self._new_modules.append(name)
+ if maybe and utils.is_commander_module(mod):
+ self._new_modules.append(name)
- return mod
+ return mod
- def uninstall(self):
- self.cancel()
+ def uninstall(self):
+ self.cancel()
- for modname in self._new_modules:
- if modname in sys.modules:
- del sys.modules[modname]
+ for modname in self._new_modules:
+ if modname in sys.modules:
+ del sys.modules[modname]
- self._new_modules = []
+ self._new_modules = []
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/entry.py b/plugins/commander/commander/entry.py
index 6122dc7..a458696 100644
--- a/plugins/commander/commander/entry.py
+++ b/plugins/commander/commander/entry.py
@@ -41,637 +41,637 @@ from xml.sax import saxutils
import traceback
class Entry(Gtk.EventBox):
- __gtype_name__ = "CommanderEntry"
+ __gtype_name__ = "CommanderEntry"
- def __init__(self, view):
- Gtk.EventBox.__init__(self)
- self._view = view
+ def __init__(self, view):
+ Gtk.EventBox.__init__(self)
+ self._view = view
- self.set_visible_window(False)
+ self.set_visible_window(False)
- hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 3)
- hbox.show()
- hbox.set_border_width(3)
+ hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 3)
+ hbox.show()
+ hbox.set_border_width(3)
- # context for the view
- self._entry = Gtk.Entry()
- self._entry.set_has_frame(False)
- self._entry.set_name('gedit-commander-entry')
- self._entry.show()
+ # context for the view
+ self._entry = Gtk.Entry()
+ self._entry.set_has_frame(False)
+ self._entry.set_name('gedit-commander-entry')
+ self._entry.show()
- css = Gtk.CssProvider()
- css.load_from_data("""
+ css = Gtk.CssProvider()
+ css.load_from_data("""
@binding-set terminal-like-bindings {
- unbind "<Control>A";
-
- bind "<Control>W" { "delete-from-cursor" (word-ends, -1) };
- bind "<Control>A" { "move-cursor" (buffer-ends, -1, 0) };
- bind "<Control>U" { "delete-from-cursor" (display-line-ends, -1) };
- bind "<Control>K" { "delete-from-cursor" (display-line-ends, 1) };
- bind "<Control>E" { "move-cursor" (buffer-ends, 1, 0) };
- bind "Escape" { "delete-from-cursor" (display-lines, 1) };
+ unbind "<Control>A";
+
+ bind "<Control>W" { "delete-from-cursor" (word-ends, -1) };
+ bind "<Control>A" { "move-cursor" (buffer-ends, -1, 0) };
+ bind "<Control>U" { "delete-from-cursor" (display-line-ends, -1) };
+ bind "<Control>K" { "delete-from-cursor" (display-line-ends, 1) };
+ bind "<Control>E" { "move-cursor" (buffer-ends, 1, 0) };
+ bind "Escape" { "delete-from-cursor" (display-lines, 1) };
}
GtkEntry#gedit-commander-entry {
- gtk-key-bindings: terminal-like-bindings;
+ gtk-key-bindings: terminal-like-bindings;
}
""")
- # FIXME: remove hardcopy of 600 (GTK_STYLE_PROVIDER_PRIORITY_APPLICATION)
- # https://bugzilla.gnome.org/show_bug.cgi?id=646860
- self._entry.get_style_context().add_provider(css, 600)
-
- self._prompt_label = Gtk.Label(label='<b>>>></b>', use_markup=True)
- self._prompt_label.show()
-
- self._entry.connect('focus-out-event', self.on_entry_focus_out)
- self._entry.connect('key-press-event', self.on_entry_key_press)
+ # FIXME: remove hardcopy of 600 (GTK_STYLE_PROVIDER_PRIORITY_APPLICATION)
+ # https://bugzilla.gnome.org/show_bug.cgi?id=646860
+ self._entry.get_style_context().add_provider(css, 600)
+
+ self._prompt_label = Gtk.Label(label='<b>>>></b>', use_markup=True)
+ self._prompt_label.show()
+
+ self._entry.connect('focus-out-event', self.on_entry_focus_out)
+ self._entry.connect('key-press-event', self.on_entry_key_press)
- self._history = History(os.path.join(GLib.get_user_config_dir(), 'gedit/commander/history'))
- self._prompt = None
+ self._history = History(os.path.join(GLib.get_user_config_dir(), 'gedit/commander/history'))
+ self._prompt = None
- self._accel_group = None
-
- hbox.pack_start(self._prompt_label, False, False, 0)
- hbox.pack_start(self._entry, True, True, 0)
+ self._accel_group = None
+
+ hbox.pack_start(self._prompt_label, False, False, 0)
+ hbox.pack_start(self._entry, True, True, 0)
- self.copy_style_from_view()
- self.view_style_updated_id = self._view.connect('style-updated', self.on_view_style_updated)
+ self.copy_style_from_view()
+ self.view_style_updated_id = self._view.connect('style-updated', self.on_view_style_updated)
- self.add(hbox)
- self.attach()
- self._entry.grab_focus()
+ self.add(hbox)
+ self.attach()
+ self._entry.grab_focus()
- self._wait_timeout = 0
- self._info_window = None
+ self._wait_timeout = 0
+ self._info_window = None
- self.connect('destroy', self.on_destroy)
- self.connect_after('size-allocate', self.on_size_allocate)
- self.view_draw_id = self._view.connect_after('draw', self.on_draw)
-
- self._history_prefix = None
- self._suspended = None
- self._handlers = [
- [0, Gdk.KEY_Up, self.on_history_move, -1],
- [0, Gdk.KEY_Down, self.on_history_move, 1],
- [None, Gdk.KEY_Return, self.on_execute, None],
- [None, Gdk.KEY_KP_Enter, self.on_execute, None],
- [0, Gdk.KEY_Tab, self.on_complete, None],
- [0, Gdk.KEY_ISO_Left_Tab, self.on_complete, None]
- ]
-
- self._re_complete = re.compile('("((?:\\\\"|[^"])*)"?|\'((?:\\\\\'|[^\'])*)\'?|[^\s]+)')
- self._command_state = commands.Commands.State()
+ self.connect('destroy', self.on_destroy)
+ self.connect_after('size-allocate', self.on_size_allocate)
+ self.view_draw_id = self._view.connect_after('draw', self.on_draw)
+
+ self._history_prefix = None
+ self._suspended = None
+ self._handlers = [
+ [0, Gdk.KEY_Up, self.on_history_move, -1],
+ [0, Gdk.KEY_Down, self.on_history_move, 1],
+ [None, Gdk.KEY_Return, self.on_execute, None],
+ [None, Gdk.KEY_KP_Enter, self.on_execute, None],
+ [0, Gdk.KEY_Tab, self.on_complete, None],
+ [0, Gdk.KEY_ISO_Left_Tab, self.on_complete, None]
+ ]
+
+ self._re_complete = re.compile('("((?:\\\\"|[^"])*)"?|\'((?:\\\\\'|[^\'])*)\'?|[^\s]+)')
+ self._command_state = commands.Commands.State()
- def on_view_style_updated(self, widget):
- self.copy_style_from_view()
-
- def get_border_color(self):
- color = self.get_background_color().copy()
- color.red = 1 - color.red
- color.green = 1 - color.green
- color.blue = 1 - color.blue
- color.alpha = 0.5
-
- return color
-
- def get_background_color(self):
- context = self._view.get_style_context()
- return context.get_background_color(Gtk.StateFlags.NORMAL)
-
- def get_foreground_color(self):
- context = self._view.get_style_context()
- return context.get_color(Gtk.StateFlags.NORMAL)
+ def on_view_style_updated(self, widget):
+ self.copy_style_from_view()
+
+ def get_border_color(self):
+ color = self.get_background_color().copy()
+ color.red = 1 - color.red
+ color.green = 1 - color.green
+ color.blue = 1 - color.blue
+ color.alpha = 0.5
+
+ return color
+
+ def get_background_color(self):
+ context = self._view.get_style_context()
+ return context.get_background_color(Gtk.StateFlags.NORMAL)
+
+ def get_foreground_color(self):
+ context = self._view.get_style_context()
+ return context.get_color(Gtk.StateFlags.NORMAL)
- def get_font(self):
- context = self._view.get_style_context()
- return context.get_font(Gtk.StateFlags.NORMAL)
-
- def copy_style_from_view(self, widget=None):
- if widget != None:
- context = self._view.get_style_context()
- font = context.get_font(Gtk.StateFlags.NORMAL)
-
- widget.override_color(Gtk.StateFlags.NORMAL, self.get_foreground_color())
- widget.override_background_color(Gtk.StateFlags.NORMAL, self.get_background_color())
- widget.override_font(self.get_font())
- else:
- if self._entry:
- self.copy_style_from_view(self._entry)
-
- if self._prompt_label:
- self.copy_style_from_view(self._prompt_label)
-
- def view(self):
- return self._view
-
- def on_size_allocate(self, widget, alloc):
- alloc = self.get_allocation()
- self._view.set_border_window_size(Gtk.TextWindowType.BOTTOM, alloc.height)
-
- win = self._view.get_window(Gtk.TextWindowType.BOTTOM)
- self.set_size_request(win.get_width(), -1)
+ def get_font(self):
+ context = self._view.get_style_context()
+ return context.get_font(Gtk.StateFlags.NORMAL)
+
+ def copy_style_from_view(self, widget=None):
+ if widget != None:
+ context = self._view.get_style_context()
+ font = context.get_font(Gtk.StateFlags.NORMAL)
+
+ widget.override_color(Gtk.StateFlags.NORMAL, self.get_foreground_color())
+ widget.override_background_color(Gtk.StateFlags.NORMAL, self.get_background_color())
+ widget.override_font(self.get_font())
+ else:
+ if self._entry:
+ self.copy_style_from_view(self._entry)
+
+ if self._prompt_label:
+ self.copy_style_from_view(self._prompt_label)
+
+ def view(self):
+ return self._view
+
+ def on_size_allocate(self, widget, alloc):
+ alloc = self.get_allocation()
+ self._view.set_border_window_size(Gtk.TextWindowType.BOTTOM, alloc.height)
+
+ win = self._view.get_window(Gtk.TextWindowType.BOTTOM)
+ self.set_size_request(win.get_width(), -1)
- # NOTE: we need to do this explicitly somehow, otherwise the window
- # size will not be updated unless something else happens, not exactly
- # sure what. This might be caused by the multi notebook, or custom
- # animation layouting?
- self._view.get_parent().resize_children()
-
- def attach(self):
- # Attach ourselves in the text view, and position just above the
- # text window
- win = self._view.get_window(Gtk.TextWindowType.TEXT)
- alloc = self.get_allocation()
-
- self._view.set_border_window_size(Gtk.TextWindowType.BOTTOM, max(alloc.height, 1))
- self._view.add_child_in_window(self, Gtk.TextWindowType.BOTTOM, 0, 0)
-
- win = self._view.get_window(Gtk.TextWindowType.BOTTOM)
-
- # Set same color as gutter, i.e. bg color of the view
- context = self._view.get_style_context()
- color = context.get_background_color(Gtk.StateFlags.NORMAL)
- win.set_background_rgba(color)
-
- self.show()
- self.set_size_request(win.get_width(), -1)
-
- def on_entry_focus_out(self, widget, evnt):
- if self._entry.get_sensitive():
- self.destroy()
-
- def on_entry_key_press(self, widget, evnt):
- state = evnt.state & Gtk.accelerator_get_default_mod_mask()
- text = self._entry.get_text()
-
- if evnt.keyval == Gdk.KEY_Escape:
- if self._info_window:
- if self._suspended:
- self._suspended.resume()
-
- if self._info_window:
- self._info_window.destroy()
-
- self._entry.set_sensitive(True)
- elif self._accel_group:
- self._accel_group = self._accel_group.parent
+ # NOTE: we need to do this explicitly somehow, otherwise the window
+ # size will not be updated unless something else happens, not exactly
+ # sure what. This might be caused by the multi notebook, or custom
+ # animation layouting?
+ self._view.get_parent().resize_children()
+
+ def attach(self):
+ # Attach ourselves in the text view, and position just above the
+ # text window
+ win = self._view.get_window(Gtk.TextWindowType.TEXT)
+ alloc = self.get_allocation()
+
+ self._view.set_border_window_size(Gtk.TextWindowType.BOTTOM, max(alloc.height, 1))
+ self._view.add_child_in_window(self, Gtk.TextWindowType.BOTTOM, 0, 0)
+
+ win = self._view.get_window(Gtk.TextWindowType.BOTTOM)
+
+ # Set same color as gutter, i.e. bg color of the view
+ context = self._view.get_style_context()
+ color = context.get_background_color(Gtk.StateFlags.NORMAL)
+ win.set_background_rgba(color)
+
+ self.show()
+ self.set_size_request(win.get_width(), -1)
+
+ def on_entry_focus_out(self, widget, evnt):
+ if self._entry.get_sensitive():
+ self.destroy()
+
+ def on_entry_key_press(self, widget, evnt):
+ state = evnt.state & Gtk.accelerator_get_default_mod_mask()
+ text = self._entry.get_text()
+
+ if evnt.keyval == Gdk.KEY_Escape:
+ if self._info_window:
+ if self._suspended:
+ self._suspended.resume()
+
+ if self._info_window:
+ self._info_window.destroy()
+
+ self._entry.set_sensitive(True)
+ elif self._accel_group:
+ self._accel_group = self._accel_group.parent
- if not self._accel_group or not self._accel_group.parent:
- self._entry.set_editable(True)
- self._accel_group = None
+ if not self._accel_group or not self._accel_group.parent:
+ self._entry.set_editable(True)
+ self._accel_group = None
- self.prompt()
- elif text:
- self._entry.set_text('')
- elif self._command_state:
- self._command_state.clear()
- self.prompt()
- else:
- self._view.grab_focus()
- self.destroy()
+ self.prompt()
+ elif text:
+ self._entry.set_text('')
+ elif self._command_state:
+ self._command_state.clear()
+ self.prompt()
+ else:
+ self._view.grab_focus()
+ self.destroy()
- return True
+ return True
- if state or self._accel_group:
- # Check if it should be handled by the accel group
- group = self._accel_group
+ if state or self._accel_group:
+ # Check if it should be handled by the accel group
+ group = self._accel_group
- if not self._accel_group:
- group = commands.Commands().accelerator_group()
+ if not self._accel_group:
+ group = commands.Commands().accelerator_group()
- accel = group.activate(evnt.keyval, state)
+ accel = group.activate(evnt.keyval, state)
- if isinstance(accel, commands.accel_group.AccelGroup):
- self._accel_group = accel
- self._entry.set_text('')
- self._entry.set_editable(False)
- self.prompt()
+ if isinstance(accel, commands.accel_group.AccelGroup):
+ self._accel_group = accel
+ self._entry.set_text('')
+ self._entry.set_editable(False)
+ self.prompt()
- return True
- elif isinstance(accel, commands.accel_group.AccelCallback):
- self._entry.set_editable(True)
- self.run_command(lambda: accel.activate(self._command_state, self))
- return True
+ return True
+ elif isinstance(accel, commands.accel_group.AccelCallback):
+ self._entry.set_editable(True)
+ self.run_command(lambda: accel.activate(self._command_state, self))
+ return True
- if not self._entry.get_editable():
- return True
+ if not self._entry.get_editable():
+ return True
- for handler in self._handlers:
- if (handler[0] == None or handler[0] == state) and evnt.keyval == handler[1] and handler[2](handler[3], state):
- return True
+ for handler in self._handlers:
+ if (handler[0] == None or handler[0] == state) and evnt.keyval == handler[1] and handler[2](handler[3], state):
+ return True
- if self._info_window and self._info_window.empty():
- self._info_window.destroy()
+ if self._info_window and self._info_window.empty():
+ self._info_window.destroy()
- self._history_prefix = None
- return False
+ self._history_prefix = None
+ return False
- def on_history_move(self, direction, modifier):
- pos = self._entry.get_position()
+ def on_history_move(self, direction, modifier):
+ pos = self._entry.get_position()
- self._history.update(self._entry.get_text())
+ self._history.update(self._entry.get_text())
- if self._history_prefix == None:
- if len(self._entry.get_text()) == pos:
- self._history_prefix = self._entry.get_chars(0, pos)
- else:
- self._history_prefix = ''
+ if self._history_prefix == None:
+ if len(self._entry.get_text()) == pos:
+ self._history_prefix = self._entry.get_chars(0, pos)
+ else:
+ self._history_prefix = ''
- if self._history_prefix == None:
- hist = ''
- else:
- hist = self._history_prefix
+ if self._history_prefix == None:
+ hist = ''
+ else:
+ hist = self._history_prefix
- next = self._history.move(direction, hist)
+ next = self._history.move(direction, hist)
- if next != None:
- self._entry.set_text(next)
- self._entry.set_position(-1)
+ if next != None:
+ self._entry.set_text(next)
+ self._entry.set_position(-1)
- return True
+ return True
- def prompt(self, pr=''):
- self._prompt = pr
+ def prompt(self, pr=''):
+ self._prompt = pr
- if self._accel_group != None:
- pr = '<i>%s</i>' % (saxutils.escape(self._accel_group.full_name()),)
+ if self._accel_group != None:
+ pr = '<i>%s</i>' % (saxutils.escape(self._accel_group.full_name()),)
- if not pr:
- pr = ''
- else:
- pr = ' ' + pr
+ if not pr:
+ pr = ''
+ else:
+ pr = ' ' + pr
- self._prompt_label.set_markup('<b>>>></b>%s' % pr)
+ self._prompt_label.set_markup('<b>>>></b>%s' % pr)
- def make_info(self):
- if self._info_window == None:
- self._info_window = Info(self)
- self._info_window.show()
+ def make_info(self):
+ if self._info_window == None:
+ self._info_window = Info(self)
+ self._info_window.show()
- self._info_window.connect('destroy', self.on_info_window_destroy)
+ self._info_window.connect('destroy', self.on_info_window_destroy)
- def on_info_window_destroy(self, widget):
- self._info_window = None
+ def on_info_window_destroy(self, widget):
+ self._info_window = None
- def info_show(self, text='', use_markup=False):
- self.make_info()
- self._info_window.add_lines(text, use_markup)
+ def info_show(self, text='', use_markup=False):
+ self.make_info()
+ self._info_window.add_lines(text, use_markup)
- def info_status(self, text):
- self.make_info()
- self._info_window.status(text)
+ def info_status(self, text):
+ self.make_info()
+ self._info_window.status(text)
- def info_add_action(self, stock, callback, data=None):
- self.make_info()
- return self._info_window.add_action(stock, callback, data)
+ def info_add_action(self, stock, callback, data=None):
+ self.make_info()
+ return self._info_window.add_action(stock, callback, data)
- def command_history_done(self):
- self._history.add(self._entry.get_text())
- self._history_prefix = None
- self._entry.set_text('')
+ def command_history_done(self):
+ self._history.add(self._entry.get_text())
+ self._history_prefix = None
+ self._entry.set_text('')
- def on_wait_cancel(self):
- if self._suspended:
- self._suspended.resume()
+ def on_wait_cancel(self):
+ if self._suspended:
+ self._suspended.resume()
- if self._cancel_button:
- self._cancel_button.destroy()
+ if self._cancel_button:
+ self._cancel_button.destroy()
- if self._info_window and self._info_window.empty():
- self._info_window.destroy()
- self._entry.grab_focus()
- self._entry.set_sensitive(True)
+ if self._info_window and self._info_window.empty():
+ self._info_window.destroy()
+ self._entry.grab_focus()
+ self._entry.set_sensitive(True)
- def _show_wait_cancel(self):
- self._cancel_button = self.info_add_action(Gtk.STOCK_STOP, self.on_wait_cancel)
- self.info_status('<i>Waiting to finish...</i>')
+ def _show_wait_cancel(self):
+ self._cancel_button = self.info_add_action(Gtk.STOCK_STOP, self.on_wait_cancel)
+ self.info_status('<i>Waiting to finish...</i>')
- self._wait_timeout = 0
- return False
+ self._wait_timeout = 0
+ return False
- def _complete_word_match(self, match):
- for i in (3, 2, 0):
- if match.group(i) != None:
- return [match.group(i), match.start(i), match.end(i)]
+ def _complete_word_match(self, match):
+ for i in (3, 2, 0):
+ if match.group(i) != None:
+ return [match.group(i), match.start(i), match.end(i)]
- def on_suspend_resume(self):
- if self._wait_timeout:
- GObject.source_remove(self._wait_timeout)
- self._wait_timeout = 0
- else:
- self._cancel_button.destroy()
- self._cancel_button = None
- self.info_status(None)
+ def on_suspend_resume(self):
+ if self._wait_timeout:
+ GObject.source_remove(self._wait_timeout)
+ self._wait_timeout = 0
+ else:
+ self._cancel_button.destroy()
+ self._cancel_button = None
+ self.info_status(None)
- self._entry.set_sensitive(True)
- self.command_history_done()
+ self._entry.set_sensitive(True)
+ self.command_history_done()
- if self._entry.props.has_focus or (self._info_window and not self._info_window.empty()):
- self._entry.grab_focus()
+ if self._entry.props.has_focus or (self._info_window and not self._info_window.empty()):
+ self._entry.grab_focus()
- self.on_execute(None, 0)
+ self.on_execute(None, 0)
- def ellipsize(self, s, size):
- if len(s) <= size:
- return s
+ def ellipsize(self, s, size):
+ if len(s) <= size:
+ return s
- mid = (size - 4) / 2
- return s[:mid] + '...' + s[-mid:]
+ mid = (size - 4) / 2
+ return s[:mid] + '...' + s[-mid:]
- def destroy(self):
- self.hide()
- Gtk.EventBox.destroy(self)
+ def destroy(self):
+ self.hide()
+ Gtk.EventBox.destroy(self)
- def run_command(self, cb):
- self._suspended = None
+ def run_command(self, cb):
+ self._suspended = None
- try:
- ret = cb()
- except Exception, e:
- self.command_history_done()
- self._command_state.clear()
+ try:
+ ret = cb()
+ except Exception, e:
+ self.command_history_done()
+ self._command_state.clear()
- self.prompt()
+ self.prompt()
- # Show error in info
- self.info_show('<b><span color="#f66">Error:</span></b> ' + saxutils.escape(str(e)), True)
+ # Show error in info
+ self.info_show('<b><span color="#f66">Error:</span></b> ' + saxutils.escape(str(e)), True)
- if not isinstance(e, commands.exceptions.Execute):
- self.info_show(self.format_trace(), False)
+ if not isinstance(e, commands.exceptions.Execute):
+ self.info_show(self.format_trace(), False)
- return None
+ return None
- if ret == commands.result.Result.SUSPEND:
- # Wait for it...
- self._suspended = ret
- ret.register(self.on_suspend_resume)
+ if ret == commands.result.Result.SUSPEND:
+ # Wait for it...
+ self._suspended = ret
+ ret.register(self.on_suspend_resume)
- self._wait_timeout = GObject.timeout_add(500, self._show_wait_cancel)
- self._entry.set_sensitive(False)
- else:
- self.command_history_done()
- self.prompt('')
+ self._wait_timeout = GObject.timeout_add(500, self._show_wait_cancel)
+ self._entry.set_sensitive(False)
+ else:
+ self.command_history_done()
+ self.prompt('')
- if ret == commands.result.Result.PROMPT:
- self.prompt(ret.prompt)
- elif (ret == None or ret == commands.result.HIDE) and not self._prompt and (not self._info_window or self._info_window.empty()):
- self._command_state.clear()
- self._view.grab_focus()
- self.destroy()
- else:
- self._entry.grab_focus()
+ if ret == commands.result.Result.PROMPT:
+ self.prompt(ret.prompt)
+ elif (ret == None or ret == commands.result.HIDE) and not self._prompt and (not self._info_window or self._info_window.empty()):
+ self._command_state.clear()
+ self._view.grab_focus()
+ self.destroy()
+ else:
+ self._entry.grab_focus()
- return ret
-
- def format_trace(self):
- tp, val, tb = sys.exc_info()
-
- origtb = tb
-
- thisdir = os.path.dirname(__file__)
-
- # Skip frames up until after the last entry.py...
- while True:
- filename = tb.tb_frame.f_code.co_filename
-
- dname = os.path.dirname(filename)
-
- if not dname.startswith(thisdir):
- break
-
- tb = tb.tb_next
-
- msg = traceback.format_exception(tp, val, tb)
- r = ''.join(msg[0:-1])
-
- # This is done to prevent cyclic references, see python
- # documentation on sys.exc_info
- del origtb
-
- return r
-
- def on_execute(self, dummy, modifier):
- if self._info_window and not self._suspended:
- self._info_window.destroy()
-
- text = self._entry.get_text().strip()
- words = list(self._re_complete.finditer(text))
- wordsstr = []
-
- for word in words:
- spec = self._complete_word_match(word)
- wordsstr.append(spec[0])
+ return ret
+
+ def format_trace(self):
+ tp, val, tb = sys.exc_info()
+
+ origtb = tb
+
+ thisdir = os.path.dirname(__file__)
+
+ # Skip frames up until after the last entry.py...
+ while True:
+ filename = tb.tb_frame.f_code.co_filename
+
+ dname = os.path.dirname(filename)
+
+ if not dname.startswith(thisdir):
+ break
+
+ tb = tb.tb_next
+
+ msg = traceback.format_exception(tp, val, tb)
+ r = ''.join(msg[0:-1])
+
+ # This is done to prevent cyclic references, see python
+ # documentation on sys.exc_info
+ del origtb
+
+ return r
+
+ def on_execute(self, dummy, modifier):
+ if self._info_window and not self._suspended:
+ self._info_window.destroy()
+
+ text = self._entry.get_text().strip()
+ words = list(self._re_complete.finditer(text))
+ wordsstr = []
+
+ for word in words:
+ spec = self._complete_word_match(word)
+ wordsstr.append(spec[0])
- if not wordsstr and not self._command_state:
- self._entry.set_text('')
- return
+ if not wordsstr and not self._command_state:
+ self._entry.set_text('')
+ return
- self.run_command(lambda: commands.Commands().execute(self._command_state, text, words, wordsstr, self, modifier))
+ self.run_command(lambda: commands.Commands().execute(self._command_state, text, words, wordsstr, self, modifier))
- return True
+ return True
- def on_complete(self, dummy, modifier):
- # First split all the text in words
- text = self._entry.get_text()
- pos = self._entry.get_position()
+ def on_complete(self, dummy, modifier):
+ # First split all the text in words
+ text = self._entry.get_text()
+ pos = self._entry.get_position()
- words = list(self._re_complete.finditer(text))
- wordsstr = []
-
- for word in words:
- spec = self._complete_word_match(word)
- wordsstr.append(spec[0])
-
- # Find out at which word the cursor actually is
- # Examples:
- # * hello world|
- # * hello| world
- # * |hello world
- # * hello wor|ld
- # * hello | world
- # * "hello world|"
- posidx = None
-
- for idx in xrange(0, len(words)):
- spec = self._complete_word_match(words[idx])
-
- if words[idx].start(0) > pos:
- # Empty space, new completion
- wordsstr.insert(idx, '')
- words.insert(idx, None)
- posidx = idx
- break
- elif spec[2] == pos:
- # At end of word, resume completion
- posidx = idx
- break
- elif spec[1] <= pos and spec[2] > pos:
- # In middle of word, do not complete
- return True
-
- if posidx == None:
- wordsstr.append('')
- words.append(None)
- posidx = len(wordsstr) - 1
-
- # First word completes a command, if not in any special 'mode'
- # otherwise, relay completion to the command, or complete by advice
- # from the 'mode' (prompt)
- cmds = commands.Commands()
-
- if not self._command_state and posidx == 0:
- # Complete the first command
- ret = commands.completion.command(words=wordsstr, idx=posidx)
- else:
- complete = None
- realidx = posidx
-
- if not self._command_state:
- # Get the command first
- cmd = commands.completion.single_command(wordsstr, 0)
- realidx -= 1
-
- ww = wordsstr[1:]
- else:
- cmd = self._command_state.top()
- ww = wordsstr
-
- if cmd:
- complete = cmd.autocomplete_func()
-
- if not complete:
- return True
-
- # 'complete' contains a dict with arg -> func to do the completion
- # of the named argument the command (or stack item) expects
- args, varargs = cmd.args()
-
- # Remove system arguments
- s = ['argstr', 'args', 'entry', 'view']
- args = filter(lambda x: not x in s, args)
-
- if realidx < len(args):
- arg = args[realidx]
- elif varargs:
- arg = '*'
- else:
- return True
-
- if not arg in complete:
- return True
-
- func = complete[arg]
-
- try:
- spec = utils.getargspec(func)
-
- if not ww:
- ww = ['']
-
- kwargs = {
- 'words': ww,
- 'idx': realidx,
- 'view': self._view
- }
-
- if not spec.keywords:
- for k in kwargs.keys():
- if not k in spec.args:
- del kwargs[k]
-
- ret = func(**kwargs)
- except Exception, e:
- # Can be number of arguments, or return values or simply buggy
- # modules
- print e
- traceback.print_exc()
- return True
-
- if not ret or not ret[0]:
- return True
-
- res = ret[0]
- completed = ret[1]
-
- if len(ret) > 2:
- after = ret[2]
- else:
- after = ' '
-
- # Replace the word
- if words[posidx] == None:
- # At end of everything, just append
- spec = None
-
- self._entry.insert_text(completed, self._entry.get_text_length())
- self._entry.set_position(-1)
- else:
- spec = self._complete_word_match(words[posidx])
+ words = list(self._re_complete.finditer(text))
+ wordsstr = []
+
+ for word in words:
+ spec = self._complete_word_match(word)
+ wordsstr.append(spec[0])
+
+ # Find out at which word the cursor actually is
+ # Examples:
+ # * hello world|
+ # * hello| world
+ # * |hello world
+ # * hello wor|ld
+ # * hello | world
+ # * "hello world|"
+ posidx = None
+
+ for idx in xrange(0, len(words)):
+ spec = self._complete_word_match(words[idx])
+
+ if words[idx].start(0) > pos:
+ # Empty space, new completion
+ wordsstr.insert(idx, '')
+ words.insert(idx, None)
+ posidx = idx
+ break
+ elif spec[2] == pos:
+ # At end of word, resume completion
+ posidx = idx
+ break
+ elif spec[1] <= pos and spec[2] > pos:
+ # In middle of word, do not complete
+ return True
+
+ if posidx == None:
+ wordsstr.append('')
+ words.append(None)
+ posidx = len(wordsstr) - 1
+
+ # First word completes a command, if not in any special 'mode'
+ # otherwise, relay completion to the command, or complete by advice
+ # from the 'mode' (prompt)
+ cmds = commands.Commands()
+
+ if not self._command_state and posidx == 0:
+ # Complete the first command
+ ret = commands.completion.command(words=wordsstr, idx=posidx)
+ else:
+ complete = None
+ realidx = posidx
+
+ if not self._command_state:
+ # Get the command first
+ cmd = commands.completion.single_command(wordsstr, 0)
+ realidx -= 1
+
+ ww = wordsstr[1:]
+ else:
+ cmd = self._command_state.top()
+ ww = wordsstr
+
+ if cmd:
+ complete = cmd.autocomplete_func()
+
+ if not complete:
+ return True
+
+ # 'complete' contains a dict with arg -> func to do the completion
+ # of the named argument the command (or stack item) expects
+ args, varargs = cmd.args()
+
+ # Remove system arguments
+ s = ['argstr', 'args', 'entry', 'view']
+ args = filter(lambda x: not x in s, args)
+
+ if realidx < len(args):
+ arg = args[realidx]
+ elif varargs:
+ arg = '*'
+ else:
+ return True
+
+ if not arg in complete:
+ return True
+
+ func = complete[arg]
+
+ try:
+ spec = utils.getargspec(func)
+
+ if not ww:
+ ww = ['']
+
+ kwargs = {
+ 'words': ww,
+ 'idx': realidx,
+ 'view': self._view
+ }
+
+ if not spec.keywords:
+ for k in kwargs.keys():
+ if not k in spec.args:
+ del kwargs[k]
+
+ ret = func(**kwargs)
+ except Exception, e:
+ # Can be number of arguments, or return values or simply buggy
+ # modules
+ print e
+ traceback.print_exc()
+ return True
+
+ if not ret or not ret[0]:
+ return True
+
+ res = ret[0]
+ completed = ret[1]
+
+ if len(ret) > 2:
+ after = ret[2]
+ else:
+ after = ' '
+
+ # Replace the word
+ if words[posidx] == None:
+ # At end of everything, just append
+ spec = None
+
+ self._entry.insert_text(completed, self._entry.get_text_length())
+ self._entry.set_position(-1)
+ else:
+ spec = self._complete_word_match(words[posidx])
- self._entry.delete_text(spec[1], spec[2])
- self._entry.insert_text(completed, spec[1])
- self._entry.set_position(spec[1] + len(completed))
+ self._entry.delete_text(spec[1], spec[2])
+ self._entry.insert_text(completed, spec[1])
+ self._entry.set_position(spec[1] + len(completed))
- if len(res) == 1:
- # Full completion
- lastpos = self._entry.get_position()
+ if len(res) == 1:
+ # Full completion
+ lastpos = self._entry.get_position()
- if not isinstance(res[0], commands.module.Module) or not res[0].commands():
- if words[posidx] and after == ' ' and (words[posidx].group(2) != None or words[posidx].group(3) != None):
- lastpos = lastpos + 1
+ if not isinstance(res[0], commands.module.Module) or not res[0].commands():
+ if words[posidx] and after == ' ' and (words[posidx].group(2) != None or words[posidx].group(3) != None):
+ lastpos = lastpos + 1
- self._entry.insert_text(after, lastpos)
- self._entry.set_position(lastpos + 1)
- elif completed == wordsstr[posidx] or not res[0].method:
- self._entry.insert_text('.', lastpos)
- self._entry.set_position(lastpos + 1)
+ self._entry.insert_text(after, lastpos)
+ self._entry.set_position(lastpos + 1)
+ elif completed == wordsstr[posidx] or not res[0].method:
+ self._entry.insert_text('.', lastpos)
+ self._entry.set_position(lastpos + 1)
- if self._info_window:
- self._info_window.destroy()
- else:
- # Show popup with completed items
- if self._info_window:
- self._info_window.clear()
+ if self._info_window:
+ self._info_window.destroy()
+ else:
+ # Show popup with completed items
+ if self._info_window:
+ self._info_window.clear()
- ret = []
+ ret = []
- for x in res:
- if isinstance(x, commands.method.Method):
- ret.append('<b>' + saxutils.escape(x.name) + '</b> (<i>' + x.oneline_doc() + '</i>)')
- else:
- ret.append(str(x))
+ for x in res:
+ if isinstance(x, commands.method.Method):
+ ret.append('<b>' + saxutils.escape(x.name) + '</b> (<i>' + x.oneline_doc() + '</i>)')
+ else:
+ ret.append(str(x))
- self.info_show("\n".join(ret), True)
+ self.info_show("\n".join(ret), True)
- return True
+ return True
- def on_draw(self, widget, ct):
- win = widget.get_window(Gtk.TextWindowType.BOTTOM)
+ def on_draw(self, widget, ct):
+ win = widget.get_window(Gtk.TextWindowType.BOTTOM)
- if not Gtk.cairo_should_draw_window(ct, win):
- return False
+ if not Gtk.cairo_should_draw_window(ct, win):
+ return False
- Gtk.cairo_transform_to_window(ct, widget, win)
+ Gtk.cairo_transform_to_window(ct, widget, win)
- color = self.get_border_color()
- width = win.get_width()
+ color = self.get_border_color()
+ width = win.get_width()
- ct.set_source_rgba(color.red, color.green, color.blue, color.alpha)
- ct.move_to(0, 0)
- ct.line_to(width, 0)
- ct.stroke()
+ ct.set_source_rgba(color.red, color.green, color.blue, color.alpha)
+ ct.move_to(0, 0)
+ ct.line_to(width, 0)
+ ct.stroke()
- return False
+ return False
- def on_destroy(self, widget):
- self._view.set_border_window_size(Gtk.TextWindowType.BOTTOM, 0)
- self._view.disconnect(self.view_style_updated_id)
- self._view.disconnect(self.view_draw_id)
+ def on_destroy(self, widget):
+ self._view.set_border_window_size(Gtk.TextWindowType.BOTTOM, 0)
+ self._view.disconnect(self.view_style_updated_id)
+ self._view.disconnect(self.view_draw_id)
- if self._info_window:
- self._info_window.destroy()
+ if self._info_window:
+ self._info_window.destroy()
- self._history.save()
+ self._history.save()
-# vi:ex:ts=4
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/history.py b/plugins/commander/commander/history.py
index 94f3b44..790741f 100644
--- a/plugins/commander/commander/history.py
+++ b/plugins/commander/commander/history.py
@@ -22,77 +22,79 @@
import os
class History:
- def __init__(self, filename):
- self._filename = filename
- self._history = ['']
- self._ptr = 0
+ def __init__(self, filename):
+ self._filename = filename
+ self._history = ['']
+ self._ptr = 0
- self.load()
+ self.load()
- def find(self, direction, prefix):
- ptr = self._ptr + direction
+ def find(self, direction, prefix):
+ ptr = self._ptr + direction
- while ptr >= 0 and ptr < len(self._history):
- if self._history[ptr].startswith(prefix):
- return ptr
+ while ptr >= 0 and ptr < len(self._history):
+ if self._history[ptr].startswith(prefix):
+ return ptr
- ptr += direction
+ ptr += direction
- return -1
+ return -1
- def move(self, direction, prefix):
- next = self.find(direction, prefix)
+ def move(self, direction, prefix):
+ next = self.find(direction, prefix)
- if next != -1:
- self._ptr = next
- return self._history[self._ptr]
- else:
- return None
+ if next != -1:
+ self._ptr = next
+ return self._history[self._ptr]
+ else:
+ return None
- def up(self, prefix=''):
- return self.move(-1, prefix)
+ def up(self, prefix=''):
+ return self.move(-1, prefix)
- def down(self, prefix=''):
- return self.move(1, prefix)
+ def down(self, prefix=''):
+ return self.move(1, prefix)
- def add(self, line):
- if line.strip() != '':
- if self._history[-1] != '':
- self._history.append(line)
- else:
- self._history[-1] = line
+ def add(self, line):
+ if line.strip() != '':
+ if self._history[-1] != '':
+ self._history.append(line)
+ else:
+ self._history[-1] = line
- if self._history[-1] != '':
- self._history.append('')
+ if self._history[-1] != '':
+ self._history.append('')
- self._ptr = len(self._history) - 1
+ self._ptr = len(self._history) - 1
- def update(self, line):
- self._history[self._ptr] = line
+ def update(self, line):
+ self._history[self._ptr] = line
- def load(self):
- try:
- self._history = map(lambda x: x.strip("\n"), file(self._filename, 'r').readlines())
- self._history.append('')
- self._ptr = len(self._history) - 1
- except IOError:
- pass
+ def load(self):
+ try:
+ self._history = map(lambda x: x.strip("\n"), file(self._filename, 'r').readlines())
+ self._history.append('')
+ self._ptr = len(self._history) - 1
+ except IOError:
+ pass
- def save(self):
- try:
- os.makedirs(os.path.dirname(self._filename))
- except OSError:
- pass
+ def save(self):
+ try:
+ os.makedirs(os.path.dirname(self._filename))
+ except OSError:
+ pass
- try:
- f = file(self._filename, 'w')
+ try:
+ f = file(self._filename, 'w')
- if self._history[-1] == '':
- hist = self._history[:-1]
- else:
- hist = self._history
+ if self._history[-1] == '':
+ hist = self._history[:-1]
+ else:
+ hist = self._history
- f.writelines(map(lambda x: x + "\n", hist))
- f.close()
- except IOError:
- pass
+ f.writelines(map(lambda x: x + "\n", hist))
+ f.close()
+ except IOError:
+ pass
+
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/info.py b/plugins/commander/commander/info.py
index a5fff5f..d3c3a77 100644
--- a/plugins/commander/commander/info.py
+++ b/plugins/commander/commander/info.py
@@ -24,318 +24,318 @@ from gi.repository import Pango, Gdk, Gtk
import math
class Info(TransparentWindow):
- __gtype_name__ = "CommanderInfo"
+ __gtype_name__ = "CommanderInfo"
- def __init__(self, entry):
- super(Info, self).__init__(Gtk.WindowType.POPUP)
+ def __init__(self, entry):
+ super(Info, self).__init__(Gtk.WindowType.POPUP)
- self._entry = entry
- self._vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)
+ self._entry = entry
+ self._vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)
- self.set_transient_for(entry.get_toplevel())
+ self.set_transient_for(entry.get_toplevel())
- self._vw = Gtk.ScrolledWindow()
- self._vw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.NEVER)
- self._vw.show()
+ self._vw = Gtk.ScrolledWindow()
+ self._vw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.NEVER)
+ self._vw.show()
- self._text = Gtk.TextView()
+ self._text = Gtk.TextView()
- font = self._entry.get_font()
- fgcolor = self._entry.get_foreground_color()
- bgcolor = self.background_color()
+ font = self._entry.get_font()
+ fgcolor = self._entry.get_foreground_color()
+ bgcolor = self.background_color()
- self._text.override_font(font)
- self._text.override_color(Gtk.StateFlags.NORMAL, fgcolor)
- self._text.override_background_color(Gtk.StateFlags.NORMAL, bgcolor)
+ self._text.override_font(font)
+ self._text.override_color(Gtk.StateFlags.NORMAL, fgcolor)
+ self._text.override_background_color(Gtk.StateFlags.NORMAL, bgcolor)
- self._text.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
+ self._text.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
- buf = self._text.get_buffer()
+ buf = self._text.get_buffer()
- buf.connect_after('insert-text', self.on_text_insert_text)
- buf.connect_after('delete-range', self.on_text_delete_range)
+ buf.connect_after('insert-text', self.on_text_insert_text)
+ buf.connect_after('delete-range', self.on_text_delete_range)
- self._text.set_editable(False)
+ self._text.set_editable(False)
- self._vw.add(self._text)
- self._vbox.pack_end(self._vw, False, False, 0)
- self._vbox.show()
- self._button_bar = None
+ self._vw.add(self._text)
+ self._vbox.pack_end(self._vw, False, False, 0)
+ self._vbox.show()
+ self._button_bar = None
- self.add(self._vbox)
- self._text.show()
- self._status_label = None
+ self.add(self._vbox)
+ self._text.show()
+ self._status_label = None
- self.props.can_focus = False
- self.set_border_width(8)
+ self.props.can_focus = False
+ self.set_border_width(8)
- self.attach()
- self.show()
+ self.attach()
+ self.show()
- self.max_lines = 10
+ self.max_lines = 10
- self.connect_after('size-allocate', self.on_size_allocate)
- self.connect_after('draw', self.on_draw)
+ self.connect_after('size-allocate', self.on_size_allocate)
+ self.connect_after('draw', self.on_draw)
- self._attr_map = {
- Pango.AttrType.STYLE: 'style',
- Pango.AttrType.WEIGHT: 'weight',
- Pango.AttrType.VARIANT: 'variant',
- Pango.AttrType.STRETCH: 'stretch',
- Pango.AttrType.SIZE: 'size',
- Pango.AttrType.FOREGROUND: 'foreground',
- Pango.AttrType.BACKGROUND: 'background',
- Pango.AttrType.UNDERLINE: 'underline',
- Pango.AttrType.STRIKETHROUGH: 'strikethrough',
- Pango.AttrType.RISE: 'rise',
- Pango.AttrType.SCALE: 'scale'
- }
+ self._attr_map = {
+ Pango.AttrType.STYLE: 'style',
+ Pango.AttrType.WEIGHT: 'weight',
+ Pango.AttrType.VARIANT: 'variant',
+ Pango.AttrType.STRETCH: 'stretch',
+ Pango.AttrType.SIZE: 'size',
+ Pango.AttrType.FOREGROUND: 'foreground',
+ Pango.AttrType.BACKGROUND: 'background',
+ Pango.AttrType.UNDERLINE: 'underline',
+ Pango.AttrType.STRIKETHROUGH: 'strikethrough',
+ Pango.AttrType.RISE: 'rise',
+ Pango.AttrType.SCALE: 'scale'
+ }
- def empty(self):
- buf = self._text.get_buffer()
- return buf.get_start_iter().equal(buf.get_end_iter())
+ def empty(self):
+ buf = self._text.get_buffer()
+ return buf.get_start_iter().equal(buf.get_end_iter())
- def status(self, text=None):
- if self._status_label == None and text != None:
- self._status_label = Gtk.Label()
+ def status(self, text=None):
+ if self._status_label == None and text != None:
+ self._status_label = Gtk.Label()
- context = self._text.get_style_context()
- state = context.get_state()
- font_desc = context.get_font(state)
+ context = self._text.get_style_context()
+ state = context.get_state()
+ font_desc = context.get_font(state)
- self._status_label.override_font(font_desc)
+ self._status_label.override_font(font_desc)
- self._status_label.override_color(Gtk.StateFlags.NORMAL, context.get_color(Gtk.StateFlags.NORMAL))
- self._status_label.show()
- self._status_label.set_alignment(0, 0.5)
- self._status_label.set_padding(10, 0)
- self._status_label.set_use_markup(True)
+ self._status_label.override_color(Gtk.StateFlags.NORMAL, context.get_color(Gtk.StateFlags.NORMAL))
+ self._status_label.show()
+ self._status_label.set_alignment(0, 0.5)
+ self._status_label.set_padding(10, 0)
+ self._status_label.set_use_markup(True)
- self.ensure_button_bar()
- self._button_bar.pack_start(self._status_label, True, True, 0)
+ self.ensure_button_bar()
+ self._button_bar.pack_start(self._status_label, True, True, 0)
- if text != None:
- self._status_label.set_markup(text)
- elif self._status_label:
- self._status_label.destroy()
+ if text != None:
+ self._status_label.set_markup(text)
+ elif self._status_label:
+ self._status_label.destroy()
- if not self._button_bar and self.empty():
- self.destroy()
+ if not self._button_bar and self.empty():
+ self.destroy()
- def attrs_to_tags(self, attrs):
- buf = self._text.get_buffer()
- table = buf.get_tag_table()
- ret = []
+ def attrs_to_tags(self, attrs):
+ buf = self._text.get_buffer()
+ table = buf.get_tag_table()
+ ret = []
- for attr in attrs:
- if not attr.type in self._attr_map:
- continue
+ for attr in attrs:
+ if not attr.type in self._attr_map:
+ continue
- if attr.type == Pango.AttrType.FOREGROUND or attr.type == Pango.AttrType.BACKGROUND:
- value = attr.color
- else:
- value = attr.value
+ if attr.type == Pango.AttrType.FOREGROUND or attr.type == Pango.AttrType.BACKGROUND:
+ value = attr.color
+ else:
+ value = attr.value
- tagname = str(attr.type) + ':' + str(value)
+ tagname = str(attr.type) + ':' + str(value)
- tag = table.lookup(tagname)
+ tag = table.lookup(tagname)
- if not tag:
- tag = buf.create_tag(tagname)
- tag.set_property(self._attr_map[attr.type], value)
+ if not tag:
+ tag = buf.create_tag(tagname)
+ tag.set_property(self._attr_map[attr.type], value)
- ret.append(tag)
+ ret.append(tag)
- return ret
+ return ret
- def add_lines(self, line, use_markup=False):
- buf = self._text.get_buffer()
+ def add_lines(self, line, use_markup=False):
+ buf = self._text.get_buffer()
- if not buf.get_start_iter().equal(buf.get_end_iter()):
- line = "\n" + line
+ if not buf.get_start_iter().equal(buf.get_end_iter()):
+ line = "\n" + line
- if not use_markup:
- buf.insert(buf.get_end_iter(), line)
- return
+ if not use_markup:
+ buf.insert(buf.get_end_iter(), line)
+ return
- try:
- ret = Pango.parse_markup(line, -1, u'\x00')
- except Exception, e:
- print 'Could not parse markup:', e
- buf.insert(buf.get_end_iter(), line)
- return
+ try:
+ ret = Pango.parse_markup(line, -1, u'\x00')
+ except Exception, e:
+ print 'Could not parse markup:', e
+ buf.insert(buf.get_end_iter(), line)
+ return
- # TODO: fix this when pango supports get_iterator
- text = ret[2]
- buf.insert(buf.get_end_iter(), text)
+ # TODO: fix this when pango supports get_iterator
+ text = ret[2]
+ buf.insert(buf.get_end_iter(), text)
- return
+ return
- piter = ret[1].get_iterator()
+ piter = ret[1].get_iterator()
- while piter:
- attrs = piter.get_attrs()
- begin, end = piter.range()
+ while piter:
+ attrs = piter.get_attrs()
+ begin, end = piter.range()
- tags = self.attrs_to_tags(attrs)
- buf.insert_with_tags(buf.get_end_iter(), text[begin:end], *tags)
+ tags = self.attrs_to_tags(attrs)
+ buf.insert_with_tags(buf.get_end_iter(), text[begin:end], *tags)
- if not piter.next():
- break
+ if not piter.next():
+ break
- def toomany_lines(self):
- buf = self._text.get_buffer()
- piter = buf.get_start_iter()
- num = 0
+ def toomany_lines(self):
+ buf = self._text.get_buffer()
+ piter = buf.get_start_iter()
+ num = 0
- while self._text.forward_display_line(piter):
- num += 1
+ while self._text.forward_display_line(piter):
+ num += 1
- if num > self.max_lines:
- return True
+ if num > self.max_lines:
+ return True
- return False
+ return False
- def contents_changed(self):
- buf = self._text.get_buffer()
+ def contents_changed(self):
+ buf = self._text.get_buffer()
- if self.toomany_lines() and (self._vw.get_policy()[1] != Gtk.PolicyType.ALWAYS):
- self._vw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.ALWAYS)
+ if self.toomany_lines() and (self._vw.get_policy()[1] != Gtk.PolicyType.ALWAYS):
+ self._vw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.ALWAYS)
- layout = self._text.create_pango_layout('Some text to measure')
- extents = layout.get_pixel_extents()
+ layout = self._text.create_pango_layout('Some text to measure')
+ extents = layout.get_pixel_extents()
- self._vw.set_min_content_height(extents[1].height * self.max_lines)
- elif not self.toomany_lines() and (self._vw.get_policy()[1] == Gtk.PolicyType.ALWAYS):
- self._vw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.NEVER)
- self._vw.set_min_content_height(0)
+ self._vw.set_min_content_height(extents[1].height * self.max_lines)
+ elif not self.toomany_lines() and (self._vw.get_policy()[1] == Gtk.PolicyType.ALWAYS):
+ self._vw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.NEVER)
+ self._vw.set_min_content_height(0)
- if not self.toomany_lines():
- size = self.get_size()
- self.resize(size[0], 1)
+ if not self.toomany_lines():
+ size = self.get_size()
+ self.resize(size[0], 1)
- def ensure_button_bar(self):
- if not self._button_bar:
- self._button_bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=3)
- self._button_bar.show()
- self._vbox.pack_start(self._button_bar, False, False, 0)
+ def ensure_button_bar(self):
+ if not self._button_bar:
+ self._button_bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=3)
+ self._button_bar.show()
+ self._vbox.pack_start(self._button_bar, False, False, 0)
- def add_action(self, stock, callback, data=None):
- image = Gtk.Image.new_from_stock(stock, Gtk.IconSize.MENU)
- image.show()
+ def add_action(self, stock, callback, data=None):
+ image = Gtk.Image.new_from_stock(stock, Gtk.IconSize.MENU)
+ image.show()
- image.commander_action_stock_item = (stock, Gtk.IconSize.MENU)
+ image.commander_action_stock_item = (stock, Gtk.IconSize.MENU)
- self.ensure_button_bar()
+ self.ensure_button_bar()
- ev = Gtk.EventBox()
- ev.set_visible_window(False)
- ev.add(image)
- ev.show()
+ ev = Gtk.EventBox()
+ ev.set_visible_window(False)
+ ev.add(image)
+ ev.show()
- self._button_bar.pack_end(ev, False, False, 0)
+ self._button_bar.pack_end(ev, False, False, 0)
- ev.connect('button-press-event', self.on_action_activate, callback, data)
- ev.connect('enter-notify-event', self.on_action_enter_notify)
- ev.connect('leave-notify-event', self.on_action_leave_notify)
+ ev.connect('button-press-event', self.on_action_activate, callback, data)
+ ev.connect('enter-notify-event', self.on_action_enter_notify)
+ ev.connect('leave-notify-event', self.on_action_leave_notify)
- ev.connect_after('destroy', self.on_action_destroy)
- return ev
+ ev.connect_after('destroy', self.on_action_destroy)
+ return ev
- def on_action_destroy(self, widget):
- if self._button_bar and len(self._button_bar.get_children()) == 0:
- self._button_bar.destroy()
- self._button_bar = None
+ def on_action_destroy(self, widget):
+ if self._button_bar and len(self._button_bar.get_children()) == 0:
+ self._button_bar.destroy()
+ self._button_bar = None
- def on_action_enter_notify(self, widget, evnt):
- img = widget.get_child()
- img.set_state(Gtk.StateType.PRELIGHT)
- widget.get_window().set_cursor(Gdk.Cursor.new(Gdk.HAND2))
+ def on_action_enter_notify(self, widget, evnt):
+ img = widget.get_child()
+ img.set_state(Gtk.StateType.PRELIGHT)
+ widget.get_window().set_cursor(Gdk.Cursor.new(Gdk.HAND2))
- pix = img.render_icon(*img.commander_action_stock_item)
- img.set_from_pixbuf(pix)
+ pix = img.render_icon(*img.commander_action_stock_item)
+ img.set_from_pixbuf(pix)
- def on_action_leave_notify(self, widget, evnt):
- img = widget.get_child()
- img.set_state(Gtk.StateType.NORMAL)
- widget.get_window().set_cursor(None)
+ def on_action_leave_notify(self, widget, evnt):
+ img = widget.get_child()
+ img.set_state(Gtk.StateType.NORMAL)
+ widget.get_window().set_cursor(None)
- pix = img.render_icon(*img.commander_action_stock_item)
- img.set_from_pixbuf(pix)
+ pix = img.render_icon(*img.commander_action_stock_item)
+ img.set_from_pixbuf(pix)
- def on_action_activate(self, widget, evnt, callback, data):
- if data:
- callback(data)
- else:
- callback()
+ def on_action_activate(self, widget, evnt, callback, data):
+ if data:
+ callback(data)
+ else:
+ callback()
- def clear(self):
- self._text.get_buffer().set_text('')
+ def clear(self):
+ self._text.get_buffer().set_text('')
- def attach(self):
- vwwnd = self._entry._view.get_window(Gtk.TextWindowType.TEXT)
- origin = vwwnd.get_origin()
- geom = vwwnd.get_geometry()
+ def attach(self):
+ vwwnd = self._entry._view.get_window(Gtk.TextWindowType.TEXT)
+ origin = vwwnd.get_origin()
+ geom = vwwnd.get_geometry()
- margin = 5
+ margin = 5
- self.realize()
+ self.realize()
- alloc = self.get_allocation()
+ alloc = self.get_allocation()
- self.move(origin[1], origin[2] + geom[3] - alloc.height)
- self.resize(geom[2] - margin * 2, alloc.height)
+ self.move(origin[1], origin[2] + geom[3] - alloc.height)
+ self.resize(geom[2] - margin * 2, alloc.height)
- def on_text_insert_text(self, buf, piter, text, length):
- self.contents_changed()
+ def on_text_insert_text(self, buf, piter, text, length):
+ self.contents_changed()
- def on_text_delete_range(self, buf, start, end):
- self.contents_changed()
+ def on_text_delete_range(self, buf, start, end):
+ self.contents_changed()
- def on_size_allocate(self, widget, allocation):
- vwwnd = self._entry.view().get_window(Gtk.TextWindowType.TEXT)
- origin = vwwnd.get_origin()
- geom = vwwnd.get_geometry()
+ def on_size_allocate(self, widget, allocation):
+ vwwnd = self._entry.view().get_window(Gtk.TextWindowType.TEXT)
+ origin = vwwnd.get_origin()
+ geom = vwwnd.get_geometry()
- alloc = self.get_allocation()
+ alloc = self.get_allocation()
- self.move(origin[1] + (geom[2] - alloc.width) / 2, origin[2] + geom[3] - alloc.height)
+ self.move(origin[1] + (geom[2] - alloc.width) / 2, origin[2] + geom[3] - alloc.height)
- def on_draw(self, widget, ct):
- color = self._entry.get_border_color()
+ def on_draw(self, widget, ct):
+ color = self._entry.get_border_color()
- self.background_shape(ct, self.get_allocation())
+ self.background_shape(ct, self.get_allocation())
- ct.set_source_rgba(color.red, color.green, color.blue, color.alpha)
- ct.stroke()
+ ct.set_source_rgba(color.red, color.green, color.blue, color.alpha)
+ ct.stroke()
- return False
+ return False
- def background_shape(self, ct, alloc):
- w = alloc.width
- h = alloc.height
+ def background_shape(self, ct, alloc):
+ w = alloc.width
+ h = alloc.height
- ct.set_line_width(1)
- radius = 10
+ ct.set_line_width(1)
+ radius = 10
- ct.move_to(0.5, h)
+ ct.move_to(0.5, h)
- if self.is_composited():
- ct.arc(radius + 0.5, radius + 0.5, radius, math.pi, math.pi * 1.5)
- ct.arc(w - radius - 0.5, radius + 0.5, radius, math.pi * 1.5, math.pi * 2)
- else:
- ct.line_to(0.5, 0)
- ct.line_to(w - 0.5, 0)
+ if self.is_composited():
+ ct.arc(radius + 0.5, radius + 0.5, radius, math.pi, math.pi * 1.5)
+ ct.arc(w - radius - 0.5, radius + 0.5, radius, math.pi * 1.5, math.pi * 2)
+ else:
+ ct.line_to(0.5, 0)
+ ct.line_to(w - 0.5, 0)
- ct.line_to(w - 0.5, h)
+ ct.line_to(w - 0.5, h)
- def background_color(self):
- color = self._entry.get_background_color().copy()
- color.alpha = 0.9
+ def background_color(self):
+ color = self._entry.get_background_color().copy()
+ color.alpha = 0.9
- return color
+ return color
- def on_text_size_allocate(self, widget, alloc):
- pass
+ def on_text_size_allocate(self, widget, alloc):
+ pass
# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/modules.py b/plugins/commander/commander/modules.py
index d3d0f3e..f62463a 100644
--- a/plugins/commander/commander/modules.py
+++ b/plugins/commander/commander/modules.py
@@ -1 +1,3 @@
# All modules are imported here by the commander
+
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/transparentwindow.py b/plugins/commander/commander/transparentwindow.py
index 50296f1..4218cf5 100644
--- a/plugins/commander/commander/transparentwindow.py
+++ b/plugins/commander/commander/transparentwindow.py
@@ -23,57 +23,57 @@ from gi.repository import GObject, Gdk, Gtk, Gedit
import cairo
class TransparentWindow(Gtk.Window):
- __gtype_name__ = "CommanderTransparentWindow"
+ __gtype_name__ = "CommanderTransparentWindow"
- def __init__(self, lvl=Gtk.WindowType.TOPLEVEL):
- Gtk.Window.__init__(self,
- type=lvl,
- decorated=False,
- app_paintable=True,
- skip_pager_hint=True,
- skip_taskbar_hint=True)
+ def __init__(self, lvl=Gtk.WindowType.TOPLEVEL):
+ Gtk.Window.__init__(self,
+ type=lvl,
+ decorated=False,
+ app_paintable=True,
+ skip_pager_hint=True,
+ skip_taskbar_hint=True)
- self.set_events(Gdk.EventMask.ALL_EVENTS_MASK)
- self.set_rgba()
+ self.set_events(Gdk.EventMask.ALL_EVENTS_MASK)
+ self.set_rgba()
- def set_rgba(self):
- visual = self.get_screen().get_rgba_visual()
+ def set_rgba(self):
+ visual = self.get_screen().get_rgba_visual()
- if not visual:
- visual = self.get_screen().get_system_visual()
+ if not visual:
+ visual = self.get_screen().get_system_visual()
- self.set_visual(visual)
+ self.set_visual(visual)
- def do_screen_changed(self, prev):
- super(TransparentWindow, self).do_screen_changed(prev)
+ def do_screen_changed(self, prev):
+ super(TransparentWindow, self).do_screen_changed(prev)
- self.set_rgba()
+ self.set_rgba()
- def background_color(self):
- return Gdk.RGBA(0, 0, 0, 0.8)
+ def background_color(self):
+ return Gdk.RGBA(0, 0, 0, 0.8)
- def background_shape(self, ct, alloc):
- ct.rectangle(0, 0, alloc.width, alloc.height)
+ def background_shape(self, ct, alloc):
+ ct.rectangle(0, 0, alloc.width, alloc.height)
- def draw_background(self, ct, widget=None):
- if widget == None:
- widget = self
+ def draw_background(self, ct, widget=None):
+ if widget == None:
+ widget = self
- ct.set_operator(cairo.OPERATOR_SOURCE)
- alloc = widget.get_allocation()
+ ct.set_operator(cairo.OPERATOR_SOURCE)
+ alloc = widget.get_allocation()
- ct.rectangle(0, 0, alloc.width, alloc.height)
- ct.set_source_rgba(0, 0, 0, 0)
- ct.fill()
+ ct.rectangle(0, 0, alloc.width, alloc.height)
+ ct.set_source_rgba(0, 0, 0, 0)
+ ct.fill()
- color = self.background_color()
- self.background_shape(ct, alloc)
+ color = self.background_color()
+ self.background_shape(ct, alloc)
- ct.set_source_rgba(color.red, color.green, color.blue, color.alpha)
- ct.fill()
+ ct.set_source_rgba(color.red, color.green, color.blue, color.alpha)
+ ct.fill()
- def do_draw(self, ct):
- self.draw_background(ct)
- return False
+ def do_draw(self, ct):
+ self.draw_background(ct)
+ return False
# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/utils.py b/plugins/commander/commander/utils.py
index 1f41288..30256d9 100644
--- a/plugins/commander/commander/utils.py
+++ b/plugins/commander/commander/utils.py
@@ -25,40 +25,42 @@ import inspect
import sys
class Struct(dict):
- def __getattr__(self, name):
- if not name in self:
- val = super(Struct, self).__getattr__(self, name)
- else:
- val = self[name]
+ def __getattr__(self, name):
+ if not name in self:
+ val = super(Struct, self).__getattr__(self, name)
+ else:
+ val = self[name]
- return val
+ return val
- def __setattr__(self, name, value):
- if not name in self:
- super(Struct, self).__setattr__(self, name, value)
- else:
- self[name] = value
+ def __setattr__(self, name, value):
+ if not name in self:
+ super(Struct, self).__setattr__(self, name, value)
+ else:
+ self[name] = value
- def __delattr__(self, name):
- del self[name]
+ def __delattr__(self, name):
+ del self[name]
def is_commander_module(mod):
- if type(mod) == types.ModuleType:
- return mod and ('__commander_module__' in mod.__dict__)
- else:
- mod = str(mod)
- return mod.endswith('.py') or (os.path.isdir(mod) and os.path.isfile(os.path.join(mod, '__init__.py')))
+ if type(mod) == types.ModuleType:
+ return mod and ('__commander_module__' in mod.__dict__)
+ else:
+ mod = str(mod)
+ return mod.endswith('.py') or (os.path.isdir(mod) and os.path.isfile(os.path.join(mod, '__init__.py')))
def getargspec(func):
- ret = inspect.getargspec(func)
+ ret = inspect.getargspec(func)
- # Before 2.6 this was just a normal tuple, we don't want that
- if sys.version_info < (2, 6):
- ret = Struct({
- 'args': ret[0],
- 'varargs': ret[1],
- 'keywords': ret[2],
- 'defaults': ret[3]
- })
+ # Before 2.6 this was just a normal tuple, we don't want that
+ if sys.version_info < (2, 6):
+ ret = Struct({
+ 'args': ret[0],
+ 'varargs': ret[1],
+ 'keywords': ret[2],
+ 'defaults': ret[3]
+ })
- return ret
+ return ret
+
+# vi:ex:ts=4:et
diff --git a/plugins/commander/commander/windowactivatable.py b/plugins/commander/commander/windowactivatable.py
index 13dc814..16a9ffb 100644
--- a/plugins/commander/commander/windowactivatable.py
+++ b/plugins/commander/commander/windowactivatable.py
@@ -43,62 +43,64 @@ ui_str = """
"""
class WindowActivatable(GObject.Object, Gedit.WindowActivatable):
- __gtype_name__ = "CommanderWindowActivatable"
+ __gtype_name__ = "CommanderWindowActivatable"
- window = GObject.property(type=Gedit.Window)
+ window = GObject.property(type=Gedit.Window)
- def __init__(self):
- GObject.Object.__init__(self)
+ def __init__(self):
+ GObject.Object.__init__(self)
- def do_activate(self):
- self._entry = None
- self._view = None
+ def do_activate(self):
+ self._entry = None
+ self._view = None
- self.install_ui()
+ self.install_ui()
- def do_deactivate(self):
- self.uninstall_ui()
+ def do_deactivate(self):
+ self.uninstall_ui()
- def do_update_state(self):
- pass
+ def do_update_state(self):
+ pass
- def install_ui(self):
- manager = self.window.get_ui_manager()
+ def install_ui(self):
+ manager = self.window.get_ui_manager()
- self._action_group = Gtk.ActionGroup("GeditCommanderPluginActions")
- self._action_group.add_toggle_actions([('CommanderModeAction', None,
- _('Commander Mode'), '<Ctrl>period',
- _('Start commander mode'), self.on_commander_mode)])
+ self._action_group = Gtk.ActionGroup("GeditCommanderPluginActions")
+ self._action_group.add_toggle_actions([('CommanderModeAction', None,
+ _('Commander Mode'), '<Ctrl>period',
+ _('Start commander mode'), self.on_commander_mode)])
- manager.insert_action_group(self._action_group, -1)
- self._merge_id = manager.add_ui_from_string(ui_str)
+ manager.insert_action_group(self._action_group, -1)
+ self._merge_id = manager.add_ui_from_string(ui_str)
- def uninstall_ui(self):
- manager = self.window.get_ui_manager()
- manager.remove_ui(self._merge_id)
- manager.remove_action_group(self._action_group)
+ def uninstall_ui(self):
+ manager = self.window.get_ui_manager()
+ manager.remove_ui(self._merge_id)
+ manager.remove_action_group(self._action_group)
- manager.ensure_update()
+ manager.ensure_update()
- def on_commander_mode(self, action, user_data=None):
- view = self.window.get_active_view()
+ def on_commander_mode(self, action, user_data=None):
+ view = self.window.get_active_view()
- if not view:
- return False
+ if not view:
+ return False
- if action.get_active():
- if not self._entry or view != self._view:
- self._entry = Entry(view)
- self._entry.connect('destroy', self.on_entry_destroy)
+ if action.get_active():
+ if not self._entry or view != self._view:
+ self._entry = Entry(view)
+ self._entry.connect('destroy', self.on_entry_destroy)
- self._entry.grab_focus()
- self._view = view
- elif self._entry:
- self._entry.destroy()
- self._view = None
+ self._entry.grab_focus()
+ self._view = view
+ elif self._entry:
+ self._entry.destroy()
+ self._view = None
- return True
+ return True
- def on_entry_destroy(self, widget, user_data=None):
- self._entry = None
- self._action_group.get_action('CommanderModeAction').set_active(False)
+ def on_entry_destroy(self, widget, user_data=None):
+ self._entry = None
+ self._action_group.get_action('CommanderModeAction').set_active(False)
+
+# vi:ex:ts=4:et
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]