コード例 #1
0
ファイル: leo2.py プロジェクト: prodigeni/leo-editor-contrib
def createFrame(fileName):
    """Create a LeoFrame during Leo's startup process."""

    import leoGlobals as g

    # g.trace(g.app.tkEncoding,fileName)

    # Try to create a frame for the file.
    if fileName:
        fileName = g.os_path_join(os.getcwd(), fileName)
        fileName = g.os_path_normpath(fileName)
        if g.os_path_exists(fileName):
            ok, frame = g.openWithFileName(fileName, None)
            if ok:
                return frame.c, frame

    # Create a new frame & indicate it is the startup window.
    c, frame = g.app.gui.newLeoCommanderAndFrame(fileName=None)
    frame.setInitialWindowGeometry()
    frame.startupWindow = True

    # Report the failure to open the file.
    if fileName:
        g.es("File not found: " + fileName)

    return c, frame
コード例 #2
0
def saveAndUpdateNode( c ):
    
    at = c.atFileCommands
    p = c.currentPosition()
    if p.isAtThinFileNode():
        path = None
        
        path, statuspath = getPathAndBase( p )
        svn =  getRepositoryLocation( p )
        if svn == None:
            g.es( "No Repository Specified")
            return
        try:
            repository = getRepository( svn )
            if repository == None: return
            ws = SVNWorkspaceManager.createWorkspace( "file", path)
            ws.update( repository.getLatestRevision() )
            #status = ws.status( None, 0, Reporter(), 1,1,1 )
            status = ws.status( p.atThinFileNodeName(), 0)
            conflict = None
            
            if status.getContentsStatus() == status.CONFLICTED:
                conflict = True
        except java.lang.Exception, x:
            x.printStackTrace()
            g.es( "Node not in a Workspace")
            return
        
        npos = reload(c, p) 
コード例 #3
0
def executeNodesMarkedAsTests(c):

    rp = c.rootPosition()
    jtests = []
    for z in rp.allNodes_iter(copy=True):
        if hasattr(z.v, "unknownAttributes"):
            if z.v.unknownAttributes.has_key("junit_test"):
                jtests.append(z)

    interface = startupServer()
    for z in jtests:

        code = writeNodeIntoString(c, z)
        ok = isStringCompilable(code)
        if ok == False:
            g.es("%s not valid Python" % z.headString())
            z.setBackground(java.awt.Color.YELLOW)
            continue

        interface.reset()
        interface.addTest(code)
        interface.runTests()
        failures = interface.getFailures()

        testResultColorization(z, failures)
    interface.shutdown()
コード例 #4
0
 def label_to_subnode(self,event=None):
     """
     Convert a label of the current node to a subnode.
     """
     title = "Creating subnode"
     label_text = "Existing labels (on this node)"
     
     p = self.c.currentPosition()
     labels = self.get_labels_dict(p)
     
     if labels is None:
         g.es("No labels defined for this node")
         return
     
     labelnames = labels.keys()
     labelnames.sort()
     root = self.c.frame.outerFrame
     widget = Pmw_combobox(root, title = title, label_text = label_text, scrolledlist_items = labelnames)
     result = widget.doit()
     if result == 'Cancel':
         return
     labelname = widget.dialog.get()
     g.es("Create subnode for label %s" % labelname)
     
     self.insert_node_for_label_as_child(p=p,labelname=labelname,labelcontent=labels[labelname])
コード例 #5
0
def applyConfiguration(c):
    """Called when the user presses the "Apply" button on the Properties form.
 
    Default: behave like the previous plugin.
    """
    def getboolean(name):
        value = getattr(config, name)
        newvalue = c.config.getBool(name)
        if newvalue is not None:
            setattr(config, name, newvalue)

    getboolean("rst2file")
    getboolean("rst2_bodyfilter")
    getboolean("rst2_clear_attributes")
    getboolean("rst2_http_server_support")
    if config.rst2_http_server_support and not mod_http:
        g.es(
            "Resetting rst2_http_server_support because mod_http plugin was not imported successfully",
            color='red')
        config.rst2_http_server_support = False
    getboolean("rst2_pure_document")
    getboolean("rst2_format_headlines")
    # getboolean("rst2_warnofdrags")
    getboolean("rst2_run_on_window_open")

    getboolean("rst2_debug_handle_endtag")
    getboolean("rst2_debug_store_lines")
    getboolean("rst2_debug_handle_starttag")
    getboolean("rst2_debug_show_unknownattributes")
    getboolean("rst2_debug_node_html_1")
    getboolean("rst2_debug_anchors")
    getboolean("rst2_debug_before_and_after_replacement")
    getboolean("rst2_install_menu_item_in_edit_menu")
コード例 #6
0
 def onDblClick(self):
     """Double click an item in the list"""
     sels = self.box.getcurselection()
     if len(sels) == 0:
         g.es('No selection')
     else:
         g.es('DoubleClick:', sels[0])
コード例 #7
0
 def onDblClick(self):
     """Double click an item in the list"""
     sels = self.box.getcurselection()
     if len(sels) == 0:
         g.es('No selection')
     else:
         g.es('DoubleClick:', sels[0]) 
コード例 #8
0
    def getRequiredModules(self, plugin_collection):
        """Determine which modules are also required by this plugin
        
        We check for,
         - importing Tk and PMW
         - other plugins which are imported (using plugin_collection)
         - a __plugin_requires__ definition
         
        """
        requires = []
        #@    << Check UI toolkits >>
        #@+node:pap.20041009230050:<< Check UI toolkits >>
        #@@c
        # Check for UI toolkits
        if self.hasImport(self.text, "Tkinter"):
            requires.append("Tkinter")

        if self.hasImport(self.text, "Pmw"):
            requires.append("Pmw")
        #@nonl
        #@-node:pap.20041009230050:<< Check UI toolkits >>
        #@nl
        #@    << Check other plugins >>
        #@+node:pap.20041009230652:<< Check other plugins >>
        #@@c
        # Check for importing other plugin files

        imports = self.getPatterns(self.text, "import (\w+)") + \
                  self.getPatterns(self.text, "from (\w+) import")

        for module_name in imports:
            if module_name in plugin_collection and module_name <> self.name:
                requires.append(module_name)

        #@nonl
        #@-node:pap.20041009230652:<< Check other plugins >>
        #@nl
        #@    << Directives >>
        #@+node:pap.20041009230953:<< Directives >>
        #@@c
        # Look for __plugin_requires__ directive

        directive_text = self.getPattern(self.text,
                                         r'__plugin_requires__\s*=\s*(.*?)$',
                                         "[]")

        try:
            directive = eval(directive_text)
        except:
            g.es("__plugin_requires__ not understood for %s: '%s'" %
                 (self.name, directive_text))
        else:
            if isinstance(directive, (str, unicode)):
                requires.append(directive)
            else:
                requires.extend(directive)
        #@nonl
        #@-node:pap.20041009230953:<< Directives >>
        #@nl
        self.requires = sets.Set(requires)
