Example #1
0
 def open_dict_file(self, fn):
     '''Open or create the dict with the given fn.'''
     trace = False and not g.unitTesting
     language = self.language
     if not fn or not language:
         return None
     if g.app.spellDict:
         if trace: g.trace('already open', self.c.fileName(), fn)
         return g.app.spellDict
     if not g.os_path_exists(fn):
         # Fix bug 1175013: leo/plugins/spellpyx.txt is
         # both source controlled and customized.
         self.create(fn)
     if g.os_path_exists(fn):
         # Merge the local and global dictionaries.
         try:
             self.clean_dict(fn)
             d = enchant.DictWithPWL(language, fn)
             if trace: g.trace('open', g.shortFileName(self.c.fileName()), fn)
         except Exception:
             # This is off-putting, and not necessary.
             # g.es('Error reading dictionary file', fn)
             # g.es_exception()
             d = enchant.Dict(language)
     else:
         # A fallback.  Unlikely to happen.
         d = enchant.Dict(language)
     return d
Example #2
0
 def make_stub_file(self, p):
     '''Make a stub file in ~/stubs for the @<file> node at p.'''
     import ast
     import leo.core.leoAst as leoAst
     assert p.isAnyAtFileNode()
     c = self.c
     fn = p.anyAtFileNodeName()
     if not fn.endswith('.py'):
         g.es_print('not a python file', fn)
         return
     abs_fn = g.fullPath(c, p)
     if not g.os_path_exists(abs_fn):
         g.es_print('not found', abs_fn)
         return
     if g.os_path_exists(self.output_directory):
         base_fn = g.os_path_basename(fn)
         out_fn = g.os_path_finalize_join(self.output_directory, base_fn)
     else:
         g.es_print('not found', self.output_directory)
         return
     out_fn = out_fn[:-3] + '.pyi'
     out_fn = os.path.normpath(out_fn)
     self.output_fn = out_fn
         # compatibility with stand-alone script
     s = open(abs_fn).read()
     node = ast.parse(s,filename=fn,mode='exec')
     leoAst.StubTraverser(controller=self).run(node)
Example #3
0
 def open_dict(self, fn, language):
     '''Open or create the dict with the given fn.'''
     trace = False and not g.unitTesting
     if not fn or not language:
         return
     d = g.app.spellDict
     if d:
         self.d = d
         if trace: g.trace('already open', self.c.fileName(), fn)
         return
     if not g.os_path_exists(fn):
         # Fix bug 1175013: leo/plugins/spellpyx.txt is both source controlled and customized.
         self.create(fn)
     if g.os_path_exists(fn):
         # Merge the local and global dictionaries.
         try:
             self.clean_dict(fn)
             self.d = enchant.DictWithPWL(language, fn)
             if trace: g.trace('open', g.shortFileName(self.c.fileName()), fn)
         except Exception:
             g.es_exception()
             g.error('not a valid dictionary file', fn)
             self.d = enchant.Dict(language)
     else:
         # A fallback.  Unlikely to happen.
         self.d = enchant.Dict(language)
     # Use only a single copy of the dict.
     g.app.spellDict = self.d
Example #4
0
 def makeShadowDirectory(self, fn):
     '''Make a shadow directory for the **public** fn.'''
     x = self; path = x.shadowDirName(fn)
     if not g.os_path_exists(path):
         # Force the creation of the directories.
         g.makeAllNonExistentDirectories(path, c=None, force=True)
     return g.os_path_exists(path) and g.os_path_isdir(path)
Example #5
0
 def find_main_dict(self):
     '''Return the full path to the global dictionary.'''
     c = self.c
     fn = c.config.getString('main_spelling_dictionary')
     if fn and g.os_path_exists(fn):
         return fn
     # Default to ~/.leo/main_spelling_dict.txt
     fn = g.os_path_finalize_join(
         g.app.homeDir, '.leo', 'main_spelling_dict.txt')
     return fn if g.os_path_exists(fn) else None
Example #6
0
    def openOutputFile (self):

        if self.outputFileName == None:
            return
        theDir,name = g.os_path_split(self.outputFileName)
        if len(theDir) == 0:
            self.show("empty output directory")
            return
        if len(name) == 0:
            self.show("empty output file name")
            return
        if not g.os_path_exists(theDir):
            self.show("output directory not found: " + theDir)
        else:
            try:
                if self.appendOutput:
                    self.show("appending to " + self.outputFileName)
                    self.outputFile = open(self.outputFileName,"ab")
                else:
                    self.show("writing to " + self.outputFileName)
                    self.outputFile = open(self.outputFileName,"wb")
            except:
                self.outputFile = None
                self.show("exception opening output file")
                g.es_exception()
Example #7
0
    def get_fn (self,s,tag):
        
        pc = self
        c = pc.c
        fn = s or c.p.h[len(tag):]
        fn = fn.strip()
        
        # Similar to code in g.computeFileUrl
        if fn.startswith('~'):
            # Expand '~' and handle Leo expressions.
            fn = fn[1:]
            fn = g.os_path_expanduser(fn)
            fn = g.os_path_expandExpression(fn,c=c)
            fn = g.os_path_finalize(fn)
        else:
            # Handle Leo expressions.
            fn = g.os_path_expandExpression(fn,c=c)
            # Handle ancestor @path directives.
            if c and c.openDirectory:
                base = c.getNodePath(c.p)
                fn = g.os_path_finalize_join(c.openDirectory,base,fn)
            else:
                fn = g.os_path_finalize(fn)

        ok = g.os_path_exists(fn)
        return ok,fn
Example #8
0
 def createFrame(self, fileName):
     '''Create a commander and frame for the given file.
     Create a new frame if the fileName is empty or non-exisent.'''
     trace = False
     g = self.g
     if fileName.strip():
         if g.os_path_exists(fileName):
             if trace:
                 import time; t1 = time.time()
             # This takes a long time due to imports in c.__init__
             c = g.openWithFileName(fileName)
             if trace:
                 t2 = time.time()
                 g.trace('g.openWithFileName: %0.2fsec' % (t2 - t1))
             if c: return c
         elif not self.silentMode:
             print('file not found: %s. creating new window' % (fileName))
     # Create a new frame. Unlike leo.run, this is not a startup window.
     c = g.app.newCommander(fileName)
     frame = c.frame
     frame.createFirstTreeNode() # 2013/09/27: bug fix.
     assert c.rootPosition()
     frame.setInitialWindowGeometry()
     frame.resizePanesToRatio(frame.ratio, frame.secondary_ratio)
     # Call the 'new' hook for compatibility with plugins.
     # 2011/11/07: Do this only if plugins have been loaded.
     g.doHook("new", old_c=None, c=c, new_c=c)
     return c
