Commits

Henning Schröder  committed 9042e7b

pep8

  • Participants
  • Parent commits 4ff2d7e

Comments (0)

Files changed (62)

File codeaide/__init__.py

 import gettext
 
 
-
 share_path = os.path.abspath(os.path.join(__file__, "..", ".."))
 locale_path = os.path.join(share_path, "locale")
 icon_path = os.path.join(share_path, "icons")
-icon_theme = "oxygen" # gnome
+icon_theme = "oxygen"  # gnome
 gettext.bindtextdomain("codeaide", locale_path)
 gettext.textdomain("codeaide")
 gettext.bind_textdomain_codeset("codeaide", "utf-8")
 
 
 mode_settings = {
-  "line_numbers": "LineNumbers",             # sidebar
-  "line_status": "LineStatus",               # sidebar
-  "block_selection": "BlockSelection",       # editextras
-  "autotyping": "AutoTyping",                # autotyping
-  "whitespace": "Whitespace",                # visualhelper
-  "highlight_current_line": "HighlightLine", # visualhelper
-  "wrap_indicator": "WrapIndicator",         # visualhelper
-  "paren_matcher": "ParentheseMatcher",      # parenmatcher
-  "occurrences": "Occurrences"               # occurrences
-}
+    "line_numbers": "LineNumbers",             # sidebar
+    "line_status": "LineStatus",               # sidebar
+    "block_selection": "BlockSelection",       # editextras
+    "autotyping": "AutoTyping",                # autotyping
+    "whitespace": "Whitespace",                # visualhelper
+    "highlight_current_line": "HighlightLine",  # visualhelper
+    "wrap_indicator": "WrapIndicator",         # visualhelper
+    "paren_matcher": "ParentheseMatcher",      # parenmatcher
+    "occurrences": "Occurrences"               # occurrences
+}

File codeaide/base.py

 _command_counter = 0
 
 
-
 def command(label, shortcut=None,
             menu=None, context_menu=False, icon=None,
             enabled_signal=None, interactive=None):
     return wrapper
 
 
-
-
 class Command(QAction):
 
-
     def __init__(self, textedit, func):
         QAction.__init__(self, textedit)
         self.name = func.__name__
                 textedit, SIGNAL("%s(bool)" % func.enabled_signal),
                 self.setEnabled)
 
-
     def __cmp__(self, other):
         return cmp(self.command_id, other.command_id)
 
-
     def __repr__(self):
         return "<Command %s %s>" % (self.text(), self.command_id)
 
-
     def context_menu(self):
         return self.callback.context_menu
 
-
     def on_triggered(self, checked):
         if self.callback.interactive:
             self.callback.interactive(self.textedit, self.callback)
             self.callback()
 
 
+state_counter = 0
 
-state_counter = 0
 
 def new_state_id():
     global state_counter
 
     state = 0
     document_mode = False
-    
+
     # required_modules will be loaded before loading
     # additionally required modes
     require_modules = []
 
     actions = {}
 
-
     @classmethod
     def implementations(cls):
         classes = []
-        for subcls  in cls.__subclasses__():
+        for subcls in cls.__subclasses__():
             classes.append(subcls)
             if issubclass(subcls, cls):
                 classes.extend(subcls.implementations())
         return classes
 
-
     @classmethod
     def find_implementation(cls, mode):
         for impl in cls.implementations():
                 if impl is mode:
                     return impl
 
-
     def __init__(self, textedit, *args, **kwargs):
         if self.document_mode:
             self.hook_target = textedit.document()
             mod = __import__(required_mod, {}, {}, [])
         for required_mode in self.requires:
             textedit.install(required_mode)
-        
+
         self.registered_hooks = []
         self.textedit = textedit
         self.init(*args, **kwargs)
         self.settings = {}
         self.reconfigure()
 
-
     def init(self):
         pass
 
-
     @property
     def default_settings(self):
         return dict()
 
-    
     def reconfigure(self, **settings):
         try:
             self.settings.update(settings)
                 defaults = jdict()
             settings_name = "mod_%s" % self.__class__.__name__.lower()
             self.settings = self.textedit.settings.setdefault(
-                    settings_name, defaults )
+                settings_name, defaults)
             self.settings.update(settings)
 
-
     def uninstall(self):
         self.uninstall_hooks(self)
         self.hook_target.installed_modes.remove(self)
 
-
     def prepare_keyboard_hooks(self, keyboard_hooks):
         h = {}
         for key, callback in keyboard_hooks.items():
                 key, modifiers = key
             else:
                 modifiers = -1
-            h[(key,modifiers)] = callback
+            h[(key, modifiers)] = callback
         return h
 
-
     def keyboard_hooks(self):
         return {}
 
-
     def install_hook(self, hook, callback, key=None, state=None, priority=False):
         if not callback:
             return
             hook.append(callback)
         self.registered_hooks.append((hook, callback))
 
-
     def install_hooks(self):
         self.install_keyboard_hooks()
         self.install_mouse_hooks()
         self.install_cursor_movement_hook()
         self.install_commands()
 
-
     def uninstall_hooks(self):
         for hook, callback in self.registered_hooks:
             hook.remove(callback)
 
-
-    def install_special_hooks(self): # XXX: special/extra?
+    def install_special_hooks(self):  # XXX: special/extra?
         """
         Here you can install extra hook using self.install_hook
         E.g. if you want to add a callback where state != self.state
         """
 
-
-
     def install_commands(self):
         for name in dir(self):
             value = getattr(self, name)
                 c = Command(self.hook_target, value)
                 self.install_hook(self.hook_target.commands, c)
 
-
     def install_keyboard_hooks(self):
         keyboard_hooks = self.prepare_keyboard_hooks(self.keyboard_hooks())
         for key, callback in keyboard_hooks.items():
             self.install_hook(self.hook_target.keyboard_hooks, callback, key)
 
-
     def install_mouse_hooks(self):
         self.install_hook(
             self.hook_target.mouse_press_hooks, self.mouse_press_hook)
             self.hook_target.mouse_double_click_hooks,
             self.mouse_double_click_hook)
 
-
     def install_paint_hook(self):
         callback = self.paint_hook_before or self.paint_hook
         self.install_hook(self.hook_target.paint_hooks_before, callback)
         self.install_hook(
             self.hook_target.paint_hooks_after, self.paint_hook_after)
 
-
     def install_resize_hook(self):
         self.install_hook(self.hook_target.resize_hooks, self.resize_hook)
 
-
     def install_contents_change_hook(self):
         self.install_hook(
             self.hook_target.contents_change_hooks, self.contents_change_hook)
 
