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()
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)
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=f"Create myLeoSettings.leo in {homeLeoDir}?", ) if ok == 'no': return None # 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
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
def open_unl(self, unl): parts = unl.split("#", 1) c = g.openWithFileName(parts[0]) if len(parts) > 1: segs = parts[1].split("-->") g.findUNL(segs, c)
def unl_to_pos(self, c2, for_p, bookmark=False): """"c2 may be an outline (like c) or an UNL (string) return c, p where c is an outline and p is a node to copy data to in that outline for_p is the p to be copied - needed to check for invalid recursive copy / move """ if g.isString(c2): # c2 is an UNL indicating where to insert full_path = c2 path, unl = full_path.split('#', 1) c2 = g.openWithFileName(path, old_c=self.c) self.c.bringToFront(c2=self.c) found, maxdepth, maxp = g.recursiveUNLFind(unl.split('-->'), c2) if found: if not bookmark and (for_p == maxp or for_p.isAncestorOf(maxp)): g.es("Invalid move") return None, None nd = maxp.insertAsNthChild(0) else: g.es("Could not find '%s'"%full_path) self.c.bringToFront(c2=self.c) return None, None else: # c2 is an outline, insert at top nd = c2.rootPosition().insertAfter() nd.copy().back().moveAfter(nd) return c2, nd
def unl_to_pos(self, unl, for_p): """"unl may be an outline (like c) or an UNL (string) return c, p where c is an outline and p is a node to copy data to in that outline for_p is the p to be copied - needed to check for invalid recursive copy / move """ # COPIED FROM quickMove.py # unl is an UNL indicating where to insert full_path = unl path, unl = full_path.split('#') c2 = g.openWithFileName(path, old_c=self.c) self.c.bringToFront(c2=self.c) found, maxdepth, maxp = g.recursiveUNLFind(unl.split('-->'), c2) if found: if (for_p == maxp or for_p.isAncestorOf(maxp)): g.es("Invalid move") return None, None nd = maxp else: g.es("Could not find '%s'"%full_path) self.c.bringToFront(c2=self.c) return None, None return c2, nd
def open_unl(self,unl): parts = unl.split("#",1) c = g.openWithFileName(parts[0]) if len(parts) > 1: segs = parts[1].split("-->") g.recursiveUNLSearch(segs, c)
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
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()
def unl2pos(unl, cmdr=None): """ Univeral Node Locator to Leo-Editor Position Arguments: unl: Universal Node Locator cmdr: Optional Leo-Editor commander for the file containing the node(s) specified by unl. Default: None Returns: cmdrUnl: Commander for the file containing the position(s) in posList. posList: A list containing in tree order all the positions that satisfy the UNL. [] (empty list) --> No position satisfies the UNL Exceptions: ValueError If unl contains a file pathname part and cmdr is not None, then ValueError is raised because both the pathname part and the cmdr specify files. This is either redundant or contradictory. If unl does NOT contain a file pathname and cmdr is None, then ValueError is raised because there is no specification of the target file. """ pathname, nodePart = unlSplit(unl) if (not pathname) and (cmdr is None): raise ValueError('No commander and No pathname in {0}'.format(unl)) if pathname and (cmdr is not None): raise ValueError('Commander for {0} and pathname in {1}'.format(cmdr.fileName(), unl)) if pathname: cmdrUnl = leoG.openWithFileName(pathname) else: cmdrUnl = cmdr unlList = _unlParseNodePart(nodePart) return cmdrUnl, _descendHdl(cmdrUnl, unlList)
def unl_to_pos(self, unl, for_p): """"unl may be an outline (like c) or an UNL (string) return c, p where c is an outline and p is a node to copy data to in that outline for_p is the p to be copied - needed to check for invalid recursive copy / move """ # COPIED FROM quickMove.py # unl is an UNL indicating where to insert full_path = unl path, unl = full_path.split('#', 1) c2 = g.openWithFileName(path, old_c=self.c) self.c.bringToFront(c2=self.c) found, maxdepth, maxp = g.recursiveUNLFind(unl.split('-->'), c2) if found: if (for_p == maxp or for_p.isAncestorOf(maxp)): g.es("Invalid move") return None, None nd = maxp else: g.es("Could not find '%s'"%full_path) self.c.bringToFront(c2=self.c) return None, None return c2, nd
def ns_provide(self, id_): if id_.startswith('_leo_bookmarks_show'): c = self.c v = None if ':' in id_: gnx = id_.split(':')[1] if not gnx and '_leo_bookmarks_show' in c.db: gnx = c.db['_leo_bookmarks_show'] # first try old style local gnx lookup for i in c.all_nodes(): if str(i.gnx) == gnx: v = i break else: # use UNL lookup file_, UNL = gnx.split('#', 1) other_c = g.openWithFileName(file_, old_c=c) if other_c != c: c.bringToFront() g.es("NOTE: bookmarks for this outline\nare in a different outline:\n '%s'"%file_) ok, depth, other_p = g.recursiveUNLFind(UNL.split('-->'), other_c) if ok: v = other_p.v else: g.es("Couldn't find '%s'"%gnx) if v is None: v = c.p.v bmd = BookMarkDisplay(self.c, v=v) return bmd.w
def openRecentFile(self, event=None, fn=None): c = self # Automatically close the previous window if... 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. if g.doHook("recentfiles1", c=c, p=c.p, v=c.p, fileName=fn, closeFlag=closeFlag): return c2 = g.openWithFileName(fn, old_c=c) if c2: g.app.makeAllBindings() if closeFlag and c2 and c2 != c: g.app.destroyWindow(c.frame) c2.setLog() g.doHook("recentfiles2", c=c2, p=c2.p, v=c2.p, fileName=fn, closeFlag=closeFlag)
def openLeoFile(self, fileName): """Open a .leo file, or create a new Leo frame if no fileName is given.""" g = self.g g.app.silentMode = self.silentMode useLog = False if not self.isOpen(): return None if self.useCaches: self.reopen_cachers() else: g.app.db = g.NullObject() fileName = self.completeFileName(fileName) c = g.openWithFileName(fileName) # #2489. # Leo 6.3: support leoInteg. g.app.windowList.append(c.frame) if not self.useCaches: c.db = g.NullObject() # New in Leo 5.1. An alternate fix for bug #130. # When using a bridge Leo might open a file, modify it, # close it, reopen it and change it all within one second. # In that case, this code must properly compute the next # available gnx by scanning the entire outline. g.app.nodeIndices.compute_last_index(c) if useLog: g.app.gui.log = log = c.frame.log log.isNull = False log.enabled = True return c
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('%s %0.2fsec' % (fileName, (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
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)
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)
def openLeoSettings(self, event=None): '''Open leoSettings.leo in a new Leo window.''' c, lm = self, g.app.loadManager path = lm.computeLeoSettingsPath() if path: return g.openWithFileName(path, old_c=c) g.es('not found: leoSettings.leo') return None
def openMyLeoSettings(self, event=None): """Open myLeoSettings.leo in a new Leo window.""" c, lm = self, g.app.loadManager path = lm.computeMyLeoSettingsPath() if path: return g.openWithFileName(path, old_c=c) g.es('not found: myLeoSettings.leo') return createMyLeoSettings(c)
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)
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)
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)
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)
def openMyLeoSettings(self, event=None): '''Open myLeoSettings.leo in a new Leo window.''' c, lm = self, g.app.loadManager path = lm.computeMyLeoSettingsPath() if path: return g.openWithFileName(path, old_c=c) else: g.es('not found: myLeoSettings.leo') return createMyLeoSettings(c)
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)
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)
def openDesktopIntegration(self, event=None): """Open Desktop-integration.leo.""" c = self fileName = g.os_path_finalize_join( g.app.loadDir, '..', 'scripts', 'desktop-integration.leo') # 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)
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 leoDocumentation(self, event=None): '''Open LeoDocs.leo in a new Leo window.''' c = self name = "LeoDocs.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)
def openLeoPyRef(self, event=None): """Open leoPyRef.leo in a new Leo window.""" c = self path = g.os_path_finalize_join(g.app.loadDir, "..", "core", "LeoPyRef.leo") # Only call g.openWithFileName if the file exists. if g.os_path_exists(path): c2 = g.openWithFileName(path, old_c=c) if c2: return g.es('LeoPyRef.leo not found')
def open_outline(self, fn): """ Find the commander for fn, creating a new outline tab if necessary. Using open commanders works because we always read entire .leo files. """ for frame in g.app.windowList: if frame.c.fileName() == fn: return frame.c gui = None if self.visible else g.app.nullGui return g.openWithFileName(fn, gui=gui)
def openLeoPy(self, event=None): '''Open leoPy.leo in a new Leo window.''' c = self names = ('leoPy.leo', 'LeoPyRef.leo',) # Used in error message. for name in names: fileName = g.os_path_finalize_join(g.app.loadDir, "..", "core", name) # 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:', ', '.join(names))
def openLeoPlugins(self, event=None): '''Open leoPlugins.leo in a new Leo window.''' c = self names = ('leoPlugins.leo', 'leoPluginsRef.leo',) # Used in error message. for name in names: fileName = g.os_path_finalize_join(g.app.loadDir, "..", "plugins", 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:', ', '.join(names))
def openLeoPy(self, event=None): """Open leoPy.leo or LeoPyRef.leo in a new Leo window.""" c = self names = ('leoPy.leo', 'LeoPyRef.leo',) # Used in error message. for name in names: fileName = g.os_path_finalize_join(g.app.loadDir, "..", "core", name) # 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:', ', '.join(names))
def openCheatSheet(self, event=None): """Open leo/doc/cheatSheet.leo""" c = self fn = g.os_path_finalize_join(g.app.loadDir, '..', 'doc', 'CheatSheet.leo') if not g.os_path_exists(fn): g.es(f"file not found: {fn}") return c2 = g.openWithFileName(fn, old_c=c) p = g.findNodeAnywhere(c2, "Leo's cheat sheet") if p: c2.selectPosition(p) p.expand() c2.redraw()
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 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 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 g.es('file not found: %s' % fn) return None
def runMainLoop(self, fileName=None): '''The main loop for the browser gui.''' # pylint: disable=arguments-differ if fileName: print('LeoWapp running: %s...' % g.shortFileName(fileName)) else: print('LeoWapp running...') if 0: # Run all unit tests. path = g.os_path_finalize_join( g.app.loadDir, '..', 'test', 'unittest.leo') c = g.openWithFileName(path, gui=self) c.findCommands.ftm = g.NullObject() # A hack. Maybe the NullGui should do this. c.debugCommands.runAllUnitTestsLocally() print('calling sys.exit(0)') sys.exit(0)
def runMainLoop(self, fileName=None): '''The main loop for the browser gui.''' # pylint: disable=arguments-differ if fileName: print('LeoWapp running: %s...' % g.shortFileName(fileName)) else: print('LeoWapp running...') if 0: # Run all unit tests. path = g.os_path_finalize_join(g.app.loadDir, '..', 'test', 'unittest.leo') c = g.openWithFileName(path, gui=self) c.findCommands.ftm = g.NullObject() # A hack. Maybe the NullGui should do this. c.debugCommands.runAllUnitTestsLocally() print('calling sys.exit(0)') sys.exit(0)
def ns_provide(self, id_): if id_.startswith('_leo_bookmarks_show'): c = self.c v = None if ':' in id_: gnx = id_.split(':')[1] if not gnx and '_leo_bookmarks_show' in c.db: gnx = c.db['_leo_bookmarks_show'] # first try old style local gnx lookup for i in c.all_nodes(): if str(i.gnx) == gnx: v = i break else: # use UNL lookup if '#' in gnx: file_, UNL = gnx.split('#', 1) other_c = g.openWithFileName(file_, old_c=c) else: file_, UNL = None, gnx other_c = c if other_c != c: # don't use c.bringToFront(), it breaks --minimize if hasattr(g.app.gui, 'frameFactory'): factory = g.app.gui.frameFactory if factory and hasattr(factory, 'setTabForCommander'): factory.setTabForCommander(c) g.es( "NOTE: bookmarks for this outline\nare in a different outline:\n '%s'" % file_) ok, depth, other_p = g.recursiveUNLFind( UNL.split('-->'), other_c) if ok: v = other_p.v else: g.es("Couldn't find '%s'" % gnx) if v is None: v = c.p.v bmd = BookMarkDisplay(self.c, v=v) return bmd.w return None
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 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 ns_provide(self, id_): if id_.startswith("_leo_bookmarks_show"): c = self.c v = None if ":" in id_: gnx = id_.split(":")[1] if not gnx and "_leo_bookmarks_show" in c.db: gnx = c.db["_leo_bookmarks_show"] # first try old style local gnx lookup for i in c.all_nodes(): if str(i.gnx) == gnx: v = i break else: # use UNL lookup if "#" in gnx: file_, UNL = gnx.split("#", 1) other_c = g.openWithFileName(file_, old_c=c) else: file_, UNL = None, gnx other_c = c if other_c != c: # don't use c.bringToFront(), it breaks --minimize if hasattr(g.app.gui, "frameFactory"): factory = g.app.gui.frameFactory if factory and hasattr(factory, "setTabForCommander"): factory.setTabForCommander(c) g.es("NOTE: bookmarks for this outline\nare in a different outline:\n '%s'" % file_) ok, depth, other_p = g.recursiveUNLFind(UNL.split("-->"), other_c) if ok: v = other_p.v else: g.es("Couldn't find '%s'" % gnx) if v is None: v = c.p.v bmd = BookMarkDisplay(self.c, v=v) return bmd.w
def onUrl1 (tag,keywords): """Redefine the @url functionality of Leo Core: allows jumping to URL _and UNLs_. Spaces are now allowed in URLs.""" trace = False and not g.unitTesting c = keywords.get("c") p = keywords.get("p") v = keywords.get("v") # The url key is new in 4.3 beta 2. # The url ends with the first blank, unless either single or double quotes are used. url = keywords.get('url') or '' url = url.replace('%20',' ') #@+at Most browsers should handle the following urls: # ftp://ftp.uu.net/public/whatever. # http://localhost/MySiteUnderDevelopment/index.html # file://home/me/todolist.html #@@c try: try: urlTuple = urlparse.urlsplit(url) if trace: logUrl(urlTuple) except: g.es("exception interpreting the url " + url) g.es_exception() return False if not urlTuple[0]: urlProtocol = "file" # assume this protocol by default else: urlProtocol = urlTuple[0] if urlProtocol == "file": if urlTuple[2].endswith(".leo"): if hasattr(c.frame.top, 'update_idletasks'): # this is Tk only - TNB c.frame.top.update_idletasks() # Clear remaining events, so they don't interfere. filename = os.path.expanduser(urlTuple[2]) filename = g.os_path_expandExpression(filename,c=c) # 2011/01/25: bogomil if not os.path.isabs(filename): filename = os.path.normpath(os.path.join(c.getNodePath(p),filename)) ok,frame = g.openWithFileName(filename, c) if ok: #@+<< go to the node>> #@+node:ekr.20110602070710.3433: *3* <<go to the node>> c2 = frame.c if urlTuple [4]: # we have a UNL! recursiveUNLSearch(urlTuple[4].split("-->"), c2) # Disable later call to c.onClick so the focus stays in c2. c.doubleClickFlag = True #@-<< go to the node>> elif urlTuple[0] == "": #@+<< go to node in present outline >> #@+node:ekr.20110602070710.3434: *3* << go to node in present outline >> if urlTuple [2]: recursiveUNLSearch(urlTuple[2].split("-->"), c) #@-<< go to node in present outline >> else: #@+<<invoke external browser>> #@+node:ekr.20110602070710.3435: *3* <<invoke external browser>> import webbrowser # Mozilla throws a weird exception, then opens the file! try: webbrowser.open(url) except: pass #@-<<invoke external browser>> else: #@+<<invoke external browser>> #@+node:ekr.20110602070710.3435: *3* <<invoke external browser>> import webbrowser # Mozilla throws a weird exception, then opens the file! try: webbrowser.open(url) except: pass #@-<<invoke external browser>> return True # PREVENTS THE EXECUTION OF LEO'S CORE CODE IN # Code-->Gui Base classes-->@thin leoFrame.py-->class leoTree-->tree.OnIconDoubleClick (@url) except: g.es("exception opening " + url) g.es_exception() return False
def add_bookmark(self): """Return the file like 'f' that leo_interface.send_head makes """ parsed_url = urlparse.urlparse(self.request_handler.path) query = urlparse.parse_qs(parsed_url.query) # print(parsed_url.query) # print(query) name = query.get('name', ['NO TITLE'])[0] url = query['url'][0] one_tab_links = [] if 'www.one-tab.com' in url.lower(): one_tab_links = query.get('ln', [''])[0] one_tab_links = json.loads(one_tab_links) c = None # outline for bookmarks previous = None # previous bookmark for adding selections parent = None # parent node for new bookmarks using_root = False path = self.bookmark_unl # g.trace(path) if path: parsed = urlparse.urlparse(path) leo_path = os.path.expanduser(parsed.path) c = g.openWithFileName(leo_path,old_c=None) if c: g.es_print("Opened '%s' for bookmarks"% path) if parsed.fragment: g.recursiveUNLSearch(parsed.fragment.split("-->"),c) parent = c.currentPosition() if parent.hasChildren(): previous = parent.getFirstChild() else: g.es_print("Failed to open '%s' for bookmarks"%self.bookmark_unl) if c is None: using_root = True c = g.app.commanders()[0] parent = c.rootPosition() previous = c.rootPosition() f = StringIO() if previous and url == previous.b.split('\n',1)[0]: # another marking of the same page, just add selection self.add_bookmark_selection( previous, query.get('selection', [''])[0]) c.selectPosition(previous) # required for body text redraw c.redraw() f.write(""" <body onload="setTimeout('window.close();', 350);" style='font-family:mono'> <p>Selection added</p></body>""") return f if '_form' in query: # got extra details, save to new node f.write(""" <body onload="setTimeout('window.close();', 350);" style='font-family:mono'> <p>Bookmark saved</p></body>""") if using_root: nd = parent.insertAfter() nd.moveToRoot(c.rootPosition()) else: nd = parent.insertAsNthChild(0) if g.pluginIsLoaded('leo.plugins.bookmarks'): nd.h = name else: nd.h = '@url '+name selection = query.get('selection', [''])[0] if selection: selection = '\n\n"""\n'+selection+'\n"""' tags = query.get('tags', [''])[0] if one_tab_links: if tags: tags += ', OneTabList' else: tags = 'OneTabList' self.get_one_tab(one_tab_links, nd) nd.b = "%s\n\nTags: %s\n\n%s\n\nCollected: %s%s\n\n%s" % ( url, tags, query.get('_name', [''])[0], time.strftime("%c"), selection, query.get('description', [''])[0], ) c.setChanged(True) c.selectPosition(nd) # required for body text redraw c.redraw() return f # send form to collect extra details f.write(""" <html><head><style> body {font-family:mono; font-size: 80%%;} th {text-align:right} </style><title>Leo Add Bookmark</title> </head><body onload='document.getElementById("tags").focus();'> <form method='GET' action='/_/add/bkmk/'> <input type='hidden' name='_form' value='1'/> <input type='hidden' name='_name' value=%s/> <input type='hidden' name='selection' value=%s/> <input type='hidden' name='ln' value=%s/> <table> <tr><th>Tags:</th><td><input id='tags' name='tags' size='60'/>(comma sep.)</td></tr> <tr><th>Title:</th><td><input name='name' value=%s size='60'/></td></tr> <tr><th>URL:</th><td><input name='url' value=%s size='60'/></td></tr> <tr><th>Notes:</th><td><textarea name='description' cols='60' rows='6'></textarea></td></tr> </table> <input type='submit' value='Save'/><br/> </form> </body></html>""" % (quoteattr(name), quoteattr(query.get('selection', [''])[0]), quoteattr(json.dumps(one_tab_links)), quoteattr(name), quoteattr(url))) return f