def writeFileFromNode(self, event=None):
    '''If node starts with @read-file-into-node, use the full path name in the headline.
    Otherwise, prompt for a file name.
    '''
    c = self; p = c.p
    c.endEditing()
    h = p.h.rstrip()
    s = p.b
    tag = '@read-file-into-node'
    if h.startswith(tag):
        fileName = h[len(tag):].strip()
    else:
        fileName = None
    if not fileName:
        filetypes = [("All files", "*"), ("Python files", "*.py"), ("Leo files", "*.leo"),]
        fileName = g.app.gui.runSaveFileDialog(c,
            initialfile=None,
            title='Write File From Node',
            filetypes=filetypes,
            defaultextension=None)
    if fileName:
        try:
            with open(fileName, 'w') as f:
                g.chdir(fileName)
                if s.startswith('@nocolor\n'):
                    s = s[len('@nocolor\n'):]
                if not g.isPython3: # 2010/08/27
                    s = g.toEncodedString(s, reportErrors=True)
                f.write(s)
                f.flush()
                g.blue('wrote:', fileName)
        except IOError:
            g.error('can not write %s', fileName)
def writeFileFromNode(self, event=None):
    """
    If node starts with @read-file-into-node, use the full path name in the headline.
    Otherwise, prompt for a file name.
    """
    c, p = self, self.p
    c.endEditing()
    h = p.h.rstrip()
    s = p.b
    tag = '@read-file-into-node'
    if h.startswith(tag):
        fileName = h[len(tag):].strip()
    else:
        fileName = None
    if not fileName:
        fileName = g.app.gui.runSaveFileDialog(c,
                                               title='Write File From Node',
                                               filetypes=[
                                                   ("All files", "*"),
                                                   ("Python files", "*.py"),
                                                   ("Leo files", "*.leo")
                                               ],
                                               defaultextension=None)
    if fileName:
        try:
            with open(fileName, 'w') as f:
                g.chdir(fileName)
                if s.startswith('@nocolor\n'):
                    s = s[len('@nocolor\n'):]
                f.write(s)
                f.flush()
                g.blue('wrote:', fileName)
        except IOError:
            g.error('can not write %s', fileName)
    def open_completer(c, closeFlag, fileName):

        c.bringToFront()
        c.init_error_dialogs()
        ok = False
        if fileName:
            if g.app.loadManager.isLeoFile(fileName):
                c2 = g.openWithFileName(fileName, old_c=c)
                if c2:
                    c2.k.makeAllBindings()
                    # Fix #579: Key bindings don't take for commands defined in plugins.
                    g.chdir(fileName)
                    g.setGlobalOpenDir(fileName)
                if c2 and closeFlag:
                    g.app.destroyWindow(c.frame)
            elif c.looksLikeDerivedFile(fileName):
                # Create an @file node for files containing Leo sentinels.
                ok = c.importCommands.importDerivedFiles(parent=c.p,
                                                         paths=[fileName],
                                                         command='Open')
            else:
                # otherwise, create an @edit node.
                ok = c.createNodeFromExternalFile(fileName)
        c.raise_error_dialogs(kind='write')
        g.app.runAlreadyOpenDialog(c)
        # openWithFileName sets focus if ok.
        if not ok:
            c.initialFocusHelper()
Beispiel #4
0
 def open_file_in_commander(self, ext, path):
     '''Open the given path in a Leonine manner.'''
     #
     # 1. Open .leo files as in open-outline command...
     path = os.path.normpath(path)
     if g.app.loadManager.isLeoFile(path):
         c = g.openWithFileName(path, old_c=self.c)
         if not c:
             return
         c.k.makeAllBindings()
         g.chdir(path)
         g.setGlobalOpenDir(path)
         return
     #
     # 2. Search open commanders for a matching @<file> node.
     for c in g.app.commanders():
         for p in c.all_unique_positions():
             if (p.isAnyAtFileNode()
                     and path == os.path.normpath(g.fullPath(c, p))):
                 if getattr(c.frame.top, 'leo_master', None):
                     c.frame.top.leo_master.select(c)
                     c.selectPosition(p)
                 c.redraw()
                 return
     #
     # 3. Open a dummy file, removing sentinels from derived files.
     c = g.openWithFileName(path, old_c=self.c)
     c.k.makeAllBindings()
     g.chdir(path)
     g.setGlobalOpenDir(path)
     c.selectPosition(c.rootPosition())
     c.redraw()
Beispiel #5
0
def readFileIntoNode(self, event=None):
    '''Read a file into a single node.'''
    c = self
    undoType = 'Read File Into Node'
    c.endEditing()
    filetypes = [
        ("All files", "*"),
        ("Python files", "*.py"),
        ("Leo files", "*.leo"),
    ]
    fileName = g.app.gui.runOpenFileDialog(c,
                                           title="Read File Into Node",
                                           filetypes=filetypes,
                                           defaultextension=None)
    if not fileName: return
    s, e = g.readFileIntoString(fileName)
    if s is None:
        return
    g.chdir(fileName)
    s = '@nocolor\n' + s
    w = c.frame.body.wrapper
    p = c.insertHeadline(op_name=undoType)
    p.setHeadString('@read-file-into-node ' + fileName)
    p.setBodyString(s)
    w.setAllText(s)
    c.redraw(p)