コード例 #9
0
 def writeOpmlCommand (self,event=None):
     
     '''Save a Leo outline to an OPMLfile.'''
     
     c = self.c
     
     if g.app.disableSave:
         g.es("Save commands disabled",color="purple")
         return
 
     # Make sure we never pass None to the ctor.
     if not c.mFileName:
         c.frame.title = ""
         
     initialfile = g.ensure_extension(c.mFileName, ".opml")
 
     # set local fileName, _not_ c.mFileName
     fileName = g.app.gui.runSaveFileDialog(
         initialfile = initialfile,
         title="Write OPML",
         filetypes=[("OPML files", "*.opml")],
         defaultextension=".opml")
     c.bringToFront()
 
     if fileName:
         fileName = g.ensure_extension(fileName, ".opml")
         c.opmlCommands.writeFile(fileName)
コード例 #10
0
ファイル: gtkDialogs.py プロジェクト: AG4GitHub/leo
def callGtkDialogs(data, path='runGtkDialogs.py.txt'):

    data = pickle.dumps(data)

    path = g.os_path_abspath(
        g.os_path_join(g.app.loadDir, '..', 'plugins', path))

    command = [pythoncommand or 'python', path, data]

    try:
        o = Popen(command, stdout=PIPE)

        o.wait()
        ok = True
    except:

        ok = False

    if not ok:
        g.es('error running gtk file chooser\nreverting to tk dialogs',
             color='red')
        return False, None

    data = o.communicate()[0].rstrip()

    ret = o.returncode

    if ret or not data:
        return True, None

    return True, pickle.loads(data)
コード例 #11
0
def addNodesDirectoryToSvn( c ):
    p = c.currentPosition()
    
    if p.isAtThinFileNode():
        p = c.currentPosition()
        path, base = getPathAndBase( p )
        try:
            print path
            ws = utilsvn.SVNUtil.createWorkspace( path, 0)
            wspath = utilsvn.SVNUtil.getWorkspacePath( ws, path)
            if len(java.lang.String( wspath).trim() ) == 0:
                wspath = None
            svn = getRepositoryLocation( p )
            if svn == None:
                g.es( "Could not find @svn directive")
                return
            location = getRepository( svn )
            if location == None:
                g.es( "Could not connect to repository")
                return
            
            loc = location.toString()
            f = java.io.File( path)
            token = ' / '
            token = token.strip()
            nstring = loc + token + f.getName()
            nlocation =  svnio.SVNRepositoryLocation.parseURL( nstring)
            ws.commit( nlocation, wspath, "HI THERE!" )
                    
        except java.lang.Exception, x: 
            
            x.printStackTrace()
            return
コード例 #12
0
def importCiscoConfig(c):

    if not c or not c.exists: return
    current = c.currentPosition()
    #@    << open file >>
    #@+node:edream.110203113231.673:<< open file >>
    name = tkFileDialog.askopenfilename(
        title="Import Cisco Configuration File",
        filetypes=[("All files", "*")]
        )
    if name == "":	return

    p = current.insertAsNthChild(0)
    c.beginUpdate()
    c.setHeadString(p,"cisco config: %s" % name)
    c.endUpdate()

    try:
        fh = open(name)
        g.es("importing: %s" % name)
        linelist = fh.read().splitlines()
        fh.close()
    except IOError,msg:
        g.es("error reading %s: %s" % (name, msg))
        return
コード例 #13
0
    def setNode(self, p):

        #print "SETTING NODE!!! %s" % t
        #print "FILEINDEX %s" % t.fileIndex
        #java.lang.Thread.dumpStack()
        v = p.v
        t = v.t
        #vid = v.vid

        if self.tnode:
            self.checksums[self.tnode] = md5.md5(
                self.tnode.bodyString).hexdigest()

        #if self.undoers.containsKey( t ):
        if self.undoers.has_key(v):
            #print "CONTAINTS %s" % t
            ua = self.undoers[v]
            print "--!!!!!!-- %s" % v
            print ua.__class__
            if ua.__class__ == leoSwingUndo.UndoBase:
                self.umanager = self.undoers[v]
                #if self.checksums.containsKey( v ):
                #    checksum = self.checksums[ v ]
                #    amd5 = md5.md5( t.bodyString )
                #    if amd5.hexdigest() != checksum:
                #        self.umanager.discardAllEdits()
                #        g.es( "Emptied undoer for %s:%s because of checksum mismatch" % ( t.headString, t ), color = "red" )
                #        #self.tnode = t
                #        #return
                #for z in self.umanager.undostack:
                #    commanders[ z ] = self.c
            else:
                print "UNPICKLING!!!!!"
                ua = cPickle.loads(ua)
                print "UNPICKLED Is now %s %s" % (ua, len(ua.undostack))
                self.undoers[v] = ua
                self.umanager = ua
            if self.checksums.containsKey(t):
                checksum = self.checksums[t]
                amd5 = md5.md5(t.bodyString)
                if amd5.hexdigest() != checksum:
                    self.umanager.discardAllEdits()
                    print "DISCARDED EDITSS!!!!"
                    g.es(
                        "Emptied undoer for %s:%s because of checksum mismatch"
                        % (t.headString, t),
                        color="red")
                    #self.tnode = t
                    #return
            for z in self.umanager.undostack:
                commanders[z] = self.c

        else:
            print "V not in Undoers %s" % v
            #print v.vid
            self.umanager = leoSwingUndo.UndoBase()
            self.undoers[v] = self.umanager

        self.tnode = t
        self.setMenu()