Example #9
0
def xdb_command(event):
    '''Start the external debugger on a toy test program.'''
    c = event.get('c')
    if not c:
        return
    path = g.fullPath(c, c.p)
    if not path:
        g.trace('Not in an @<file> tree')
        return
    if not g.os_path_exists(path):
        return g.trace('not found', path)
    os.chdir(g.os_path_dirname(path))
    xdb = getattr(g.app, 'xdb', None)
    if xdb:
        # Just issue a message.
        xdb.write('xdb active: use Quit button or db-q to terminate')
        # Killing the previous debugger works,
        # *provided* we don't try to restart xdb!
        # That would create a race condition on g.app.xdb.
            # xdb.do_quit()
    else:
        # Start the debugger in a separate thread.
        g.app.xdb = xdb = Xdb(path)
        xdb.start()
        xdb.qr.put(['clear-stdout'])
Example #10
0
def make_at_file_node(line, path):
    '''
    Make and populate an @auto node for the given path.
    '''
    c = g.app.log.c
    if not c:
        return
    path = g.os_path_finalize(path).replace('\\','/')
    if not g.os_path_exists(path):
        g.trace('Not found:', repr(path))
        return
    # Create the new node.
    p = c.lastTopLevel().insertAfter()
    # Like c.looksLikeDerivedFile, but retaining the contents.
    with open(path, 'r') as f:
        file_s = f.read()
        is_derived = file_s.find('@+leo-ver=') > -1
    if is_derived:
        # Set p.v.gnx from the derived file.
        is_derived = get_gnx_from_file(file_s, p, path)
    kind = '@file' if is_derived else '@auto'
    p.h = '%s %s' % (kind, path)
    c.selectPosition(p)
    c.refreshFromDisk()
    return p
Example #11
0
    def startup (self):

        path = self.lib ; global dbs, libraries

        try:
            # 'r' and 'w' fail if the database doesn't exist.
            # 'c' creates it only if it doesn't exist.
            # 'n' always creates a new database.
            if dbs.has_key(path):
                self.db = dbs [path]
                self.trace('Library reusing: %s' % path)
            elif g.os_path_exists(path):
                self.db = anydbm.open(path,"rw")
                self.trace('Library reopening: %s' % path)
                dbs [path] = self.db
            else:
                self.trace('Library creating: %s' % path)
                self.db = anydbm.open(path,"c")
            self.path = path
        except Exception as err:
            g.es('Library: Exception creating database: %s' % (err,))

        ok = (self.path and self.db and
            hasattr(self.db,'isOpen') and self.db.isOpen() and hasattr(self.db,'sync'))
        if ok:
            dbs [path] = self.db
        else:
            g.es('problem starting Library: %s' % (path))
        return ok
Example #12
0
 def should_open_old_file(self, path, root):
     '''Return True if we should open the old temp file.'''
     v = root.v
     return (
         path and g.os_path_exists(path) and
         hasattr(v.b, '_vim_old_body') and v.b == v._vim_old_body
     )
 def create_temp_file(self, c, ext, p):
     '''
     Create the temp file used by open-with if necessary.
     Add the corresponding ExternalFile instance to self.files
     '''
     trace = False and not g.unitTesting
     if trace: g.trace(len(p.b), p.h)
     path = self.temp_file_path(c, p, ext)
     exists = g.os_path_exists(path)
     if trace:
         kind = 'recreating:' if exists else 'creating: '
         g.trace(kind, path)
     # Compute encoding and s.
     d2 = c.scanAllDirectives(p)
     encoding = d2.get('encoding', None)
     if encoding is None:
         encoding = c.config.default_derived_file_encoding
     s = g.toEncodedString(p.b, encoding, reportErrors=True)
     # Write the file *only* if it doesn't exist.
     # No need to read the file: recomputing s above suffices.
     if not exists:
         try:
             f = open(path, 'wb')
             f.write(s)
             f.flush()
             f.close()
         except IOError:
             g.error('exception creating temp file: %s' % path)
             g.es_exception()
             return None
     # Add or update the external file entry.
     time = self.get_mtime(path)
     self.files = [z for z in self.files if z.path != path]
     self.files.append(ExternalFile(c, ext, p, path, time))
     return path
Example #14
0
    def replaceFileWithString (self,fn,s):

        '''Replace the file with s if s is different from theFile's contents.

        Return True if theFile was changed.
        '''

        trace = False and not g.unitTesting ; verbose = False
        x = self
        exists = g.os_path_exists(fn)

        if exists:
            # Read the file.  Return if it is the same.
            s2,e = g.readFileIntoString(fn)
            if s2 is None:
                return False
            if s == s2:
                if not g.unitTesting: g.es('unchanged:',fn)
                return False

        # Issue warning if directory does not exist.
        theDir = g.os_path_dirname(fn)
        if theDir and not g.os_path_exists(theDir):
            if not g.unitTesting:
                x.error('not written: %s directory not found' % fn)
            return False

        # Replace the file.
        try:
            f = open(fn,'wb')
            # 2011/09/09: Use self.encoding.
            f.write(g.toEncodedString(s,encoding=self.encoding))
            if trace:
                g.trace('encoding',self.encoding)
                if verbose: g.trace('fn',fn,
                    '\nlines...\n%s' %(g.listToString(g.splitLines(s))),
                    '\ncallers',g.callers(4))
            f.close()
            if not g.unitTesting:
                # g.trace('created:',fn,g.callers())
                if exists:  g.es('wrote:',fn)
                else:       g.es('created:',fn)
            return True
        except IOError:
            x.error('unexpected exception writing file: %s' % (fn))
            g.es_exception()
            return False
