Beispiel #1
0
    def update_ivars(self):
        """Called just before doing a find to update ivars from the find panel."""

        for key in self.intKeys:
            val = self.dict[key].get()
            setattr(self, key, val)  # No more _flag hack.
            # g.trace(key,val)

        # Set ivars from radio buttons. Convert these to 1 or 0.
        find_type = self.dict["radio-find-type"].get()
        self.pattern_match = g.choose(find_type == "pattern-search", 1, 0)
        self.script_search = g.choose(find_type == "script-search", 1, 0)

        search_scope = self.dict["radio-search-scope"].get()
        self.suboutline_only = g.choose(search_scope == "suboutline-only", 1,
                                        0)
        self.node_only = g.choose(search_scope == "node-only", 1, 0)
        self.selection = g.choose(search_scope == "selection-only", 1,
                                  0)  # 11/9/03

        s = self.find_ctrl.get("1.0", "end - 1c")  # Remove trailing newline
        s = g.toUnicode(s, g.app.tkEncoding)
        self.find_text = s

        s = self.change_ctrl.get("1.0", "end - 1c")  # Remove trailing newline
        s = g.toUnicode(s, g.app.tkEncoding)
        self.change_text = s
Beispiel #2
0
def computeLoadDir():
    """Returns the directory containing leo.py."""

    import leoGlobals as g

    # g.trace(g.app.tkEncoding)

    try:
        import leo
        path = g.os_path_abspath(leo.__file__)

        if sys.platform == "win32":  # "mbcs" exists only on Windows.
            path = g.toUnicode(path, "mbcs")
        elif sys.platform == "dawwin":
            path = g.toUnicode(path, "utf-8")
        else:
            path = g.toUnicode(path, g.app.tkEncoding)

        if path:
            loadDir = g.os_path_dirname(path)
        else:
            loadDir = None
        if not loadDir:
            loadDir = g.os_path_abspath(os.getcwd())
            print "Using emergency loadDir:", repr(loadDir)

        encoding = g.choose(sys.platform == "dawwin", "utf-8",
                            g.app.tkEncoding)  # 11/18/03
        loadDir = g.toUnicode(loadDir, encoding)  # 10/20/03
        return loadDir
    except:
        print "Exception getting load directory"
        import traceback
        traceback.print_exc()
        return None
 def update_ivars (self):
     
     """Called just before doing a find to update ivars from the find panel."""
 
     for key in self.intKeys:
         val = self.dict[key].get()
         setattr(self, key, val) # No more _flag hack.
         # g.trace(key,val)
 
     # Set ivars from radio buttons. Convert these to 1 or 0.
     find_type = self.dict["radio-find-type"].get()
     self.pattern_match = g.choose(find_type == "pattern-search",1,0)
     self.script_search = g.choose(find_type == "script-search",1,0)
 
     search_scope = self.dict["radio-search-scope"].get()
     self.suboutline_only = g.choose(search_scope == "suboutline-only",1,0)
     self.node_only       = g.choose(search_scope == "node-only",1,0)
     self.selection       = g.choose(search_scope == "selection-only",1,0) # 11/9/03
 
     s = self.find_ctrl.get("1.0","end - 1c") # Remove trailing newline
     s = g.toUnicode(s,g.app.tkEncoding)
     self.find_text = s
 
     s = self.change_ctrl.get("1.0","end - 1c") # Remove trailing newline
     s = g.toUnicode(s,g.app.tkEncoding)
     self.change_text = s
 def update_ivars (self):
     
     """Called just before doing a find to update ivars from the find panel."""
 
     for key in self.intKeys:
         val = self.dict[key].get()
         setattr(self, key, val) # No more _flag hack.
         # g.trace(key,val)
 
     # Set ivars from radio buttons. Convert these to 1 or 0.
     if 0: ###
         find_type = self.dict["radio-find-type"].get()
         self.pattern_match = g.choose(find_type == "pattern-search",1,0)
         self.script_search = g.choose(find_type == "script-search",1,0)
     
     search_scope = self.dict["radio-search-scope"].get()
     self.suboutline_only = g.choose(search_scope == "suboutline-only",1,0)
     self.node_only       = g.choose(search_scope == "node-only",1,0)
     self.selection       = g.choose(search_scope == "selection-only",1,0) # 11/9/03
 
     # New in 4.3: The caller is responsible for removing most trailing cruft.
     # Among other things, this allows Leo to search for a single trailing space.
     s = self.find_ctrl.get("1.0","end")
     s = g.toUnicode(s,g.app.tkEncoding)
     # g.trace(repr(s))
     if s and s[-1] in ('\r','\n'):
         s = s[:-1]
     self.find_text = s
 
     s = self.change_ctrl.get("1.0","end")
     if s and s[-1] in ('\r','\n'):
         s = s[:-1]
     s = g.toUnicode(s,g.app.tkEncoding)
     self.change_text = s
 def getCharAfterIndex (self,t,index):
     
     if t.compare(index + "+1c",">=","end"):
         return None
     else:
         ch = t.get(index + "+1c")
         return g.toUnicode(ch,g.app.tkEncoding)
 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")