コード例 #14
0
def loadConfig():
    '''Loads Emacs extensions and new keystrokes to be added to Emacs instances'''
    pth = os.path.split(g.app.loadDir)   
    aini = pth[0]+r"/plugins/usetemacs.ini"
    if os.path.exists( aini ):
        
        cp = ConfigParser.ConfigParser()
        cp.read( aini )
        section = None
        for z in cp.sections():
            if z.strip() == 'extensions':
                section = z
                break
        
        if section:
            for z in cp.options( section ):
                extension = cp.get( section, z )
                try:
                    ex = __import__( extension )
                    extensions.append( ex )
                except Exception, x:
                    g.es( "Could not load %s because of %s" % ( extension, x ), color = 'red' )
                
        kstroke_sec = None
        for z in cp.sections():
            if z.strip() == 'newkeystrokes':
                kstroke_sec = z
                break
        if kstroke_sec:
            for z in cp.options( kstroke_sec ):
                new_keystrokes[ z.capitalize() ] = cp.get( kstroke_sec, z )
コード例 #15
0
def CloseProcess(c):

    global RunNode,ExitCode,WorkDir
    global In,OutThread,ErrThread

    # Close file and get error code.
    In.close()
    OutThread.File.close()
    ExitCode = ErrThread.File.close()

    # Unmark the node and reset it.
    RunNode.clearMarked()
    RunNode = None

    # Reset the working dir.
    if WorkDir != None:
        os.chdir(WorkDir)
        WorkDir = None

    # Write exit code.
    if ExitCode is None:
        g.es("@run done",color="blue")
    else:
        g.es("@run exits with code: %s" % (str(ExitCode)),color="red")	

    # Redraw.
    c.redraw()
コード例 #16
0
ファイル: leo.py プロジェクト: prodigeni/leo-editor-contrib
def createFrame (fileName):
    
    """Create a LeoFrame during Leo's startup process."""
    
    import leoGlobals as g
    #import java
    #import java.util.concurrent as concur
    # g.trace(g.app.tkEncoding,fileName)

    # Try to create a frame for the file.
    #class CreateCommander( concur.Callable ):
        
    #    def call( self ):
    if fileName:
        if g.os_path_exists(fileName):
            ok, frame = g.openWithFileName(fileName,None)
            if ok:
                return frame.c,frame
    
            # Create a new frame & indicate it is the startup window.
    c,frame = g.app.gui.newLeoCommanderAndFrame(fileName=fileName)
    frame.setInitialWindowGeometry()
    frame.startupWindow = True
    #        return c, frame
            
    #ft = concur.FutureTask( CreateCommander() )
    #java.awt.EventQueue.invokeAndWait( ft )
    #c,frame = ft.get()
    
    # Report the failure to open the file.
    if fileName:
        g.es("File not found: " + fileName)

    return c,frame
コード例 #17
0
ファイル: leo.py プロジェクト: prodigeni/leo-editor-contrib
def getBatchScript ():
    
    import leoGlobals as g
    
    name = None ; i = 1 # Skip the dummy first arg.
    while i + 1 < len(sys.argv):
        arg = sys.argv[i].strip().lower()
        if arg in ("--script","-script"):
            name = sys.argv[i+1].strip() ; break
        i += 1

    if not name:
        return None
    name = g.os_path_join(g.app.loadDir,name)
    try:
        f = None
        try:
            f = open(name,'r')
            script = f.read()
            # g.trace("script",script)
        except IOError:
            g.es("can not open script file: " + name, color="red")
            script = None
    finally:
        if f: f.close()
        return script
コード例 #18
0
def loadConfig():
    '''Loads Emacs extensions and new keystrokes to be added to Emacs instances'''
    pth = os.path.split(g.app.loadDir)
    aini = pth[0] + r"/plugins/usetemacs.ini"
    if os.path.exists(aini):

        cp = ConfigParser.ConfigParser()
        cp.read(aini)
        section = None
        for z in cp.sections():
            if z.strip() == 'extensions':
                section = z
                break

        if section:
            for z in cp.options(section):
                extension = cp.get(section, z)
                try:
                    ex = __import__(extension)
                    extensions.append(ex)
                except Exception, x:
                    g.es("Could not load %s because of %s" % (extension, x),
                         color='red')

        kstroke_sec = None
        for z in cp.sections():
            if z.strip() == 'newkeystrokes':
                kstroke_sec = z
                break
        if kstroke_sec:
            for z in cp.options(kstroke_sec):
                new_keystrokes[z.capitalize()] = cp.get(kstroke_sec, z)
コード例 #19
0
def popupMessage(message):

    '''Pops up a message when the time comes'''

    if 0: # Hangs.  Not sure why.
        g.es("You've Got a Message",color='blue')
        g.es(message)
    else:
        dialog = Tk.Toplevel()
        dialog.title("You've Got a Message!")
        #@        << define close callback >>
        #@+node:ekr.20040331155341:<< define close callback >>
        def close(dialog=dialog):

            dialog.withdraw()
            dialog.destroy()
        #@nonl
        #@-node:ekr.20040331155341:<< define close callback >>
        #@nl
        l = Tk.Label(dialog,text=message,background='white')
        l.pack()
        b = Tk.Button(dialog,text='Close',command=close)
        b.pack()
        sh = dialog.winfo_screenheight()/4
        sw = dialog.winfo_screenwidth()/4
        dialog.geometry(str(525)+"x"+str(400)+"+"+str(sw)+"+"+str(sh))
コード例 #20
0
    def moveCurrentNodeToTarget(self):

        '''Move the current position to the last child of self.target.'''

        c = self.c
        p = c.currentPosition()
        p2 = self.target
        u = c.undoer

        if not c.positionExists(p2):
            for z in c.allNodes_iter():
                if z.v == p:
                    p2 = z
                    break
            else:
                g.es('Target no longer exists: %s' % self.targetHeadString,color='red')
                return

        if p.v.t == p2.v.t or not self.checkMove(p,p2):
            g.es('Invalid move: %s' % (self.targetHeadString),color='red')
            return

        c.beginUpdate()
        try:
            bunch = c.undoer.beforeMoveNode(p)
            p2.expand()
            nxt = p.visNext(c) or p.visBack(c)
            if self.first:  p.moveToFirstChildOf(p2)
            else:           p.moveToLastChildOf(p2)
            c.selectPosition(nxt)
            c.undoer.afterMoveNode(p,'Quick Move', bunch)
        finally:
            c.endUpdate()