Example #15
0
 def project_files(self, name, force_all=False):
     '''Return a list of all files in the named project.'''
     # Ignore everything after the first space.
     i = name.find(' ')
     if i > -1:
         name = name[: i].strip()
     leo_path, junk = g.os_path_split(__file__)
     d = {
         # Change these paths as required for your system.
         'coverage': (
             r'C:\Python26\Lib\site-packages\coverage-3.5b1-py2.6-win32.egg\coverage',
             ['.py'], ['.bzr', 'htmlfiles']),
         'leo': (
             r'C:\leo.repo\leo-editor\leo\core',
             ['.py'], ['.git']), # ['.bzr']
         'lib2to3': (
             r'C:\Python26\Lib\lib2to3',
             ['.py'], ['tests']),
         'pylint': (
             r'C:\Python26\Lib\site-packages\pylint',
             ['.py'], ['.bzr', 'test']),
         'rope': (
             r'C:\Python26\Lib\site-packages\rope-0.9.4-py2.6.egg\rope\base', ['.py'], ['.bzr']),
         # 'test': (
             # g.os_path_finalize_join(leo_path,'test-proj'),
             # ['.py'],['.bzr']),
     }
     data = d.get(name.lower())
     if not data:
         g.trace('bad project name: %s' % (name))
         return []
     theDir, extList, excludeDirs = data
     files = self.files_in_dir(theDir, recursive=True, extList=extList, excludeDirs=excludeDirs)
     if files:
         if name.lower() == 'leo':
             for exclude in ['__init__.py', 'format-code.py']:
                 files = [z for z in files if not z.endswith(exclude)]
             table = (
                 r'C:\leo.repo\leo-editor\leo\commands',
                 # r'C:\leo.repo\leo-editor\leo\plugins\importers',
                 # r'C:\leo.repo\leo-editor\leo\plugins\writers',
             )
             for dir_ in table:
                 files2 = self.files_in_dir(dir_, recursive=True, extList=['.py',], excludeDirs=[])
                 files2 = [z for z in files2 if not z.endswith('__init__.py')]
                 # g.trace(g.os_path_exists(dir_), dir_, '\n'.join(files2))
                 files.extend(files2)
             files.extend(glob.glob(r'C:\leo.repo\leo-editor\leo\plugins\qt_*.py'))
             fn = g.os_path_finalize_join(theDir, '..', 'plugins', 'qtGui.py')
             if fn and g.os_path_exists(fn):
                 files.append(fn)
         if g.app.runningAllUnitTests and len(files) > 1 and not force_all:
             return [files[0]]
     if not files:
         g.trace(theDir)
     if g.app.runningAllUnitTests and len(files) > 1 and not force_all:
         return [files[0]]
     else:
         return files
Example #16
0
def openUnittest(self, event=None):
    '''Open unittest.leo.'''
    c = self
    fileName = g.os_path_finalize_join(g.app.loadDir, '..', 'test', 'unitTest.leo')
    if g.os_path_exists(fileName):
        c2 = g.openWithFileName(fileName, old_c=c)
        if c2: return
    g.es('not found:', fileName)
Example #17
0
 def destroy_temp_file(self, ef):
     '''Destroy the *temp* file corresponding to ef, an ExternalFile instance.'''
     # Do not use g.trace here.
     if ef.path and g.os_path_exists(ef.path):
         try:
             os.remove(ef.path)
         except Exception:
             pass
Example #18
0
 def isSignificantPublicFile(self, fn):
     '''This tells the AtFile.read logic whether to import a public file
     or use an existing public file.'''
     return (
         g.os_path_exists(fn) and
         g.os_path_isfile(fn) and
         g.os_path_getsize(fn) > 10
     )
Example #19
0
 def find_git_working_directory(self):
     '''Return the git working directory.'''
     path = g.os_path_abspath('.')
     while path:
         if g.os_path_exists(g.os_path_finalize_join(path, '.git')):
             return path
         path = g.os_path_finalize_join(path, '..')
     return None
Example #20
0
def openLeoDist(self, event=None):
    '''Open leoDist.leo in a new Leo window.'''
    c = self
    name = "leoDist.leo"
    fileName = g.os_path_finalize_join(g.app.loadDir, "..", "dist", name)
    if g.os_path_exists(fileName):
        c2 = g.openWithFileName(fileName, old_c=c)
        if c2: return
    g.es("not found:", name)
Example #21
0
 def get_icon_fn(self, fn):
     '''Resolve fn relative to the Icons directory.'''
     dir_ = g.os_path_finalize_join(g.app.loadDir, '..', 'Icons')
     path = g.os_path_finalize_join(dir_, fn)
     if g.os_path_exists(path):
         return path
     else:
         g.trace('does not exist: %s' % (path))
         return None
Example #22
0
def leoQuickStart(self, event=None):
    '''Open quickstart.leo in a new Leo window.'''
    c = self; name = "quickstart.leo"
    fileName = g.os_path_finalize_join(g.app.loadDir, "..", "doc", name)
    # Bug fix: 2012/04/09: only call g.openWithFileName if the file exists.
    if g.os_path_exists(fileName):
        c2 = g.openWithFileName(fileName, old_c=c)
        if c2: return
    g.es("not found:", name)
Example #23
0
def openLeoScripts(self, event=None):
    '''Open scripts.leo.'''
    c = self
    fileName = g.os_path_finalize_join(g.app.loadDir, '..', 'scripts', 'scripts.leo')
    # Bug fix: 2012/04/09: only call g.openWithFileName if the file exists.
    if g.os_path_exists(fileName):
        c2 = g.openWithFileName(fileName, old_c=c)
        if c2: return
    g.es('not found:', fileName)
Example #24
0
 def get_session_path (self):
     
     '''Return the path to the session file.'''
     
     for path in (g.app.homeLeoDir,g.app.homeDir):
         if g.os_path_exists(path):
             return g.os_path_finalize_join(path,'leo.session')
             
     return None
 def openOutlineByNameFinisher(self, fn):
     c = self.c
     if fn and g.os_path_exists(fn) and not g.os_path_isdir(fn):
         c2 = g.openWithFileName(fn, old_c=c)
         try:
             g.app.gui.runAtIdle(c2.treeWantsFocusNow)
         except Exception:
             pass
     else:
         g.es('ignoring: %s' % fn)
 def openOutlineByName(self, event):
     '''file-open-by-name: Prompt for the name of a Leo outline and open it.'''
     c, k = self.c, self.c.k
     fileName = ''.join(k.givenArgs)
     # Bug fix: 2012/04/09: only call g.openWithFileName if the file exists.
     if fileName and g.os_path_exists(fileName):
         g.openWithFileName(fileName, old_c=c)
     else:
         k.setLabelBlue('Open Leo Outline: ')
         k.getFileName(event, callback=self.openOutlineByNameFinisher)