Beispiel #7
0
    def update (self,*args,**keys):

        c = self.c

        # This is called at idle-time, and there can be problems when closing the window.
        if g.app.killed or not c or not hasattr(c,'frame'):
            return

        w = c.frame.body.bodyCtrl 
        tab_width = c.frame.tab_width

        s = w.getAllText()
        index = w.getInsertPoint()
        row,col = g.convertPythonIndexToRowCol(s,index)

        if col > 0:
            s2 = s[index-col:index]
            s2 = g.toUnicode(s2,g.app.tkEncoding)
            col = g.computeWidth (s2,c.tab_width)

        if row != self.lastRow or col != self.lastCol:
            s = "line %d, col %d " % (row,col)
            self.label.configure(text=s)
            self.lastRow,self.lastCol = row,col

        if 0: # Done in idle handler.
            self.label.after(500,self.update)
    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")
Beispiel #9
0
 def update (self,*args,**keys):
     
     c = self.c
 
     # This is called at idle-time, and there can be problems when closing the window.
     if g.app.killed or not c or not hasattr(c,'frame'):
         return
 
     body = c.frame.body.bodyCtrl ; gui = g.app.gui
     tab_width = c.frame.tab_width
 
     index = body.index("insert")
     row,col = gui.getindex(body,index)
 
     if col > 0:
         s = body.get("%d.0" % (row),index)
         s = g.toUnicode(s,g.app.tkEncoding)
         col = g.computeWidth(s,tab_width)
 
     if row != self.lastRow or col != self.lastCol:
         s = "line %d, col %d " % (row,col)
         self.label.configure(text=s)
         self.lastRow,self.lastCol = row,col
         
     if 0: # Done in idle handler.
         self.label.after(500,self.update)
Beispiel #10
0
    def getCharAfterIndex(self, t, index):

        if t.compare(index + "+1c", ">=", "end"):
            return None
        else:
            ch = t.get(index + "+1c")
            return g.toUnicode(ch, g.app.tkEncoding)
Beispiel #11
0
    def getAllText(self, t):
        """Return all the text of Tk.Text t converted to unicode."""

        s = t.get("1.0", "end")
        if s is None:
            return u""
        else:
            return g.toUnicode(s, g.app.tkEncoding)
Beispiel #12
0
    def getCharBeforeIndex(self, t, index):

        index = t.index(index)
        if index == "1.0":
            return None
        else:
            ch = t.get(index + "-1c")
            return g.toUnicode(ch, g.app.tkEncoding)
 def getCharBeforeIndex (self,t,index):
     
     index = t.index(index)
     if index == "1.0":
         return None
     else:
         ch = t.get(index + "-1c")
         return g.toUnicode(ch,g.app.tkEncoding)
 def getAllText (self,t):
     
     """Return all the text of Tk.Text t converted to unicode."""
     
     s = t.get("1.0","end")
     if s is None:
         return u""
     else:
         return g.toUnicode(s,g.app.tkEncoding)
 def getSelectedText (self,t):
 
     start, end = self.getTextSelection(t)
     if start and end and start != end:
         s = t.get(start,end)
         if s is None:
             return u""
         else:
             return g.toUnicode(s,g.app.tkEncoding)
     else:
         return u""