def saveAs(self, event=None, fileName=None):
    """Save a Leo outline to a file with a new filename."""
    c = self
    p = c.p
    # Do this now: w may go away.
    w = g.app.gui.get_focus(c)
    inBody = g.app.gui.widget_name(w).startswith('body')
    if inBody: p.saveCursorAndScroll()
    if g.app.disableSave:
        g.es("save commands disabled", color="purple")
        return
    c.init_error_dialogs()
    # 2013/09/28: add fileName keyword arg for leoBridge scripts.
    if fileName:
        c.frame.title = g.computeWindowTitle(fileName)
        c.mFileName = fileName
    # Make sure we never pass None to the ctor.
    if not c.mFileName:
        c.frame.title = ""
    if not fileName:
        fileName = ''.join(c.k.givenArgs)
    if not fileName:
        fileName = g.app.gui.runSaveFileDialog(
            c,
            initialfile=c.mFileName,
            title="Save As",
            filetypes=[
                ("Leo files", "*.leo *.db"),
            ],
            defaultextension=g.defaultLeoFileExtension(c))
    c.bringToFront()
    if fileName:
        # Fix bug 998090: save file as doesn't remove entry from open file list.
        if c.mFileName:
            g.app.forgetOpenFile(c.mFileName)
        # Don't change mFileName until the dialog has suceeded.
        c.mFileName = g.ensure_extension(fileName,
                                         g.defaultLeoFileExtension(c))
        # Part of the fix for https://bugs.launchpad.net/leo-editor/+bug/1194209
        c.frame.title = title = c.computeWindowTitle(c.mFileName)
        c.frame.setTitle(title)
        # 2013/08/04: use c.computeWindowTitle.
        c.openDirectory = c.frame.openDirectory = g.os_path_dirname(
            c.mFileName)
        # Bug fix in 4.4b2.
        # Calls c.clearChanged() if no error.
        if g.app.qt_use_tabs and hasattr(c.frame, 'top'):
            c.frame.top.leo_master.setTabName(c, c.mFileName)
        c.fileCommands.saveAs(c.mFileName)
        g.app.recentFilesManager.updateRecentFiles(c.mFileName)
        g.chdir(c.mFileName)
    # Done in FileCommands.saveAs.
    # c.redraw_after_icons_changed()
    c.raise_error_dialogs(kind='write')
    # *Safely* restore focus, without using the old w directly.
    if inBody:
        c.bodyWantsFocus()
        p.restoreCursorAndScroll()
    else:
        c.treeWantsFocus()
def writeFileFromNode(self, event=None):
    '''If node starts with @read-file-into-node, use the full path name in the headline.
    Otherwise, prompt for a file name.
    '''
    c = self; p = c.p
    c.endEditing()
    h = p.h.rstrip()
    s = p.b
    tag = '@read-file-into-node'
    if h.startswith(tag):
        fileName = h[len(tag):].strip()
    else:
        fileName = None
    if not fileName:
        filetypes = [("All files", "*"), ("Python files", "*.py"), ("Leo files", "*.leo"),]
        fileName = g.app.gui.runSaveFileDialog(c,
            initialfile=None,
            title='Write File From Node',
            filetypes=filetypes,
            defaultextension=None)
    if fileName:
        try:
            with open(fileName, 'w') as f:
                g.chdir(fileName)
                if s.startswith('@nocolor\n'):
                    s = s[len('@nocolor\n'):]
                if not g.isPython3: # 2010/08/27
                    s = g.toEncodedString(s, reportErrors=True)
                f.write(s)
                f.flush()
                g.blue('wrote:', fileName)
        except IOError:
            g.error('can not write %s', fileName)
def saveAs(self, event=None, fileName=None):
    '''Save a Leo outline to a file with a new filename.'''
    c = self; p = c.p
    # Do this now: w may go away.
    w = g.app.gui.get_focus(c)
    inBody = g.app.gui.widget_name(w).startswith('body')
    if inBody: p.saveCursorAndScroll()
    if g.app.disableSave:
        g.es("save commands disabled", color="purple")
        return
    c.init_error_dialogs()
    # 2013/09/28: add fileName keyword arg for leoBridge scripts.
    if fileName:
        c.frame.title = g.computeWindowTitle(fileName)
        c.mFileName = fileName
    # Make sure we never pass None to the ctor.
    if not c.mFileName:
        c.frame.title = ""
    if not fileName:
        fileName = ''.join(c.k.givenArgs)
    if not fileName:
        fileName = g.app.gui.runSaveFileDialog(c,
            initialfile=c.mFileName,
            title="Save As",
            filetypes=[g.fileFilters('LEOFILES')],
            defaultextension=g.defaultLeoFileExtension(c))
    c.bringToFront()
    if fileName:
        # Fix bug 998090: save file as doesn't remove entry from open file list.
        if c.mFileName:
            g.app.forgetOpenFile(c.mFileName)
        # Don't change mFileName until the dialog has suceeded.
        c.mFileName = g.ensure_extension(fileName, g.defaultLeoFileExtension(c))
        # Part of the fix for https://bugs.launchpad.net/leo-editor/+bug/1194209
        c.frame.title = title = c.computeWindowTitle(c.mFileName)
        c.frame.setTitle(title)
            # 2013/08/04: use c.computeWindowTitle.
        c.openDirectory = c.frame.openDirectory = g.os_path_dirname(c.mFileName)
            # Bug fix in 4.4b2.
        # Calls c.setChanged(False) if no error.
        if g.app.qt_use_tabs and hasattr(c.frame, 'top'):
            c.frame.top.leo_master.setTabName(c, c.mFileName)
        c.fileCommands.saveAs(c.mFileName)
        g.app.recentFilesManager.updateRecentFiles(c.mFileName)
        g.chdir(c.mFileName)
    # Done in FileCommands.saveAs.
    # c.redraw_after_icons_changed()
    c.raise_error_dialogs(kind='write')
    # *Safely* restore focus, without using the old w directly.
    if inBody:
        c.bodyWantsFocus()
        p.restoreCursorAndScroll()
    else:
        c.treeWantsFocus()