Example #27
0
 def project_files(self, name, force_all=False):
     """Return a list of all files in the named project."""
     # Ignore everything after the first space.
     i = name.find(" ")
     if i > -1:
         name = name[:i].strip()
     leo_path, junk = g.os_path_split(__file__)
     d = {
         # Change these paths as required for your system.
         "coverage": (
             r"C:\Python26\Lib\site-packages\coverage-3.5b1-py2.6-win32.egg\coverage",
             [".py"],
             [".bzr", "htmlfiles"],
         ),
         "leo": (r"C:\leo.repo\leo-editor\leo\core", [".py"], [".git"]),  # ['.bzr']
         "lib2to3": (r"C:\Python26\Lib\lib2to3", [".py"], ["tests"]),
         "pylint": (r"C:\Python26\Lib\site-packages\pylint", [".py"], [".bzr", "test"]),
         "rope": (r"C:\Python26\Lib\site-packages\rope-0.9.4-py2.6.egg\rope\base", [".py"], [".bzr"]),
         # 'test': (
         # g.os_path_finalize_join(leo_path,'test-proj'),
         # ['.py'],['.bzr']),
     }
     data = d.get(name.lower())
     if not data:
         g.trace("bad project name: %s" % (name))
         return []
     theDir, extList, excludeDirs = data
     files = self.files_in_dir(theDir, recursive=True, extList=extList, excludeDirs=excludeDirs)
     if files:
         if name.lower() == "leo":
             for exclude in ["__init__.py", "format-code.py"]:
                 files = [z for z in files if not z.endswith(exclude)]
             table = (
                 r"C:\leo.repo\leo-editor\leo\commands",
                 # r'C:\leo.repo\leo-editor\leo\plugins\importers',
                 # r'C:\leo.repo\leo-editor\leo\plugins\writers',
             )
             for dir_ in table:
                 files2 = self.files_in_dir(dir_, recursive=True, extList=[".py"], excludeDirs=[])
                 files2 = [z for z in files2 if not z.endswith("__init__.py")]
                 # g.trace(g.os_path_exists(dir_), dir_, '\n'.join(files2))
                 files.extend(files2)
             files.extend(glob.glob(r"C:\leo.repo\leo-editor\leo\plugins\qt_*.py"))
             fn = g.os_path_finalize_join(theDir, "..", "plugins", "qtGui.py")
             if fn and g.os_path_exists(fn):
                 files.append(fn)
         if g.app.runningAllUnitTests and len(files) > 1 and not force_all:
             return [files[0]]
     if not files:
         g.trace(theDir)
     if g.app.runningAllUnitTests and len(files) > 1 and not force_all:
         return [files[0]]
     else:
         return files
Example #28
0
def createMyLeoSettings(c):
    """createMyLeoSettings - Return true if myLeoSettings.leo created ok
    """
    name = "myLeoSettings.leo"
    homeLeoDir = g.app.homeLeoDir
    loadDir = g.app.loadDir
    configDir = g.app.globalConfigDir
    # check it doesn't already exist
    for path in homeLeoDir, loadDir, configDir:
        fileName = g.os_path_join(path, name)
        if g.os_path_exists(fileName):
            return None
    ok = g.app.gui.runAskYesNoDialog(c,
        title = 'Create myLeoSettings.leo?',
        message = 'Create myLeoSettings.leo in %s?' % (homeLeoDir),
    )
    if ok == 'no':
        return
    # get '@enabled-plugins' from g.app.globalConfigDir
    fileName = g.os_path_join(configDir, "leoSettings.leo")
    leosettings = g.openWithFileName(fileName, old_c=c)
    enabledplugins = g.findNodeAnywhere(leosettings, '@enabled-plugins')
    enabledplugins = enabledplugins.b
    leosettings.close()
    # now create "~/.leo/myLeoSettings.leo"
    fileName = g.os_path_join(homeLeoDir, name)
    c2 = g.openWithFileName(fileName, old_c=c)
    # add content to outline
    nd = c2.rootPosition()
    nd.h = "Settings README"
    nd.b = (
        "myLeoSettings.leo personal settings file created {time}\n\n"
        "Only nodes that are descendants of the @settings node are read.\n\n"
        "Only settings you need to modify should be in this file, do\n"
        "not copy large parts of leoSettings.py here.\n\n"
        "For more information see http://leoeditor.com/customizing.html"
        "".format(time=time.asctime())
    )
    nd = nd.insertAfter()
    nd.h = '@settings'
    nd = nd.insertAsNthChild(0)
    nd.h = '@enabled-plugins'
    nd.b = enabledplugins
    nd = nd.insertAfter()
    nd.h = '@keys'
    nd = nd.insertAsNthChild(0)
    nd.h = '@shortcuts'
    nd.b = (
        "# You can define keyboard shortcuts here of the form:\n"
        "#\n"
        "#    some-command Shift-F5\n"
    )
    c2.redraw()
    return c2
Example #29
0
 def regularizeName(self, fn):
     '''Return the name used as a key to this modules dictionaries.'''
     if not fn.endswith('.py'):
         return fn
     #
     # Allow .leo/plugins
     path = g.os_path_finalize_join('~', '.leo', 'plugins', fn)
     if g.os_path_exists(path):
         return fn[: -3]
     # Return the default module for leo plugins.
     return "leo.plugins." + fn[: -3]
    def importDir (self,dir,compteurglobal):

        """ La routine récursive de lecture des fichiers """

        if not g.os_path_exists(dir):
            if language == 'french':
                g.es("Ce répertoire n'existe pas: %s" + dir)
            else:
                g.es("No such Directory: %s" + dir)
            return compteurglobal

        head,tail = g.os_path_split(dir)
        c = self.c ; current = c.p
        try:
            #ici, on liste le contenu du répertoire
            body=""
            #@+<< listdir >>
            #@+node:ekr.20050301083306.11: *4* << listdir >>
            try:
                fichiers = os.listdir(dir)
                dossiers = []
                for f in fichiers:
                    # mettre ici le code de création des noeuds
                    path = g.os_path_join(dir,f)
                    # est-ce un fichier ?
                    if g.os_path_isfile(path):
                        body += (f+"\n")
                    else:
                        # c'est alors un répertoire
                        dossiers.append(path)
                    compteurglobal += 1
            except Exception:
                if language == 'french':
                    g.es("erreur dans listage fichiers...")
                else:
                    g.es("os.listdir error...")
                g.es_exception()
            #@-<< listdir >>
            p = c.importCommands.createHeadline(current,body,tail)
            c.selectPosition(p)
            if dossiers:
                for d in dossiers:
                    compteurglobal = self.importDir(d,compteurglobal)
            c.setChanged(True)
            #sélectionne le noeud parent
            c.selectPosition(current)
        except Exception:
            if language == 'french':
                g.es("erreur d'insertion de noeud...")
            else:
                g.es("error while creating node...")
            g.es_exception()

        return compteurglobal