-
     def install_cursor_movement_hook(self):
         self.install_hook(
             self.hook_target.cursor_movement_hooks, self.cursor_movement_hook)
 
 
-
 indention_match = re.compile("^[ \t]*").match
 
+
 class TextCursor(QTextCursor):
 
-
     def __enter__(self, *args):
         self.beginEditBlock()
         return self
 
-
     def __exit__(self, *args):
         if isinstance(args[0], Exception):
             print args
         self.endEditBlock()
         return self
 
-
     def iter_blocks(self):
         block = self.block()
         if self.hasSelection():
             yield block
             block = block.next()
 
-
     def row_col(self):
         return (self.blockNumber(), self.columnNumber())
 
-
     def block_start_position(self):
         return self.block().position()
 
-
     def block_end_position(self):
         block = self.block()
         return block.position() + block.length()
 
-
     def block_span(self):
         block = self.block()
         pos = block.position()
         return (pos, pos + block.length())
 
-
     def block_length(self):
         return self.block().length()
 
-
     def indention(self):
         return indention_match(self.current_line()).end()
 
-
     def current_word(self):
         self.select(QTextCursor.WordUnderCursor)
         return unicode(self.selectedText())
 
-
     def current_line(self):
         return unicode(self.block().text())
 
-
     def endswith_word(self):
         word = self.current_word()
         pos = self.position()
         if line[:pos].endswith(word):
             return word
 
-
     def select_region(self, start_pos, end_pos):
         self.setPosition(start_pos)
         self.setPosition(end_pos, QTextCursor.KeepAnchor)
 
-
     def select_region_to(self, end_pos):
         self.setPosition(end_pos, QTextCursor.KeepAnchor)
 
-
     def remove_region(self, start_pos, end_pos):
         self.select_region(start_pos, end_pos)
         self.removeSelectedText()
 
-
     def remove_region_to(self, end_pos):
         self.select_region_to(end_pos)
         self.removeSelectedText()
 
-
     def replace_region(self, start_pos, end_pos, new_text):
         self.remove_region(start_pos, end_pos)
         self.insertText(new_text)
 
-
     def set_block_text(self, text):
         block = self.block()
         pos = block.postion()
         self.replace_region(pos, pos + block.length(), text)
 
-
     def prepend_block_text(self, text):
         cursor = QTextCursor(self.block())
         cursor.insertText(text)
 
-
     def append_block_text(self, text):
         block = self.block()
         cursor = QTextCursor(block)
         cursor.setPosition(block.position() + block.length())
         cursor.insertText(text)
 
-
     def insert_block_text(self, text, pos):
         block = self.block()
         cursor = QTextCursor(block)
         cursor.insertText(text)
 
 
-
 class ExtraSelection(QTextEdit.ExtraSelection):
 
-
     def __init__(self, cursor_or_block_or_document,
                  start_pos=None, end_pos=None):
         QTextEdit.ExtraSelection.__init__(self)
             cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
         self.cursor = cursor
 
-        
     def set_bold(self, flag):
         #font = self.format.font()
-        #font.setBold(flag)
-        #self.format.setFont(font)
+        # font.setBold(flag)
+        # self.format.setFont(font)
         self.format.setFontWeight(QFont.Bold)
 
-
     def set_foreground(self, color):
         self.format.setForeground(color)
 
-
     def set_background(self, brush):
         self.format.setBackground(brush)
 
-
     def set_full_width(self, flag=True):
         self.format.setProperty(
             QTextFormat.FullWidthSelection, QVariant(flag))
 
-
     def set_spellchecking(self, color=Qt.red):
         self.format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
-        self.format.setUnderlineColor(color) 
+        self.format.setUnderlineColor(color)
 
-        
     def set_error(self, color=Qt.red):
         self.format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
         self.format.setUnderlineColor(color)
 
-        
     def set_warning(self, color=QColor("orange")):
         self.format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
         self.format.setUnderlineColor(color)
-

File codeaide/editors.py

 import codeaide.modes
 
 
-
 class BaseEditor(CodeAide):
 
     modes = (
         "Whitespace",
         "EditExtras",
         "Snippets",
-        )
+    )
     require_modules = ()
 
-
     def __init__(self, parent=None):
         if not codeaide.modes.loaded:
             codeaide.modes.load_all(verbose=False)
         self.install(*self.modes)
         self.init_editor()
 
-
     def init_editor(self):
         pass
 
-
     @classmethod
     def create_window(cls, *args, **kwargs):
         edit = cls(*args, **kwargs)
-        edit.resize(800,600)
+        edit.resize(800, 600)
         edit.show()
         return edit
 
-
     @classmethod
     def test(cls, *args, **kwargs):
         app = QApplication.instance() or QApplication(sys.argv)
         return app.exec_()
 
 
-
 class CodeEditor(BaseEditor):
     modes = BaseEditor.modes + ("AutoloadLanguage",)
 
         edit = super(CodeEditor, cls).create_window(*args, **kwargs)
         if len(sys.argv) == 2:
             filename = sys.argv[1]
-        else: filename = __file__.rstrip("co")
+        else:
+            filename = __file__.rstrip("co")
         edit.load_buffer(filename)
         return edit
 
 
-
 class PythonEditor(CodeEditor):
     modes = CodeEditor.modes + ("Python",)
 
 
-
 class BaseConsole(BaseEditor):
-    modes =  (
+    modes = (
         "AutoTyping",
         #"WrapIndicator",
-        #"LineNumbers",  # installs Sidebar as a dependency
+        # "LineNumbers",  # installs Sidebar as a dependency
         "ParentheseMatcher",
         "Whitespace",
         "Session"
-        )
-
+    )
 
     @classmethod
     def create_window(cls, *args, **kwargs):
     modes = BaseConsole.modes + ("PythonConsole",)
 
 
-
 class QtScriptConsole(BaseConsole):
     modes = BaseConsole.modes + ("QtScriptConsole",)
 
 
-    
 class ShellConsole(BaseConsole):
     modes = BaseConsole.modes + ("Shell",)

File codeaide/fileio.py

 from PyQt4.QtGui import QMessageBox, QFileDialog
 
 
-
 mimetypes.init()
 DEFAULT_ENCODING = "utf-8"
 
 try:
     i18n
 except NameError:
-    i18n = lambda s:s
+    i18n = lambda s: s
 
 
 def confirm_close(doc, parent=None):
             pass
 
 
-
-
 class FileDialog(object):
 
-
     def __init__(self, filters, path=None, remember=True):
         self.filters = filters
         self.path = path or os.getcwd()
         self.remember = remember
 
