[gedit] Port plugins to python 3



commit ebbb4e5ae48269dbfcf758b7865351d010937320
Author: Ignacio Casal Quinteiro <icq gnome org>
Date:   Thu Oct 25 16:37:27 2012 +0200

    Port plugins to python 3

 plugins/externaltools/tools/__init__.py          |    4 +-
 plugins/externaltools/tools/capture.py           |   42 +++++++-----
 plugins/externaltools/tools/functions.py         |    4 +-
 plugins/externaltools/tools/library.py           |   15 ++---
 plugins/externaltools/tools/manager.py           |   15 +++--
 plugins/externaltools/tools/outputpanel.py       |   12 ++--
 plugins/externaltools/tools/windowactivatable.py |   10 ++--
 plugins/pythonconsole/pythonconsole/__init__.py  |    8 +-
 plugins/pythonconsole/pythonconsole/console.py   |   17 ++---
 plugins/quickopen/quickopen/__init__.py          |   10 ++--
 plugins/quickopen/quickopen/popup.py             |   14 +++-
 plugins/quickopen/quickopen/virtualdirs.py       |    2 +-
 plugins/snippets/snippets/__init__.py            |    6 +-
 plugins/snippets/snippets/appactivatable.py      |    4 +-
 plugins/snippets/snippets/completion.py          |    8 +-
 plugins/snippets/snippets/document.py            |   74 +++++++++++-----------
 plugins/snippets/snippets/exporter.py            |    4 +-
 plugins/snippets/snippets/importer.py            |    6 +-
 plugins/snippets/snippets/languagemanager.py     |    2 +-
 plugins/snippets/snippets/library.py             |    8 +-
 plugins/snippets/snippets/manager.py             |   30 +++++-----
 plugins/snippets/snippets/parser.py              |    2 +-
 plugins/snippets/snippets/placeholder.py         |   21 +++---
 plugins/snippets/snippets/shareddata.py          |    6 +-
 plugins/snippets/snippets/snippet.py             |   23 +++----
 plugins/snippets/snippets/windowactivatable.py   |    8 +-
 26 files changed, 181 insertions(+), 174 deletions(-)
---
diff --git a/plugins/externaltools/tools/__init__.py b/plugins/externaltools/tools/__init__.py
index 721fd85..87af9cf 100644
--- a/plugins/externaltools/tools/__init__.py
+++ b/plugins/externaltools/tools/__init__.py
@@ -17,8 +17,8 @@
 #    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
 from gi.repository import GObject, Gedit
-from windowactivatable import WindowActivatable
-from library import ToolLibrary
+from .windowactivatable import WindowActivatable
+from .library import ToolLibrary
 import os
 
 class AppActivatable(GObject.Object, Gedit.AppActivatable):
diff --git a/plugins/externaltools/tools/capture.py b/plugins/externaltools/tools/capture.py
index 64b50a2..1614f5b 100644
--- a/plugins/externaltools/tools/capture.py
+++ b/plugins/externaltools/tools/capture.py
@@ -22,7 +22,7 @@ import os, sys, signal
 import locale
 import subprocess
 import fcntl
-from gi.repository import GObject
+from gi.repository import GLib, GObject
 
 class Capture(GObject.Object):
     CAPTURE_STDOUT = 0x01
@@ -87,7 +87,7 @@ class Capture(GObject.Object):
 
         try:
             self.pipe = subprocess.Popen(self.command, **popen_args)
-        except OSError, e:
+        except OSError as e:
             self.pipe = None
             self.emit('stderr-line', _('Could not execute command: %s') % (e, ))
             return