def weave(self, event=None):
    """Simulate a literate-programming weave operation by writing the outline to a text file."""
    c = self
    fileName = g.app.gui.runSaveFileDialog(c,
                                           title="Weave",
                                           filetypes=[("Text files", "*.txt"),
                                                      ("All files", "*")],
                                           defaultextension=".txt")
    c.bringToFront()
    if fileName:
        g.setGlobalOpenDir(fileName)
        g.chdir(fileName)
        c.importCommands.weave(fileName)
def exportHeadlines(self, event=None):
    """Export all headlines to an external file."""
    c = self
    filetypes = [("Text files", "*.txt"), ("All files", "*")]
    fileName = g.app.gui.runSaveFileDialog(c,
                                           title="Export Headlines",
                                           filetypes=filetypes,
                                           defaultextension=".txt")
    c.bringToFront()
    if fileName:
        g.setGlobalOpenDir(fileName)
        g.chdir(fileName)
        c.importCommands.exportHeadlines(fileName)
Beispiel #11
0
def open(self, event=None):
    '''Open a Leo window containing the contents of a .leo file.'''
    c = self
    # Close the window if this command completes successfully?
    closeFlag = (
        c.frame.startupWindow and
        # The window was open on startup
        not c.changed and not c.frame.saved and
        # The window has never been changed
        g.app.numberOfUntitledWindows == 1
        # Only one untitled window has ever been opened
    )
    table = [
        # 2010/10/09: Fix an interface blunder. Show all files by default.
        ("All files", "*"),
        g.fileFilters("LEOFILES"),
        ("Python files", "*.py"),
    ]
    fileName = ''.join(c.k.givenArgs)
    if not fileName:
        fileName = g.app.gui.runOpenFileDialog(
            c,
            title="Open",
            filetypes=table,
            defaultextension=g.defaultLeoFileExtension(c))
    c.bringToFront()
    c.init_error_dialogs()
    ok = False
    if fileName:
        if g.app.loadManager.isLeoFile(fileName):
            c2 = g.openWithFileName(fileName, old_c=c)
            if c2:
                c2.k.makeAllBindings()
                # Fix #579: Key bindings don't take for commands defined in plugins.
                g.chdir(fileName)
                g.setGlobalOpenDir(fileName)
            if c2 and closeFlag:
                g.app.destroyWindow(c.frame)
        elif c.looksLikeDerivedFile(fileName):
            # Create an @file node for files containing Leo sentinels.
            ok = c.importCommands.importDerivedFiles(parent=c.p,
                                                     paths=[fileName],
                                                     command='Open')
        else:
            # otherwise, create an @edit node.
            ok = c.createNodeFromExternalFile(fileName)
    c.raise_error_dialogs(kind='write')
    g.app.runAlreadyOpenDialog(c)
    # openWithFileName sets focus if ok.
    if not ok:
        c.initialFocusHelper()
def weave(self, event=None):
    '''Simulate a literate-programming weave operation by writing the outline to a text file.'''
    c = self
    filetypes = [("Text files", "*.txt"), ("All files", "*")]
    fileName = g.app.gui.runSaveFileDialog(c,
        initialfile="weave.txt",
        title="Weave",
        filetypes=filetypes,
        defaultextension=".txt")
    c.bringToFront()
    if fileName:
        g.setGlobalOpenDir(fileName)
        g.chdir(fileName)
        c.importCommands.weave(fileName)
def exportHeadlines(self, event=None):
    '''Export all headlines to an external file.'''
    c = self
    filetypes = [("Text files", "*.txt"), ("All files", "*")]
    fileName = g.app.gui.runSaveFileDialog(c,
        initialfile="headlines.txt",
        title="Export Headlines",
        filetypes=filetypes,
        defaultextension=".txt")
    c.bringToFront()
    if fileName:
        g.setGlobalOpenDir(fileName)
        g.chdir(fileName)
        c.importCommands.exportHeadlines(fileName)
def open(self, event=None):
    '''Open a Leo window containing the contents of a .leo file.'''
    c = self
    # Close the window if this command completes successfully?
    closeFlag = (
        c.frame.startupWindow and
            # The window was open on startup
        not c.changed and not c.frame.saved and
            # The window has never been changed
        g.app.numberOfUntitledWindows == 1
            # Only one untitled window has ever been opened
    )
    table = [
        # 2010/10/09: Fix an interface blunder. Show all files by default.
        ("All files", "*"),
        g.fileFilters("LEOFILES"),
        ("Python files", "*.py"),]
    fileName = ''.join(c.k.givenArgs)
    if not fileName:
        fileName = g.app.gui.runOpenFileDialog(c,
            title="Open",
            filetypes=table,
            defaultextension=g.defaultLeoFileExtension(c))
    c.bringToFront()
    c.init_error_dialogs()
    ok = False
    if fileName:
        if g.app.loadManager.isLeoFile(fileName):
            c2 = g.openWithFileName(fileName, old_c=c)
            if c2:
                c2.k.makeAllBindings()
                    # Fix #579: Key bindings don't take for commands defined in plugins.
                g.chdir(fileName)
                g.setGlobalOpenDir(fileName)
            if c2 and closeFlag:
                g.app.destroyWindow(c.frame)
        elif c.looksLikeDerivedFile(fileName):
            # Create an @file node for files containing Leo sentinels.
            ok = c.importCommands.importDerivedFiles(parent=c.p,
                paths=[fileName], command='Open')
        else:
            # otherwise, create an @edit node.
            ok = c.createNodeFromExternalFile(fileName)
    c.raise_error_dialogs(kind='write')
    g.app.runAlreadyOpenDialog(c)
    # openWithFileName sets focus if ok.
    if not ok:
        c.initialFocusHelper()