コード例 #21
0
def createFrame (fileName,relativeFileName):

    """Create a LeoFrame during Leo's startup process."""

    import leoGlobals as g

    # Try to create a frame for the file.
    if fileName and g.os_path_exists(fileName):
        ok, frame = g.openWithFileName(relativeFileName or fileName,None)
        if ok: return frame.c,frame

    # Create a _new_ frame & indicate it is the startup window.
    c,frame = g.app.newLeoCommanderAndFrame(
        fileName=fileName,
        relativeFileName=relativeFileName,
        initEditCommanders=True)
    frame.setInitialWindowGeometry()
    frame.resizePanesToRatio(frame.ratio,frame.secondary_ratio)
    frame.startupWindow = True
    if frame.c.chapterController:
        frame.c.chapterController.finishCreate()
        frame.c.setChanged(False) # Clear the changed flag set when creating the @chapters node.
    # Call the 'new' hook for compatibility with plugins.
    g.doHook("new",old_c=None,c=c,new_c=c)

    # Report the failure to open the file.
    if fileName:
        g.es("File not found:",fileName)

    return c,frame
コード例 #22
0
    def findNext(self, initFlag=True):

        c = self.c
        if not self.checkArgs():
            return

        if initFlag:
            self.initInHeadline()
            data = self.save()
            self.initInteractiveCommands()
        else:
            data = self.save()

        c.beginUpdate()
        pos, newpos = self.findNextMatch()
        c.endUpdate(
            False)  # Inhibit redraws so that headline remains selected.

        if pos:
            self.showSuccess(pos, newpos)
        else:
            if self.wrapping:
                g.es("end of wrapped search")
            else:
                g.es("not found: " + "'" + self.find_text + "'")
            self.restore(data)
コード例 #23
0
def onSelect (tag,keywords):

    new_v = keywords.get("new_v")
    h = new_v.headString()
    if h[:7] == "@image ":
        filename = h[7:]
        #@        << Select Image >>
        #@+node:EKR.20040517080555.29:<< Select Image >>
        # Display the image file in the text pane, if you can find the file
        a = g.app
        c = keywords.get("c")
        if not c: return

        body = c.frame.body

        if os.path.isfile(filename):
            try:
                # Note that Tkinter only understands GIF
                photo = Tk.PhotoImage(master=a.root, file=filename)
            except:
                g.es("error: cannot load image")
                return
            # Nicely display the image at the center top and push the text below.
            a.gsphoto = photo # This is soooo important.
            photoWidth = photo.width()
            bodyWidth = body.bodyCtrl.winfo_width()
            padding = int((bodyWidth - photoWidth - 16) / 2)
            padding = max(0,padding)
            a.gsimage = body.bodyCtrl.image_create("1.0",image=photo,padx=padding)
        else:
            g.es("warning: missing image file")
コード例 #24
0
def onUnselect (tag,keywords):

    a = g.app
    c = keywords.get("c")
    if not c: return

    old_v = keywords.get("old_v")

    if old_v:
        h = old_v.headString()
        if h[:7] == "@image ":
            #@            << Unselect Image >>
            #@+node:EKR.20040517080555.31:<< Unselect Image >>
            # Erase image if it was previously displayed
            if a.gsimage:
                try:
                     c.frame.body.bodyCtrl.delete(a.gsimage)
                except:
                    g.es("info: no image to erase")

            # And forget about it
            a.gsimage = None
            a.gsphoto = None
            #@-node:EKR.20040517080555.31:<< Unselect Image >>
            #@nl
    else: # Leo is initializing.
        a.gsphoto = None # Holds our photo file
        a.gsimage = None # Holds our image instance within the text pane
コード例 #25
0
        def setDefaultIcon(self):

            """Set the icon to be used in all Leo windows.

            This code does nothing for Tk versions before 8.4.3."""

            gui = self

            try:
                version = gui.root.getvar("tk_patchLevel")
                # g.trace(repr(version),g.CheckVersion(version,"8.4.3"))
                if g.CheckVersion(version,"8.4.3") and sys.platform == "win32":

                    # gtk 8.4.3 or greater: load a 16 by 16 icon.
                    path = g.os_path_join(g.app.loadDir,"..","Icons")
                    if g.os_path_exists(path):
                        theFile = g.os_path_join(path,"LeoApp16.ico")
                        if g.os_path_exists(path):
                            self.bitmap = gtk.BitmapImage(theFile)
                        else:
                            g.es("LeoApp16.ico not in Icons directory", color="red")
                    else:
                        g.es("Icons directory not found: "+path, color="red")
            except:
                print "exception setting bitmap"
                import traceback ; traceback.print_exc()
コード例 #26
0
    def changeAll(self):

        c = self.c
        st = self.s_ctrl
        gui = g.app.gui
        if not self.checkArgs():
            return
        self.initInHeadline()
        data = self.save()
        self.initBatchCommands()
        count = 0
        c.beginUpdate()
        while 1:
            pos1, pos2 = self.findNextMatch()
            if pos1:
                count += 1
                self.batchChange(pos1, pos2, count)
                line = gui.getLineContainingIndex(st, pos1)
                self.printLine(line, allFlag=True)
            else:
                break
        c.endUpdate()
        # Make sure the headline and body text are updated.
        v = c.currentVnode()
        c.frame.tree.onHeadChanged(v)
        c.frame.body.onBodyChanged(v, "Can't Undo")
        if count > 0:
            # A change was made.  Tag the end of the Change All command.
            c.undoer.setUndoParams("Change All", v)
        g.es("changed: ", count)
        self.restore(data)
コード例 #27
0
 def marks_to_label(self,event=None):
     """
     Convert the existing marks to a label.
     """
     title = "show labels"
 
     labellist = self.collect_labels()
     root = self.c.frame.outerFrame
     widget = Pmw_combobox(root, title = title, label_text = 'Existing labels', scrolledlist_items = labellist)
     result = widget.doit()
     if result == 'Cancel':
         return
     labelname = widget.dialog.get()
     g.es("Convert the existing marks to label %s" % labelname)
     #  markedBit = self.c.rootVnode().__class__.markedBit
     for p in self.c.allNodes_iter():
         if p.isMarked():
             # if (v.statusBits & markedBit ) != 0:
             labels_dict = self.get_labels_dict(p)
             if labels_dict is None:
                 labels_dict = {}
             # do nothing if the node already has such a label.
             if not labels_dict.has_key(labelname):
                 labels_dict[labelname] = ''
                 self.set_labels_dict(p, labels_dict)
                 p.setDirty()
