PluginPrintRemover.py

changeset 0
deeb8c24a7ab
child 2
1375fce99e3b
diff -r 000000000000 -r deeb8c24a7ab PluginPrintRemover.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/PluginPrintRemover.py	Wed Dec 18 08:50:31 2013 +0100
@@ -0,0 +1,224 @@
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2013 Detlev Offenbach <detlev@die-offenbachs.de>
+#
+
+"""
+Module implementing the Print Remover plug-in.
+"""
+
+from __future__ import unicode_literals    # __IGNORE_WARNING__
+
+import os
+
+from PyQt4.QtCore import QObject, QTranslator, QCoreApplication
+from PyQt4.QtGui import QAction
+
+from E5Gui.E5Application import e5App
+
+import Preferences
+
+# Start-Of-Header
+name = "Print Remover Plug-in"
+author = "Detlev Offenbach <detlev@die-offenbachs.de>"
+autoactivate = True
+deactivateable = True
+version = "0.1.0"
+className = "PrintRemoverPlugin"
+packageName = "PrintRemover"
+shortDescription = "Remove print() like debug statements."
+longDescription = \
+    """This plug-in implements a tool to remove lines starting with""" \
+    """ a configurable string. This is mostly used to remove print()""" \
+    """ like debug statements. The match is done after stripping all""" \
+    """ whitespace from the beginning of a line. Lines containing the""" \
+    """ string '__NO_REMOVE__' are preserved"""
+needsRestart = False
+pyqtApi = 2
+# End-Of-Header
+
+error = ""
+
+printRemoverPluginObject = None
+    
+
+def createPrintRemoverPage(configDlg):
+    """
+    Module function to create the Print Remover configuration page.
+    
+    @param configDlg reference to the configuration dialog
+    @return reference to the configuration page
+    """
+    global printRemoverPluginObject
+    from PrintRemover.ConfigurationPage.PrintRemoverPage import \
+        PrintRemoverPage
+    page = PrintRemoverPage(printRemoverPluginObject)
+    return page
+    
+
+def getConfigData():
+    """
+    Module function returning data as required by the configuration dialog.
+    
+    @return dictionary containing the relevant data
+    """
+    if e5App().getObject("UserInterface").versionIsNewer('5.2.99', '20121012'):
+        # TODO: add a sensible icon
+        return {
+            "printRemoverPage": [
+                QCoreApplication.translate("PrintRemoverPlugin",
+                                           "Print Remover"),
+                os.path.join("PrintRemover", "icons", "clock.png"),
+                createPrintRemoverPage, None, None],
+        }
+    else:
+        return {}
+
+
+def prepareUninstall():
+    """
+    Module function to prepare for an uninstallation.
+    """
+    Preferences.Prefs.settings.remove(PrintRemoverPlugin.PreferencesKey)
+
+
+class PrintRemoverPlugin(QObject):
+    """
+    Class implementing the Print Remover plugin.
+    """
+    PreferencesKey = "PrintRemover"
+    
+    def __init__(self, ui):
+        """
+        Constructor
+        
+        @param ui reference to the user interface object (UI.UserInterface)
+        """
+        QObject.__init__(self, ui)
+        self.__ui = ui
+        
+        self.__defaults = {
+            "StartswithStrings": [
+                "print(", "print ", "console.log"],
+        }
+        
+        self.__translator = None
+        self.__loadTranslator()
+    
+    def activate(self):
+        """
+        Public method to activate this plugin.
+        
+        @return tuple of None and activation status (boolean)
+        """
+        global error
+        error = ""     # clear previous error
+        
+        global printRemoverPluginObject
+        printRemoverPluginObject = self
+        
+        self.__ui.showMenu.connect(self.__populateMenu)
+        
+        return None, True
+    
+    def deactivate(self):
+        """
+        Public method to deactivate this plugin.
+        """
+        self.__ui.showMenu.disconnect(self.__populateMenu)
+    
+    def __loadTranslator(self):
+        """
+        Private method to load the translation file.
+        """
+        if self.__ui is not None:
+            loc = self.__ui.getLocale()
+            if loc and loc != "C":
+                locale_dir = os.path.join(
+                    os.path.dirname(__file__), "PrintRemover", "i18n")
+                translation = "printremover_{0}".format(loc)
+                translator = QTranslator(None)
+                loaded = translator.load(translation, locale_dir)
+                if loaded:
+                    self.__translator = translator
+                    e5App().installTranslator(self.__translator)
+                else:
+                    print("Warning: translation file '{0}' could not be"
+                          " loaded.".format(translation))
+                    print("Using default.")
+    
+    def getPreferences(self, key):
+        """
+        Public method to retrieve the various settings.
+        
+        @param key the key of the value to get (string)
+        @return the requested setting
+        """
+        if key in ["StartswithStrings"]:
+            return Preferences.toList(
+                Preferences.Prefs.settings.value(
+                    self.PreferencesKey + "/" + key, self.__defaults[key]))
+        else:
+            return Preferences.Prefs.settings.value(
+                self.PreferencesKey + "/" + key, self.__defaults[key])
+    
+    def setPreferences(self, key, value):
+        """
+        Public method to store the various settings.
+        
+        @param key the key of the setting to be set (string)
+        @param value the value to be set
+        """
+        Preferences.Prefs.settings.setValue(
+            self.PreferencesKey + "/" + key, value)
+    
+    def __populateMenu(self, name, menu):
+        """
+        Private slot to populate the tools menu with our entries.
+        
+        @param name name of the menu (string)
+        @param menu reference to the menu to be populated (QMenu)
+        """
+        if name != "Tools":
+            return
+        
+        editor = e5App().getObject("ViewManager").activeWindow()
+        if editor is None:
+            return
+        
+        if not menu.isEmpty():
+            menu.addSeparator()
+        
+        for string in self.getPreferences("StartswithStrings"):
+            act = menu.addAction(
+                self.tr("Remove '{0}'").format(string),
+                self.__removeLine)
+            act.setData(string)
+    
+    def __removeLine(self):
+        """
+        Private slot to remove lines starting with the selected pattern.
+        """
+        act = self.sender()
+        if act is None or not isinstance(act, QAction):
+            return
+        
+        editor = e5App().getObject("ViewManager").activeWindow()
+        if editor is None:
+            return
+        
+        pattern = act.data()
+        if not pattern:
+            return
+        
+        text = editor.text()
+        newText = "".join([
+            line for line in text.splitlines(keepends=True)
+            if not line.lstrip().startswith(pattern) or
+            "__NO_REMOVE__" in line
+        ])
+        if newText != text:
+            editor.beginUndoAction()
+            editor.selectAll()
+            editor.replaceSelectedText(newText)
+            editor.endUndoAction()

eric ide

mercurial