def flattenOutline(self, event=None):
    """
    Export the selected outline to an external file.
    The outline is represented in MORE format.
    """
    c = self
    filetypes = [("Text files", "*.txt"), ("All files", "*")]
    fileName = g.app.gui.runSaveFileDialog(c,
                                           title="Flatten Selected Outline",
                                           filetypes=filetypes,
                                           defaultextension=".txt")
    c.bringToFront()
    if fileName:
        g.setGlobalOpenDir(fileName)
        g.chdir(fileName)
        c.importCommands.flattenOutline(fileName)
def outlineToCWEB(self, event=None):
    """
    Export the selected outline to an external file.
    The outline is represented in CWEB format.
    """
    c = self
    filetypes = [("CWEB files", "*.w"), ("Text files", "*.txt"),
                 ("All files", "*")]
    fileName = g.app.gui.runSaveFileDialog(c,
                                           title="Outline To CWEB",
                                           filetypes=filetypes,
                                           defaultextension=".w")
    c.bringToFront()
    if fileName:
        g.setGlobalOpenDir(fileName)
        g.chdir(fileName)
        c.importCommands.outlineToWeb(fileName, "cweb")
Beispiel #17
0
def removeSentinels(self, event=None):
    '''Import one or more files, removing any sentinels.'''
    c = self
    types = [("All files", "*"), ("C/C++ files", "*.c"),
             ("C/C++ files", "*.cpp"), ("C/C++ files", "*.h"),
             ("C/C++ files", "*.hpp"), ("Java files", "*.java"),
             ("Lua files", "*.lua"), ("Pascal files", "*.pas"),
             ("Python files", "*.py")]
    names = g.app.gui.runOpenFileDialog(c,
                                        title="Remove Sentinels",
                                        filetypes=types,
                                        defaultextension=".py",
                                        multiple=True)
    c.bringToFront()
    if names:
        g.chdir(names[0])
        c.importCommands.removeSentinelsCommand(names)
def flattenOutline(self, event=None):
    '''
    Export the selected outline to an external file.
    The outline is represented in MORE format.
    '''
    c = self
    filetypes = [("Text files", "*.txt"), ("All files", "*")]
    fileName = g.app.gui.runSaveFileDialog(c,
        initialfile="flat.txt",
        title="Flatten Selected Outline",
        filetypes=filetypes,
        defaultextension=".txt")
    c.bringToFront()
    if fileName:
        g.setGlobalOpenDir(fileName)
        g.chdir(fileName)
        c.importCommands.flattenOutline(fileName)
def open_theme_file_helper(event, closeFlag, fn):
    '''Open a theme file and apply the theme.'''
    trace = False and not g.unitTesting
    c = event and event.get('c')
    if not c: return
    old_dir = g.os_path_abspath(os.curdir)
    themes_dir = g.os_path_finalize_join(g.app.loadDir, '..', 'themes')
    if fn:
        fn = c.styleSheetManager.find_theme_file(fn)
        if not fn: return
    else:
        fn = g.app.gui.runOpenFileDialog(c,
            title="Open Theme",
            filetypes=[
                 g.fileFilters("LEOFILES"),
                ("All files", "*"),
            ],
            defaultextension=g.defaultLeoFileExtension(c),
            startpath=themes_dir,
        )
    c.bringToFront()
    c.init_error_dialogs()
    # Adapted from c.open().
    if fn and g.app.loadManager.isLeoFile(fn):
        # Close the file if it is already open, provided there is another.
        aList = g.app.commanders()
        if len(aList) > 1:
            for c2 in aList:
                if trace: g.trace('COMPARE\n%s\n%s' % (fn, c2.fileName()))
                if fn == c2.fileName():
                    if trace: g.trace('===== CLOSING', fn)
                    c2.close(new_c=c)
                    break
        c2 = g.openWithFileName(fn, old_c=c)
        if c2:
            c2.k.makeAllBindings()
            g.chdir(fn)
            g.setGlobalOpenDir(fn)
            if closeFlag:
                g.app.destroyWindow(c2.frame)
                g.app.windowList.remove(c2.frame)
    os.chdir(old_dir)
    c.raise_error_dialogs(kind='write')
    g.app.runAlreadyOpenDialog(c)
    c.initialFocusHelper()
def saveTo(self, event=None, fileName=None, silent=False):
    """
    Save a Leo outline to a file, prompting for a new file name unless the
    fileName kwarg is given. Leave the file name of the Leo outline unchanged.
    
    kwarg: a file name, for use by scripts using Leo's bridge.
    """
    c = self
    p = c.p
    # Do this now: w may go away.
    w = g.app.gui.get_focus(c)
    inBody = g.app.gui.widget_name(w).startswith('body')
    if inBody:
        p.saveCursorAndScroll()
    if g.app.disableSave:
        g.es("save commands disabled", color="purple")
        return
    c.init_error_dialogs()
    # Add fileName keyword arg for leoBridge scripts.
    if not fileName:
        # set local fileName, _not_ c.mFileName
        fileName = ''.join(c.k.givenArgs)
    if not fileName:
        fileName = g.app.gui.runSaveFileDialog(
            c,
            initialfile=c.mFileName,
            title="Save To",
            filetypes=[
                ("Leo files", "*.leo *.db"),
            ],
            defaultextension=g.defaultLeoFileExtension(c))
    c.bringToFront()
    if fileName:
        c.fileCommands.saveTo(fileName, silent=silent)
        g.app.recentFilesManager.updateRecentFiles(fileName)
        g.chdir(fileName)
    c.raise_error_dialogs(kind='write')
    # *Safely* restore focus, without using the old w directly.
    if inBody:
        c.bodyWantsFocus()
        p.restoreCursorAndScroll()
    else:
        c.treeWantsFocus()
    c.outerUpdate()
