# -*- coding: utf8 -*- # # reformats the selection to fit to the right margin, based # on uwog's more featureful C plugin # import gedit import gtk class ParPlugin(gedit.Plugin): def __init__(self): gedit.Plugin.__init__(self) def reformat_selection(self, window): view = window.get_active_view() if not view: return right_margin = view.get_property("margin") doc = view.get_buffer() if not doc.get_selection_bounds(): return ins = doc.get_insert() sel = doc.get_selection_bound() s = doc.get_iter_at_mark(ins) e = doc.get_iter_at_mark(sel) if s.compare(e) < 0: end = sel else: s = e end = ins doc.begin_user_action() s.set_line_offset(0) while s.compare(doc.get_iter_at_mark(end)) < 0: chars = s.get_chars_in_line() if chars == 0: # empty line, skip s.forward_line() elif chars > right_margin: s.set_line_offset(right_margin) s.backward_word_start() if s.starts_line(): # ouch... no word breaks in the line, skip for now s.forward_line() else: # todo: strip whitespaces doc.insert(s, "\n") elif chars < right_margin: if s.forward_to_line_end(): tmp = s.copy() s.backward_word_start() s.forward_word_end() if not tmp.forward_word_end(): break # we hit the end iter tmp.backward_word_start() # two empty lines mean end of paragraph if s.get_line() - s.get_line() > 2: s.forward_line() continue doc.delete(s, tmp) doc.insert(s, " ") s.set_line_offset(0) # re evaluate the line else: s.forward_line() doc.end_user_action() def activate(self, window): action = ("Par", None, "Format Paragraph", "J", "Reformat selection to fit the right margin", lambda x, y: self.reformat_selection(y)) # store per window data in the window object windowdata = dict() window.set_data("ParPluginWindowDataKey", windowdata) windowdata["action_group"] = gtk.ActionGroup("GeditParPluginActions") #windowdata["action_group"].set_translation_domain(GETTEXT_PACKAGE) 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", "Par", "Par", gtk.UI_MANAGER_MENUITEM, True) def deactivate(self, window): windowdata = window.get_data("ParPluginWindowDataKey") 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("ParPluginWindowDataKey") windowdata["action_group"].set_sensitive(bool(view and view.get_editable()))