Example #31
0
 def __init__(self, c):
     """Ctor for EnchantClass class."""
     self.c = c
     language = g.toUnicode(c.config.getString('enchant_language'))
     # Set the base language
     if language and not enchant.dict_exists(language):
         g.warning('Invalid language code for Enchant', repr(language))
         g.es_print('Using "en_US" instead')
         language = 'en_US'
     # Compute fn, the full path to the local dictionary.
     fn = c.config.getString('enchant_local_dictionary')
     if not fn:
         fn = g.os_path_finalize_join(g.app.loadDir, "..", "plugins", 'spellpyx.txt')
     # Fix bug https://github.com/leo-editor/leo-editor/issues/108
     if not g.os_path_exists(fn):
         fn = g.os_path_finalize_join(g.app.homeDir, '.leo', 'spellpyx.txt')
     self.open_dict(fn, language)
Example #32
0
 def get_file_from_rev(self, rev, fn):
     '''Get the file from the given rev, or the working directory if None.'''
     if rev:
         # Get the file using git.
         command = 'git show %s:%s' % (rev, fn)
         lines = g.execGitCommand(command, self.repo_dir)
         s = ''.join(lines)
     else:
         # Get the file from the working directory.
         path = g.os_path_finalize_join(self.repo_dir, fn)
         if g.os_path_exists(path):
             with open(path, 'r') as f:
                 s = f.read()
         else:
             g.trace('not found:', path)
             s = ''
     return g.toUnicode(s).replace('\r', '')
Example #33
0
 def find_user_dict(self):
     """Return the full path to the local dictionary."""
     c = self.c
     table = (
         c.config.getString('enchant-local-dictionary'),
             # Settings first.
         g.os_path_finalize_join(g.app.homeDir, '.leo', 'spellpyx.txt'),
             # #108: then the .leo directory.
         g.os_path_finalize_join(g.app.loadDir, "..", "plugins", 'spellpyx.txt'),
             # The plugins directory as a last resort.
     )
     for path in table:
         if g.os_path_exists(path):
             return path
     #
     g.es_print('Do spellpyx.txt file found')
     return None
Example #34
0
 def get_flake8_config(self):
     """Return the path to the pylint configuration file."""
     join = g.os_path_finalize_join
     dir_table = (
         g.app.homeDir,
         join(g.app.homeDir, '.leo'),
         join(g.app.loadDir, '..', '..', 'leo', 'test'),
     )
     for base in ('flake8', 'flake8.txt'):
         for path in dir_table:
             fn = g.os_path_abspath(join(path, base))
             if g.os_path_exists(fn):
                 return fn
     if not g.unitTesting:
         table_s = '\n'.join(dir_table)
         g.es_print(f"no flake8 configuration file found in\n{table_s}")
     return None
Example #35
0
 def forget_path(self, path):
     '''
     Stop handling the path:
     - Remove the path from the list of open-with files.
     - Send a command to vim telling it to close the path.
     '''
     trace = (False or self.trace) and not g.unitTesting
     assert path
     # Don't do this: it prevents efc from reopening paths.
         # efc = g.app.externalFilesController
         # if efc: efc.forget_path(path)
     if 0: # Dubious.
         if g.os_path_exists(path):
             os.remove(path)
     cmd = self.vim_cmd + "--remote-send '<C-\\><C-N>:bd " + path + "<CR>'"
     if trace: g.trace('os.system(%s)' % cmd)
     os.system(cmd)
Example #36
0
 def get_rc_file(self):
     """Return the path to the pylint configuration file."""
     base = 'pylint-leo-rc.txt'
     table = (
         g.os_path_finalize_join(g.app.homeDir, '.leo', base),
         # In ~/.leo
         g.os_path_finalize_join(g.app.loadDir, '..', '..', 'leo', 'test',
                                 base),
         # In leo/test
     )
     for fn in table:
         fn = g.os_path_abspath(fn)
         if g.os_path_exists(fn):
             return fn
     table_s = '\n'.join(table)
     g.es_print(f"no pylint configuration file found in\n{table_s}")
     return None
Example #37
0
    def load_session(self,c=None,unls=None):

        '''Open a tab for each item in UNLs & select the indicated node in each.'''

        if unls is None: unls = []

        for unl in unls:
            if unl.strip():
                fn,unl = unl.split("#")
                if g.os_path_exists(fn):
                    # g.trace(fn)
                    c2 = g.app.loadManager.loadLocalFile(fn,gui=g.app.gui,old_c=c)
                    for p in c2.all_positions():
                        if p.get_UNL() == unl:
                            c2.setCurrentPosition(p)
                            c2.redraw()
                            break
Example #38
0
def main(files):
    '''Call run on all tables in tables_table.'''
    t1 = time.time()
    for fn in files:
        # Report the file name.
        assert g.os_path_exists(fn), fn
        sfn = g.shortFileName(fn)
        s = g.readFileIntoEncodedString(fn, silent=False)
        if s and s.strip():
            r = reporter.Reporter(
                errorStream=sys.stderr,
                warningStream=sys.stderr,
            )
            api.check(s, sfn, r)
    t2 = time.time()
    n = len(files)
    print('%s file%s, time: %5.2f sec.' % (n, g.plural(n), t2 - t1))
Example #39
0
    def create_directory(self, fn):
        '''
        Create the directory for fn if
        a) it doesn't exist and
        b) the user options allow it.

        Return True if the directory existed or was made.
        '''
        c = self.c
        theDir, junk = g.os_path_split(fn)
        theDir = c.os_path_finalize(theDir)
        if g.os_path_exists(theDir):
            return True
        ok = g.makeAllNonExistentDirectories(theDir, c=c, force=False)
        if not ok:
            g.error('did not create:', theDir)
        return ok