Beispiel #21
0
def outlineToNoweb(self, event=None):
    '''
    Export the selected outline to an external file.
    The outline is represented in noweb format.
    '''
    c = self
    filetypes = [("Noweb files", "*.nw"), ("Text files", "*.txt"),
                 ("All files", "*")]
    fileName = g.app.gui.runSaveFileDialog(
        c,
        initialfile=self.outlineToNowebDefaultFileName,
        title="Outline To Noweb",
        filetypes=filetypes,
        defaultextension=".nw")
    c.bringToFront()
    if fileName:
        g.setGlobalOpenDir(fileName)
        g.chdir(fileName)
        c.importCommands.outlineToWeb(fileName, "noweb")
        c.outlineToNowebDefaultFileName = fileName
def outlineToCWEB(self, event=None):
    '''
    Export the selected outline to an external file.
    The outline is represented in CWEB format.
    '''
    c = self
    filetypes = [
        ("CWEB files", "*.w"),
        ("Text files", "*.txt"),
        ("All files", "*")]
    fileName = g.app.gui.runSaveFileDialog(c,
        initialfile="cweb.w",
        title="Outline To CWEB",
        filetypes=filetypes,
        defaultextension=".w")
    c.bringToFront()
    if fileName:
        g.setGlobalOpenDir(fileName)
        g.chdir(fileName)
        c.importCommands.outlineToWeb(fileName, "cweb")
def readOutlineOnly(self, event=None):
    '''Open a Leo outline from a .leo file, but do not read any derived files.'''
    c = self
    c.endEditing()
    fileName = g.app.gui.runOpenFileDialog(c,
        title="Read Outline Only",
        filetypes=[("Leo files", "*.leo"), ("All files", "*")],
        defaultextension=".leo")
    if not fileName:
        return
    try:
        # pylint: disable=assignment-from-no-return
        # Can't use 'with" because readOutlineOnly closes the file.
        theFile = open(fileName, 'r')
        g.chdir(fileName)
        c = g.app.newCommander(fileName)
        frame = c.frame
        frame.deiconify()
        frame.lift()
        c.fileCommands.readOutlineOnly(theFile, fileName) # closes file.
    except Exception:
        g.es("can not open:", fileName)
def removeSentinels(self, event=None):
    '''Import one or more files, removing any sentinels.'''
    c = self
    types = [
        ("All files", "*"),
        ("C/C++ files", "*.c"),
        ("C/C++ files", "*.cpp"),
        ("C/C++ files", "*.h"),
        ("C/C++ files", "*.hpp"),
        ("Java files", "*.java"),
        ("Lua files", "*.lua"),
        ("Pascal files", "*.pas"),
        ("Python files", "*.py")]
    names = g.app.gui.runOpenFileDialog(c,
        title="Remove Sentinels",
        filetypes=types,
        defaultextension=".py",
        multiple=True)
    c.bringToFront()
    if names:
        g.chdir(names[0])
        c.importCommands.removeSentinelsCommand(names)
def readFileIntoNode(self, event=None):
    '''Read a file into a single node.'''
    c = self
    undoType = 'Read File Into Node'
    c.endEditing()
    filetypes = [("All files", "*"), ("Python files", "*.py"), ("Leo files", "*.leo"),]
    fileName = g.app.gui.runOpenFileDialog(c,
        title="Read File Into Node",
        filetypes=filetypes,
        defaultextension=None)
    if not fileName: return
    s, e = g.readFileIntoString(fileName)
    if s is None:
        return
    g.chdir(fileName)
    s = '@nocolor\n' + s
    w = c.frame.body.wrapper
    p = c.insertHeadline(op_name=undoType)
    p.setHeadString('@read-file-into-node ' + fileName)
    p.setBodyString(s)
    w.setAllText(s)
    c.redraw(p)
def readOutlineOnly(self, event=None):
    '''Open a Leo outline from a .leo file, but do not read any derived files.'''
    c = self
    c.endEditing()
    fileName = g.app.gui.runOpenFileDialog(c,
        title="Read Outline Only",
        filetypes=[("Leo files", "*.leo"), ("All files", "*")],
        defaultextension=".leo")
    if not fileName:
        return
    try:
        # pylint: disable=assignment-from-no-return
        # Can't use 'with" because readOutlineOnly closes the file.
        theFile = open(fileName, 'r')
        g.chdir(fileName)
        c = g.app.newCommander(fileName)
        frame = c.frame
        frame.deiconify()
        frame.lift()
        c.fileCommands.readOutlineOnly(theFile, fileName) # closes file.
    except Exception:
        g.es("can not open:", fileName)