コード例 #28
0
def shellScriptInWindow(c,script):

    if sys.platform == 'darwin':
        #@        << write script to temporary MacOS file >>
        #@+node:ekr.20040915105758.22:<< write script to temporary MacOS file >>
        handle, path = tempfile.mkstemp(text=True)
        directory = c.frame.openDirectory
        script = ("cd %s\n" % directory) + script + '\n' + ("rm -f %s\n" % path)
        os.write(handle, script)
        os.close(handle)
        os.chmod(path, 0700)
        #@nonl
        #@-node:ekr.20040915105758.22:<< write script to temporary MacOS file >>
        #@nl
        os.system("open -a /Applications/Utilities/Terminal.app " + path)

    elif sys.platform == 'win32':
        g.es("shellScriptInWindow not ready for Windows",color='red')

    else:
        #@        << write script to temporary Unix file >>
        #@+node:ekr.20040915105758.25:<< write script to temporary Unix file >>
        handle, path = tempfile.mkstemp(text=True)
        directory = c.frame.openDirectory
        script = ("cd %s\n" % directory) + script + '\n' + ("rm -f %s\n" % path)
        os.write(handle, script)
        os.close(handle)
        os.chmod(path, 0700)
        #@nonl
        #@-node:ekr.20040915105758.25:<< write script to temporary Unix file >>
        #@nl
        os.system("xterm -e sh  " + path)
コード例 #29
0
def openForRead (self,filename,rb):
    """
    Replaces the standard open for reads.
    Checks and handles shadow files:
        if the length of the real file is zero:
            update the real file from the shadow file.
        else:
            update the shadow file from the real file.
    """
    try:
        dir, simplename = os.path.split(filename)
        shadow_filename = os.path.join(dir,shadow_subdir,prefix + simplename)
        if os.path.exists(shadow_filename):
            file_to_read_from = shadow_filename 
            if os.path.exists(filename)and os.path.getsize(filename)<=2:
                if verbosity >= 2:
                    g.es("Copy %s to %s without sentinels"%(shadow_filename,filename))
                push_file(sourcefilename=shadow_filename,targetfilename=filename)
            else:
                sq = sentinel_squasher()
                if verbosity >= 2:
                    g.es("reading in shadow directory %s"% shadow_subdir,color="orange")
                sq.pull_source(sourcefile=shadow_filename,targetfile=filename)
        else:
            file_to_read_from = filename 
        return open(file_to_read_from,'rb')
    except:
        # Make sure failures to open a file generate clear messages.
        g.es_exception()
        raise 
コード例 #30
0
 def putUa (self,torv,key,val):
     
     '''Put attribute whose name is key and value is val to the output stream.'''
     
     # New in 4.3: leave string attributes starting with 'str_' alone.
     if key.startswith('str_'):
         if type(val) == type(''):
             attr = ' %s="%s"' % (key,self.xmlEscape(val))
             self.put(attr)
         else:
             g.es("ignoring non-string attribute %s in %s" % (
                 key,torv),color="blue")
         return
     try:
         try:
             # Protocol argument is new in Python 2.3
             # Use protocol 1 for compatibility with bin.
             s = pickle.dumps(val,protocol=1)
         except TypeError:
             s = pickle.dumps(val,bin=True)
         attr = ' %s="%s"' % (key,binascii.hexlify(s))
         self.put(attr)
 
     except pickle.PicklingError:
         # New in 4.2 beta 1: keep going after error.
         g.es("ignoring non-pickleable attribute %s in %s" % (
             key,torv),color="blue")
コード例 #31
0
def openForWrite (self, filename, wb):
    """
    Replaces the standard open for writes:
        - Check if filename designates a file
          which has a shadow file.
          If so, write to the shadow file,
          and update the real file after the close.
    """
    c = self.c
    shadow_subdir = c.config.getString('shadow_subdir') or shadow_subdir_default
    shadow_prefix = c.config.getString('shadow_prefix') or shadow_prefix_default
    shadow_verbosity = getVerbosity(c)
    dir, simplename = os.path.split(filename)
    rootname, ext = os.path.splitext(simplename)
    assert ext=='.tmp'
    shadow_filename = os.path.join(dir,shadow_subdir, shadow_prefix + rootname)
    self.writing_to_shadow_directory = os.path.exists(shadow_filename)
    if self.writing_to_shadow_directory:
        self.shadow_filename = shadow_filename 
        if shadow_verbosity >= 2: 
            g.es("Using shadow file in folder %s" % shadow_subdir,color="orange")
        file_to_use = os.path.join(dir,shadow_subdir,shadow_prefix + simplename)
    else:
        file_to_use = filename 
    return open(file_to_use,'wb')
コード例 #32
0
 def redo (self):
 
     u = self ; c = u.c
     if not u.canRedo(): return
     if not u.getBead(u.bead+1): return
     if not  c.currentPosition(): return
     # g.trace(u.bead+1,len(u.beads),u.peekBead(u.bead+1))
 
     u.redoing = True 
     u.redrawFlag = True
     u.updateSetChangedFlag = True
     
     c.beginUpdate()
     if 1: # update...
         try:
             func = u.redoDispatchDict[u.undoType]
         except KeyError:
             s = "Unknown redo key: %s" % u.undoType
             g.trace(s) ; g.es(s, color="red")
             func = None
         if func:
             func()
             if u.updateSetChangedFlag:
                 c.setChanged(True)
                 if u.p: u.p.setDirty(setDescendentsDirty=False)
     c.endUpdate(u.redrawFlag)
 
     u.redoing = False
     u.bead += 1
     u.setUndoTypes()
コード例 #33
0
 def undo (self):
 
     """Undo the operation described by the undo parmaters."""
     
     u = self ; c = u.c
     if not u.canUndo(): return
     if not u.getBead(u.bead): return
     if not c.currentPosition(): return
     # g.trace(len(u.beads),u.bead,u.peekBead(u.bead))
 
     c.endEditing()# Make sure we capture the headline for a redo.
     u.undoing = True
     u.redrawFlag = True
     u.updateSetChangedFlag = True
 
     c.beginUpdate()
     if 1: # update...
         try:
             func = u.undoDispatchDict[u.undoType]
         except KeyError:
             s = "Unknown undo key: %s" % u.undoType
             g.trace(s) ; g.es(s, color="red")
             func = None
         if func:
             func()
             if u.updateSetChangedFlag:
                 c.setChanged(True)
                 if u.p: u.p.setDirty(setDescendentsDirty=False)
     c.endUpdate(u.redrawFlag)
 
     u.undoing = False
     u.bead -= 1
     u.setUndoTypes()