Example #40
0
 def findDebugger(self):
     '''Find the debugger using settings.'''
     c = self.c
     pythonDir = g.os_path_dirname(sys.executable)
     debuggers = (
         c.config.getString('debugger-path'),
         g.os_path_join(pythonDir, 'Lib', 'site-packages', 'winpdb.py'), # winpdb 1.1.2 or newer
         g.os_path_join(pythonDir, 'scripts', '_winpdb.py'), # oder version.
     )
     for debugger in debuggers:
         if debugger:
             debugger = c.os_path_finalize(debugger)
             if g.os_path_exists(debugger):
                 return debugger
             g.warning('debugger does not exist:', debugger)
     g.es('no debugger found.')
     return None
Example #41
0
def openCheatSheet(self, event=None, redraw=True):
    '''Open leo/doc/cheatSheet.leo'''
    c = self
    fn = g.os_path_finalize_join(g.app.loadDir, '..', 'doc', 'CheatSheet.leo')
    # g.es_debug(g.os_path_exists(fn),fn)
    if g.os_path_exists(fn):
        c2 = g.openWithFileName(fn, old_c=c)
        if redraw:
            p = g.findNodeAnywhere(c2, "Leo's cheat sheet")
            if p:
                c2.selectPosition(p)
                p.expand()
            c2.redraw()
        return c2
    else:
        g.es('file not found: %s' % fn)
        return None
def insertWikiPicture(colorer, filename, s, i):
    '''Insert the picture with the given filename.'''

    # g.trace(i,filename)

    c = colorer.c
    p = c.p
    w = c.frame.body.bodyCtrl

    if not p or not g.os_path_exists(filename):
        return

    try:
        # Create the image
        if PIL:  # Allow many kinds of images.
            from PIL import Image, ImageTk
            image = Image.open(filename)
            photo = ImageTk.PhotoImage(image)
        else:  # Allow only .gif or .pgm images.
            photo = Tk.PhotoImage(master=g.app.root, file=filename)
            image = None

        index = colorer.index(i)
        if filename in w.mark_names() and w.image_names():
            # This isn't quite correct because
            # it won't allow copies of the picture.
            pass
            # g.trace('**picture exists',filename)
        else:
            index = colorer.index(i)
            # g.trace('**inserting picture',i,index)
            image = c.frame.body.bodyCtrl.image_create(index,
                                                       image=photo,
                                                       padx=0)
            w.mark_set(filename, index)
            # Keep references so images stay on the canvas.
            # The reference to photo must appear, even though it is not used.
            colorer.image_references.append((photo, image, index), )
    except:
        if not PIL:
            g.es_print(
                'PIL not loaded: wiki images must be .gif or .pgm files.',
                color='blue')
        else:
            g.es_exception()
Example #43
0
 def get_rc_file(self):
     '''Return the path to the pylint configuration file.'''
     trace = False and not g.unitTesting
     base = 'pylint-leo-rc.txt'
     table = (
         g.os_path_finalize_join(g.app.homeDir, '.leo', base),
             # In ~/.leo
         g.os_path_finalize_join(g.app.loadDir, '..', '..', 'leo', 'test', base),
             # In leo/test
     )
     for fn in table:
         fn = g.os_path_abspath(fn)
         if g.os_path_exists(fn):
             if trace: g.trace('found:', fn)
             return fn
     g.es_print('no pylint configuration file found in\n%s' % (
         '\n'.join(table)))
     return None
Example #44
0
def get_flake8_config():
    '''Return the path to the flake8 configuration file.'''
    join = g.os_path_finalize_join
    homeDir = get_home()
    loadDir = g.os_path_finalize_join(g.__file__, '..', '..')
    base_table = ('flake8', 'flake8.txt')
    dir_table = (
        homeDir,
        join(homeDir, '.leo'),
        join(loadDir, '..', '..', 'leo', 'test'),
    )
    for base in base_table:
        for path in dir_table:
            fn = g.os_path_abspath(join(path, base))
            if g.os_path_exists(fn):
                return fn
    print('no flake8 configuration file found in\n%s' % ('\n'.join(dir_table)))
    return None
Example #45
0
 def find_user_dict(self):
     """Return the full path to the local dictionary."""
     c = self.c
     join = g.os_path_finalize_join
     table = (
         # Settings first.
         c.config.getString('enchant-local-dictionary'),
         # #108: then the .leo directory.
         join(g.app.homeDir, '.leo', 'spellpyx.txt'),
         # The plugins directory as a last resort.
         join(g.app.loadDir, "..", "plugins", 'spellpyx.txt'),
     )
     for path in table:
         if g.os_path_exists(path):
             return path
     g.es_print('Creating ~/.leo/spellpyx.txt')
     # #1453: Return the default path.
     return join(g.app.homeDir, '.leo', 'spellpyx.txt')
Example #46
0
    def load_snapshot(self):
        """
        Load a snapshot of a session from the leo.session file.

        Called when --restore-session is in effect.
        """
        fn = self.path
        if fn and g.os_path_exists(fn):
            try:
                with open(fn) as f:
                    session = json.loads(f.read())
                return session
            except Exception:
                pass
        #
        # #1107: No need for this message.
        # print('can not load session: no leo.session file')
        return None
Example #47
0
    def create_temp_file(self, c, d, p):
        '''
        Create the temp file used by open-with if necessary.
        Add the corresponding ExternalFile instance to self.files

        d is a dictionary created from an @openwith settings node.

        'args':     the command-line arguments to be used to open the file.
        'ext':      the file extension.
        'kind':     the method used to open the file, such as subprocess.Popen.
        'name':     menu label (used only by the menu code).
        'shortcut': menu shortcut (used only by the menu code).
        '''
        trace = False and not g.unitTesting
        assert isinstance(d, dict), d
        ext = d.get('ext')
        path = self.temp_file_path(c, p, ext)
        exists = g.os_path_exists(path)
        if trace:
            kind = 'recreating:' if exists else 'creating: '
            g.trace(kind, path)
        # Compute encoding and s.
        d2 = c.scanAllDirectives(p)
        encoding = d2.get('encoding', None)
        if encoding is None:
            encoding = c.config.default_derived_file_encoding
        s = g.toEncodedString(p.b, encoding, reportErrors=True)
        # Write the file *only* if it doesn't exist.
        # No need to read the file: recomputing s above suffices.
        if not exists:
            try:
                f = open(path, 'wb')
                f.write(s)
                f.flush()
                f.close()
            except IOError:
                g.error('exception creating temp file: %s' % path)
                g.es_exception()
                return None
        # Add or update the external file entry.
        time = self.get_mtime(path)
        self.files = [z for z in self.files if z.path != path]
        self.files.append(ExternalFile(c, ext, p, path, time))
        return path