Beispiel #27
0
def saveTo(self, event=None, fileName=None):
    '''Save a Leo outline to a file, leaving the file associated with the Leo outline unchanged.'''
    c = self
    p = c.p
    # Do this now: w may go away.
    w = g.app.gui.get_focus(c)
    inBody = g.app.gui.widget_name(w).startswith('body')
    if inBody:
        p.saveCursorAndScroll()
    if g.app.disableSave:
        g.es("save commands disabled", color="purple")
        return
    c.init_error_dialogs()
    # Add fileName keyword arg for leoBridge scripts.
    if not fileName:
        # set local fileName, _not_ c.mFileName
        fileName = ''.join(c.k.givenArgs)
    if not fileName:
        fileName = g.app.gui.runSaveFileDialog(
            c,
            initialfile=c.mFileName,
            title="Save To",
            filetypes=[g.fileFilters('LEOFILES')],
            defaultextension=g.defaultLeoFileExtension(c))
    c.bringToFront()
    if fileName:
        fileName = g.ensure_extension(fileName, g.defaultLeoFileExtension(c))
        c.fileCommands.saveTo(fileName)
        g.app.recentFilesManager.updateRecentFiles(fileName)
        g.chdir(fileName)
    c.raise_error_dialogs(kind='write')
    # *Safely* restore focus, without using the old w directly.
    if inBody:
        c.bodyWantsFocus()
        p.restoreCursorAndScroll()
    else:
        c.treeWantsFocus()
    c.outerUpdate()
def saveTo(self, event=None, fileName=None):
    '''Save a Leo outline to a file, leaving the file associated with the Leo outline unchanged.'''
    c = self; p = c.p
    # Do this now: w may go away.
    w = g.app.gui.get_focus(c)
    inBody = g.app.gui.widget_name(w).startswith('body')
    if inBody:
        p.saveCursorAndScroll()
    if g.app.disableSave:
        g.es("save commands disabled", color="purple")
        return
    c.init_error_dialogs()
    # Add fileName keyword arg for leoBridge scripts.
    if not fileName:
        # set local fileName, _not_ c.mFileName
        fileName = ''.join(c.k.givenArgs)
    if not fileName:
        fileName = g.app.gui.runSaveFileDialog(c,
            initialfile=c.mFileName,
            title="Save To",
            filetypes=[g.fileFilters('LEOFILES')],
            defaultextension=g.defaultLeoFileExtension(c))
    c.bringToFront()
    if fileName:
        fileName = g.ensure_extension(fileName, g.defaultLeoFileExtension(c))
        c.fileCommands.saveTo(fileName)
        g.app.recentFilesManager.updateRecentFiles(fileName)
        g.chdir(fileName)
    c.raise_error_dialogs(kind='write')
    # *Safely* restore focus, without using the old w directly.
    if inBody:
        c.bodyWantsFocus()
        p.restoreCursorAndScroll()
    else:
        c.treeWantsFocus()
    c.outerUpdate()
def importAnyFile(self, event=None):
    '''Import one or more files.'''
    c = self
    ic = c.importCommands
    types = [
        ("All files", "*"),
        ("C/C++ files", "*.c"),
        ("C/C++ files", "*.cpp"),
        ("C/C++ files", "*.h"),
        ("C/C++ files", "*.hpp"),
        ("FreeMind files", "*.mm.html"),
        ("Java files", "*.java"),
        ("JavaScript files", "*.js"),
        # ("JSON files", "*.json"),
        ("Mindjet files", "*.csv"),
        ("MORE files", "*.MORE"),
        ("Lua files", "*.lua"),
        ("Pascal files", "*.pas"),
        ("Python files", "*.py"),
        ("Tabbed files", "*.txt"),
    ]
    names = g.app.gui.runOpenFileDialog(c,
        title="Import File",
        filetypes=types,
        defaultextension=".py",
        multiple=True)
    c.bringToFront()
    if names:
        g.chdir(names[0])
    else:
        names = []
    if not names:
        if g.unitTesting:
            # a kludge for unit testing.
            c.init_error_dialogs()
            c.raise_error_dialogs(kind='read')
        return
    # New in Leo 4.9: choose the type of import based on the extension.
    c.init_error_dialogs()
    derived = [z for z in names if c.looksLikeDerivedFile(z)]
    others = [z for z in names if z not in derived]
    if derived:
        ic.importDerivedFiles(parent=c.p, paths=derived)
    for fn in others:
        junk, ext = g.os_path_splitext(fn)
        if ext.startswith('.'):
            ext = ext[1:]
        if ext == 'csv':
            ic.importMindMap([fn])
        elif ext in ('cw', 'cweb'):
            ic.importWebCommand([fn], "cweb")
        # Not useful. Use @auto x.json instead.
        # elif ext == 'json':
            # ic.importJSON([fn])
        elif fn.endswith('mm.html'):
            ic.importFreeMind([fn])
        elif ext in ('nw', 'noweb'):
            ic.importWebCommand([fn], "noweb")
        elif ext == 'txt':
            ic.importFlattenedOutline([fn])
        else:
            # Make *sure* that parent.b is empty.
            last = c.lastTopLevel()
            parent = last.insertAfter()
            parent.v.h = 'Imported Files'
            ic.importFilesCommand(
                files=[fn],
                parent=parent,
                treeType='@auto', # was '@clean'
                    # Experimental: attempt to use permissive section ref logic.
            )
    c.raise_error_dialogs(kind='read')