@@ -100,29 +100,33 @@ class Capture(GObject.Object):
             flags = fcntl.fcntl(self.pipe.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK
             fcntl.fcntl(self.pipe.stdout.fileno(), fcntl.F_SETFL, flags)
 
-            GObject.io_add_watch(self.pipe.stdout,
-                                 GObject.IO_IN | GObject.IO_HUP | GObject.IO_ERR,
-                                 self.on_output)
+            channel = GLib.IOChannel.unix_new(self.pipe.stdout.fileno())
+            GLib.io_add_watch(channel,
+                              GLib.PRIORITY_DEFAULT,
+                              GLib.IOCondition.IN | GLib.IOCondition.HUP | GLib.IOCondition.ERR,
+                              self.on_output)
 
         if self.flags & self.CAPTURE_STDERR:
             # Set non blocking
             flags = fcntl.fcntl(self.pipe.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK
             fcntl.fcntl(self.pipe.stderr.fileno(), fcntl.F_SETFL, flags)
 
-            GObject.io_add_watch(self.pipe.stderr,
-                                 GObject.IO_IN | GObject.IO_HUP | GObject.IO_ERR,
-                                 self.on_output)
+            channel = GLib.IOChannel.unix_new(self.pipe.stderr.fileno())
+            GLib.io_add_watch(channel,
+                              GLib.PRIORITY_DEFAULT,
+                              GLib.IOCondition.IN | GLib.IOCondition.HUP | GLib.IOCondition.ERR,
+                              self.on_output)
 
         # IO
         if self.input_text is not None:
             # Write async, in chunks of something
-            self.write_buffer = str(self.input_text)
+            self.write_buffer = self.input_text.encode('utf-8')
 
             if self.idle_write_chunk():
-                self.idle_write_id = GObject.idle_add(self.idle_write_chunk)
+                self.idle_write_id = GLib.idle_add(self.idle_write_chunk)
 
         # Wait for the process to complete
-        GObject.child_watch_add(self.pipe.pid, self.on_child_end)
+        GLib.child_watch_add(self.pipe.pid, self.on_child_end)
 
     def idle_write_chunk(self):
         if not self.pipe:
@@ -136,7 +140,7 @@ class Capture(GObject.Object):
             self.pipe.stdin.write(self.write_buffer[:m])
             
             if m == l:
-                self.write_buffer = ''
+                self.write_buffer = b''
                 self.pipe.stdin.close()
                 
                 self.idle_write_id = 0
@@ -166,11 +170,9 @@ class Capture(GObject.Object):
 
             if len(line) > 0:
                 try:
-                    line = unicode(line, 'utf-8')
+                    line = line
                 except:
-                    line = unicode(line,
-                                   locale.getdefaultlocale()[1],
-                                   'replace')
+                    line = line.encode(locale.getdefaultlocale()[1])
 
                 self.read_buffer += line
                 lines = self.read_buffer.splitlines(True)
@@ -204,7 +206,7 @@ class Capture(GObject.Object):
     def stop(self, error_code = -1):
         if self.pipe is not None:
             if self.idle_write_id:
-                GObject.source_remove(self.idle_write_id)
+                GLib.source_remove(self.idle_write_id)
                 self.idle_write_id = 0
 
             if not self.tried_killing:
@@ -213,9 +215,13 @@ class Capture(GObject.Object):
             else:
                 os.kill(self.pipe.pid, signal.SIGKILL)
 
+    def emit_end_execute(self, error_code):
+        self.emit('end-execute', error_code)
+        return False
+
     def on_child_end(self, pid, error_code):
         # In an idle, so it is emitted after all the std*-line signals
         # have been intercepted
-        GObject.idle_add(self.emit, 'end-execute', error_code)
+        GLib.idle_add(self.emit_end_execute, error_code)
 
 # ex:ts=4:et:
diff --git a/plugins/externaltools/tools/functions.py b/plugins/externaltools/tools/functions.py
index 6a6266e..5acf50d 100644
--- a/plugins/externaltools/tools/functions.py
+++ b/plugins/externaltools/tools/functions.py
@@ -18,8 +18,8 @@
 
 import os
 from gi.repository import Gio, Gtk, Gdk, GtkSource, Gedit
-from outputpanel import OutputPanel
-from capture import *
+from .outputpanel import OutputPanel
+from .capture import *
 
 def default(val, d):
     if val is not None:
diff --git a/plugins/externaltools/tools/library.py b/plugins/externaltools/tools/library.py
index 1e4ef64..6efd03d 100644
--- a/plugins/externaltools/tools/library.py
+++ b/plugins/externaltools/tools/library.py
@@ -88,7 +88,7 @@ class ToolLibrary(Singleton):
         if not os.path.isfile(filename):
             return
 
-        print "External tools: importing old tools into the new store..."
+        print("External tools: importing old tools into the new store...")
 
         xtree = et.parse(filename)
         xroot = xtree.getroot()
@@ -159,8 +159,7 @@ class ToolDirectory(object):
                 continue
             for i in os.listdir(d):
                 elements[i] = None
-        keys = elements.keys()
-        keys.sort()
+        keys = sorted(elements.keys())
         return keys
 
     def _load(self):
@@ -245,7 +244,7 @@ class Tool(object):
         if filename is None:
             return
 
-        fp = file(filename, 'r', 1)
+        fp = open(filename, 'r', 1)
         in_block = False
         lang = locale.getlocale(locale.LC_MESSAGES)[0]
 
@@ -409,7 +408,7 @@ class Tool(object):
 
     def _dump_properties(self):
         lines = ['# [Gedit Tool]']
-        for item in self._properties.iteritems():
+        for item in self._properties.items():
             if item[0] in self._transform:
                 lines.append('# %s=%s' % (item[0], self._transform[item[0]][1](item[1])))
             elif item[1] is not None:
@@ -453,7 +452,7 @@ class Tool(object):
             fp.write(line + "\n")
 
         fp.close()
-        os.chmod(filename, 0750)
+        os.chmod(filename, 0o750)
         self.changed = False
 
     def save(self):
@@ -480,10 +479,10 @@ if __name__ == '__main__':
     library = ToolLibrary()
 
     def print_tool(t, indent):
-        print indent * "  " + "%s: %s" % (t.filename, t.name)
+        print(indent * "  " + "%s: %s" % (t.filename, t.name))
 
     def print_dir(d, indent):
-        print indent * "  " + d.dirname + '/'
+        print(indent * "  " + d.dirname + '/')
         for i in d.subdirs:
             print_dir(i, indent+1)
         for i in d.tools:
diff --git a/plugins/externaltools/tools/manager.py b/plugins/externaltools/tools/manager.py
index 2a39a79..84a016e 100644
--- a/plugins/externaltools/tools/manager.py
+++ b/plugins/externaltools/tools/manager.py
@@ -19,8 +19,8 @@
 __all__ = ('Manager', )
 
 import os.path
-from library import *
-from functions import *
+from .library import *
+from .functions import *
 import hashlib
 from xml.sax import saxutils
 from gi.repository import GObject, Gtk, GtkSource, Gedit
@@ -460,7 +460,12 @@ class Manager(GObject.Object):
             n1 = t1.name
             n2 = t2.name
 
-        return cmp(n1.lower(), n2.lower())
+        if n1.lower() < n2.lower():
+            return -1
+        elif n1.lower() > n2.lower():
+            return 1
+        else:
+            return 0
 
     def __init_tools_view(self):
         # Tools column
@@ -510,7 +515,7 @@ class Manager(GObject.Object):
             return None, None
 
     def compute_hash(self, string):
-        return hashlib.md5(string).hexdigest()
+        return hashlib.md5(string.encode('utf-8')).hexdigest()
 
     def save_current_tool(self):
         if self.current_node is None:
@@ -584,7 +589,7 @@ class Manager(GObject.Object):
 
         self.script_hash = self.compute_hash(script)
 
-        contenttype, uncertain = Gio.content_type_guess(None, script)
+        contenttype, uncertain = Gio.content_type_guess(None, script.encode('utf-8'))
         lmanager = GtkSource.LanguageManager.get_default()
         language = lmanager.guess_language(None, contenttype)
 
diff --git a/plugins/externaltools/tools/outputpanel.py b/plugins/externaltools/tools/outputpanel.py
index afb41d2..e22ed73 100644
--- a/plugins/externaltools/tools/outputpanel.py
+++ b/plugins/externaltools/tools/outputpanel.py
@@ -21,11 +21,11 @@ __all__ = ('OutputPanel', 'UniqueById')
 
 import os
 from weakref import WeakKeyDictionary
-from capture import *
+from .capture import *
 import re
-import linkparsing
-import filelookup
-from gi.repository import GObject, Gio, Gdk, Gtk, Pango, Gedit
+from . import linkparsing
+from . import filelookup
+from gi.repository import GLib, Gio, Gdk, Gtk, Pango, Gedit
 
 class UniqueById:
     __shared_state = WeakKeyDictionary()
@@ -168,7 +168,7 @@ class OutputPanel(UniqueById):
             buffer.apply_tag(tag, start_iter, end_iter)
 
         buffer.delete_mark(insert)
-        GObject.idle_add(self.scroll_to_end)
+        GLib.idle_add(self.scroll_to_end)
 
     def show(self):
         panel = self.window.get_bottom_panel()
@@ -233,6 +233,6 @@ class OutputPanel(UniqueById):
 
         if gfile:
             Gedit.commands_load_location(self.window, gfile, None, link.line_nr, link.col_nr)
-            GObject.idle_add(self.idle_grab_focus)
+            GLib.idle_add(self.idle_grab_focus)
 
 # ex:ts=4:et:
diff --git a/plugins/externaltools/tools/windowactivatable.py b/plugins/externaltools/tools/windowactivatable.py
index da03b78..cfd99f0 100644
--- a/plugins/externaltools/tools/windowactivatable.py
+++ b/plugins/externaltools/tools/windowactivatable.py
@@ -19,11 +19,11 @@
 __all__ = ('ExternalToolsPlugin', 'Manager', 'OutputPanel', 'Capture', 'UniqueById')
 
 from gi.repository import GObject, Gtk, Gedit, PeasGtk
-from manager import Manager
-from library import ToolLibrary
-from outputpanel import OutputPanel
-from capture import Capture
-from functions import *
+from .manager import Manager
+from .library import ToolLibrary
+from .outputpanel import OutputPanel
+from .capture import Capture
+from .functions import *
 
 class ToolMenu(object):
     def __init__(self, library, window, panel, menupath):
diff --git a/plugins/pythonconsole/pythonconsole/__init__.py b/plugins/pythonconsole/pythonconsole/__init__.py
index 29cd24b..0d33608 100644
--- a/plugins/pythonconsole/pythonconsole/__init__.py
+++ b/plugins/pythonconsole/pythonconsole/__init__.py
@@ -26,8 +26,8 @@
 
 from gi.repository import GObject, Gtk, Gedit, Peas, PeasGtk
 
-from console import PythonConsole
-from config import PythonConsoleConfigWidget
+from .console import PythonConsole
+from .config import PythonConsoleConfigWidget
 
 PYTHON_ICON = 'gnome-mime-text-x-python'
 
@@ -43,8 +43,8 @@ class PythonConsolePlugin(GObject.Object, Gedit.WindowActivatable, PeasGtk.Confi
         self._console = PythonConsole(namespace = {'__builtins__' : __builtins__,
                                                    'gedit' : Gedit,
                                                    'window' : self.window})
-        self._console.eval('print "You can access the main window through ' \
-                           '\'window\' :\\n%s" % window', False)
+        self._console.eval('print("You can access the main window through ' \
+                           '\'window\' :\\n%s" % window)', False)
         bottom = self.window.get_bottom_panel()
         image = Gtk.Image()
         image.set_from_icon_name(PYTHON_ICON, Gtk.IconSize.MENU)
diff --git a/plugins/pythonconsole/pythonconsole/console.py b/plugins/pythonconsole/pythonconsole/console.py
index ac57368..f6540d2 100644
--- a/plugins/pythonconsole/pythonconsole/console.py
+++ b/plugins/pythonconsole/pythonconsole/console.py
@@ -29,7 +29,7 @@ import sys
 import re
 import traceback
 
-from gi.repository import GObject, Gio, Gtk, Gdk, Pango
+from gi.repository import GLib, Gio, Gtk, Gdk, Pango
 
 __all__ = ('PythonConsole', 'OutFile')
 
@@ -177,7 +177,7 @@ class PythonConsole(Gtk.ScrolledWindow):
                 cur = buf.get_end_iter()
 
             buf.place_cursor(cur)
-            GObject.idle_add(self.scroll_to_end)
+            GLib.idle_add(self.scroll_to_end)
             return True
 
         elif event.keyval == Gdk.KEY_Return:
@@ -221,21 +221,21 @@ class PythonConsole(Gtk.ScrolledWindow):
             cur = buf.get_end_iter()
             buf.move_mark(inp_mark, cur)
             buf.place_cursor(cur)
-            GObject.idle_add(self.scroll_to_end)
+            GLib.idle_add(self.scroll_to_end)
             return True
 
         elif event.keyval == Gdk.KEY_KP_Down or event.keyval == Gdk.KEY_Down:
             # Next entry from history
             view.emit_stop_by_name("key_press_event")
             self.history_down()
-            GObject.idle_add(self.scroll_to_end)
+            GLib.idle_add(self.scroll_to_end)
             return True
 
         elif event.keyval == Gdk.KEY_KP_Up or event.keyval == Gdk.KEY_Up:
             # Previous entry from history
             view.emit_stop_by_name("key_press_event")
             self.history_up()
-            GObject.idle_add(self.scroll_to_end)
+            GLib.idle_add(self.scroll_to_end)
             return True
 
         elif event.keyval == Gdk.KEY_KP_Left or event.keyval == Gdk.KEY_Left or \
@@ -344,7 +344,7 @@ class PythonConsole(Gtk.ScrolledWindow):
         else:
             buf.insert_with_tags(buf.get_end_iter(), text, tag)
 
-        GObject.idle_add(self.scroll_to_end)
+        GLib.idle_add(self.scroll_to_end)
 
     def eval(self, command, display_command = False):
         buf = self.view.get_buffer()
@@ -373,11 +373,6 @@ class PythonConsole(Gtk.ScrolledWindow):
         sys.stdout, self.stdout = self.stdout, sys.stdout
         sys.stderr, self.stderr = self.stderr, sys.stderr
 
-        # eval and exec are broken in how they deal with utf8-encoded
-        # strings so we have to explicitly decode the command before
-        # passing it along
-        command = command.decode('utf8')
-
         try:
             try:
                 r = eval(command, self.namespace, self.namespace)
diff --git a/plugins/quickopen/quickopen/__init__.py b/plugins/quickopen/quickopen/__init__.py
index e4772af..9a32187 100644
--- a/plugins/quickopen/quickopen/__init__.py
+++ b/plugins/quickopen/quickopen/__init__.py
@@ -17,11 +17,11 @@
 #  Foundation, Inc., 59 Temple Place, Suite 330,
 #  Boston, MA 02111-1307, USA.
 
-from popup import Popup
+from .popup import Popup
 import os
 from gi.repository import GObject, Gio, Gtk, Gedit
-from virtualdirs import RecentDocumentsDirectory
-from virtualdirs import CurrentDocumentsDirectory
+from .virtualdirs import RecentDocumentsDirectory
+from .virtualdirs import CurrentDocumentsDirectory
 
 ui_str = """<ui>
   <menubar name="MenuBar">
@@ -133,7 +133,7 @@ class QuickOpenPlugin(GObject.Object, Gedit.WindowActivatable):
 
         paths = []
 
-        for line in file(filename, 'r').xreadlines():
+        for line in open(filename, 'r'):
             uri = line.strip().split(" ")[0]
             f = Gio.file_new_for_uri(uri)
 
@@ -160,7 +160,7 @@ class QuickOpenPlugin(GObject.Object, Gedit.WindowActivatable):
         desktopdir = None
 
         if os.path.isfile(config):
-            for line in file(config, 'r').xreadlines():
+            for line in open(config, 'r'):
                 line = line.strip()
 
                 if line.startswith('XDG_DESKTOP_DIR'):
diff --git a/plugins/quickopen/quickopen/popup.py b/plugins/quickopen/quickopen/popup.py
index 237a8c9..331ca6e 100644
--- a/plugins/quickopen/quickopen/popup.py
+++ b/plugins/quickopen/quickopen/popup.py
@@ -18,10 +18,11 @@
 #  Boston, MA 02111-1307, USA.
 
 import os
+import functools
 import fnmatch
 from gi.repository import Gio, GObject, Pango, Gtk, Gdk, Gedit
 import xml.sax.saxutils
-from virtualdirs import VirtualDirectory
+from .virtualdirs import VirtualDirectory
 
 class Popup(Gtk.Dialog):
     __gtype_name__ = "QuickOpenPopup"
@@ -172,7 +173,12 @@ class Popup(Gtk.Dialog):
     def _compare_entries(self, a, b, lpart):
         if lpart in a:
             if lpart in b:
-                return cmp(a.index(lpart), b.index(lpart))
+                if a.index(lpart) < b.index(lpart):
+                    return -1
+                elif a.index(lpart) > b.index(lpart):
+                    return 1
+                else:
+                    return 0
             else:
                 return -1
         elif lpart in b:
@@ -194,7 +200,7 @@ class Popup(Gtk.Dialog):
             entries = self._cache[d]
         else:
             entries = self._list_dir(d)
-            entries.sort(lambda x, y: cmp(x[1].lower(), y[1].lower()))
+            entries.sort(key=lambda x: x[1].lower())
             self._cache[d] = entries
 
         found = []
@@ -218,7 +224,7 @@ class Popup(Gtk.Dialog):
                      (not lpart or len(parts) == 1):
                     found.append(entry)
 
-        found.sort(lambda a, b: self._compare_entries(a[1].lower(), b[1].lower(), lpart))
+        found.sort(key=functools.cmp_to_key(lambda a, b: self._compare_entries(a[1].lower(), b[1].lower(), lpart)))
 
         if lpart == '..':
             newdirs.append(d.get_parent())
diff --git a/plugins/quickopen/quickopen/virtualdirs.py b/plugins/quickopen/quickopen/virtualdirs.py
index 40cb2c2..71fca2a 100644
--- a/plugins/quickopen/quickopen/virtualdirs.py
+++ b/plugins/quickopen/quickopen/virtualdirs.py
@@ -58,7 +58,7 @@ class RecentDocumentsDirectory(VirtualDirectory):
         manager = Gtk.RecentManager.get_default()
 
         items = manager.get_items()
-        items.sort(lambda a, b: cmp(b.get_visited(), a.get_visited()))
+        items.sort(key=lambda a: a.get_visited())
 
         added = 0
 
diff --git a/plugins/snippets/snippets/__init__.py b/plugins/snippets/snippets/__init__.py
index 0d4d92e..305d4c8 100644
--- a/plugins/snippets/snippets/__init__.py
+++ b/plugins/snippets/snippets/__init__.py
@@ -15,8 +15,8 @@
 #    along with this program; if not, write to the Free Software
 #    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
-from appactivatable import AppActivatable
-from windowactivatable import WindowActivatable
-from document import Document
+from .appactivatable import AppActivatable
+from .windowactivatable import WindowActivatable
+from .document import Document
 
 # ex:ts=8:et:
diff --git a/plugins/snippets/snippets/appactivatable.py b/plugins/snippets/snippets/appactivatable.py
index 63f9147..9c33426 100644
--- a/plugins/snippets/snippets/appactivatable.py
+++ b/plugins/snippets/snippets/appactivatable.py
@@ -22,8 +22,8 @@ import shutil
 from gi.repository import Gedit, GLib, GObject, Gtk
 import platform
 
-from library import Library
-from manager import Manager
+from .library import Library
+from .manager import Manager
 
 class AppActivatable(GObject.Object, Gedit.AppActivatable):
         __gtype_name__ = "GeditSnippetsAppActivatable"
diff --git a/plugins/snippets/snippets/completion.py b/plugins/snippets/snippets/completion.py
index b97ddba..25610f2 100644
--- a/plugins/snippets/snippets/completion.py
+++ b/plugins/snippets/snippets/completion.py
@@ -17,9 +17,9 @@
 
 from gi.repository import GObject, Gtk, GtkSource, Gedit
 
-from library import Library
-from languagemanager import get_language_manager
-from snippet import Snippet
+from .library import Library
+from .languagemanager import get_language_manager
+from .snippet import Snippet
 
 class Proposal(GObject.Object, GtkSource.CompletionProposal):
         __gtype_name__ = "GeditSnippetsProposal"
@@ -83,7 +83,7 @@ class Provider(GObject.Object, GtkSource.CompletionProvider):
 
                 if start.backward_word_start():
                         self.mark_position(start)
-                        return unicode(start.get_text(it), 'utf-8')
+                        return start.get_text(it)
                 else:
                         return None
 
diff --git a/plugins/snippets/snippets/document.py b/plugins/snippets/snippets/document.py
index 678aa5e..63283b3 100644
--- a/plugins/snippets/snippets/document.py
+++ b/plugins/snippets/snippets/document.py
@@ -21,13 +21,13 @@ import re
 import cairo
 from gi.repository import Gtk, Gdk, Gio, GLib, GtkSource, Gedit
 
-from library import Library
-from snippet import Snippet
-from placeholder import *
-import completion
-from signals import Signals
-from shareddata import SharedData
-import helper
+from .library import Library
+from .snippet import Snippet
+from .placeholder import *
+from . import completion
+from .signals import Signals
+from .shareddata import SharedData
+from . import helper
 
 class DynamicSnippet(dict):
         def __init__(self, text):
@@ -327,37 +327,37 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                 bounds = buf.get_selection_bounds()
 
                 if bounds:
-                        u8 = unicode(buf.get_text(bounds[0], bounds[1], False), 'utf-8')
+                        u8 = buf.get_text(bounds[0], bounds[1], False)
 
                         return {'utf8': u8, 'noenc': self.string_in_native_doc_encoding(buf, u8)}
                 else:
-                        return u''
+                        return ''
 
         def env_get_current_word(self, buf):
                 start, end = buffer_word_boundary(buf)
                 enc = buf.get_encoding()
 
-                u8 = unicode(buf.get_text(start, end, False), 'utf-8')
+                u8 = buf.get_text(start, end, False)
 
                 return {'utf8': u8, 'noenc': self.string_in_native_doc_encoding(buf, u8)}
 
         def env_get_current_line(self, buf):
                 start, end = buffer_line_boundary(buf)
 
-                u8 = unicode(buf.get_text(start, end, False), 'utf-8')
+                u8 = buf.get_text(start, end, False)
 
                 return {'utf8': u8, 'noenc': self.string_in_native_doc_encoding(buf, u8)}
 
         def env_get_current_line_number(self, buf):
                 start, end = buffer_line_boundary(buf)
 
-                return unicode(str(start.get_line() + 1), 'utf-8')
+                return str(start.get_line() + 1)
 
         def location_uri_for_env(self, location):
                 if not location:
-                        return {'utf8': u'', 'noenc': u''}
+                        return {'utf8': '', 'noenc': ''}
 
-                u8 = unicode(location.get_parse_name(), 'utf-8')
+                u8 = location.get_parse_name()
 
                 if location.has_uri_scheme('file'):
                         u8 = "file://" + u8
@@ -372,23 +372,23 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                         except:
                                 display_name = ''
 
-                        return {'utf8': unicode(display_name, 'utf-8'),
+                        return {'utf8': display_name,
                                 'noenc': location.get_basename()}
                 else:
-                        return u''
+                        return ''
 
         def location_scheme_for_env(self, location):
                 if location:
-                        return unicode(location.get_uri_scheme(), 'utf-8')
+                        return location.get_uri_scheme()
                 else:
-                        return u''
+                        return ''
 
         def location_path_for_env(self, location):
                 if location and location.has_uri_scheme('file'):
-                        return {'utf8': unicode(location.get_parse_name(), 'utf-8'),
+                        return {'utf8': location.get_parse_name(),
                                 'noenc': location.get_path()}
                 else:
-                        return u''
+                        return ''
 
         def location_dir_for_env(self, location):
                 if location:
@@ -398,7 +398,7 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                                 return {'utf8': parent.get_parse_name(),
                                         'noenc': parent.get_path()}
 
-                return u''
+                return ''
 
         def env_add_for_location(self, environ, location, prefix):
                 parts = {'URI': self.location_uri_for_env,
@@ -424,9 +424,9 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                 typ = buf.get_mime_type()
 
                 if typ:
-                        return unicode(typ, 'utf-8')
+                        return typ
                 else:
-                        return u''
+                        return ''
 
         def env_get_documents_uri(self, buf):
                 toplevel = self.view.get_toplevel()
@@ -444,7 +444,7 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                                         documents_uri['utf8'].append(r)
                                         documents_uri['noenc'].append(str(r))
 
-                return {'utf8': u' '.join(documents_uri['utf8']),
+                return {'utf8': ' '.join(documents_uri['utf8']),
                         'noenc': ' '.join(documents_uri['noenc'])}
 
         def env_get_documents_path(self, buf):
@@ -463,7 +463,7 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                                         documents_path['utf8'].append(r)
                                         documents_path['noenc'].append(str(r))
 
-                return {'utf8': u' '.join(documents_path['utf8']),
+                return {'utf8': ' '.join(documents_path['utf8']),
                         'noenc': ' '.join(documents_path['noenc'])}
 
         def get_environment(self):
@@ -474,15 +474,15 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                         # Get the original environment, as utf-8
                         v = os.environ[k]
                         environ['noenc'][k] = v
-                        environ['utf8'][k] = unicode(os.environ[k], 'utf-8')
+                        environ['utf8'][k] = os.environ[k].encode('utf-8')
 
-                variables = {u'GEDIT_SELECTED_TEXT': self.env_get_selected_text,
-                             u'GEDIT_CURRENT_WORD': self.env_get_current_word,
-                             u'GEDIT_CURRENT_LINE': self.env_get_current_line,
-                             u'GEDIT_CURRENT_LINE_NUMBER': self.env_get_current_line_number,
-                             u'GEDIT_CURRENT_DOCUMENT_TYPE': self.env_get_document_type,
-                             u'GEDIT_DOCUMENTS_URI': self.env_get_documents_uri,
-                             u'GEDIT_DOCUMENTS_PATH': self.env_get_documents_path}
+                variables = {'GEDIT_SELECTED_TEXT': self.env_get_selected_text,
+                             'GEDIT_CURRENT_WORD': self.env_get_current_word,
+                             'GEDIT_CURRENT_LINE': self.env_get_current_line,
+                             'GEDIT_CURRENT_LINE_NUMBER': self.env_get_current_line_number,
+                             'GEDIT_CURRENT_DOCUMENT_TYPE': self.env_get_document_type,
+                             'GEDIT_DOCUMENTS_URI': self.env_get_documents_uri,
+                             'GEDIT_DOCUMENTS_PATH': self.env_get_documents_path}
 
                 for var in variables:
                         v = variables[var](buf)
@@ -570,7 +570,7 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                 self.active_snippets.append(sn)
 
                 # Put cursor at first tab placeholder
-                keys = filter(lambda x: x > 0, sn.placeholders.keys())
+                keys = list(filter(lambda x: x > 0, sn.placeholders.keys()))
 
                 if len(keys) == 0:
                         if 0 in sn.placeholders:
@@ -625,7 +625,7 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                         first = False
 
                 if not start.equal(end):
-                        word = unicode(buf.get_text(start, end, False), 'utf-8')
+                        word = buf.get_text(start, end, False)
 
                         if word and word != '':
                                 return (word, start, end)
@@ -859,7 +859,7 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                 # Remove file scheme
                 gfile = Gio.file_new_for_uri(uri)
 
-                environ = {'utf8': {'GEDIT_DROP_DOCUMENT_TYPE': unicode(mime, 'utf-8')},
+                environ = {'utf8': {'GEDIT_DROP_DOCUMENT_TYPE': mime.encode('utf-8')},
                            'noenc': {'GEDIT_DROP_DOCUMENT_TYPE': mime}}
 
                 self.env_add_for_location(environ, gfile, 'GEDIT_DROP_DOCUMENT')
@@ -870,7 +870,7 @@ class Document(GObject.Object, Gedit.ViewActivatable, Signals):
                 relpath = location.get_relative_path(gfile)
 
                 # CHECK: what is the encoding of relpath?
-                environ['utf8']['GEDIT_DROP_DOCUMENT_RELATIVE_PATH'] = unicode(relpath, 'utf-8')
+                environ['utf8']['GEDIT_DROP_DOCUMENT_RELATIVE_PATH'] = relpath.encode('utf-8')
                 environ['noenc']['GEDIT_DROP_DOCUMENT_RELATIVE_PATH'] = relpath
 
                 mark = buf.get_mark('gtk_drag_target')
diff --git a/plugins/snippets/snippets/exporter.py b/plugins/snippets/snippets/exporter.py
index 7b80210..185215e 100644
--- a/plugins/snippets/snippets/exporter.py
+++ b/plugins/snippets/snippets/exporter.py
@@ -20,9 +20,9 @@ import tempfile
 import sys
 import shutil
 
-from library import *
+from .library import *
 import xml.etree.ElementTree as et
-from helper import *
+from .helper import *
 
 class Exporter:
         def __init__(self, filename, snippets):
diff --git a/plugins/snippets/snippets/importer.py b/plugins/snippets/snippets/importer.py
index 2cf6063..14206f7 100644
--- a/plugins/snippets/snippets/importer.py
+++ b/plugins/snippets/snippets/importer.py
@@ -21,7 +21,7 @@ import tempfile
 import sys
 import shutil
 
-from library import *
+from .library import *
 
 class Importer:
         def __init__(self, filename):
@@ -55,7 +55,7 @@ class Importer:
                 # Make sure dir exists
                 try:
                     os.makedirs(destdir)
-                except OSError, e:
+                except OSError as e:
                     if e.errno != errno.EEXIST:
                         raise
 
@@ -92,7 +92,7 @@ class Importer:
                 shutil.rmtree(dirname)
 
                 if len(errors) > 0:
-                        return _('The following files could not be imported: %s') % u', '.join(errors)
+                        return _('The following files could not be imported: %s') % ', '.join(errors)
 
         def import_targz(self):
                 self.import_archive('tar -x --gzip -f')
diff --git a/plugins/snippets/snippets/languagemanager.py b/plugins/snippets/snippets/languagemanager.py
index d70449b..30b079e 100644
--- a/plugins/snippets/snippets/languagemanager.py
+++ b/plugins/snippets/snippets/languagemanager.py
@@ -18,7 +18,7 @@
 from gi.repository import GtkSource
 import os
 
-from library import Library
+from .library import Library
 
 global manager
 manager = None
diff --git a/plugins/snippets/snippets/library.py b/plugins/snippets/snippets/library.py
index 79b894c..5ff0ffb 100644
--- a/plugins/snippets/snippets/library.py
+++ b/plugins/snippets/snippets/library.py
@@ -24,7 +24,7 @@ import re
 from gi.repository import Gdk, Gtk
 
 import xml.etree.ElementTree as et
-from helper import *
+from .helper import *
 
 class NamespacedId:
         def __init__(self, namespace, id):
@@ -87,7 +87,7 @@ class SnippetData:
                                         keyval, mod = Gtk.accelerator_parse(child.text)
 
                                         if Gtk.accelerator_valid(keyval, mod):
-                                                child.text = unicode(Gtk.accelerator_name(keyval, mod), 'utf-8')
+                                                child.text = Gtk.accelerator_name(keyval, mod)
                                         else:
                                                 child.text = ''
 
@@ -138,7 +138,7 @@ class SnippetData:
                         return
 
                 if isinstance(value, list):
-                        value = u','.join(value)
+                        value = ','.join(value)
 
                 if not self.can_modify() and self.properties[prop] != value:
                         # ohoh, this is not can_modify, but it needs to be changed...
@@ -620,7 +620,7 @@ class SnippetsUserFile(SnippetsSystemFile):
 
                 try:
                         if not os.path.isdir(path):
-                                os.makedirs(path, 0755)
+                                os.makedirs(path, 0o755)
                 except OSError:
                         # TODO: this is bad...
                         sys.stderr.write("Error in making dirs\n")
diff --git a/plugins/snippets/snippets/manager.py b/plugins/snippets/snippets/manager.py
index 0612545..80df05f 100644
--- a/plugins/snippets/snippets/manager.py
+++ b/plugins/snippets/snippets/manager.py
@@ -21,13 +21,13 @@ import shutil
 
 from gi.repository import Gtk, Gio, Gdk, GtkSource, Gedit, GObject
 
-from snippet import Snippet
-from helper import *
-from library import *
-from importer import *
-from exporter import *
-from document import Document
-from languagemanager import get_language_manager
+from .snippet import Snippet
+from .helper import *
+from .library import *
+from .importer import *
+from .exporter import *
+from .document import Document
+from .languagemanager import get_language_manager
 
 class Manager(Gtk.Dialog, Gtk.Buildable):
         NAME_COLUMN = 0
@@ -515,7 +515,7 @@ class Manager(Gtk.Dialog, Gtk.Buildable):
                         self['entry_tab_trigger'].set_text(self.snippet['tag'])
                         self['entry_accelerator'].set_text( \
                                         self.snippet.accelerator_display())
-                        self['combo_drop_targets'].get_child().set_text(u', '.join(self.snippet['drop-targets']))
+                        self['combo_drop_targets'].get_child().set_text(', '.join(self.snippet['drop-targets']))
 
                         buf = self['source_view_snippet'].get_buffer()
                         buf.begin_not_undoable_action()
@@ -652,7 +652,7 @@ class Manager(Gtk.Dialog, Gtk.Buildable):
 
         def entry_tab_trigger_update_valid(self):
                 entry = self['entry_tab_trigger']
-                text = unicode(entry.get_text(), 'utf-8')
+                text = entry.get_text()
 
                 if text and not Library().valid_tab_trigger(text):
                         img = self['image_tab_trigger']
@@ -675,7 +675,7 @@ class Manager(Gtk.Dialog, Gtk.Buildable):
                 if not self.snippet:
                         return
 
-                text = unicode(entry.get_text(), 'utf-8')
+                text = entry.get_text()
 
                 # save tag
                 self.snippet['tag'] = text
@@ -685,7 +685,7 @@ class Manager(Gtk.Dialog, Gtk.Buildable):
                 if not self.snippet:
                         return
 
-                text = unicode(entry.get_text(), 'utf-8')
+                text = entry.get_text()
 
                 # save drop targets
                 self.snippet['drop-targets'] = text
@@ -699,8 +699,8 @@ class Manager(Gtk.Dialog, Gtk.Buildable):
                         return
 
                 buf = source_view.get_buffer()
-                text = unicode(buf.get_text(buf.get_start_iter(), \
-                                buf.get_end_iter(), False), 'utf-8')
+                text = buf.get_text(buf.get_start_iter(), \
+                       buf.get_end_iter(), False)
 
                 self.snippet['text'] = text
                 self.snippet_changed()
@@ -1113,7 +1113,7 @@ class Manager(Gtk.Dialog, Gtk.Buildable):
                 if not uris:
                         return
 
-                text = unicode(entry.get_text(), 'utf-8')
+                text = entry.get_text()
 
                 if text:
                         mimes = [text]
@@ -1129,7 +1129,7 @@ class Manager(Gtk.Dialog, Gtk.Buildable):
                         if mime:
                                 mimes.append(mime)
 
-                entry.set_text(u', '.join(mimes))
+                entry.set_text(', '.join(mimes))
                 self.on_entry_drop_targets_focus_out(entry, None)
                 context.finish(True, False, timestamp)
 
diff --git a/plugins/snippets/snippets/parser.py b/plugins/snippets/snippets/parser.py
index 0012c71..628db4e 100644
--- a/plugins/snippets/snippets/parser.py
+++ b/plugins/snippets/snippets/parser.py
@@ -18,7 +18,7 @@
 import os
 import re
 import sys
-from substitutionparser import SubstitutionParser
+from .substitutionparser import SubstitutionParser
 
 class Token:
         def __init__(self, klass, data):
diff --git a/plugins/snippets/snippets/placeholder.py b/plugins/snippets/snippets/placeholder.py
index 5fc95f1..46f338e 100644
--- a/plugins/snippets/snippets/placeholder.py
+++ b/plugins/snippets/snippets/placeholder.py
@@ -25,8 +25,8 @@ import locale
 import subprocess
 from gi.repository import GObject
 
-from helper import *
-from substitutionparser import SubstitutionParser
+from .helper import *
+from .substitutionparser import SubstitutionParser
 
 # These are places in a view where the cursor can go and do things
 class Placeholder:
@@ -143,7 +143,7 @@ class Placeholder:
                         eiter = self.end_iter()
 
                         if biter and eiter:
-                                return unicode(self.buf.get_text(self.begin_iter(), self.end_iter(), False), 'utf-8')
+                                return self.buf.get_text(self.begin_iter(), self.end_iter(), False)
                         else:
                                 return ''
                 else:
@@ -422,7 +422,7 @@ class PlaceholderShell(PlaceholderExpand):
                 self.close_shell()
                 self.remove_timeout()
 
-                self.set_text(unicode.join(u'', self.shell_output).rstrip('\n'))
+                self.set_text(str.join('', self.shell_output).rstrip('\n'))
 
                 if self.default == None:
                         self.default = self.get_text()
@@ -437,10 +437,9 @@ class PlaceholderShell(PlaceholderExpand):
 
                         if len(line) > 0:
                                 try:
-                                        line = unicode(line, 'utf-8')
+                                        line = line
                                 except:
-                                        line = unicode(line, locale.getdefaultlocale()[1],
-                                                        'replace')
+                                        line = line.encode(locale.getdefaultlocale()[1])
 
                                 self.shell_output += line
                                 self.install_timeout()
@@ -539,7 +538,7 @@ class PlaceholderEval(PlaceholderExpand):
                 return hasattr(signal, 'SIGALRM')
 
         def timeout_cb(self, signum = 0, frame = 0):
-                raise TimeoutError, "Operation timed out (>2 seconds)"
+                raise TimeoutError("Operation timed out (>2 seconds)")
 
         def install_timeout(self):
                 if not self.timeout_supported():
@@ -578,7 +577,7 @@ class PlaceholderEval(PlaceholderExpand):
                         del self.namespace['process_snippet']
 
                 try:
-                        exec text in self.namespace
+                        exec(text, self.namespace)
                 except:
                         traceback.print_exc()
 
@@ -603,7 +602,7 @@ class PlaceholderEval(PlaceholderExpand):
                                 'time, execution aborted.') % self.command)
 
                                 return False
-                        except Exception, detail:
+                        except Exception as detail:
                                 self.remove_timeout()
 
                                 message_dialog(None, Gtk.MessageType.ERROR,
@@ -684,7 +683,7 @@ class PlaceholderRegex(PlaceholderExpand):
                 # Try to compile pattern
                 try:
                         regex = re.compile(pattern, self.modifiers)
-                except re.error, message:
+                except re.error as message:
                         sys.stderr.write('Could not compile regular expression: %s\n%s\n' % (pattern, message))
                         return False
 
diff --git a/plugins/snippets/snippets/shareddata.py b/plugins/snippets/snippets/shareddata.py
index 1b5c9c2..3f41a12 100644
--- a/plugins/snippets/snippets/shareddata.py
+++ b/plugins/snippets/snippets/shareddata.py
@@ -15,14 +15,12 @@
 #    along with this program; if not, write to the Free Software
 #    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
-from singleton import Singleton
+from .singleton import Singleton
 import os
 
 from gi.repository import Gtk
 
-class SharedData(object):
-    __metaclass__ = Singleton
-
+class SharedData(object, metaclass=Singleton):
     def __init__(self):
         self.dlg = None
         self.dlg_default_size = None
diff --git a/plugins/snippets/snippets/snippet.py b/plugins/snippets/snippets/snippet.py
index c3afeba..280483a 100644
--- a/plugins/snippets/snippets/snippet.py
+++ b/plugins/snippets/snippets/snippet.py
@@ -18,9 +18,9 @@
 import os
 from gi.repository import Gio
 
-from placeholder import *
-from parser import Parser, Token
-from helper import *
+from .placeholder import *
+from .parser import Parser, Token
+from .helper import *
 
 class EvalUtilities:
         def __init__(self, view=None):
@@ -113,9 +113,9 @@ class Snippet:
 
                 if accel:
                         keyval, mod = Gtk.accelerator_parse(accel)
-                        accel = unicode(Gtk.accelerator_get_label(keyval, mod), 'utf-8')
+                        accel = Gtk.accelerator_get_label(keyval, mod)
 
-                return accel or u''
+                return accel or ''
 
         def display(self):
                 nm = markup_escape(self['description'])
@@ -133,7 +133,7 @@ class Snippet:
                 if not detail:
                         return nm
                 else:
-                        return nm + ' (<b>' + markup_escape(unicode.join(u', ', detail)) + \
+                        return nm + ' (<b>' + markup_escape(', '.join(detail)) + \
                                         '</b>)'
 
         def _add_placeholder(self, placeholder):
@@ -150,7 +150,7 @@ class Snippet:
 
         def _insert_text(self, text):
                 # Insert text keeping indentation in mind
-                indented = unicode.join(u'\n' + self._indent, spaces_instead_of_tabs(self._view, text).split('\n'))
+                indented = str.join('\n' + self._indent, spaces_instead_of_tabs(self._view, text).split('\n'))
                 self._view.get_buffer().insert(self._insert_iter(), indented)
 
         def _insert_iter(self):
@@ -160,7 +160,7 @@ class Snippet:
                 if data in self.environ['utf8']:
                         val = self.environ['utf8'][data]
                 else:
-                        val = u''
+                        val = ''
 
                 # Get all the current indentation
                 all_indent = compute_indentation(self._view, self._insert_iter())
@@ -169,7 +169,7 @@ class Snippet:
                 indent = all_indent[len(self._indent):]
 
                 # Keep indentation
-                return unicode.join(u'\n' + indent, val.split('\n'))
+                return str.join('\n' + indent, val.split('\n'))
 
         def _create_placeholder(self, data):
                 tabstop = data['tabstop']
@@ -247,7 +247,7 @@ class Snippet:
                                 sys.stderr.write('Token class not supported: %s (%s)\n' % token.klass)
                                 continue
 
-                        if isinstance(val, basestring):
+                        if isinstance(val, str):
                                 # Insert text
                                 self._insert_text(val)
                         else:
@@ -321,8 +321,7 @@ class Snippet:
                 # So now all of the snippet is in the buffer, we have all our
                 # placeholders right here, what's next, put all marks in the
                 # plugin_data.marks
-                k = self.placeholders.keys()
-                k.sort(reverse=True)
+                k = sorted(self.placeholders.keys(), reverse=True)
 
                 plugin_data.placeholders.insert(last_index, self.placeholders[0])
                 last_iter = self.placeholders[0].end_iter()
diff --git a/plugins/snippets/snippets/windowactivatable.py b/plugins/snippets/snippets/windowactivatable.py
index 7b99e98..d34e279 100644
--- a/plugins/snippets/snippets/windowactivatable.py
+++ b/plugins/snippets/snippets/windowactivatable.py
@@ -21,10 +21,10 @@ import gettext
 
 from gi.repository import Gtk, Gdk, Gedit, GObject
 
-from document import Document
-from library import Library
-from shareddata import SharedData
-from signals import Signals
+from .document import Document
+from .library import Library
+from .shareddata import SharedData
+from .signals import Signals
 
 class Message(Gedit.Message):
         view = GObject.property(type=Gedit.View)



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]