コード例 #34
0
 def changeAll(self):
 
     c = self.c ; u = c.undoer ; undoType = 'Change All'
     current = c.currentPosition()
     st = self.s_ctrl ; gui = g.app.gui
     if not self.checkArgs(): return
     self.initInHeadline()
     saveData = self.save()
     self.initBatchCommands()
     count = 0
     c.beginUpdate()
     try: # In update...
         u.beforeChangeGroup(current,undoType)
         while 1:
             pos1, pos2 = self.findNextMatch()
             if not pos1: break
             count += 1
             self.batchChange(pos1,pos2)
             line = gui.getLineContainingIndex(st,pos1)
             self.printLine(line,allFlag=True)
         p = c.currentPosition()
         u.afterChangeGroup(p,undoType,reportFlag=True)
         g.es("changed: %d instances" % (count))
     finally:
         c.endUpdate()
         self.restore(saveData)
コード例 #35
0
def WriteTreeAsAsc(vnode, ascFileN):
    'Writes the tree under vnode to the file ascFile'
    def CleanUp():
        'Cleanup on exit'
        ascFile.close()

    writeNodeReturnValue = None
    startinglevel = vnode.level()
    try:
        ascFile = file(ascFileN,'w')
    except IOError:
        g.es("Could not open output file: %s" % ascFileN)
        return
    stopHere = vnode.nodeAfterTree()
    v = vnode
    while v != stopHere:
        writeNodeReturnValue = WriteNode(v, startinglevel, ascFile)
        if  writeNodeReturnValue == CV.END_PROGRAM:
            CleanUp()
            return
        elif  writeNodeReturnValue == CV.NODE_IGNORE:
            v = v.nodeAfterTree()       # ran into an @ascignore
        else:
            v = v.threadNext()

    CleanUp()
    g.es('Wrote: '+`ascFileN`)
コード例 #36
0
def sync_node_to_folder(c,parent,d):

    oldlist = {}
    newlist = []
    #get children info
    v = parent
    after_v = parent.nodeAfterTree()
    while v != after_v:
        if not v.hasChildren():
            oldlist[v.headString()] = v.bodyString()
        v = v.threadNext()
    #compare folder content to children
    for name in os.listdir(d):
        if name in oldlist:
            del oldlist[name]
        else:
            newlist.append(name)
    #insert newlist
    newlist.sort()
    newlist.reverse()
    for name in newlist:
        v = parent.insertAsNthChild(0)
        c.setHeadString(v,name)
        v.setMarked()
    #warn for orphan oldlist
    if len(oldlist)>0:
        g.es('missing: '+','.join(oldlist.keys()))
コード例 #37
0
 def adjust_ivars (self):
     
     '''New in 4.3.
     
     Adjust ivars, particularly the find and change text.
     This is called just before executing a command and
     just after calling update_ivars.
     
     Plugins may replace this code as desired.'''
     
     if 0:
         # The TkFind class now removes tailing newlines.
     
         ft = self.find_text
         if not ft: return
     
         # Remove a trailing newline unless that is all there is.
         if len(ft) > 1 and ft[-1] in ('\n','\r'):
             ft = ft[:-1]
             self.adjust_find_text(ft)
             if 0:
                 g.es('before:',repr(self.find_text))
                 g.es(' after:',repr(ft))
             self.find_text = ft
     
         return
コード例 #38
0
    def setDefaultIcon(self):
        """Set the icon to be used in all Leo windows.
        
        This code does nothing for Tk versions before 8.4.3."""

        gui = self

        try:
            version = gui.root.getvar("tk_patchLevel")
            if g.CheckVersion(version,
                              "8.4.3") and sys.platform == "win32":  # 12/2/03
                # tk 8.4.3 or greater: load a 16 by 16 icon.
                path = g.os_path_join(g.app.loadDir, "..", "Icons")
                if g.os_path_exists(path):
                    theFile = g.os_path_join(path, "LeoApp16.ico")
                    if g.os_path_exists(path):
                        self.bitmap = Tk.BitmapImage(theFile)
                    else:
                        g.es("LeoApp16.ico not in Icons directory",
                             color="red")
                else:
                    g.es("Icons directory not found: " + path, color="red")
        except:
            print "exception setting bitmap"
            import traceback
            traceback.print_exc()
コード例 #39
0
def replaceTargetFileIfDifferent (self):
    
    # Check if we are dealing with a shadow file
    try:
        targetFileName = self.targetFileName 
        outputFileName = self.outputFileName 
        if self.writing_to_shadow_directory:
            self.targetFileName = self.shadow_filename 
            self.outputFileName = self.shadow_filename+'.tmp'
        if original_replaceTargetFileIfDifferent(self):
            # Original_replaceTargetFileIfDifferent should be oblivious
            # to the existance of the shadow directory.
            if self.writing_to_shadow_directory:
                if verbosity >= 2:
                    g.es("Updating file from shadow folder %s" % shadow_subdir,color='orange')
                push_file(self.shadow_filename,targetFileName)

    finally:
        if self.writing_to_shadow_directory:
            assert self.targetFileName == self.shadow_filename 
            assert self.outputFileName == self.shadow_filename+'.tmp'
        else:
            assert self.targetFileName == targetFileName
            assert self.outputFileName == outputFileName
            # We need to check what's going on if the targetFileName or the outputFileName is changed.
        
        # Not sure if this finally clause is needed or not
        self.targetFileName = targetFileName
        self.outputFileName = outputFileName 
コード例 #40
0
 def check_lines_for_equality (self,lines1,lines2,message,lines1_message,lines2_message):
    """
    Little helper function to get nice output if something goes wrong.
    """
    if lines1==lines2:
       return 
    print "================================="
    print message 
    print "================================="
    print lines1_message 
    print "---------------------------------"
    f1 = file("mod_shadow.tmp1", "w")
    for line in lines1:
       print line, 
       f1.write(line)
    f1.close()
    print "=================================="
    print lines2_message 
    print "---------------------------------"
    f1 = file("mod_shadow.tmp2", "w")
    for line in lines2:
       print line, 
       f1.write(line)
    f1.close()
    g.es("'push' did not re-create the output file; please check mod_shadow.tmp1 and mod_shadow.tmp2 for differences")