-
     def open(self, parent=None, label=None):
         filename = QFileDialog.getOpenFileName(
             parent, label or i18n("Open file"), self.path, self.filters)
                 self.path = os.path.dirname(filename)
         return filename
 
-
     def save(self, parent=None, label=None):
         filename = QFileDialog.getSaveFileName(
             parent, label or i18n("Save file"), self.path, self.filters)
         return filename
 
 
-
-
-
 class FileIO(object):
 
-
-    def __init__(self, backups=True, 
-              strip_blank_lines=True, 
-              untabify=True, 
-              tab_width=4,
-              encoding=DEFAULT_ENCODING,
-              backup_name="%s~", autosave_name="#%s#"):
+    def __init__(self, backups=True,
+                 strip_blank_lines=True,
+                 untabify=True,
+                 tab_width=4,
+                 encoding=DEFAULT_ENCODING,
+                 backup_name="%s~", autosave_name="#%s#"):
         self.settings = dict(
-            backups=backups, 
+            backups=backups,
             strip_blank_lines=strip_blank_lines,
             untabify=untabify,
             tab_width=tab_width,
             encoding=encoding,
             backup_name=backup_name,
             autosave_name=autosave_name,
-          )
+        )
         self.file_dialog = FileDialog("Python Source (*.py *.pyw)")
 
-
     def guess_mimetpye(self, filename):
         return mimetypes.guess_type(filename, strict=False)[0] or "text/plain"
 
-
     def guess_encoding(self, filename, text):
         lines = text.splitlines()
         enc_match = re.compile("#\s*-\*-\s*coding:\s*(.*?)\s*-\*-").match
                     break
         return encoding
 
-
     def open_dialog(self):
         return self.file_dialog.open()
 
-        
     def save_dialog(self):
         return self.file_dialog.save()
 
-
     def load(self, filename, encoding=None):
         # XXX: check if autosave filename is newer
-        # XXX: check size below sensible limit 
+        # XXX: check size below sensible limit
         f = open(filename)
         text = f.read()
         f.close()
                 text = "\n".join(new)
         return text.decode(encoding)
 
-
     def save(self, filename, text, **settings):
-        encoding = settings.get("encoding") or self.guess_encoding(filename, text)
+        encoding = settings.get(
+            "encoding") or self.guess_encoding(filename, text)
         settings = dict(self.settings, **settings)
         tab = " " * setting["tab_width"]
         lines = text.splitlines()
                 l = l.replace("\t", tab)
             out.append(out)
         text = "\n".join(out).encode(encoding)
-        
+
         if settings["backups"]:
             path, name = os.path.split(filename)
             backup_fn = os.path.join(path, settings["backup_name"] % name)
                 if os.path.exists(backup_fn):
                     os.remove(backup_fn)
                 os.rename(filename, backup_fn)
-            
+
         f = open(filename, "w")
         f.write(text)
         f.close()
-    
+
         # remove autosaved file
         path, name = os.path.split(filename)
         if name.startswith("#") and name.endswith("#"):
             os.remove(afilename)
 
         return text
-    
 
     def autosave(self, filename, text, **settings):
         asettings = dict(self.settings)
-        asettings.update(            
+        asettings.update(
             strip_blank_lines=False,
             untabify=False)
         asettings.update(settings)
         afilename = os.path.join(path, "#%s#" % name)
         return self.save(afilename, text, backups=False, **settings)
 
-    
-    
     def readable(self, filename):
         return True
-    
-    
+
     def writeable(self, filename):
         return True
-    
-    
+
     def exists(self, filename):
         return os.path.exists(filename)
-    
-    
+
     def warning(self, msg):
         print i18n("Warning:"), msg
 
-        
     def error(self, msg):
         print i18n("Error:"), msg
 
-
     def expect_exists(self, filename):
-        self.exists(filename) or self.warning(i18n("The filename %s does not exist."))
+        self.exists(filename) or self.warning(
+            i18n("The filename %s does not exist."))

File codeaide/interface.py

 DEBUG = False
 
 
-
 class lazyproperty(object):
 
-
     def __init__(self, fget=None, fset=None, fdel=None, doc=''):
         for attr in ('fget', 'fset'):
             func = locals()[attr]
                 setattr(self, attr, func.func_name)
         setattr(self, '__doc__', doc)
 
-
     def __get__(self, obj=None, type_=None):
         if not obj:
             return 'property'
         if self.fget:
             return getattr(obj, self.fget)()
 
-
     def __set__(self, obj, arg):
         if self.fset:
             return getattr(obj, self.fset)(arg)
 
 
-
-
-
 class classproperty(object):
 
     def __init__(self, fget=None, fset=None, fdel=None, doc=None, name=None):
         self.__doc__ = doc
         self.name = name
 
-
     def __get__(self, obj, cls):
         fget = self.fget
         if issubclass(cls, Interface) and self.fget is None:
             fget = cp.fget
         return fget(cls)
 
-
     def __set__(self, obj, value):
         if self.fset is None:
             raise AttributeError, "can't set attribute"
         self.fset(obj, value)
 
-
     def __delete__(self, obj):
         if self.fdel is None:
             raise AttributeError, "can't delete attribute"
         self.fdel(obj)
 
 
-
-
-
 class Interface(type):
 
     __registered__ = {}
 
-
     class Error(Exception):
         pass
+
     class NotFoundError(Error):
         pass
 
     class __metaclass__(type):
+
         def __new__(cls, name, bases, attrs):
             if name != "Interface":
                 attrs["__attributes__"] = [
-                    attr_name for attr_name in attrs.keys() \
-                    if not hasattr(Interface, attr_name) ]
+                    attr_name for attr_name in attrs.keys()
+                    if not hasattr(Interface, attr_name)]
             else:
                 attrs["__attributes__"] = []
             for aname, avalue in attrs.items():
                 t.__registered__[name] = t
             return t
 
-
         def __getattr__(cls, name):
             impl = cls.find_implementation()
             return getattr(impl, name)
 
-
     def __new__(cls, *args, **kwargs):
         impl = cls.find_implementation()
         return cls.create(impl, *args, **kwargs)
-    
 
     @classmethod
     def create(cls, impl, *args, **kwargs):
         class Destructor(object):
+
             def __init__(self):
                 self.interfaces = []
-            
+
             def __call__(self, obj):
                 if DEBUG:
                     print "destruct", repr(obj), self.interfaces
                 for iface in self.interfaces:
                     try:
                         iface.__objects__.remove(obj)
