[gedit] Port snippets to libpeas/gtk+-3
- From: Jesse van den Kieboom <jessevdk src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [gedit] Port snippets to libpeas/gtk+-3
- Date: Mon, 27 Dec 2010 16:43:46 +0000 (UTC)
commit 3f5c69427579f80e8614f551aafa89baa9bfd0ca
Author: Jesse van den Kieboom <jesse vandenkieboom epfl ch>
Date: Sun Dec 19 21:49:25 2010 +0100
Port snippets to libpeas/gtk+-3
This is not yet completely working. But most parts do.
plugins/snippets/snippets/Makefile.am | 26 +-
plugins/snippets/snippets/__init__.py | 97 ++--
.../snippets/{Completion.py => completion.py} | 105 ++--
.../snippets/snippets/{Document.py => document.py} | 377 ++++++------
.../snippets/snippets/{Exporter.py => exporter.py} | 39 +-
plugins/snippets/snippets/{Helper.py => helper.py} | 35 +-
.../snippets/snippets/{Importer.py => importer.py} | 39 +-
.../{LanguageManager.py => languagemanager.py} | 16 +-
.../snippets/snippets/{Library.py => library.py} | 358 ++++++------
.../snippets/snippets/{Manager.py => manager.py} | 661 ++++++++++----------
plugins/snippets/snippets/{Parser.py => parser.py} | 102 ++--
.../snippets/{Placeholder.py => placeholder.py} | 219 ++++----
.../snippets/snippets/{Snippet.py => snippet.py} | 133 ++--
plugins/snippets/snippets/snippets.ui | 65 +--
...SubstitutionParser.py => substitutionparser.py} | 77 ++--
.../{WindowHelper.py => windowactivatable.py} | 146 +++---
16 files changed, 1205 insertions(+), 1290 deletions(-)
---
diff --git a/plugins/snippets/snippets/Makefile.am b/plugins/snippets/snippets/Makefile.am
index 7a05b56..ae46ee9 100644
--- a/plugins/snippets/snippets/Makefile.am
+++ b/plugins/snippets/snippets/Makefile.am
@@ -3,19 +3,19 @@ plugindir = $(GEDIT_PLUGINS_LIBS_DIR)/snippets
plugin_PYTHON = \
__init__.py \
- WindowHelper.py \
- Document.py \
- Library.py \
- Snippet.py \
- Parser.py \
- Placeholder.py \
- Manager.py \
- Helper.py \
- SubstitutionParser.py \
- Importer.py \
- Exporter.py \
- LanguageManager.py \
- Completion.py
+ windowactivatable.py \
+ document.py \
+ library.py \
+ snippet.py \
+ parser.py \
+ placeholder.py \
+ manager.py \
+ helper.py \
+ substitutionparser.py \
+ importer.py \
+ exporter.py \
+ languagemanager.py \
+ completion.py
uidir = $(GEDIT_PLUGINS_DATA_DIR)/snippets/ui
ui_DATA = snippets.ui
diff --git a/plugins/snippets/snippets/__init__.py b/plugins/snippets/snippets/__init__.py
index f2990d8..38f5320 100644
--- a/plugins/snippets/snippets/__init__.py
+++ b/plugins/snippets/snippets/__init__.py
@@ -19,22 +19,29 @@ import sys
import os
import shutil
-import gtk
-from gtk import gdk
-import gedit
+import cairo
+
+from gi.repository import Gtk, Gdk, Gedit, PeasGtk, GObject
import platform
-from WindowHelper import WindowHelper
-from Library import Library
-from Manager import Manager
-from Snippet import Snippet
+from library import Library
+from manager import Manager
+from snippet import Snippet
+
+from windowactivatable import WindowActivatable
+
+class AppActivatable(GObject.Object, Gedit.AppActivatable, PeasGtk.Configurable):
+ __gtype_name__ = "GeditSnippetsAppActivatable"
+
+ app = GObject.property(type=GObject.Object)
-class SnippetsPlugin(gedit.Plugin):
def __init__(self):
- gedit.Plugin.__init__(self)
+ GObject.Object.__init__(self)
self.dlg = None
-
+
+ def do_activate(self):
+ # Initialize snippets library
library = Library()
library.set_accelerator_callback(self.accelerator_activated)
@@ -50,52 +57,36 @@ class SnippetsPlugin(gedit.Plugin):
library.set_dirs(snippetsdir, self.system_dirs())
def system_dirs(self):
- if platform.platform() != 'Windows':
- if 'XDG_DATA_DIRS' in os.environ:
- datadirs = os.environ['XDG_DATA_DIRS']
- else:
- datadirs = '/usr/local/share' + os.pathsep + '/usr/share'
-
- dirs = []
-
- for d in datadirs.split(os.pathsep):
- d = os.path.join(d, 'gedit-2', 'plugins', 'snippets')
-
- if os.path.isdir(d):
- dirs.append(d)
-
- dirs.append(self.get_data_dir())
+ if platform.platform() != 'Windows':
+ if 'XDG_DATA_DIRS' in os.environ:
+ datadirs = os.environ['XDG_DATA_DIRS']
+ else:
+ datadirs = '/usr/local/share' + os.pathsep + '/usr/share'
+
+ dirs = []
+
+ for d in datadirs.split(os.pathsep):
+ d = os.path.join(d, 'gedit-2', 'plugins', 'snippets')
+
+ if os.path.isdir(d):
+ dirs.append(d)
+
+ dirs.append(self.plugin_info.get_data_dir())
return dirs
-
- def activate(self, window):
- data = WindowHelper(self)
- window._snippets_plugin_data = data
- data.run(window)
-
- def deactivate(self, window):
- window._snippets_plugin_data.stop()
- window._snippets_plugin_data = None
-
- def update_ui(self, window):
- window._snippets_plugin_data.update()
-
- def create_configure_dialog(self):
- if not self.dlg:
- self.dlg = Manager(self.get_data_dir())
- else:
- self.dlg.run()
-
- window = gedit.app_get_default().get_active_window()
-
- if window:
- self.dlg.dlg.set_transient_for(window)
-
- return self.dlg.dlg
-
+
+
+ def do_create_configure_widget(self):
+ builder = Gtk.Builder()
+ builder.add_from_file(os.path.join(self.plugin_info.get_data_dir(), 'ui', 'snippets.ui'))
+
+ return builder.get_object('snippets_manager')
+
def accelerator_activated(self, group, obj, keyval, mod):
ret = False
- if hasattr(obj, '_snippets_plugin_data'):
- ret = obj._snippets_plugin_data.accelerator_activated(keyval, mod)
+# if hasattr(obj, '_snippets_plugin_data'):
+# ret = obj._snippets_plugin_data.accelerator_activated(keyval, mod)
return ret
+
+# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/Completion.py b/plugins/snippets/snippets/completion.py
similarity index 77%
rename from plugins/snippets/snippets/Completion.py
rename to plugins/snippets/snippets/completion.py
index f36b5f1..03c4235 100644
--- a/plugins/snippets/snippets/Completion.py
+++ b/plugins/snippets/snippets/completion.py
@@ -15,34 +15,35 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-import gtksourceview2 as gsv
-import gobject
-import gedit
-import gtk
+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"
-class Proposal(gobject.GObject, gsv.CompletionProposal):
def __init__(self, snippet):
- gobject.GObject.__init__(self)
+ GObject.Object.__init__(self)
self._snippet = Snippet(snippet)
-
+
def snippet(self):
return self._snippet.data
-
+
# Interface implementation
def do_get_markup(self):
return self._snippet.display()
-
+
def do_get_info(self):
return self._snippet.data['text']
-class Provider(gobject.GObject, gsv.CompletionProvider):
+class Provider(GObject.Object, GtkSource.CompletionProvider):
+ __gtype_name__ = "GeditSnippetsProvider"
+
def __init__(self, name, language_id, handler):
- gobject.GObject.__init__(self)
-
+ GObject.Object.__init__(self)
+
self.name = name
self.info_widget = None
self.proposals = []
@@ -50,16 +51,16 @@ class Provider(gobject.GObject, gsv.CompletionProvider):
self.handler = handler
self.info_widget = None
self.mark = None
-
- theme = gtk.icon_theme_get_default()
- w, h = gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)
- self.icon = theme.load_icon(gtk.STOCK_JUSTIFY_LEFT, w, 0)
-
+ theme = Gtk.IconTheme.get_default()
+ f, w, h = Gtk.icon_size_lookup(Gtk.IconSize.MENU)
+
+ self.icon = theme.load_icon(Gtk.STOCK_JUSTIFY_LEFT, w, 0)
+
def __del__(self):
if self.mark:
self.mark.get_buffer().delete_mark(self.mark)
-
+
def set_proposals(self, proposals):
self.proposals = proposals
@@ -68,27 +69,27 @@ class Provider(gobject.GObject, gsv.CompletionProvider):
self.mark = it.get_buffer().create_mark(None, it, True)
else:
self.mark.get_buffer().move_mark(self.mark, it)
-
+
def get_word(self, context):
it = context.get_iter()
-
+
if it.starts_word() or it.starts_line() or not it.ends_word():
return None
-
+
start = it.copy()
-
+
if start.backward_word_start():
self.mark_position(start)
return start.get_text(it)
else:
return None
-
- def do_get_start_iter(self, context, proposal):
+
+ def do_get_start_iter(self, context, proposal, iter):
if not self.mark or self.mark.get_deleted():
return None
-
+
return self.mark.get_buffer().get_iter_at_mark(self.mark)
-
+
def do_match(self, context):
return True
@@ -97,7 +98,7 @@ class Provider(gobject.GObject, gsv.CompletionProvider):
proposals = self.proposals
else:
proposals = Library().get_snippets(None)
-
+
if self.language_id:
proposals += Library().get_snippets(self.language_id)
@@ -116,26 +117,26 @@ class Provider(gobject.GObject, gsv.CompletionProvider):
def do_activate_proposal(self, proposal, piter):
return self.handler(proposal, piter)
-
+
def do_get_info_widget(self, proposal):
if not self.info_widget:
- view = gedit.View(gedit.Document())
+ view = Gedit.View(Gedit.Document())
manager = get_language_manager()
lang = manager.get_language('snippets')
view.get_buffer().set_language(lang)
-
- sw = gtk.ScrolledWindow()
+
+ sw = Gtk.ScrolledWindow()
sw.add(view)
-
+
self.info_view = view
self.info_widget = sw
-
+
return self.info_widget
-
+
def do_update_info(self, proposal, info):
buf = self.info_view.get_buffer()
-
+
buf.set_text(proposal.get_info())
buf.move_mark(buf.get_insert(), buf.get_start_iter())
buf.move_mark(buf.get_selection_bound(), buf.get_start_iter())
@@ -143,40 +144,38 @@ class Provider(gobject.GObject, gsv.CompletionProvider):
info.set_sizing(-1, -1, False, False)
info.process_resize()
-
+
def do_get_icon(self):
return self.icon
def do_get_activation(self):
- return gsv.COMPLETION_ACTIVATION_USER_REQUESTED
+ return GtkSource.CompletionActivation.USER_REQUESTED
+
+class Defaults(GObject.Object, GtkSource.CompletionProvider):
+ __gtype_name__ = "GeditSnippetsDefaultsProvider"
-class Defaults(gobject.GObject, gsv.CompletionProvider):
def __init__(self, handler):
- gobject.GObject.__init__(self)
+ GObject.Object.__init__(self)
self.handler = handler
self.proposals = []
-
+
def set_defaults(self, defaults):
self.proposals = []
-
+
for d in defaults:
- self.proposals.append(gsv.CompletionItem(d))
-
+ self.proposals.append(GtkSource.CompletionItem(d))
+
def do_get_name(self):
return ""
-
+
def do_activate_proposal(self, proposal, piter):
return self.handler(proposal, piter)
-
+
def do_populate(self, context):
context.add_proposals(self, self.proposals, True)
def do_get_activation(self):
- return gsv.COMPLETION_ACTIVATION_NONE
-
-gobject.type_register(Proposal)
-gobject.type_register(Provider)
-gobject.type_register(Defaults)
+ return GtkSource.CompletionActivation.NONE
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/Document.py b/plugins/snippets/snippets/document.py
similarity index 87%
rename from plugins/snippets/snippets/Document.py
rename to plugins/snippets/snippets/document.py
index 7c275da..6f84e2c 100644
--- a/plugins/snippets/snippets/Document.py
+++ b/plugins/snippets/snippets/document.py
@@ -18,17 +18,14 @@
import os
import re
-import gtk
-from gtk import gdk
-import gio
-import gedit
-import gtksourceview2 as gsv
-import gobject
-
-from Library import Library
-from Snippet import Snippet
-from Placeholder import *
-import Completion
+import cairo
+from gi.repository import Gtk, Gdk, Gio, GLib, GtkSource, Gedit
+import glib
+
+from library import Library
+from snippet import Snippet
+from placeholder import *
+import completion
class DynamicSnippet(dict):
def __init__(self, text):
@@ -36,37 +33,37 @@ class DynamicSnippet(dict):
self.valid = True
class Document:
- TAB_KEY_VAL = (gtk.keysyms.Tab, \
- gtk.keysyms.ISO_Left_Tab)
- SPACE_KEY_VAL = (gtk.keysyms.space,)
-
+ TAB_KEY_VAL = (Gdk.KEY_Tab, \
+ Gdk.KEY_ISO_Left_Tab)
+ SPACE_KEY_VAL = (Gdk.KEY_space,)
+
def __init__(self, instance, view):
self.view = None
self.instance = instance
-
+
self.placeholders = []
self.active_snippets = []
self.active_placeholder = None
self.signal_ids = {}
-
+
self.ordered_placeholders = []
self.update_placeholders = []
self.jump_placeholders = []
self.language_id = 0
self.timeout_update_id = 0
-
- self.provider = Completion.Provider(_('Snippets'), self.language_id, self.on_proposal_activated)
- self.defaults_provider = Completion.Defaults(self.on_default_activated)
-
+
+ self.provider = completion.Provider(_('Snippets'), self.language_id, self.on_proposal_activated)
+ self.defaults_provider = completion.Defaults(self.on_default_activated)
+
# Always have a reference to the global snippets
Library().ref(None)
self.set_view(view)
-
+
# Stop controlling the view. Remove all active snippets, remove references
# to the view and the plugin instance, disconnect all signal handlers
def stop(self):
if self.timeout_update_id != 0:
- gobject.source_remove(self.timeout_update_id)
+ GLib.source_remove(self.timeout_update_id)
self.timeout_update_id = 0
del self.update_placeholders[:]
del self.jump_placeholders[:]
@@ -81,15 +78,15 @@ class Document:
if (obj, signal) in self.signal_ids:
obj.disconnect(self.signal_ids[(obj, signal)])
del self.signal_ids[(obj, signal)]
-
+
def connect_signal(self, obj, signal, cb):
- self.disconnect_signal(obj, signal)
+ self.disconnect_signal(obj, signal)
self.signal_ids[(obj, signal)] = obj.connect(signal, cb)
def connect_signal_after(self, obj, signal, cb):
self.disconnect_signal(obj, signal)
self.signal_ids[(obj, signal)] = obj.connect_after(signal, cb)
-
+
# Set the view to be controlled. Installs signal handlers and sets current
# language. If there is already a view set this function will first remove
# all currently active snippets and disconnect all current signals. So
@@ -100,28 +97,31 @@ class Document:
buf = self.view.get_buffer()
# Remove signals
- signals = {self.view: ('key-press-event', 'destroy',
+ signals = {self.view: ('key-press-event', 'destroy',
'notify::editable', 'drag-data-received', 'expose-event'),
buf: ('notify::language', 'changed', 'cursor-moved', 'insert-text'),
self.view.get_completion(): ('hide',)}
for obj, sig in signals.items():
- for s in sig:
- self.disconnect_signal(obj, s)
-
+ if obj:
+ for s in sig:
+ self.disconnect_signal(obj, s)
+
# Remove all active snippets
for snippet in list(self.active_snippets):
self.deactivate_snippet(snippet, True)
-
+
completion = self.view.get_completion()
- completion.remove_provider(self.provider)
- completion.remove_provider(self.defaults_provider)
+
+ if completion:
+ completion.remove_provider(self.provider)
+ completion.remove_provider(self.defaults_provider)
self.view = view
-
+
if view != None:
buf = view.get_buffer()
-
+
self.connect_signal(view, 'destroy', self.on_view_destroy)
if view.get_editable():
@@ -130,22 +130,22 @@ class Document:
self.connect_signal(buf, 'notify::language', self.on_notify_language)
self.connect_signal(view, 'notify::editable', self.on_notify_editable)
self.connect_signal(view, 'drag-data-received', self.on_drag_data_received)
- self.connect_signal_after(view, 'expose-event', self.on_expose_event)
+ self.connect_signal_after(view, 'draw', self.on_draw)
self.update_language()
completion = view.get_completion()
+
completion.add_provider(self.provider)
-
completion.add_provider(self.defaults_provider)
-
+
self.connect_signal(completion, 'hide', self.on_completion_hide)
elif self.language_id != 0:
langid = self.language_id
-
+
self.language_id = None;
self.provider.language_id = self.language_id
-
+
if self.instance:
self.instance.language_changed(self)
@@ -154,7 +154,7 @@ class Document:
def set_view(self, view):
if view == self.view:
return
-
+
self._set_view(view)
# Call this whenever the language in the view changes. This makes sure that
@@ -187,7 +187,7 @@ class Document:
if not self.view or not self.view.get_editable():
return False
- accelerator = gtk.accelerator_name(keyval, mod)
+ accelerator = Gtk.accelerator_name(keyval, mod)
snippets = Library().from_accelerator(accelerator, \
self.language_id)
@@ -206,11 +206,11 @@ class Document:
def first_snippet_inserted(self):
buf = self.view.get_buffer()
-
+
self.connect_signal(buf, 'changed', self.on_buffer_changed)
self.connect_signal(buf, 'cursor-moved', self.on_buffer_cursor_moved)
self.connect_signal_after(buf, 'insert-text', self.on_buffer_insert_text)
-
+
def last_snippet_removed(self):
buf = self.view.get_buffer()
self.disconnect_signal(buf, 'changed')
@@ -219,8 +219,8 @@ class Document:
def current_placeholder(self):
buf = self.view.get_buffer()
-
- piter = buf.get_iter_at_mark(buf.get_insert())
+
+ piter = buf.get_iter_at_mark(buf.get_insert())
found = []
for placeholder in self.placeholders:
@@ -240,17 +240,17 @@ class Document:
def advance_placeholder(self, direction):
# Returns (CurrentPlaceholder, NextPlaceholder), depending on direction
buf = self.view.get_buffer()
-
+
piter = buf.get_iter_at_mark(buf.get_insert())
found = current = next = None
length = len(self.placeholders)
-
+
placeholders = list(self.placeholders)
-
+
if self.active_placeholder:
begin = self.active_placeholder.begin_iter()
end = self.active_placeholder.end_iter()
-
+
if piter.compare(begin) >= 0 and piter.compare(end) <= 0:
current = self.active_placeholder
currentIndex = placeholders.index(self.active_placeholder)
@@ -270,19 +270,19 @@ class Document:
placeholder = placeholders[index]
begin = placeholder.begin_iter()
end = placeholder.end_iter()
-
+
# Find the nearest placeholder
if nearest(piter, begin, end, found):
foundIndex = index
found = placeholder
-
+
# Find the current placeholder
if piter.compare(begin) >= 0 and \
piter.compare(end) <= 0 and \
current == None:
currentIndex = index
current = placeholder
-
+
if current and current != found and \
(current.begin_iter().compare(found.begin_iter()) == 0 or \
current.end_iter().compare(found.begin_iter()) == 0) and \
@@ -292,7 +292,7 @@ class Document:
# resolve the 'hugging' problem
current = self.active_placeholder
currentIndex = placeholders.index(current)
-
+
if current:
if indexer(currentIndex):
next = placeholders[currentIndex + direction]
@@ -300,19 +300,19 @@ class Document:
next = found
elif length > 0:
next = self.placeholders[0]
-
+
return current, next
-
+
def next_placeholder(self):
return self.advance_placeholder(1)
-
+
def previous_placeholder(self):
return self.advance_placeholder(-1)
def cursor_on_screen(self):
buf = self.view.get_buffer()
self.view.scroll_mark_onscreen(buf.get_insert())
-
+
def set_active_placeholder(self, placeholder):
self.active_placeholder = placeholder
@@ -323,20 +323,20 @@ class Document:
# Signal this placeholder to end action
self.view.get_completion().hide()
current.leave()
-
+
if current.__class__ == PlaceholderEnd:
last = current
-
+
self.set_active_placeholder(next)
-
+
if next:
next.enter()
-
+
if next.__class__ == PlaceholderEnd:
last = next
elif len(next.defaults) > 1 and next.get_text() == next.default:
self.defaults_provider.set_defaults(next.defaults)
-
+
cm = self.view.get_completion()
cm.show([self.defaults_provider], cm.create_context())
@@ -346,15 +346,15 @@ class Document:
if snippet.placeholders[0] == last:
self.deactivate_snippet(snippet)
break
-
+
self.cursor_on_screen()
-
+
return next != None
-
+
def skip_to_next_placeholder(self):
(current, next) = self.next_placeholder()
return self.goto_placeholder(current, next)
-
+
def skip_to_previous_placeholder(self):
(current, prev) = self.previous_placeholder()
return self.goto_placeholder(current, prev)
@@ -363,36 +363,36 @@ class Document:
bounds = buf.get_selection_bounds()
if bounds:
- return buf.get_text(bounds[0], bounds[1])
+ return buf.get_text(bounds[0], bounds[1], False)
else:
return ''
def env_get_current_word(self, buf):
start, end = buffer_word_boundary(buf)
-
- return buf.get_text(start, end)
+
+ return buf.get_text(start, end, False)
def env_get_current_line(self, buf):
start, end = buffer_line_boundary(buf)
-
- return buf.get_text(start, end)
+
+ return buf.get_text(start, end, False)
def env_get_current_line_number(self, buf):
start, end = buffer_line_boundary(buf)
-
+
return str(start.get_line() + 1)
-
+
def env_get_document_uri(self, buf):
location = buf.get_location()
-
+
if location:
return location.get_uri()
else:
return ''
-
+
def env_get_document_name(self, buf):
location = buf.get_location()
-
+
if location:
return location.get_basename()
else:
@@ -400,7 +400,7 @@ class Document:
def env_get_document_scheme(self, buf):
location = buf.get_location()
-
+
if location:
return location.get_uri_scheme()
else:
@@ -408,7 +408,7 @@ class Document:
def env_get_document_path(self, buf):
location = buf.get_location()
-
+
if location:
return location.get_path()
else:
@@ -424,7 +424,7 @@ class Document:
def env_get_document_type(self, buf):
typ = buf.get_mime_type()
-
+
if typ:
return typ
else:
@@ -432,40 +432,40 @@ class Document:
def env_get_documents_uri(self, buf):
toplevel = self.view.get_toplevel()
-
- if isinstance(toplevel, gedit.Window):
+
+ if isinstance(toplevel, Gedit.Window):
documents_uri = [doc.get_location().get_uri()
for doc in toplevel.get_documents()
if doc.get_location() is not None]
else:
documents_uri = []
-
+
return ' '.join(documents_uri)
def env_get_documents_path(self, buf):
toplevel = self.view.get_toplevel()
-
- if isinstance(toplevel, gedit.Window):
+
+ if isinstance(toplevel, Gedit.Window):
documents_location = [doc.get_location()
for doc in toplevel.get_documents()
if doc.get_location() is not None]
documents_path = [location.get_path()
for location in documents_location
- if gedit.utils.location_has_file_scheme(location)]
+ if Gedit.utils_location_has_file_scheme(location)]
else:
documents_path = []
-
+
return ' '.join(documents_path)
def update_environment(self):
buf = self.view.get_buffer()
-
- variables = {'GEDIT_SELECTED_TEXT': self.env_get_selected_text,
- 'GEDIT_CURRENT_WORD': self.env_get_current_word,
+
+ 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_URI': self.env_get_document_uri,
+ 'GEDIT_CURRENT_DOCUMENT_URI': self.env_get_document_uri,
'GEDIT_CURRENT_DOCUMENT_NAME': self.env_get_document_name,
'GEDIT_CURRENT_DOCUMENT_SCHEME': self.env_get_document_scheme,
'GEDIT_CURRENT_DOCUMENT_PATH': self.env_get_document_path,
@@ -474,26 +474,26 @@ class Document:
'GEDIT_DOCUMENTS_URI': self.env_get_documents_uri,
'GEDIT_DOCUMENTS_PATH': self.env_get_documents_path,
}
-
+
for var in variables:
os.environ[var] = variables[var](buf)
-
+
def uses_current_word(self, snippet):
matches = re.findall('(\\\\*)\\$GEDIT_CURRENT_WORD', snippet['text'])
-
+
for match in matches:
if len(match) % 2 == 0:
return True
-
+
return False
-
+
def uses_current_line(self, snippet):
matches = re.findall('(\\\\*)\\$GEDIT_CURRENT_LINE', snippet['text'])
-
+
for match in matches:
if len(match) % 2 == 0:
return True
-
+
return False
def apply_snippet(self, snippet, start = None, end = None):
@@ -502,40 +502,40 @@ class Document:
buf = self.view.get_buffer()
s = Snippet(snippet)
-
+
if not start:
start = buf.get_iter_at_mark(buf.get_insert())
-
+
if not end:
end = buf.get_iter_at_mark(buf.get_selection_bound())
if start.equal(end) and self.uses_current_word(s):
# There is no tab trigger and no selection and the snippet uses
- # the current word. Set start and end to the word boundary so that
+ # the current word. Set start and end to the word boundary so that
# it will be removed
start, end = buffer_word_boundary(buf)
elif start.equal(end) and self.uses_current_line(s):
# There is no tab trigger and no selection and the snippet uses
- # the current line. Set start and end to the line boundary so that
+ # the current line. Set start and end to the line boundary so that
# it will be removed
start, end = buffer_line_boundary(buf)
# Set environmental variables
self.update_environment()
-
+
# You know, we could be in an end placeholder
(current, next) = self.next_placeholder()
if current and current.__class__ == PlaceholderEnd:
self.goto_placeholder(current, None)
-
+
buf.begin_user_action()
# Remove the tag, selection or current word
buf.delete(start, end)
-
+
# Insert the snippet
holders = len(self.placeholders)
-
+
if len(self.active_snippets) == 0:
self.first_snippet_inserted()
@@ -559,12 +559,14 @@ class Document:
cur = buf.get_iter_at_mark(buf.get_insert())
last = sn.end_iter()
- curloc = self.view.get_iter_location(cur)
- lastloc = self.view.get_iter_location(last)
+ # FIXME: get_iter_location doesnt work
+
+ #curloc = self.view.get_iter_location(cur)
+ #lastloc = self.view.get_iter_location(last)
- if (lastloc.y + lastloc.height) - curloc.y <= \
- self.view.get_visible_rect().height:
- self.view.scroll_mark_onscreen(sn.end_mark)
+ #if (lastloc.y + lastloc.height) - curloc.y <= \
+ # self.view.get_visible_rect().height:
+ # self.view.scroll_mark_onscreen(sn.end_mark)
buf.end_user_action()
self.view.grab_focus()
@@ -576,21 +578,21 @@ class Document:
end = buf.get_iter_at_mark(buf.get_insert())
start = end.copy()
-
+
word = None
-
+
if start.backward_word_start():
# Check if we were at a word start ourselves
tmp = start.copy()
tmp.forward_word_end()
-
+
if tmp.equal(end):
- word = buf.get_text(start, end)
+ word = buf.get_text(start, end, False)
else:
start = end.copy()
else:
start = end.copy()
-
+
if not word or word == '':
if start.backward_char():
word = start.get_char()
@@ -619,12 +621,12 @@ class Document:
# Do the fancy completion dialog
self.provider.set_proposals(snippets)
cm = self.view.get_completion()
-
+
cm.show([self.provider], cm.create_context())
return True
return False
-
+
def run_snippet(self):
if not self.view:
return False
@@ -652,12 +654,12 @@ class Document:
placeholders = snippet.placeholders[-1]
else:
placeholders = [snippet.placeholders[tabstop]]
-
+
for placeholder in placeholders:
if placeholder in self.placeholders:
if placeholder in self.update_placeholders:
placeholder.update_contents()
-
+
self.update_placeholders.remove(placeholder)
elif placeholder in self.jump_placeholders:
placeholder[0].leave()
@@ -716,7 +718,7 @@ class Document:
else:
begin = snippet.begin_iter()
end = snippet.end_iter()
-
+
if piter.compare(begin) < 0 or piter.compare(end) > 0:
# Oh no! Remove the snippet this instant!!
self.deactivate_snippet(snippet)
@@ -727,7 +729,7 @@ class Document:
self.jump_placeholders.append((self.active_placeholder, current))
if self.timeout_update_id == 0:
- self.timeout_update_id = gobject.timeout_add(0,
+ self.timeout_update_id = glib.timeout_add(0,
self.update_snippet_contents)
def on_buffer_changed(self, buf):
@@ -736,41 +738,41 @@ class Document:
if current:
if not current in self.update_placeholders:
self.update_placeholders.append(current)
-
+
if self.timeout_update_id == 0:
- self.timeout_update_id = gobject.timeout_add(0, \
+ self.timeout_update_id = glib.timeout_add(0, \
self.update_snippet_contents)
-
+
def on_buffer_insert_text(self, buf, piter, text, length):
ctx = get_buffer_context(buf)
-
- # do nothing special if there is no context and no active
+
+ # do nothing special if there is no context and no active
# placeholder
if (not ctx) and (not self.active_placeholder):
return
-
+
if not ctx:
ctx = self.active_placeholder
-
+
if not ctx in self.ordered_placeholders:
return
-
+
# move any marks that were incorrectly moved by this insertion
# back to where they belong
begin = ctx.begin_iter()
end = ctx.end_iter()
idx = self.ordered_placeholders.index(ctx)
-
+
for placeholder in self.ordered_placeholders:
if placeholder == ctx:
continue
-
+
ob = placeholder.begin_iter()
oe = placeholder.end_iter()
-
+
if ob.compare(begin) == 0 and ((not oe) or oe.compare(end) == 0):
oidx = self.ordered_placeholders.index(placeholder)
-
+
if oidx > idx and ob:
buf.move_mark(placeholder.begin, end)
elif oidx < idx and oe:
@@ -779,35 +781,37 @@ class Document:
buf.move_mark(placeholder.begin, end)
elif (oe and oe.compare(begin) > 0) and ob.compare(begin) <= 0:
buf.move_mark(placeholder.end, begin)
-
+
def on_notify_language(self, buf, spec):
self.update_language()
def on_notify_editable(self, view, spec):
self._set_view(view)
-
+
def on_view_key_press(self, view, event):
library = Library()
- if not (event.state & gdk.CONTROL_MASK) and \
- not (event.state & gdk.MOD1_MASK) and \
+ _, state = event.get_state()
+
+ if not (state & Gdk.ModifierType.CONTROL_MASK) and \
+ not (state & Gdk.ModifierType.MOD1_MASK) and \
event.keyval in self.TAB_KEY_VAL:
- if not event.state & gdk.SHIFT_MASK:
+ if not state & Gdk.ModifierType.SHIFT_MASK:
return self.run_snippet()
else:
return self.skip_to_previous_placeholder()
elif not library.loaded and \
- library.valid_accelerator(event.keyval, event.state):
+ library.valid_accelerator(event.keyval, state):
library.ensure_files()
library.ensure(self.language_id)
self.accelerator_activate(event.keyval, \
- event.state & gtk.accelerator_get_default_mod_mask())
+ state & Gtk.accelerator_get_default_mod_mask())
return False
-
+
def path_split(self, path, components=[]):
head, tail = os.path.split(path)
-
+
if not tail and head:
return [head] + components
elif tail:
@@ -852,7 +856,7 @@ class Document:
if not path2:
result = os.path.basename(second)
-
+
if path2:
result += os.path.join(*path2)
@@ -860,12 +864,12 @@ class Document:
def apply_uri_snippet(self, snippet, mime, uri):
# Remove file scheme
- gfile = gio.File(uri)
+ gfile = Gio.File(uri)
pathname = ''
dirname = ''
ruri = ''
- if gedit.utils.location_has_file_scheme(gfile):
+ if Gedit.utils_location_has_file_scheme(gfile):
pathname = gfile.get_path()
dirname = gfile.get_parent().get_path()
@@ -889,7 +893,7 @@ class Document:
os.environ['GEDIT_DROP_DOCUMENT_RELATIVE_PATH'] = relpath
mark = buf.get_mark('gtk_drag_target')
-
+
if not mark:
mark = buf.get_insert()
@@ -898,29 +902,29 @@ class Document:
def in_bounds(self, x, y):
rect = self.view.get_visible_rect()
- rect.x, rect.y = self.view.buffer_to_window_coords(gtk.TEXT_WINDOW_WIDGET, rect.x, rect.y)
+ rect.x, rect.y = self.view.buffer_to_window_coords(Gtk.TextWindowType.WIDGET, rect.x, rect.y)
return not (x < rect.x or x > rect.x + rect.width or y < rect.y or y > rect.y + rect.height)
-
- def on_drag_data_received(self, view, context, x, y, data, info, timestamp):
- if not (gtk.targets_include_uri(context.targets) and data.data and self.in_bounds(x, y)):
+
+ def on_drag_data_received(self, view, context, x, y, data, info, timestamp):
+ if not (Gtk.targets_include_uri(context.targets) and data.data and self.in_bounds(x, y)):
return
uris = drop_get_uris(data)
uris.reverse()
stop = False
-
+
for uri in uris:
try:
- mime = gio.content_type_guess(uri)
+ mime = Gio.content_type_guess(uri)
except:
mime = None
if not mime:
continue
-
+
snippets = Library().from_drop_target(mime, self.language_id)
-
+
if snippets:
stop = True
self.apply_uri_snippet(snippets[0], mime, uri)
@@ -930,19 +934,19 @@ class Document:
view.stop_emission('drag-data-received')
view.get_toplevel().present()
view.grab_focus()
-
+
def find_uri_target(self, context):
- lst = gtk.target_list_add_uri_targets((), 0)
-
+ lst = Gtk.target_list_add_uri_targets((), 0)
+
return self.view.drag_dest_find_target(context, lst)
-
+
def on_completion_hide(self, completion):
self.provider.set_proposals(None)
def on_proposal_activated(self, proposal, piter):
buf = self.view.get_buffer()
bounds = buf.get_selection_bounds()
-
+
if bounds:
self.apply_snippet(proposal.snippet(), None, None)
else:
@@ -950,7 +954,7 @@ class Document:
self.apply_snippet(proposal.snippet(), start, end)
return True
-
+
def on_default_activated(self, proposal, piter):
buf = self.view.get_buffer()
bounds = buf.get_selection_bounds()
@@ -967,7 +971,7 @@ class Document:
def iter_coords(self, piter):
rect = self.view.get_iter_location(piter)
- rect.x, rect.y = self.view.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT, rect.x, rect.y)
+ rect.x, rect.y = self.view.buffer_to_window_coords(Gtk.TextWindowType.TEXT, rect.x, rect.y)
return rect
@@ -996,13 +1000,13 @@ class Document:
line = start.copy()
line.set_line_offset(0)
- geom = self.view.get_window(gtk.TEXT_WINDOW_TEXT).get_geometry()
-
+ geom = self.view.get_window(Gtk.TextWindowType.TEXT).get_geometry()
+
ctx.translate(0.5, 0.5)
-
+
while line.get_line() <= end_line:
ypos, height = self.view.get_line_yrange(line)
- x_, ypos = self.view.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT, 0, ypos)
+ x_, ypos = self.view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, 0, ypos)
if line.get_line() == start_line and line.get_line() == end_line:
# Simply draw a box, both are on the same line
@@ -1026,7 +1030,7 @@ class Document:
def draw_placeholder_bar(self, ctx, placeholder, col):
start = placeholder.begin_iter()
start_rect = self.iter_coords(start)
-
+
ctx.translate(0.5, 0.5)
extend_width = 2.5
@@ -1035,7 +1039,7 @@ class Document:
ctx.move_to(start_rect.x, start_rect.y)
ctx.rel_line_to(0, start_rect.height - 1)
-
+
ctx.rel_move_to(-extend_width, 0)
ctx.rel_line_to(extend_width * 2, 0)
ctx.stroke()
@@ -1049,9 +1053,9 @@ class Document:
buf = self.view.get_buffer()
- col = self.from_color(self.view.get_style().text[gtk.STATE_INSENSITIVE])
+ col = self.from_color(self.view.get_style().text[Gtk.StateType.INSENSITIVE])
ctx.set_source_rgba(col[0], col[1], col[2], 0.5)
-
+
if placeholder.tabstop > 0:
ctx.set_dash([], 0)
else:
@@ -1065,24 +1069,29 @@ class Document:
else:
self.draw_placeholder_rect(ctx, placeholder, col)
- def on_expose_event(self, view, event):
- if event.window != view.get_window(gtk.TEXT_WINDOW_TEXT):
- return False
+ def on_draw(self, view, ctx):
+# window = view.get_window(Gtk.TextWindowType.TEXT)
- # Draw something
- ctx = event.window.cairo_create()
- ctx.rectangle(event.area)
- ctx.clip()
+# if not Gtk.cairo_should_draw_window(ctx, window):
+# return False
- ctx.set_line_width(1.0)
+# # Draw something
+# ctx.set_line_width(1.0)
- for placeholder in self.ordered_placeholders:
- if not self.placeholder_in_area(placeholder, event.area):
- continue
+# Gtk.cairo_transform_to_window(ctx, view, window)
+
+# clipped, clip = Gdk.cairo_get_clip_rectangle(ctx)
+
+# if not clipped:
+# return False
+
+# for placeholder in self.ordered_placeholders:
+# if not self.placeholder_in_area(placeholder, clipped):
+# continue
- ctx.save()
- self.draw_placeholder(ctx, placeholder)
- ctx.restore()
+# ctx.save()
+# self.draw_placeholder(ctx, placeholder)
+# ctx.restore()
return False
diff --git a/plugins/snippets/snippets/Exporter.py b/plugins/snippets/snippets/exporter.py
similarity index 92%
rename from plugins/snippets/snippets/Exporter.py
rename to plugins/snippets/snippets/exporter.py
index 8dcf623..7b80210 100644
--- a/plugins/snippets/snippets/Exporter.py
+++ b/plugins/snippets/snippets/exporter.py
@@ -20,9 +20,9 @@ import tempfile
import sys
import shutil
-from snippets.Library import *
+from library import *
import xml.etree.ElementTree as et
-from Helper import *
+from helper import *
class Exporter:
def __init__(self, filename, snippets):
@@ -31,7 +31,7 @@ class Exporter:
def set_snippets(self, snippets):
self.snippets = {}
-
+
for snippet in snippets:
lang = snippet.language()
@@ -43,66 +43,66 @@ class Exporter:
def export_xml(self, dirname, language, snippets):
# Create the root snippets node
root = et.Element('snippets')
-
+
# Create filename based on language
if language:
filename = os.path.join(dirname, language + '.xml')
-
+
# Set the language attribute
root.attrib['language'] = language
else:
filename = os.path.join(dirname, 'global.xml')
-
+
# Add all snippets to the root node
for snippet in snippets:
root.append(snippet.to_xml())
-
+
# Write xml
write_xml(root, filename, ('text', 'accelerator'))
def export_archive(self, cmd):
dirname = tempfile.mkdtemp()
-
+
# Save current working directory and change to temporary directory
curdir = os.getcwd()
-
+
try:
os.chdir(dirname)
-
+
# Write snippet xml files
for language, snippets in self.snippets.items():
self.export_xml(dirname, language , snippets)
-
+
# Archive files
status = os.system('%s "%s" *.xml' % (cmd, self.filename))
finally:
os.chdir(curdir)
-
+
if status != 0:
return _('The archive "%s" could not be created' % self.filename)
-
+
# Remove the temporary directory
shutil.rmtree(dirname)
def export_targz(self):
self.export_archive('tar -c --gzip -f')
-
+
def export_tarbz2(self):
self.export_archive('tar -c --bzip2 -f')
def export_tar(self):
self.export_archive('tar -cf')
-
+
def run(self):
dirname = os.path.dirname(self.filename)
if not os.path.exists(dirname):
return _('Target directory "%s" does not exist') % dirname
-
+
if not os.path.isdir(dirname):
return _('Target directory "%s" is not a valid directory') % dirname
-
+
(root, ext) = os.path.splitext(self.filename)
-
+
actions = {'.tar.gz': self.export_targz,
'.tar.bz2': self.export_tarbz2,
'.tar': self.export_tar}
@@ -110,6 +110,7 @@ class Exporter:
for k, v in actions.items():
if self.filename.endswith(k):
return v()
-
+
return self.export_targz()
+
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/Helper.py b/plugins/snippets/snippets/helper.py
similarity index 95%
rename from plugins/snippets/snippets/Helper.py
rename to plugins/snippets/snippets/helper.py
index de36336..0598dc0 100644
--- a/plugins/snippets/snippets/Helper.py
+++ b/plugins/snippets/snippets/helper.py
@@ -20,11 +20,10 @@ from xml.sax import saxutils
from xml.etree.ElementTree import *
import re
-import gtk
-from gtk import gdk
+from gi.repository import Gtk, Gdk
def message_dialog(par, typ, msg):
- d = gtk.MessageDialog(par, gtk.DIALOG_MODAL, typ, gtk.BUTTONS_OK, msg)
+ d = Gtk.MessageDialog(par, Gtk.DialogFlags.MODAL, typ, Gtk.ButtonsType.OK, msg)
d.set_property('use-markup', True)
d.run()
@@ -34,19 +33,19 @@ def compute_indentation(view, piter):
line = piter.get_line()
start = view.get_buffer().get_iter_at_line(line)
end = start.copy()
-
+
ch = end.get_char()
-
+
while (ch.isspace() and ch != '\r' and ch != '\n' and \
end.compare(piter) < 0):
if not end.forward_char():
break;
-
+
ch = end.get_char()
-
+
if start.equal(end):
return ''
-
+
return start.get_slice(end)
def markup_escape(text):
@@ -76,7 +75,7 @@ def insert_with_indent(view, piter, text, indentfirst = True, context = None):
text += indent + lines[i] + '\n'
else:
text += lines[i] + '\n'
-
+
view.get_buffer().insert(piter, text[:-1])
view.get_buffer().set_data('GeditSnippetsPluginContext', None)
@@ -111,7 +110,7 @@ def _write_node(node, file, cdata_nodes=(), indent=0):
_write_indent(file, "<?%s?>\n" % saxutils.escape(node.text.encode('utf-8')), indent)
else:
items = node.items()
-
+
if items or node.text or len(node):
_write_indent(file, "<" + tag.encode('utf-8'), indent)
@@ -131,7 +130,7 @@ def _write_node(node, file, cdata_nodes=(), indent=0):
for n in node:
_write_node(n, file, cdata_nodes, indent + 1)
-
+
if not len(node):
file.write("</" + tag.encode('utf-8') + ">\n")
else:
@@ -150,33 +149,33 @@ def _cdata(text, replace=string.replace):
def buffer_word_boundary(buf):
iter = buf.get_iter_at_mark(buf.get_insert())
start = iter.copy()
-
+
if not iter.starts_word() and (iter.inside_word() or iter.ends_word()):
start.backward_word_start()
-
+
if not iter.ends_word() and iter.inside_word():
iter.forward_word_end()
-
+
return (start, iter)
def buffer_line_boundary(buf):
iter = buf.get_iter_at_mark(buf.get_insert())
start = iter.copy()
start.set_line_offset(0)
-
+
if not iter.ends_line():
iter.forward_to_line_end()
-
+
return (start, iter)
def drop_get_uris(selection):
lines = re.split('\\s*[\\n\\r]+\\s*', selection.data.strip())
result = []
-
+
for line in lines:
if not line.startswith('#'):
result.append(line)
-
+
return result
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/Importer.py b/plugins/snippets/snippets/importer.py
similarity index 92%
rename from plugins/snippets/snippets/Importer.py
rename to plugins/snippets/snippets/importer.py
index c0f76c8..1e267eb 100644
--- a/plugins/snippets/snippets/Importer.py
+++ b/plugins/snippets/snippets/importer.py
@@ -20,7 +20,7 @@ import tempfile
import sys
import shutil
-from snippets.Library import *
+from library import *
class Importer:
def __init__(self, filename):
@@ -28,46 +28,46 @@ class Importer:
def import_destination(self, filename):
userdir = Library().userdir
-
+
filename = os.path.basename(filename)
(root, ext) = os.path.splitext(filename)
filename = os.path.join(userdir, root + ext)
i = 1
-
+
while os.path.exists(filename):
filename = os.path.join(userdir, root + '_' + str(i) + ext)
i += 1
-
+
return filename
-
+
def import_file(self, filename):
if not os.path.exists(filename):
return _('File "%s" does not exist') % filename
-
+
if not os.path.isfile(filename):
return _('File "%s" is not a valid snippets file') % filename
-
+
# Find destination for file to copy to
dest = self.import_destination(filename)
# Copy file
shutil.copy(filename, dest)
-
+
# Add library
if not Library().add_user_library(dest):
return _('Imported file "%s" is not a valid snippets file') % os.path.basename(dest)
-
+
def import_xml(self):
return self.import_file(self.filename)
def import_archive(self, cmd):
dirname = tempfile.mkdtemp()
status = os.system('cd %s; %s "%s"' % (dirname, cmd, self.filename))
-
+
if status != 0:
return _('The archive "%s" could not be extracted' % self.filename)
-
+
errors = []
# Now import all the files from the archive
@@ -79,31 +79,31 @@ class Importer:
errors.append(os.path.basename(f))
else:
sys.stderr.write('Skipping %s, not a valid snippets file' % os.path.basename(f))
-
+
# Remove the temporary directory
shutil.rmtree(dirname)
if len(errors) > 0:
return _('The following files could not be imported: %s') % ', '.join(errors)
-
+
def import_targz(self):
self.import_archive('tar -x --gzip -f')
-
+
def import_tarbz2(self):
self.import_archive('tar -x --bzip2 -f')
def import_tar(self):
self.import_archive('tar -xf')
-
+
def run(self):
if not os.path.exists(self.filename):
return _('File "%s" does not exist') % self.filename
-
+
if not os.path.isfile(self.filename):
return _('File "%s" is not a valid snippets archive') % self.filename
-
+
(root, ext) = os.path.splitext(self.filename)
-
+
actions = {'.tar.gz': self.import_targz,
'.tar.bz2': self.import_tarbz2,
'.xml': self.import_xml,
@@ -112,6 +112,7 @@ class Importer:
for k, v in actions.items():
if self.filename.endswith(k):
return v()
-
+
return _('File "%s" is not a valid snippets archive') % self.filename
+
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/LanguageManager.py b/plugins/snippets/snippets/languagemanager.py
similarity index 89%
rename from plugins/snippets/snippets/LanguageManager.py
rename to plugins/snippets/snippets/languagemanager.py
index ffbe5b6..d70449b 100644
--- a/plugins/snippets/snippets/LanguageManager.py
+++ b/plugins/snippets/snippets/languagemanager.py
@@ -15,24 +15,26 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-import gtksourceview2 as gsv
+from gi.repository import GtkSource
import os
-from Library import Library
+from library import Library
global manager
manager = None
def get_language_manager():
global manager
-
+
if not manager:
dirs = []
-
+
for d in Library().systemdirs:
dirs.append(os.path.join(d, 'lang'))
-
- manager = gsv.LanguageManager()
+
+ manager = GtkSource.LanguageManager()
manager.set_search_path(dirs + manager.get_search_path())
-
+
return manager
+
+# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/Library.py b/plugins/snippets/snippets/library.py
similarity index 90%
rename from plugins/snippets/snippets/Library.py
rename to plugins/snippets/snippets/library.py
index a522ead..e477719 100644
--- a/plugins/snippets/snippets/Library.py
+++ b/plugins/snippets/snippets/library.py
@@ -21,10 +21,10 @@ import sys
import tempfile
import re
-import gtk
+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):
@@ -35,11 +35,11 @@ class NamespacedId:
self.id = namespace + '-'
else:
self.id = 'global-'
-
+
self.id += id
class SnippetData:
- PROPS = {'tag': '', 'text': '', 'description': 'New snippet',
+ PROPS = {'tag': '', 'text': '', 'description': 'New snippet',
'accelerator': '', 'drop-targets': ''}
def __init__(self, node, library):
@@ -65,9 +65,9 @@ class SnippetData:
self.node = node
else:
self.node = None
-
+
self.init_snippet_data(node)
-
+
def init_snippet_data(self, node):
if node == None:
return
@@ -84,10 +84,10 @@ class SnippetData:
# Normalize accelerator
if child.tag == 'accelerator' and child.text != None:
- keyval, mod = gtk.accelerator_parse(child.text)
+ keyval, mod = Gtk.accelerator_parse(child.text)
- if gtk.accelerator_valid(keyval, mod):
- child.text = gtk.accelerator_name(keyval, mod)
+ if Gtk.accelerator_valid(keyval, mod):
+ child.text = Gtk.accelerator_name(keyval, mod)
else:
child.text = ''
@@ -95,7 +95,7 @@ class SnippetData:
self.properties[child.tag] = child
else:
self.properties[child.tag] = child.text or ''
-
+
# Create all the props that were not found so we stay consistent
for prop in props:
if self.can_modify():
@@ -105,41 +105,41 @@ class SnippetData:
self.properties[prop] = child
else:
self.properties[prop] = props[prop]
-
+
self.check_validation()
-
+
def check_validation(self):
if not self['tag'] and not self['accelerator'] and not self['drop-targets']:
return False
library = Library()
- keyval, mod = gtk.accelerator_parse(self['accelerator'])
-
+ keyval, mod = Gtk.accelerator_parse(self['accelerator'])
+
self.valid = library.valid_tab_trigger(self['tag']) and \
(not self['accelerator'] or library.valid_accelerator(keyval, mod))
-
+
def _format_prop(self, prop, value):
if prop == 'drop-targets' and value != '':
return re.split('\\s*[,;]\\s*', value)
else:
return value
-
+
def __getitem__(self, prop):
if prop in self.properties:
if self.can_modify():
return self._format_prop(prop, self.properties[prop].text or '')
else:
return self._format_prop(prop, self.properties[prop] or '')
-
+
return self._format_prop(prop, '')
-
+
def __setitem__(self, prop, value):
if not prop in self.properties:
return
-
+
if isinstance(value, list):
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...
# make sure it is transfered to the changes file and set all the
@@ -155,11 +155,11 @@ class SnippetData:
oldvalue = self.properties[prop].text
self.properties[prop].text = value
-
+
if prop == 'tag' or prop == 'accelerator' or prop == 'drop-targets':
container = Library().container(self.language())
container.prop_changed(self, prop, oldvalue)
-
+
self.check_validation()
def language(self):
@@ -167,10 +167,10 @@ class SnippetData:
return self.library().language
else:
return None
-
+
def is_override(self):
return self.override and Library().overridden[self.override]
-
+
def to_xml(self):
return self._create_xml()
@@ -185,12 +185,12 @@ class SnippetData:
for p in self.properties:
prop = et.SubElement(element, p)
prop.text = self[p]
-
+
if update:
self.properties[p] = prop
-
- return element
-
+
+ return element
+
def _override(self):
# Find the user file
target = Library().get_user_library(self.language())
@@ -204,34 +204,34 @@ class SnippetData:
override = SnippetData(element, self.library())
override.set_node(None)
override.id = self.id
-
+
# Set our node to the new element
self.node = element
-
+
# Set the override to our id
self.override = self.id
self.id = None
-
+
# Set the new library
self.set_library(target)
-
+
# The library is tainted because we added this snippet
target.tainted = True
-
+
# Add the override
Library().overridden[self.override] = override
-
+
def revert(self, snippet):
userlib = self.library()
self.set_library(snippet.library())
-
+
userlib.remove(self.node)
-
+
self.set_node(None)
# Copy the properties
self.properties = snippet.properties
-
+
# Set the id
self.id = snippet.id
@@ -246,24 +246,24 @@ class SnippetsTreeBuilder(et.TreeBuilder):
def set_start(self, start):
self._start_cb = start
-
+
def set_end(self, end):
self._end_cb = end
def start(self, tag, attrs):
result = et.TreeBuilder.start(self, tag, attrs)
-
+
if self._start_cb:
self._start_cb(result)
-
+
return result
-
+
def end(self, tag):
result = et.TreeBuilder.end(self, tag)
-
+
if self._end_cb:
self._end_cb(result)
-
+
return result
class LanguageContainer:
@@ -271,28 +271,28 @@ class LanguageContainer:
self.language = language
self.snippets = []
self.snippets_by_prop = {'tag': {}, 'accelerator': {}, 'drop-targets': {}}
- self.accel_group = gtk.AccelGroup()
+ self.accel_group = Gtk.AccelGroup()
self._refs = 0
def _add_prop(self, snippet, prop, value=0):
if value == 0:
value = snippet[prop]
-
+
if not value or value == '':
return
snippets_debug('Added ', prop ,' ', value, ' to ', str(self.language))
-
+
if prop == 'accelerator':
- keyval, mod = gtk.accelerator_parse(value)
- self.accel_group.connect_group(keyval, mod, 0, \
+ keyval, mod = Gtk.accelerator_parse(value)
+ self.accel_group.connect(keyval, mod, 0, \
Library().accelerator_activated)
-
+
snippets = self.snippets_by_prop[prop]
-
+
if not isinstance(value, list):
value = [value]
-
+
for val in value:
if val in snippets:
snippets[val].append(snippet)
@@ -309,14 +309,14 @@ class LanguageContainer:
snippets_debug('Removed ', prop, ' ', value, ' from ', str(self.language))
if prop == 'accelerator':
- keyval, mod = gtk.accelerator_parse(value)
+ keyval, mod = Gtk.accelerator_parse(value)
self.accel_group.disconnect_key(keyval, mod)
snippets = self.snippets_by_prop[prop]
-
+
if not isinstance(value, list):
value = [value]
-
+
for val in value:
try:
snippets[val].remove(snippet)
@@ -326,64 +326,64 @@ class LanguageContainer:
def append(self, snippet):
tag = snippet['tag']
accelerator = snippet['accelerator']
-
+
self.snippets.append(snippet)
-
+
self._add_prop(snippet, 'tag')
self._add_prop(snippet, 'accelerator')
self._add_prop(snippet, 'drop-targets')
return snippet
-
+
def remove(self, snippet):
try:
self.snippets.remove(snippet)
except:
True
-
+
self._remove_prop(snippet, 'tag')
self._remove_prop(snippet, 'accelerator')
self._remove_prop(snippet, 'drop-targets')
-
+
def prop_changed(self, snippet, prop, oldvalue):
snippets_debug('PROP CHANGED (', prop, ')', oldvalue)
self._remove_prop(snippet, prop, oldvalue)
self._add_prop(snippet, prop)
-
+
def from_prop(self, prop, value):
snippets = self.snippets_by_prop[prop]
-
+
if prop == 'drop-targets':
s = []
-
- # FIXME: change this to use
+
+ # FIXME: change this to use
# gnomevfs.mime_type_get_equivalence when it comes
# available
for key, val in snippets.items():
if not value.startswith(key):
continue
-
+
for snippet in snippets[key]:
if not snippet in s:
s.append(snippet)
-
+
return s
else:
if value in snippets:
return snippets[value]
else:
return []
-
+
def ref(self):
self._refs += 1
-
+
return True
def unref(self):
if self._refs > 0:
self._refs -= 1
-
+
return self._refs != 0
class SnippetsSystemFile:
@@ -393,7 +393,7 @@ class SnippetsSystemFile:
self.language = None
self.ok = True
self.need_id = True
-
+
def load_error(self, message):
sys.stderr.write("An error occurred loading " + self.path + ":\n")
sys.stderr.write(message + "\nSnippets in this file will not be " \
@@ -405,13 +405,13 @@ class SnippetsSystemFile:
def set_language(self, element):
self.language = element.attrib.get('language')
-
+
if self.language:
self.language = self.language.lower()
-
+
def _set_root(self, element):
self.set_language(element)
-
+
def _preprocess_element(self, element):
if not self.loaded:
if not element.tag == "snippets":
@@ -433,20 +433,20 @@ class SnippetsSystemFile:
def _process_element(self, element):
if element.tag == 'snippet':
self._add_snippet(element)
- self.insnippet = False
+ self.insnippet = False
return True
def ensure(self):
if not self.ok or self.loaded:
return
-
+
self.load()
def parse_xml(self, readsize=16384):
if not self.path:
return
-
+
elements = []
builder = SnippetsTreeBuilder( \
@@ -455,23 +455,23 @@ class SnippetsSystemFile:
parser = et.XMLTreeBuilder(target=builder)
self.insnippet = False
-
+
try:
f = open(self.path, "r")
-
+
while True:
data = f.read(readsize)
-
+
if not data:
break
-
+
parser.feed(data)
-
+
for element in elements:
yield element
-
+
del elements[:]
-
+
f.close()
except IOError:
self.ok = False
@@ -482,11 +482,11 @@ class SnippetsSystemFile:
snippets_debug("Loading library (" + str(self.language) + "): " + \
self.path)
-
+
self.loaded = False
self.ok = False
self.loading_elements = []
-
+
for element in self.parse_xml():
if element[1]:
if not self._preprocess_element(element[0]):
@@ -499,7 +499,7 @@ class SnippetsSystemFile:
for element in self.loading_elements:
snippet = Library().add_snippet(self, element)
-
+
del self.loading_elements[:]
self.ok = True
@@ -510,7 +510,7 @@ class SnippetsSystemFile:
def ensure_language(self):
if not self.loaded:
self.ok = False
-
+
for element in self.parse_xml(256):
if element[1]:
if element[0].tag == 'snippets':
@@ -518,7 +518,7 @@ class SnippetsSystemFile:
self.ok = True
break
-
+
def unload(self):
snippets_debug("Unloading library (" + str(self.language) + "): " + \
self.path)
@@ -531,16 +531,16 @@ class SnippetsUserFile(SnippetsSystemFile):
SnippetsSystemFile.__init__(self, path)
self.tainted = False
self.need_id = False
-
+
def _set_root(self, element):
SnippetsSystemFile._set_root(self, element)
self.root = element
-
+
def add_prop(self, node, tag, data):
if data[tag]:
prop = et.SubElement(node, tag)
prop.text = data[tag]
-
+
return prop
else:
return None
@@ -548,67 +548,67 @@ class SnippetsUserFile(SnippetsSystemFile):
def new_snippet(self, properties=None):
if (not self.ok) or self.root == None:
return None
-
+
element = et.SubElement(self.root, 'snippet')
-
+
if properties:
for prop in properties:
sub = et.SubElement(element, prop)
sub.text = properties[prop]
-
+
self.tainted = True
-
+
return Library().add_snippet(self, element)
-
+
def set_language(self, element):
SnippetsSystemFile.set_language(self, element)
-
+
filename = os.path.basename(self.path).lower()
-
+
if not self.language and filename == "global.xml":
self.modifier = True
elif self.language and filename == self.language + ".xml":
self.modifier = True
else:
self.modifier = False
-
+
def create_root(self, language):
if self.loaded:
snippets_debug('Not creating root, already loaded')
return
-
+
if language:
root = et.Element('snippets', {'language': language})
self.path = os.path.join(Library().userdir, language.lower() + '.xml')
else:
root = et.Element('snippets')
self.path = os.path.join(Library().userdir, 'global.xml')
-
+
self._set_root(root)
self.loaded = True
self.ok = True
self.tainted = True
self.save()
-
+
def remove(self, element):
try:
self.root.remove(element)
self.tainted = True
except:
return
-
+
try:
first = self.root[0]
except:
# No more elements, this library is useless now
Library().remove_library(self)
-
+
def save(self):
if not self.ok or self.root == None or not self.tainted:
return
path = os.path.dirname(self.path)
-
+
try:
if not os.path.isdir(path):
os.makedirs(path, 0755)
@@ -623,7 +623,7 @@ class SnippetsUserFile(SnippetsSystemFile):
# Couldn't save, what to do
sys.stderr.write("Could not save user snippets file to " + \
self.path + "\n")
-
+
def unload(self):
SnippetsSystemFile.unload(self)
self.root = None
@@ -639,26 +639,26 @@ class Singleton(object):
return cls._instance
-class Library(Singleton):
+class Library(Singleton):
def __init_once__(self):
self._accelerator_activated_cb = None
self.loaded = False
- self.check_buffer = gtk.TextBuffer()
+ self.check_buffer = Gtk.TextBuffer()
def set_dirs(self, userdir, systemdirs):
self.userdir = userdir
self.systemdirs = systemdirs
-
+
self.libraries = {}
self.containers = {}
self.overridden = {}
self.loaded_ids = []
self.loaded = False
-
+
def set_accelerator_callback(self, cb):
self._accelerator_activated_cb = cb
-
+
def accelerator_activated(self, group, obj, keyval, mod):
ret = False
@@ -670,14 +670,14 @@ class Library(Singleton):
def add_snippet(self, library, element):
container = self.container(library.language)
overrided = self.overrided(library, element)
-
+
if overrided:
overrided.set_library(library)
snippets_debug('Snippet is overriden: ' + overrided['description'])
return None
-
+
snippet = SnippetData(element, library)
-
+
if snippet.id in self.loaded_ids:
snippets_debug('Not added snippet ' + str(library.language) + \
'::' + snippet['description'] + ' (duplicate)')
@@ -686,33 +686,33 @@ class Library(Singleton):
snippet = container.append(snippet)
snippets_debug('Added snippet ' + str(library.language) + '::' + \
snippet['description'])
-
+
if snippet and snippet.override:
self.add_override(snippet)
-
+
if snippet.id:
self.loaded_ids.append(snippet.id)
return snippet
-
+
def container(self, language):
language = self.normalize_language(language)
-
+
if not language in self.containers:
self.containers[language] = LanguageContainer(language)
-
+
return self.containers[language]
-
+
def get_user_library(self, language):
target = None
-
+
if language in self.libraries:
for library in self.libraries[language]:
if isinstance(library, SnippetsUserFile) and library.modifier:
target = library
elif not isinstance(library, SnippetsUserFile):
break
-
+
if not target:
# Create a new user file then
snippets_debug('Creating a new user file for language ' + \
@@ -720,68 +720,68 @@ class Library(Singleton):
target = SnippetsUserFile()
target.create_root(language)
self.add_library(target)
-
+
return target
-
+
def new_snippet(self, language, properties=None):
language = self.normalize_language(language)
library = self.get_user_library(language)
return library.new_snippet(properties)
-
+
def revert_snippet(self, snippet):
# This will revert the snippet to the one it overrides
if not snippet.can_modify() or not snippet.override in self.overridden:
# It can't be reverted, shouldn't happen, but oh..
return
-
+
# The snippet in self.overriden only contains the property contents and
# the library it belongs to
revertto = self.overridden[snippet.override]
del self.overridden[snippet.override]
-
+
if revertto:
snippet.revert(revertto)
-
+
if revertto.id:
self.loaded_ids.append(revertto.id)
-
+
def remove_snippet(self, snippet):
if not snippet.can_modify() or snippet.is_override():
return
-
+
# Remove from the library
userlib = snippet.library()
userlib.remove(snippet.node)
-
+
# Remove from the container
container = self.containers[userlib.language]
container.remove(snippet)
-
+
def overrided(self, library, element):
id = NamespacedId(library.language, element.attrib.get('id')).id
-
+
if id in self.overridden:
snippet = SnippetData(element, None)
snippet.set_node(None)
-
+
self.overridden[id] = snippet
return snippet
else:
return None
-
+
def add_override(self, snippet):
snippets_debug('Add override:', snippet.override)
if not snippet.override in self.overridden:
self.overridden[snippet.override] = None
-
+
def add_library(self, library):
library.ensure_language()
-
+
if not library.ok:
snippets_debug('Library in wrong format, ignoring')
return False
-
+
snippets_debug('Adding library (' + str(library.language) + '): ' + \
library.path)
@@ -795,57 +795,57 @@ class Library(Singleton):
self.libraries[library.language] = [library]
return True
-
+
def remove_library(self, library):
if not library.ok:
return
-
+
if library.path and os.path.isfile(library.path):
os.unlink(library.path)
-
+
try:
self.libraries[library.language].remove(library)
except KeyError:
True
-
+
container = self.containers[library.language]
-
+
for snippet in list(container.snippets):
if snippet.library() == library:
container.remove(snippet)
-
+
def add_user_library(self, path):
library = SnippetsUserFile(path)
return self.add_library(library)
-
+
def add_system_library(self, path):
library = SnippetsSystemFile(path)
return self.add_library(library)
def find_libraries(self, path, searched, addcb):
snippets_debug("Finding in: " + path)
-
+
if not os.path.isdir(path):
return searched
files = os.listdir(path)
searched.append(path)
-
+
for f in files:
f = os.path.realpath(os.path.join(path, f))
# Determine what language this file provides snippets for
if os.path.isfile(f):
addcb(f)
-
+
return searched
-
+
def normalize_language(self, language):
if language:
return language.lower()
-
+
return language
-
+
def remove_container(self, language):
for snippet in self.containers[language].snippets:
if snippet.id in self.loaded_ids:
@@ -855,42 +855,42 @@ class Library(Singleton):
del self.overridden[snippet.override]
del self.containers[language]
-
+
def get_accel_group(self, language):
language = self.normalize_language(language)
container = self.container(language)
self.ensure(language)
return container.accel_group
-
+
def save(self, language):
language = self.normalize_language(language)
-
+
if language in self.libraries:
for library in self.libraries[language]:
if isinstance(library, SnippetsUserFile):
library.save()
else:
break
-
+
def ref(self, language):
language = self.normalize_language(language)
snippets_debug('Ref:', language)
self.container(language).ref()
-
+
def unref(self, language):
language = self.normalize_language(language)
-
+
snippets_debug('Unref:', language)
-
+
if language in self.containers:
if not self.containers[language].unref() and \
language in self.libraries:
for library in self.libraries[language]:
library.unload()
-
+
self.remove_container(language)
def ensure(self, language):
@@ -913,7 +913,7 @@ class Library(Singleton):
searched = []
searched = self.find_libraries(self.userdir, searched, \
self.add_user_library)
-
+
for d in self.systemdirs:
searched = self.find_libraries(d, searched, \
self.add_system_library)
@@ -921,11 +921,11 @@ class Library(Singleton):
self.loaded = True
def valid_accelerator(self, keyval, mod):
- mod &= gtk.accelerator_get_default_mod_mask()
-
- return (mod and (gdk.keyval_to_unicode(keyval) or \
- keyval in range(gtk.keysyms.F1, gtk.keysyms.F12 + 1)))
-
+ mod &= Gtk.accelerator_get_default_mod_mask()
+
+ return (mod and (Gdk.keyval_to_unicode(keyval) or \
+ keyval in range(Gdk.KEY_F1, Gdk.KEY_F12 + 1)))
+
def valid_tab_trigger(self, trigger):
if not trigger:
return True
@@ -936,46 +936,46 @@ class Library(Singleton):
self.check_buffer.set_text(trigger)
start, end = self.check_buffer.get_bounds()
- text = self.check_buffer.get_text(start, end)
-
+ text = self.check_buffer.get_text(start, end, False)
+
s = start.copy()
e = end.copy()
-
+
end.backward_word_start()
start.forward_word_end()
-
+
return (s.equal(end) and e.equal(start)) or (len(text) == 1 and not (text.isalnum() or text.isspace()))
# Snippet getters
# ===============
def _from_prop(self, prop, value, language=None):
self.ensure_files()
-
- result = []
+
+ result = []
language = self.normalize_language(language)
-
+
if not language in self.containers:
return []
self.ensure(language)
result = self.containers[language].from_prop(prop, value)
-
+
if len(result) == 0 and language and None in self.containers:
result = self.containers[None].from_prop(prop, value)
-
+
return result
-
+
# Get snippets for a given language
def get_snippets(self, language=None):
self.ensure_files()
language = self.normalize_language(language)
-
+
if not language in self.libraries:
return []
-
+
snippets = []
self.ensure(language)
-
+
return list(self.containers[language].snippets)
# Get snippets for a given accelerator
@@ -985,9 +985,9 @@ class Library(Singleton):
# Get snippets for a given tag
def from_tag(self, tag, language=None):
return self._from_prop('tag', tag, language)
-
+
# Get snippets for a given drop target
def from_drop_target(self, drop_target, language=None):
return self._from_prop('drop-targets', drop_target, language)
-
+
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/Manager.py b/plugins/snippets/snippets/manager.py
similarity index 75%
rename from plugins/snippets/snippets/Manager.py
rename to plugins/snippets/snippets/manager.py
index 2015152..f24f6d8 100644
--- a/plugins/snippets/snippets/Manager.py
+++ b/plugins/snippets/snippets/manager.py
@@ -19,49 +19,43 @@ import os
import tempfile
import shutil
-import gobject
-import gtk
-from gtk import gdk
-import gtksourceview2 as gsv
-import pango
-import gedit
-import gio
-
-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:
+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
+
+class Manager(Gtk.VBox, Gtk.Buildable):
NAME_COLUMN = 0
SORT_COLUMN = 1
- OBJ_COLUMN = 2
+ LANG_COLUMN = 2
+ SNIPPET_COLUMN = 3
TARGET_URI = 105
+ __gtype_name__ = "GeditSnippetsManager"
+
model = None
drag_icons = ('gnome-mime-application-x-tarz', 'gnome-package', 'package')
default_export_name = _('Snippets archive') + '.tar.gz'
dragging = False
- dnd_target_list = [('text/uri-list', 0, TARGET_URI)]
+ dnd_target_list = [Gtk.TargetEntry.new('text/uri-list', 0, TARGET_URI)]
- def __init__(self, datadir):
- self.datadir = datadir
+ def __init__(self):
self.snippet = None
- self.dlg = None
self._temp_export = None
self.snippets_doc = None
self.manager = None
self.default_size = None
self.key_press_id = 0
- self.run()
-
+
def get_language_snippets(self, path, name = None):
library = Library()
-
+
name = self.get_language(path)
nodes = library.get_snippets(name)
@@ -69,21 +63,21 @@ class Manager:
def add_new_snippet_node(self, parent):
return self.model.append(parent, ('<i>' + _('Add a new snippet...') + \
- '</i>', '', None))
+ '</i>', '', None, None))
def fill_language(self, piter, expand=True):
# Remove all children
child = self.model.iter_children(piter)
-
+
while child and self.model.remove(child):
True
-
+
path = self.model.get_path(piter)
nodes = self.get_language_snippets(path)
language = self.get_language(path)
-
+
Library().ref(language)
-
+
if nodes:
for node in nodes:
self.add_snippet(piter, node)
@@ -95,8 +89,8 @@ class Manager:
self.tree_view.expand_row(path, False)
def build_model(self, force_reload = False):
- window = gedit.app_get_default().get_active_window()
-
+ window = Gedit.App.get_default().get_active_window()
+
if window:
view = window.get_active_view()
@@ -111,28 +105,32 @@ class Manager:
tree_view = self['tree_view_snippets']
expand = None
-
+
if not self.model or force_reload:
- self.model = gtk.TreeStore(str, str, object)
- self.model.set_sort_column_id(self.SORT_COLUMN, gtk.SORT_ASCENDING)
+ self.model = Gtk.TreeStore(str, str, GObject.Object, object)
+ self.model.set_sort_column_id(self.SORT_COLUMN, Gtk.SortType.ASCENDING)
+
manager = get_language_manager()
- langs = gedit.language_manager_list_languages_sorted(manager, True)
-
- piter = self.model.append(None, (_('Global'), '', None))
+
+ langs = [manager.get_language(x) for x in manager.get_language_ids()]
+ langs.sort(key=lambda x: x.get_name())
+
+ piter = self.model.append(None, (_('Global'), '', None, None))
+
# Add dummy node
- self.model.append(piter, ('', '', None))
-
+ self.model.append(piter, ('', '', None, None))
+
nm = None
-
+
if current_lang:
nm = current_lang.get_name()
-
+
for lang in langs:
name = lang.get_name()
- parent = self.model.append(None, (name, name, lang))
+ parent = self.model.append(None, (name, name, lang, None))
# Add dummy node
- self.model.append(parent, ('', '', None))
+ self.model.append(parent, ('', '', None, None))
if (nm == name):
expand = parent
@@ -140,52 +138,49 @@ class Manager:
if current_lang:
piter = self.model.get_iter_first()
nm = current_lang.get_name()
-
+
while piter:
lang = self.model.get_value(piter, \
self.SORT_COLUMN)
-
+
if lang == nm:
expand = piter
break;
-
+
piter = self.model.iter_next(piter)
tree_view.set_model(self.model)
-
+
if not expand:
- expand = self.model.get_iter_root()
-
+ expand = self.model.get_iter_first()
+
tree_view.expand_row(self.model.get_path(expand), False)
self.select_iter(expand)
- def get_cell_data_pixbuf_cb(self, column, cell, model, iter):
- s = model.get_value(iter, self.OBJ_COLUMN)
-
- snippet = isinstance(s, SnippetData)
-
- if snippet and not s.valid:
- cell.set_property('stock-id', gtk.STOCK_DIALOG_ERROR)
+ def get_cell_data_pixbuf_cb(self, column, cell, model, iter, data):
+ lang = model.get_value(iter, self.LANG_COLUMN)
+ snippet = model.get_value(iter, self.SNIPPET_COLUMN)
+
+ if snippet and not snippet.valid:
+ cell.set_property('stock-id', Gtk.STOCK_DIALOG_ERROR)
else:
cell.set_property('stock-id', None)
cell.set_property('xalign', 1.0)
-
- def get_cell_data_cb(self, column, cell, model, iter):
- s = model.get_value(iter, self.OBJ_COLUMN)
-
- snippet = isinstance(s, SnippetData)
-
- cell.set_property('editable', snippet)
+
+ def get_cell_data_cb(self, column, cell, model, iter, data):
+ snippet = model.get_value(iter, self.SNIPPET_COLUMN)
+
+ cell.set_property('editable', snippet != None)
cell.set_property('markup', model.get_value(iter, self.NAME_COLUMN))
def on_tree_view_drag_data_get(self, widget, context, selection_data, info, time):
- gfile = gio.File(self._temp_export)
+ gfile = Gio.File(self._temp_export)
selection_data.set_uris([gfile.get_uri()])
-
+
def on_tree_view_drag_begin(self, widget, context):
self.dragging = True
-
+
if self._temp_export:
shutil.rmtree(os.path.dirname(self._temp_export))
self._temp_export = None
@@ -195,101 +190,98 @@ class Manager:
dirname = tempfile.mkdtemp()
filename = os.path.join(dirname, self.default_export_name)
-
+
# Generate temporary file name
self.export_snippets(filename, False)
self._temp_export = filename
-
+
def on_tree_view_drag_end(self, widget, context):
self.dragging = False
def on_tree_view_drag_data_received(self, widget, context, x, y, selection, info, timestamp):
uris = selection.get_uris()
-
+
self.import_snippets(uris)
def on_tree_view_drag_motion(self, widget, context, x, y, timestamp):
# Return False if we are dragging
if self.dragging:
return False
-
+
# Check uri target
- if not gtk.targets_include_uri(context.targets):
+ if not Gtk.targets_include_uri(context.targets):
return False
# Check action
action = None
- if context.suggested_action == gdk.ACTION_COPY:
- action = gdk.ACTION_COPY
+ if context.suggested_action == Gdk.DragAction.COPY:
+ action = Gdk.DragAction.COPY
else:
for act in context.actions:
- if act == gdk.ACTION_COPY:
- action = gdk.ACTION_COPY
- break
-
- if action == gdk.ACTION_COPY:
- context.drag_status(gdk.ACTION_COPY, timestamp)
+ if act == Gdk.DragAction.COPY:
+ action = Gdk.DragAction.COPY
+ break
+
+ if action == Gdk.DragAction.COPY:
+ context.drag_status(Gdk.DragAction.COPY, timestamp)
return True
else:
return False
def build_dnd(self):
tv = self.tree_view
-
+
# Set it as a drag source for exporting snippets
- tv.drag_source_set(gdk.BUTTON1_MASK, self.dnd_target_list, gdk.ACTION_DEFAULT | gdk.ACTION_COPY)
-
+ Gtk.drag_source_set(tv, Gdk.ModifierType.BUTTON1_MASK, self.dnd_target_list, Gdk.DragAction.DEFAULT | Gdk.DragAction.COPY)
+
# Set it as a drag destination for importing snippets
- tv.drag_dest_set(gtk.DEST_DEFAULT_HIGHLIGHT | gtk.DEST_DEFAULT_DROP,
- self.dnd_target_list, gdk.ACTION_DEFAULT | gdk.ACTION_COPY)
-
+ Gtk.drag_dest_set(tv, Gtk.DestDefaults.HIGHLIGHT | Gtk.DestDefaults.DROP,
+ self.dnd_target_list, Gdk.DragAction.DEFAULT | Gdk.DragAction.COPY)
+
tv.connect('drag_data_get', self.on_tree_view_drag_data_get)
tv.connect('drag_begin', self.on_tree_view_drag_begin)
tv.connect('drag_end', self.on_tree_view_drag_end)
tv.connect('drag_data_received', self.on_tree_view_drag_data_received)
tv.connect('drag_motion', self.on_tree_view_drag_motion)
- theme = gtk.icon_theme_get_for_screen(tv.get_screen())
-
+ theme = Gtk.IconTheme.get_for_screen(tv.get_screen())
+
self.dnd_name = None
for name in self.drag_icons:
- icon = theme.lookup_icon(name, gtk.ICON_SIZE_DND, 0)
-
+ icon = theme.lookup_icon(name, Gtk.IconSize.DND, 0)
+
if icon:
self.dnd_name = name
break
-
- def build_tree_view(self):
+
+ def build_tree_view(self):
self.tree_view = self['tree_view_snippets']
-
- self.column = gtk.TreeViewColumn(None)
- self.renderer = gtk.CellRendererText()
+ self.column = Gtk.TreeViewColumn(None)
+
+ self.renderer = Gtk.CellRendererText()
self.column.pack_start(self.renderer, False)
- self.column.set_cell_data_func(self.renderer, self.get_cell_data_cb)
+ self.column.set_cell_data_func(self.renderer, self.get_cell_data_cb, None)
- renderer = gtk.CellRendererPixbuf()
+ renderer = Gtk.CellRendererPixbuf()
self.column.pack_start(renderer, True)
- self.column.set_cell_data_func(renderer, self.get_cell_data_pixbuf_cb)
+ self.column.set_cell_data_func(renderer, self.get_cell_data_pixbuf_cb, None)
self.tree_view.append_column(self.column)
-
+
self.renderer.connect('edited', self.on_cell_edited)
self.renderer.connect('editing-started', self.on_cell_editing_started)
selection = self.tree_view.get_selection()
- selection.set_mode(gtk.SELECTION_MULTIPLE)
+ selection.set_mode(Gtk.SelectionMode.MULTIPLE)
selection.connect('changed', self.on_tree_view_selection_changed)
-
+
self.build_dnd()
-
- def build(self):
- self.builder = gtk.Builder()
- self.builder.add_from_file(os.path.join(self.datadir, 'ui', 'snippets.ui'))
-
+
+ def do_parser_finished(self, builder):
+ self.builder = builder
+
handlers_dic = {
- 'on_dialog_snippets_response': self.on_dialog_snippets_response,
- 'on_dialog_snippets_destroy': self.on_dialog_snippets_destroy,
'on_button_new_snippet_clicked': self.on_button_new_snippet_clicked,
'on_button_import_snippets_clicked': self.on_button_import_snippets_clicked,
'on_button_export_snippets_clicked': self.on_button_export_snippets_clicked,
@@ -304,12 +296,12 @@ class Manager:
'on_tree_view_snippets_key_press': self.on_tree_view_snippets_key_press}
self.builder.connect_signals(handlers_dic)
-
+
self.build_tree_view()
self.build_model()
image = self['image_remove']
- image.set_from_stock(gtk.STOCK_REMOVE, gtk.ICON_SIZE_SMALL_TOOLBAR)
+ image.set_from_stock(Gtk.STOCK_REMOVE, Gtk.IconSize.SMALL_TOOLBAR)
source_view = self['source_view_snippet']
manager = get_language_manager()
@@ -321,33 +313,27 @@ class Manager:
self.snippets_doc = Document(None, source_view)
combo = self['combo_drop_targets']
- combo.set_text_column(0)
- entry = combo.child
+ entry = combo.get_child()
entry.connect('focus-out-event', self.on_entry_drop_targets_focus_out)
entry.connect('drag-data-received', self.on_entry_drop_targets_drag_data_received)
-
- lst = entry.drag_dest_get_target_list()
- lst = gtk.target_list_add_uri_targets(entry.drag_dest_get_target_list(), self.TARGET_URI)
- entry.drag_dest_set_target_list(lst)
-
- self.dlg = self['dialog_snippets']
-
- if self.default_size:
- self.dlg.set_default_size(*self.default_size)
-
+
+ lst = Gtk.drag_dest_get_target_list(entry)
+ lst.add_uri_targets(self.TARGET_URI)
+
def __getitem__(self, key):
return self.builder.get_object(key)
def is_filled(self, piter):
if not self.model.iter_has_child(piter):
return True
-
+
child = self.model.iter_children(piter)
nm = self.model.get_value(child, self.NAME_COLUMN)
- obj = self.model.get_value(child, self.OBJ_COLUMN)
-
- return (obj or nm)
+ lang = self.model.get_value(child, self.LANG_COLUMN)
+ snippet = self.model.get_value(child, self.SNIPPET_COLUMN)
+
+ return (lang or snippet or nm)
def fill_if_needed(self, piter, expand=True):
if not self.is_filled(piter):
@@ -356,15 +342,15 @@ class Manager:
def find_iter(self, parent, snippet):
self.fill_if_needed(parent)
piter = self.model.iter_children(parent)
-
+
while (piter):
- node = self.model.get_value(piter, self.OBJ_COLUMN)
+ sn = self.model.get_value(piter, self.SNIPPET_COLUMN)
- if node == snippet.data:
+ if sn == snippet.data:
return piter
-
+
piter = self.model.iter_next(piter)
-
+
return None
def selected_snippets_state(self):
@@ -372,7 +358,7 @@ class Manager:
override = False
remove = False
system = False
-
+
for snippet in snippets:
if not snippet:
continue
@@ -383,7 +369,7 @@ class Manager:
remove = True
else:
system = True
-
+
# No need to continue if both are found
if override and remove:
break
@@ -397,25 +383,25 @@ class Manager:
button_new.set_sensitive(self.language_path != None)
override, remove, system = self.selected_snippets_state()
-
+
if not (override ^ remove) or system:
button_remove.set_sensitive(False)
- image_remove.set_from_stock(gtk.STOCK_DELETE, gtk.ICON_SIZE_BUTTON)
+ image_remove.set_from_stock(Gtk.STOCK_DELETE, Gtk.IconSize.BUTTON)
else:
button_remove.set_sensitive(True)
-
+
if override:
- image_remove.set_from_stock(gtk.STOCK_UNDO, gtk.ICON_SIZE_BUTTON)
+ image_remove.set_from_stock(Gtk.STOCK_UNDO, Gtk.IconSize.BUTTON)
tooltip = _('Revert selected snippet')
else:
- image_remove.set_from_stock(gtk.STOCK_DELETE, gtk.ICON_SIZE_BUTTON)
+ image_remove.set_from_stock(Gtk.STOCK_DELETE, Gtk.IconSize.BUTTON)
tooltip = _('Delete selected snippet')
-
+
button_remove.set_tooltip_text(tooltip)
def snippet_changed(self, piter = None):
if piter:
- node = self.model.get_value(piter, self.OBJ_COLUMN)
+ node = self.model.get_value(piter, self.SNIPPET_COLUMN)
s = Snippet(node)
else:
s = self.snippet
@@ -423,46 +409,38 @@ class Manager:
if piter:
nm = s.display()
-
- self.model.set(piter, self.NAME_COLUMN, nm, self.SORT_COLUMN, nm)
+
+ self.model.set_value(piter, self.NAME_COLUMN, nm)
+ self.model.set_value(piter, self.SORT_COLUMN, nm)
self.update_buttons()
self.entry_tab_trigger_update_valid()
return piter
def add_snippet(self, parent, snippet):
- piter = self.model.append(parent, ('', '', snippet))
-
- return self.snippet_changed(piter)
+ piter = self.model.append(parent, ('', '', None, snippet))
- def run(self):
- if not self.dlg:
- self.build()
- self.dlg.show()
- else:
- self.build_model()
- self.dlg.present()
+ return self.snippet_changed(piter)
-
def snippet_from_iter(self, model, piter):
parent = model.iter_parent(piter)
-
+
if parent:
- return model.get_value(piter, self.OBJ_COLUMN)
+ return model.get_value(piter, self.SNIPPET_COLUMN)
else:
return None
-
+
def language_snippets(self, model, parent, as_path=False):
self.fill_if_needed(parent, False)
piter = model.iter_children(parent)
snippets = []
-
+
if not piter:
return snippets
-
+
while piter:
snippet = self.snippet_from_iter(model, piter)
-
+
if snippet:
if as_path:
snippets.append(model.get_path(piter))
@@ -470,46 +448,46 @@ class Manager:
snippets.append(snippet)
piter = model.iter_next(piter)
-
+
return snippets
-
+
def selected_snippets(self, include_languages=True, as_path=False):
selection = self.tree_view.get_selection()
(model, paths) = selection.get_selected_rows()
snippets = []
-
+
if paths and len(paths) != 0:
for p in paths:
piter = model.get_iter(p)
parent = model.iter_parent(piter)
-
+
if not piter:
continue
-
+
if parent:
snippet = self.snippet_from_iter(model, piter)
-
+
if not snippet:
continue
-
+
if as_path:
snippets.append(p)
else:
snippets.append(snippet)
elif include_languages:
snippets += self.language_snippets(model, piter, as_path)
-
- return snippets
-
+
+ return snippets
+
def selected_snippet(self):
selection = self.tree_view.get_selection()
(model, paths) = selection.get_selected_rows()
-
+
if len(paths) == 1:
piter = model.get_iter(paths[0])
parent = model.iter_parent(piter)
snippet = self.snippet_from_iter(model, piter)
-
+
return parent, piter, snippet
else:
return None, None, None
@@ -524,7 +502,7 @@ class Manager:
buf.begin_not_undoable_action()
buf.set_text('')
buf.end_not_undoable_action()
- self['combo_drop_targets'].child.set_text('')
+ self['combo_drop_targets'].get_child().set_text('')
else:
sens = True
@@ -532,8 +510,8 @@ class Manager:
self['entry_tab_trigger'].set_text(self.snippet['tag'])
self['entry_accelerator'].set_text( \
self.snippet.accelerator_display())
- self['combo_drop_targets'].child.set_text(', '.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()
buf.set_text(self.snippet['text'])
@@ -541,21 +519,21 @@ class Manager:
for name in ['source_view_snippet', 'label_tab_trigger',
- 'entry_tab_trigger', 'label_accelerator',
+ 'entry_tab_trigger', 'label_accelerator',
'entry_accelerator', 'label_drop_targets',
'combo_drop_targets']:
self[name].set_sensitive(sens)
-
+
self.update_buttons()
-
+
def select_iter(self, piter, unselect=True):
selection = self.tree_view.get_selection()
-
+
if unselect:
selection.unselect_all()
selection.select_iter(piter)
-
+
self.tree_view.scroll_to_cell(self.model.get_path(piter), None, \
True, 0.5, 0.5)
@@ -564,42 +542,42 @@ class Manager:
return None
else:
return self.model.get_value(self.model.get_iter( \
- (path[0],)), self.OBJ_COLUMN).get_id()
+ (path[0],)), self.LANG_COLUMN).get_id()
def new_snippet(self, properties=None):
if not self.language_path:
return None
snippet = Library().new_snippet(self.get_language(self.language_path), properties)
-
+
return Snippet(snippet)
def get_dummy(self, parent):
if not self.model.iter_n_children(parent) == 1:
return None
-
+
dummy = self.model.iter_children(parent)
-
- if not self.model.get_value(dummy, self.OBJ_COLUMN):
+
+ if not self.model.get_value(dummy, self.SNIPPET_COLUMN):
return dummy
-
+
return None
-
+
def unref_languages(self):
piter = self.model.get_iter_first()
library = Library()
-
+
while piter:
if self.is_filled(piter):
language = self.get_language(self.model.get_path(piter))
library.save(language)
library.unref(language)
-
+
piter = self.model.iter_next(piter)
# Callbacks
- def on_dialog_snippets_destroy(self, dlg):
+ def do_destroy(self):
# Remove temporary drag export
if self._temp_export:
shutil.rmtree(os.path.dirname(self._temp_export))
@@ -607,48 +585,38 @@ class Manager:
if self.snippets_doc:
self.snippets_doc.stop()
-
- self.default_size = [dlg.allocation.width, dlg.allocation.height]
- self.manager = None
- self.unref_languages()
- self.snippet = None
+ self.manager = None
+ self.unref_languages()
+ self.snippet = None
self.model = None
- self.dlg = None
-
- def on_dialog_snippets_response(self, dlg, resp):
- if resp == gtk.RESPONSE_HELP:
- gedit.app_get_default().show_help(self.dlg, 'gedit', 'gedit-snippets-plugin')
- return
- self.dlg.destroy()
-
def on_cell_editing_started(self, renderer, editable, path):
piter = self.model.get_iter(path)
-
+
if not self.model.iter_parent(piter):
renderer.stop_editing(True)
editable.remove_widget()
- elif isinstance(editable, gtk.Entry):
+ elif isinstance(editable, Gtk.Entry):
if self.snippet:
editable.set_text(self.snippet['description'])
else:
# This is the `Add a new snippet...` item
editable.set_text('')
-
+
editable.grab_focus()
-
- def on_cell_edited(self, cell, path, new_text):
+
+ def on_cell_edited(self, cell, path, new_text):
if new_text != '':
piter = self.model.get_iter(path)
- node = self.model.get_value(piter, self.OBJ_COLUMN)
-
+ node = self.model.get_value(piter, self.SNIPPET_COLUMN)
+
if node:
if node == self.snippet.data:
s = self.snippet
else:
s = Snippet(node)
-
+
s['description'] = new_text
self.snippet_changed(piter)
self.select_iter(piter)
@@ -656,13 +624,13 @@ class Manager:
# This is the `Add a new snippet...` item
# We create a new snippet
snippet = self.new_snippet({'description': new_text})
-
+
if snippet:
- self.model.set(piter, self.OBJ_COLUMN, snippet.data)
+ self.model.set_value(piter, self.SNIPPET_COLUMN, snippet.data)
self.snippet_changed(piter)
self.snippet = snippet
self.selection_changed()
-
+
def on_entry_accelerator_focus_out(self, entry, event):
if not self.snippet:
return
@@ -672,22 +640,22 @@ class Manager:
def entry_tab_trigger_update_valid(self):
entry = self['entry_tab_trigger']
text = entry.get_text()
-
+
if text and not Library().valid_tab_trigger(text):
img = self['image_tab_trigger']
- img.set_from_stock(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_BUTTON)
+ img.set_from_stock(Gtk.STOCK_DIALOG_ERROR, Gtk.IconSize.BUTTON)
img.show()
#self['hbox_tab_trigger'].set_spacing(3)
tip = _('This is not a valid Tab trigger. Triggers can either contain letters or a single (non-alphanumeric) character like: {, [, etc.')
-
+
entry.set_tooltip_text(tip)
img.set_tooltip_text(tip)
else:
self['image_tab_trigger'].hide()
#self['hbox_tab_trigger'].set_spacing(0)
entry.set_tooltip_text(_('Single word the snippet is activated with after pressing Tab'))
-
+
return False
def on_entry_tab_trigger_focus_out(self, entry, event):
@@ -699,46 +667,46 @@ class Manager:
# save tag
self.snippet['tag'] = text
self.snippet_changed()
-
+
def on_entry_drop_targets_focus_out(self, entry, event):
if not self.snippet:
return
-
+
text = entry.get_text()
# save drop targets
self.snippet['drop-targets'] = text
self.snippet_changed()
-
+
def on_entry_tab_trigger_changed(self, entry):
self.entry_tab_trigger_update_valid()
-
+
def on_source_view_snippet_focus_out(self, source_view, event):
if not self.snippet:
return
buf = source_view.get_buffer()
text = buf.get_text(buf.get_start_iter(), \
- buf.get_end_iter())
+ buf.get_end_iter(), False)
self.snippet['text'] = text
self.snippet_changed()
-
+
def on_button_new_snippet_clicked(self, button):
snippet = self.new_snippet()
-
+
if not snippet:
return
parent = self.model.get_iter(self.language_path)
path = self.model.get_path(parent)
-
+
dummy = self.get_dummy(parent)
-
+
if dummy:
# Remove the dummy
self.model.remove(dummy)
-
+
# Add the snippet
piter = self.add_snippet(parent, snippet.data)
self.select_iter(piter)
@@ -751,23 +719,23 @@ class Manager:
path = self.model.get_path(piter)
self.tree_view.set_cursor(path, self.column, True)
-
+
def file_filter(self, name, pattern):
- fil = gtk.FileFilter()
+ fil = Gtk.FileFilter()
fil.set_name(name)
-
+
for p in pattern:
fil.add_pattern(p)
-
+
return fil
-
+
def import_snippets(self, filenames):
success = True
-
+
for filename in filenames:
- gfile = gio.File(filename)
+ gfile = Gio.File(filename)
- if not gedit.utils.location_has_file_scheme(gfile):
+ if not Gedit.utils_location_has_file_scheme(gfile):
continue
# Remove file://
@@ -775,34 +743,34 @@ class Manager:
importer = Importer(filename)
error = importer.run()
-
+
if error:
message = _('The following error occurred while importing: %s') % error
success = False
- message_dialog(self.dlg, gtk.MESSAGE_ERROR, message)
-
+ message_dialog(self.get_toplevel(), Gtk.MessageType.ERROR, message)
+
self.build_model(True)
if success:
message = _('Import successfully completed')
- message_dialog(self.dlg, gtk.MESSAGE_INFO, message)
-
+ message_dialog(self.get_toplevel(), Gtk.MessageType.INFO, message)
+
def on_import_response(self, dialog, response):
- if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_CLOSE:
+ if response == Gtk.ResponseType.CANCEL or response == Gtk.ResponseType.CLOSE:
dialog.destroy()
return
-
+
f = dialog.get_uris()
dialog.destroy()
-
+
self.import_snippets(f)
-
+
def on_button_import_snippets_clicked(self, button):
- dlg = gtk.FileChooserDialog(parent=self.dlg, title=_("Import snippets"),
- action=gtk.FILE_CHOOSER_ACTION_OPEN,
- buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_OPEN, gtk.RESPONSE_OK))
-
+ dlg = Gtk.FileChooserDialog(parent=self.get_toplevel(), title=_("Import snippets"),
+ action=Gtk.FileChooserAction.OPEN,
+ buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
+ Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
+
dlg.add_filter(self.file_filter(_('All supported archives'), ('*.gz','*.bz2','*.tar', '*.xml')))
dlg.add_filter(self.file_filter(_('Gzip compressed archive'), ('*.tar.gz',)))
dlg.add_filter(self.file_filter(_('Bzip2 compressed archive'), ('*.tar.bz2',)))
@@ -811,44 +779,44 @@ class Manager:
dlg.connect('response', self.on_import_response)
dlg.set_local_only(True)
-
+
dlg.show()
def export_snippets_real(self, filename, snippets, show_dialogs=True):
export = Exporter(filename, snippets)
error = export.run()
-
+
if error:
message = _('The following error occurred while exporting: %s') % error
- msgtype = gtk.MESSAGE_ERROR
+ msgtype = Gtk.MessageType.ERROR
retval = False
else:
message = _('Export successfully completed')
- msgtype = gtk.MESSAGE_INFO
+ msgtype = Gtk.MessageType.INFO
retval = True
if show_dialogs:
- message_dialog(self.dlg, msgtype, message)
+ message_dialog(self.get_toplevel(), msgtype, message)
return retval
-
+
def on_export_response(self, dialog, response):
filename = dialog.get_filename()
snippets = dialog._export_snippets
-
+
dialog.destroy()
-
- if response != gtk.RESPONSE_OK:
+
+ if response != Gtk.ResponseType.OK:
return
-
+
self.export_snippets_real(filename, snippets);
-
+
def export_snippets(self, filename=None, show_dialogs=True):
snippets = self.selected_snippets()
-
+
if not snippets or len(snippets) == 0:
return False
-
+
usersnippets = []
systemsnippets = []
@@ -858,36 +826,36 @@ class Manager:
usersnippets.append(snippet)
else:
systemsnippets.append(snippet)
-
+
export_snippets = snippets
if len(systemsnippets) != 0 and show_dialogs:
# Ask if system snippets should also be exported
message = _('Do you want to include selected <b>system</b> snippets in your export?')
- mes = gtk.MessageDialog(flags=gtk.DIALOG_MODAL,
- type=gtk.MESSAGE_QUESTION,
- buttons=gtk.BUTTONS_YES_NO,
+ mes = Gtk.MessageDialog(flags=Gtk.DialogFlags.MODAL,
+ type=Gtk.MessageType.QUESTION,
+ buttons=Gtk.ButtonsType.YES_NO,
message_format=message)
mes.set_property('use-markup', True)
resp = mes.run()
mes.destroy()
-
- if resp == gtk.RESPONSE_NO:
+
+ if resp == Gtk.ResponseType.NO:
export_snippets = usersnippets
- elif resp != gtk.RESPONSE_YES:
+ elif resp != Gtk.ResponseType.YES:
return False
-
- if len(export_snippets) == 0 and show_dialogs:
+
+ if len(export_snippets) == 0 and show_dialogs:
message = _('There are no snippets selected to be exported')
- message_dialog(self.dlg, gtk.MESSAGE_INFORMATION, message)
+ message_dialog(self.get_toplevel(), Gtk.MessageType.INFORMATION, message)
return False
-
+
if not filename:
- dlg = gtk.FileChooserDialog(parent=self.dlg, title=_('Export snippets'),
- action=gtk.FILE_CHOOSER_ACTION_SAVE,
- buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_SAVE, gtk.RESPONSE_OK))
-
+ dlg = Gtk.FileChooserDialog(parent=self.get_toplevel(), title=_('Export snippets'),
+ action=Gtk.FileChooserAction.SAVE,
+ buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
+ Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
+
dlg._export_snippets = export_snippets
dlg.add_filter(self.file_filter(_('All supported archives'), ('*.gz','*.bz2','*.tar')))
dlg.add_filter(self.file_filter(_('Gzip compressed archive'), ('*.tar.gz',)))
@@ -896,21 +864,21 @@ class Manager:
dlg.add_filter(self.file_filter(_('All files'), '*'))
dlg.set_do_overwrite_confirmation(True)
dlg.set_current_name(self.default_export_name)
-
+
dlg.connect('response', self.on_export_response)
dlg.set_local_only(True)
-
+
dlg.show()
return True
else:
return self.export_snippets_real(filename, export_snippets, show_dialogs)
-
+
def on_button_export_snippets_clicked(self, button):
snippets = self.selected_snippets()
-
+
if not snippets or len(snippets) == 0:
return
-
+
usersnippets = []
systemsnippets = []
@@ -921,37 +889,37 @@ class Manager:
else:
systemsnippets.append(snippet)
- dlg = gtk.FileChooserDialog(parent=self.dlg, title=_('Export snippets'),
- action=gtk.FILE_CHOOSER_ACTION_SAVE,
- buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_SAVE, gtk.RESPONSE_OK))
-
+ dlg = Gtk.FileChooserDialog(parent=self.get_toplevel(), title=_('Export snippets'),
+ action=Gtk.FileChooserAction.SAVE,
+ buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
+ Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
+
dlg._export_snippets = snippets
if len(systemsnippets) != 0:
# Ask if system snippets should also be exported
message = _('Do you want to include selected <b>system</b> snippets in your export?')
- mes = gtk.MessageDialog(flags=gtk.DIALOG_MODAL,
- type=gtk.MESSAGE_QUESTION,
- buttons=gtk.BUTTONS_YES_NO,
+ mes = Gtk.MessageDialog(flags=Gtk.DialogFlags.MODAL,
+ type=Gtk.MessageType.QUESTION,
+ buttons=Gtk.ButtonsType.YES_NO,
message_format=message)
mes.set_property('use-markup', True)
resp = mes.run()
mes.destroy()
-
- if resp == gtk.RESPONSE_NO:
+
+ if resp == Gtk.ResponseType.NO:
dlg._export_snippets = usersnippets
- elif resp != gtk.RESPONSE_YES:
+ elif resp != Gtk.ResponseType.YES:
dlg.destroy()
return
-
+
if len(dlg._export_snippets) == 0:
dlg.destroy()
-
+
message = _('There are no snippets selected to be exported')
- message_dialog(self.dlg, gtk.MESSAGE_INFORMATION, message)
+ message_dialog(self.get_toplevel(), Gtk.MessageType.INFORMATION, message)
return
-
+
dlg.add_filter(self.file_filter(_('All supported archives'), ('*.gz','*.bz2','*.tar')))
dlg.add_filter(self.file_filter(_('Gzip compressed archive'), ('*.tar.gz',)))
dlg.add_filter(self.file_filter(_('Bzip2 compressed archive'), ('*.tar.bz2',)))
@@ -959,18 +927,18 @@ class Manager:
dlg.add_filter(self.file_filter(_('All files'), '*'))
dlg.set_do_overwrite_confirmation(True)
dlg.set_current_name(self.default_export_name)
-
+
dlg.connect('response', self.on_export_response)
dlg.set_local_only(True)
-
- dlg.show()
-
+
+ dlg.show()
+
def remove_snippet_revert(self, path, piter):
node = self.snippet_from_iter(self.model, piter)
Library().revert_snippet(node)
-
+
return piter
-
+
def remove_snippet_delete(self, path, piter):
node = self.snippet_from_iter(self.model, piter)
parent = self.model.iter_parent(piter)
@@ -985,36 +953,36 @@ class Manager:
dummy = self.add_new_snippet_node(parent)
self.tree_view.expand_row(self.model.get_path(parent), False)
return dummy
-
+
def on_button_remove_snippet_clicked(self, button):
override, remove, system = self.selected_snippets_state()
-
+
if not (override ^ remove) or system:
return
-
+
paths = self.selected_snippets(include_languages=False, as_path=True)
-
+
if override:
action = self.remove_snippet_revert
else:
action = self.remove_snippet_delete
-
+
# Remove selection
self.tree_view.get_selection().unselect_all()
-
+
# Create tree row references
references = []
for path in paths:
- references.append(gtk.TreeRowReference(self.model, path))
+ references.append(Gtk.TreeRowReference(self.model, path))
# Remove/revert snippets
select = None
for reference in references:
path = reference.get_path()
piter = self.model.get_iter(path)
-
+
res = action(path, piter)
-
+
if res:
select = res
@@ -1022,58 +990,58 @@ class Manager:
self.select_iter(select)
self.selection_changed()
-
+
def set_accelerator(self, keyval, mod):
- accelerator = gtk.accelerator_name(keyval, mod)
+ accelerator = Gtk.accelerator_name(keyval, mod)
self.snippet['accelerator'] = accelerator
return True
-
+
def on_entry_accelerator_key_press(self, entry, event):
source_view = self['source_view_snippet']
- if event.keyval == gdk.keyval_from_name('Escape'):
+ if event.keyval == Gdk.keyval_from_name('Escape'):
# Reset
entry.set_text(self.snippet.accelerator_display())
self.tree_view.grab_focus()
-
+
return True
- elif event.keyval == gdk.keyval_from_name('Delete') or \
- event.keyval == gdk.keyval_from_name('BackSpace'):
+ elif event.keyval == Gdk.keyval_from_name('Delete') or \
+ event.keyval == Gdk.keyval_from_name('BackSpace'):
# Remove the accelerator
entry.set_text('')
self.snippet['accelerator'] = ''
self.tree_view.grab_focus()
-
+
self.snippet_changed()
return True
- elif Library().valid_accelerator(event.keyval, event.state):
+ elif Library().valid_accelerator(event.keyval, event.get_state()[1]):
# New accelerator
self.set_accelerator(event.keyval, \
- event.state & gtk.accelerator_get_default_mod_mask())
+ event.get_state()[1] & Gtk.accelerator_get_default_mod_mask())
entry.set_text(self.snippet.accelerator_display())
self.snippet_changed()
self.tree_view.grab_focus()
else:
return True
-
+
def on_entry_accelerator_focus_in(self, entry, event):
if self.snippet['accelerator']:
entry.set_text(_('Type a new shortcut, or press Backspace to clear'))
else:
entry.set_text(_('Type a new shortcut'))
-
+
def update_language_path(self):
model, paths = self.tree_view.get_selection().get_selected_rows()
-
+
# Check if all have the same language parent
current_parent = None
for path in paths:
piter = model.get_iter(path)
parent = model.iter_parent(piter)
-
+
if parent:
path = model.get_path(parent)
@@ -1084,18 +1052,18 @@ class Manager:
current_parent = path
self.language_path = current_parent
-
+
def on_tree_view_selection_changed(self, selection):
parent, piter, node = self.selected_snippet()
-
+
if self.snippet:
self.on_entry_tab_trigger_focus_out(self['entry_tab_trigger'],
None)
- self.on_source_view_snippet_focus_out(self['source_view_snippet'],
+ self.on_source_view_snippet_focus_out(self['source_view_snippet'],
None)
- self.on_entry_drop_targets_focus_out(self['combo_drop_targets'].child,
+ self.on_entry_drop_targets_focus_out(self['combo_drop_targets'].get_child(),
None)
-
+
self.update_language_path()
if node:
@@ -1111,14 +1079,14 @@ class Manager:
tp = self.model.get_path(target)
ap = self.model.get_path(after)
-
+
if tp[0] > ap[0] or (tp[0] == ap[0] and (len(ap) == 1 or tp[1] > ap[1])):
return True
-
+
return False
-
+
def on_tree_view_snippets_key_press(self, treeview, event):
- if event.keyval == gdk.keyval_from_name('Delete'):
+ if event.keyval == Gdk.keyval_from_name('Delete'):
self.on_button_remove_snippet_clicked(None)
return True
@@ -1126,33 +1094,34 @@ class Manager:
# Check if it is already filled
self.fill_if_needed(piter)
self.select_iter(piter)
-
+
def on_entry_drop_targets_drag_data_received(self, entry, context, x, y, selection_data, info, timestamp):
- if not gtk.targets_include_uri(context.targets):
+ if not Gtk.targets_include_uri(context.targets):
return
-
+
uris = drop_get_uris(selection_data)
-
+
if not uris:
return
-
+
if entry.get_text():
mimes = [entry.get_text()]
else:
mimes = []
-
+
for uri in uris:
try:
- mime = gio.content_type_guess(uri)
+ mime = Gio.content_type_guess(uri)
except:
mime = None
-
+
if mime:
mimes.append(mime)
-
+
entry.set_text(', '.join(mimes))
self.on_entry_drop_targets_focus_out(entry, None)
context.finish(True, False, timestamp)
-
+
entry.stop_emission('drag_data_received')
+
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/Parser.py b/plugins/snippets/snippets/parser.py
similarity index 90%
rename from plugins/snippets/snippets/Parser.py
rename to plugins/snippets/snippets/parser.py
index 3bbaf6e..0012c71 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):
@@ -27,10 +27,10 @@ class Token:
def __str__(self):
return '%s: [%s]' % (self.klass, self.data)
-
+
def __eq__(self, other):
return self.klass == other.klass and self.data == other.data
-
+
def __ne__(self, other):
return not self.__eq__(other)
@@ -39,16 +39,16 @@ class Parser:
SREG_ID = '[0-9]+'
REG_ESCAPE = re.compile('(\\$(%s|\\(|\\{|<|%s)|`|\\\\)' % (SREG_ENV, SREG_ID))
-
+
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
self.position = 0
self.data_length = len(self.data)
-
+
self.RULES = (self._match_env, self._match_regex, self._match_placeholder, self._match_shell, self._match_eval, self._text)
-
+
def remains(self):
return self.data[self.position:]
@@ -57,7 +57,7 @@ class Parser:
return ''
else:
return self.data[self.position + 1]
-
+
def char(self):
if self.position >= self.data_length:
return ''
@@ -78,12 +78,12 @@ class Parser:
# Detect end of text token
if func != self._text and self.tktext != '':
return Token('text', self.tktext)
-
+
tk = func()
if tk:
return tk
-
+
if self.tktext != '':
return Token('text', self.tktext)
@@ -92,93 +92,93 @@ class Parser:
if text == '':
return False
-
+
return self.REG_ESCAPE.match(text)
-
- def _escape(self):
+
+ def _escape(self):
if not self._need_escape():
return
-
+
# Increase position with 1
self.position += 1
-
+
def _text(self):
if self.char() == '\\':
self._escape()
self.tktext += self.char()
self.position += 1
-
+
def _rule(self):
for rule in self.RULES:
res = rule()
-
+
if res:
return res
def _match_env(self):
text = self.remains()
match = re.match('\\$(%s)' % self.SREG_ENV, text) or re.match('\\${(%s)}' % self.SREG_ENV, text)
-
+
if match:
self.position += len(match.group(0))
return Token('environment', match.group(1))
-
+
def _parse_list(self, lst):
pos = 0
length = len(lst)
items = []
last = None
-
+
while pos < length:
char = lst[pos]
next = pos < length - 1 and lst[pos + 1]
-
+
if char == '\\' and (next == ',' or next == ']'):
char = next
pos += 1
elif char == ',':
if last != None:
items.append(last)
-
+
last = None
pos += 1
continue
last = (last != None and last + char) or char
pos += 1
-
+
if last != None:
items.append(last)
-
+
return items
-
+
def _parse_default(self, default):
match = re.match('^\\s*(\\\\)?(\\[((\\\\]|[^\\]])+)\\]\\s*)$', default)
-
+
if not match:
return [default]
-
+
groups = match.groups()
-
+
if groups[0]:
return [groups[1]]
return self._parse_list(groups[2])
-
+
def _match_placeholder(self):
text = self.remains()
-
+
match = re.match('\\${(%s)(:((\\\\\\}|[^}])+))?}' % self.SREG_ID, text) or re.match('\\$(%s)' % self.SREG_ID, text)
-
+
if not match:
return None
-
+
groups = match.groups()
default = ''
tabstop = int(groups[0])
self.position += len(match.group(0))
-
+
if len(groups) > 1 and groups[2]:
default = self._parse_default(groups[2].replace('\\}', '}'))
@@ -187,10 +187,10 @@ class Parser:
def _match_shell(self):
text = self.remains()
match = re.match('`((%s):)?((\\\\`|[^`])+?)`' % self.SREG_ID, text) or re.match('\\$\\(((%s):)?((\\\\\\)|[^\\)])+?)\\)' % self.SREG_ID, text)
-
+
if not match:
return None
-
+
groups = match.groups()
tabstop = (groups[1] and int(groups[1])) or -1
self.position += len(match.group(0))
@@ -199,61 +199,61 @@ class Parser:
contents = groups[2].replace('\\`', '`')
else:
contents = groups[2].replace('\\)', ')')
-
+
return Token('shell', {'tabstop': tabstop, 'contents': contents})
def _try_match_shell(self):
return self._match_shell() or self._text()
-
+
def _eval_options(self, options):
reg = re.compile(self.SREG_ID)
tabstop = -1
depend = []
-
+
options = options.split(':')
-
+
for opt in options:
if reg.match(opt):
tabstop = int(opt)
else:
depend += self._parse_list(opt[1:-1])
-
+
return (tabstop, depend)
-
+
def _match_eval(self):
text = self.remains()
-
+
options = '((%s)|\\[([0-9, ]+)\\])' % self.SREG_ID
match = re.match('\\$<((%s:)*)((\\\\>|[^>])+?)>' % options, text)
-
+
if not match:
return None
-
+
groups = match.groups()
(tabstop, depend) = (groups[0] and self._eval_options(groups[0][:-1])) or (-1, [])
self.position += len(match.group(0))
-
+
return Token('eval', {'tabstop': tabstop, 'dependencies': depend, 'contents': groups[5].replace('\\>', '>')})
-
+
def _match_regex(self):
text = self.remains()
-
+
content = '((?:\\\\[/]|\\\\}|[^/}])+)'
match = re.match('\\${(?:(%s):)?\\s*(%s|\\$([A-Z_]+))?[/]%s[/]%s(?:[/]([a-zA-Z]*))?}' % (self.SREG_ID, self.SREG_ID, content, content), text)
-
+
if not match:
return None
-
+
groups = match.groups()
tabstop = (groups[0] and int(groups[0])) or -1
inp = (groups[2] or (groups[1] and int(groups[1]))) or ''
-
+
pattern = re.sub('\\\\([/}])', '\\1', groups[3])
substitution = re.sub('\\\\([/}])', '\\1', groups[4])
modifiers = groups[5] or ''
-
+
self.position += len(match.group(0))
-
+
return Token('regex', {'tabstop': tabstop, 'input': inp, 'pattern': pattern, 'substitution': substitution, 'modifiers': modifiers})
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/Placeholder.py b/plugins/snippets/snippets/placeholder.py
similarity index 90%
rename from plugins/snippets/snippets/Placeholder.py
rename to plugins/snippets/snippets/placeholder.py
index c43eeca..d10eaeb 100644
--- a/plugins/snippets/snippets/Placeholder.py
+++ b/plugins/snippets/snippets/placeholder.py
@@ -23,10 +23,10 @@ import signal
import select
import locale
import subprocess
-from SubstitutionParser import SubstitutionParser
-import gobject
+from gi.repository import GObject
-from Helper import *
+from helper import *
+from substitutionparser import SubstitutionParser
# These are places in a view where the cursor can go and do things
class Placeholder:
@@ -42,14 +42,14 @@ class Placeholder:
self.set_default(defaults)
self.prev_contents = self.default
self.set_mark_gravity()
-
+
if begin:
self.begin = self.buf.create_mark(None, begin, self.mark_gravity[0])
else:
self.begin = None
-
+
self.end = None
-
+
def __str__(self):
return '%s (%s)' % (str(self.__class__), str(self.default))
@@ -65,20 +65,20 @@ class Placeholder:
for d in defaults:
dm = self.expand_environment(d)
-
+
if dm:
self.defaults.append(dm)
if not self.default:
self.default = dm
-
+
if dm != d:
break
-
+
def literal(self, s):
return repr(s)
-
+
def format_environment(self, s):
return s
@@ -93,7 +93,7 @@ class Placeholder:
return text
return re.sub('(\\\\)?\\$([A-Z_]+)', self.re_environment, text)
-
+
def get_iter(self, mark):
if mark and not mark.get_deleted():
return self.buf.get_iter_at_mark(mark)
@@ -102,24 +102,24 @@ class Placeholder:
def begin_iter(self):
return self.get_iter(self.begin)
-
+
def end_iter(self):
return self.get_iter(self.end)
-
+
def run_last(self, placeholders):
begin = self.begin_iter()
self.end = self.buf.create_mark(None, begin, self.mark_gravity[1])
if self.default:
insert_with_indent(self.view, begin, self.default, False, self)
-
+
def remove(self, force = False):
if self.begin and not self.begin.get_deleted():
self.buf.delete_mark(self.begin)
-
+
if self.end and not self.end.get_deleted():
self.buf.delete_mark(self.end)
-
+
# Do something on beginning this placeholder
def enter(self):
if not self.begin or self.begin.get_deleted():
@@ -131,19 +131,19 @@ class Placeholder:
self.buf.move_mark(self.buf.get_selection_bound(), self.end_iter())
else:
self.buf.move_mark(self.buf.get_selection_bound(), self.begin_iter())
-
+
def get_text(self):
if self.begin and self.end:
biter = self.begin_iter()
eiter = self.end_iter()
-
+
if biter and eiter:
- return self.buf.get_text(self.begin_iter(), self.end_iter())
+ return self.buf.get_text(self.begin_iter(), self.end_iter(), False)
else:
return ''
else:
return ''
-
+
def add_mirror(self, mirror, onleave = False):
mirror.has_references = True
@@ -165,13 +165,13 @@ class Placeholder:
# Insert the text from the mirror
insert_with_indent(self.view, begin, text, True, self)
self.buf.end_user_action()
-
+
self.update_contents()
def update_contents(self):
prev = self.prev_contents
self.prev_contents = self.get_text()
-
+
if prev != self.get_text():
for mirror in self.mirrors:
if not mirror.update(self):
@@ -189,13 +189,13 @@ class Placeholder:
def find_mirrors(self, text, placeholders):
mirrors = []
-
+
while (True):
m = re.search('(\\\\)?\\$(?:{([0-9]+)}|([0-9]+))', text)
-
+
if not m:
break
-
+
# Skip escaped mirrors
if m.group(1):
text = text[m.end():]
@@ -211,10 +211,10 @@ class Placeholder:
else:
self.ok = False
return None
-
- return mirrors
-# This is an placeholder which inserts a mirror of another Placeholder
+ return mirrors
+
+# This is an placeholder which inserts a mirror of another Placeholder
class PlaceholderMirror(Placeholder):
def __init__(self, view, tabstop, begin):
Placeholder.__init__(self, view, -1, None, begin)
@@ -229,9 +229,9 @@ class PlaceholderMirror(Placeholder):
if self.mirror_stop in placeholders:
mirror = placeholders[self.mirror_stop]
-
+
mirror.add_mirror(self)
-
+
if mirror.default:
self.set_text(mirror.default)
else:
@@ -241,14 +241,14 @@ class PlaceholderMirror(Placeholder):
class PlaceholderEnd(Placeholder):
def __init__(self, view, begin, default):
Placeholder.__init__(self, view, 0, default, begin)
-
+
def run_last(self, placeholders):
Placeholder.run_last(self, placeholders)
-
+
# Remove the begin mark and set the begin mark
# to the end mark, this is needed so the end placeholder won't contain
# any text
-
+
if not self.default:
self.mark_gravity[0] = False
self.buf.delete_mark(self.begin)
@@ -257,14 +257,14 @@ class PlaceholderEnd(Placeholder):
def enter(self):
if self.begin and not self.begin.get_deleted():
self.buf.move_mark(self.buf.get_insert(), self.begin_iter())
-
+
if self.end and not self.end.get_deleted():
self.buf.move_mark(self.buf.get_selection_bound(), self.end_iter())
-
+
def leave(self):
- self.enter()
+ self.enter()
-# This placeholder is used to expand a command with embedded mirrors
+# This placeholder is used to expand a command with embedded mirrors
class PlaceholderExpand(Placeholder):
def __init__(self, view, tabstop, begin, s):
Placeholder.__init__(self, view, tabstop, None, begin)
@@ -276,30 +276,30 @@ class PlaceholderExpand(Placeholder):
def __str__(self):
s = Placeholder.__str__(self)
-
+
return s + ' ' + self.cmd
def get_mirrors(self, placeholders):
return self.find_mirrors(self.cmd, placeholders)
-
+
# Check if all substitution placeholders are accounted for
def run_last(self, placeholders):
Placeholder.run_last(self, placeholders)
self.ok = True
mirrors = self.get_mirrors(placeholders)
-
+
if mirrors:
allDefault = True
-
+
for mirror in mirrors:
p = placeholders[mirror]
p.add_mirror(self, not self.instant_update)
self.mirror_text[p.tabstop] = p.default
-
+
if not p.default and not isinstance(p, PlaceholderExpand):
allDefault = False
-
+
if allDefault:
self.update(None)
self.default = self.get_text() or None
@@ -309,7 +309,7 @@ class PlaceholderExpand(Placeholder):
if self.tabstop == -1:
self.done = True
-
+
def re_placeholder(self, m, formatter):
if m.group(1):
return '"$' + m.group(2) + '"'
@@ -318,23 +318,23 @@ class PlaceholderExpand(Placeholder):
index = int(m.group(3))
else:
index = int(m.group(4))
-
+
return formatter(self.mirror_text[index])
def remove_timeout(self):
if self.timeout_id != None:
- gobject.source_remove(self.timeout_id)
+ GLib.source_remove(self.timeout_id)
self.timeout_id = None
-
+
def install_timeout(self):
self.remove_timeout()
- self.timeout_id = gobject.timeout_add(1000, self.timeout_cb)
+ self.timeout_id = GLib.timeout_add(1000, self.timeout_cb)
def timeout_cb(self):
self.timeout_id = None
-
+
return False
-
+
def format_environment(self, text):
return self.literal(text)
@@ -342,30 +342,30 @@ class PlaceholderExpand(Placeholder):
formatter = formatter or self.literal
# substitute all mirrors, but also environmental variables
- text = re.sub('(\\\\)?\\$({([0-9]+)}|([0-9]+))', lambda m: self.re_placeholder(m, formatter),
+ text = re.sub('(\\\\)?\\$({([0-9]+)}|([0-9]+))', lambda m: self.re_placeholder(m, formatter),
text)
-
+
return self.expand_environment(text)
-
+
def run_update(self):
text = self.substitute(self.cmd)
-
+
if text:
ret = self.expand(text)
-
+
if ret:
self.update_leave_mirrors()
else:
ret = True
-
+
return ret
-
+
def update(self, mirror):
text = None
-
+
if mirror:
self.mirror_text[mirror.tabstop] = mirror.get_text()
-
+
# Check if all substitutions have been made
for tabstop in self.mirror_text:
if tabstop == 0:
@@ -389,49 +389,49 @@ class PlaceholderShell(PlaceholderExpand):
def close_shell(self):
self.shell.stdout.close()
- self.shell = None
-
+ self.shell = None
+
def timeout_cb(self):
PlaceholderExpand.timeout_cb(self)
self.remove_timeout()
-
+
if not self.shell:
return False
- gobject.source_remove(self.watch_id)
+ GLib.source_remove(self.watch_id)
self.close_shell()
if self.remove_me:
PlaceholderExpand.remove(self)
- message_dialog(None, gtk.MESSAGE_ERROR, 'Execution of the shell ' \
+ message_dialog(None, Gtk.MessageType.ERROR, 'Execution of the shell ' \
'command (%s) exceeded the maximum time; ' \
'execution aborted.' % self.command)
-
+
return False
-
+
def process_close(self):
self.close_shell()
self.remove_timeout()
self.set_text(str.join('', self.shell_output).rstrip('\n'))
-
+
if self.default == None:
self.default = self.get_text()
self.leave()
-
+
if self.remove_me:
PlaceholderExpand.remove(self, True)
-
+
def process_cb(self, source, condition):
- if condition & gobject.IO_IN:
+ if condition & GObject.IO_IN:
line = source.readline()
if len(line) > 0:
try:
line = unicode(line, 'utf-8')
except:
- line = unicode(line, locale.getdefaultlocale()[1],
+ line = unicode(line, locale.getdefaultlocale()[1],
'replace')
self.shell_output += line
@@ -441,18 +441,18 @@ class PlaceholderShell(PlaceholderExpand):
self.process_close()
return False
-
+
def literal_replace(self, match):
return "\\%s" % (match.group(0))
def literal(self, text):
return '"' + re.sub('([\\\\"])', self.literal_replace, text) + '"'
-
+
def expand(self, text):
self.remove_timeout()
if self.shell:
- gobject.source_remove(self.watch_id)
+ GLib.source_remove(self.watch_id)
self.close_shell()
popen_args = {
@@ -465,12 +465,12 @@ class PlaceholderShell(PlaceholderExpand):
self.command = text
self.shell = subprocess.Popen(text, **popen_args)
self.shell_output = ''
- self.watch_id = gobject.io_add_watch(self.shell.stdout, gobject.IO_IN | \
- gobject.IO_HUP, self.process_cb)
+ self.watch_id = GLib.io_add_watch(self.shell.stdout, GObject.IO_IN | \
+ GObject.IO_HUP, self.process_cb)
self.install_timeout()
-
+
return True
-
+
def remove(self, force = False):
if not force and self.shell:
# Still executing shell command
@@ -478,7 +478,7 @@ class PlaceholderShell(PlaceholderExpand):
else:
if force:
self.remove_timeout()
-
+
if self.shell:
self.close_shell()
@@ -487,7 +487,7 @@ class PlaceholderShell(PlaceholderExpand):
class TimeoutError(Exception):
def __init__(self, value):
self.value = value
-
+
def __str__(self):
return repr(self.value)
@@ -499,9 +499,9 @@ class PlaceholderEval(PlaceholderExpand):
self.fdread = 0
self.remove_me = False
self.namespace = namespace
-
+
self.refs = []
-
+
if refs:
for ref in refs:
self.refs.append(int(ref.strip()))
@@ -532,28 +532,28 @@ class PlaceholderEval(PlaceholderExpand):
def timeout_cb(self, signum = 0, frame = 0):
raise TimeoutError, "Operation timed out (>2 seconds)"
-
+
def install_timeout(self):
if not self.timeout_supported():
return
if self.timeout_id != None:
self.remove_timeout()
-
+
self.timeout_id = signal.signal(signal.SIGALRM, self.timeout_cb)
signal.alarm(2)
-
+
def remove_timeout(self):
if not self.timeout_supported():
return
if self.timeout_id != None:
signal.alarm(0)
-
+
signal.signal(signal.SIGALRM, self.timeout_id)
self.timeout_id = None
-
+
def expand(self, text):
self.remove_timeout()
@@ -565,7 +565,7 @@ class PlaceholderEval(PlaceholderExpand):
return
text = "def process_snippet():\n\t" + "\n\t".join(text.split("\n"))
-
+
if 'process_snippet' in self.namespace:
del self.namespace['process_snippet']
@@ -576,30 +576,30 @@ class PlaceholderEval(PlaceholderExpand):
if 'process_snippet' in self.namespace:
try:
- # Install a sigalarm signal. This is a HACK to make sure
+ # Install a sigalarm signal. This is a HACK to make sure
# gedit doesn't get freezed by someone creating a python
# placeholder which for instance loops indefinately. Since
# the code is executed synchronously it will hang gedit. With
# the alarm signal we raise an exception and catch this
# (see below). We show an error message and return False.
- # ___this is a HACK___ and should be fixed properly (I just
- # don't know how)
+ # ___this is a HACK___ and should be fixed properly (I just
+ # don't know how)
self.install_timeout()
result = self.namespace['process_snippet']()
self.remove_timeout()
except TimeoutError:
self.remove_timeout()
- message_dialog(None, gtk.MESSAGE_ERROR, \
+ message_dialog(None, Gtk.MessageType.ERROR, \
_('Execution of the Python command (%s) exceeds the maximum ' \
'time, execution aborted.') % self.command)
-
+
return False
except Exception, detail:
self.remove_timeout()
-
- message_dialog(None, gtk.MESSAGE_ERROR,
- _('Execution of the Python command (%s) failed: %s') %
+
+ message_dialog(None, Gtk.MessageType.ERROR,
+ _('Execution of the Python command (%s) failed: %s') %
(self.command, detail))
return False
@@ -609,21 +609,21 @@ class PlaceholderEval(PlaceholderExpand):
result = ''
self.set_text(str(result))
-
+
return True
# Regular expression placeholder
class PlaceholderRegex(PlaceholderExpand):
def __init__(self, view, tabstop, begin, inp, pattern, substitution, modifiers):
PlaceholderExpand.__init__(self, view, tabstop, begin, '')
-
+
self.instant_update = True
self.inp = inp
self.pattern = pattern
self.substitution = substitution
-
+
self.init_modifiers(modifiers)
-
+
def init_modifiers(self, modifiers):
mods = {'I': re.I,
'L': re.L,
@@ -631,7 +631,7 @@ class PlaceholderRegex(PlaceholderExpand):
'S': re.S,
'U': re.U,
'X': re.X}
-
+
self.modifiers = 0
for modifier in modifiers:
@@ -660,16 +660,16 @@ class PlaceholderRegex(PlaceholderExpand):
return os.environ[self.inp]
else:
return ''
-
+
def run_update(self):
pattern = self.substitute(self.pattern)
substitution = self.substitute(self.substitution, SubstitutionParser.escape_substitution)
-
+
if pattern:
return self.expand(pattern, substitution)
-
+
return True
-
+
def expand(self, pattern, substitution):
# Try to compile pattern
try:
@@ -677,15 +677,15 @@ class PlaceholderRegex(PlaceholderExpand):
except re.error, message:
sys.stderr.write('Could not compile regular expression: %s\n%s\n' % (pattern, message))
return False
-
+
inp = self.get_input()
match = regex.search(inp)
-
+
if not match:
self.set_text(inp)
else:
groups = match.groupdict()
-
+
idx = 0
for group in match.groups():
groups[str(idx + 1)] = group
@@ -695,6 +695,7 @@ class PlaceholderRegex(PlaceholderExpand):
parser = SubstitutionParser(substitution, groups)
self.set_text(parser.parse())
-
+
return True
+
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/Snippet.py b/plugins/snippets/snippets/snippet.py
similarity index 90%
rename from plugins/snippets/snippets/Snippet.py
rename to plugins/snippets/snippets/snippet.py
index d7baead..13cf30d 100644
--- a/plugins/snippets/snippets/Snippet.py
+++ b/plugins/snippets/snippets/snippet.py
@@ -16,17 +16,17 @@
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import os
-import gio
+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):
self.view = view
self._init_namespace()
-
+
def _init_namespace(self):
self.namespace = {
'__builtins__': __builtins__,
@@ -42,28 +42,28 @@ class EvalUtilities:
return len(s.expandtabs(tablen))
def _filename_to_uri(self, filename):
- gfile = gio.File(filename)
+ gfile = Gio.File(filename)
return gfile.get_uri()
def util_readfile(self, filename):
- stream = gio.File(filename).read()
-
+ stream = Gio.File(filename).read()
+
if not stream:
return ''
-
+
res = stream.read()
stream.close()
-
+
return res
def util_filesize(self, filename):
- gfile = gio.File(filename)
- info = gfile.query_info(gio.FILE_ATTRIBUTE_STANDARD_SIZE)
-
+ gfile = Gio.File(filename)
+ info = gfile.query_info(Gio.FILE_ATTRIBUTE_STANDARD_SIZE)
+
if not info:
return 0
-
+
return info.get_size()
def util_align(self, items):
@@ -74,61 +74,61 @@ class EvalUtilities:
for col in range(0, len(items[row]) - 1):
if row == 0:
maxlen.append(0)
-
+
items[row][col] += "\t"
rl = self._real_len(items[row][col], tablen)
-
+
if (rl > maxlen[col]):
maxlen[col] = rl
result = ''
-
+
for row in range(0, len(items)):
for col in range(0, len(items[row]) - 1):
item = items[row][col]
-
+
result += item + ("\t" * ((maxlen[col] - \
self._real_len(item, tablen)) / tablen))
-
+
result += items[row][len(items[row]) - 1]
-
+
if row != len(items) - 1:
result += "\n"
-
+
return result
class Snippet:
def __init__(self, data):
self.data = data
-
+
def __getitem__(self, prop):
return self.data[prop]
-
+
def __setitem__(self, prop, value):
self.data[prop] = value
-
+
def accelerator_display(self):
accel = self['accelerator']
if accel:
- keyval, mod = gtk.accelerator_parse(accel)
- accel = gtk.accelerator_get_label(keyval, mod)
-
+ keyval, mod = Gtk.accelerator_parse(accel)
+ accel = Gtk.accelerator_get_label(keyval, mod)
+
return accel or ''
def display(self):
nm = markup_escape(self['description'])
-
+
tag = self['tag']
accel = self.accelerator_display()
detail = []
-
+
if tag and tag != '':
detail.append(tag)
-
+
if accel and accel != '':
detail.append(accel)
-
+
if not detail:
return nm
else:
@@ -154,23 +154,23 @@ class Snippet:
def _insert_iter(self):
return self._view.get_buffer().get_iter_at_mark(self._insert_mark)
-
+
def _create_environment(self, data):
val = ((data in os.environ) and os.environ[data]) or ''
-
+
# Get all the current indentation
all_indent = compute_indentation(self._view, self._insert_iter())
-
+
# Substract initial indentation to get the snippet indentation
indent = all_indent[len(self._indent):]
# Keep indentation
return unicode.join('\n' + unicode(indent), val.split('\n'))
-
+
def _create_placeholder(self, data):
tabstop = data['tabstop']
begin = self._insert_iter()
-
+
if tabstop == 0:
# End placeholder
return PlaceholderEnd(self._view, begin, data['default'])
@@ -188,21 +188,21 @@ class Snippet:
def _create_eval(self, data):
begin = self._insert_iter()
return PlaceholderEval(self._view, data['tabstop'], data['dependencies'], begin, data['contents'], self._utils.namespace)
-
+
def _create_regex(self, data):
begin = self._insert_iter()
return PlaceholderRegex(self._view, data['tabstop'], begin, data['input'], data['pattern'], data['substitution'], data['modifiers'])
-
+
def _create_text(self, data):
return data
def _invalid_placeholder(self, placeholder, remove):
buf = self._view.get_buffer()
-
+
# Remove the text because this placeholder is invalid
if placeholder.default and remove:
buf.delete(placeholder.begin_iter(), placeholder.end_iter())
-
+
placeholder.remove()
if placeholder.tabstop == -1:
@@ -210,25 +210,25 @@ class Snippet:
del self.placeholders[-1][index]
else:
del self.placeholders[placeholder.tabstop]
-
+
self.plugin_data.ordered_placeholders.remove(placeholder)
def _parse(self, plugin_data):
# Initialize current variables
self._view = plugin_data.view
- self._indent = compute_indentation(self._view, self._view.get_buffer().get_iter_at_mark(self.begin_mark))
+ self._indent = compute_indentation(self._view, self._view.get_buffer().get_iter_at_mark(self.begin_mark))
self._utils = EvalUtilities(self._view)
self.placeholders = {}
self._insert_mark = self.end_mark
self.plugin_data = plugin_data
-
+
# Create parser
parser = Parser(data=self['text'])
# Parse tokens
while (True):
token = parser.token()
-
+
if not token:
break
@@ -242,7 +242,7 @@ class Snippet:
except:
sys.stderr.write('Token class not supported: %s\n' % token.klass)
continue
-
+
if isinstance(val, basestring):
# Insert text
self._insert_text(val)
@@ -262,13 +262,13 @@ class Snippet:
for placeholder in ph:
placeholder.run_last(self.placeholders)
-
+
if not placeholder.ok or placeholder.done:
self._invalid_placeholder(placeholder, not placeholder.ok)
# Remove all the Expand placeholders which have a tabstop because
# they can be used to mirror, but they shouldn't be real tabstops
- # (if they have mirrors installed). This is problably a bit of
+ # (if they have mirrors installed). This is problably a bit of
# a dirty hack :)
if -1 not in self.placeholders:
self.placeholders[-1] = []
@@ -281,20 +281,20 @@ class Snippet:
placeholder.has_references:
# Add to anonymous placeholders
self.placeholders[-1].append(placeholder)
-
+
# Remove placeholder
del self.placeholders[tabstop]
-
+
self.plugin_data = None
def insert_into(self, plugin_data, insert):
buf = plugin_data.view.get_buffer()
last_index = 0
-
+
# Find closest mark at current insertion, so that we may insert
# our marks in the correct order
(current, next) = plugin_data.next_placeholder()
-
+
if current:
# Insert AFTER current
last_index = plugin_data.placeholders.index(current) + 1
@@ -304,52 +304,53 @@ class Snippet:
else:
# Insert at first position
last_index = 0
-
+
# lastIndex now contains the position of the last mark
# Create snippet bounding marks
self.begin_mark = buf.create_mark(None, insert, True)
self.end_mark = buf.create_mark(None, insert, False)
-
+
# Now parse the contents of this snippet, create Placeholders
# and insert the placholder marks in the marks array of plugin_data
self._parse(plugin_data)
-
- # 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
+
+ # 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)
-
+
plugin_data.placeholders.insert(last_index, self.placeholders[0])
last_iter = self.placeholders[0].end_iter()
-
+
for tabstop in k:
if tabstop != -1 and tabstop != 0:
placeholder = self.placeholders[tabstop]
end_iter = placeholder.end_iter()
-
+
if last_iter.compare(end_iter) < 0:
last_iter = end_iter
-
+
# Inserting placeholder
plugin_data.placeholders.insert(last_index, placeholder)
-
+
# Move end mark to last placeholder
buf.move_mark(self.end_mark, last_iter)
return self
-
+
def deactivate(self):
buf = self.begin_mark.get_buffer()
-
+
buf.delete_mark(self.begin_mark)
buf.delete_mark(self.end_mark)
-
+
self.placeholders = {}
-
+
def begin_iter(self):
return self.begin_mark.get_buffer().get_iter_at_mark(self.begin_mark)
-
+
def end_iter(self):
return self.end_mark.get_buffer().get_iter_at_mark(self.end_mark)
+
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/snippets.ui b/plugins/snippets/snippets/snippets.ui
index 426df88..e770e2f 100644
--- a/plugins/snippets/snippets/snippets.ui
+++ b/plugins/snippets/snippets/snippets.ui
@@ -35,64 +35,10 @@
<object class="GeditDocument" id="source_buffer">
<property name="highlight-matching-brackets">True</property>
</object>
- <object class="GtkDialog" id="dialog_snippets">
- <property name="title" translatable="yes">Snippets Manager</property>
- <property name="type">GTK_WINDOW_TOPLEVEL</property>
- <property name="window_position">GTK_WIN_POS_NONE</property>
- <property name="modal">False</property>
- <property name="default_width">750</property>
- <property name="default_height">500</property>
- <property name="resizable">True</property>
- <property name="destroy_with_parent">True</property>
- <property name="decorated">True</property>
- <property name="skip_taskbar_hint">True</property>
- <property name="skip_pager_hint">False</property>
- <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property>
- <property name="gravity">GDK_GRAVITY_NORTH_WEST</property>
- <property name="focus_on_map">True</property>
- <property name="urgency_hint">False</property>
- <property name="has_separator">False</property>
- <signal handler="on_dialog_snippets_response" last_modification_time="Mon, 19 Dec 2005 11:20:00 GMT" name="response"/>
- <signal handler="on_dialog_snippets_destroy" last_modification_time="Sun, 22 Jun 2008 13:22:00 GMT" name="destroy"/>
- <child internal-child="vbox">
- <object class="GtkVBox" id="dialog-vbox1">
+ <object class="GeditSnippetsManager" id="snippets_manager">
<property name="visible">True</property>
<property name="homogeneous">False</property>
<property name="spacing">0</property>
- <child internal-child="action_area">
- <object class="GtkHButtonBox" id="dialog-action_area1">
- <property name="visible">True</property>
- <property name="layout_style">GTK_BUTTONBOX_END</property>
- <child>
- <object class="GtkButton" id="closebutton1">
- <property name="visible">True</property>
- <property name="can_default">True</property>
- <property name="can_focus">True</property>
- <property name="label">gtk-close</property>
- <property name="use_stock">True</property>
- <property name="relief">GTK_RELIEF_NORMAL</property>
- <property name="focus_on_click">True</property>
- </object>
- </child>
- <child>
- <object class="GtkButton" id="button1">
- <property name="visible">True</property>
- <property name="can_default">True</property>
- <property name="can_focus">True</property>
- <property name="label">gtk-help</property>
- <property name="use_stock">True</property>
- <property name="relief">GTK_RELIEF_NORMAL</property>
- <property name="focus_on_click">True</property>
- </object>
- </child>
- </object>
- <packing>
- <property name="padding">0</property>
- <property name="expand">False</property>
- <property name="fill">True</property>
- <property name="pack_type">GTK_PACK_END</property>
- </packing>
- </child>
<child>
<object class="GtkHPaned" id="hpaned_paned">
<property name="border_width">6</property>
@@ -581,10 +527,11 @@
</packing>
</child>
<child>
- <object class="GtkComboBoxEntry" id="combo_drop_targets">
+ <object class="GtkComboBox" id="combo_drop_targets">
<property name="visible">True</property>
<property name="add_tearoffs">False</property>
<property name="has_frame">True</property>
+ <property name="has_entry">True</property>
<property name="focus_on_click">True</property>
<property name="model">model1</property>
<child>
@@ -638,10 +585,4 @@
</packing>
</child>
</object>
- </child>
- <action-widgets>
- <action-widget response="-7">closebutton1</action-widget>
- <action-widget response="-11">button1</action-widget>
- </action-widgets>
- </object>
</interface>
diff --git a/plugins/snippets/snippets/SubstitutionParser.py b/plugins/snippets/snippets/substitutionparser.py
similarity index 90%
rename from plugins/snippets/snippets/SubstitutionParser.py
rename to plugins/snippets/snippets/substitutionparser.py
index 6522222..45aa1f9 100644
--- a/plugins/snippets/snippets/SubstitutionParser.py
+++ b/plugins/snippets/snippets/substitutionparser.py
@@ -25,9 +25,9 @@ class Modifiers:
def _first_char(s):
first = (s != '' and s[0]) or ''
rest = (len(s) > 1 and s[1:]) or ''
-
+
return first, rest
-
+
def upper_first(s):
first, rest = Modifiers._first_char(s)
@@ -40,13 +40,13 @@ class Modifiers:
first, rest = Modifiers._first_char(s)
return '%s%s' % (first.lower(), rest)
-
+
def lower(s):
return s.lower()
-
+
def title(s):
return s.title()
-
+
upper_first = staticmethod(upper_first)
upper = staticmethod(upper)
lower_first = staticmethod(lower_first)
@@ -63,22 +63,22 @@ class SubstitutionParser:
def __init__(self, pattern, groups = {}, modifiers = {}):
self.pattern = pattern
self.groups = groups
-
+
self.REG_GROUP = '(?:(%s)|<(%s|%s)(?:,(%s))?>)' % (self.REG_ID, self.REG_ID, self.REG_NAME, self.REG_MOD)
self.modifiers = {'u': Modifiers.upper_first,
'U': Modifiers.upper,
'l': Modifiers.lower_first,
'L': Modifiers.lower,
't': Modifiers.title}
-
+
for k, v in modifiers.items():
self.modifiers[k] = v
-
+
def parse(self):
result, tokens = self._parse(self.pattern, None)
-
+
return result
-
+
def _parse(self, tokens, terminator):
result = ''
@@ -91,24 +91,24 @@ class SubstitutionParser:
res, tokens = self._expr(tokens, terminator)
except ParseError:
res, tokens = self._text(tokens)
-
+
result += res
-
+
return result, tokens
-
+
def _peek(self, tokens, num = 0):
return (num < len(tokens) and tokens[num])
-
+
def _token(self, tokens):
if tokens == '':
return '', '';
return tokens[0], (len(tokens) > 1 and tokens[1:]) or ''
-
+
def _remains(self, tokens, num = 1):
return (num < len(tokens) and tokens[num:]) or ''
- def _expr(self, tokens, terminator):
+ def _expr(self, tokens, terminator):
if tokens == '':
return ''
@@ -123,30 +123,30 @@ class SubstitutionParser:
def _substitute(self, group, modifiers = ''):
result = (self.groups.has_key(group) and self.groups[group]) or ''
-
+
for modifier in modifiers:
if self.modifiers.has_key(modifier):
result = self.modifiers[modifier](result)
-
+
return result
-
+
def _match_group(self, tokens):
match = re.match('\\\\%s' % self.REG_GROUP, tokens)
-
+
if not match:
return None, tokens
-
+
return self._substitute(match.group(1) or match.group(2), match.group(3) or ''), tokens[match.end():]
-
+
def _escape(self, tokens, terminator):
# Try to match a group
result, tokens = self._match_group(tokens)
-
+
if result != None:
return result, tokens
-
+
s = self.REG_GROUP
-
+
if terminator:
s += '|%s' % re.escape(terminator)
@@ -154,39 +154,39 @@ class SubstitutionParser:
if not match:
raise ParseError
-
- return match.group(1), tokens[match.end():]
-
+
+ return match.group(1), tokens[match.end():]
+
def _condition_value(self, tokens):
match = re.match('\\\\?%s\s*' % self.REG_GROUP, tokens)
-
+
if not match:
return None, tokens
groups = match.groups()
name = groups[0] or groups[1]
- return self.groups.has_key(name) and self.groups[name] != None, tokens[match.end():]
-
+ return self.groups.has_key(name) and self.groups[name] != None, tokens[match.end():]
+
def _condition(self, tokens, terminator):
# Match ? after (
if self._peek(tokens, 1) != '?':
raise ParseError
-
+
# Remove initial (? token
tokens = self._remains(tokens, 2)
condition, tokens = self._condition_value(tokens)
-
+
if condition == None or self._peek(tokens) != ',':
raise ParseError
truepart, tokens = self._parse(self._remains(tokens), ',')
-
+
if truepart == None:
raise ParseError
-
+
falsepart, tokens = self._parse(tokens, ')')
-
+
if falsepart == None:
raise ParseError
@@ -194,9 +194,10 @@ class SubstitutionParser:
return truepart, tokens
else:
return falsepart, tokens
-
+
def escape_substitution(substitution):
return re.sub('(%s|%s)' % (self.REG_GROUP, self.REG_ESCAPE), '\\\\\\1', substitution)
-
+
escapesubstitution = staticmethod(escape_substitution)
+
# ex:ts=8:et:
diff --git a/plugins/snippets/snippets/WindowHelper.py b/plugins/snippets/snippets/windowactivatable.py
similarity index 74%
rename from plugins/snippets/snippets/WindowHelper.py
rename to plugins/snippets/snippets/windowactivatable.py
index 29bf3a5..d73adef 100644
--- a/plugins/snippets/snippets/WindowHelper.py
+++ b/plugins/snippets/snippets/windowactivatable.py
@@ -19,88 +19,99 @@ import re
import os
import gettext
-import gtk
-from gtk import gdk
-import gedit
+from gi.repository import Gtk, Gdk, Gedit, GObject
-from Document import Document
-from Library import Library
+from document import Document
+from library import Library
-class WindowHelper:
- def __init__(self, plugin):
- self.plugin = plugin
+class WindowActivatable(GObject.Object, Gedit.WindowActivatable):
+ __gtype_name__ = "GeditSnippetsWindowActivatable"
+
+ window = GObject.property(type=GObject.Object)
+
+ def __init__(self):
self.current_controller = None
self.current_language = None
self.signal_ids = {}
-
- def run(self, window):
- self.window = window
+ def do_activate(self):
self.insert_menu()
self.register_messages()
-
+
self.accel_group = Library().get_accel_group(None)
-
- window.add_accel_group(self.accel_group)
- window.connect('tab-added', self.on_tab_added)
-
+
+ if self.accel_group:
+ self.window.add_accel_group(self.accel_group)
+
+ self.window.connect('tab-added', self.on_tab_added)
+
# Add controllers to all the current views
for view in self.window.get_views():
- if isinstance(view, gedit.View) and not self.has_controller(view):
+ if isinstance(view, Gedit.View) and not self.has_controller(view):
view._snippet_controller = Document(self, view)
-
- self.update()
-
- def stop(self):
- self.window.remove_accel_group(self.accel_group)
+
+ self.do_update_state()
+
+ def do_deactivate(self):
+ if self.accel_group:
+ self.window.remove_accel_group(self.accel_group)
+
self.accel_group = None
-
- #self.window.remove_accel_group(accel)
+
self.remove_menu()
self.unregister_messages()
# Iterate over all the tabs and remove every controller
for view in self.window.get_views():
- if isinstance(view, gedit.View) and self.has_controller(view):
+ if isinstance(view, Gedit.View) and self.has_controller(view):
view._snippet_controller.stop()
view._snippet_controller = None
-
- self.window = None
- self.plugin = None
-
+
+ def do_update_state(self):
+ view = self.window.get_active_view()
+
+ if not view or not self.has_controller(view):
+ return
+
+ controller = view._snippet_controller
+
+ if controller != self.current_controller:
+ self.current_controller = controller
+ self.update_language()
+
def register_messages(self):
bus = self.window.get_message_bus()
-
- self.messages = {
- 'activate': bus.register('/plugins/snippets', 'activate', ('view', 'iter'), trigger=str, view=gedit.View, iter=gtk.TextIter),
- 'parse-and-activate': bus.register('/plugins/snippets', 'parse-and-activate', ('view', 'iter'), snippet=str, view=gedit.View, iter=gtk.TextIter)
- }
-
- bus.connect('/plugins/snippets', 'activate', self.on_message_activate)
- bus.connect('/plugins/snippets', 'parse-and-activate', self.on_message_parse_and_activate)
-
+
+# self.messages = {
+# 'activate': bus.register('/plugins/snippets', 'activate', ('view', 'iter'), trigger=str, view=Gedit.View, iter=Gtk.TextIter),
+# 'parse-and-activate': bus.register('/plugins/snippets', 'parse-and-activate', ('view', 'iter'), snippet=str, view=Gedit.View, iter=Gtk.TextIter)
+# }
+
+# bus.connect('/plugins/snippets', 'activate', self.on_message_activate)
+# bus.connect('/plugins/snippets', 'parse-and-activate', self.on_message_parse_and_activate)
+
def unregister_messages(self):
bus = self.window.get_message_bus()
-
- for name in self.messages:
- bus.unregister(self.messages[name])
-
+
+# for name in self.messages:
+# bus.unregister(self.messages[name])
+
self.messages = {}
-
+
def on_message_activate(self, bus, message):
if message.has_key('view'):
view = message.view
else:
view = self.window.get_active_view()
-
+
if not self.has_controller(view):
return
-
+
if message.has_key('iter'):
iter = message.iter
else:
iter = view.get_buffer().get_iter_at_mark(view.get_buffer().get_insert())
-
+
controller = view._snippet_controller
controller.run_snippet_trigger(message.trigger, (iter, iter))
@@ -109,22 +120,22 @@ class WindowHelper:
view = message.view
else:
view = self.window.get_active_view()
-
+
if not self.has_controller(view):
return
-
+
if message.has_key('iter'):
iter = message.iter
else:
iter = view.get_buffer().get_iter_at_mark(view.get_buffer().get_insert())
-
+
controller = view._snippet_controller
controller.parse_and_run_snippet(message.snippet, iter)
def insert_menu(self):
manager = self.window.get_ui_manager()
- self.action_group = gtk.ActionGroup("GeditSnippetPluginActions")
+ self.action_group = Gtk.ActionGroup("GeditSnippetPluginActions")
self.action_group.set_translation_domain('gedit')
self.action_group.add_actions([('ManageSnippets', None,
_('Manage _Snippets...'), \
@@ -134,21 +145,21 @@ class WindowHelper:
self.merge_id = manager.new_merge_id()
manager.insert_action_group(self.action_group, -1)
manager.add_ui(self.merge_id, '/MenuBar/ToolsMenu/ToolsOps_5', \
- 'ManageSnippets', 'ManageSnippets', gtk.UI_MANAGER_MENUITEM, False)
+ 'ManageSnippets', 'ManageSnippets', Gtk.UIManagerItemType.MENUITEM, False)
def remove_menu(self):
manager = self.window.get_ui_manager()
manager.remove_ui(self.merge_id)
manager.remove_action_group(self.action_group)
self.action_group = None
-
+
def find_snippet(self, snippets, tag):
result = []
-
+
for snippet in snippets:
if Snippet(snippet)['tag'] == tag:
result.append(snippet)
-
+
return result
def has_controller(self, view):
@@ -165,43 +176,32 @@ class WindowHelper:
if self.current_controller:
self.current_language = self.current_controller.language_id
-
+
if self.current_language != None:
accel_group = Library().get_accel_group( \
self.current_language)
self.window.add_accel_group(accel_group)
else:
self.current_language = None
-
+
def language_changed(self, controller):
if controller == self.current_controller:
self.update_language()
-
- def update(self):
- view = self.window.get_active_view()
-
- if not view or not self.has_controller(view):
- return
-
- controller = view._snippet_controller
-
- if controller != self.current_controller:
- self.current_controller = controller
- self.update_language()
# Callbacks
-
+
def on_tab_added(self, window, tab):
# Create a new controller for this tab if it has a standard gedit view
view = tab.get_view()
-
- if isinstance(view, gedit.View) and not self.has_controller(view):
+
+ if isinstance(view, Gedit.View) and not self.has_controller(view):
view._snippet_controller = Document(self, view)
- self.update()
+ self.do_update_state()
def on_action_snippets_activate(self, item):
- self.plugin.create_configure_dialog()
+ #self.plugin.create_configure_dialog()
+ pass
def accelerator_activated(self, keyval, mod):
return self.current_controller.accelerator_activate(keyval, mod)
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]