# -*- coding: utf8 -*- import gedit import gtk def strip_whitespaces_from_line(textbuffer, line): end = textbuffer.get_iter_at_line(line) if not end.ends_line(): end.forward_to_line_end() newend = end.copy() i = end.copy() while i.backward_char(): l = i.get_line() c = i.get_char() if l == line and (c == ' ' or c == '\t'): newend = i.copy() else: break if not end.equal(newend): textbuffer.delete(newend, end) class StripTrailingSpacePlugin(gedit.Plugin): def __init__(self): gedit.Plugin.__init__(self) def strip_cb(self, window): doc = window.get_active_document() if not doc: return doc.begin_user_action() selection = doc.get_selection_bounds() if selection != (): (start, end) = selection l = start.get_line() e = end.get_line() while True: strip_whitespaces_from_line(doc, l) if l == e: break l = l + 1 else: l = doc.get_iter_at_mark(doc.get_insert()).get_line() strip_whitespaces_from_line(doc, l) doc.end_user_action() def activate(self, window): action = ("StripTrailingWhitespace", None, "Strip Trailing Whitespace", None, "Strip Trailing Whitespace", lambda x, y: self.strip_cb(y)) # store per window data in the window object windowdata = dict() window.set_data("StripTrailingWhitespacePluginWindowDataKey", windowdata) windowdata["action_group"] = gtk.ActionGroup("GeditStripTrailingWhitespacePluginActions") windowdata["action_group"].add_actions ([action], window) manager = window.get_ui_manager() manager.insert_action_group(windowdata["action_group"], -1) windowdata["ui_id"] = manager.new_merge_id () manager.add_ui (windowdata["ui_id"], "/MenuBar/EditMenu/EditOps_4", "StripTrailingWhitespace", "StripTrailingWhitespace", gtk.UI_MANAGER_MENUITEM, True) def deactivate(self, window): windowdata = window.get_data("StripTrailingWhitespacePluginWindowDataKey") manager = window.get_ui_manager() manager.remove_action_ui(windowdata["ui_id"]) manager.remove_action_group(windowdata["action_group"]) def update_ui(self, window): view = window.get_active_view() windowdata = window.get_data("StripTrailingWhitespacePluginWindowDataKey") windowdata["action_group"].set_sensitive(bool(view and view.get_editable()))