Example #48
0
 def update_pyplot(self, s, keywords):
     '''Get the pyplot script at c.p.b and show it.'''
     c = self.c
     # To do: show plot in the VR area.
     if not self.pyplot_imported:
         self.pyplot_imported = True
         backend = g.os_path_finalize_join(
             g.app.loadDir, '..', 'plugins', 'pyplot_backend.py')
         if g.os_path_exists(backend):
             try:
                 # The order of these statements is important...
                 import matplotlib
                 matplotlib.use('module://leo.plugins.pyplot_backend')
                 if trace: g.trace('===== LOADED: pyplot.backend')
             except ImportError:
                 g.trace('===== FAIL: pyplot.backend')
         else:
             g.trace('===== MISSING: pyplot.backend')
     try:
         import matplotlib # Make *sure* this is imported.
         import matplotlib.pyplot as plt
         import numpy as np
         import matplotlib.animation as animation
         plt.ion() # Automatically set interactive mode.
         namespace = {
             'animation': animation,
             'matplotlib': matplotlib,
             'numpy': np, 'np': np,
             'pyplot': plt, 'plt': plt,
         }
     except ImportError:
         g.es_print('matplotlib imports failed')
         namespace = {}
     self.embed_pyplot_widget()
     c.executeScript(
         event=None,
         args=None, p=None,
         script=None,
         useSelectedText=False,
         define_g=True,
         define_name='__main__',
         silent=False,
         namespace=namespace,
         raiseFlag=False)
Example #49
0
 def get_file_from_rev(self, rev, fn):
     """Get the file from the given rev, or the working directory if None."""
     path = g.os_path_finalize_join(self.repo_dir, fn)
     if not g.os_path_exists(path):
         return ''
     if rev:
         # Get the file using git.
         # Use the file name, not the path.
         command = f"git show {rev}:{fn}"
         lines = g.execGitCommand(command, self.repo_dir)
         return g.toUnicode(''.join(lines)).replace('\r', '')
     try:
         with open(path, 'rb') as f:  # Was 'r'
             b = f.read()
         return g.toUnicode(b).replace('\r', '')
     except Exception:
         g.es_print('Can not read', path)
         g.es_exception()
         return ''
Example #50
0
def open_in_emacs_helper(c, p):

    v = p.v

    # Load contextmenu plugin if required.
    contextMenu = g.loadOnePlugin('contextmenu.py', verbose=True)
    if not contextMenu:
        if not contextmenu_message_given:
            contextmenu_message_given = True
            g.trace('can not load contextmenu.py')
        return

    # Search g.app.openWithFiles for a file corresponding to v.
    for d in g.app.openWithFiles:
        if d.get('v') == id(v):
            path = d.get('path', '')
            break
    else:
        path = ''

    # g.trace('config',c.config.getString('xemacs_exe'))
    emacs_cmd = c.config.getString(
        'xemacs_exe') or _emacs_cmd  # 2010/01/18: found by pylint.

    if (not g.os_path_exists(path) or not hasattr(v, 'OpenWithOldBody')
            or v.b != v.OpenWithOldBody):
        # Open a new temp file.
        if path:
            # Remove the old file and the entry in g.app.openWithFiles.
            os.remove(path)
            g.app.openWithFiles = [
                d for d in g.app.openWithFiles if d.get('path') != path
            ]
            os.system(emacs_cmd)
        v.OpenWithOldBody = v.b  # Remember the old contents

        # open the node in emacs (note the space after _emacs_cmd)
        # data = "os.spawnl", emacs_cmd, None
        d = {'kind': 'os.spawnl', 'args': [emacs_cmd], 'ext': None}
        c.openWith(d=d)
    else:
        # Reopen the old temp file.
        os.system(emacs_cmd)
Example #51
0
    def createDirectoryForFile(self, fn):
        """
        Create the directory for fn if
        a) it doesn't exist and
        b) the user options allow it.

        Return True if the directory existed or was made.
        """
        c, ok = self.c, False  # 1815.
        # Create the directory if it doesn't exist.
        theDir, junk = g.os_path_split(fn)
        theDir = g.os_path_finalize(theDir)  # 1341
        if g.os_path_exists(theDir):
            return True
        if c and c.config and c.config.create_nonexistent_directories:
            theDir = c.expand_path_expression(theDir)
            ok = g.makeAllNonExistentDirectories(theDir)
            if not ok:
                g.error('did not create:', theDir)
        return ok
Example #52
0
 def parse(self, fn):
     """Parse the file, which should be JSON format."""
     if not nbformat:
         if not self.nb_warning_given:
             self.nb_warning_given = True
             g.es_print('@auto for .ipynb files requires the nbformat package', color='red')
         return None
     if g.os_path_exists(fn):
         with open(fn) as f:
             # payload_source = f.name
             payload = f.read()
         try:
             nb = nbformat.reads(payload, as_version=4)
             return nb
         except Exception:
             g.es_exception()
             return None
     else:
         g.es_print('not found', fn)
         return None
Example #53
0
 def load_session(self, c=None, unls=None):
     """Open a tab for each item in UNLs & select the indicated node in each."""
     if not unls:
         return
     unls = [z.strip() for z in unls or [] if z.strip()]
     for unl in unls:
         i = unl.find("#")
         if i > -1:
             fn, unl = unl[:i], unl[i:]
         else:
             fn, unl = unl, ''
         fn = fn.strip()
         exists = fn and g.os_path_exists(fn)
         if not exists:
             if 'startup' in g.app.debug:
                 g.trace('session file not found:', fn)
             continue
         if 'startup' in g.app.debug:
             g.trace('loading session file:', fn)
         g.app.loadManager.loadLocalFile(fn, gui=g.app.gui, old_c=c)