Beispiel #16
0
  def select(self,p,updateBeadList=True,scroll=True):
    # TODO Much more here: there's four hooks and all sorts of other things called in the TK version. 

    c = self.c ; frame = c.frame
    body = w = c.frame.body.bodyCtrl

    c.setCurrentPosition(p)

    # This is also where the body-text control is given the text of the selected node...
    # Always do this.  Otherwise there can be problems with trailing hewlines.
    s = g.toUnicode(p.v.t.bodyString,"utf-8")
    w.setAllText(s)
Beispiel #17
0
    def cleanButtonText (self,s):

        '''Clean the text following @button or @command so that it is a valid name of a minibuffer command.'''

        # Strip @...@button.
        while s.startswith('@'):
            s = s[1:]
        if g.match_word(s,0,'button'):
            s = s[6:]
        i = s.find('@key')
        if i != -1:
            s = s[:i].strip()
        if 1: # Not great, but spaces, etc. interfere with tab completion.
            chars = g.toUnicode(string.letters + string.digits,g.app.tkEncoding)
            aList = [g.choose(ch in chars,ch,'-') for ch in g.toUnicode(s,g.app.tkEncoding)]
            s = ''.join(aList)
            s = s.replace('--','-')
        while s.startswith('-'):
            s = s[1:]
        while s.endswith('-'):
            s = s[:-1]
        return s
Beispiel #18
0
def completeFileName (fileName):

    import leoGlobals as g

    if not (fileName and fileName.strip()):
        return None,None

    # This does not depend on config settings.
    try:
        if sys.platform.lower().startswith('win'):
            fileName = g.toUnicode(fileName,'mbcs')
        else:
            fileName = g.toUnicode(fileName,'utf-8')
    except Exception: pass

    relativeFileName = fileName
    fileName = g.os_path_join(os.getcwd(),fileName)

    junk,ext = g.os_path_splitext(fileName)
    if not ext:
        fileName = fileName + ".leo"
        relativeFileName = relativeFileName + ".leo"

    return fileName,relativeFileName
Beispiel #19
0
def loadOnePlugin (moduleOrFileName, verbose=False):
    
    global loadedModules
    
    if moduleOrFileName [-3:] == ".py":
        moduleName = moduleOrFileName [:-3]
    else:
        moduleName = moduleOrFileName
    moduleName = g.shortFileName(moduleName)

    if isLoaded(moduleName):
        module = loadedModules.get(moduleName)
        if verbose:
            print 'plugin %s already loaded' % moduleName
        return module

    plugins_path = g.os_path_join(g.app.loadDir,"..","plugins")
    moduleName = g.toUnicode(moduleName,g.app.tkEncoding)
    
    # This import typically results in calls to registerHandler.
    global loadingModuleNameStack
    loadingModuleNameStack.append(moduleName)
    result = g.importFromPath(moduleName,plugins_path)
    if hasattr( result, 'init' ):
        result.init()
    
    loadingModuleNameStack.pop()

    if result:
        loadedModules[moduleName] = result
    
    if verbose:
        if result is None:
            s = 'can not load %s plugin' % moduleName
            print s ; g.es(s,color="blue")
        else:
            print 'loaded %s plugin' % moduleName
    
    return result