def save(self, event=None, fileName=None):
    '''Save a Leo outline to a file.'''
    if False and g.app.gui.guiName() == 'curses':
        g.trace('===== Save disabled in curses gui =====')
        return
    c = self
    p = c.p
    # Do this now: w may go away.
    w = g.app.gui.get_focus(c)
    inBody = g.app.gui.widget_name(w).startswith('body')
    if inBody:
        p.saveCursorAndScroll()
    if g.unitTesting and g.app.unitTestDict.get('init_error_dialogs') is not None:
        # A kludge for unit testing:
        # indicated that c.init_error_dialogs and c.raise_error_dialogs
        # will be called below, *without* actually saving the .leo file.
        c.init_error_dialogs()
        c.raise_error_dialogs(kind='write')
        return
    if g.app.disableSave:
        g.es("save commands disabled", color="purple")
        return
    c.init_error_dialogs()
    # 2013/09/28: use the fileName keyword argument if given.
    # This supports the leoBridge.
    # Make sure we never pass None to the ctor.
    if fileName:
        c.frame.title = g.computeWindowTitle(fileName)
        c.mFileName = fileName
    if not c.mFileName:
        c.frame.title = ""
        c.mFileName = ""
    if c.mFileName:
        # Calls c.setChanged(False) if no error.
        g.app.syntax_error_files = []
        c.fileCommands.save(c.mFileName)
        c.syntaxErrorDialog()
    else:
        root = c.rootPosition()
        if not root.next() and root.isAtEditNode():
            # There is only a single @edit node in the outline.
            # A hack to allow "quick edit" of non-Leo files.
            # See https://bugs.launchpad.net/leo-editor/+bug/381527
            fileName = None
            # Write the @edit node if needed.
            if root.isDirty():
                c.atFileCommands.writeOneAtEditNode(root,
                    toString=False, force=True)
            c.setChanged(False)
        else:
            fileName = ''.join(c.k.givenArgs)
            if not fileName:
                fileName = g.app.gui.runSaveFileDialog(c,
                    initialfile=c.mFileName,
                    title="Save",
                    filetypes=[g.fileFilters('LEOFILES')],
                    defaultextension=g.defaultLeoFileExtension(c))
        c.bringToFront()
        if fileName:
            # Don't change mFileName until the dialog has suceeded.
            c.mFileName = g.ensure_extension(fileName, g.defaultLeoFileExtension(c))
            c.frame.title = c.computeWindowTitle(c.mFileName)
            c.frame.setTitle(c.computeWindowTitle(c.mFileName))
                # 2013/08/04: use c.computeWindowTitle.
            c.openDirectory = c.frame.openDirectory = g.os_path_dirname(c.mFileName)
                # Bug fix in 4.4b2.
            if g.app.qt_use_tabs and hasattr(c.frame, 'top'):
                c.frame.top.leo_master.setTabName(c, c.mFileName)
            c.fileCommands.save(c.mFileName)
            g.app.recentFilesManager.updateRecentFiles(c.mFileName)
            g.chdir(c.mFileName)
    # Done in FileCommands.save.
    # c.redraw_after_icons_changed()
    c.raise_error_dialogs(kind='write')
    # *Safely* restore focus, without using the old w directly.
    if inBody:
        c.bodyWantsFocus()
        p.restoreCursorAndScroll()
    else:
        c.treeWantsFocus()
def save(self, event=None, fileName=None):
    '''Save a Leo outline to a file.'''
    if False and g.app.gui.guiName() == 'curses':
        g.trace('===== Save disabled in curses gui =====')
        return
    c = self
    p = c.p
    # Do this now: w may go away.
    w = g.app.gui.get_focus(c)
    inBody = g.app.gui.widget_name(w).startswith('body')
    if inBody:
        p.saveCursorAndScroll()
    if g.unitTesting and g.app.unitTestDict.get('init_error_dialogs') is not None:
        # A kludge for unit testing:
        # indicated that c.init_error_dialogs and c.raise_error_dialogs
        # will be called below, *without* actually saving the .leo file.
        c.init_error_dialogs()
        c.raise_error_dialogs(kind='write')
        return
    if g.app.disableSave:
        g.es("save commands disabled", color="purple")
        return
    c.init_error_dialogs()
    # 2013/09/28: use the fileName keyword argument if given.
    # This supports the leoBridge.
    # Make sure we never pass None to the ctor.
    if fileName:
        c.frame.title = g.computeWindowTitle(fileName)
        c.mFileName = fileName
    if not c.mFileName:
        c.frame.title = ""
        c.mFileName = ""
    if c.mFileName:
        # Calls c.setChanged(False) if no error.
        g.app.syntax_error_files = []
        c.fileCommands.save(c.mFileName)
        c.syntaxErrorDialog()
    else:
        root = c.rootPosition()
        if not root.next() and root.isAtEditNode():
            # There is only a single @edit node in the outline.
            # A hack to allow "quick edit" of non-Leo files.
            # See https://bugs.launchpad.net/leo-editor/+bug/381527
            fileName = None
            # Write the @edit node if needed.
            if root.isDirty():
                c.atFileCommands.writeOneAtEditNode(root,
                    toString=False, force=True)
            c.setChanged(False)
        else:
            fileName = ''.join(c.k.givenArgs)
            if not fileName:
                fileName = g.app.gui.runSaveFileDialog(c,
                    initialfile=c.mFileName,
                    title="Save",
                    filetypes=[g.fileFilters('LEOFILES')],
                    defaultextension=g.defaultLeoFileExtension(c))
        c.bringToFront()
        if fileName:
            # Don't change mFileName until the dialog has suceeded.
            c.mFileName = g.ensure_extension(fileName, g.defaultLeoFileExtension(c))
            c.frame.title = c.computeWindowTitle(c.mFileName)
            c.frame.setTitle(c.computeWindowTitle(c.mFileName))
                # 2013/08/04: use c.computeWindowTitle.
            c.openDirectory = c.frame.openDirectory = g.os_path_dirname(c.mFileName)
                # Bug fix in 4.4b2.
            if g.app.qt_use_tabs and hasattr(c.frame, 'top'):
                c.frame.top.leo_master.setTabName(c, c.mFileName)
            c.fileCommands.save(c.mFileName)
            g.app.recentFilesManager.updateRecentFiles(c.mFileName)
            g.chdir(c.mFileName)
    # Done in FileCommands.save.
    # c.redraw_after_icons_changed()
    c.raise_error_dialogs(kind='write')
    # *Safely* restore focus, without using the old w directly.
    if inBody:
        c.bodyWantsFocus()
        p.restoreCursorAndScroll()
    else:
        c.treeWantsFocus()