Example #54
0
 def __init__(self, c):
     """Ctor for DefaultWrapper class."""
     # pylint: disable=super-init-not-called
     self.c = c
     if not g.app.spellDict:
         g.app.spellDict = DefaultDict()
     self.d = g.app.spellDict
     self.user_fn = self.find_user_dict()
     if not g.os_path_exists(self.user_fn):
         # Fix bug 1175013: leo/plugins/spellpyx.txt is
         # both source controlled and customized.
         self.create(self.user_fn)
     self.main_fn = self.find_main_dict()
     table = (
         ('user', self.user_fn),
         ('main', self.main_fn),
     )
     for kind, fn in table:
         if fn:
             words = self.read_words(kind, fn)
             self.d.add_words_from_dict(kind, fn, words)
Example #55
0
 def test_lm_openAnyLeoFile(self):
     lm = g.app.loadManager
     # Create a zip file for testing.
     s = 'this is a test file'
     testDir = g.os_path_join(g.app.loadDir, '..', 'test')
     assert g.os_path_exists(testDir), testDir
     path = g.os_path_finalize_join(testDir, 'testzip.zip')
     if os.path.exists(path):
         os.remove(path)  # pragma: no cover
     f = zipfile.ZipFile(path, 'x')
     assert f, path
     try:
         f.writestr('leo-zip-file', s)
         f.close()
         # Open the file, and get the contents.
         f = lm.openAnyLeoFile(path)
         s2 = f.read()
         f.close()
     finally:
         os.remove(path)
     self.assertEqual(s, s2)
Example #56
0
 def test_syntax_of_all_files(self):
     skip_tuples = (
         ('extensions', 'asciidoc.py'),
         ('test', 'scriptFile.py'),
     )
     join = g.os_path_finalize_join
     skip_list = [join(g.app.loadDir, '..', a, b) for a, b in skip_tuples]
     n = 0
     for theDir in ('core', 'external', 'extensions', 'modes', 'plugins',
                    'scripts', 'test'):
         path = g.os_path_finalize_join(g.app.loadDir, '..', theDir)
         self.assertTrue(g.os_path_exists(path), msg=path)
         aList = glob.glob(g.os_path_join(path, '*.py'))
         if g.isWindows:
             aList = [z.replace('\\', '/') for z in aList]
         for z in aList:
             if z not in skip_list:
                 n += 1
                 fn = g.shortFileName(z)
                 s, e = g.readFileIntoString(z)
                 self.assertTrue(self.check_syntax(fn, s), msg=fn)
Example #57
0
 def get_flake8_config(self):
     '''Return the path to the pylint configuration file.'''
     join = g.os_path_finalize_join
     dir_table = (
         g.app.homeDir,
         join(g.app.homeDir, '.leo'),
         join(g.app.loadDir, '..', '..', 'leo', 'test'),
     )
     if g.isPython3:
         base_table = ('flake8', 'flake8.txt')
     else:
         base_table = ('flake8',)
     for base in base_table:
         for path in dir_table:
             fn = g.os_path_abspath(join(path, base))
             if g.os_path_exists(fn):
                 return fn
     if not g.unitTesting:
         g.es_print('no flake8 configuration file found in\n%s' % (
             '\n'.join(dir_table)))
     return None
Example #58
0
    def make_image(path, src, fail_ok=False):
        """relative to path (if needed), make a QGraphicsPixmapItem
        for the image named in src, returning None if not available,
        or an 'No Image' image if fail_ok == False"""

        if '//' not in src or src.startswith('file://'):
            testpath = src
            if '//' in testpath:
                testpath = testpath.split('//', 1)[-1]

            # file on local file system
            testpath = g.os_path_finalize_join(path, testpath)
            if g.os_path_exists(testpath):
                return QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(testpath))

            # explicit file://, but no such file exists
            if src.startswith('file://'):
                if fail_ok:
                    return None
                else:
                    return GetImage._no_image()

        # no explict file://, so try other protocols

        if '//' not in src:
            testpath = 'http://%s' % src
        else:
            testpath = src

        data = GetImage.get_url(testpath)

        if data:
            img = QtGui.QPixmap()
            if img.loadFromData(data):
                return QtWidgets.QGraphicsPixmapItem(img)

        if fail_ok:
            return None

        return GetImage._no_image()
Example #59
0
 def get_file_from_rev(self, rev, fn):
     """Get the file from the given rev, or the working directory if None."""
     if rev:
         # Get the file using git.
         command = f"git show {rev}:{fn}"
         lines = g.execGitCommand(command, self.repo_dir)
         s = ''.join(lines)
     else:
         # Get the file from the working directory.
         path = g.os_path_finalize_join(self.repo_dir, fn)
         if g.os_path_exists(path):
             try:
                 with open(path, 'rb') as f:  # Was 'r'
                     s = f.read()
             except Exception:
                 g.es_print('Can not read', path)
                 g.es_exception()
                 s = ''
         else:
             g.trace('not found:', path)
             s = ''
     return g.toUnicode(s).replace('\r', '')
Example #60
0
def start_file(c,p):

    # Set the base directory by searching for @folder directives in ancestors.
    h = p.h.strip()
    thisdir = os.path.abspath(os.curdir) # remember the current dir
    basedir = thisdir[:] # use current dir as default.
    parent = p.parent() # start with parent
    while parent: # stop when no more parent found
        p = parent.h.strip()
        if g.match_word(p,0,'@folder'):
            basedir = p[8:] # take rest of headline as pathname
            break # we found the closest @folder
        else:
            parent = parent.parent() # try the parent of the parent
    fname = os.path.join(basedir,h) # join path and filename
    startdir, filename = os.path.split(fname)
    try:
        os.chdir(startdir)
        dirfound = 1
    except Exception:
        g.es(startdir+' - folder not found')
        dirfound = 0

    if dirfound:
        fullpath = g.os_path_join(startdir,filename)
        fullpath = g.os_path_abspath(fullpath)
        if g.os_path_exists(filename):
            try:
                # Warning: os.startfile usually does not throw exceptions.
                # pylint: disable=no-member
                # Previous code checks that os.startfile exists.
                os.startfile(filename)
                    # This may not work for all file types.
            except Exception:
                g.es(filename+' - file not found in '+startdir)
                g.es_exception()
        else:
            g.warning('%s not found in %s' % (filename,startdir))
    os.chdir(thisdir) # restore the original current dir.