Beispiel #20
0
def loadOnePlugin (moduleOrFileName, verbose=False):

    global loadedModules,loadingModuleNameStack

    verbose = verbose or g.app.config.getBool(c=None,setting='trace_plugins')
    warn_on_failure = g.app.config.getBool(c=None,setting='warn_when_plugins_fail_to_load')

    if moduleOrFileName.endswith('.py'):
        moduleName = moduleOrFileName [:-3]
    else:
        moduleName = moduleOrFileName
    moduleName = g.shortFileName(moduleName)

    if isLoaded(moduleName):
        module = loadedModules.get(moduleName)
        if verbose:
            s = 'plugin %s already loaded' % moduleName
            g.es_print(s,color="blue")
        return module

    plugins_path = g.os_path_join(g.app.loadDir,"..","plugins")
    moduleName = g.toUnicode(moduleName,g.app.tkEncoding)

    # This import will typically result in calls to registerHandler.
    # if the plugin does _not_ use the init top-level function.
    loadingModuleNameStack.append(moduleName)
    result = g.importFromPath(moduleName,plugins_path,pluginName=moduleName,verbose=True)
    loadingModuleNameStack.pop()

    if result:
        loadingModuleNameStack.append(moduleName)
        if hasattr(result,'init'):
            try:
                # Indicate success only if init_result is True.
                init_result = result.init()
                if init_result:
                    loadedModules[moduleName] = result
                else:
                    if verbose and not g.app.initing: ## or not g.app.unitTesting:
                        g.es_print('loadOnePlugin: loading module %s failed' % (moduleName),color="red")
                    result = None
            except Exception:
                g.es('Exception loading plugin',color='red')
                g.es_exception()
                result = None
        else:
            # No top-level init function.
            # Guess that the module was loaded correctly,
            # but do *not* load the plugin if we are unit testing.
            g.trace('no init()',moduleName)
            if g.app.unitTesting:
                result = None
                loadedModules[moduleName] = None
            else:
                loadedModules[moduleName] = result
        loadingModuleNameStack.pop()

    if g.unitTesting or g.app.batchMode or g.app.inBridge:
        pass
    elif result is None:
        if warn_on_failure or (verbose and not g.app.initing): # or not g.app.unitTesting:
            s = 'can not load enabled %s plugin' % moduleName
            g.es_print(s,color="red")
    elif verbose:
        s = 'loaded %s plugin' % moduleName
        g.es_print(s,color="blue")

    return result
 def undoRedoText (self,p,
     leading,trailing, # Number of matching leading & trailing lines.
     oldMidLines,newMidLines, # Lists of unmatched lines.
     oldNewlines,newNewlines, # Number of trailing newlines.
     tag="undo", # "undo" or "redo"
     undoType=None):
 
     u = self ; c = u.c
     assert(p == c.currentPosition())
     v = p.v
 
     #@    << Incrementally update the Tk.Text widget >>
     #@+node:ekr.20031218072017.1494:<< Incrementally update the Tk.Text widget >>
     # Only update the changed lines.
     mid_text = string.join(oldMidLines,'\n')
     new_mid_len = len(newMidLines)
     # Maybe this could be simplified, and it is good to treat the "end" with care.
     if trailing == 0:
         c.frame.body.deleteLine(leading)
         if leading > 0:
             c.frame.body.insertAtEnd('\n')
         c.frame.body.insertAtEnd(mid_text)
     else:
         if new_mid_len > 0:
             c.frame.body.deleteLines(leading,new_mid_len)
         elif leading > 0:
             c.frame.body.insertAtStartOfLine(leading,'\n')
         c.frame.body.insertAtStartOfLine(leading,mid_text)
     # Try to end the Tk.Text widget with oldNewlines newlines.
     # This may be off by one, and we don't care because
     # we never use body text to compute undo results!
     s = c.frame.body.getAllText()
     newlines = 0 ; i = len(s) - 1
     while i >= 0 and s[i] == '\n':
         newlines += 1 ; i -= 1
     while newlines > oldNewlines:
         c.frame.body.deleteLastChar()
         newlines -= 1
     if oldNewlines > newlines:
         c.frame.body.insertAtEnd('\n'*(oldNewlines-newlines))
     #@nonl
     #@-node:ekr.20031218072017.1494:<< Incrementally update the Tk.Text widget >>
     #@nl
     #@    << Compute the result using v's body text >>
     #@+node:ekr.20031218072017.1495:<< Compute the result using v's body text >>
     # Recreate the text using the present body text.
     body = v.bodyString()
     body = g.toUnicode(body,"utf-8")
     body_lines = body.split('\n')
     s = []
     if leading > 0:
         s.extend(body_lines[:leading])
     if len(oldMidLines) > 0:
         s.extend(oldMidLines)
     if trailing > 0:
         s.extend(body_lines[-trailing:])
     s = string.join(s,'\n')
     # Remove trailing newlines in s.
     while len(s) > 0 and s[-1] == '\n':
         s = s[:-1]
     # Add oldNewlines newlines.
     if oldNewlines > 0:
         s = s + '\n' * oldNewlines
     result = s
     if u.debug_print:
         print "body:  ",body
         print "result:",result
     #@nonl
     #@-node:ekr.20031218072017.1495:<< Compute the result using v's body text >>
     #@nl
     # g.trace(v)
     # g.trace("old:",v.bodyString())
     v.setTnodeText(result)
     # g.trace("new:",v.bodyString())
     #@    << Get textResult from the Tk.Text widget >>
     #@+node:ekr.20031218072017.1496:<< Get textResult from the Tk.Text widget >>
     textResult = c.frame.body.getAllText()
     
     if textResult != result:
         # Remove the newline from textResult if that is the only difference.
         if len(textResult) > 0 and textResult[:-1] == result:
             textResult = result
     #@nonl
     #@-node:ekr.20031218072017.1496:<< Get textResult from the Tk.Text widget >>
     #@nl
     if textResult == result:
         if undoType in ("Cut","Paste"):
             # g.trace("non-incremental undo")
             c.frame.body.recolor(p,incremental=False)
         else:
             # g.trace("incremental undo:",leading,trailing)
             c.frame.body.recolor_range(p,leading,trailing)
     else: # 11/19/02: # Rewrite the pane and do a full recolor.
         if u.debug_print:
             #@            << print mismatch trace >>
             #@+node:ekr.20031218072017.1497:<< print mismatch trace >>
             print "undo mismatch"
             print "expected:",result
             print "actual  :",textResult
             #@nonl
             #@-node:ekr.20031218072017.1497:<< print mismatch trace >>
             #@nl
         # g.trace("non-incremental undo")
         p.setBodyStringOrPane(result)
            fh.close()
            
            # finally, get the list of hyperlinks and append to the end of the text
            hyperlinks = parser.anchorlist
            numlinks = len(hyperlinks)
            if numlinks > 0:
                hyperlist = ['\n\n--Hyperlink list follows--']
                for i in xrange(numlinks):
                    hyperlist.append("\n[%d]: %s" % (i+1,hyperlinks[i])) # 3/26/03: was i.
                new = new + ''.join(hyperlist)
            #@nonl
            #@-node:edream.110203113231.895:<< convert HTML to text >>
            #@nl
        previous = v.t.bodyString
        v.setBodyStringOrPane(new)
        changed = (g.toUnicode(new,'ascii') != g.toUnicode(previous,'ascii'))
        if changed and previous != "":
            g.es("changed: %s" % name) # A real change.
        return changed
#@nonl
#@-node:edream.110203113231.894:insert_read_only_node (FTP version)
#@+node:edream.110203113231.896:on_open
#  scan the outline and process @read-only nodes.
def on_open (tag,keywords):

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

    v = c.rootVnode()
    g.es("scanning for @read-only nodes...",color="blue")
    c.beginUpdate()
 def getCharAtIndex (self,t,index):
     ch = t.get(index)
     return g.toUnicode(ch,g.app.tkEncoding)
 def getLineContainingIndex (self,t,index):
 
     line = t.get(index + " linestart", index + " lineend")
     return g.toUnicode(line,g.app.tkEncoding)
Beispiel #25
0
    def retrieve (self,name):

        data = self.db [name]
        data = zlib.decompress(data)
        return g.toUnicode(data,"utf-8",reportErrors=True)
Beispiel #26
0
 def getCharAtIndex(self, t, index):
     ch = t.get(index)
     return g.toUnicode(ch, g.app.tkEncoding)
Beispiel #27
0
    def getLineContainingIndex(self, t, index):

        line = t.get(index + " linestart", index + " lineend")
        return g.toUnicode(line, g.app.tkEncoding)