コード例 #41
0
def processDocumentNode( c ):
    '''this executes the stylesheet node against the current node'''
    try:
        if not styleNodeSelected( c ): return
        proc = Processor()
        stylenode = stylenodes[ c ]
        pos = c.currentPosition()
        c.beginUpdate()
        c.selectPosition( stylenode )
        sIO = getString( c )
        mdom1 = minidom.parseString( sIO )
        sIO = str( mdom1.toxml() )
        hstring = str( stylenode.headString() )
        if hstring == "": hstring = "no headline"
        stylesource = InputSource.DefaultFactory.fromString( sIO, uri = hstring)
        proc.appendStylesheet( stylesource )
        c.selectPosition( pos )
        xmlnode = pos.v.t
        xIO = getString( c )
        mdom2 = minidom.parseString( xIO )
        xIO = str( mdom2.toxml())
        xhead = str( xmlnode.headString )
        if xhead == "": xhead = "no headline"
        xmlsource = InputSource.DefaultFactory.fromString( xIO, uri = xhead ) 
        result = proc.run( xmlsource )
        nhline = "xsl:transform of " + str( xmlnode.headString )
        tnode = leoNodes.tnode( result, nhline )
        pos.insertAfter( tnode )
        c.endUpdate()
        
    except Exception, x:
        g.es( 'exception ' + str( x ))
コード例 #42
0
def replaceTargetFileIfDifferent (self):

    # Check if we are dealing with a shadow file
    try:
        c = self.c
        targetFileName = self.targetFileName 
        outputFileName = self.outputFileName
        shadow_subdir = c.config.getString('shadow_subdir') or shadow_subdir_default
        shadow_verbosity = getVerbosity(c)
        if self.writing_to_shadow_directory:
            self.targetFileName = self.shadow_filename 
            self.outputFileName = self.shadow_filename+'.tmp'
        if original_replaceTargetFileIfDifferent(self):
            # Original_replaceTargetFileIfDifferent should be oblivious
            # to the existance of the shadow directory.
            if self.writing_to_shadow_directory:
                if shadow_verbosity >= 2:
                    g.es("Updating file from shadow folder %s" % shadow_subdir,color='orange')
                mod_shadow_core.copy_file_removing_sentinels(self.shadow_filename,targetFileName, marker_from_extension)

    finally:
        if self.writing_to_shadow_directory:
            assert self.targetFileName == self.shadow_filename 
            assert self.outputFileName == self.shadow_filename+'.tmp'
        else:
            assert self.targetFileName == targetFileName
            assert self.outputFileName == outputFileName
            # We need to check what's going on if the targetFileName or the outputFileName is changed.

        # Not sure if this finally clause is needed or not
        self.targetFileName = targetFileName
        self.outputFileName = outputFileName 
コード例 #43
0
 def createOpenWithMenuFromTable (self,table):
 
     g.app.openWithTable = table # Override any previous table.
     # Delete the previous entry.
     parent = self.getMenu("File")
     label = self.getRealMenuName("Open &With...")
     amp_index = label.find("&")
     label = label.replace("&","")
     try:
         index = parent.index(label)
         parent.delete(index)
     except:
         try:
             index = parent.index("Open With...")
             parent.delete(index)
         except: return
     # Create the "Open With..." menu.
     openWithMenu = Tk.Menu(parent,tearoff=0)
     self.setMenu("Open With...",openWithMenu)
     parent.insert_cascade(index,label=label,menu=openWithMenu,underline=amp_index)
     # Populate the "Open With..." menu.
     shortcut_table = []
     for triple in table:
         if len(triple) == 3: # 6/22/03
             shortcut_table.append(triple)
         else:
             g.es("createOpenWithMenuFromTable: invalid data",color="red")
             return
             
     # for i in shortcut_table: print i
     self.createMenuItemsFromTable("Open &With...",shortcut_table,openWith=True)
コード例 #44
0
    def onAboutLeoEmail(self, event=None):
        """Handle clicks in the email link in an About Leo dialog."""

        try:
            import webbrowser
            webbrowser.open("mailto:" + self.email)
        except:
            g.es("not found: " + self.email)
コード例 #45
0
    def onAboutLeoUrl(self, event=None):
        """Handle clicks in the url link in an About Leo dialog."""

        try:
            import webbrowser
            webbrowser.open(self.url)
        except:
            g.es("not found: " + self.url)
コード例 #46
0
def loadHandlers():

    """Load all enabled plugins from the plugins directory"""
    
    plugins_path = g.os_path_join(g.app.loadDir,"..","plugins")
    manager_path = g.os_path_join(plugins_path,"pluginsManager.txt")
    
    files = glob.glob(g.os_path_join(plugins_path,"*.py"))
    #print files
    files = [g.os_path_abspath(theFile) for theFile in files]

    #@    << set enabled_files from pluginsManager.txt >>
    #@+node:ekr.20031218072017.3441:<< set enabled_files from pluginsManager.txt >>
    if not g.os_path_exists(manager_path):
        return
        
    # New in 4.3: The first reference to a plugin in pluginsManager.txt controls.
    enabled_files = []
    disabled_files = []
    try:
        theFile = open(manager_path)
        lines = theFile.readlines()
        for s in lines:
            s = s.strip()
            if s:
                if g.match(s,0,"#"):
                    s = s[1:].strip()
                    # Kludge: ignore comment lines containing a blank or not ending in '.py'.
                    if s and s.find(' ') == -1 and s[-3:] == '.py':
                        path = g.os_path_abspath(g.os_path_join(plugins_path,s))
                        if path not in enabled_files and path not in disabled_files:
                            # print 'disabled',path
                            disabled_files.append(path)
                else:
                    #print g.os_path_join( plugins_path, s )
                    path = g.os_path_abspath(g.os_path_join(plugins_path,s))
                    if path not in enabled_files and path not in disabled_files:
                        # print 'enbled',path
                        enabled_files.append(path)
        theFile.close()
    except IOError:
        g.es("Can not open: " + manager_path)
        # Don't import leoTest initially.  It causes problems.
        import leoTest ; leoTest.fail()
        return
        
    #@-node:ekr.20031218072017.3441:<< set enabled_files from pluginsManager.txt >>
    #@nl
    
    # Load plugins in the order they appear in the enabled_files list.
    if files and enabled_files:
        for theFile in enabled_files:
            if theFile in files:
                loadOnePlugin(theFile)
                
    # Note: g.plugin_signon adds module names to g.app.loadedPlugins 
    if g.app.loadedPlugins:
        g.es("%d plugins loaded" % (len(g.app.loadedPlugins)), color="blue")