-                    except: pass
-        
+                    except:
+                        pass
+
         if DEBUG:
             print "%s.%s:%s.%s" % (
-              cls.__module__, cls.__name__,
-              impl.__module__, impl.__name__),
+                cls.__module__, cls.__name__,
+                impl.__module__, impl.__name__),
             l = []
             l.extend([repr(a) for a in args])
             l.extend(["%s=%r" % (k, v) for k, v in kwargs.items()])
             if DEBUG:
                 print "adding", iface, "to", obj
         return obj
-        
 
-    
     @classmethod
     def attributes(cls):
-        interfaces = [interface for interface in [cls]+cls.mro(cls) \
+        interfaces = [interface for interface in [cls] + cls.mro(cls)
                       if issubclass(interface, Interface)]
         attribs = set()
         for interface in interfaces:
                     attribs.add(name)
         return attribs
 
-
     @classmethod
     def callables(cls):
-        interfaces = [interface for interface in [cls]+cls.mro(cls) \
+        interfaces = [interface for interface in [cls] + cls.mro(cls)
                       if issubclass(interface, Interface)]
         attribs = set()
         for interface in interfaces:
                     attribs.add(name)
         return attribs
 
-    
     @classproperty
     def objects(cls):
         return cls.__objects__
 
-    
     @classproperty
     def instance(cls):
         return cls.__objects__[0]
 
-    
     @classproperty
     def implementations(cls):
         l = []
             l.append(impl)
         return l
 
-    
     @classmethod
     def create_implementations(cls, *args, **kwargs):
         l = []
             l.append(cls.create(impl, *args, **kwargs))
         return l
 
-
     @classmethod
     def find_implementation(cls):
         try:
         except IndexError, e:
             raise Interface.NotFoundError, "No implementation found"
 
-
     @classmethod
     def validate_interface(cls, impl, throw_exception=False):
         for attr in cls.attributes():
                 getattr(impl, attr)
             except AttributeError:
                 if throw_exception:
-                    raise TypeError, "%s does not implement attribute %r of interface %s" % (impl, attr, cls)
+                    raise TypeError, "%s does not implement attribute %r of interface %s" % (
+                        impl, attr, cls)
                 else:
                     return False
         for attr in cls.callables():
                 method = getattr(impl, attr)
             except AttributeError:
                 if throw_exception:
-                    raise TypeError, "%s does not implement callable %r of interface %s" % (impl, attr, cls)
+                    raise TypeError, "%s does not implement callable %r of interface %s" % (
+                        impl, attr, cls)
                 else:
                     return False
         return True
 
 
-
 def implements(*interfaces):
     frame = sys._getframe(1)
     class_name = frame.f_code.co_name
     cls.__interfaces__ = getattr(cls, "__interfaces__", []) + iface_classes
 
 
-    
-    
 def on_hook(hook_iface, *args, **kwargs):
     break_on_result = kwargs.pop("break_on_hook_result", True)
     for hook_class in hook_iface.implementations:
         if result and break_on_result:
             return result
 
-        
-        
-
 
 class _WeakMethod_FuncHost(object):
 
     def __init__(self, func):
         self.hostedFunction = func
+
     def func(self, *args, **kwargs):
         self.hostedFunction(*args, **kwargs)
 
 
-
 class _WeakMethod(object):
 
     def __init__(self, f):
         self.f = f.im_func
         self.c = weakref.ref(f.im_self)
 
-
     def __call__(self, *args, **kwargs):
         obj = self.c()
-        if obj == None : return
+        if obj == None:
+            return
         self.f(obj, *args, **kwargs)
 
-        
-        
-        
+
 class Signal(object):
 
     block_all = False
 
-
     def __init__(self):
         self.slots = []
         # for keeping references to _WeakMethod_FuncHost objects.
 
     blocked = property(get_blocked, set_blocked)
 
-
     dispatcher = None
 
-    
     def __call__(self, *args, **kwargs):
         cls = self.__class__
         if self._blocked or cls.block_all:
             else:
                 call(slot, *args, **kwargs)
 
-
     def connect(self, slot):
         self.disconnect(slot)
         if inspect.ismethod(slot):
             # we stick a copy in here just to keep the instance alive
             self.func_host.append(o)
 
-
     def __iadd__(self, slot):
         self.connect(slot)
         return self
 
-
     def disconnect(self, slot):
         try:
             for i, wm in enumerate(self.slots[:]):
         except:
             pass
 
-
     def __isub__(self, slot):
         self.disconnect(slot)
         return self
 
-
     def disconnect_all(self):
         del self.slots
         del self.func_host
         self.func_host = []
 
 
-
 class SignalMapper(object):
 
-
     def __init__(self, slot, *args, **kwargs):
         self.slot = slot
         self.args = args
         self.kwargs = kwargs
 
-
     def __call__(self, *args, **kwargs):
         args = self.args + args
         kwargs.update(self.kwargs)
         return self.slot(*args, **kwargs)
 
 
-
-
 if __name__ == "__main__":
     class Greeting(Interface):
-        def greet(self, name): pass
+
+        def greet(self, name):
+            pass
 
     class EastFrisian(object):
         implements(Greeting)
-        def greet(self, name): return "moin " + name
+
+        def greet(self, name):
+            return "moin " + name
 
     greeting = Greeting()
     print greeting

File codeaide/lib/__init__.py

                 if filename not in sys.path:
                     sys.path.insert(0, filename)
 
-                    
-                    
+
 def add_path(path):
     if os.path.exists(path):
         __path__.append(path)
-    
 
 
 home_path = os.path.expanduser("~")

File codeaide/main.py

 from PyQt4.QtGui import (
     qApp,
     QPlainTextEdit, QPainter, QColor,
-    QTextBlockUserData, QTextDocument, QPlainTextDocumentLayout, 
+    QTextBlockUserData, QTextDocument, QPlainTextDocumentLayout,
     QAbstractSlider, QScrollBar,
     QMenu, QTextCursor)
 
 FileIO.instance = FileIO()
 
 
-
 class ScrollBar(QScrollBar):
 
-
     def __init__(self, parent):
         QScrollBar.__init__(self, parent)
 
-
     def sliderChange(self, change):
         if self.signalsBlocked() and change == QAbstractSlider.SliderValueChange:
             self.blockSignals(False)
         return QScrollBar.sliderChange(self, change)
 
 
-
 class TextBlockUserData(QTextBlockUserData):
 
     def __init__(self):
         QTextBlockUserData.__init__(self)
         self.attrs = {}
 
-
     def __getitem__(self, name):
         return self.attrs[name]
 
-
     def get(self, name, default=None):
         return self.attrs.get(name, default)
 
-
     def __setitem__(self, name, value):
         self.attrs[name] = value
 
 
+class VisibleBlock(object):
 
-class VisibleBlock(object):
     """
     This class contains the geometry of currently visible blocks
     """
 
 
 class Configurable(object):
-    
 
     def __init__(self):
         self.connect(self, SIGNAL("settings_changed()"), self.on_reconfigure)
 
-
     def reconfigure(self, **settings):
         try:
             self.settings.update(settings)
             self.settings.update(settings)
         self.emit(SIGNAL("settings_changed()"))
 
-
     def on_reconfigure(self):
         pass
 
 
+class Hookable(object):
 
-        
-class Hookable(object):
-    
-    
     def setup_hooks(self):
         self.state = 0
         self.commands = {}
         self.active_cursor_movement_hooks = ()
         self.active_row_change_hooks = ()
 
-        
         self.state = -1
         self.installed_modes = []
 
-        
     def prepare_hooks(self):
         for cmd in self._commands:
             self.removeAction(cmd)
             return list(hooks.get(self.state, []) + hooks.get(-1, []))
 
         self._mouse_press_hooks = filter_active_state(self.mouse_press_hooks)
-        
-        self._mouse_double_click_hooks = filter_active_state(self.mouse_double_click_hooks)
+
+        self._mouse_double_click_hooks = filter_active_state(
+            self.mouse_double_click_hooks)
         self._paint_hooks_before = filter_active_state(self.paint_hooks_before)
         self._paint_hooks_after = filter_active_state(self.paint_hooks_after)
-        self._contents_change_hooks = filter_active_state(self.contents_change_hooks)
-        self._cursor_movement_hooks = filter_active_state(self.cursor_movement_hooks)
+        self._contents_change_hooks = filter_active_state(
+            self.contents_change_hooks)
+        self._cursor_movement_hooks = filter_active_state(
+            self.cursor_movement_hooks)
         self._row_change_hooks = filter_active_state(self.row_change_hooks)
         self._resize_hooks = filter_active_state(self.resize_hooks)
 
         for state in (self.state, -1):
             for keys, callbacks in self.keyboard_hooks.get(state, {}).items():
                 h.setdefault(keys, []).extend(callbacks)
-   
 
     def find_mode(self, cls):
         for mode in self.installed_modes:
             if isinstance(mode, cls):
                 return mode
 
-
     def is_installed(self, mode):
         for installed in self.installed_modes:
             if installed.__class__ is mode:
                 return True
         return False
 
-
     def _find_modes(self, *mode_args):
         for m in mode_args:
             mode = ModeBase.find_implementation(m)
                 raise ValueError, "Installing mode %r failed: Not found." % m
             yield mode
 
-
     def install(self, *mode_list):
         for mode in self._find_modes(*mode_list):
             if not self.is_installed(mode):
                 setattr(self, mode.__name__, mode_instance)
         self.switch_state(0)
 
-    require = install #alias for emacs fans ;)
+    require = install  # alias for emacs fans ;)
 
-    
     def install_on_idle(self, *mode_list, **kwargs):
         callback = kwargs.pop("callback", None)
-        self.idle_install = IdleCall(self, self.install, callback, *mode_list, **kwargs)
-
+        self.idle_install = IdleCall(
+            self, self.install, callback, *mode_list, **kwargs)
 
     def uninstall(self, *mode_list):
         for mode in self._find_modes(*mode_list):
                     self.installed_modes.remove(instance)
                     break
 
-
     def switch_state(self, state):
         """
         changes the state and set hooks for current state
         self.emit(SIGNAL("new_state()"))
 
 
-
 class Buffer(QTextDocument, Hookable, Configurable):
 
     killring = []
     registers = []
-    instances =  []
+    instances = []
     file_io = None
 
     @classmethod
                     return buf
         return cls.instances[idx]
 
-
     def __init__(self, text=None, filename=None):
         QTextDocument.__init__(self)
         Hookable.__init__(self)
         self.setModified(False)
         Buffer.instances.append(self)
         self.setup_hooks()
-        #self.install("Autosave")
-
-
+        # self.install("Autosave")
 
     def document(self):
-        return self # work-around...
-
+        return self  # work-around...
 
     def close(self):
         Buffer.instances.remove(self)
 
-
     def max_line_length(self):
         lines = unicode(self.toPlainText()).splitlines()
         return max([len(l) for l in lines])
 
-
     def row_col2position(self, row, col):
         """
         index starts with 0
         block = self.findBlockByNumber(row)
         return block.position() + col
 
-
     def row2position(self, row):
         return self.row_col2position(row, 0)
 
 
-
 if sys.platform == "win32":
     editor_default_font = "Lucida Console"
 else:
 
 
 default_scheme = jdict(
-      color="black",
-      background="white",
-      selection_color="white",
-      selection_background="#437DCD",
-      font_name=editor_default_font,
-      font_size=9,
-      line_number_color="#866D71",
-      line_number_active_color="black",
-      line_number_background="#E1E1E1",
-      highlight_line_background="#E4EDF8",
-      wrap_indicator_color="#D8D8D8",
-      wrap_indicator_background="#F7F7F7",
-      occurrence_color="black",
-      occurrence_background="yellow",
-      paren_color="red",
-      paren_background="#b4eeb4",
-      space_color="lightgrey",
-      tab_color="lightblue",
-      all_space_color="darkred",
-      status_new="darkgreen",
-      status_modified="red",
-      syntax_keyword="#808000", # darkYellow
-      syntax_builtin="brown", 
-      syntax_magic="magenta",
-      syntax_self="darkMagenta",
-      syntax_comment="darkGray",
-      syntax_string="darkGreen",
-      syntax_number="darkBlue",
-      css = """
+    color="black",
+    background="white",
+    selection_color="white",
+    selection_background="#437DCD",
+    font_name=editor_default_font,
+    font_size=9,
+    line_number_color="#866D71",
+    line_number_active_color="black",
+    line_number_background="#E1E1E1",
+    highlight_line_background="#E4EDF8",
+    wrap_indicator_color="#D8D8D8",
+    wrap_indicator_background="#F7F7F7",
+    occurrence_color="black",
+    occurrence_background="yellow",
+    paren_color="red",
+    paren_background="#b4eeb4",
+    space_color="lightgrey",
+    tab_color="lightblue",
+    all_space_color="darkred",
+    status_new="darkgreen",
+    status_modified="red",
+    syntax_keyword="#808000",  # darkYellow
+    syntax_builtin="brown",
+    syntax_magic="magenta",
+    syntax_self="darkMagenta",
+    syntax_comment="darkGray",
+    syntax_string="darkGreen",
+    syntax_number="darkBlue",
+    css="""
         QPlainTextEdit {
           font-family: %(font_name)s;
           font-size: %(font_size)spt;
           selection-background-color: %(selection_background)s;
         }"""
 )
-    
 
 
 class Idler(QObject):
     # XXX make seconds configurable?
 
-
     def __init__(self, textedit):
         QObject.__init__(self, textedit)
         self.textedit = textedit
         self.idle_timer_id = self.startTimer(1000)
 
-
     def busy(self):
         try:
             self.killTimer(self.idle_timer_id)
-        except AttributeError: pass
+        except AttributeError:
+            pass
         self.idle_timer_id = self.startTimer(1000)
 
-
     def timerEvent(self, event):
         try:
             self.killTimer(self.idle_timer_id)
-        except AttributeError: pass
+        except AttributeError:
+            pass
         QTimer.singleShot(0, self._emit_idle)
         self.idle_timer_id = self.startTimer(1000)
 
-
     def _emit_idle(self):
         self.textedit.emit(SIGNAL("idle()"))
 
 
+class CodeAide(QPlainTextEdit, Hookable, Configurable):
 
-    
-class CodeAide(QPlainTextEdit, Hookable, Configurable):
     """
     new signals:
       newText()
 
     """
 
-
     def __init__(self, parent=None):
         QPlainTextEdit.__init__(self, parent)
-        self.connect(qApp.clipboard(), SIGNAL("dataChanged()"), self.on_clipboard_changed)
+        self.connect(qApp.clipboard(), SIGNAL(
+            "dataChanged()"), self.on_clipboard_changed)
         Hookable.__init__(self)
         Configurable.__init__(self)
         self.vbar = ScrollBar(self)
 
         self.fm = self.fontMetrics()
         self.reconfigure()
-        
+
         self.setup_vars()
         self.setup_hooks()
         self.setup_signals()
         self.busy = Idler(self).busy
         self.update_hooks()
         self.setFocus()
-        
+
         self.new_buffer()
-    
 
     @property
     def default_settings(self):
         return dict(
-           line_wraps=True,
-           scheme=default_scheme,
+            line_wraps=True,
+            scheme=default_scheme,
         )
-        
-
 
     def on_reconfigure(self):
         if self.settings.line_wraps:
         self.set_scheme(self.settings.scheme)
         self.on_blocks_changed()
 
-
     def setup_vars(self):
         self.row = self.column = -1
         self.contents_changed = True
         self.visible_blocks = []
         self.extra_selections = []
 
-
     def setup_signals(self):
         self.connect(
             self, SIGNAL("blockCountChanged(int)"), self.on_blocks_changed)
         self.connect(self, SIGNAL("cursorPositionChanged()"),
                      self.on_cursor_position_changed)
 
-
     def clone(self, parent=None):
         te = self.__class__(parent)
         for mode in self.installed_modes:
         te.setDocument(te.document)
         te.setTextCursor(QTextCursor(self.textCursor()))
 
-
     def on_document_changed(self):
         self.update_hooks()
 
-        
     def update_hooks(self):
         doc = self.document()
         if not isinstance(doc, Buffer):
         doc.prepare_hooks()
         self.prepare_hooks()
 
-        self.active_mouse_press_hooks = doc._mouse_press_hooks + self._mouse_press_hooks
-        self.active_mouse_double_click_hooks = doc._mouse_double_click_hooks + self._mouse_double_click_hooks
-        self.active_paint_hooks_before = doc._paint_hooks_before + self._paint_hooks_before
-        self.active_paint_hooks_after = doc._paint_hooks_after + self._paint_hooks_after
-        self.active_contents_change_hooks = doc._contents_change_hooks + self._contents_change_hooks
-        self.active_cursor_movement_hooks = doc._cursor_movement_hooks + self._cursor_movement_hooks
-        self.active_row_change_hooks = doc._row_change_hooks + self._row_change_hooks
+        self.active_mouse_press_hooks = doc._mouse_press_hooks + \
+            self._mouse_press_hooks
+        self.active_mouse_double_click_hooks = doc._mouse_double_click_hooks + \
+            self._mouse_double_click_hooks
+        self.active_paint_hooks_before = doc._paint_hooks_before + \
+            self._paint_hooks_before
+        self.active_paint_hooks_after = doc._paint_hooks_after + \
+            self._paint_hooks_after
+        self.active_contents_change_hooks = doc._contents_change_hooks + \
+            self._contents_change_hooks
+        self.active_cursor_movement_hooks = doc._cursor_movement_hooks + \
+            self._cursor_movement_hooks
+        self.active_row_change_hooks = doc._row_change_hooks + \
+            self._row_change_hooks
         self.active_resize_hooks = doc._resize_hooks + self._resize_hooks
-        self.active_keyboard_hooks = dict(self._keyboard_hooks, **doc._keyboard_hooks)
-
+        self.active_keyboard_hooks = dict(
+            self._keyboard_hooks, **doc._keyboard_hooks)
 
     def new_buffer(self, text=None):
         doc = Buffer(text=text)
         doc.state = self.state
         self.setDocument(doc)
-        self.connect(doc, SIGNAL("modificationChanged(bool)"), self.window().setWindowModified)
+        self.connect(
+            doc, SIGNAL("modificationChanged(bool)"), self.window().setWindowModified)
         return doc
 
-    
     def load_buffer(self, filename):
         doc = Buffer(filename=filename)
         self.setDocument(doc)
-        self.connect(doc, SIGNAL("modificationChanged(bool)"), self.window().setWindowModified)
+        self.connect(
+            doc, SIGNAL("modificationChanged(bool)"), self.window().setWindowModified)
         return doc
 
-    
     def save_buffer(self, filename=None):
         doc = self.document()
         filename = filename or doc.filename
         FileIO.instance.save(filename, unicode(doc.toPlainText()))
         doc.setModified(False)
 
-
     def rename_buffer(self, filename):
         doc = self.document()
         doc.filename = filename
-        
 
     def switch_buffer(self, num):
         doc = Buffer[num]
         self.setDocument(doc)
-        self.connect(doc, SIGNAL("modificationChanged(bool)"), self.window().setWindowModified)
+        self.connect(
+            doc, SIGNAL("modificationChanged(bool)"), self.window().setWindowModified)
         return doc
 
-    
     def close_buffer(self):
         self.document().close()
         self.new_buffer()
 
-
     def set_scheme(self, scheme):
         scheme = jdict(default_scheme, **scheme)
         css = scheme.css % scheme
         font.setPointSize(scheme.font_size)
         self.setFont(font)
         #format = self.currentCharFormat()
-        #format.setFont(font)
-        #self.setCurrentCharFormat(format)
+        # format.setFont(font)
+        # self.setCurrentCharFormat(format)
         self.document().setDefaultFont(font)
         self.fm = self.fontMetrics()
         self.scheme = scheme
 
-        
     def setFocus(self):
         QPlainTextEdit.setFocus(self)
         self.ensureCursorVisible()
 
-
     def paintEvent(self, event):
         # callbacks to paint background (wrap indicator etc)
         viewport = self.viewport()
                     return
             painter.end()
 
-
     def mousePressEvent(self, event):
         for callback in self.active_mouse_press_hooks:
             if callback(event):
         self.busy()
         return QPlainTextEdit.mousePressEvent(self, event)
 
-
-
-    def mouseDoubleClickEvent (self, event):
+    def mouseDoubleClickEvent(self, event):
         for callback in self.active_mouse_double_click_hooks:
             if callback(event):
                 return
-        self.busy() # XXX really?
+        self.busy()  # XXX really?
         return QPlainTextEdit.mouseDoubleClickEvent(self, event)
 
-
-
     def keyPressEvent(self, event):
         key = event.key()
         text = event.text()
         modifiers = event.modifiers()
         m = int(modifiers)
         keyboard_hooks = self.active_keyboard_hooks
-        
+
         if keyboard_hooks:
             h = keyboard_hooks.get((key, m), []) + \
                 keyboard_hooks.get((key, -1), []) + \
         self.busy()
         return QPlainTextEdit.keyPressEvent(self, event)
 
-
     def resizeEvent(self, event):
         for callback in self.active_resize_hooks:
             if callback(event):
             self.on_blocks_changed()
         return QPlainTextEdit.resizeEvent(self, event)
 
-
     def user_data(self, block=None):
         if not block:
             block = self.textCursor().block()
             block.setUserData(user_data)
         return user_data
 
-
     def remove_extra_selections(self, selections):
         extras = self.extra_selections
         for sel in selections:
                 extras.remove(sel)
         self.setExtraSelections(extras)
 
-
-
     def add_extra_selections(self, selections):
         self.extra_selections.extend(selections)
         self.setExtraSelections(self.extra_selections)
 
-
-    def on_blocks_changed(self, num=-1):        
+    def on_blocks_changed(self, num=-1):
         visible_blocks = []
         block = self.firstVisibleBlock()
         row = block.blockNumber() + 1
         width = self.width()
-        w  = width -2
+        w = width - 2
         h = self.fm.height()
 
         bbgeom = self.blockBoundingGeometry(block)
         top = bbgeom.translated(self.contentOffset()).top()
         bottom = top + bbgeom.height()
-        ebottom_top = 0 #event.rect().top()
-        ebottom_bottom = self.height() #event.rect().bottom()
+        ebottom_top = 0  # event.rect().top()
+        ebottom_bottom = self.height()  # event.rect().bottom()
         visible_blocks_append = visible_blocks.append
         while block.isValid() and top <= ebottom_bottom:
             if block.isVisible() and bottom >= ebottom_top:
                 visible_blocks_append(
-                   VisibleBlock(row, block, (0, top, w, h))
-                   )
+                    VisibleBlock(row, block, (0, top, w, h))
+                )
             block = block.next()
             row += 1
             top = bottom
         self.visible_blocks = visible_blocks
         self.emit(SIGNAL("visible_blocks_changed()"))
 
-
     def on_cursor_position_changed(self):
         cursor = self.textCursor()
         row = cursor.blockNumber()
         self.row = row
         self.column = col
 
-
     def on_contents_changed(self, pos, chars_removed, chars_added):
         if chars_removed == 0 and chars_added == 0:
             # style changes (highlighting, ..)
             block = block.next()
             block_number += 1
 
-
     def contextMenuEvent(self, event):
         menu = QMenu(self)
         for cmd in self._commands:
                 menu.addAction(cmd)
         menu.exec_(event.globalPos())
 
-
     def setDocument(self, doc):
         self.disconnect(self.document(),
                         SIGNAL("contentsChange(int,int,int)"),
                         self.on_contents_changed)
         QPlainTextEdit.setDocument(self, doc)
         self.connect(doc, SIGNAL("contentsChange(int,int,int)"),
-          self.on_contents_changed)
+                     self.on_contents_changed)
         self.emit(SIGNAL("documentChanged()"))
         self.emit(SIGNAL("newText()"))
 
-
     def setPlainText(self, text):
         QPlainTextEdit.setPlainText(self, text)
         self.emit(SIGNAL("newText()"))
 
-
     def set_position(self, pos):
         cursor = self.textCursor()
         cursor.setPosition(pos)
         self.setTextCursor(cursor)
 
-
     def set_row_col(self, row, col):
         pos = self.document().row_col2position(row, col)
         cursor = self.textCursor()
         cursor.setPosition(pos)
         self.setTextCursor(cursor)
 
-        
-        
     def set_row_start(self, row):
         pos = self.document().row_col2position(row, 0)
         cursor = self.text_cursor()
         cursor.setPosition(pos)
         col = cursor.indention()
-        cursor.setPosition(pos+col)
+        cursor.setPosition(pos + col)
         self.setTextCursor(cursor)
 
-        
     def text_cursor(self):
         return TextCursor(self.textCursor())
 
-
-    
     def on_clipboard_changed(self):
         self.emit(SIGNAL("pasteAvailable"), self.canPaste())
-

File codeaide/modes/__init__.py

 
 module_names = []
 
+
 def find():
     global module_names
     module_names = []
             elif re.match("^[A-Za-z][A-ZA-z0-9]*\.py$", name):
                 module_names.append(os.path.splitext(name)[0])
 
-                
+
 def add_path(path):
     global module_names
-    module_names = [] 
+    module_names = []
     __path__.insert(0, path)
 
-    
+
 loaded = 0
-        
+
+
 def load(name):
     global loaded
     mod = __import__("codeaide.modes.%s" % name, {}, {}, [])

File codeaide/modes/_skel.py

 
 
 class PerfectlyValidMode(ModeBase):
+
     """
     As you can see here your mode can be really small.
     See below what you can do.
 
 
 class SkeletonMode(ModeBase):
-    
+
     """
     Remove everything you do not need for your mode.
     Unused stuff only slows down the editor.
     This should only be used with caution (e.g. disabling keys in special states).
 
     """
-    
-    state = 123456        # default state of this mode, use 0 default state, -1 for all states
+
+    # default state of this mode, use 0 default state, -1 for all states
+    state = 123456
     require_modules = []  # string list of additionally needed modules/packages
-    requires = []         # string list of required modes 
-    document_mode = Fase  # defines if this mode belongs an editor widget or to a buffer
-
+    requires = []         # string list of required modes
+    # defines if this mode belongs an editor widget or to a buffer
+    document_mode = Fase
 
     def init(self):
         """
         Use this method for initialization, it is called from __init__
         """
-        ## Some signals you could be find handy
+        # Some signals you could be find handy
         #te = self.textedit
-        #te.connect(te, SIGNAL("idle()"), .. )
-        #te.conntext(te, SIGNAL("documentChanged()")), .. )
-        #te.conntext(te, SIGNAL("newText()")), .. )
-        #te.connect(te, SIGNAL("state_change(int)"), .. )
-        #te.connect(te, SIGNAL("new_state()"), .. )
-        #te.connect(te, SIGNAL("visible_blocks_changed()"), ..)
-        
+        # te.connect(te, SIGNAL("idle()"), .. )
+        # te.conntext(te, SIGNAL("documentChanged()")), .. )
+        # te.conntext(te, SIGNAL("newText()")), .. )
+        # te.connect(te, SIGNAL("state_change(int)"), .. )
+        # te.connect(te, SIGNAL("new_state()"), .. )
+        # te.connect(te, SIGNAL("visible_blocks_changed()"), ..)
 
-    def install_special_hooks(self): 
+    def install_special_hooks(self):
         """
         Your hook methods are defined for the mode state.
         If you want to add additional hooks or if you want to add hooks for
           * row_change_hooks
 
         """
-        #self.install_hook(
+        # self.install_hook(
         #   self.textedit.resize_hooks, self.update_something, state=-1)
-        ## This is useful for triggering a new state
-        #self.install_hook(
-        #   self.textedit.keyboard_hooks, 
-        #   lambda : self.textedit.switch_state(self.state), 
+        # This is useful for triggering a new state
+        # self.install_hook(
+        #   self.textedit.keyboard_hooks,
+        #   lambda : self.textedit.switch_state(self.state),
         #   key=(Qt.Key_X, Qt.ControlModifier), state=0)
 
-
     def keyboard_hooks(self):
         """
         return a dictionary consisting of keys and callbacks
         keys can be tuples with the modfier as second element
         -1 means any
         """
-        #return {
+        # return {
         #    Qt.Key_Escape: lambda event, key, modifiers, text: QApplication.instance().quit(),
-        #    (-1,-1): self.myKeyPressEvent  
+        #    (-1,-1): self.myKeyPressEvent
         #}
 
+    # def myKeyPressEvent(self, event, key, modifiers, text):
+    #   pass
+    def contents_change_hook(self, block_number, block, text, user_data):
+        """
+        """
 
-    #def myKeyPressEvent(self, event, key, modifiers, text):
-    #   pass
+    def resize_hook(self, event):
+        """
+        """
 
+    def paint_hook_before(self, event, painter, viewport):
+        """
+        """
+
+    def paint_hook_after(self, event, painter, viewport):
+        """
+        """
+
+    def mouse_press_hook(self, event):
+        """
+        """
+
+    def mouse_double_click_hook(self, event):
+        """
+        """
+
+    def cursor_movement_hook(self, row, col, cursor):
+        """
+        """
+
+    def row_change_hook(self):
+        """
+        """
 
     def contents_change_hook(self, block_number, block, text, user_data):
         """
         """
 
-
-    def resize_hook(self, event):
-        """
-        """
-
-
-    def paint_hook_before(self, event, painter, viewport):
-        """
-        """
-
-
-    def paint_hook_after(self, event, painter, viewport):
-        """
-        """
-
-
-    def mouse_press_hook(self, event):
-        """
-        """
-    
-    
-    def mouse_double_click_hook(self, event):
-        """
-        """
-    
-        
-    def cursor_movement_hook(self, row, col, cursor):
-        """
-        """
-
-        
-    def row_change_hook(self):
-        """
-        """
-        
-        
-    def contents_change_hook(self, block_number, block, text, user_data):
-        """
-        """
-
-        
     @command("Some &action", context_menu=True, shortcut="Ctrl+A")
     def do_something(self):
         """

File codeaide/modes/autosave.py

 
 watchers = {}
 
+
 class FileWatcher(QObject):
 
-    
     def __init__(self, document):
         QObject.__init__(self)
         self.document = document
         self.filename = os.path.abspath(document.filename)
         self.watcher = QFileSystemWatcher(self)
         self.watcher.addPath(self.filename)
-        self.connect(self.watcher, SIGNAL("fileChanged(const QString&)"), self.on_file_changed)
+        self.connect(self.watcher, SIGNAL(
+            "fileChanged(const QString&)"), self.on_file_changed)
         watchers[self.filename] = self
 
-
     def stop(self):
         self.watcher.blockSignals(True)
-        
-        
+
     def resume(self):
         self.watcher.blockSignals(False)
 
-        
     def on_file_changed(self, path):
         self.emit(SIGNAL("file_changed"), unicode(path))
 
 
-
-
 class FileSaver(QObject):
 
-    
     def __init__(self, document, autosave_interval=60):
         QObject.__init__(self)
         # XXX check if read-only
         self.document = document
-        self.startTimer(autosave_interval*1000)
+        self.startTimer(autosave_interval * 1000)
 
-        
     def timerEvent(self, event):
         if self.document.isModified():
             self.save_backup()
 
-        
     def _save(self, filename, enoding="utf-8"):
         w = watchers.get(filename, None)
         if w:
         if w:
             w.resume()
 
-        
     def backup_filename(self):
         fn = self.document.filename
         path, name = os.path.split(os.path.abspath(fn))
         return os.path.join(path, "#%s#" % name)
 
-
     def save_backup(self):
         print "backup"
         backup_fn = self.backup_filename()
         self._save(backup_fn)
         return backup_fn
 
-    
     def save(self):
         self._save(self.document.filename)
         backup_fn = self.backup_filename()
         if os.path.exists(backup_fn):
             os.remove(self.backup_fn)
         self.document.setModified(False)
-            
-            
+
 
 class Autosave(ModeBase):
 
     document_mode = True
-    
+
     def init(self):
         print "autosaver installed"
         if self.textedit.document().filename:
             self.watcher = FileWatcher(self.textedit.document())
 
 
-
-            
 if __name__ == "__main__":
     class Document():
         fi