def importAnyFile(self, event=None):
    '''Import one or more files.'''
    c = self
    ic = c.importCommands
    types = [
        ("All files", "*"),
        ("C/C++ files", "*.c"),
        ("C/C++ files", "*.cpp"),
        ("C/C++ files", "*.h"),
        ("C/C++ files", "*.hpp"),
        ("FreeMind files", "*.mm.html"),
        ("Java files", "*.java"),
        ("JavaScript files", "*.js"),
        # ("JSON files", "*.json"),
        ("Mindjet files", "*.csv"),
        ("MORE files", "*.MORE"),
        ("Lua files", "*.lua"),
        ("Pascal files", "*.pas"),
        ("Python files", "*.py"),
        ("Tabbed files", "*.txt"),
    ]
    names = g.app.gui.runOpenFileDialog(c,
        title="Import File",
        filetypes=types,
        defaultextension=".py",
        multiple=True)
    c.bringToFront()
    if names:
        g.chdir(names[0])
    else:
        names = []
    if not names:
        if g.unitTesting:
            # a kludge for unit testing.
            c.init_error_dialogs()
            c.raise_error_dialogs(kind='read')
        return
    # New in Leo 4.9: choose the type of import based on the extension.
    c.init_error_dialogs()
    derived = [z for z in names if c.looksLikeDerivedFile(z)]
    others = [z for z in names if z not in derived]
    if derived:
        ic.importDerivedFiles(parent=c.p, paths=derived)
    for fn in others:
        junk, ext = g.os_path_splitext(fn)
        if ext.startswith('.'):
            ext = ext[1:]
        if ext == 'csv':
            ic.importMindMap([fn])
        elif ext in ('cw', 'cweb'):
            ic.importWebCommand([fn], "cweb")
        # Not useful. Use @auto x.json instead.
        # elif ext == 'json':
            # ic.importJSON([fn])
        elif fn.endswith('mm.html'):
            ic.importFreeMind([fn])
        elif ext in ('nw', 'noweb'):
            ic.importWebCommand([fn], "noweb")
        elif ext == 'txt':
            ic.importFlattenedOutline([fn])
        else:
            # Make *sure* that parent.b is empty.
            last = c.lastTopLevel()
            parent = last.insertAfter()
            parent.v.h = 'Imported Files'
            ic.importFilesCommand(
                files=[fn],
                parent=parent,
                treeType='@auto', # was '@clean'
                    # Experimental: attempt to use permissive section ref logic.
            )
    c.raise_error_dialogs(kind='read')
def save(self, event=None, fileName=None):
    """
    Save a Leo outline to a file, using the existing file name unless
    the fileName kwarg is given.

    kwarg: a file name, for use by scripts using Leo's bridge.
    """
    c = self
    p = c.p
    # Do this now: w may go away.
    w = g.app.gui.get_focus(c)
    inBody = g.app.gui.widget_name(w).startswith('body')
    if inBody:
        p.saveCursorAndScroll()
    if g.app.disableSave:
        g.es("save commands disabled", color="purple")
        return
    c.init_error_dialogs()
    # 2013/09/28: use the fileName keyword argument if given.
    # This supports the leoBridge.
    # Make sure we never pass None to the ctor.
    if fileName:
        c.frame.title = g.computeWindowTitle(fileName)
        c.mFileName = fileName
    if not c.mFileName:
        c.frame.title = ""
        c.mFileName = ""
    if c.mFileName:
        # Calls c.clearChanged() if no error.
        g.app.syntax_error_files = []
        c.fileCommands.save(c.mFileName)
        c.syntaxErrorDialog()
    else:
        root = c.rootPosition()
        if not root.next() and root.isAtEditNode():
            # There is only a single @edit node in the outline.
            # A hack to allow "quick edit" of non-Leo files.
            # See https://bugs.launchpad.net/leo-editor/+bug/381527
            fileName = None
            # Write the @edit node if needed.
            if root.isDirty():
                c.atFileCommands.writeOneAtEditNode(root)
            c.clearChanged()  # Clears all dirty bits.
        else:
            fileName = ''.join(c.k.givenArgs)
            if not fileName:
                fileName = g.app.gui.runSaveFileDialog(
                    c,
                    title="Save",
                    filetypes=[
                        ("Leo files", "*.leo *.db"),
                    ],
                    defaultextension=g.defaultLeoFileExtension(c))
        c.bringToFront()
        if fileName:
            # Don't change mFileName until the dialog has suceeded.
            c.mFileName = g.ensure_extension(fileName,
                                             g.defaultLeoFileExtension(c))
            c.frame.title = c.computeWindowTitle(c.mFileName)
            c.frame.setTitle(c.computeWindowTitle(c.mFileName))
            c.openDirectory = c.frame.openDirectory = g.os_path_dirname(
                c.mFileName)
            if hasattr(c.frame, 'top'):
                c.frame.top.leo_master.setTabName(c, c.mFileName)
            c.fileCommands.save(c.mFileName)
            g.app.recentFilesManager.updateRecentFiles(c.mFileName)
            g.chdir(c.mFileName)
    # FileCommands.save calls c.redraw_after_icons_changed()
    c.raise_error_dialogs(kind='write')
    # *Safely* restore focus, without using the old w directly.
    if inBody:
        c.bodyWantsFocus()
        p.restoreCursorAndScroll()
    else:
        c.treeWantsFocus()