コード例 #47
0
    def runFindScript(self):

        c = self.c
        try:
            exec self.find_text in {}  # Use {} to get a pristine environment.
        except:
            g.es("exception executing find script")
            g.es_exception(full=False)
            g.app.searchDict["continue"] = False  # 2/1/04
コード例 #48
0
def getWorkspace( path):
    
    try:
        ws = SVNWorkspaceManager.createWorkspace( "file", path)
        ws.addWorkspaceListener( LeoWSListener())
        return ws
    except java.lang.Exception, x:
        x.printStackTrace()
        g.es( "Could not create Workspace %s" % path)
コード例 #49
0
    def createFrame(self):
        """Create the frame for an About Leo dialog."""

        frame = self.frame
        theCopyright = self.copyright
        email = self.email
        url = self.url
        version = self.version

        # Calculate the approximate height & width. (There are bugs in Tk here.)
        lines = string.split(theCopyright, '\n')
        height = len(lines) + 8  # Add lines for version,url,email,spacing.
        width = 0
        for line in lines:
            width = max(width, len(line))
        width = max(width, len(url))
        width += 10  # 9/9/02

        frame.pack(padx=6, pady=4)

        self.text = text = Tk.Text(frame,
                                   height=height,
                                   width=width,
                                   bd=0,
                                   bg=frame.cget("background"))
        text.pack(pady=10)

        try:
            bitmap_name = g.os_path_join(g.app.loadDir, "..", "Icons",
                                         "Leoapp.GIF")  # 5/12/03
            image = Tk.PhotoImage(file=bitmap_name)
            text.image_create("1.0", image=image, padx=10)
        except:
            g.es("exception getting icon")
            g.es_exception()

        text.insert("end", version, "version")
        text.insert("end", theCopyright, "copyright")
        text.insert("end", '\n')
        text.insert("end", url, "url")  # Add "url" tag.
        text.insert("end", '\n')
        text.insert("end", email, "email")  # Add "email" tag.

        text.tag_config("version", justify="center")
        text.tag_config("copyright", justify="center", spacing1="3")

        text.tag_config("url", underline=1, justify="center", spacing1="10")
        text.tag_bind("url", "<Button-1>", self.onAboutLeoUrl)
        text.tag_bind("url", "<Enter>", self.setArrowCursor)
        text.tag_bind("url", "<Leave>", self.setDefaultCursor)

        text.tag_config("email", underline=1, justify="center", spacing1="10")
        text.tag_bind("email", "<Button-1>", self.onAboutLeoEmail)
        text.tag_bind("email", "<Enter>", self.setArrowCursor)
        text.tag_bind("email", "<Leave>", self.setDefaultCursor)

        text.configure(state="disabled")
コード例 #50
0
def getRepository( url ):
    
    repository = None
    try:
        location = svnio.SVNRepositoryLocation.parseURL( url)
        repository = svnio.SVNRepositoryFactory.create( location)
    except java.lang.Exception, x:
        x.printStackTrace
        g.es( "Could not connect to repository %s" % url)
        return None
コード例 #51
0
    def show(self, s):

        # print s
        if self.outputFile:
            self.outputFile.write(s + '\n')
        elif self.c:
            g.es(s)
        else:
            print s
            print
コード例 #52
0
ファイル: leo.py プロジェクト: prodigeni/leo-editor-contrib
def reportDirectories(verbose):
    
    import leoGlobals as g
   
    if verbose:
        for kind,theDir in (
            ("global config",g.app.globalConfigDir),
            ("home",g.app.homeDir),
        ):
            g.es("%s dir: %s" % (kind,theDir),color="blue")
コード例 #53
0
    def runChangeScript(self):

        c = self.c
        try:
            assert (self.script_change)
            exec self.change_text in {
            }  # Use {} to get a pristine environment.
        except:
            g.es("exception executing change script")
            g.es_exception(full=False)
            g.app.searchDict["continue"] = False  # 2/1/04
コード例 #54
0
    def checkArgs(self):

        c = self.c
        val = True
        if not self.search_headline and not self.search_body:
            g.es("not searching headline or body")
            val = False
        if len(self.find_text) == 0:
            g.es("empty find patttern")
            val = False
        return val
コード例 #55
0
 def write( self, *args ):
 
     if len( args)> 1:
         data = args[ 0]
         start = args[ 1]
         length = args[ 2 ]
         s = java.lang.String( data[ start: start + length] )
         if self.is_error == True: 
             
             g.es( s, color = "RED")
         else:
             g.es( s )
コード例 #56
0
    def getExistingVnode(self, tref, headline):

        tref1 = tref
        assert (tref > -1)
        tref = self.canonicalTnodeIndex(tref)
        t = self.tnodesDict.get(tref)
        try:
            return t.vnodeList[0]
        except (IndexError, AttributeError):
            g.es("Missing vnode:", headline, color="red")
            g.es("Probably an outline topology error.")
            # g.trace(tref1,t,t.vnodeList)
            return None
コード例 #57
0
def addTemacsExtensions(Emacs):
    '''Adds extensions to Emacs parameter.'''
    for z in extensions:
        try:
            if hasattr(z, 'getExtensions'):
                ex_meths = z.getExtensions()
                for x in ex_meths.keys():
                    Emacs.extendAltX(x, ex_meths[x])
            else:
                g.es('Module %s does not have a getExtensions function' % z,
                     color='red')
        except Exception, x:
            g.es('Could not add extension because of %s' % x, color='red')
コード例 #58
0
    def loadPlugin(self, p):

        global atPluginNodes

        c = self.c
        tag = "@plugin"
        h = p.headString()
        assert (g.match(h, 0, tag))

        # Get the name of the module.
        theFile = h[len(tag):].strip()
        if theFile[-3:] == ".py":
            theFile = theFile[:-3]
        theFile = g.toUnicode(theFile, g.app.tkEncoding)

        if not atPluginNodes:
            g.es("disabled @plugin: %s" % (theFile), color="blue")
        elif theFile in g.app.loadedPlugins:
            g.es("plugin already loaded: %s" % (theFile), color="blue")
        else:
            plugins_path = g.os_path_join(g.app.loadDir, "..", "plugins")
            theModule = g.importFromPath(theFile,
                                         plugins_path,
                                         pluginName=__name__,
                                         verbose=False)
            if theModule:
                g.es("plugin loaded: %s" % (theFile), color="blue")
                g.app.loadedPlugins.append(theFile)
            else:
                g.es("can not load plugin: %s" % (theFile), color="blue")