Welcome to Leo’s API documentation!¶
Contents:
leo Package¶
Subpackages¶
core Package¶
core
Package¶
bzr_version
Module¶
format-code
Module¶
leoApp
Module¶
-
class
leo.core.leoApp.
IdleTimeManager
[source]¶ Bases:
object
A singleton class to manage idle-time handling. This class handles all details of running code at idle time, including running ‘idle’ hooks.
Any code can call g.app.idleTimeManager.add_callback(callback) to cause the callback to be called at idle time forever.
-
on_idle_count
= 0¶
-
-
class
leo.core.leoApp.
LeoApp
[source]¶ Bases:
object
A class representing the Leo application itself.
Ivars of this class are Leo’s global variables.
-
closeLeoWindow
(frame, new_c=None, finish_quit=True)[source]¶ Attempt to close a Leo window.
Return False if the user veto’s the close.
- finish_quit - usually True, close Leo when last file closes, but
- False when closing an already-open-elsewhere file during initial load, so UI remains for files further along the command line.
-
createDefaultGui
(fileName='', verbose=False)[source]¶ A convenience routines for plugins to create the default gui class.
-
createQtGui
(fileName='', verbose=False)[source]¶ A convenience routines for plugins to create the Qt gui class.
-
createWxGui
(fileName='', verbose=False)[source]¶ A convenience routines for plugins to create the wx gui class.
-
forceShutdown
()[source]¶ Forces an immediate shutdown of Leo at any time.
In particular, may be called from plugins during startup.
-
forgetOpenFile
(fn, force=False)[source]¶ Forget the open file, so that is no longer considered open.
-
listenToLog
(event=None)[source]¶ A socket listener, listening on localhost. See: https://docs.python.org/2/howto/logging-cookbook.html#sending-and-receiving-logging-events-across-a-network
Start this listener first, then start the broadcaster.
leo/plugins/cursesGui2.py is a typical broadcaster.
-
makeAllBindings
()[source]¶ LeoApp.makeAllBindings:
Call c.k.makeAllBindings for all open commanders c.
-
newCommander
(fileName, relativeFileName=None, gui=None, previousSettings=None)[source]¶ Create a commander and its view frame for the Leo main window.
-
scanner_for_at_auto
(c, p, **kwargs)[source]¶ A factory returning a scanner function for p, an @auto node.
-
scanner_for_ext
(c, ext, **kwargs)[source]¶ A factory returning a scanner function for the given file extension.
-
-
class
leo.core.leoApp.
LoadManager
[source]¶ Bases:
object
A class to manage loading .leo files, including configuration files.
-
adjustSysPath
()[source]¶ Adjust sys.path to enable imports as usual with Leo.
This method is no longer needed:
- g.importModule will import from the ‘external’ or ‘extensions’ folders as needed without altering sys.path.
- Plugins now do fully qualified imports.
-
checkForDuplicateShortcuts
(c, d)[source]¶ Check for duplicates in an “inverted” dictionary d whose keys are strokes and whose values are lists of BindingInfo nodes.
Duplicates happen only if panes conflict.
-
computeLocalSettings
(c, settings_d, bindings_d, localFlag)[source]¶ Merge the settings dicts from c’s outline into new copies of settings_d and bindings_d.
-
computeMyLeoSettingsPath
()[source]¶ Return the full path to myLeoSettings.leo.
The “footnote”: Get the local directory from lm.files[0]
-
computeStandardDirectories
()[source]¶ Compute the locations of standard directories and set the corresponding ivars.
-
computeThemeDirectories
()[source]¶ Return a list of existing directories that might contain theme .leo files.
-
computeWorkbookFileName
()[source]¶ Return the name of the workbook.
Return None only if: 1. The workbook does not exist. 2. We are unit testing or in batch mode.
-
createAllImporetersData
()[source]¶ New in Leo 5.5:
Create global data structures describing importers and writers.
-
getPreviousSettings
(fn)[source]¶ Return the settings in effect for fn. Typically, this involves pre-reading fn.
-
initWrapperLeoFile
(c, fn)[source]¶ Create an empty file if the external fn is empty.
Otherwise, create an @edit or @file node for the external file.
-
invert
(d)[source]¶ Invert a shortcut dict whose keys are command names, returning a dict whose keys are strokes.
-
loadLocalFile
(fn, gui, old_c)[source]¶ Completely read a file, creating the corresonding outline.
1. If fn is an existing .leo file (possibly zipped), read it twice: the first time with a NullGui to discover settings, the second time with the requested gui to create the outline.
2. If fn is an external file: get settings from the leoSettings.leo and myLeoSetting.leo, then create a “wrapper” outline continain an @file node for the external file.
3. If fn is empty: get settings from the leoSettings.leo and myLeoSetting.leo or default settings, or open an empty outline.
-
mergeShortcutsDicts
(c, old_d, new_d, localFlag)[source]¶ Create a new dict by overriding all shortcuts in old_d by shortcuts in new_d.
Both old_d and new_d remain unchanged.
-
openFileByName
(fn, gui, old_c, previousSettings)[source]¶ Read the local file whose full path is fn using the given gui. fn may be a Leo file (including .leo or zipped file) or an external file.
This is not a pre-read: the previousSettings always exist and the commander created here persists until the user closes the outline.
Reads the entire outline if fn exists and is a .leo file or zipped file. Creates an empty outline if fn is a non-existent Leo file. Creates an wrapper outline if fn is an external file, existing or not.
-
openSettingsFile
(fn)[source]¶ Open a settings file with a null gui. Return the commander.
The caller must init the c.config object.
-
parse_importer_dict
(sfn, m)[source]¶ Set entries in g.app.classDispatchDict, g.app.atAutoDict and g.app.atAutoNames using entries in m.importer_dict.
-
parse_writer_dict
(sfn, m)[source]¶ Set entries in g.app.writersDispatchDict and g.app.atAutoWritersDict using entries in m.writers_dict.
-
scanOptions
(fileName, pymacs)[source]¶ Handle all options, remove them from sys.argv and set lm.options.
-
-
class
leo.core.leoApp.
PreviousSettings
(settingsDict, shortcutsDict)[source]¶ Bases:
object
A class holding the settings and shortcuts dictionaries that are computed in the first pass when loading local files and passed to the second pass.
-
class
leo.core.leoApp.
RecentFilesManager
[source]¶ Bases:
object
A class to manipulate leoRecentFiles.txt.
-
cleanRecentFiles
(c)[source]¶ Remove items from the recent files list that no longer exist.
This almost never does anything because Leo’s startup logic removes nonexistent files from the recent files list.
-
createRecentFiles
()[source]¶ Try to create .leoRecentFiles.txt, in the users home directory, or in Leo’s config directory if that fails.
-
demangleRecentFiles
(c, data)[source]¶ Rewrite recent files based on c.config.getData(‘path-demangle’)
-
editRecentFiles
(c)[source]¶ Dump recentFiles into new node appended as lastTopLevel, selects it and request focus in body.
NOTE: command write-edited-recent-files assume that headline of this node is not changed by user.
-
writeEditedRecentFiles
(c)[source]¶ Write content of “edit_headline” node as recentFiles and recreates menues.
-
-
leo.core.leoApp.
demangle_recent_files_command
(event)[source]¶ Path demangling potentially alters the paths in the recent files list according to find/replace patterns in the @data path-demangle setting. For example:
REPLACE: .gnome-desktop WITH: My DesktopThe default setting specifies no patterns.
-
leo.core.leoApp.
join_leo_irc
(event=None)[source]¶ Open the web page to Leo’s irc channel on freenode.net.
leoAtFile
Module¶
Classes to read and write @file nodes.
-
class
leo.core.leoAtFile.
AtFile
(c)[source]¶ Bases:
object
A class implementing the atFile subcommander.
-
adjustTargetLanguage
(fn)[source]¶ Use the language implied by fn’s extension if there is a conflict between it and c.target_language.
-
allDirective
= 2¶
-
atDirective
= 4¶
-
at_directive_kind_pattern
= <_sre.SRE_Pattern object>¶
-
cDirective
= 6¶
-
changeLevel
(oldLevel, newLevel)[source]¶ Update data structures when changing node level.
The key invariant: on exit, the top of at.thinNodeStack is the new parent node.
-
checkDerivedFile
(event=None)[source]¶ Make sure an external file written by Leo may be read properly.
-
checkExternalFileAgainstDb
(root)[source]¶ Returns True if file is not modified since last save in db. Otherwise returns False.
-
checkPythonCode
(root, s=None, targetFn=None, pyflakes_errors_only=False)[source]¶ Perform python-related checks on root.
-
codeDirective
= 5¶
-
compareFiles
(path1, path2, ignoreLineEndings, ignoreBlankLines=False)[source]¶ Compare two text files.
-
completeFirstDirectives
(out, firstLines)[source]¶ 14-SEP-2002 DTHEIN
Scans the lines in the list ‘out’ for @first directives, appending the corresponding line from ‘firstLines’ to each @first directive found.
NOTE: the @first directives must be the very first lines in ‘out’.
-
completeLastDirectives
(out, lastLines)[source]¶ 14-SEP-2002 DTHEIN.
Scans the lines in the list ‘out’ for @last directives, appending the corresponding line from ‘lastLines’ to each @last directive found.
NOTE: the @last directives must be the very last lines in ‘out’.
-
completeRootNode
(firstLines, lastLines, root)[source]¶ Terminate the root’s body text, handling @first and @last.
-
defineResurrectedNodeCallback
(r, root)[source]¶ Define a callback that moves node p as r’s last child.
-
deleteUnvisitedNodes
(root, redraw=True)[source]¶ Delete unvisited nodes in root’s subtree, not including root.
Before Leo 5.6: Move unvisited node to be children of the ‘Resurrected Nodes’.
-
docDirective
= 3¶
-
endAll
= 70¶
-
endAt
= 21¶
-
endBody
= 22¶
-
endDoc
= 24¶
-
endLeo
= 25¶
-
endMiddle
= 71¶
-
endNode
= 26¶
-
endOthers
= 27¶
-
endRawDirective
= 10¶
-
endRef
= 84¶
-
ensureTrailingNewline
(s)[source]¶ Ensure a trailing newline in s. If we add a trailing newline, we’ll generate an @nonl sentinel below.
- We always ensure a newline in @file and @thin trees.
- This code is not used used in @asis trees.
- New in Leo 4.4.3 b1: We add a newline in @clean/@nosent trees unless @bool force_newlines_in_at_nosent_bodies = False
-
findChild4
(headline)[source]¶ Return the next VNode in at.root.tnodeList. Called only for legacy @file nodes.
tnodeLists are used only when reading @file (not @thin) nodes. tnodeLists compensate for not having gnx’s in derived files!
-
findSectionName
(s, i)[source]¶ Return n1, n2 representing a section name. The section name, including brackes is s[n1:n2]
-
getEncodingFromHeader
(fn, s)[source]¶ Return the encoding given in the @+leo sentinel, if the sentinel is present, or the previous value of at.encoding otherwise.
-
getNodeHeadline
(s, i)[source]¶ Set headline to the rest of the line. Don’t strip leading whitespace.
-
handleChangedNode
(new_body, old_body, p, thinFile)[source]¶ Set ancestor files dirty and support mod_labels plugin.
-
indicateNodeChanged
(old, new, postPass, v)[source]¶ Add an entry to c.nodeConflictList. Called only from at.terminateBody.
-
initCommonIvars
()[source]¶ Init ivars common to both reading and writing.
The defaults set here may be changed later.
-
initWriteIvars
(root, targetFileName, atEdit=False, atShadow=False, forcePythonSentinels=False, nosentinels=False, toString=False)[source]¶
-
miscDirective
= 8¶
-
new_createThinChild4
(gnxString, headline, n, parent)[source]¶ Find or create a new vnode whose parent (also a vnode) is at.lastThinNode. This is called only for @thin trees.
-
noDirective
= 1¶
-
noSentinel
= 20¶
-
old_createThinChild4
(gnxString, headline)[source]¶ Find or create a new vnode whose parent (also a vnode) is at.lastThinNode. This is called only for @thin trees.
-
openFileForReading
(fromString=False)[source]¶ Open the file given by at.root. This will be the private file for @shadow nodes.
-
os
(s)[source]¶ Write a string to the output stream.
All output produced by leoAtFile module goes here.
-
othersDirective
= 7¶
-
parseLeoSentinel
(s)[source]¶ Parse the sentinel line s. If the sentinel is valid, set at.encoding, at.readVersion, at.readVersion5.
-
promptForDangerousWrite
(fileName, kind, message=None)[source]¶ Raise a dialog asking the user whether to overwrite an existing file.
-
putAfterMiddleRef
(s, delta)[source]¶ Handle whatever follows a ref that is not the last ref of a line.
-
putAtFirstLines
(s)[source]¶ Write any @firstlines from string s. These lines are converted to @verbatim lines, so the read logic simply ignores lines preceding the @+leo sentinel.
-
putAtLastLines
(s)[source]¶ Write any @last lines from string s. These lines are converted to @verbatim lines, so the read logic simply ignores lines following the @-leo sentinel.
-
putBody
(p, fromString='')[source]¶ Generate the body enclosed in sentinel lines. Return True if the body contains an @others line.
-
putDirective
(s, i)[source]¶ Output a sentinel a directive or reference s.
It is important for PHP and other situations that @first and @last directives get translated to verbatim lines that do not include what follows the @first & @last directives.
-
putDocLine
(s, i)[source]¶ Handle one line of a doc part.
Output complete lines and split long lines and queue pending lines. Inserted newlines are always preceded by whitespace.
-
putIndent
(n, s='')[source]¶ Put tabs and spaces corresponding to n spaces, assuming that we are at the start of a line.
Remove extra blanks if the line starts with the underindentEscapeString
-
putLeadInSentinel
(s, i, j, delta)[source]¶ Set at.leadingWs as needed for @+others and @+<< sentinels.
i points at the start of a line. j points at @others or a section reference. delta is the change in at.indent that is about to happen and hasn’t happened yet.
-
putLine
(i, kind, p, s, status)[source]¶ Put the line at s[i:] of the given kind, updating the status.
-
putPending
(split)[source]¶ Write the pending part of a doc part.
We retain trailing whitespace iff the split flag is True.
-
rawDirective
= 9¶
-
read
(root, importFileName=None, fromString=None, atShadow=False, force=False)[source]¶ Read an @thin or @file tree.
-
readEndNode
(unused_s, unused_i, middle=False)[source]¶ Handle old-style @-node sentinels. In the new scheme, only the post-pass terminates nodes.
-
readFileToUnicode
(fn)[source]¶ Carefully sets at.encoding, then uses at.encoding to convert the file to a unicode string. Calls at.initReadLine if all went well.
Sets at.encoding as follows: 1. Use the BOM, if present. This unambiguously determines the encoding. 2. Use the -encoding= field in the @+leo header, if present and valid. 3. Otherwise, uses existing value of at.encoding, which comes from:
- An @encoding directive, found by at.scanAllDirectives.
- The value of c.config.default_derived_file_encoding.
Returns the string, or None on failure.
This method is now part of the main @file read code. at.openFileForReading calls this method to read all @file nodes. Previously only at.scanHeaderForThin (import code) called this method.
-
readLastDocLine
(tag)[source]¶ Read the @c line that terminates the doc part. tag is @doc or @.
Not used when reading new sentinels.
-
readLine
()[source]¶ Read one line from file using the present encoding. Returns at.read_lines[at.read_i++]
-
readOpenFile
(root, fileName, deleteNodes=False)[source]¶ Read an open derived file. Leo 4.5 and later can only read 4.x derived files.
-
readStartNode
(s, i, middle=False)[source]¶ Read an @+node or @+middle sentinel. This will terminate the previous node.
-
rememberReadPath
(fn, p)[source]¶ Remember the files that have been read and the full headline (@<file> type) that caused the read.
-
removeCommentDelims
(p)[source]¶ If the present @language/@comment settings do not specify a single-line comment we remove all block comment delims from h. This prevents headline text from interfering with the parsing of node sentinels.
-
rename
(src, dst, mode=None, verbose=True)[source]¶ Remove dst if it exists, then rename src to dst. Change the mode of the renamed file if mode is given. Return True if all went well.
-
replaceFileWithString
(fn, s)[source]¶ Replace the file with s if s is different from theFile’s contents.
Return True if theFile was changed.
This is used only by the @shadow logic.
-
replaceTargetFileIfDifferent
(root, ignoreBlankLines=False)[source]¶ Create target file as follows: 1. If target file does not exist, rename output file to target file. 2. If target file is identical to output file, remove the output file. 3. If target file is different from output file,
remove target file, then rename output file to be target file.Return True if the original file was changed.
-
scanAllDirectives
(p, forcePythonSentinels=False, importing=False, issuePathWarning=False, reading=False)[source]¶ Scan p and p’s ancestors looking for directives, setting corresponding AtFile ivars.
-
scanFirstLines
(firstLines)[source]¶ Append all lines before the @+leo line to firstLines.
Empty lines are ignored because empty @first directives are ignored.
We can not call sentinelKind here because that depends on the comment delimiters we set here.
-
scanForClonedSibs
(parent_v, v)[source]¶ Scan the siblings of VNode v looking for clones of v. Return the number of cloned sibs and n where p is the n’th cloned sibling.
-
scanHeader
(fileName, giveErrors=True)[source]¶ Scan the @+leo sentinel.
Sets self.encoding, and self.start/endSentinelComment.
Returns (firstLines,new_df,isThinDerivedFile) where: firstLines contains all @first lines, new_df is True if we are reading a new-format derived file. isThinDerivedFile is True if the file is an @thin file.
-
scanHeaderForThin
(fileName)[source]¶ Return true if the derived file is a thin file.
This is a kludgy method used only by the import code.
-
sentinelDict
= {'@+all': 72, '@+at': 41, '@+body': 42, '@+doc': 43, '@+leo': 44, '@+middle': 73, '@+node': 45, '@+others': 46, '@-all': 70, '@-at': 21, '@-body': 22, '@-doc': 24, '@-leo': 25, '@-middle': 71, '@-node': 26, '@-others': 27, '@afterref': 80, '@clone': 81, '@comment': 60, '@delims': 61, '@nl': 82, '@nonl': 83, '@verbatim': 64, '@verbatimAfterRef': 65}¶
-
setDirtyOrphanBits
(root)[source]¶ Setting the orphan and dirty flags tells Leo to write the tree. However, the dirty bits get cleared if we are called from the save command.
-
shouldDeleteChildren
(root, thinFile)[source]¶ Return True if we should delete all children before a read.
-
shouldPromptForDangerousWrite
(fn, p)[source]¶ Return True if a prompt should be issued when writing p (an @<file> node) to fn.
-
silentWrite
(root, toString=False)¶
-
startAfterRef
= 80¶
-
startAll
= 72¶
-
startAt
= 41¶
-
startBody
= 42¶
-
startClone
= 81¶
-
startComment
= 60¶
-
startDelims
= 61¶
-
startDirective
= 62¶
-
startDoc
= 43¶
-
startLeo
= 44¶
-
startMiddle
= 73¶
-
startNl
= 82¶
-
startNode
= 45¶
-
startNonl
= 83¶
-
startOthers
= 46¶
-
startRef
= 63¶
-
startVerbatim
= 64¶
-
startVerbatimAfterRef
= 65¶
-
stat
(fileName)[source]¶ Return the access mode of named file, removing any setuid, setgid, and sticky bits.
-
terminateNode
(middle=False, postPass=True, v=None)[source]¶ Set the body text of at.v, and issue warning if it has changed.
This is called as follows:
old sentinels: when handling a @-node sentinel. new sentinels: from the post-pass when v.tempBodyList exists.
-
validInAtOthers
(p)[source]¶ Return True if p should be included in the expansion of the @others directive in the body text of p’s parent.
-
write
(root, kind='@unknown', nosentinels=False, toString=False)[source]¶ Write a 4.x derived file. root is the position of an @<file> node.
-
writeAll
(writeAtFileNodesFlag=False, writeDirtyAtFileNodesFlag=False, toString=False)[source]¶ Write @file nodes in all or part of the outline
-
writeAllHelper
(p, root, force, toString, writeAtFileNodesFlag, writtenFiles)[source]¶ Write one file for the at.writeAll. Do not write @auto files unless p == root. This prevents the write-all command from needlessly updating the @persistence data, thereby annoyingly changing the .leo file.
-
writeAtAutoNodesHelper
(toString=False, writeDirtyOnly=True)[source]¶ Write @auto nodes in the selected outline
-
writeAtShadowNodesHelper
(toString=False, writeDirtyOnly=True)[source]¶ Write @shadow nodes in the selected outline
-
writeFromString
(root, s, forcePythonSentinels=True, useSentinels=True)[source]¶ Write a 4.x derived file from a string.
This is at.write specialized for scripting.
-
writeOneAtAutoNode
(p, force=False, toString=False, trialWrite=False)[source]¶ Write p, an @auto node. File indices must have already been assigned.
-
writeOneAtShadowNode
(p, toString, force)[source]¶ Write p, an @shadow node. File indices must have already been assigned.
-
writeOpenFile
(root, nosentinels=False, toString=False, fromString='')[source]¶ Do all writes except asis writes.
-
write_at_clean_sentinels
(root)[source]¶ Return all lines of the @clean tree as if it were written as an @file node.
-
-
leo.core.leoAtFile.
atFile
¶ alias of
leo.core.leoAtFile.AtFile
leoBridge
Module¶
A module to allow full access to Leo commanders from outside Leo.
-
class
leo.core.leoBridge.
BridgeController
(guiName, loadPlugins, readSettings, silent, tracePlugins, verbose)[source]¶ Bases:
object
Creates a way for host programs to access Leo.
-
createFrame
(fileName)[source]¶ Create a commander and frame for the given file. Create a new frame if the fileName is empty or non-exisent.
-
leoBridgeTest
Module¶
A module that runs unit tests with the leoBridge module.
All options come from sys.argv. See scan_options for the available options.
Important: Leo’s core does not use this module in any way.
leoCache
Module¶
A module encapsulating Leo’s file caching
-
class
leo.core.leoCache.
Cacher
(c=None)[source]¶ Bases:
object
A class that encapsulates all aspects of Leo’s file caching.
-
checkForChangedNodes
(child_tuple, fileName, parent_v)[source]¶ Update the outline described by child_tuple, including all descendants.
-
clearAllCaches
()[source]¶ Clear the Cachers only for all open windows. This is much safer than killing all db’s.
-
collectChangedNodes
(root_v, aList, fileName)[source]¶ Populates c.nodeConflictList with data about nodes that are going to change during recreation of outline from cached list.
-
createOutlineFromCacheList
(parent_v, aList, fileName, top=True)[source]¶ Create outline structure from recursive aList built by makeCacheList.
-
createOutlineFromCacheList2
(parent_v, aList)[source]¶ Create outline structure from recursive aList built by makeCacheList.
-
fastAddLastChild
(fileName, gnxString, parent_v)[source]¶ Create new VNode as last child of the receiver. If the gnx exists already, create a clone instead of new VNode.
-
fileKey
(fileName, content, requireEncodedString=False)[source]¶ Compute the hash of fileName and content. fileName may be unicode, content must be bytes (or plain string in Python 2.x).
-
makeCacheList
(p)[source]¶ Create a recursive list describing a tree for use by createOutlineFromCacheList.
-
Bases:
object
The main ‘connection’ object for PickleShare database
Return all keys in DB, or all keys matching a glob
Removes all, or specified items from cache
Use this after reading a large amount of large objects to free up memory, when you won’t be needing the objects for a while.
Bases:
object
The main ‘connection’ object for SqlitePickleShare database
Return all keys in DB, or all keys matching a glob
not used in SqlitePickleShare
leoChapters
Module¶
Classes that manage chapters in Leo’s core.
-
class
leo.core.leoChapters.
Chapter
(c, chapterController, name)[source]¶ Bases:
object
A class representing the non-gui data of a single chapter.
-
class
leo.core.leoChapters.
ChapterController
(c)[source]¶ Bases:
object
A per-commander controller that manages chapters and related nodes.
-
findChapterNameForPosition
(p)[source]¶ Return the name of a chapter containing p or None if p does not exist.
-
findChapterNode
(name)[source]¶ Return the position of the first @chapter node with the given name anywhere in the entire outline.
All @chapter nodes are created as children of the @chapters node, but users may move them anywhere.
-
selectChapter
(event=None)[source]¶ Use the minibuffer to get a chapter name, then create the chapter.
-
selectChapterByName
(name, collapse=True)[source]¶ Select a chapter. Return True if a redraw is needed.
-
selectChapterByNameHelper
(chapter, collapse=True)[source]¶ Select the chapter, and redraw if necessary.
-
leoColor
Module¶
A color database for Leo.
leo_color_database is a dictionary of color names mapped onto the colors ‘#rrggbb’ representation.
The color names are derived from standard Linux color names which includes all Tk color names.
The names have been normalized by excluding spaces and removing capitalization. This should also be done for all new colors.
Accessor functions are provided which will normalize name requests before looking them up in the database.
These are:
getColor (aka: get)
getColorRGB (aka: getRGB)
getColorCairo (aka: getCairo)
Use these functions as follows:
import leo.core.leoColor as leoColor
leoColor.getRGB(name, default)
If neither ‘name’ nor ‘default’ can be translated then accessor functions will return None.
-
leo.core.leoColor.
get
(name, default=None)¶ Translate a named color into #rrggbb’ format.
if ‘name’ is not a string it is returned unchanged.
If ‘name’ is already in ‘#rrggbb’ format then it is returned unchanged.
If ‘name’ is not in global_color_database then getColor(default, None) is called and that result returned.
-
leo.core.leoColor.
getCairo
(name, default=None)¶ Convert a named color into a cairo color tuple.
-
leo.core.leoColor.
getColor
(name, default=None)[source]¶ Translate a named color into #rrggbb’ format.
if ‘name’ is not a string it is returned unchanged.
If ‘name’ is already in ‘#rrggbb’ format then it is returned unchanged.
If ‘name’ is not in global_color_database then getColor(default, None) is called and that result returned.
-
leo.core.leoColor.
getColorCairo
(name, default=None)[source]¶ Convert a named color into a cairo color tuple.
-
leo.core.leoColor.
getColorRGB
(name, default=None)[source]¶ Convert a named color into an (r, g, b) tuple.
-
leo.core.leoColor.
getRGB
(name, default=None)¶ Convert a named color into an (r, g, b) tuple.
leoCommands
Module¶
-
class
leo.core.leoCommands.
Commands
(fileName, relativeFileName=None, gui=None, previousSettings=None)[source]¶ Bases:
object
A per-outline class that implements most of Leo’s commands. The “c” predefined object is an instance of this class.
c.initObjects() creates sucommanders corresponding to files in the leo/core and leo/commands. All of Leo’s core code is accessible via this class and its subcommanders.
g.app.pluginsController is Leo’s plugins controller. Many plugins inject controllers objects into the Commands class. These are another kind of subcommander.
The @g..commander_command decorator injects methods into this class.
-
BeginUpdate
()¶ Deprecated: does nothing.
-
BringToFront
(c2=None, set_focus=True)¶
-
EndUpdate
(flag=True)¶ Request a redraw of the screen if flag is True.
-
allNodes_iter
()¶ A generator return all positions of the outline, in outline order.
-
all_positions_iter
()¶ A generator return all positions of the outline, in outline order.
-
all_positions_with_unique_tnodes_iter
()¶ A generator return all positions of the outline, in outline order. Returns only the first position for each vnode.
-
all_positions_with_unique_vnodes_iter
()¶ A generator return all positions of the outline, in outline order. Returns only the first position for each vnode.
-
all_roots
(predicate=None)[source]¶ A generator yielding all the root positions in the outline that satisfy the given predicate. p.isAnyAtFileNode is the default predicate.
The generator yields all root anywhere in the outline that satisfy the predicate. Once a root is found, the generator skips its subtree.
-
all_tnodes_iter
()¶ A generator returning all vnodes in the outline, in outline order.
-
all_unique_positions
()[source]¶ A generator return all positions of the outline, in outline order. Returns only the first position for each vnode.
-
all_unique_roots
(predicate=None)[source]¶ A generator yielding all unique root positions in the outline that satisfy the given predicate. p.isAnyAtFileNode is the default predicate.
The generator yields all root anywhere in the outline that satisfy the predicate. Once a root is found, the generator skips its subtree.
-
all_unique_tnodes_iter
()¶ A generator returning each vnode of the outline.
-
all_unique_vnodes_iter
()¶ A generator returning each vnode of the outline.
-
all_vnodes_iter
()¶ A generator returning all vnodes in the outline, in outline order.
-
backup
(fileName=None, prefix=None, silent=False, useTimeStamp=True)[source]¶ Back up given fileName or c.fileName(). If useTimeStamp is True, append a timestamp to the filename.
-
backup_helper
(base_dir=None, env_key='LEO_BACKUP', sub_dir=None, use_git_prefix=True)[source]¶ A helper for scripts that back up a .leo file. Use os.environ[env_key] as the base_dir only if base_dir is not given. Backup to base_dir or join(base_dir, sub_dir).
-
canCutOutline
()¶
-
canDehoist
()[source]¶ Return True if do-hoist should be enabled in a menu. Should not be used in any other context.
-
canExtractSectionNames
()¶
-
canHoist
()[source]¶ Return True if hoist should be enabled in a menu. Should not be used in any other context.
-
canShiftBodyRight
()¶
-
checkAllPythonCode
(event=None, unittest=False, ignoreAtIgnore=True)[source]¶ Check all nodes in the selected tree for syntax and tab errors.
-
checkFileTimeStamp
(fn)[source]¶ Return True if the file given by fn has not been changed since Leo read it or if the user agrees to overwrite it.
-
checkGnxs
()[source]¶ Check the consistency of all gnx’s and remove any tnodeLists. Reallocate gnx’s for duplicates or empty gnx’s. Return the number of structure_errors found.
-
checkMoveWithParentWithWarning
(root, parent, warningFlag)[source]¶ Return False if root or any of root’s descendents is a clone of parent or any of parents ancestors.
-
checkOutline
(event=None, check_links=False)[source]¶ Check for errors in the outline. Return the count of serious structure errors.
-
checkPythonCode
(event=None, unittest=False, ignoreAtIgnore=True, suppressErrors=False, checkOnSave=False)[source]¶ Check the selected tree for syntax and tab errors.
-
cloneFindByPredicate
(generator, predicate, failMsg=None, flatten=False, iconPath=None, redraw=True, undoType=None)[source]¶ Traverse the tree given using the generator, cloning all positions for which predicate(p) is True. Undoably move all clones to a new node, created as the last top-level node. Returns the newly-created node. Arguments:
generator, The generator used to traverse the tree. predicate, A function of one argument p returning true if p should be included. failMsg=None, Message given if nothing found. Default is no message. flatten=False, True: Move all node to be parents of the root node. iconPath=None, Full path to icon to attach to all matches. redraw=True, True: redraw the screen. undo_type=None, The undo/redo name shown in the Edit:Undo menu.
The default is ‘clone-find-predicate’
-
command_count
= 0¶
-
createCloneFindPredicateRoot
(flatten, undoType)[source]¶ Create a root node for clone-find-predicate.
-
createCommandNames
()[source]¶ Create all entries in c.commandsDict. Do not clear c.commandsDict here.
-
createNodeFromExternalFile
(fn)[source]¶ Read the file into a node. Return None, indicating that c.open should set focus.
-
createNodeHierarchy
(heads, parent=None, forcecreate=False)[source]¶ Create the proper hierarchy of nodes with headlines defined in ‘heads’ under ‘parent’
params: parent - parent node to start from. Set to None for top-level nodes heads - list of headlines in order to create, i.e. [‘foo’,’bar’,’baz’]
- will create:
- parent -foo –bar —baz
- forcecreate - If False (default), will not create nodes unless they don’t exist
- If True, will create nodes regardless of existing nodes
returns the final position (‘baz’ in the above example)
-
currentPosition
()[source]¶ Return a copy of the presently selected position or a new null position. So c.p.copy() is never necessary.
-
currentPositionHasNext
()[source]¶ Return True if the current position is the root position.
This method is called during idle time, so not generating positions here fixes a major leak.
-
currentPositionIsRootPosition
()[source]¶ Return True if the current position is the root position.
This method is called during idle time, so not generating positions here fixes a major leak.
-
currentVnode
()¶ Return a copy of the presently selected position or a new null position. So c.p.copy() is never necessary.
-
deletePositionsInList
(aList, callback=None, redraw=True)[source]¶ Delete all vnodes corresponding to the positions in aList. If a callback is given, the callback is called for every node in the list.
The callback takes one explicit argument, p. As usual, the callback can bind values using keyword arguments.
This is very tricky code. The theory of operation section explains why.
-
diff_file
(fn, rev1='HEAD', rev2='', directory=None)[source]¶ Create an outline describing the git diffs for all files changed between rev1 and rev2.
-
diff_two_branches
(branch1, branch2, fn, directory=None)[source]¶ Create an outline describing the git diffs for all files changed between rev1 and rev2.
-
diff_two_revs
(directory=None, rev1='', rev2='')[source]¶ Create an outline describing the git diffs for all files changed between rev1 and rev2.
-
doCommand
(command, label, event=None)[source]¶ Execute the given command, invoking hooks and catching exceptions.
The code assumes that the “command1” hook has completely handled the command if g.doHook(“command1”) returns False. This provides a simple mechanism for overriding commands.
-
executeAnyCommand
(command, event)[source]¶ Execute a command, no matter how defined.
Supports @g.commander_command and @g.new_cmd_decorator and plain methods.
-
executeScript
(event=None, args=None, p=None, script=None, useSelectedText=True, define_g=True, define_name='__main__', silent=False, namespace=None, raiseFlag=False)[source]¶ Execute a Leo script. Keyword args: args=None Not None: set script_args in the execution environment. p=None Get the script from p.b, unless script is given. script=None None: use script in p.b or c.p.b useSelectedText=True False: use all the text in p.b or c.p.b. define_g=True True: define g for the script. define_name=’__main__’ Not None: define the name symbol. silent=False No longer used. namespace=None Not None: execute the script in this namespace. raiseFlag=False True: reraise any exceptions.
-
expandAllAncestors
(p)[source]¶ Expand all ancestors without redrawing. Return a flag telling whether a redraw is needed.
-
findNodeOutsideAnyAtFileTree
(target)[source]¶ Select the first clone of target that is outside any @file node.
-
findRootPosition
()¶ Return the root position.
Root position is the first position in the document. Other top level positions are siblings of this node.
-
find_b
(regex, flags=10)[source]¶ Return list (a PosList) of all nodes whose body matches regex one or more times.
-
find_h
(regex, flags=2)[source]¶ Return list (a PosList) of all nodes where zero or more characters at the beginning of the headline match regex
-
finishCreate
()[source]¶ Finish creating the commander and all sub-objects. This is the last step in the startup process.
-
force_redraw
(p=None, setFocus=False)¶ Redraw the screen immediately.
-
getBodyLines
(expandSelection=False)[source]¶ Return head,lines,tail where:
before is string containg all the lines before the selected text (or the text before the insert point if no selection) lines is a list of lines containing the selected text (or the line containing the insert point if no selection) after is a string all lines after the selected text (or the text after the insert point if no selection)
-
getLanguageAtCursor
(p, language)[source]¶ Return the language in effect at the present insert point. Use the language argument as a default if no @language directive seen.
-
getNodeFileName
(p)[source]¶ Return the full file name at node p, including effects of all @path directives. Return None if p is no kind of @file node.
-
getSelectedPositions
()[source]¶ Get list (PosList) of currently selected positions
So far only makes sense on qt gui (which supports multiselection)
-
goToLineNumber
(n)[source]¶ Go to line n (zero-based) of a script. A convenience method called from g.handleScriptException.
-
goToScriptLineNumber
(n, p)[source]¶ Go to line n (zero-based) of a script. A convenience method called from g.handleScriptException.
-
idle_focus_count
= 0¶
-
interactive
(callback, event, prompts)[source]¶ c.interactive: Prompt for up to three arguments from the minibuffer.
The number of prompts determines the number of arguments.
Use the @command decorator to define commands. Examples:
@g.command(‘i3’) def i3_command(event):
c = event.get(‘c’) if not c: return
- def callback(args, c, event):
- g.trace(args) c.bodyWantsFocus()
- c.interactive(callback, event,
- prompts=[‘Arg1: ‘, ‘ Arg2: ‘, ‘ Arg3: ‘])
-
last_unusual_focus
= None¶
-
looksLikeDerivedFile
(fn)[source]¶ Return True if fn names a file that looks like an external file written by Leo.
return true if there are two quick outline navigation keys in quick succession.
Returns False if @float outline_nav_extend_delay setting is 0.0 or unspecified.
-
nullPosition
()[source]¶ New in Leo 5.5: Return None. Using empty positions masks problems in program logic.
In fact, there are no longer any calls to this method in Leo’s core.
-
onCanvasKey
(event)[source]¶ Navigate to the next headline starting with ch = event.char. If ch is uppercase, search all headlines; otherwise search only visible headlines. This is modelled on Windows explorer.
-
openWith
(event=None, d=None)[source]¶ This is not a command.
Handles the items in the Open With… menu.
See ExternalFilesController.open_with for details about d.
-
p
¶ commander current position property
-
recolor_now
(**kwargs)¶
-
recursiveImport
(dir_, kind, add_path=True, recursive=True, safe_at_file=True, theTypes=None)[source]¶ Recursively import all python files in a directory and clean the results.
- Parameters::
dir_ The root directory or file to import. kind One of (‘@clean’,’@edit’,’@file’,’@nosent’). add_path=True True: add a full @path directive to @<file> nodes. recursive=True True: recurse into subdirectories. safe_at_file=True True: produce @@file nodes instead of @file nodes. theTypes=None A list of file extensions to import.
None is equivalent to [‘.py’]
This method cleans imported files as follows:
- Replace backslashes with forward slashes in headlines.
- Remove empty nodes.
- Add @path directives that reduce the needed path specifiers in descendant nodes.
- Add @file to nodes or replace @file with @@file.
-
redrawAndEdit
(p, selectAll=False, selection=None, keepMinibuffer=False)[source]¶ Redraw the screen and edit p’s headline.
-
redraw_after_head_changed
()[source]¶ Redraw the screen (if needed) when editing ends. This may be a do-nothing for some gui’s.
-
redraw_later
()[source]¶ Ensure that c.redraw() will be called eventually.
c.outerUpdate will call c.redraw() only if no other code calls c.redraw().
-
redraw_now
(p=None, setFocus=False)¶ Redraw the screen immediately.
-
reloadConfigurableSettings
()[source]¶ Call all reloadSettings method in c.subcommanders, c.configurables and other known classes.
-
rootPosition
()[source]¶ Return the root position.
Root position is the first position in the document. Other top level positions are siblings of this node.
-
rootVnode
()¶ Return the root position.
Root position is the first position in the document. Other top level positions are siblings of this node.
-
safe_all_positions
()[source]¶ A generator returning all positions of the outline. This generator does not assume that vnodes are never their own ancestors.
-
scanAllDirectives
(p=None)[source]¶ Scan p and ancestors for directives.
Returns a dict containing the results, including defaults.
-
scanAtPathDirectives
(aList)[source]¶ Scan aList for @path directives. Return a reasonable default if no @path directive is found.
-
selectPosition
(p, **kwargs)[source]¶ Select a new position, redrawing the screen only if we must change chapters.
-
selectVnode
(p, **kwargs)¶ Select a new position, redrawing the screen only if we must change chapters.
-
setChanged
(changedFlag=True, redrawFlag=True)[source]¶ Set or clear the marker that indicates that the .leo file has been changed.
-
setComplexCommand
(commandName)[source]¶ Make commandName the command to be executed by repeat-complex-command.
-
setCurrentPosition
(p)[source]¶ Set the presently selected position. For internal use only. Client code should use c.selectPosition instead.
-
setCurrentVnode
(p)¶ Set the presently selected position. For internal use only. Client code should use c.selectPosition instead.
-
setHeadString
(p, s)[source]¶ Set the p’s headline and the corresponding tree widget to s.
This is used in by unit tests to restore the outline.
-
setTopVnode
(p)¶ Set the root positioin.
-
shortFilename
()¶
-
tabNannyNode
(p, headline, body, unittest=False, suppressErrors=False)[source]¶ Check indentation using tabnanny.
-
topVnode
()¶ Return the root position.
-
trimTrailingLines
(p)[source]¶ Trims trailing blank lines from a node.
It is surprising difficult to do this during Untangle.
-
universalCallback
(source_c, function)[source]¶ Create a universal command callback.
Create and return a callback that wraps a function with an rClick signature in a callback which adapts standard minibufer command callbacks to a compatible format.
This also serves to allow rClick callback functions to handle minibuffer commands from sources other than rClick menus so allowing a single function to handle calls from all sources.
A function wrapped in this wrapper can handle rclick generator and invocation commands and commands typed in the minibuffer.
It will also be able to handle commands from the minibuffer even if rclick is not installed.
-
universallCallback
(source_c, function)¶ Create a universal command callback.
Create and return a callback that wraps a function with an rClick signature in a callback which adapts standard minibufer command callbacks to a compatible format.
This also serves to allow rClick callback functions to handle minibuffer commands from sources other than rClick menus so allowing a single function to handle calls from all sources.
A function wrapped in this wrapper can handle rclick generator and invocation commands and commands typed in the minibuffer.
It will also be able to handle commands from the minibuffer even if rclick is not installed.
-
updateBodyPane
(head, middle, tail, undoType, oldSel, oldYview, preserveSel=False)[source]¶ Handle changed text in the body pane.
-
leoCompare
Module¶
Leo’s base compare class.
-
class
leo.core.leoCompare.
BaseLeoCompare
(commands=None, appendOutput=False, ignoreBlankLines=True, ignoreFirstLine1=False, ignoreFirstLine2=False, ignoreInteriorWhitespace=False, ignoreLeadingWhitespace=True, ignoreSentinelLines=False, limitCount=0, limitToExtension='.py', makeWhitespaceVisible=True, printBothMatches=False, printMatches=False, printMismatches=True, printTrailingMismatches=False, outputFileName=None)[source]¶ Bases:
object
The base class for Leo’s compare code.
-
class
leo.core.leoCompare.
CompareLeoOutlines
(c)[source]¶ Bases:
object
A class to do outline-oriented diffs of two or more .leo files. Similar to GitDiffController, adapted for use by scripts.
-
class
leo.core.leoCompare.
LeoCompare
(commands=None, appendOutput=False, ignoreBlankLines=True, ignoreFirstLine1=False, ignoreFirstLine2=False, ignoreInteriorWhitespace=False, ignoreLeadingWhitespace=True, ignoreSentinelLines=False, limitCount=0, limitToExtension='.py', makeWhitespaceVisible=True, printBothMatches=False, printMatches=False, printMismatches=True, printTrailingMismatches=False, outputFileName=None)[source]¶ Bases:
leo.core.leoCompare.BaseLeoCompare
A class containing Leo’s compare code.
These are not very useful comparisons.
-
leo.core.leoCompare.
diffMarkedNodes
(event)[source]¶ When two or more nodes are marked, this command does the following:
- Creates a “diff marked node” as the last top-level node. The body of this node contains “diff n” nodes, one for each pair of compared nodes.
- Each diff n contains the diffs between the two diffed nodes, that is, difflib.Differ().compare(p1.b, p2.b). The children of the diff n are clones of the two compared nodes.
-
leo.core.leoCompare.
diff_and_open_leo_files
(event)[source]¶ Open a dialog prompting for two or more .leo files.
Opens all the files and creates a top-level node in c’s outline showing the diffs of those files, two at a time.
-
leo.core.leoCompare.
diff_leo_files
(event)[source]¶ Open a dialog prompting for two or more .leo files.
Creates a top-level node showing the diffs of those files, two at a time.
leoConfig
Module¶
leoDebugger
Module¶
Per-commander debugging class.
leoDynamicTest
Module¶
A module to run unit tests with the leoBridge module. Leo’s unit test code uses this module when running unit tests externally.
leoEditCommands
Module¶
leoFileCommands
Module¶
Classes relating to reading and writing .leo files.
-
class
leo.core.leoFileCommands.
FileCommands
(c)[source]¶ Bases:
object
A class creating the FileCommands subcommander.
-
bytes_to_unicode
(ob)[source]¶ recursively convert bytes objects in strings / lists / dicts to str objects, thanks to TNT http://stackoverflow.com/questions/22840092/unpickling-data-from-python-2-with-unicode-strings-in-python-3
Needed for reading Python 2.7 pickles in Python 3.4 in getSaxUa()
-
cleanSaxInputString
(s)[source]¶ Clean control characters from s. s may be a bytes or a (unicode) string.
-
compactFileIndices
()¶ Assign a file index to all tnodes
-
createBackupFile
(fileName)[source]¶ Create a closed backup file and copy the file to it, but only if the original file exists.
-
createUaList
(aList)[source]¶ Given aList of pairs (p,torv), return a list of pairs (torv,d) where d contains all picklable items of torv.unknownAttributes.
-
decodePosition
(s)[source]¶ Creates position from its string representation encoded by fc.encodePosition.
-
getDescendentAttributes
(s, tag='')[source]¶ s is a list of gnx’s, separated by commas from a <v> or <t> element. Parses s into a list.
This is used to record marked and expanded nodes.
-
getDescendentUnknownAttributes
(s, v=None)[source]¶ Unhexlify and unpickle t/v.descendentUnknownAttribute field.
-
getLeoFile
(theFile, fileName, readAtFileNodesFlag=True, silent=False, checkOpenFiles=True)[source]¶ Read a .leo file. The caller should follow this with a call to c.redraw().
-
getLeoOutline
(s, reassignIndices=True)¶ Read a Leo outline from string s in clipboard format.
-
getLeoOutlineFromClipboard
(s, reassignIndices=True)[source]¶ Read a Leo outline from string s in clipboard format.
-
getSaxUa
(attr, val, kind=None)[source]¶ Parse an unknown attribute in a <v> or <t> element. The unknown tag has been pickled and hexlify’d.
-
handleNodeConflicts
()[source]¶ Create a ‘Recovered Nodes’ node for each entry in c.nodeConflictList.
-
handleVnodeSaxAttributes
(sax_node, v)[source]¶ The native attributes of <v> elements are a, t, vtag, tnodeList, marks, expanded, and descendentTnode/VnodeUnknownAttributes.
-
putDescendentVnodeUas
(p)[source]¶ Return the a uA field for descendent VNode attributes, suitable for reconstituting uA’s for anonymous vnodes.
-
putLeoOutline
(p=None)[source]¶ Return a string, not unicode, encoded with self.leo_file_encoding, suitable for pasting to the clipboard.
-
putStyleSheetLine
()[source]¶ Put the xml stylesheet line.
Leo 5.3: - Use only the stylesheet setting, ignoreing c.frame.stylesheet. - Write no stylesheet element if there is no setting.
The old way made it almost impossible to delete stylesheet element.
-
putUaHelper
(torv, key, val)[source]¶ Put attribute whose name is key and value is val to the output stream.
-
putUnknownAttributes
(torv)[source]¶ Put pickleable values for all keys in torv.unknownAttributes dictionary.
-
readSaxFile
(theFile, fileName, silent, inClipboard, reassignIndices, s=None)[source]¶ Read the entire .leo file using the sax parser.
-
resolveArchivedPosition
(archivedPosition, root_v)[source]¶ Return a VNode corresponding to the archived position relative to root node root_v.
-
retrieveVnodesFromDb
(conn)[source]¶ Recreates tree from the data contained in table vnodes. This method follows behavior of readSaxFile.
-
setDefaultDirectoryForNewFiles
(fileName)[source]¶ Set c.openDirectory for new files for the benefit of leoAtFile.scanAllDirectives.
-
updateSaxClone
(sax_node, parent_v, v)[source]¶ Update the body text of v. It overrides any previous body text.
-
writeMissingAtFileNodes
(event=None)[source]¶ Write all @file nodes for which the corresponding external file does not exist.
-
write_LEO_file
(fileName, outlineOnlyFlag, toString=False, toOPML=False)¶ Write the .leo file.
-
-
class
leo.core.leoFileCommands.
SaxContentHandler
(c, fileName, silent, inClipboard)[source]¶ Bases:
xml.sax.saxutils.XMLGenerator
A sax content handler class that reads Leo files.
-
attrsToList
(attrs)[source]¶ Convert the attributes to a list of g.Bunches.
attrs: an Attributes item passed to startElement.
-
attrsToString
(attrs, sep='\n')[source]¶ Convert the attributes to a string.
attrs: an Attributes item passed to startElement.
sep: the separator charater between attributes.
-
leoFind
Module¶
Leo’s gui-independent find classes.
-
class
leo.core.leoFind.
LeoFind
(c)[source]¶ Bases:
object
The base class for Leo’s Find commands.
-
batchChange
(pos1, pos2)[source]¶ Do a single batch change operation, updating the head or body string of p and leaving the result in s_ctrl.
s_ctrl contains the found text on entry and contains the changed text on exit. pos and pos2 indicate the selection. The selection will never be empty.
-
createCloneFindAllNodes
(clones, flattened)[source]¶ Create a “Found” node as the last node of the outline. Clone all positions in the clones set a children of found.
-
createCloneTagNodes
(clones)[source]¶ Create a “Found Tag” node as the last node of the outline. Clone all positions in the clones set as children of found.
-
debugIndices
= []¶
-
doCloneFindAll
(after, data, flatten, p, undoType)[source]¶ Handle the clone-find-all command, from p to after.
-
editWidget
(event, forceFocus=True)[source]¶ An override of baseEditCommands.editWidget that does not set focus when using anything other than the tk gui.
This prevents this class from caching an edit widget that is about to be deallocated.
-
findDefHelper
(event, defFlag)[source]¶ Find the definition of the class, def or var under the cursor.
-
firstSearchPane
()[source]¶ Set return the value of self.in_headline indicating which pane to search first.
-
focusInTree
()[source]¶ Return True is the focus widget w is anywhere in the tree pane.
Note: the focus may be in the find pane.
-
generalSearchHelper
(pattern, cloneFindAll=False, cloneFindAllFlattened=False, findAll=False)[source]¶
-
getFindResultStatus
(find_all=False)[source]¶ Return the status to be shown in the status line after a find command completes.
-
initInHeadline
()[source]¶ Select the first pane to search for incremental searches and changes. This is called only at the start of each search. This must not alter the current insertion point or selection range.
-
initInteractiveCommands
()[source]¶ Init an interactive command. This is tricky!
Always start in the presently selected widget, provided that searching is enabled for that widget. Always start at the present insert point for the body pane. For headlines, start at beginning or end of the headline text.
-
initNextText
(ins=None)[source]¶ Init s_ctrl when a search fails. On entry: - self.in_headline indicates what text to use. - self.reverse indicates how to set the insertion point.
-
isearchBackward
(event)[source]¶ Begin a backward incremental search.
- Plain characters extend the search backward.
- !<isearch-forward>! repeats the search.
- Esc or any non-plain key ends the search.
- Backspace reverses the search.
- Backspacing to an empty search pattern completely undoes the effect of the search.
-
isearchBackwardRegexp
(event)[source]¶ Begin a backward incremental regexp search.
- Plain characters extend the search.
- !<isearch-forward-regexp>! repeats the search.
- Esc or any non-plain key ends the search.
- Backspace reverses the search.
- Backspacing to an empty search pattern completely undoes the effect of the search.
-
isearchForward
(event)[source]¶ Begin a forward incremental search.
- Plain characters extend the search.
- !<isearch-forward>! repeats the search.
- Esc or any non-plain key ends the search.
- Backspace reverses the search.
- Backspacing to an empty search pattern completely undoes the effect of the search.
-
isearchForwardRegexp
(event)[source]¶ Begin a forward incremental regexp search.
- Plain characters extend the search.
- !<isearch-forward-regexp>! repeats the search.
- Esc or any non-plain key ends the search.
- Backspace reverses the search.
- Backspacing to an empty search pattern completely undoes the effect of the search.
-
isearchWithPresentOptions
(event)[source]¶ Begin an incremental search using find panel options.
- Plain characters extend the search.
- !<isearch-forward-regexp>! repeats the search.
- Esc or any non-plain key ends the search.
- Backspace reverses the search.
- Backspacing to an empty search pattern completely undoes the effect of the search.
-
makeRegexSubs
(s, groups)[source]¶ Carefully substitute group[i-1] for i strings in s. The group strings may contain i strings: they are not substituted.
-
minibufferCloneFindAll
(event=None, preloaded=None)[source]¶ clone-find-all ( aka find-clone-all and cfa).
Create an organizer node whose descendants contain clones of all nodes matching the search string, except @nosearch trees.
The list is not flattened: clones appear only once in the descendants of the organizer node.
-
minibufferCloneFindAllFlattened
(event=None, preloaded=None)[source]¶ clone-find-all-flattened (aka find-clone-all-flattened and cff).
Create an organizer node whose direct children are clones of all nodes matching the search string, except @nosearch trees.
The list is flattened: every cloned node appears as a direct child of the organizer node, even if the clone also is a descendant of another cloned node.
-
minibufferCloneFindTag
(event=None)[source]¶ clone-find-tag (aka find-clone-tag and cft).
Create an organizer node whose descendants contain clones of all nodes matching the given tag, except @nosearch trees.
The list is always flattened: every cloned node appears as a direct child of the organizer node, even if the clone also is a descendant of another cloned node.
-
minibufferFindAll
(event=None)[source]¶ Create a summary node containing descriptions of all matches of the search string.
-
minibufferFindAllUniqueRegex
(event=None)[source]¶ Create a summary node containing all unique matches of the regex search string. This command shows only the matched string itself.
-
minibufferReplaceAll
(event=None)[source]¶ Replace all instances of the search string with the replacement string.
-
minibufferTagChildren
(event=None)[source]¶ tag-children: prompt for a tag and add it to all children of c.p.
-
outsideSearchRange
(p)[source]¶ Return True if the search is about to go outside its range, assuming both the headline and body text of the present node have been searched.
-
replace
(event=None)¶
-
restoreAllExpansionStates
(expanded, redraw=False)[source]¶ expanded is a set of gnx of nodes that should be expanded
-
search
()[source]¶ Search s_ctrl for self.find_text with present options. Returns (pos, newpos) or (None,None).
-
searchWithPresentOptions
(event, findAllFlag=False, findAllUniqueFlag=False, changeAllFlag=False)[source]¶ Open the search pane and get the search string.
-
setFindScopeSuboutlineOnly
(event=None)[source]¶ Set the ‘Suboutline Only’ radio button in the Find tab.
-
setupArgs
(forward=False, regexp=False, word=False)[source]¶ Set up args for commands that force various values for commands (re-/word-/search-backward/forward) that force one or more of these values to be a spefic value.
Init a search started by a button in the Find panel.
-
showFindOptions
(event=None)[source]¶ Show the present find options in the status line. This is useful for commands like search-forward that do not show the Find Panel.
-
showSuccess
(pos, newpos, showState=True)[source]¶ Display the result of a successful find operation.
-
leoFrame
Module¶
leoGlobals
Module¶
Global constants, variables and utility functions used throughout Leo.
Important: This module imports no other Leo module.
-
class
leo.core.leoGlobals.
BindingInfo
(kind, commandName='', func=None, nextMode=None, pane=None, stroke=None)[source]¶ Bases:
object
A class representing any kind of key binding line.
This includes other information besides just the KeyStroke.
-
class
leo.core.leoGlobals.
Bunch
(**keywords)[source]¶ Bases:
object
A class that represents a colection of things.
Especially useful for representing a collection of related variables.
-
leo.core.leoGlobals.
CheckVersion
(s1, s2, condition='>=', stringCompare=None, delimiter='.', trace=False)[source]¶
-
class
leo.core.leoGlobals.
Command
(name, **kwargs)[source]¶ Bases:
object
A global decorator for creating commands.
This is the recommended way of defining all new commands, including commands that could befined inside a class. The typical usage is:
@g.command(‘command-name’) def A_Command(event):
c = event.get(‘c’) …g can not be used anywhere in this class!
-
class
leo.core.leoGlobals.
CommanderCommand
(name, **kwargs)[source]¶ Bases:
object
A global decorator for creating commander commands, that is, commands that were formerly methods of the Commands class in leoCommands.py.
Usage:
The decorator injects command_name into the Commander class and calls funcToMethod so the ivar will be injected in all future commanders.
g can not be used anywhere in this class!
-
class
leo.core.leoGlobals.
FileLikeObject
(encoding='utf-8', fromString=None)[source]¶ Bases:
object
Define a file-like object for redirecting writes to a string.
The caller is responsible for handling newlines correctly.
-
getvalue
()¶
-
read
()¶
-
-
class
leo.core.leoGlobals.
GeneralSetting
(kind, encoding=None, ivar=None, setting=None, val=None, path=None, tag='setting', unl=None)[source]¶ Bases:
object
A class representing any kind of setting except shortcuts.
-
dump
()¶ x.__repr__() <==> repr(x)
-
-
class
leo.core.leoGlobals.
GitIssueController
[source]¶ Bases:
object
A class encapsulating the retrieval of GitHub issues.
The GitHub api: https://developer.github.com/v3/issues/
-
leo.core.leoGlobals.
IdleTime
(handler, delay=500, tag=None)[source]¶ A thin wrapper for the LeoQtGui.IdleTime class.
The IdleTime class executes a handler with a given delay at idle time. The handler takes a single argument, the IdleTime instance:
def handler(timer): """IdleTime handler. timer is an IdleTime instance.""" delta_t = timer.time-timer.starting_time g.trace(timer.count, '%2.4f' % (delta_t)) if timer.count >= 5: g.trace('done') timer.stop() # Execute handler every 500 msec. at idle time. timer = g.IdleTime(handler,delay=500) if timer: timer.start()
Timer instances are completely independent:
def handler1(timer): delta_t = timer.time-timer.starting_time g.trace('%2s %2.4f' % (timer.count,delta_t)) if timer.count >= 5: g.trace('done') timer.stop() def handler2(timer): delta_t = timer.time-timer.starting_time g.trace('%2s %2.4f' % (timer.count,delta_t)) if timer.count >= 10: g.trace('done') timer.stop() timer1 = g.IdleTime(handler1,delay=500) timer2 = g.IdleTime(handler2,delay=1000) if timer1 and timer2: timer1.start() timer2.start()
-
class
leo.core.leoGlobals.
KeyStroke
(binding)[source]¶ Bases:
object
A class that represent any key stroke or binding.
stroke.s is the “canonicalized” stroke.
-
isPlainKey
()[source]¶ Return True if self.s represents a plain key.
A plain key is a key that can be inserted into text.
Note: The caller is responsible for handling Alt-Ctrl keys.
-
-
class
leo.core.leoGlobals.
MatchBrackets
(c, p, language)[source]¶ Bases:
object
A class implementing the match-brackets command. In the interest of speed, the code assumes that the user invokes the match-bracket command ouside of any string, comment or (for perl or javascript) regex.
-
ends_comment
(s, i)[source]¶ Return True if s[i] ends a comment. This is called while scanning backward, so this is a bit of a guess.
-
expand_range
(s, left, right, max_right, expand=False)[source]¶ Find the bracket nearest the cursor searching outwards left and right.
Expand the range (left, right) in string s until either s[left] or s[right] is a bracket. right can not exceed max_right, and if expand is True, the new range must encompass the old range, in addition to s[left] or s[right] being a bracket.
- Returns
- new_left, new_right, bracket_char, index_of_bracket_char
- if expansion succeeds, otherwise
- None, None, None, None
Note that only one of new_left and new_right will necessarily be a bracket, but index_of_bracket_char will definitely be a bracket.
-
run
()[source]¶ The driver for the MatchBrackets class.
With no selected range, find the nearest bracket and select from it to it’s match, moving cursor to mathc. With selected range, the first time, move cursor back to other end of range. The second time, select enclosing range.
-
-
class
leo.core.leoGlobals.
NullObject
(*args, **keys)[source]¶ Bases:
object
An object that does nothing, and does it very well. From the Python cookbook, recipe 5.23
-
class
leo.core.leoGlobals.
PosList
(c, aList=None)[source]¶ Bases:
list
A subclass of list for creating and selecting lists of positions.
This is deprecated, use leoNodes.PosList instead!
- aList = g.PosList(c)
- # Creates a PosList containing all positions in c.
- aList = g.PosList(c,aList2)
- # Creates a PosList from aList2.
- aList2 = aList.select(pattern,regex=False,removeClones=True)
- # Creates a PosList containing all positions p in aList # such that p.h matches the pattern. # The pattern is a regular expression if regex is True. # if removeClones is True, all positions p2 are removed # if a position p is already in the list and p2.v == p.v.
- aList.dump(sort=False,verbose=False)
- # Prints all positions in aList, sorted if sort is True. # Prints p.h, or repr(p) if verbose is True.
-
class
leo.core.leoGlobals.
ReadLinesClass
(s)[source]¶ Bases:
object
A class whose next method provides a readline method for Python’s tokenize module.
-
class
leo.core.leoGlobals.
RedirectClass
[source]¶ Bases:
object
A class to redirect stdout and stderr to Leo’s log pane.
-
class
leo.core.leoGlobals.
SherlockTracer
(patterns, dots=True, show_args=True, show_return=True, verbose=True)[source]¶ Bases:
object
A stand-alone tracer class with many of Sherlock’s features.
This class should work in any environment containing the re, os and sys modules.
The arguments in the pattern lists determine which functions get traced or which stats get printed. Each pattern starts with “+”, “-“, “+:” or “-:”, followed by a regular expression:
"+x" Enables tracing (or stats) for all functions/methods whose name
matches the regular expression x.“-x” Disables tracing for functions/methods. “+:x” Enables tracing for all functions in the file whose name matches x. “-:x” Disables tracing for an entire file.
Enabling and disabling depends on the order of arguments in the pattern list. Consider the arguments for the Rope trace:
- patterns=[‘+.*’,’+:.*’,
- ‘-:.*lib.*’,’+:.*rope.*’,’-:.*leoGlobals.py’, ‘-:.*worder.py’,’-:.*prefs.py’,’-:.*resources.py’,])
This enables tracing for everything, then disables tracing for all library modules, except for all rope modules. Finally, it disables the tracing for Rope’s worder, prefs and resources modules. Btw, this is one of the best uses for regular expressions that I know of.
Being able to zero in on the code of interest can be a big help in studying other people’s code. This is a non-invasive method: no tracing code needs to be inserted anywhere.
-
class
leo.core.leoGlobals.
Tracer
(limit=0, trace=False, verbose=False)[source]¶ Bases:
object
A “debugger” that computes a call graph.
To trace a function and its callers, put the following at the function’s start:
g.startTracer()
-
class
leo.core.leoGlobals.
TypedDict
(name, keyType, valType)[source]¶ Bases:
object
A class containing a name and enforcing type checking.
-
class
leo.core.leoGlobals.
TypedDictOfLists
(name, keyType, valType)[source]¶ Bases:
leo.core.leoGlobals.TypedDict
A class whose values are lists of typed values.
-
leo.core.leoGlobals.
act_on_node
(c, p, event)¶
-
leo.core.leoGlobals.
actualColor
(color)[source]¶ Return the actual color corresponding to the requested color.
-
leo.core.leoGlobals.
adjustTripleString
(s, tab_width)[source]¶ Remove leading indentation from a triple-quoted string.
This works around the fact that Leo nodes can’t represent underindented strings.
-
leo.core.leoGlobals.
alert
(message, c=None)[source]¶ Raise an alert.
This method is deprecated: use c.alert instead.
-
leo.core.leoGlobals.
backupGitIssues
(c, base_url=None)[source]¶ Get a list of issues from Leo’s GitHub site.
-
leo.core.leoGlobals.
bunch
¶ alias of
leo.core.leoGlobals.Bunch
-
leo.core.leoGlobals.
callback
(func)[source]¶ A global decorator that protects Leo against crashes in callbacks.
This is the recommended way of defining all callback.
@g.callback def a_callback(…):
c = event.get(‘c’) …
-
leo.core.leoGlobals.
callers
(n=4, count=0, excludeCaller=True, verbose=False)[source]¶ Return a list containing the callers of the function that called g.callerList.
excludeCaller: True (the default), g.callers itself is not on the list.
If the verbose keyword is True, or the caller name is in the names list, return:
line N <file name> <class_name>.<caller_name> # methods line N <file name> <caller_name> # functions.Otherwise, just return the <caller name>
-
leo.core.leoGlobals.
cantImport
(moduleName, pluginName=None, verbose=True)[source]¶ Print a “Can’t Import” message and return None.
-
leo.core.leoGlobals.
check_cmd_instance_dict
(c, g)[source]¶ Check g.check_cmd_instance_dict. This is a permanent unit test, called from c.finishCreate.
-
leo.core.leoGlobals.
command
¶ alias of
leo.core.leoGlobals.Command
-
leo.core.leoGlobals.
command_alias
(alias, func)[source]¶ Create an alias for the already defined method in the Commands class.
-
leo.core.leoGlobals.
commander_command
¶ alias of
leo.core.leoGlobals.CommanderCommand
-
leo.core.leoGlobals.
comment_delims_from_extension
(filename)[source]¶ Return the comment delims corresponding to the filename’s extension.
>>> import leo.core.leoGlobals as g >>> g.comment_delims_from_extension(".py") ('#', '', '')
>>> g.comment_delims_from_extension(".c") ('//', '/*', '*/')
>>> g.comment_delims_from_extension(".html") ('', '<!--', '-->')
-
leo.core.leoGlobals.
composeScript
(c, p, s, forcePythonSentinels=True, useSentinels=True)[source]¶ Compose a script from p.b.
-
leo.core.leoGlobals.
computeBaseDir
(c, base_dir, path_setting, trace=False)[source]¶ Compute a base_directory. If given, @string path_setting takes precedence.
-
leo.core.leoGlobals.
computeCommands
(c, commands, command_setting, trace=False)[source]¶ Get the list of commands. If given, @data command_setting takes precedence.
-
leo.core.leoGlobals.
computeFileUrl
(fn, c=None, p=None)[source]¶ Compute finalized url for filename fn. This involves adding url escapes and evaluating Leo expressions.
-
leo.core.leoGlobals.
compute_directives_re
()[source]¶ Return an re pattern which word matches all Leo directives. Only g.get_directives_dict uses this pattern.
-
leo.core.leoGlobals.
convertPythonIndexToRowCol
(s, i)[source]¶ Convert index i into string s into zero-based row/col indices.
-
leo.core.leoGlobals.
convertRowColToPythonIndex
(s, row, col, lines=None)[source]¶ Convert zero-based row/col indices into a python index into string s.
-
leo.core.leoGlobals.
createTopologyList
(c, root=None, useHeadlines=False)[source]¶ Creates a list describing a node and all its descendents
-
leo.core.leoGlobals.
create_temp_file
(textMode=False)[source]¶ Return a tuple (theFile,theFileName)
theFile: a file object open for writing. theFileName: the name of the temporary file.
-
leo.core.leoGlobals.
dictToString
(d, indent='', tag=None)[source]¶ Pretty print a Python dict to a string.
-
leo.core.leoGlobals.
doHook
(tag, *args, **keywords)[source]¶ This global function calls a hook routine. Hooks are identified by the tag param.
Returns the value returned by the hook routine, or None if the there is an exception.
We look for a hook routine in three places: 1. c.hookFunction 2. app.hookFunction 3. leoPlugins.doPlugins()
Set app.hookError on all exceptions. Scripts may reset app.hookError to try again.
-
leo.core.leoGlobals.
doKeywordArgs
(keys, d=None)[source]¶ Return a result dict that is a copy of the keys dict with missing items replaced by defaults in d dict.
-
leo.core.leoGlobals.
dump_encoded_string
(encoding, s)[source]¶ Dump s, assumed to be an encoded string.
-
leo.core.leoGlobals.
es
(*args, **keys)[source]¶ Put all non-keyword args to the log pane. The first, third, fifth, etc. arg translated by g.translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.core.leoGlobals.
es_debug
(*args, **keys)[source]¶ Print all non-keyword args, and put them to the log pane in orange.
The first, third, fifth, etc. arg translated by g.translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.core.leoGlobals.
es_print
(*args, **keys)[source]¶ Print all non-keyword args, and put them to the log pane.
The first, third, fifth, etc. arg translated by g.translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.core.leoGlobals.
es_print_exception
(full=True, c=None, color='red')[source]¶ Print exception info about the last exception.
-
leo.core.leoGlobals.
execGitCommand
(command, directory=None)[source]¶ Execute the given git command in the given directory.
-
leo.core.leoGlobals.
exec_file
(path, d, script=None)[source]¶ Simulate python’s execfile statement for python 3.
-
leo.core.leoGlobals.
executeScript
(name)[source]¶ Execute a script whose short python file name is given.
This is called only from the scripts_menu plugin.
-
leo.core.leoGlobals.
execute_shell_commands
(commands, trace=False)[source]¶ Execute each shell command in a separate process. Wait for each command to complete, except those starting with ‘&’
-
leo.core.leoGlobals.
execute_shell_commands_with_options
(base_dir=None, c=None, command_setting=None, commands=None, path_setting=None, trace=False, warning=None)[source]¶ A helper for prototype commands or any other code that runs programs in a separate process.
base_dir: Base directory to use if no config path given. commands: A list of commands, for g.execute_shell_commands. commands_setting: Name of @data setting for commands. path_setting: Name of @string setting for the base directory. warning: A warning to be printed before executing the commands.
-
leo.core.leoGlobals.
extractExecutableString
(c, p, s, language='python')[source]¶ Return all lines for the given @language directive.
Ignore all lines under control of any other @language directive.
-
leo.core.leoGlobals.
fileLikeObject
¶ alias of
leo.core.leoGlobals.FileLikeObject
-
leo.core.leoGlobals.
findLanguageDirectives
(c, p)[source]¶ Return the language in effect at position p.
-
leo.core.leoGlobals.
findNodeInChildren
(c, p, headline, exact=True)[source]¶ Search for a node in v’s tree matching the given headline.
-
leo.core.leoGlobals.
findNodeInTree
(c, p, headline, exact=True)[source]¶ Search for a node in v’s tree matching the given headline.
-
leo.core.leoGlobals.
findReference
(name, root)[source]¶ Find the section definition for name.
If a search of the descendants fails, and an ancestor is an @root node, search all the descendants of the @root node.
-
leo.core.leoGlobals.
findRootsWithPredicate
(c, root, predicate=None)[source]¶ Commands often want to find one or more roots, given a position p. A root is the position of any node matching a predicate.
This function formalizes the search order used by the pylint, pyflakes and the rst3 commands, returning a list of zero or more found roots.
-
leo.core.leoGlobals.
findTabWidthDirectives
(c, p)[source]¶ Return the language in effect at position p.
-
leo.core.leoGlobals.
find_line_start
(s, i)[source]¶ Return the index in s of the start of the line containing s[i].
-
leo.core.leoGlobals.
find_word
(s, word, i=0)[source]¶ Return the index of the first occurance of word in s, or -1 if not found.
g.find_word is not the same as s.find(i,word); g.find_word ensures that only word-matches are reported.
-
leo.core.leoGlobals.
flatten_list
(obj)[source]¶ A generator yielding a flattened (concatenated) version of obj.
-
leo.core.leoGlobals.
fullPath
(c, p, simulate=False)[source]¶ Return the full path (including fileName) in effect at p. Neither the path nor the fileName will be created if it does not exist.
-
leo.core.leoGlobals.
funcToMethod
(f, theClass, name=None)[source]¶ From the Python Cookbook…
The following method allows you to add a function as a method of any class. That is, it converts the function to a method of the class. The method just added is available instantly to all existing instances of the class, and to all instances created in the future.
The function’s first argument should be self.
The newly created method has the same name as the function unless the optional name argument is supplied, in which case that name is used as the method name.
-
leo.core.leoGlobals.
getDocStringForFunction
(func)[source]¶ Return the docstring for a function that creates a Leo command.
-
leo.core.leoGlobals.
getEncodingAt
(p, s=None)[source]¶ Return the encoding in effect at p and/or for string s.
Read logic: s is not None. Write logic: s is None.
-
leo.core.leoGlobals.
getGitIssues
(c, base_url=None, label_list=None, milestone=None, state=None)[source]¶ Get a list of issues from Leo’s GitHub site.
-
leo.core.leoGlobals.
getIvarsDict
(obj)[source]¶ Return a dictionary of ivars:values for non-methods of obj.
-
leo.core.leoGlobals.
getLanguageAtPosition
(c, p)[source]¶ Return the language in effect at position p. This is always a lowercase language name, never None.
-
leo.core.leoGlobals.
getLanguageFromAncestorAtFileNode
(p)[source]¶ Return the language in effect as determined by the file extension of the nearest enclosing @<file> node.
-
leo.core.leoGlobals.
getLine
(s, i)[source]¶ Return i,j such that s[i:j] is the line surrounding s[i]. s[i] is a newline only if the line is empty. s[j] is a newline unless there is no trailing newline.
-
leo.core.leoGlobals.
getLineAfter
(s, i)¶
-
leo.core.leoGlobals.
getOutputNewline
(c=None, name=None)[source]¶ Convert the name of a line ending to the line ending itself.
Priority: - Use name if name given - Use c.config.output_newline if c given, - Otherwise use g.app.config.output_newline.
-
leo.core.leoGlobals.
getPythonEncodingFromString
(s)[source]¶ Return the encoding given by Python’s encoding line. s is the entire file.
-
leo.core.leoGlobals.
getScript
(c, p, useSelectedText=True, forcePythonSentinels=True, useSentinels=True)[source]¶ Return the expansion of the selected text of node p. Return the expansion of all of node p’s body text if p is not the current node or if there is no text selection.
-
leo.core.leoGlobals.
getUrlFromNode
(p)[source]¶ Get an url from node p: 1. Use the headline if it contains a valid url. 2. Otherwise, look only at the first line of the body.
-
leo.core.leoGlobals.
getWord
(s, i)[source]¶ Return i,j such that s[i:j] is the word surrounding s[i].
-
leo.core.leoGlobals.
get_directives_dict
(p, root=None)[source]¶ Scan p for @directives found in globalDirectiveList.
Returns a dict containing the stripped remainder of the line following the first occurrence of each recognized directive
-
leo.core.leoGlobals.
get_directives_dict_list
(p)[source]¶ Scans p and all its ancestors for directives.
Returns a list of dicts containing pointers to the start of each directive
-
leo.core.leoGlobals.
gitBranchName
(path=None)[source]¶ Return the git branch name associated with path/.git, or the empty string if path/.git does not exist. If path is None, use the leo-editor directory.
-
leo.core.leoGlobals.
gitCommitNumber
(path=None)[source]¶ Return the git commit number associated with path/.git, or the empty string if path/.git does not exist. If path is None, use the leo-editor directory.
-
leo.core.leoGlobals.
gitDescribe
(path=None)[source]¶ Return the Git tag, distance-from-tag, and commit hash for the associated path. If path is None, use the leo-editor directory.
Given git describe cmd line output: `x-leo-v5.6-55-ge1129da
- `
- This function returns (‘x-leo-v5.6’, ‘55’, ‘e1129da’)
-
leo.core.leoGlobals.
gitHeadPath
(path=None)[source]¶ Compute the path to the .git/HEAD directory given the path to another directory. If no path is given, use the path to this file. This code can not use g.app.loadDir because it is called too early in Leo’s startup code.
-
leo.core.leoGlobals.
gitInfo
(path=None)[source]¶ Path is a .git/HEAD directory, or None.
Return the branch and commit number or (‘’, ‘’).
-
leo.core.leoGlobals.
handleUrlHelper
(url, c, p)[source]¶ Open a url. Most browsers should handle: ftp://ftp.uu.net/public/whatever http://localhost/MySiteUnderDevelopment/index.html file:///home/me/todolist.html
-
leo.core.leoGlobals.
importExtension
(moduleName, pluginName=None, verbose=False, required=False)[source]¶ Try to import a module. If that fails, try to import the module from Leo’s extensions directory.
moduleName is the module’s name, without file extension.
-
leo.core.leoGlobals.
importFromPath
(moduleName, path, verbose=False)[source]¶ Import a module whose name is given from the directory given by path.
Warning: This is a thin wrapper for imp.load_module, which is equivalent to reload! Reloading Leo files while running will crash Leo.
-
leo.core.leoGlobals.
importModule
(moduleName, pluginName=None, verbose=False)[source]¶ Try to import a module as Python’s import command does.
moduleName is the module’s name, without file extension.
This function first attempts to import from sys.modules, then from the extensions and external directories.
-
leo.core.leoGlobals.
initScriptFind
(c, findHeadline, changeHeadline=None, firstNode=None, script_search=True, script_change=True)[source]¶
-
leo.core.leoGlobals.
init_dialog_folder
(c, p, use_at_path=True)[source]¶ Return the most convenient folder to open or save a file.
-
leo.core.leoGlobals.
init_zodb
(pathToZodbStorage, verbose=True)[source]¶ Return an ZODB.DB instance from ZODB.FileStorage.FileStorage(pathToZodbStorage) return None on any error.
-
leo.core.leoGlobals.
input_
(message='', c=None)[source]¶ Safely execute python’s input statement.
c.executeScriptHelper binds ‘input’ to be a wrapper that calls g.input_ with c and handler bound properly.
-
leo.core.leoGlobals.
insertCodingLine
(encoding, script)[source]¶ Insert a coding line at the start of script s if no such line exists. The coding line must start with @first because it will be passed to at.writeFromString.
-
leo.core.leoGlobals.
is_sentinel
(line, delims)[source]¶ Return True if line starts with a sentinel comment.
>>> import leo.core.leoGlobals as g >>> py_delims = g.comment_delims_from_extension('.py') >>> g.is_sentinel("#@+node",py_delims) True >>> g.is_sentinel("#comment",py_delims) False
>>> c_delims = g.comment_delims_from_extension('.c') >>> g.is_sentinel("//@+node",c_delims) True >>> g.is_sentinel("//comment",c_delims) False
>>> html_delims = g.comment_delims_from_extension('.html') >>> g.is_sentinel("<!--@+node-->",html_delims) True >>> g.is_sentinel("<!--comment-->",html_delims) False
-
leo.core.leoGlobals.
is_special
(s, i, directive)[source]¶ Return True if the body text contains the @ directive.
-
leo.core.leoGlobals.
itemsMatchingPrefixInList
(s, aList, matchEmptyPrefix=False)[source]¶ This method returns a sorted list items of aList whose prefix is s.
It also returns the longest common prefix of all the matches.
-
leo.core.leoGlobals.
ivars2instance
(c, g, ivars)[source]¶ Return the instance of c given by ivars. ivars is a list of strings. A special case: ivars may be ‘g’, indicating the leoGlobals module.
-
leo.core.leoGlobals.
join_list
(aList, indent='', leading='', sep='', trailing='')[source]¶ Create a dict representing the concatenation of the strings in aList, formatted per the keyword args. See the HTMLReportTraverser class for many examples.
-
leo.core.leoGlobals.
joinlines
(aList)¶
-
leo.core.leoGlobals.
jsonCommitInfo
()[source]¶ return asctime and timestamp from leo/core/commit_timestamp.json. return (‘’, ‘’) if the file does not exist or is not a valid .json file.
-
leo.core.leoGlobals.
listToString
(obj, indent='', tag=None)[source]¶ Pretty print a Python list to a string.
-
leo.core.leoGlobals.
list_to_string
(obj)[source]¶ Convert obj (a list of lists) to a single string.
This function stresses the gc; it will usually be better to work with the much smaller strings generated by flatten_list.
Use this function only in special circumstances, for example, when it is known that the resulting string will be small.
-
leo.core.leoGlobals.
log
(*args, **keys)¶ Put all non-keyword args to the log pane. The first, third, fifth, etc. arg translated by g.translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.core.leoGlobals.
longestCommonPrefix
(s1, s2)[source]¶ Find the longest prefix common to strings s1 and s2.
-
leo.core.leoGlobals.
makeAllNonExistentDirectories
(theDir, c=None, force=False, verbose=True)[source]¶ Attempt to make all non-existent directories
-
leo.core.leoGlobals.
makeDict
(**keys)[source]¶ Returns a Python dictionary from using the optional keyword arguments.
-
leo.core.leoGlobals.
new_cmd_decorator
(name, ivars)[source]¶ Return a new decorator for a command with the given name. Compute the class instance using the ivar string or list.
-
leo.core.leoGlobals.
nullObject
¶ alias of
leo.core.leoGlobals.NullObject
-
leo.core.leoGlobals.
objToString
(obj, indent='', printCaller=False, tag=None)[source]¶ Pretty print any Python object to a string.
-
leo.core.leoGlobals.
openUrl
(p)[source]¶ Open the url of node p. Use the headline if it contains a valid url. Otherwise, look only at the first line of the body.
-
leo.core.leoGlobals.
openUrlHelper
(event, url=None)[source]¶ Open the UNL or URL under the cursor. Return it for unit testing.
-
leo.core.leoGlobals.
openUrlOnClick
(event, url=None)[source]¶ Open the URL under the cursor. Return it for unit testing.
-
leo.core.leoGlobals.
openWithFileName
(fileName, old_c=None, gui=None)[source]¶ Create a Leo Frame for the indicated fileName if the file exists.
returns the commander of the newly-opened outline.
-
leo.core.leoGlobals.
os_path_basename
(path)[source]¶ Return the second half of the pair returned by split(path).
-
leo.core.leoGlobals.
os_path_dirname
(path)[source]¶ Return the first half of the pair returned by split(path).
-
leo.core.leoGlobals.
os_path_expandExpression
(s, **keys)[source]¶ Expand all {{anExpression}} in c’s context.
-
leo.core.leoGlobals.
os_path_finalize
(path, **keys)[source]¶ Expand ‘~’, then return os.path.normpath, os.path.abspath of the path. There is no corresponding os.path method
-
leo.core.leoGlobals.
os_path_finalize_join
(*args, **keys)[source]¶ Do os.path.join(*args), then finalize the result.
-
leo.core.leoGlobals.
os_path_join
(*args, **keys)[source]¶ The same as os.path.join, but safe for unicode. In addition, it supports the !! and . conventions.
-
leo.core.leoGlobals.
os_path_realpath
(path)[source]¶ Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).
-
leo.core.leoGlobals.
pno
(tag='')¶ Print newly allocated objects.
-
leo.core.leoGlobals.
pr
(*args, **keys)[source]¶ Print all non-keyword args. This is a wrapper for the print statement.
The first, third, fifth, etc. arg translated by g.translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.core.leoGlobals.
printDict
(obj, indent='', printCaller=False, tag=None)¶ Pretty print any Python object using g.pr.
-
leo.core.leoGlobals.
printList
(obj, indent='', printCaller=False, tag=None)¶ Pretty print any Python object using g.pr.
-
leo.core.leoGlobals.
printNewObjects
(tag='')¶ Print newly allocated objects.
-
leo.core.leoGlobals.
printObj
(obj, indent='', printCaller=False, tag=None)[source]¶ Pretty print any Python object using g.pr.
-
leo.core.leoGlobals.
printTuple
(obj, indent='', printCaller=False, tag=None)¶ Pretty print any Python object using g.pr.
-
leo.core.leoGlobals.
python_tokenize
(s, line_numbers=True)[source]¶ Tokenize string s and return a list of tokens (kind,value,line_number)
where kind is in (‘comment,’id’,’nl’,’other’,’string’,’ws’).
-
leo.core.leoGlobals.
readFileIntoEncodedString
(fn, silent=False)[source]¶ Return the raw contents of the file whose full path is fn.
-
leo.core.leoGlobals.
readFileIntoString
(fn, encoding='utf-8', kind=None)[source]¶ Return the contents of the file whose full path is fn.
Return (s,e) s is the string, converted to unicode, or None if there was an error. e is the encoding of s, computed in the following order: - The BOM encoding if the file starts with a BOM mark. - The encoding given in the # -- coding: utf-8 -- line for python files. - The encoding given by the ‘encoding’ keyword arg. - None, which typically means ‘utf-8’.
-
leo.core.leoGlobals.
readFileIntoUnicodeString
(fn, encoding=None, silent=False)[source]¶ Return the raw contents of the file whose full path is fn.
-
leo.core.leoGlobals.
recursiveUNLFind
(unlList, c, depth=0, p=None, maxdepth=0, maxp=None, soft_idx=False, hard_idx=False)[source]¶ Internal part of recursiveUNLSearch which doesn’t change the selected position or call c.frame.bringToFront()
returns found, depth, p, where:
- found is True if a full match was found
- depth is the depth of the best match
- p is the position of the best match
- NOTE: maxdepth is max depth seen in recursion so far, not a limit on
- how far we will recurse. So it should default to 0 (zero).
- unlList: list of ‘headline’, ‘headline:N’, or ‘headline:N,M’ elements, where N is the node’s position index and M the zero based count of like named nodes, eg. ‘foo:2’, ‘foo:4,1’, ‘foo:12,3’
- c: outline
- soft_idx: use index when matching name not found
- hard_idx: use only indexes, ignore node names
- depth: part of recursion, don’t set explicitly
- p: part of recursion, don’t set explicitly
- maxdepth: part of recursion, don’t set explicitly
- maxp: part of recursion, don’t set explicitly
-
leo.core.leoGlobals.
recursiveUNLParts
(text)[source]¶ recursiveUNLParts - return index, occurence, line_number, col_number from an UNL fragment. line_number is allowed to be negative to indicate a “global” line number within the file.
Parameters: text (str) – the fragment, foo or foo:2 or foo:2,0,4,10 Returns: index, occurence, line_number, col_number Return type: (int, int, int, int) or (None, None, None, None)
-
leo.core.leoGlobals.
recursiveUNLSearch
(unlList, c, depth=0, p=None, maxdepth=0, maxp=None, soft_idx=False, hard_idx=False)[source]¶ try and move to unl in the commander c
All parameters passed on to recursiveUNLFind(), see that for docs.
- NOTE: maxdepth is max depth seen in recursion so far, not a limit on
- how far we will recurse. So it should default to 0 (zero).
-
leo.core.leoGlobals.
removeExtraLws
(s, tab_width)[source]¶ Remove extra indentation from one or more lines.
Warning: used by getScript. This is not the same as g.adjustTripleString.
-
leo.core.leoGlobals.
removeLeading
(s, chars)[source]¶ Remove all characters in chars from the front of s.
-
leo.core.leoGlobals.
removeTrailing
(s, chars)[source]¶ Remove all characters in chars from the end of s.
-
leo.core.leoGlobals.
replace_path_expression
(c, expr)[source]¶ local function to replace a single path expression.
-
leo.core.leoGlobals.
run_pylint
(fn, rc, dots=True, patterns=None, sherlock=False, show_return=True, stats_patterns=None, verbose=True)[source]¶ Run pylint with the given args, with Sherlock tracing if requested.
Do not assume g.app exists.
run() in pylint-leo.py and PylintCommand.run_pylint optionally call this function.
-
leo.core.leoGlobals.
sanitize_filename
(s)[source]¶ Prepares string s to be a valid file name:
- substitute ‘_’ for whitespace and special path characters.
- eliminate all other non-alphabetic characters.
- convert double quotes to single quotes.
- strip leading and trailing whitespace.
- return at most 128 characters.
-
leo.core.leoGlobals.
scanAllAtTabWidthDirectives
(c, p)[source]¶ Scan p and all ancestors looking for @tabwidth directives.
-
leo.core.leoGlobals.
scanAllAtWrapDirectives
(c, p)[source]¶ Scan p and all ancestors looking for @wrap/@nowrap directives.
-
leo.core.leoGlobals.
scanAtCommentAndAtLanguageDirectives
(aList)[source]¶ Scan aList for @comment and @language directives.
@comment should follow @language if both appear in the same node.
-
leo.core.leoGlobals.
scanAtHeaderDirectives
(aList)[source]¶ scan aList for @header and @noheader directives.
-
leo.core.leoGlobals.
scanAtLineendingDirectives
(aList)[source]¶ Scan aList for @lineending directives.
-
leo.core.leoGlobals.
scanAtPagewidthDirectives
(aList, issue_error_flag=False)[source]¶ Scan aList for @pagewidth directives.
-
leo.core.leoGlobals.
scanAtTabwidthDirectives
(aList, issue_error_flag=False)[source]¶ Scan aList for @tabwidth directives.
-
leo.core.leoGlobals.
scanAtWrapDirectives
(aList, issue_error_flag=False)[source]¶ Scan aList for @wrap and @nowrap directives.
-
leo.core.leoGlobals.
scanForAtIgnore
(c, p)[source]¶ Scan position p and its ancestors looking for @ignore directives.
-
leo.core.leoGlobals.
scanForAtLanguage
(c, p)[source]¶ Scan position p and p’s ancestors looking only for @language and @ignore directives.
Returns the language found, or c.target_language.
-
leo.core.leoGlobals.
scanForAtSettings
(p)[source]¶ Scan position p and its ancestors looking for @settings nodes.
-
leo.core.leoGlobals.
setDefaultDirectory
(c, p, importing=False)[source]¶ Return a default directory by scanning @path directives.
-
leo.core.leoGlobals.
set_delims_from_language
(language)[source]¶ Return a tuple (single,start,end) of comment delims.
-
leo.core.leoGlobals.
set_delims_from_string
(s)[source]¶ Return (delim1, delim2, delim2), the delims following the @comment directive.
This code can be called from @language logic, in which case s can point at @comment
-
leo.core.leoGlobals.
set_language
(s, i, issue_errors_flag=False)[source]¶ Scan the @language directive that appears at s[i:].
The @language may have been stripped away.
Returns (language, delim1, delim2, delim3)
-
leo.core.leoGlobals.
shortFilename
(fileName, n=None)¶ Return the base name of a path.
-
leo.core.leoGlobals.
skip_braces
(s, i)[source]¶ Skips from the opening to the matching brace.
If no matching is found i is set to len(s)
-
leo.core.leoGlobals.
skip_leading_ws_with_indent
(s, i, tab_width)[source]¶ Skips leading whitespace and returns (i, indent),
- i points after the whitespace
- indent is the width of the whitespace, assuming tab_width wide tabs.
-
leo.core.leoGlobals.
skip_long
(s, i)[source]¶ Scan s[i:] for a valid int. Return (i, val) or (i, None) if s[i] does not point at a number.
-
leo.core.leoGlobals.
skip_parens
(s, i)[source]¶ Skips from the opening ( to the matching ).
If no matching is found i is set to len(s)
-
leo.core.leoGlobals.
skip_pascal_begin_end
(s, i)[source]¶ Skips from begin to matching end. If found, i points to the end. Otherwise, i >= len(s) The end keyword matches begin, case, class, record, and try.
-
leo.core.leoGlobals.
skip_string
(s, i, verbose=True)[source]¶ Scan forward to the end of a string. New in Leo 4.4.2 final: give error only if verbose is True
-
leo.core.leoGlobals.
splitLines
(s)[source]¶ Split s into lines, preserving the number of lines and the endings of all lines, including the last line.
-
leo.core.leoGlobals.
splitLongFileName
(fn, limit=40)[source]¶ Return fn, split into lines at slash characters.
-
leo.core.leoGlobals.
splitlines
(s)¶ Split s into lines, preserving the number of lines and the endings of all lines, including the last line.
-
leo.core.leoGlobals.
stat
(name=None)[source]¶ Increments the statistic for name in g.app.statsDict The caller’s name is used by default.
-
leo.core.leoGlobals.
stripBOM
(s)[source]¶ If there is a BOM, return (e,s2) where e is the encoding implied by the BOM and s2 is the s stripped of the BOM.
If there is no BOM, return (None,s)
s must be the contents of a file (a string) read in binary mode.
-
leo.core.leoGlobals.
stripBrackets
(s)[source]¶ Same as s.lstrip(‘<’).rstrip(‘>’) except it works for Python 2.2.1.
-
leo.core.leoGlobals.
toEncodedString
(s, encoding='utf-8', reportErrors=False)[source]¶ Convert unicode string to an encoded string.
-
leo.core.leoGlobals.
toEncodedStringWithErrorCode
(s, encoding, reportErrors=False)[source]¶ For unit testing: convert s to an encoded string and return (s,ok).
-
leo.core.leoGlobals.
toPythonIndex
(s, index)[source]¶ Convert index to a Python int.
index may be a Tk index (x.y) or ‘end’.
-
leo.core.leoGlobals.
toString
(obj, indent='', printCaller=False, tag=None)¶ Pretty print any Python object to a string.
-
leo.core.leoGlobals.
toUnicode
(s, encoding='utf-8', reportErrors=False)[source]¶ Connvert a non-unicode string with the given encoding to unicode.
-
leo.core.leoGlobals.
toUnicodeWithErrorCode
(s, encoding, reportErrors=False)[source]¶ For unit testing: convert s to unicode and return (s,ok).
-
leo.core.leoGlobals.
tr
(s)¶ Return the translated text of s.
-
leo.core.leoGlobals.
translateArgs
(args, d)[source]¶ Return the concatenation of s and all args,
with odd args translated.
-
leo.core.leoGlobals.
tupleToString
(obj, indent='', tag=None)[source]¶ Pretty print a Python tuple to a string.
-
leo.core.leoGlobals.
unquoteUrl
(url)[source]¶ Replace special characters (especially %20, by their equivalent).
This function handles 2/3 issues and suppresses pylint complaints.
-
leo.core.leoGlobals.
update_file_if_changed
(c, file_name, temp_name)[source]¶ Compares two files.
If they are different, we replace file_name with temp_name. Otherwise, we just delete temp_name. Both files should be closed.
-
leo.core.leoGlobals.
utils_stat
(fileName)[source]¶ Return the access mode of named file, removing any setuid, setgid, and sticky bits.
-
leo.core.leoGlobals.
virtual_event_name
(s)¶
leoGui
Module¶
leoIPython
Module¶
leoImport
Module¶
-
class
leo.core.leoImport.
FreeMindImporter
(c)[source]¶ Bases:
object
Importer class for FreeMind (.mmap) files.
-
class
leo.core.leoImport.
JSON_Import_Helper
(c)[source]¶ Bases:
object
A class that helps client scripts import .json files.
Client scripts supply data describing how to create Leo outlines from the .json data.
-
class
leo.core.leoImport.
LeoImportCommands
(c)[source]¶ Bases:
object
A class implementing all of Leo’s import/export code. This class uses importers in the leo/plugins/importers folder.
For more information, see leo/plugins/importers/howto.txt.
-
appendStringToBody
(p, s)[source]¶ Similar to c.appendStringToBody, but does not recolor the text or redraw the screen.
-
body_parser_for_ext
(ext)[source]¶ A factory returning a body parser function for the given file extension.
-
convertCodePartToWeb
(s, i, p, result)[source]¶ # Headlines not containing a section reference are ignored in noweb and generate index index in cweb.
-
convertVnodeToWeb
(v)[source]¶ This code converts a VNode to noweb text as follows:
Convert @doc to @ Convert @root or @code to < < name > >=, assuming the headline contains < < name > > Ignore other directives Format doc parts so they fit in pagewidth columns. Output code parts as is.
-
createHeadline
(parent, body, headline)[source]¶ Create a new VNode as the last child of parent position.
-
createOutline
(fileName, parent, atShadow=False, ext=None, s=None)[source]¶ Create an outline by importing a file, reading the file with the given encoding if string s is None.
ext, The file extension to be used, or None. fileName: A string or None. The name of the file to be read. parent: The parent position of the created outline. s: A string or None. The file’s contents.
-
flattenOutline
(fileName)[source]¶ A helper for the flatten-outline command.
Export the selected outline to an external file. The outline is represented in MORE format.
-
getHeadRef
(p)[source]¶ Look for either noweb or cweb brackets. Return everything between those brackets.
-
get_import_filename
(fileName, parent)[source]¶ Return the absolute path of the file and set .default_directory.
-
importDerivedFiles
(parent=None, paths=None, command='Import')[source]¶ Import one or more external files. This is not a command. It must not have an event arg. command is None when importing from the command line.
-
importFreeMind
(files)[source]¶ Import a list of .mm.html files exported from FreeMind: http://freemind.sourceforge.net/wiki/index.php/Main_Page
-
importMindMap
(files)[source]¶ Import a list of .csv files exported from MindJet: https://www.mindjet.com/
-
init_import
(atShadow, ext, fileName, s)[source]¶ Init ivars imports and read the file into s. Return ext, s.
-
parse_body
(p)[source]¶ Parse p.b as source code, creating a tree of descendant nodes. This is essentially an import of p.b.
-
reloadSettings
()¶
-
removeSentinelLines
(s, line_delim, start_delim, unused_end_delim)[source]¶ Properly remove all sentinle lines in s.
-
scannerUnitTest
(p, ext=None, fileName=None, s=None, showTree=False)[source]¶ Run a unit test of an import scanner, i.e., create a tree from string s at location p.
-
-
class
leo.core.leoImport.
MORE_Importer
(c)[source]¶ Bases:
object
Class to import MORE files.
-
class
leo.core.leoImport.
RecursiveImportController
(c, kind, add_path=True, recursive=True, safe_at_file=True, theTypes=None)[source]¶ Bases:
object
Recursively import all python files in a directory and clean the result.
-
minimize_headlines
(p, prefix)[source]¶ Create @path nodes to minimize the paths required in descendant nodes.
-
post_process
(p, prefix)[source]¶ Traverse p’s tree, replacing all nodes that start with prefix by the smallest equivalent @path or @file node.
-
-
class
leo.core.leoImport.
TabImporter
(c, separate=True)[source]¶ A class to import a file whose outline levels are indicated by leading tabs or blanks (but not both).
-
class
leo.core.leoImport.
ZimImportController
(c)[source]¶ Bases:
object
A class to import Zim folders and files: http://zim-wiki.org/ First use Zim to export your project to rst files.
Original script by Davy Cottet.
- User options:
- @int rst_level = 0 @string rst_type @string zim_node_name @string path_to_zim
-
leo.core.leoImport.
headToPrevNode
(event)[source]¶ Move the code preceding a def to end of previous node.
-
leo.core.leoImport.
import_free_mind_files
(event)[source]¶ Prompt for free-mind files and import them.
-
leo.core.leoImport.
import_tabbed_files_command
(event)[source]¶ Prompt for tabbed files and import them.
-
leo.core.leoImport.
import_zim_command
(event)[source]¶ Import a zim folder, http://zim-wiki.org/, as the last top-level node of the outline.
First use Zim to export your project to rst files.
This command requires the following Leo settings:
@int rst_level = 0 @string rst_type @string zim_node_name @string path_to_zim
leoInspect
Module¶
leoKeys
Module¶
Gui-independent keystroke handling for Leo.
-
class
leo.core.leoKeys.
AutoCompleterClass
(k)[source]¶ Bases:
object
A class that inserts autocompleted and calltip text in text widgets. This class shows alternatives in the tabbed log pane.
The keyHandler class contains hooks to support these characters: invoke-autocompleter-character (default binding is ‘.’) invoke-calltips-character (default binding is ‘(‘)
-
abort
()¶
-
attr_matches
(s, namespace)[source]¶ Compute matches when string s is of the form name.name….name.
Evaluates s using eval(s,namespace)
Assuming the text is of the form NAME.NAME….[NAME], and is evaluatable in the namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions.
For class instances, class members are are also considered.)
Warning: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated.
-
autoCompleteForce
(event=None)[source]¶ Show autocompletion, even if autocompletion is not presently enabled.
-
calltip
()[source]¶ Show the calltips for the present prefix. ch is ‘(‘ if the user has just typed it.
-
clean_completion_list
(header, tabList)[source]¶ Return aList with header removed from the start of each list item.
-
finish
()¶
-
get_leo_namespace
(prefix)[source]¶ Return an environment in which to evaluate prefix. Add some common standard library modules as needed.
-
get_summary_list
(header, tabList)[source]¶ Show the possible starting letters, but only if there are more than one.
-
jedi_warning
= False¶
-
showCalltipsForce
(event=None)[source]¶ Show the calltips at the cursor, even if calltips are not presently enabled.
-
-
class
leo.core.leoKeys.
ContextSniffer
[source]¶ Bases:
object
Class to analyze surrounding context and guess class
For simple dynamic code completion engines.
-
class
leo.core.leoKeys.
FileNameChooser
(c)[source]¶ Bases:
object
A class encapsulation file selection & completion logic.
-
class
leo.core.leoKeys.
GetArg
(c, prompt='full-command: ', tabName='Completion')[source]¶ Bases:
object
A class encapsulating all k.getArg logic.
k.getArg maps to ga.get_arg, which gets arguments in the minibuffer.
For details, see the docstring for ga.get_arg
-
command_source
(commandName)[source]¶ Return the source legend of an @button/@command node. ‘G’ leoSettings.leo ‘M’ myLeoSettings.leo ‘L’ local .leo File ‘ ‘ not an @command or @button node
-
compute_tab_list
(tabList, backspace=False, allow_empty_completion=False)[source]¶ Compute and show the available completions.
-
do_state_zero
(completion, event, handler, oneCharacter, returnKind, returnState, tabList, useMinibuffer)[source]¶ Do state 0 processing.
-
do_tab_callback
()[source]¶ If the command-name handler has a tab_callback, call handler.tab_callback() and return True.
-
do_tab_cycling
(common_prefix, tabList)[source]¶ Put the next (or first) completion in the minibuffer.
-
get_arg
(event, returnKind=None, returnState=None, handler=None, tabList=None, completion=True, oneCharacter=False, stroke=None, useMinibuffer=True)[source]¶ Accumulate an argument. Enter the given return state when done.
Ctrl-G will abort this processing at any time.
All commands needing user input call k.getArg, which just calls ga.get_arg.
The arguments to ga.get_arg are as follows:
event: The event passed to the command.
returnKind=None: A string. returnState=None, An int. handler=None, A function.
When the argument is complete, ga.do_end does:
if kind: k.setState(kind,n,handler)
tabList=[]: A list of possible completions.
completion=True: True if completions are enabled.
oneCharacter=False: True if k.arg should be a single character.
stroke=None: The incoming key stroke.
- useMinibuffer=True: True: put focus in the minibuffer while accumulating arguments.
- False allows sort-lines, for example, to show the selection range.
-
-
class
leo.core.leoKeys.
KeyHandlerClass
(c)[source]¶ Bases:
object
A class to support emacs-style commands. c.k is an instance of this class.
-
NEWgeneralModeHandler
(event, commandName=None, func=None, modeName=None, nextMode=None, prompt=None)[source]¶ Handle a mode defined by an @mode node in leoSettings.leo.
-
bindKey
(pane, shortcut, callback, commandName, modeFlag=False, tag=None)[source]¶ Bind the indicated shortcut (a Tk keystroke) to the callback.
No actual gui bindings are made: only entries in k.masterBindingsDict and k.bindingsDict.
tag gives the source of the binding.
Return True if the binding was made successfully.
-
bindShortcut
(pane, shortcut, callback, commandName, modeFlag=False, tag=None)¶ Bind the indicated shortcut (a Tk keystroke) to the callback.
No actual gui bindings are made: only entries in k.masterBindingsDict and k.bindingsDict.
tag gives the source of the binding.
Return True if the binding was made successfully.
-
checkBindings
()[source]¶ Print warnings if commands do not have any @shortcut entry. The entry may be None, of course.
-
check_bind_key
(commandName, pane, stroke)[source]¶ Return True if the binding of stroke to commandName for the given pane can be made.
-
commandHistoryBackwd
()[source]¶ Return the previous entry in the Command History - stay at the top if we are there
-
commandHistoryFwd
()[source]¶ Move down the Command History - fall off the bottom (return empty string) if necessary
-
completeAllBindings
(w=None)[source]¶ New in 4.4b3: make an actual binding in all the standard places.
The event will go to k.masterKeyHandler as always, so nothing really changes. except that k.masterKeyHandler will know the proper stroke.
-
createModeBindings
(modeName, d, w)[source]¶ Create mode bindings for the named mode using dictionary d for w, a text widget.
-
doBackSpace
(tabList, completion=True)[source]¶ Convenience method mapping k.doBackSpace to ga.do_back_space.
-
doBinding
(event)[source]¶ The last phase of k.masertKeyHandler. Execute the command associated with stroke’s binding. Call k.handleUnboundKeys for killed or non-existent bindings.
-
doKeyboardQuit
(event)[source]¶ Handle keyboard-quit logic. return True if k.masterKeyHandler should return.
-
doUnboundPlainKey
(event)[source]¶ Handle unbound plain keys. Return True if k.masterKeyHandler should return.
-
endCommand
(commandName)[source]¶ Make sure Leo updates the widget following a command.
Never changes the minibuffer label: individual commands must do that.
-
finishCreate
()[source]¶ Complete the construction of the keyHandler class. c.commandsDict has been created when this is called.
-
fullCommand
(event, specialStroke=None, specialFunc=None, help=False, helpHandler=None)[source]¶ Handle ‘full-command’ (alt-x) mode.
-
generalModeHandler
(event, commandName=None, func=None, modeName=None, nextMode=None, prompt=None)[source]¶ Handle a mode defined by an @mode node in leoSettings.leo.
-
get1Arg
(event, handler, prefix=None, tabList=None, completion=True, oneCharacter=False, stroke=None, useMinibuffer=True)[source]¶ k.get1Arg: Handle the next character the user types when accumulating a user argument from the minibuffer. Ctrl-G will abort this processing at any time.
Commands should use k.get1Arg to get the first minibuffer argument and k.getNextArg to get all other arguments.
Before going into the many details, let’s look at some examples. This code will work in any class having a ‘c’ ivar bound to a commander.
Example 1: get one argument from the user:
@g.command(‘my-command’) def myCommand(self, event):
k = self.c.k k.setLabelBlue(‘prompt: ‘) k.get1Arg(event, handler=self.myCommand1)- def myCommand1(self, event):
- k = self.c.k # k.arg contains the argument. # Finish the command. … # Reset the minibuffer. k.clearState() k.resetLabel() k.showStateAndMode()
Example 2: get two arguments from the user:
@g.command(‘my-command’) def myCommand(self, event):
k = self.c.k k.setLabelBlue(‘first prompt: ‘) k.get1Arg(event, handler=self.myCommand1)- def myCommand1(self, event):
- k = self.c.k self.arg1 = k.arg k.extendLabel(‘ second prompt: ‘, select=False, protect=True) k.getNextArg(handler=self.myCommand2)
- def myCommand2(self, event):
- k = self.c.k # k.arg contains second argument. # Finish the command, using self.arg1 and k.arg. … # Reset the minibuffer. k.clearState() k.resetLabel() k.showStateAndMode()
k.get1Arg and k.getNextArg are a convenience methods. They simply pass their arguments to the get_arg method of the singleton GetArg instance. This docstring describes k.get1arg and k.getNextArg as if they were the corresponding methods of the GetArg class.
k.get1Arg is a state machine. Logically, states are tuples (kind, n, handler) though they aren’t represented that way. When the state machine in the GetArg class is active, the kind is ‘getArg’. This constant has special meaning to Leo’s key-handling code.
The arguments to k.get1Arg are as follows:
event: The event passed to the command.
- handler=None, An executable. k.get1arg calls handler(event)
- when the user completes the argument by typing <Return> or (sometimes) <tab>.
tabList=[]: A list of possible completions.
completion=True: True if completions are enabled.
oneCharacter=False: True if k.arg should be a single character.
stroke=None: The incoming key stroke.
- useMinibuffer=True: True: put focus in the minibuffer while accumulating arguments.
- False allows sort-lines, for example, to show the selection range.
-
getArg
(event, returnKind=None, returnState=None, handler=None, prefix=None, tabList=None, completion=True, oneCharacter=False, stroke=None, useMinibuffer=True)[source]¶ Convenience method mapping k.getArg to ga.get_arg.
-
getFileName
(event, callback=None, filterExt=None, prompt='Enter File Name: ', tabName='Dired')[source]¶ Get a file name from the minibuffer.
-
getMinibufferCommandName
()[source]¶ Convenience method mapping k.getMinibufferCommandName to ga.get_minibuffer_command_name.
-
getNextArg
(handler)[source]¶ Get the next arg. For example, after a Tab in the find commands. See the docstring for k.get1Arg for examples of its use.
-
handleDefaultChar
(event, stroke)[source]¶ Handle an unbound key, based on the event’s widget. Do not assume that stroke exists.
-
handleMinibufferHelper
(event, pane, state, stroke)[source]¶ Execute a pane binding in the minibuffer.
Return ‘continue’, ‘ignore’, ‘found’
-
initOneAbbrev
(commandName, key)[source]¶ Enter key as an abbreviation for commandName in c.commandsDict.
-
isAutoCompleteChar
(stroke)[source]¶ Return True if stroke is bound to the auto-complete in the insert or overwrite state.
-
keyboardQuit
(event=None, setFocus=True, mouseClick=False)[source]¶ This method clears the state and the minibuffer label.
k.endCommand handles all other end-of-command chores.
-
kill_one_shortcut
(stroke)[source]¶ Update the configuration dicts so that c.config.getShortcut(name) will return None for all names presently bound to the stroke.
-
makeMasterGuiBinding
(stroke, w=None, trace=False)[source]¶ Make a master gui binding for stroke in pane w, or in all the standard widgets.
-
manufactureKeyPressForCommandName
(w, commandName)[source]¶ Implement a command by passing a keypress to the gui.
Only unit tests use this method.
-
masterCommand
(commandName=None, event=None, func=None, stroke=None)[source]¶ This is the central dispatching method. All commands and keystrokes pass through here. This returns None, but may set k.funcReturn.
-
modeHelp
(event)[source]¶ The mode-help command.
A possible convention would be to bind <Tab> to this command in most modes, by analogy with tab completion.
-
printButtons
(event=None)[source]¶ Print all @button and @command commands, their bindings and their source.
-
registerCommand
(commandName, func, allowBinding=False, pane='all', shortcut=None, **kwargs)[source]¶ Make the function available as a minibuffer command.
You can wrap any method in a callback function, so the restriction to functions is not significant.
Ignore the ‘shortcut’ arg unless ‘allowBinding’ is True.
Only k.bindOpenWith and the mod_scripting.py plugin should set allowBinding.
-
registerCommandShortcut
(commandName, func, pane, shortcut)[source]¶ Register a shortcut for the a command.
Important: Bindings created here from plugins can not be overridden. This includes @command and @button bindings created by mod_scripting.py.
-
resetCommandHistory
()[source]¶ reset the command history index to indicate that we are pointing ‘past’ the last entry
-
setLabelGray
(label=None)¶
-
setStatusLabel
(s)[source]¶ Set the label to s.
Use k.setStatusLabel, not k.setLael, to report the status of a Leo command. This allows the option to use g.es instead of the minibuffer to report status.
-
showStateAndMode
(w=None, prompt=None, setFocus=True)[source]¶ Show the state and mode at the start of the minibuffer.
-
leoMenu
Module¶
Gui-independent menu handling for Leo.
-
class
leo.core.leoMenu.
LeoMenu
(frame)[source]¶ Bases:
object
The base class for all Leo menus.
-
createMenuEntries
(menu, table, dynamicMenu=False)[source]¶ Create a menu entry from the table. New in 4.4: this method shows the shortcut in the menu, but this method never binds any shortcuts.
-
createMenuFromConfigList
(parentName, aList, level=0)[source]¶ Build menu based on nested list
List entries are either:
[‘@item’, ‘command-name’, ‘optional-view-name’]or:
[‘@menu Submenu name’, <nested list>, None]Parameters: - parentName (str) – name of menu under which to place this one
- aList (list) – list of entries as described above
-
createMenusFromConfigList
(aList)[source]¶ Create menus from aList. The ‘top’ menu has already been created.
-
createOpenWithMenuFromTable
(table)[source]¶ Table is a list of dictionaries, created from @openwith settings nodes.
This menu code uses these keys:
‘name’: menu label. ‘shortcut’: optional menu shortcut.efc.open_temp_file uses these keys:
‘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.
-
createOpenWithMenuItemsFromTable
(menu, table)[source]¶ Create an entry in the Open with Menu from the table, a list of dictionaries.
Each dictionary d has the following keys:
‘args’: the command-line arguments used to open the file. ‘ext’: not used here: used by efc.open_temp_file. ‘kind’: not used here: used by efc.open_temp_file. ‘name’: menu label. ‘shortcut’: optional menu shortcut.
-
deleteMenuItem
(itemName, menuName='top')[source]¶ Delete itemName from the menu whose name is menuName.
-
handleSpecialMenus
(name, parentName, alt_name=None, table=None)[source]¶ Handle a special menu if name is the name of a special menu. return True if this method handles the menu.
-
-
class
leo.core.leoMenu.
NullMenu
(frame)[source]¶ Bases:
leo.core.leoMenu.LeoMenu
A null menu class for testing and batch execution.
leoNodes
Module¶
Leo’s fundamental data classes.
-
class
leo.core.leoNodes.
NodeIndices
(id_)[source]¶ Bases:
object
A class managing global node indices (gnx’s).
-
getNewIndex
(v, cached=False)[source]¶ Create a new gnx for v or an empty string if the hold flag is set. Important: the method must allocate a new gnx even if v.fileIndex exists.
-
setTimeStamp
()¶ Set the timestamp string to be used by getNewIndex until further notice
-
-
class
leo.core.leoNodes.
PosList
[source]¶ Bases:
list
-
children
()[source]¶ Return a PosList instance containing pointers to all the immediate children of nodes in PosList self.
-
-
class
leo.core.leoNodes.
Position
(v, childIndex=0, stack=None)[source]¶ Bases:
object
-
archivedPosition
(root_p=None)[source]¶ Return a representation of a position suitable for use in .leo files.
-
atAsisFileNodeName
()¶
-
atNoSentFileNodeName
()¶
-
b
¶ position body string property
-
back
()¶
-
children_iter
()¶ Yield all child positions of p.
-
copyWithNewVnodes
(copyMarked=False)[source]¶ Return an unliked copy of p with a new vnode v. The new vnode is complete copy of v and all its descendants.
-
createNodeHierarchy
(heads, forcecreate=False)[source]¶ Create the proper hierarchy of nodes with headlines defined in ‘heads’ as children of the current position
params: heads - list of headlines in order to create, i.e. [‘foo’,’bar’,’baz’]
- will create:
- self -foo –bar —baz
- forcecreate - If False (default), will not create nodes unless they don’t exist
- If True, will create nodes regardless of existing nodes
returns the final position (‘baz’ in the above example)
-
firstChild
()¶
-
following_siblings_iter
()¶ Yield all siblings positions that follow p, not including p.
-
get_UNL
(with_file=True, with_proto=False, with_index=True, with_count=False)[source]¶ with_file=True - include path to Leo file with_proto=False - include ‘file://’ with_index - include ‘,x’ at end where x is child index in parent with_count - include ‘,x,y’ at end where y zero based count of same headlines
-
gnx
¶ position gnx property
-
h
¶ position property returning the headline string
-
hasFirstChild
()¶
-
hasVisBack
(c)¶
-
hasVisNext
(c)¶
-
initBodyString
(s)¶
-
insertAsLastChild
()[source]¶ Inserts a new VNode as the last child of self.
Returns the newly created position.
-
insertAsNthChild
(n)[source]¶ Inserts a new node as the the nth child of self. self must have at least n-1 children.
Returns the newly created position.
-
isAtAsisFileNode
()¶
-
isAtNoSentFileNode
()¶
-
lastChild
()¶
-
lastNode
()¶
-
moreBody
()[source]¶ Returns the body string in MORE format.
Inserts a backslash before any leading plus, minus or backslash.
-
moveToLastNode
()[source]¶ Move a position to last node of its tree.
N.B. Returns p if p has no children.
-
moveToRoot
(oldRoot=None)[source]¶ Moves a position to the root position.
Important: oldRoot must the previous root position if it exists.
-
nearest
(predicate=None)¶ A generator yielding all unique root positions “near” p1 = self that satisfy the given predicate. p.isAnyAtFileNode is the default predicate.
The search first proceeds up the p’s tree. If a root is found, this generator yields just that root.
Otherwise, the generator yields all unique nodes in p.subtree() that satisfy the predicate. Once a root is found, the generator skips its subtree.
-
nearest_roots
(predicate=None)[source]¶ A generator yielding all the root positions “near” p1 = self that satisfy the given predicate. p.isAnyAtFileNode is the default predicate.
The search first proceeds up the p’s tree. If a root is found, this generator yields just that root.
Otherwise, the generator yields all nodes in p.subtree() that satisfy the predicate. Once a root is found, the generator skips its subtree.
-
nearest_unique_roots
(predicate=None)[source]¶ A generator yielding all unique root positions “near” p1 = self that satisfy the given predicate. p.isAnyAtFileNode is the default predicate.
The search first proceeds up the p’s tree. If a root is found, this generator yields just that root.
Otherwise, the generator yields all unique nodes in p.subtree() that satisfy the predicate. Once a root is found, the generator skips its subtree.
-
next
()¶
-
nodeAfterTree
()¶
-
nosentinels
¶ position property returning the body text without sentinels
-
nthChild
(n)¶
-
parent
()¶
-
parents_iter
()¶ Yield all parent positions of p.
-
positionAfterDeletedTree
()[source]¶ Return the position corresponding to p.nodeAfterTree() after this node is deleted. This will be p.nodeAfterTree() unless p.next() exists.
This method allows scripts to traverse an outline, deleting nodes during the traversal. The pattern is:
p = c.rootPosition() while p: if <delete p?>: next = p.positionAfterDeletedTree() p.doDelete() p = next else: p.moveToThreadNext()
This method also allows scripts to move nodes during a traversal, provided that nodes are moved to a “safe” spot so that moving a node does not change the position of any other nodes.
For example, the move-marked-nodes command first creates a move node, called ‘Clones of marked nodes’. All moved nodes become children of this move node. Inserting these nodes as children of the “move node” does not change the positions of other nodes. Deleting these nodes may change the position of nodes, but the pattern above handles this complication cleanly.
-
safeMoveToThreadNext
()[source]¶ Move a position to threadNext position. Issue an error if any vnode is an ancestor of itself.
-
script
¶ position property returning the script formed by p and its descendants
-
scriptSetBodyString
(s)¶
-
self_and_parents_iter
()¶ Yield p and all parent positions of p.
-
self_and_siblings_iter
()¶ Yield all sibling positions of p including p.
-
self_and_subtree_iter
()¶ Yield p and all positions in p’s subtree.
-
setDirty
(setDescendentsDirty=True)[source]¶ Mark a node and all ancestor @file nodes dirty.
Warning: p.setDirty() is expensive because it calls p.setAllAncestorAtFileNodesDirty().
Usually, code should this setter, despite its cost, because it update’s Leo’s outline pane properly. Calling c.redraw() is not enough.
-
setTnodeText
(s)¶
-
simpleLevel
()¶ Return the number of p’s parents.
-
subtree_iter
()¶ Yield all positions in p’s subtree, but not p.
-
subtree_with_unique_tnodes_iter
()¶ Yield p and all other unique positions in p’s subtree.
-
subtree_with_unique_vnodes_iter
()¶ Yield p and all other unique positions in p’s subtree.
-
textOffset
()[source]¶ Return the fcol offset of self. Return None if p is has no ancestor @<file> node. http://tinyurl.com/5nescw
-
threadBack
()¶
-
threadNext
()¶
-
tnodes_iter
()¶ Yield p.v and all vnodes in p’s subtree.
-
u
¶ p.u property
-
unique_tnodes_iter
()¶ Yield p.v and all unique vnodes in p’s subtree.
-
unique_vnodes_iter
()¶ Yield p.v and all unique vnodes in p’s subtree.
-
visBack
(c)¶
-
visNext
(c)¶
-
vnodes_iter
()¶ Yield p.v and all vnodes in p’s subtree.
-
-
leo.core.leoNodes.
Poslist
¶ alias of
leo.core.leoNodes.PosList
-
leo.core.leoNodes.
VNode
[source]¶ alias of
leo.core.leoNodes.VNodeBase
-
class
leo.core.leoNodes.
VNodeBase
(context, gnx=None)[source]¶ Bases:
object
-
atAsisFileNodeName
()¶
-
atNoSentFileNodeName
()¶
-
b
¶ VNode body string property
-
body_unicode_warning
= False¶
-
clonedBit
= 1¶
-
copyTree
(copyMarked=False)[source]¶ Return an all-new tree of vnodes that are copies of self and all its descendants.
Important: the v.parents ivar must be [] for all nodes. v._addParentLinks will set all parents.
-
directParents
()[source]¶ (New in 4.2) Return a list of all direct parent vnodes of a VNode.
This is NOT the same as the list of ancestors of the VNode.
-
dirtyBit
= 512¶
-
expandedBit
= 4¶
-
getBody
()¶
-
gnx
¶ VNode gnx property
-
h
¶ VNode headline string property
-
hasFirstChild
()¶
-
head_unicode_warning
= False¶
-
initBodyString
(s)¶
-
initHeadString
(s)¶
-
isAtAllNode
()[source]¶ Returns True if the receiver contains @others in its body at the start of a line.
-
isAtAsisFileNode
()¶
-
isAtIgnoreNode
()[source]¶ Returns True if the receiver contains @ignore in its body at the start of a line.
or if the headline starts with @ignore.
-
isAtNoSentFileNode
()¶
-
isAtOthersNode
()[source]¶ Returns True if the receiver contains @others in its body at the start of a line.
-
markedBit
= 8¶
-
matchHeadline
(pattern)[source]¶ Returns True if the headline matches the pattern ignoring whitespace and case.
The headline may contain characters following the successfully matched pattern.
-
orphanBit
= 2048¶
-
richTextBit
= 128¶
-
selectedBit
= 32¶
-
setHeadText
(s)¶
-
setTnodeText
(s)¶
-
topBit
= 64¶
-
u
¶ VNode u property
-
unicode_warning_given
= False¶
-
visitedBit
= 256¶
-
writeBit
= 1024¶
-
-
leo.core.leoNodes.
position
¶ alias of
leo.core.leoNodes.Position
-
leo.core.leoNodes.
vnode
¶ alias of
leo.core.leoNodes.VNodeBase
leoPlugins
Module¶
Classes relating to Leo’s plugin architecture.
-
class
leo.core.leoPlugins.
BaseLeoPlugin
(tag, keywords)[source]¶ Bases:
object
A Convenience class to simplify plugin authoring
import the base class:
from leoPlugins import leo.core.leoBasePlugin as leoBasePlugin
create a class which inherits from leoBasePlugin:
class myPlugin(leoBasePlugin):
in the __init__ method of the class, call the parent constructor:
def __init__(self, tag, keywords): leoBasePlugin.__init__(self, tag, keywords)
put the actual plugin code into a method; for this example, the work is done by myPlugin.handler()
- put the class in a file which lives in the <LeoDir>/plugins directory
for this example it is named myPlugin.py
add code to register the plugin:
leoPlugins.registerHandler("after-create-leo-frame", Hello)
BaseLeoPlugins has 3 methods for setting commands
setCommand:
def setCommand(self, commandName, handler, shortcut = None, pane = 'all', verbose = True):
setMenuItem:
def setMenuItem(self, menu, commandName = None, handler = None):
setButton:
def setButton(self, buttonText = None, commandName = None, color = None):
variables
CommandName: the string typed into minibuffer to execute the handler
Handler: the method in the class which actually does the work Shortcut: the key combination to activate the command Menu: a string designating on of the menus (‘File’, Edit’, ‘Outline’, …) ButtonText: the text to put on the button if one is being created. Contents of file
<LeoDir>/plugins/hello.py
:class Hello(BaseLeoPlugin): def __init__(self, tag, keywords): # call parent __init__ BaseLeoPlugin.__init__(self, tag, keywords) # if the plugin object defines only one command, # just give it a name. You can then create a button and menu entry self.setCommand('Hello', self.hello) self.setButton() self.setMenuItem('Cmds') # create a command with a shortcut self.setCommand('Hola', self.hola, 'Alt-Ctrl-H') # create a button using different text than commandName self.setButton('Hello in Spanish') # create a menu item with default text self.setMenuItem('Cmds') # define a command using setMenuItem self.setMenuItem('Cmds', 'Ciao baby', self.ciao) def hello(self, event): g.pr("hello from node %s" % self.c.p.h) def hola(self, event): g.pr("hola from node %s" % self.c.p.h) def ciao(self, event): g.pr("ciao baby (%s)" % self.c.p.h) leoPlugins.registerHandler("after-create-leo-frame", Hello)
-
setButton
(buttonText=None, commandName=None, color=None)[source]¶ Associate an existing command with a ‘button’
-
class
leo.core.leoPlugins.
CommandChainDispatcher
(commands=None)[source]¶ Bases:
object
Dispatch calls to a chain of commands until some func can handle it
Usage: instantiate, execute “add” to add commands (with optional priority), execute normally via f() calling mechanism.
-
class
leo.core.leoPlugins.
LeoPluginsController
[source]¶ Bases:
object
The global plugins controller, g.app.pluginsController
-
doHandlersForTag
(tag, keywords)[source]¶ Execute all handlers for a given tag, in alphabetical order. The caller, doHook, catches all exceptions.
-
loadHandlers
(tag, keys)[source]¶ Load all enabled plugins.
Using a module name (without the trailing .py) allows a plugin to be loaded from outside the leo/plugins directory.
-
loadOnePlugin
(moduleOrFileName, tag='open0', verbose=False)[source]¶ Load one plugin from a file name or module. Use extensive tracing if –trace-plugins is in effect.
Using a module name allows plugins to be loaded from outside the leo/plugins directory.
-
-
exception
leo.core.leoPlugins.
TryNext
(*args, **kwargs)[source]¶ Bases:
exceptions.Exception
Try next hook exception.
Raise this in your hook function to indicate that the next hook handler should be used to handle the operation. If you pass arguments to the constructor those arguments will be used by the next hook instead of the original ones.
leoPymacs
Module¶
A module to allow the Pymacs bridge to access Leo data.
All code in this module must be called from Emacs: calling Pymacs.lisp in other situations will hang Leo.
Notes:
The init method adds the parent directory of leoPymacs.py to Python’s sys.path. This is essential to make imports work from inside Emacs.
As of Leo 4.5, the following code, when executed from an Emacs buffer, will open trunk/leo/test.leo:
(pymacs-load "c:\leo.repo\trunk\leo\core\leoPymacs" "leo-") (setq c (leo-open "c:\leo.repo\trunk\leo\test\test.leo"))
Note that full path names are required in each case.
leoRst
Module¶
leoSessions
Module¶
Support for sessions in Leo.
-
class
leo.core.leoSessions.
SessionManager
[source]¶ Bases:
object
-
load_session
(c=None, unls=None)[source]¶ Open a tab for each item in UNLs & select the indicated node in each.
-
-
leo.core.leoSessions.
session_clear_command
(event)[source]¶ Close all tabs except the presently selected tab.
-
leo.core.leoSessions.
session_restore_command
(event)[source]¶ Open a tab for each item in the @session node & select the indicated node in each.
leoShadow
Module¶
leoShadow.py
This code allows users to use Leo with files which contain no sentinels and still have information flow in both directions between outlines and derived files.
Private files contain sentinels: they live in the Leo-shadow subdirectory. Public files contain no sentinels: they live in the parent (main) directory.
When Leo first reads an @shadow we create a file without sentinels in the regular directory.
The slightly hard thing to do is to pick up changes from the file without sentinels, and put them into the file with sentinels.
Settings: - @string shadow_subdir (default: .leo_shadow): name of the shadow directory.
- @string shadow_prefix (default: x): prefix of shadow files. This prefix allows the shadow file and the original file to have different names. This is useful for name-based tools like py.test.
-
class
leo.core.leoShadow.
ShadowController
(c, trace=False, trace_writers=False)[source]¶ Bases:
object
A class to manage @shadow files
-
class
AtShadowTestCase
(c, p, shadowController, delims=None, trace=False)[source]¶ Bases:
unittest.case.TestCase
Support @shadow-test nodes.
These nodes should have two descendant nodes: ‘before’ and ‘after’.
-
init_data
()[source]¶ Init x.sentinels and x.trailing_sentinels arrays. Return the list of non-sentinel lines in x.old_sent_lines.
-
init_ivars
(new_public_lines, old_private_lines, marker)[source]¶ Init all ivars used by propagate_changed_lines & its helpers.
-
isSignificantPublicFile
(fn)[source]¶ This tells the AtFile.read logic whether to import a public file or use an existing public file.
-
markerFromFileLines
(lines, fn)[source]¶ Return the sentinel delimiter comment to be used for filename.
-
markerFromFileName
(filename)[source]¶ Return the sentinel delimiter comment to be used for filename.
-
preprocess
(lines)[source]¶ Preprocess public lines, adding newlines as needed. This happens before the diff.
-
propagate_changed_lines
(new_public_lines, old_private_lines, marker, p=None)[source]¶ The Mulder update algorithm, revised by EKR.
Use the diff between the old and new public lines to insperse sentinels from old_private_lines into the result.
The algorithm never deletes or rearranges sentinels. However, verbatim sentinels may be inserted or deleted as needed.
-
propagate_changes
(old_public_file, old_private_file)[source]¶ Propagate the changes from the public file (without_sentinels) to the private file (with_sentinels)
-
replaceFileWithString
(fn, s)[source]¶ Replace the file with s if s is different from theFile’s contents.
Return True if theFile was changed.
-
separate_sentinels
(lines, marker)[source]¶ Separates regular lines from sentinel lines. Do not return @verbatim sentinels.
Returns (regular_lines, sentinel_lines)
-
shadowDirName
(filename)[source]¶ Return the directory for the shadow file corresponding to filename.
-
shadowPathName
(filename)[source]¶ Return the full path name of filename, resolved using c.fileName()
-
unlink
(filename, silent=False)[source]¶ Unlink filename from the file system. Give an error on failure.
-
class
leoTangle
Module¶
Support for @root and Leo’s tangle and untangle commands.
Everything in this file is deprecated, but will remain “forever”.
-
class
leo.core.leoTangle.
BaseTangleCommands
(c)[source]¶ Bases:
object
The base class for Leo’s tangle and untangle commands.
-
class
RegexpForLanguageOrComment
[source]¶ Bases:
object
-
re
= <module 're' from '/home/docs/checkouts/readthedocs.org/user_builds/leo-editor/envs/latest/lib/python2.7/re.pyc'>¶
-
regex
= <_sre.SRE_Pattern object>¶
-
-
reloadSettings
()¶
-
scanAllDirectives
(p)[source]¶ Scan VNode p and p’s ancestors looking for directives, setting corresponding tangle ivars and globals.
-
select_next_sentinel
(part_start_flag=True)[source]¶ The next sentinel will be either (a) a section part reference, using the “before” comment style for that part - when there are section references yet to interpolate for this part - when we’re followed by another part for this section (b) an end sentinel using the “after” comment style for the current part - when we’ve exhausted the parts for this section or (c) end of file for the root section The above requires that the parts in the tst be aware of the section interpolations each part will make
-
skip_body
(p, delims)[source]¶ The following subsections contain the interface between the Tangle and Untangle commands. This interface is an important hack, and allows Untangle to avoid duplicating the logic in skip_tree and its allies.
The aha is this: just at the time the Tangle command enters a definition into the symbol table, all the information is present that Untangle needs to update that definition.
To get whitespace exactly right we retain the outline’s leading whitespace and remove leading whitespace from the updated definition.
-
st_enter
(name, code, doc, delims_begin, delims_end, is_root_flag=False)[source]¶ Enters names and their associated code and doc parts into the given symbol table.
-
st_enter_section_name
(name, code, doc, delims_begin, delims_end)[source]¶ Enters a section name into the given symbol table.
The code and doc pointers are None for references.
-
st_lookup
(name, is_root_flag=False)[source]¶ Looks up name in the symbol table and creates a TstNode for it if it does not exist.
-
standardize_name
(name)[source]¶ Removes leading and trailing brackets, converts white space to a single blank and converts to lower case.
-
tangleTree
(p, report_errors)[source]¶ Tangles all nodes in the tree whose root is p.
Reports on its results if report_errors is True.
-
token_type
(s, i, report_errors=True)[source]¶ This method returns a code indicating the apparent kind of token at the position i.
The caller must determine whether section definiton tokens are valid.
returns (kind, end) and sets global root_name using setRootFromText(). end is only valid for kind in (section_ref, section_def, at_root).
-
update_current_vnode
(s)[source]¶ Called from within the Untangle logic to update the body text of self.p.
-
ust_enter
(name, part, of, code, nl_flag, is_root_flag=False)[source]¶ This routine enters names and their code parts into the given table. The ‘part’ and ‘of’ parameters are taken from the “(part n of m)” portion of the line that introduces the section definition in the C code.
If no part numbers are given the caller should set the ‘part’ and ‘of’ parameters to zero. The caller is reponsible for checking for duplicate parts.
This function handles names scanned from a source file; the corresponding st_enter routine handles names scanned from outlines.
-
ust_lookup
(name, part_number, is_root_flag=False, update_flag=False)[source]¶ Search the given table for a part matching the name and part number.
-
class
-
class
leo.core.leoTangle.
PartNode
(name, code, doc, is_root, is_dirty, delims)[source]¶ Bases:
object
-
class
leo.core.leoTangle.
TangleCommands
(c)[source]¶ Bases:
leo.core.leoTangle.BaseTangleCommands
A class that implements Leo’ tangle and untangle commands.
leoTest
Module¶
leoUndo
Module¶
Leo’s undo/redo manager.
-
class
leo.core.leoUndo.
Undoer
(c)[source]¶ Bases:
object
A class that implements unlimited undo and redo.
-
afterChangeGroup
(p, undoType, reportFlag=False, dirtyVnodeList=None)[source]¶ Create an undo node for general tree operations using d created by beforeChangeGroup
-
afterChangeNodeContents
(p, command, bunch, dirtyVnodeList=None, inHead=False)[source]¶ Create an undo node using d created by beforeChangeNode.
-
afterChangeTree
(p, command, bunch)[source]¶ Create an undo node for general tree operations using d created by beforeChangeTree
-
afterMark
(p, command, bunch, dirtyVnodeList=None)[source]¶ Create an undo node for mark and unmark commands.
-
beforeChangeGroup
(p, command, verboseUndoGroup=True)[source]¶ Prepare to undo a group of undoable operations.
-
beforeChangeNodeContents
(p, oldBody=None, oldHead=None, oldYScroll=None)[source]¶ Return data that gets passed to afterChangeNode
-
beforeSort
(p, undoType, oldChildren, newChildren, sortChildren)[source]¶ Create an undo node for sort operations.
-
clearUndoState
()[source]¶ Clears then entire Undo state.
All non-undoable commands should call this method.
-
createCommonBunch
(p)[source]¶ Return a bunch containing all common undo info. This is mostly the info for recreating an empty node at position p.
-
createVnodeUndoInfo
(v)[source]¶ Create a bunch containing all info needed to recreate a VNode for undo.
-
recognizeStartOfTypingWord
(old_lines, old_row, old_col, old_ch, new_lines, new_row, new_col, new_ch, prev_row, prev_col)[source]¶ A potentially user-modifiable method that should return True if the typing indicated by the params starts a new ‘word’ for the purposes of undo with ‘word’ granularity.
u.setUndoTypingParams calls this method only when the typing could possibly continue a previous word. In other words, undo will work safely regardless of the value returned here.
old_ch is the char at the given (Tk) row, col of old_lines. new_ch is the char at the given (Tk) row, col of new_lines.
The present code uses only old_ch and new_ch. The other arguments are given for use by more sophisticated algorithms.
-
saveTree
(p, treeInfo=None)[source]¶ Return a list of tuples with all info needed to handle a general undo operation.
-
setUndoTypingParams
(p, undo_type, oldText, newText, oldSel=None, newSel=None, oldYview=None)[source]¶ Save enough information to undo or redo typing operation.
Do nothing when called from the undo/redo logic because the Undo and Redo commands merely reset the bead pointer.
-
undoNodeContents
()[source]¶ Undo all changes to the contents of a node, including headline and body text, and marked bits.
-
leoVersion
Module¶
A module holding the following version-related info:
leoVersion.branch: The git branch name, or ‘’. leoVersion.build: The timestamp field from commit_timestamp.json. leoVersion.date: The asctime field from commit_timestamp.json. leoVersion.version: Leo’s version number, set below.
runLeo
Module¶
extensions Package¶
extensions
Package¶
asciidoc
Module¶
asciidoc - converts an AsciiDoc text file to HTML or DocBook
Copyright (C) 2002-2010 Stuart Rackham. Free use of this software is granted under the terms of the GNU General Public License (GPL).
-
class
leo.extensions.asciidoc.
AbstractBlock
[source]¶ -
blocknames
= []¶
-
get_param
(name, params=None)[source]¶ Return named processing parameter from params dictionary. If the parameter is not in params look in self.parameters.
-
is_conf_entry
(param)[source]¶ Return True if param matches an allowed configuration file entry name.
-
merge_attributes
(attrs, params=[])[source]¶ Use the current block’s attribute list (attrs dictionary) to build a dictionary of block processing parameters (self.parameters) and tag substitution attributes (self.attributes).
1. Copy the default parameters (self.*) to self.parameters. self.parameters are used internally to render the current block. Optional params array of additional parameters.
2. Copy attrs to self.attributes. self.attributes are used for template and tag substitution in the current block.
3. If a style attribute was specified update self.parameters with the corresponding style parameters; if there are any style parameters remaining add them to self.attributes (existing attribute list entries take precedence).
4. Set named positional attributes in self.attributes if self.posattrs was specified.
5. Finally self.parameters is updated with any corresponding parameters specified in attrs.
-
pop_blockname
()[source]¶ On block exits restore previous (parent) ‘blockname’ attribute or undefine it if we’re no longer inside a block.
-
push_blockname
(blockname=None)[source]¶ On block entry set the ‘blockname’ attribute. Only applies to delimited blocks, lists and tables.
-
-
class
leo.extensions.asciidoc.
AbstractBlocks
[source]¶ List of block definitions.
-
BLOCK_TYPE
= None¶
-
PREFIX
= ''¶
-
-
class
leo.extensions.asciidoc.
AttrDict
[source]¶ Bases:
dict
Like a dictionary except values can be accessed as attributes i.e. obj.foo can be used in addition to obj[‘foo’]. If an item is not present None is returned.
-
class
leo.extensions.asciidoc.
AttributeEntry
[source]¶ Static methods and attributes only.
-
attributes
= {}¶
-
name
= None¶
-
name2
= None¶
-
pattern
= None¶
-
subs
= None¶
-
value
= None¶
-
-
class
leo.extensions.asciidoc.
AttributeList
[source]¶ Static methods and attributes only.
-
attrs
= {}¶
-
match
= None¶
-
pattern
= None¶
-
-
class
leo.extensions.asciidoc.
BlockTitle
[source]¶ Static methods and attributes only.
-
pattern
= None¶
-
title
= None¶
-
-
class
leo.extensions.asciidoc.
Column
(width=None, align_spec=None, style=None)[source]¶ Table column.
-
class
leo.extensions.asciidoc.
Config
[source]¶ Methods to process configuration files.
-
ENTRIES_SECTIONS
= ('tags', 'miscellaneous', 'attributes', 'specialcharacters', 'specialwords', 'macros', 'replacements', 'quotes', 'titles', 'paradef-.+', 'listdef-.+', 'blockdef-.+', 'tabledef-.+', 'tabletags-.+', 'listtags-.+', 'replacements[23]', 'old_tabledef-.+')¶
-
entries_section
(section_name)[source]¶ Return True if conf file section contains entries, not a markup template.
-
find_config_dir
(*dirnames)[source]¶ Return path of configuration directory. Try all the well known locations. Return None if directory not found.
-
find_in_dirs
(filename, dirs=None)[source]¶ Find conf files from dirs list. Return list of found file paths. Return empty list if not found in any of the locations.
-
init
(cmd)[source]¶ Check Python version and locate the executable and configuration files directory. cmd is the asciidoc command or asciidoc.py path.
-
load_backend
(dirs=None)[source]¶ Load the backend configuration files from dirs list. If dirs not specified try all the well known locations. If a <backend>.conf file was found return it’s full path name, if not found return None.
-
load_file
(fname, dir=None, include=[], exclude=[])[source]¶ Loads sections dictionary with sections from file fname. Existing sections are overlaid. The ‘include’ list contains the section names to be loaded. The ‘exclude’ list contains section names not to be loaded. Return False if no file was found in any of the locations.
-
load_filters
(dirs=None)[source]¶ Load filter configuration files from ‘filters’ directory in dirs list. If dirs not specified try all the well known locations. Suppress loading if a file named __noautoload__ is in same directory as the conf file unless the filter has been specified with the –filter command-line option (in which case it is loaded unconditionally).
-
load_from_dirs
(filename, dirs=None, include=[])[source]¶ Load conf file from dirs list. If dirs not specified try all the well known locations. Return False if no file was sucessfully loaded.
-
load_sections
(sections, attrs=None)[source]¶ Loads sections dictionary. Each dictionary entry contains a list of lines. Updates ‘attrs’ with parsed [attributes] section entries.
-
parse_replacements
(sect='replacements')[source]¶ Parse replacements section into self.replacements dictionary.
Parse [tags] section entries into self.tags dictionary.
Perform attribute substitution on ‘section’ using document attributes plus ‘d’ attributes. Return tuple (stag,etag) containing pre and post | placeholder tags. ‘skipstart’ and ‘skipend’ are used to suppress substitution.
-
static
set_replacement
(pat, rep, replacements)[source]¶ Add pattern and replacement to replacements dictionary.
-
subs_replacements
(s, sect='replacements')[source]¶ Substitute patterns from self.replacements in ‘s’.
-
subs_section
(section, d)[source]¶ Section attribute substitution using attributes from document.attributes and ‘d’. Lines containing undefinded attributes are deleted.
-
subs_specialwords
(s)[source]¶ Search for word patterns from self.specialwords in ‘s’ and substitute using corresponding macro.
-
-
class
leo.extensions.asciidoc.
DelimitedBlocks
[source]¶ Bases:
leo.extensions.asciidoc.AbstractBlocks
List of delimited blocks.
-
BLOCK_TYPE
¶ alias of
DelimitedBlock
-
PREFIX
= 'blockdef-'¶
-
-
class
leo.extensions.asciidoc.
Document
[source]¶ Bases:
object
-
backend
¶
-
consume_attributes_and_comments
(comments_only=False, noblanks=False)[source]¶ Returns True if one or more attributes or comments were consumed. If ‘noblanks’ is True then consumation halts if a blank line is encountered.
-
doctype
¶
Return False if the author is malformed.
-
parse_header
(doctype, backend)[source]¶ Parses header, sets corresponding document attributes and finalizes document doctype and backend properties. Returns False if the document does not have a header. ‘doctype’ and ‘backend’ are the doctype and backend option values passed on the command-line, None if no command-line option was not specified.
Calculate any missing author related attributes.
-
-
class
leo.extensions.asciidoc.
FloatingTitle
[source]¶ Bases:
leo.extensions.asciidoc.Title
Floated titles are translated differently.
-
class
leo.extensions.asciidoc.
Header
[source]¶ Static methods and attributes only.
-
RCS_ID_RE
= '^\\$Id: \\S+ (?P<revnumber>\\S+) (?P<revdate>\\S+) \\S+ (?P<author>\\S+) (\\S+ )?\\$$'¶
-
REV_LINE_RE
= '^(\\D*(?P<revnumber>.*?),)?(?P<revdate>.*?)(:\\s*(?P<revremark>.*))?$'¶
-
-
class
leo.extensions.asciidoc.
InsensitiveDict
[source]¶ Bases:
dict
Like a dictionary except key access is case insensitive. Keys are stored in lower case.
-
class
leo.extensions.asciidoc.
Lex
[source]¶ Lexical analysis routines. Static methods and attributes only.
-
static
next
()[source]¶ Returns class of next element on the input (None if EOF). The reader is assumed to be at the first line following a previous element, end of file or line one. Exits with the reader pointing to the first line of the next element or EOF (leading blank lines are skipped).
-
prev_cursor
= None¶
-
prev_element
= None¶
-
static
set_margin
(lines, margin=0)[source]¶ Utility routine that sets the left margin to ‘margin’ space in a block of non-blank lines.
-
static
-
class
leo.extensions.asciidoc.
List
[source]¶ Bases:
leo.extensions.asciidoc.AbstractBlock
-
NUMBER_STYLES
= ('arabic', 'loweralpha', 'upperalpha', 'lowerroman', 'upperroman')¶
-
static
calc_index
(index, style)[source]¶ Return the ordinal number of (1…) of the list item index for the given list style.
-
static
calc_style
(index)[source]¶ Return the numbered list style (‘arabic’…) of the list item index. Return None if unrecognized style.
-
check_index
()[source]¶ Check calculated self.ordinal (1,2,…) against the item number in the document (self.index) and check the number style is the same as the first item (self.number_style).
Check that all necessary tags are present.
-
-
class
leo.extensions.asciidoc.
Lists
[source]¶ Bases:
leo.extensions.asciidoc.AbstractBlocks
List of List objects.
-
PREFIX
= 'listdef-'¶
-
TAGS
= ('list', 'entry', 'item', 'text', 'label', 'term')¶
-
TYPES
= ('bulleted', 'numbered', 'labeled', 'callout')¶
Load listtags-* conf file sections to self.tags.
-
-
class
leo.extensions.asciidoc.
Macro
[source]¶ -
-
section_name
(name=None)[source]¶ Return macro markup template section name based on macro name and prefix. Return None section not found.
-
-
class
leo.extensions.asciidoc.
Macros
[source]¶ -
SYS_RE
= '(?u)^(?P<name>[\\\\]?\\w(\\w|-)*?)::(?P<target>\\S*?)(\\[(?P<attrlist>.*?)\\])$'¶
-
extract_passthroughs
(text, prefix='')[source]¶ Extract the passthrough text and replace with temporary placeholders.
-
match
(prefix, name, text)[source]¶ Return re match object matching ‘text’ with macro type ‘prefix’, macro name ‘name’.
-
-
class
leo.extensions.asciidoc.
Message
[source]¶ Message functions.
-
PROG
= 'asciidoc'¶
-
error
(msg, cursor=None, halt=False)[source]¶ Report fatal error. If halt=True raise EAsciiDoc exception. If halt=False don’t exit application, continue in the hope of reporting all fatal errors finishing with a non-zero exit code.
-
-
class
leo.extensions.asciidoc.
OrderedDict
(d=None, **kwargs)[source]¶ Bases:
dict
Dictionary ordered by insertion order. Python Cookbook: Ordered Dictionary, Submitter: David Benjamin. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
-
popitem
() → (k, v), remove and return some (key, value) pair as a[source]¶ 2-tuple; but raise KeyError if D is empty.
-
-
class
leo.extensions.asciidoc.
Paragraphs
[source]¶ Bases:
leo.extensions.asciidoc.AbstractBlocks
List of paragraph definitions.
-
PREFIX
= 'paradef-'¶
-
-
class
leo.extensions.asciidoc.
Plugin
[source]¶ –filter and –theme option commands.
-
CMDS
= ('install', 'remove', 'list', 'build')¶
-
static
build
(args)[source]¶ Create plugin Zip file. args[0] is Zip file name. args[1] is plugin directory.
-
static
get_dir
()[source]¶ Return plugins path (.asciidoc/filters or .asciidoc/themes) in user’s home direcory or None if user home not defined.
-
static
install
(args)[source]¶ Install plugin Zip file. args[0] is plugin zip file path. args[1] is optional destination plugins directory.
-
static
remove
(args)[source]¶ Delete plugin directory. args[0] is plugin name. args[1] is optional plugin directory (defaults to ~/.asciidoc/<plugin_name>).
-
type
= None¶
-
-
class
leo.extensions.asciidoc.
Reader
[source]¶ Bases:
leo.extensions.asciidoc.Reader1
Wraps (well, sought of) Reader1 class and implements conditional text inclusion.
-
read_until
(terminators, same_file=False)[source]¶ Like read() but reads lines up to (but not including) the first line that matches the terminator regular expression, regular expression object or list of regular expression objects. If same_file is True then the terminating pattern must occur in the file the was being read when the routine was called.
-
-
class
leo.extensions.asciidoc.
Reader1
[source]¶ Line oriented AsciiDoc input file reader. Processes include and conditional inclusion system macros. Tabs are expanded and lines are right trimmed.
-
READ_BUFFER_MIN
= 10¶
-
-
class
leo.extensions.asciidoc.
Section
[source]¶ Static methods and attributes only.
-
static
gen_id
(title)[source]¶ The normalized value of the id attribute is an NCName according to the ‘Namespaces in XML’ Recommendation: NCName ::= NCNameStartChar NCNameChar* NCNameChar ::= NameChar - ‘:’ NCNameStartChar ::= Letter | ‘_’ NameChar ::= Letter | Digit | ‘.’ | ‘-‘ | ‘_’ | ‘:’
-
ids
= []¶
-
static
-
class
leo.extensions.asciidoc.
Table
[source]¶ Bases:
leo.extensions.asciidoc.AbstractBlock
-
ALIGN
= {'<': 'left', '>': 'right', '^': 'center'}¶
-
FORMATS
= ('psv', 'csv', 'dsv')¶
-
SEPARATORS
= {'csv': ',', 'dsv': ':|\\n', 'psv': '((?<!\\S)((?P<span>[\\d.]+)(?P<op>[*+]))?(?P<align>[<\\^>.]{,3})?(?P<style>[a-z])?)?\\|'}¶
-
VALIGN
= {'<': 'top', '>': 'bottom', '^': 'middle'}¶
-
static
parse_align_spec
(align_spec)[source]¶ Parse AsciiDoc cell alignment specifier and return 2-tuple with horizonatal and vertical alignment names. Unspecified alignments set to None.
-
parse_cols
(cols, halign, valign)[source]¶ Build list of column objects from table ‘cols’, ‘halign’ and ‘valign’ attributes.
-
parse_csv
(text)[source]¶ Parse the table source text and return a list of rows, each row is a list of Cells.
-
parse_psv_dsv
(text)[source]¶ Parse list of PSV or DSV table source text lines and return a list of Cells.
-
parse_rows
(text)[source]¶ Parse the table source text into self.rows (a list of rows, each row is a list of Cells.
-
static
parse_span_spec
(span_spec)[source]¶ Parse AsciiDoc cell span specifier and return 2-tuple with horizonatal and vertical span counts. Set default values (1,1) if not specified.
-
subs_row
(row, rowtype)[source]¶ Substitute the list of Cells using the data tag. Returns a list of marked up table cell elements.
-
-
class
leo.extensions.asciidoc.
Table_OLD
[source]¶ Bases:
leo.extensions.asciidoc.AbstractBlock
-
ALIGNMENTS
= {"'": 'right', '.': 'center', '`': 'left'}¶
-
COL_STOP
= "(`|'|\\.)"¶
-
FORMATS
= ('fixed', 'csv', 'dsv')¶
-
build_colspecs
()[source]¶ Generate colwidths and colspecs. This can only be done after the table arguments have been parsed since we use the table format.
-
parse_csv
(rows)[source]¶ Parse the list of source table rows. Each row item in the returned list contains a list of cell data elements.
-
parse_dsv
(rows)[source]¶ Parse the list of source table rows. Each row item in the returned list contains a list of cell data elements.
-
parse_fixed
(rows)[source]¶ Parse the list of source table rows. Each row item in the returned list contains a list of cell data elements.
-
parse_rows
(rows, rtag, dtag)[source]¶ Parse rows list using the row and data tags. Returns a substituted list of output lines.
-
split_rows
(rows)[source]¶ Return a two item tuple containing a list of lines up to but not including the next underline (continued lines are joined ) and the tuple of all lines after the underline.
-
-
class
leo.extensions.asciidoc.
Tables
[source]¶ Bases:
leo.extensions.asciidoc.AbstractBlocks
List of tables.
-
PREFIX
= 'tabledef-'¶
-
TAGS
= ('colspec', 'headrow', 'footrow', 'bodyrow', 'headdata', 'footdata', 'bodydata', 'paragraph')¶
Load tabletags-* conf file sections to self.tags.
-
-
class
leo.extensions.asciidoc.
Tables_OLD
[source]¶ Bases:
leo.extensions.asciidoc.AbstractBlocks
List of tables.
-
PREFIX
= 'old_tabledef-'¶
-
-
class
leo.extensions.asciidoc.
Title
[source]¶ Processes Header and Section titles. Static methods and attributes only.
-
attributes
= {}¶
-
dump_dict
= {}¶
-
static
getnumber
(level)[source]¶ Return next section number at section ‘level’ formatted like 1.2.3.4.
-
level
= 0¶
-
linecount
= None¶
-
pattern
= None¶
-
section_numbers
= [0, 0, 0, 0, 0]¶
-
sectname
= None¶
-
static
setsectname
()[source]¶ Set Title section name: If the first positional or ‘template’ attribute is set use it, next search for section title in [specialsections], if not found use default ‘sect<level>’ name.
-
subs
= ()¶
-
static
translate
(skipsubs=False)[source]¶ Parse the Title.attributes and Title.level from the reader. The real work has already been done by parse().
-
underlines
= ('==', '--', '~~', '^^', '++')¶
-
-
class
leo.extensions.asciidoc.
Trace
[source]¶ Bases:
object
Used in conjunction with the ‘trace’ attribute to generate diagnostic output. There is a single global instance of this class named trace.
-
SUBS_NAMES
= ('specialcharacters', 'quotes', 'specialwords', 'replacements', 'attributes', 'macros', 'callouts', 'replacements2', 'replacements3')¶
-
-
class
leo.extensions.asciidoc.
Writer
[source]¶ Writes lines to output file.
-
open
(fname, bom=None)[source]¶ bom is optional byte order mark. http://en.wikipedia.org/wiki/Byte-order_mark
-
-
leo.extensions.asciidoc.
asciidoc
(backend, doctype, confiles, infile, outfile, options)[source]¶ Convert AsciiDoc document to DocBook document of type doctype The AsciiDoc document is read from file object src the translated DocBook file written to file object dst.
-
leo.extensions.asciidoc.
assign
(dst, src)[source]¶ Assign all attributes from ‘src’ object to ‘dst’ object.
-
leo.extensions.asciidoc.
create_zip
(zip_file, src, skip_hidden=False)[source]¶ Create Zip file. If src is a directory archive all contained files and subdirectories, if src is a file archive the src file. Files and directories names starting with . are skipped if skip_hidden is True. Throws exception if error occurs.
-
leo.extensions.asciidoc.
date_str
(t)[source]¶ Convert seconds since the Epoch to formatted local date string.
-
leo.extensions.asciidoc.
dovetail
(lines1, lines2)[source]¶ Append list or tuple of strings ‘lines2’ to list ‘lines1’. Join the last non-blank item in ‘lines1’ with the first non-blank item in ‘lines2’ into a single string.
Merge the end tag with the first content line and the last content line with the end tag. This ensures verbatim elements don’t include extraneous opening and closing line breaks.
-
leo.extensions.asciidoc.
dump_section
(name, dict, f=<open file '<stdout>', mode 'w'>)[source]¶ Write parameters in ‘dict’ as in configuration file section format with section ‘name’.
-
leo.extensions.asciidoc.
east_asian_widths
= {'A': 1, 'F': 2, 'H': 1, 'N': 1, 'Na': 1, 'W': 2}¶ Mapping of result codes from unicodedata.east_asian_width() to character column widths.
-
leo.extensions.asciidoc.
execute
(cmd, opts, args)[source]¶ Execute asciidoc with command-line options and arguments. cmd is asciidoc command or asciidoc.py path. opts and args conform to values returned by getopt.getopt(). Raises SystemExit if an error occurs.
Doctests:
Check execution:
>>> import StringIO >>> infile = StringIO.StringIO('Hello *{author}*') >>> outfile = StringIO.StringIO() >>> opts = [] >>> opts.append(('--backend','html4')) >>> opts.append(('--no-header-footer',None)) >>> opts.append(('--attribute','author=Joe Bloggs')) >>> opts.append(('--out-file',outfile)) >>> execute(__file__, opts, [infile]) >>> print outfile.getvalue() <p>Hello <strong>Joe Bloggs</strong></p>
>>>
-
leo.extensions.asciidoc.
extract_zip
(zip_file, destdir)[source]¶ Unzip Zip file to destination directory. Throws exception if error occurs.
-
leo.extensions.asciidoc.
file_in
(fname, directory)[source]¶ Return True if file fname resides inside directory.
-
leo.extensions.asciidoc.
filter_lines
(filter_cmd, lines, attrs={})[source]¶ Run ‘lines’ through the ‘filter_cmd’ shell command and return the result. The ‘attrs’ dictionary contains additional filter attributes.
-
leo.extensions.asciidoc.
is_attr_defined
(attrs, dic)[source]¶ Check if the sequence of attributes is defined in dictionary ‘dic’. Valid ‘attrs’ sequence syntax: <attr> Return True if single attrbiute is defined. <attr1>,<attr2>,… Return True if one or more attributes are defined. <attr1>+<attr2>+… Return True if all the attributes are defined.
-
leo.extensions.asciidoc.
is_name
(s)[source]¶ Return True if s is valid attribute, macro or tag name (starts with alpha containing alphanumeric and dashes only).
-
leo.extensions.asciidoc.
is_re
(s)[source]¶ Return True if s is a valid regular expression else return False.
-
leo.extensions.asciidoc.
join_lines_OLD
(lines)[source]¶ Return a list in which lines terminated with the backslash line continuation character are joined.
-
leo.extensions.asciidoc.
localapp
()[source]¶ Return True if we are not executing the system wide version i.e. the configuration is in the executable’s directory.
-
leo.extensions.asciidoc.
lstrip_list
(s)[source]¶ Return list with empty items from start of list removed.
-
leo.extensions.asciidoc.
parse_attributes
(attrs, dict)[source]¶ Update a dictionary with name/value attributes from the attrs string. The attrs string is a comma separated list of values and keyword name=value pairs. Values must preceed keywords and are named ‘1’,‘2’… The entire attributes list is named ‘0’. If keywords are specified string values must be quoted. Examples:
attrs: ‘’ dict: {}
attrs: ‘hello,world’ dict: {‘2’: ‘world’, ‘0’: ‘hello,world’, ‘1’: ‘hello’}
attrs: ‘“hello”, planet=”earth”’ dict: {‘planet’: ‘earth’, ‘0’: ‘“hello”,planet=”earth”’, ‘1’: ‘hello’}
-
leo.extensions.asciidoc.
parse_entries
(entries, dict, unquote=False, unique_values=False, allow_name_only=False, escape_delimiter=True)[source]¶ Parse name=value entries from from lines of text in ‘entries’ into dictionary ‘dict’. Blank lines are skipped.
-
leo.extensions.asciidoc.
parse_entry
(entry, dict=None, unquote=False, unique_values=False, allow_name_only=False, escape_delimiter=True)[source]¶ Parse name=value entry to dictionary ‘dict’. Return tuple (name,value) or None if illegal entry. If name= then value is set to ‘’. If name and allow_name_only=True then value is set to ‘’. If name! and allow_name_only=True then value is set to None. Leading and trailing white space is striped from ‘name’ and ‘value’. ‘name’ can contain any printable characters. If the ‘=’ delimiter character is allowed in the ‘name’ then it must be escaped with a backslash and escape_delimiter must be True. If ‘unquote’ is True leading and trailing double-quotes are stripped from ‘name’ and ‘value’. If unique_values’ is True then dictionary entries with the same value are removed before the parsed entry is added.
-
leo.extensions.asciidoc.
parse_list
(s)[source]¶ Parse comma separated string of Python literals. Return a tuple of of parsed values.
-
leo.extensions.asciidoc.
parse_named_attributes
(s, attrs)[source]¶ Update a attrs dictionary with name=”value” attributes from the s string. Returns False if invalid syntax. Example: attrs: ‘star=”sun”,planet=”earth”’ dict: {‘planet’:’earth’, ‘star’:’sun’}
-
leo.extensions.asciidoc.
parse_options
(options, allowed, errmsg)[source]¶ Parse comma separated string of unquoted option names and return as a tuple of valid options. ‘allowed’ is a list of allowed option values. If allowed=() then all legitimate names are allowed. ‘errmsg’ is an error message prefix if an illegal option error is thrown.
-
leo.extensions.asciidoc.
re_join
(relist)[source]¶ Join list of regular expressions re1,re2,… to single regular expression (re1)|(re2)|…
-
leo.extensions.asciidoc.
rstrip_list
(s)[source]¶ Return list with empty items from end of list removed.
-
leo.extensions.asciidoc.
safe_filename
(fname, parentdir)[source]¶ Return file name which must reside in the parent file directory. Return None if file is not safe.
-
leo.extensions.asciidoc.
strip_list
(s)[source]¶ Return list with empty items from start and end of list removed.
-
leo.extensions.asciidoc.
strip_quotes
(s)[source]¶ Trim white space and, if necessary, quote characters from s.
-
leo.extensions.asciidoc.
subs_attrs
(lines, dictionary=None)[source]¶ Substitute ‘lines’ of text with attributes from the global document.attributes dictionary and from ‘dictionary’ (‘dictionary’ entries take precedence). Return a tuple of the substituted lines. ‘lines’ containing undefined attributes are deleted. If ‘lines’ is a string then return a string.
- Attribute references are substituted in the following order: simple, conditional, system.
- Attribute references inside ‘dictionary’ entry values are substituted.
-
leo.extensions.asciidoc.
subs_quotes
(text)[source]¶ Quoted text is marked up and the resulting text is returned.
-
leo.extensions.asciidoc.
subs_tag
(tag, dict={})[source]¶ Perform attribute substitution and split tag string returning start, end tag tuple (c.f. Config.tag()).
-
leo.extensions.asciidoc.
system
(name, args, is_macro=False, attrs=None)[source]¶ Evaluate a system attribute ({name:args}) or system block macro (name::[args]). If is_macro is True then we are processing a system block macro otherwise it’s a system attribute. The attrs dictionary is updated by the counter and set system attributes. NOTE: The include1 attribute is used internally by the include1::[] macro and is not for public use.
-
leo.extensions.asciidoc.
time_str
(t)[source]¶ Convert seconds since the Epoch to formatted local time string.
colors
Module¶
Colors module provides a colors names database and functions to access it.
The database is a python dictionary with reduced colornames as keys and color data in the form ‘#RRGGBB’ as values.
The reudced color names are common color names with spaces and capitalization removed.
Functions to access the data base are:
This function will convert name and return it in ‘#RRGGBB’ format if possible otherwise it will do the sme for default.
If default can not be converted, None will be returned.
name and default are reduced by removing spaces and capitalization before looking them up in the database.
This function will first call getColor to convert name (or default) to ‘#RRGGBB’ format, then it will convert this and return it as a python tuple in the form (0-255, 0-255, 0-255).
Returns None if anything goes wrong.
patch_11_01
Module¶
Patch utility to apply unified diffs
Brute-force line-by-line non-recursive parsing
Copyright (c) 2008-2011 anatoly techtonik Available under the terms of MIT license
Project home: http://code.google.com/p/python-patch/
$Id: patch.py 117 2011-01-09 16:38:03Z techtonik $ $HeadURL: https://python-patch.googlecode.com/svn/trunk/patch.py $
-
class
leo.extensions.patch_11_01.
Hunk
[source]¶ Bases:
object
Parsed hunk data container (hunk starts with @@ -R +R @@)
-
startsrc
= None¶ line count starts with 1
-
-
class
leo.extensions.patch_11_01.
Patch
(stream=None)[source]¶ Bases:
object
-
can_patch
(filename)[source]¶ Check if specified filename can be patched. Returns None if file can not be found among source filenames. False if patch can not be applied clearly. True otherwise.
Returns: True, False or None
-
header
= None¶ headers for each file
-
hunkends
= None¶ file endings statistics for every hunk
-
hunks
= None¶ list of lists of hunks
-
patch_stream
(instream, hunks)[source]¶ Generator that yields stream patched with hunks iterable
Converts lineends in hunk lines to the best suitable format autodetected from input
-
source
= None¶ list of source filenames
-
type
= None¶ patch type - one of constants
-
sh
Module¶
testExtension
Module¶
external Package¶
external
Package¶
codewise
Module¶
CodeWise - global code intelligence database
Why this module¶
- Exuberant ctags is an excellent code scanner
- Unfortunately, TAGS file lookup sucks for “find methods of this class”
- TAGS files can be all around the hard drive. CodeWise database is just one file (by default ~/.codewise.db)
- I wanted to implement modern code completion for Leo editor
- codewise.py is usable as a python module, or a command line tool.
Creating ctags data¶
Make sure you have exuberant ctags (not just regular ctags) installed. It’s an Ubuntu package, so its easy to install if you’re using Ubuntu.
- [Optional] Create a custom ~/.ctags file containing default
configuration settings for ctags. See: http://ctags.sourceforge.net/ctags.html#FILES for more details.
The
codewise setup
command (see below), will leave this file alone if it exists; otherwise,codewise setup
will create a ~/.ctags file containing:--exclude=*.html --exclude=*.css
Create the ctags data in ~/.codewise.db using this module. Execute the following from a console window:
codewise setup # Optional: creates ~/.ctags if it does not exist. # See http://ctags.sourceforge.net/ctags.html#FILES codewise init # Optional: deletes ~/.codewise.db if it exists. codewise parse <path to directory> # Adds ctags data to ~/.codewise.db for <directory>
Note: On Windows, use a batch file, say codewise.bat, to execute the above code. codewise.bat contains:
python <path to leo>\leo\external\codewise.py %*
Using the autocompleter¶
After restarting Leo, type, for example, in the body pane:
c.op<ctrl-space>
that is, use use the autocomplete-force command, to find all the c. methods starting with ‘op’ etc.
Theory of operation¶
- ~/.codewise.db is an sqlite database with following tables:
CLASS maps class id’s to names.
FILE maps file id’s to file names
DATASOURCE contains places where data has been parsed from, to enable reparse
- FUNCTION, the most important one, contains functions/methods, along with CLASS
- and FILE it was found in. Additionally, it has SEARCHPATTERN field that can be used to give calltips, or used as a regexp to find the method from file quickly.
You can browse the data by installing sqlitebrovser and doing ‘sqlitebrowser ~/codewise.db’
If you know the class name you want to find the methods for, CodeWise.get_members with a list of classes to match.
If you want to match a function without a class, call CodeWise.get_functions. This can be much slower if you have a huge database.
-
class
leo.external.codewise.
CodeWise
(dbpath=None)[source]¶ Bases:
object
-
feed_function
(func_name, class_name, file_name, aux)[source]¶ insert one function
‘aux’ can be a search pattern (as with ctags), signature, or description
-
-
class
leo.external.codewise.
ContextSniffer
[source]¶ Bases:
object
Class to analyze surrounding context and guess class
For simple dynamic code completion engines
-
leo.external.codewise.
callers
(n=4, count=0, excludeCaller=True, files=False)[source]¶ Return a list containing the callers of the function that called callerList.
If the excludeCaller keyword is True (the default), callers is not on the list.
If the files keyword argument is True, filenames are included in the list.
-
leo.external.codewise.
doKeywordArgs
(keys, d=None)[source]¶ Return a result dict that is a copy of the keys dict with missing items replaced by defaults in d dict.
-
leo.external.codewise.
pr
(*args, **keys)[source]¶ Print all non-keyword args, and put them to the log pane. The first, third, fifth, etc. arg translated by translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.external.codewise.
toEncodedString
(s, encoding='utf-8', reportErrors=False)[source]¶ Convert unicode string to an encoded string.
-
leo.external.codewise.
toUnicode
(s, encoding='utf-8', reportErrors=False)[source]¶ Connvert a non-unicode string with the given encoding to unicode.
edb
Module¶
edb: The Python Debugger Pdb, modified for blender by EKR¶
To use the debugger in its simplest form:
>>> import pdb
>>> pdb.run('<a statement>')
The debugger’s prompt is ‘(Pdb) ‘. This will stop in the first function call in <a statement>.
Alternatively, if a statement terminated with an unhandled exception, you can use pdb’s post-mortem facility to inspect the contents of the traceback:
>>> <a statement>
<exception traceback>
>>> import pdb
>>> pdb.pm()
The commands recognized by the debugger are listed in the next section. Most can be abbreviated as indicated; e.g., h(elp) means that ‘help’ can be typed as ‘h’ or ‘help’ (but not as ‘he’ or ‘hel’, nor as ‘H’ or ‘Help’ or ‘HELP’). Optional arguments are enclosed in square brackets. Alternatives in the command syntax are separated by a vertical bar (|).
A blank line repeats the previous command literally, except for ‘list’, where it lists the next 11 lines.
Commands that the debugger doesn’t recognize are assumed to be Python statements and are executed in the context of the program being debugged. Python statements can also be prefixed with an exclamation point (‘!’). This is a powerful way to inspect the program being debugged; it is even possible to change variables or call functions. When an exception occurs in such a statement, the exception name is printed but the debugger’s state is not changed.
The debugger supports aliases, which can save typing. And aliases can have parameters (see the alias help entry) which allows one a certain level of adaptability to the context under examination.
Multiple commands may be entered on a single line, separated by the pair ‘;;’. No intelligence is applied to separating the commands; the input is split at the first ‘;;’, even if it is in the middle of a quoted string.
If a file “.pdbrc” exists in your home directory or in the current directory, it is read in and executed as if it had been typed at the debugger prompt. This is particularly useful for aliases. If both files exist, the one in the home directory is read first and aliases defined there can be overriden by the local file.
Aside from aliases, the debugger is not directly programmable; but it is implemented as a class from which you can derive your own debugger class, which you can make as fancy as you like.
Debugger commands¶
- h(elp)
- Without argument, print the list of available commands. With a command name as argument, print help about that command. “help pdb” shows the full pdb documentation. “help exec” gives help on the ! command.
- w(here)
- Print a stack trace, with the most recent frame at the bottom. An arrow indicates the “current frame”, which determines the context of most commands. ‘bt’ is an alias for this command.
- d(own) [count]
- Move the current frame count (default one) levels down in the stack trace (to a newer frame).
- u(p) [count]
- Move the current frame count (default one) levels up in the stack trace (to an older frame).
- b(reak) [ ([filename:]lineno | function) [, condition] ]
Without argument, list all breaks.
With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored.
The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn’t been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted.
- tbreak [ ([filename:]lineno | function) [, condition] ]
- Same arguments as break, but sets a temporary breakpoint: it is automatically deleted when first hit.
cl(ear) filename:lineno cl(ear) [bpnumber [bpnumber…]]
With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, clear all breaks at that line in that file.
- disable bpnumber [bpnumber …]
- Disables the breakpoints given as a space separated list of breakpoint numbers. Disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing a breakpoint, it remains in the list of breakpoints and can be (re-)enabled.
- enable bpnumber [bpnumber …]
- Enables the breakpoints given as a space separated list of breakpoint numbers.
- ignore bpnumber [count]
- Set the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true.
- condition bpnumber [condition]
- Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional.
- commands [bpnumber]
(com) … (com) end (Pdb)
Specify a list of commands for breakpoint number bpnumber. The commands themselves are entered on the following lines. Type a line containing just ‘end’ to terminate the commands. The commands are executed when the breakpoint is hit.
To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands.
With no bpnumber argument, commands refers to the last breakpoint set.
You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution.
Specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command list (as if that command was immediately followed by end). This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint – which could have its own command list, leading to ambiguities about which list to execute.
If you use the ‘silent’ command in the command list, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you will see no sign that the breakpoint was reached.
- s(tep)
- Execute the current line, stop at the first possible occasion (either in a function that is called or in the current function).
- n(ext)
- Continue execution until the next line in the current function is reached or it returns.
- unt(il) [lineno]
- Without argument, continue execution until the line with a number greater than the current one is reached. With a line number, continue execution until a line with a number greater or equal to that is reached. In both cases, also stop when the current frame returns.
- j(ump) lineno
Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don’t want to run.
It should be noted that not all jumps are allowed – for instance it is not possible to jump into the middle of a for loop or out of a finally clause.
- r(eturn)
- Continue execution until the current function returns.
- retval
- Print the return value for the last return of a function.
- run [args…]
- Restart the debugged python program. If a string is supplied it is splitted with “shlex”, and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. “restart” is an alias for “run”.
- c(ont(inue))
- Continue execution, only stop when a breakpoint is encountered.
l(ist) [first [,last] | .]
List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With . as argument, list 11 lines around the current line. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count.
The current line in the current frame is indicated by “->”. If an exception is being debugged, the line where the exception was originally raised or propagated is indicated by “>>”, if it differs from the current line.
- longlist | ll
- List the whole source code for the current function or frame.
- a(rgs)
- Print the argument list of the current function.
- p(rint) expression
- Print the value of the expression.
- pp expression
- Pretty-print the value of the expression.
- whatis arg
- Print the type of the argument.
- source expression
- Try to get source code for the given object and display it.
display [expression]
Display the value of the expression if it changed, each time execution stops in the current frame.
Without expression, list all display expressions for the current frame.
undisplay [expression]
Do not display the expression any more in the current frame.
Without expression, clear all display expressions for the current frame.
interact
Start an interative interpreter whose global namespace contains all the (global and local) names found in the current scope.
- alias [name [command [parameter parameter …] ]]
Create an alias called ‘name’ that executes ‘command’. The command must not be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the current alias for name is shown. If no name is given, all aliases are listed.
Aliases may be nested and can contain anything that can be legally typed at the pdb prompt. Note! You can override internal pdb commands with aliases! Those internal commands are then hidden until the alias is removed. Aliasing is recursively applied to the first word of the command line; all other words in the line are left alone.
As an example, here are two useful aliases (especially when placed in the .pdbrc file):
# Print instance variables (usage “pi classInst”) alias pi for k in %1.__dict__.keys(): print “%1.”,k,”=”,%1.__dict__[k] # Print instance variables in self alias ps pi self
- unalias name
- Delete the specified alias.
- debug code
- Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment).
q(uit) exit
Quit from the debugger. The program being executed is aborted.
- (!) statement
- Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word of the statement resembles a debugger command. To assign to a global variable you must always prefix the command with a ‘global’ command, e.g.: (Pdb) global list_options; list_options = [‘-l’] (Pdb)
-
class
leo.external.edb.
Pdb
(completekey='tab', stdin=None, stdout=None, skip=None, nosigint=False)[source]¶ Bases:
bdb.Bdb
,cmd.Cmd
-
bp_commands
(frame)[source]¶ Call every command that was set for the current active breakpoint (if there is one).
Returns True if the normal interaction function must be called, False otherwise.
-
checkline
(filename, lineno)[source]¶ Check whether specified line seems to be executable.
Return lineno if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive.
-
commands_resuming
= ['do_continue', 'do_step', 'do_next', 'do_return', 'do_quit', 'do_jump']¶
-
displayhook
(obj)[source]¶ Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins.
-
do_a
(arg)¶ a(rgs) Print the argument list of the current function.
-
do_alias
(arg)[source]¶ alias [name [command [parameter parameter …] ]] Create an alias called ‘name’ that executes ‘command’. The command must not be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the current alias for name is shown. If no name is given, all aliases are listed.
Aliases may be nested and can contain anything that can be legally typed at the pdb prompt. Note! You can override internal pdb commands with aliases! Those internal commands are then hidden until the alias is removed. Aliasing is recursively applied to the first word of the command line; all other words in the line are left alone.
As an example, here are two useful aliases (especially when placed in the .pdbrc file):
# Print instance variables (usage “pi classInst”) alias pi for k in %1.__dict__.keys(): print “%1.”,k,”=”,%1.__dict__[k] # Print instance variables in self alias ps pi self
-
do_b
(arg, temporary=0)¶ b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks.
With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored.
The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn’t been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted.
-
do_break
(arg, temporary=0)[source]¶ b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks.
With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored.
The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn’t been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted.
-
do_bt
(arg)¶ w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the “current frame”, which determines the context of most commands. ‘bt’ is an alias for this command.
-
do_c
(arg)¶ c(ont(inue)) Continue execution, only stop when a breakpoint is encountered.
-
do_cl
(arg)¶ cl(ear) filename:lineno cl(ear) [bpnumber [bpnumber…]]
With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, clear all breaks at that line in that file.
-
do_clear
(arg)[source]¶ cl(ear) filename:lineno cl(ear) [bpnumber [bpnumber…]]
With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, clear all breaks at that line in that file.
-
do_commands
(arg)[source]¶ commands [bpnumber] (com) … (com) end (Pdb)
Specify a list of commands for breakpoint number bpnumber. The commands themselves are entered on the following lines. Type a line containing just ‘end’ to terminate the commands. The commands are executed when the breakpoint is hit.
To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands.
With no bpnumber argument, commands refers to the last breakpoint set.
You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution.
Specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command list (as if that command was immediately followed by end). This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint – which could have its own command list, leading to ambiguities about which list to execute.
If you use the ‘silent’ command in the command list, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you will see no sign that the breakpoint was reached.
-
do_condition
(arg)[source]¶ condition bpnumber [condition] Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional.
-
do_cont
(arg)¶ c(ont(inue)) Continue execution, only stop when a breakpoint is encountered.
-
do_continue
(arg)[source]¶ c(ont(inue)) Continue execution, only stop when a breakpoint is encountered.
-
do_d
(arg)¶ d(own) [count] Move the current frame count (default one) levels down in the stack trace (to a newer frame).
-
do_debug
(arg)[source]¶ debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment).
-
do_disable
(arg)[source]¶ disable bpnumber [bpnumber …] Disables the breakpoints given as a space separated list of breakpoint numbers. Disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing a breakpoint, it remains in the list of breakpoints and can be (re-)enabled.
-
do_display
(arg)[source]¶ display [expression]
Display the value of the expression if it changed, each time execution stops in the current frame.
Without expression, list all display expressions for the current frame.
-
do_down
(arg)[source]¶ d(own) [count] Move the current frame count (default one) levels down in the stack trace (to a newer frame).
-
do_enable
(arg)[source]¶ enable bpnumber [bpnumber …] Enables the breakpoints given as a space separated list of breakpoint numbers.
-
do_exit
(arg)¶ q(uit) exit
Quit from the debugger. The program being executed is aborted.
-
do_h
(arg)¶ h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command. “help pdb” shows the full pdb documentation. “help exec” gives help on the ! command.
-
do_help
(arg)[source]¶ h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command. “help pdb” shows the full pdb documentation. “help exec” gives help on the ! command.
-
do_ignore
(arg)[source]¶ ignore bpnumber [count] Set the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true.
-
do_interact
(arg)[source]¶ interact
Start an interative interpreter whose global namespace contains all the (global and local) names found in the current scope.
-
do_j
(arg)¶ j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don’t want to run.
It should be noted that not all jumps are allowed – for instance it is not possible to jump into the middle of a for loop or out of a finally clause.
-
do_jump
(arg)[source]¶ j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don’t want to run.
It should be noted that not all jumps are allowed – for instance it is not possible to jump into the middle of a for loop or out of a finally clause.
-
do_l
(arg)¶ l(ist) [first [,last] | .]
List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With . as argument, list 11 lines around the current line. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count.
The current line in the current frame is indicated by “->”. If an exception is being debugged, the line where the exception was originally raised or propagated is indicated by “>>”, if it differs from the current line.
-
do_list
(arg)[source]¶ l(ist) [first [,last] | .]
List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With . as argument, list 11 lines around the current line. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count.
The current line in the current frame is indicated by “->”. If an exception is being debugged, the line where the exception was originally raised or propagated is indicated by “>>”, if it differs from the current line.
-
do_ll
(arg)¶ longlist | ll List the whole source code for the current function or frame.
-
do_longlist
(arg)[source]¶ longlist | ll List the whole source code for the current function or frame.
-
do_n
(arg)¶ n(ext) Continue execution until the next line in the current function is reached or it returns.
-
do_next
(arg)[source]¶ n(ext) Continue execution until the next line in the current function is reached or it returns.
-
do_print
(arg)¶ p(rint) expression Print the value of the expression.
-
do_q
(arg)¶ q(uit) exit
Quit from the debugger. The program being executed is aborted.
-
do_r
(arg)¶ r(eturn) Continue execution until the current function returns.
-
do_restart
(arg)¶ run [args…] Restart the debugged python program. If a string is supplied it is splitted with “shlex”, and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. “restart” is an alias for “run”.
-
do_run
(arg)[source]¶ run [args…] Restart the debugged python program. If a string is supplied it is splitted with “shlex”, and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. “restart” is an alias for “run”.
-
do_rv
(arg)¶ retval Print the return value for the last return of a function.
-
do_s
(arg)¶ s(tep) Execute the current line, stop at the first possible occasion (either in a function that is called or in the current function).
-
do_source
(arg)[source]¶ source expression Try to get source code for the given object and display it.
-
do_step
(arg)[source]¶ s(tep) Execute the current line, stop at the first possible occasion (either in a function that is called or in the current function).
-
do_tbreak
(arg)[source]¶ tbreak [ ([filename:]lineno | function) [, condition] ] Same arguments as break, but sets a temporary breakpoint: it is automatically deleted when first hit.
-
do_u
(arg)¶ u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame).
-
do_undisplay
(arg)[source]¶ undisplay [expression]
Do not display the expression any more in the current frame.
Without expression, clear all display expressions for the current frame.
-
do_unt
(arg)¶ unt(il) [lineno] Without argument, continue execution until the line with a number greater than the current one is reached. With a line number, continue execution until a line with a number greater or equal to that is reached. In both cases, also stop when the current frame returns.
-
do_until
(arg)[source]¶ unt(il) [lineno] Without argument, continue execution until the line with a number greater than the current one is reached. With a line number, continue execution until a line with a number greater or equal to that is reached. In both cases, also stop when the current frame returns.
-
do_up
(arg)[source]¶ u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame).
-
do_w
(arg)¶ w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the “current frame”, which determines the context of most commands. ‘bt’ is an alias for this command.
-
do_where
(arg)[source]¶ w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the “current frame”, which determines the context of most commands. ‘bt’ is an alias for this command.
-
help_exec
()[source]¶ (!) statement Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word of the statement resembles a debugger command. To assign to a global variable you must always prefix the command with a ‘global’ command, e.g.: (Pdb) global list_options; list_options = [‘-l’] (Pdb)
-
lookupmodule
(filename)[source]¶ Helper function for break/clear parsing – may be overridden.
lookupmodule() translates (possibly incomplete) file or module name into an absolute file name.
-
onecmd
(line)[source]¶ Interpret the argument as though it had been typed in response to the prompt.
Checks whether this line is typed at the normal prompt or in a breakpoint command list definition.
-
user_call
(frame, argument_list)[source]¶ This method is called when there is the remote possibility that we ever need to stop in this function.
-
ipy_leo
Module¶
leoSAGlobals
Module¶
leoSAGlobals.py: the stand-alone version of leo.core.leoGlobals.py
-
class
leo.external.leoSAGlobals.
Bunch
(**keywords)[source]¶ Bases:
object
A class that represents a colection of things.
Especially useful for representing a collection of related variables.
-
leo.external.leoSAGlobals.
CheckVersion
(s1, s2, condition='>=', stringCompare=None, delimiter='.', trace=False)[source]¶
-
leo.external.leoSAGlobals.
adjustTripleString
(s, tab_width)[source]¶ Remove leading indentation from a triple-quoted string.
This works around the fact that Leo nodes can’t represent underindented strings.
-
leo.external.leoSAGlobals.
bunch
¶ alias of
leo.external.leoSAGlobals.Bunch
-
leo.external.leoSAGlobals.
callers
(n=4, count=0, excludeCaller=True, files=False)[source]¶ Return a list containing the callers of the function that called callerList.
If the excludeCaller keyword is True (the default), callers is not on the list.
If the files keyword argument is True, filenames are included in the list.
-
leo.external.leoSAGlobals.
convertPythonIndexToRowCol
(s, i)[source]¶ Convert index i into string s into zero-based row/col indices.
-
leo.external.leoSAGlobals.
convertRowColToPythonIndex
(s, row, col, lines=None)[source]¶ Convert zero-based row/col indices into a python index into string s.
-
leo.external.leoSAGlobals.
doKeywordArgs
(keys, d=None)[source]¶ Return a result dict that is a copy of the keys dict with missing items replaced by defaults in d dict.
-
leo.external.leoSAGlobals.
es
(*args, **keys)¶ Print all non-keyword args, and put them to the log pane. The first, third, fifth, etc. arg translated by translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.external.leoSAGlobals.
es_error
(*args, **keys)¶ Print all non-keyword args, and put them to the log pane. The first, third, fifth, etc. arg translated by translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.external.leoSAGlobals.
es_print
(*args, **keys)¶ Print all non-keyword args, and put them to the log pane. The first, third, fifth, etc. arg translated by translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.external.leoSAGlobals.
es_print_error
(*args, **keys)¶ Print all non-keyword args, and put them to the log pane. The first, third, fifth, etc. arg translated by translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
class
leo.external.leoSAGlobals.
fileLikeObject
(encoding='utf-8', fromString=None)[source]¶ Define a file-like object for redirecting writes to a string.
The caller is responsible for handling newlines correctly.
-
getvalue
()¶
-
read
()¶
-
-
leo.external.leoSAGlobals.
getDocString
(s)[source]¶ Return the text of the first docstring found in s.
-
leo.external.leoSAGlobals.
getDocStringForFunction
(func)[source]¶ Return the docstring for a function that creates a Leo command.
-
leo.external.leoSAGlobals.
getLine
(s, i)[source]¶ Return i,j such that s[i:j] is the line surrounding s[i]. s[i] is a newline only if the line is empty. s[j] is a newline unless there is no trailing newline.
-
leo.external.leoSAGlobals.
getLineAfter
(s, i)¶
-
leo.external.leoSAGlobals.
getPythonEncodingFromString
(s)[source]¶ Return the encoding given by Python’s encoding line. s is the entire file.
-
leo.external.leoSAGlobals.
getWord
(s, i)[source]¶ Return i,j such that s[i:j] is the word surrounding s[i].
-
leo.external.leoSAGlobals.
is_special
(s, i, directive)[source]¶ Return True if the body text contains the @ directive.
-
leo.external.leoSAGlobals.
joinlines
(aList)¶
-
leo.external.leoSAGlobals.
listToString
(aList, tag=None, sort=False, indent='', toRepr=False)[source]¶
-
leo.external.leoSAGlobals.
makeDict
(**keys)[source]¶ Returns a Python dictionary from using the optional keyword arguments.
-
leo.external.leoSAGlobals.
maxStringListLength
(aList)[source]¶ Return the maximum string length in a list of strings.
-
class
leo.external.leoSAGlobals.
nullObject
(*args, **keys)[source]¶ An object that does nothing, and does it very well.
-
leo.external.leoSAGlobals.
oldCheckVersion
(version, againstVersion, condition='>=', stringCompare='0.0.0.0', delimiter='.')[source]¶
-
leo.external.leoSAGlobals.
os_path_basename
(path)[source]¶ Return the second half of the pair returned by split(path).
-
leo.external.leoSAGlobals.
os_path_dirname
(path)[source]¶ Return the first half of the pair returned by split(path).
-
leo.external.leoSAGlobals.
os_path_expandExpression
(s, **keys)[source]¶ Expand {{anExpression}} in c’s context.
-
leo.external.leoSAGlobals.
os_path_finalize
(path, **keys)[source]¶ Expand ‘~’, then return os.path.normpath, os.path.abspath of the path.
There is no corresponding os.path method
-
leo.external.leoSAGlobals.
os_path_finalize_join
(*args, **keys)[source]¶ Do os.path.join(*args), then finalize the result.
-
leo.external.leoSAGlobals.
pr
(*args, **keys)[source]¶ Print all non-keyword args, and put them to the log pane. The first, third, fifth, etc. arg translated by translateString. Supports color, comma, newline, spaces and tabName keyword arguments.
-
leo.external.leoSAGlobals.
printDict
(d, tag='', verbose=True, indent='')¶
-
leo.external.leoSAGlobals.
printList
(aList, tag=None, sort=False, indent='')¶
-
leo.external.leoSAGlobals.
printStack
()¶
-
leo.external.leoSAGlobals.
removeExtraLws
(s, tab_width)[source]¶ Remove extra indentation from one or more lines.
Warning: used by getScript. This is not the same as adjustTripleString.
-
leo.external.leoSAGlobals.
removeLeading
(s, chars)[source]¶ Remove all characters in chars from the front of s.
-
leo.external.leoSAGlobals.
removeTrailing
(s, chars)[source]¶ Remove all characters in chars from the end of s.
-
leo.external.leoSAGlobals.
shortFilename
(fileName)¶
-
leo.external.leoSAGlobals.
skip_leading_ws_with_indent
(s, i, tab_width)[source]¶ Skips leading whitespace and returns (i, indent),
- i points after the whitespace
- indent is the width of the whitespace, assuming tab_width wide tabs.
-
leo.external.leoSAGlobals.
skip_long
(s, i)[source]¶ Scan s[i:] for a valid int. Return (i, val) or (i, None) if s[i] does not point at a number.
-
leo.external.leoSAGlobals.
skip_matching_c_delims
(s, i, delim1, delim2, reverse=False)[source]¶ Skip from the opening delim to the matching delim2.
Return the index of the matching ‘)’, or -1
-
leo.external.leoSAGlobals.
skip_matching_python_delims
(s, i, delim1, delim2, reverse=False)[source]¶ Skip from the opening delim to the matching delim2.
Return the index of the matching ‘)’, or -1
-
leo.external.leoSAGlobals.
skip_matching_python_parens
(s, i)[source]¶ Skip from the opening ( to the matching ).
Return the index of the matching ‘)’, or -1
-
leo.external.leoSAGlobals.
splitLines
(s)[source]¶ Split s into lines, preserving the number of lines and the endings of all lines, including the last line.
-
leo.external.leoSAGlobals.
splitlines
(s)¶ Split s into lines, preserving the number of lines and the endings of all lines, including the last line.
-
leo.external.leoSAGlobals.
stripBrackets
(s)[source]¶ Same as s.lstrip(‘<’).rstrip(‘>’) except it works for Python 2.2.1.
-
leo.external.leoSAGlobals.
toGuiIndex
(s, index)¶ Convert index to a Python int.
index may be a Tk index (x.y) or ‘end’.
-
leo.external.leoSAGlobals.
toPythonIndex
(s, index)[source]¶ Convert index to a Python int.
index may be a Tk index (x.y) or ‘end’.
-
leo.external.leoSAGlobals.
tr
(s)¶ Return the translated text of s.
-
leo.external.leoSAGlobals.
translateArgs
(args, d)[source]¶ Return the concatenation of s and all args,
with odd args translated.
-
leo.external.leoSAGlobals.
virtual_event_name
(s)¶
leoftsindex
Module¶
leosax
Module¶
Read .leo files into a simple python data structure with h, b, u (unknown attribs), gnx and children information. Clones and derived files are ignored. Useful for scanning multiple .leo files quickly.
-
class
leo.external.leosax.
LeoNode
[source]¶ Bases:
object
Representation of a Leo node. Root node has itself as parent.
IVariables: - children
python list of children
- u
unknownAttributes dict (decoded)
- h
headline
- b
body text
- gnx
node id
- parent
node’s parent
- path
list of nodes that lead to this one from root, including this one
-
class
leo.external.leosax.
LeoReader
(*args, **kwargs)[source]¶ Bases:
xml.sax.handler.ContentHandler
Read .leo files into a simple python data structure with h, b, u (unknown attribs), gnx and children information. Clones and derived files are ignored. Useful for scanning multiple .leo files quickly.
IVariables: - root
root node
- cur
used internally during SAX read
- idx
mapping from gnx to node
- in_
name of XML element we’re current in, used for SAX read
- in_attr
attributes of element tag we’re currentl in, used for SAX read
- path
list of nodes leading to current node
lproto
Module¶
stringlist
Module¶
-
class
leo.external.stringlist.
SList
[source]¶ Bases:
list
List derivative with a special access attributes.
These are normal string lists, but with the special attributes:
.l: value as list (the list itself). .n: value as a string, joined on newlines. .s: value as a string, joined on spaces.-
fields
(*fields)[source]¶ Collect whitespace-separated fields from string list
Allows quick awk-like usage of string lists.
- Example data (in var a, created by ‘a = !ls -l’)::
-rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
a.fields(0) is [‘-rwxrwxrwx’, ‘drwxrwxrwx+’] a.fields(1,0) is [‘1 -rwxrwxrwx’, ‘6 drwxrwxrwx+’] (note the joining by space). a.fields(-1) is [‘ChangeLog’, ‘IPython’]
IndexErrors are ignored.
Without args, fields() just split()’s the strings.
-
grep
(pattern, prune=False, field=None)[source]¶ Return all strings matching ‘pattern’ (a regex or callable)
This is case-insensitive. If prune is true, return all items NOT matching the pattern.
If field is specified, the match must occur in the specified whitespace-separated field.
Examples:
a.grep( lambda x: x.startswith('C') ) a.grep('Cha.*log', prune=1) a.grep('chm', field=-1)
-
l
¶
-
n
¶
-
s
¶
-
Subpackages¶
concurrent Package¶
concurrent
Package¶futures
Package¶Execute computations asynchronously using threads or processes.
_base
Module¶-
exception
leo.external.concurrent.futures._base.
CancelledError
[source]¶ Bases:
leo.external.concurrent.futures._base.Error
The Future was cancelled.
-
class
leo.external.concurrent.futures._base.
DoneAndNotDoneFutures
(done, not_done)¶ Bases:
tuple
-
done
¶ Alias for field number 0
-
not_done
¶ Alias for field number 1
-
-
exception
leo.external.concurrent.futures._base.
Error
[source]¶ Bases:
exceptions.Exception
Base class for all future-related exceptions.
-
class
leo.external.concurrent.futures._base.
Executor
[source]¶ Bases:
object
This is an abstract base class for concrete asynchronous executors.
-
map
(fn, *iterables, **kwargs)[source]¶ Returns a iterator equivalent to map(fn, iter).
- Args:
- fn: A callable that will take take as many arguments as there are
- passed iterables.
- timeout: The maximum number of seconds to wait. If None, then there
- is no limit on the wait time.
- Returns:
- An iterator equivalent to: map(func, *iterables) but the calls may be evaluated out-of-order.
- Raises:
- TimeoutError: If the entire result iterator could not be generated
- before the given timeout.
Exception: If fn(*args) raises for any values.
-
shutdown
(wait=True)[source]¶ Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other methods can be called after this one.
- Args:
- wait: If True then shutdown will not return until all running
- futures have finished executing and the resources used by the executor have been reclaimed.
-
-
class
leo.external.concurrent.futures._base.
Future
[source]¶ Bases:
object
Represents the result of an asynchronous computation.
-
add_done_callback
(fn)[source]¶ Attaches a callable that will be called when the future finishes.
- Args:
- fn: A callable that will be called with this future as its only
- argument when the future completes or is cancelled. The callable will always be called by a thread in the same process in which it was added. If the future has already completed or been cancelled then the callable will be called immediately. These callables are called in the order that they were added.
-
cancel
()[source]¶ Cancel the future if possible.
Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed.
-
exception
(timeout=None)[source]¶ Return the exception raised by the call that the future represents.
- Args:
- timeout: The number of seconds to wait for the exception if the
- future isn’t done. If None, then there is no limit on the wait time.
- Returns:
- The exception raised by the call that the future represents or None if the call completed without raising.
- Raises:
CancelledError: If the future was cancelled. TimeoutError: If the future didn’t finish executing before the given
timeout.
-
result
(timeout=None)[source]¶ Return the result of the call that the future represents.
- Args:
- timeout: The number of seconds to wait for the result if the future
- isn’t done. If None, then there is no limit on the wait time.
- Returns:
- The result of the call that the future represents.
- Raises:
CancelledError: If the future was cancelled. TimeoutError: If the future didn’t finish executing before the given
timeout.Exception: If the call raised then that exception will be raised.
-
set_exception
(exception)[source]¶ Sets the result of the future as being the given exception.
Should only be used by Executor implementations and unit tests.
-
set_result
(result)[source]¶ Sets the return value of work associated with the future.
Should only be used by Executor implementations and unit tests.
-
set_running_or_notify_cancel
()[source]¶ Mark the future as running or process any cancel notifications.
Should only be used by Executor implementations and unit tests.
If the future has been cancelled (cancel() was called and returned True) then any threads waiting on the future completing (though calls to as_completed() or wait()) are notified and False is returned.
If the future was not cancelled then it is put in the running state (future calls to running() will return True) and True is returned.
This method should be called by Executor implementations before executing the work associated with this future. If this method returns False then the work should not be executed.
- Returns:
- False if the Future was cancelled, True otherwise.
- Raises:
- RuntimeError: if this method was already called or if set_result()
- or set_exception() was called.
-
-
exception
leo.external.concurrent.futures._base.
TimeoutError
[source]¶ Bases:
leo.external.concurrent.futures._base.Error
The operation exceeded the given deadline.
-
leo.external.concurrent.futures._base.
as_completed
(fs, timeout=None)[source]¶ An iterator over the given futures that yields each as it completes.
- Args:
- fs: The sequence of Futures (possibly created by different Executors) to
- iterate over.
- timeout: The maximum number of seconds to wait. If None, then there
- is no limit on the wait time.
- Returns:
- An iterator that yields the given Futures as they complete (finished or cancelled).
- Raises:
- TimeoutError: If the entire result iterator could not be generated
- before the given timeout.
-
leo.external.concurrent.futures._base.
wait
(fs, timeout=None, return_when='ALL_COMPLETED')[source]¶ Wait for the futures in the given sequence to complete.
- Args:
- fs: The sequence of Futures (possibly created by different Executors) to
- wait upon.
- timeout: The maximum number of seconds to wait. If None, then there
- is no limit on the wait time.
- return_when: Indicates when this function should return. The options
are:
- FIRST_COMPLETED - Return when any future finishes or is
- cancelled.
- FIRST_EXCEPTION - Return when any future finishes by raising an
- exception. If no future raises an exception then it is equivalent to ALL_COMPLETED.
ALL_COMPLETED - Return when all futures finish or are cancelled.
- Returns:
- A named 2-tuple of sets. The first set, named ‘done’, contains the futures that completed (is finished or cancelled) before the wait completed. The second set, named ‘not_done’, contains uncompleted futures.
_compat
Module¶-
leo.external.concurrent.futures._compat.
namedtuple
(typename, field_names)[source]¶ Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessable by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22)
process
Module¶Implements ProcessPoolExecutor.
The follow diagram and text describe the data-flow through the system:
|======================= In-process =====================|== Out-of-process ==|
+———-+ +———-+ +——–+ +———–+ +———+ | | => | Work Ids | => | | => | Call Q | => | | | | +———-+ | | +———–+ | | | | | … | | | | … | | | | | | 6 | | | | 5, call() | | | | | | 7 | | | | … | | | | Process | | … | | Local | +———–+ | Process | | Pool | +———-+ | Worker | | #1..n | | Executor | | Thread | | | | | +———– + | | +———–+ | | | | <=> | Work Items | <=> | | <= | Result Q | <= | | | | +————+ | | +———–+ | | | | | 6: call() | | | | … | | | | | | future | | | | 4, result | | | | | | … | | | | 3, except | | | +———-+ +————+ +——–+ +———–+ +———+
Executor.submit() called: - creates a uniquely numbered _WorkItem and adds it to the “Work Items” dict - adds the id of the _WorkItem to the “Work Ids” queue
Local worker thread: - reads work ids from the “Work Ids” queue and looks up the corresponding
WorkItem from the “Work Items” dict: if the work item has been cancelled then it is simply removed from the dict, otherwise it is repackaged as a _CallItem and put in the “Call Q”. New _CallItems are put in the “Call Q” until “Call Q” is full. NOTE: the size of the “Call Q” is kept small because calls placed in the “Call Q” can no longer be cancelled with Future.cancel().
- reads _ResultItems from “Result Q”, updates the future stored in the “Work Items” dict and deletes the dict entry
Process #1..n: - reads _CallItems from “Call Q”, executes the calls, and puts the resulting
_ResultItems in “Request Q”
-
class
leo.external.concurrent.futures.process.
ProcessPoolExecutor
(max_workers=None)[source]¶ Bases:
concurrent.futures._base.Executor
-
shutdown
(wait=True)[source]¶ Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other methods can be called after this one.
- Args:
- wait: If True then shutdown will not return until all running
- futures have finished executing and the resources used by the executor have been reclaimed.
-
thread
Module¶Implements ThreadPoolExecutor.
-
class
leo.external.concurrent.futures.thread.
ThreadPoolExecutor
(max_workers)[source]¶ Bases:
concurrent.futures._base.Executor
-
shutdown
(wait=True)[source]¶ Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other methods can be called after this one.
- Args:
- wait: If True then shutdown will not return until all running
- futures have finished executing and the resources used by the executor have been reclaimed.
-
plugins Package¶
plugins
Package¶
FileActions
Module¶
Defines actions taken when double-clicking on @<file> nodes and supports @file-ref nodes.
The double-click-icon-box command on any kind of @<file> node writes out the file if changes have been made since the last save, and then runs a script on it, which is retrieved from the outline.
Scripts are located in a node whose headline is FileActions. This node can be anywhere in the outline. If there is more than one such node, the first one in outline order is used.
The children of that node are expected to contain a file pattern in the headline and the script to be executed in the body. The file name is matched against the patterns (which are Unix-style shell patterns), and the first matching node is selected. If the filename is a path, only the last item is matched.
Execution of the scripts is similar to the “Execute Script” command in Leo. The main difference is that the namespace in which the scripts are run contains these elements:
- ‘c’ and ‘g’ and ‘p’: as in the regular execute script command.
- ‘filename’: the filename from the @file directive.
- ‘shellScriptInWindow’, a utility function that runs a shell script in an
- external windows, thus permitting programs to be called that require user interaction
File actions are implemented for all kinds @<file> nodes. There is also a new node type @file-ref for referring to files purely for the purpose of file actions, Leo does not do anything with or to such files.
active_path
Module¶
Synchronizes @path nodes with folders.
If a node is named ‘@path <path_to_folder>’, the content (file and folder names) of the folder and the children of that node will synchronized whenever you double-click the node.
For files not previously seen in a folder a new node will appear on top of the children list (with a mark).
Folders appear in the list as /foldername/. If you double click on the folder node, it will have children added to it based on the contents of the folder on disk. These folders have the ‘@path’ directive as the first line of their body text.
When files are deleted from the folder and the list is updated by double clicking the files will appear in the list as filename (or /foldername/).
You can describe files and directories in the body of the nodes.
You can organize files and directories with organizer nodes, an organizer node name cannot contain with ‘/’.
Files and folders can be created by entering a node with the required name as its headline (must start and/or end with “/” for a folder) and then double clicking on the node.
@auto nodes can be set up for existing files can be loaded by double clicking on the node. If you prefer @shadow or something else use the “active_path_attype” setting, without the “@”.
There are commands on the Plugins active_path submenu:
- show path - show the current path
- set absolute path - changes a node “/dirname/” to “@path /absolute/path/to/dirname”.
- purge vanished (recursive) - remove entries
- update recursive - recursive load of directories, use with caution on large file systems
- pick dir - select a folder interactively to make a new top level @path node
- mark-content - mark outline content in the @path tree, as opposed to filesystem content. Useful if you want to delete the @path tree to check for content not on the filesystem first
If you want to use an input other than double clicking a node set active_path_event to a value like ‘hypercclick1’ or ‘headrclick1’.
There are @settings for ignoring directory entries and automatically loading
files. re.search
is used, rather than re.match
, so patterns need only
match part of the filename, not the whole filename.
The body of the @setting @data active_path_ignore
is a list of regex
patterns, one per line. Directory entries matching any pattern in the list will
be ignored. The names of directories used for matching will have forward slashes
around them (‘/dirname/’), so patterns can use this to distinguish between
directories and files.
The body of the @setting @data active_path_autoload
is a list of regex
patterns, one per line. File entries matching any pattern in the list will be
loaded automatically. This works only with files, not directories (but you can
load directories recursively anyway).
Autoloading can be toggled with active-path-toggle-autoload, autoloading defaults to initially on unless @bool active-path-do-autoload = False.
Set @bool active_path_load_docstring = True
to have active_path load the
docstring of .py files automatically. These nodes start with the special
string:
@language rest # AUTOLOADED DOCSTRING
which must be left intact if you want active path to be able to double-click load the file later.
@float active_path_timeout_seconds (default 10.) controls the maximum time active_path will spend on a recursive operation.
@int active_path_max_size (default 1000000) controls the maximum size file active_path will open without query.
Per Folder file/folder inclusion and exclusion by adding flags to the body of an
active path folder (either @
or /*/
), can include multiple inc=
and
exc=
flags:
excdirs
- excludes all directoriesexcfiles
- excludes all filesinc=
- a single item or comma separated list of strings to include in the list of files/foldersexc=
- a single item or comma separated list of strings to exclude in the list of files/foldersre
- search using regular expressions (otherwise a case-sensitive ‘in’ comparison)
active_path is a rewrite of the at_directory plugin to use @path directives (which influence @auto and other @file type directives), and to handle sub-folders more automatically.
-
leo.plugins.active_path.
active_path_act_on_node
(event, p=None)¶ act_on_node handler for active_path.py
-
leo.plugins.active_path.
checkIncExc
(item, inc, exc, regEx)[source]¶ Primary logic to check if an item is in either the include or exclude list
-
leo.plugins.active_path.
cmd_ActOnNode
(event, p=None)[source]¶ act_on_node handler for active_path.py
-
leo.plugins.active_path.
cmd_MarkContent
(event)[source]¶ cmd_MarkContent - mark nodes in @path sub-tree with non-filesystem content
i.e. not organizer nodes (no body), subdirs (body starts with @path) vanished file placeholders, or @<file> nodes.
-
leo.plugins.active_path.
cmd_PickDir
(event)[source]¶ cmd_PickDir - Show user a folder picker to create
-
leo.plugins.active_path.
cmd_PurgeUnloadedFilesHere
(event)[source]¶ Remove files never loaded, i.e. no kind of @file node.
-
leo.plugins.active_path.
cmd_PurgeUnloadedFilesRecursive
(event)[source]¶ Remove files never loaded, i.e. no kind of @file node.
-
leo.plugins.active_path.
cmd_PurgeVanishedFilesHere
(event)[source]¶ Remove files no longer present, i.e. “filename” entries.
-
leo.plugins.active_path.
cmd_PurgeVanishedFilesRecursive
(event)[source]¶ Remove files no longer present, i.e. “filename” entries.
-
leo.plugins.active_path.
cmd_SetNodeToAbsolutePath
(event, p=None)[source]¶ Change “/dirname/” to “@path /absolute/path/to/dirname”.
-
leo.plugins.active_path.
cmd_SetNodeToAbsolutePathRecursive
(event)[source]¶ Change “/dirname/” to “@path /absolute/path/to/dirname”, recursively
-
leo.plugins.active_path.
cmd_ShowCurrentPath
(event)[source]¶ Just show the path to the current file/directory node in the log pane.
-
leo.plugins.active_path.
cmd_ToggleAutoLoad
(event)[source]¶ cmd_ToggleAutoLoad - toggle autoloading behavior
-
leo.plugins.active_path.
deleteDescendents
(p, cond, dtor=None, descendAnyway=False, _culls=0)[source]¶
-
leo.plugins.active_path.
flattenOrganizers
(p)[source]¶ Children of p, some of which may be in organizer nodes
In the following example nodeA’s children are nodes B, F, and G:
/nodeA/ nodeB /nodeC/ nodeD nodeE oldStuff nodeF nodeG
-
leo.plugins.active_path.
inAny
(item, group, regEx=False)[source]¶ Helper function to check if word from list is in a string
-
leo.plugins.active_path.
onSelect
(tag, keywords)[source]¶ Determine if a file or directory node was clicked, and the path
-
leo.plugins.active_path.
openDir
(c, parent, d)[source]¶ Expand / refresh an existing folder
Note: With the addition of per folder inclusion/exclusion a check is done against both the current list of nodes and against the files/folders as they exist on the system. This check must be done in both places to keep the node list in sync with the file system while respecting the inc/exc lists - John Lunzer
add_directives
Module¶
Allows users to define new @direcives.
at_folder
Module¶
Synchronizes @folder nodes with folders.
If a node is named ‘@folder <path_to_folder>’, the content (filenames) of the folder and the children of that node will be sync. Whenever a new file is put there, a new node will appear on top of the children list (with mark). So that I can put my description (annotation) as the content of that node. In this way, I can find any files much easier from leo.
Moreover, I add another feature to allow you to group files(in leo) into children of another group. This will help when there are many files in that folder. You can logically group it in leo (or even clone it to many groups), while keep every files in a flat/single directory on your computer.
at_produce
Module¶
Executes commands in nodes whose body text starts with @produce.
WARNING: trying to execute a non-existent command will hang Leo.
To use, put in the body text of a node:
@produce echo hi
This plugin creates two new commands: at-produce-all and at-produce-selected.
at-produce-all scans the entire tree for body text containing @produce. at-produce-selected just scans the selected tree.
Whatever follows @produce is executed as a command.
@produce commands are executed in the order they are found, that is, in outline order.
The at-produce commands produce a log node as the last top-level node of the outline. Any output, including error messages, should be there.
This plugin is not intended as a replacement for make or Ant, but as a simple substitute when that machinery is overkill.
-
leo.plugins.at_produce.
addMenu
(tag, keywords)[source]¶ Produce two new entries at the end of the Outlines menu.
-
leo.plugins.at_produce.
getList
(c, all)[source]¶ Return a list of all @produce lines in body texts in an outline. all = True: scan c’s entire outline. all = False: scan c.p and its descendants.
-
leo.plugins.at_produce.
run
(c, all)[source]¶ Run all @produce nodes in a separate thread. Report progress via a timer in this thread.
at_view
Module¶
attrib_edit
Module¶
backlink
Module¶
baseNativeTree
Module¶
bibtex
Module¶
Creates a BibTex file from an ‘@bibtex <filename>’ tree.
Nodes of the form ‘@<x> key’ create entries in the file.
When the user creates a new node (presses enter in headline text) the plugin automatically inserts a template for the entry in the body pane.
The ‘templates’ dict in the << globals >> section defines the template. The default, the template creates all required entries.
Double-clicking the @bibtex node writes the file. For example, the following outline:
-@bibtex biblio.bib
+@book key,
author = {A. Uthor},
year = 1999
creates the following ‘biblio.bib’ file:
@book{key,
author = {A. Uthor},
year= 1999}
- @string nodes define strings and may contain multiple entries. The plugin writes
all @string nodes at the start of the file. For example, the following outline:
-@bibtext biblio.bib +@string j1 = {Journal1} +@article AUj1 author = {A. Uthor}, journal = j1 +@string j2 = {Journal2} j3 = {Journal3}
creates the following file:
@string{j1 = {Journal1}}
@string{j2 = {Journal2}}
@string{j3 = {Journal3}}
@article{AUj1,
author = {A. Uthor},
journal = j1}
Headlines that do not start with ‘@’ are organizer nodes: the plugin does not write organizer nodes, but does write descendant nodes.
BibTeX files can be imported by creating an empty node with ‘@bibtex filename’ in the headline. Double-clicking it will read the file and parse it into a @bibtex tree. No syntax checks are made: the file is expected to be a valid BibTeX file.
-
leo.plugins.bibtex.
onHeadKey
(tag, keywords)[source]¶ Write template for the entry in body pane.
If body pane is empty, get template for the entry from a dictionary ‘templates ‘ and write it in the body pane.
20141127 - note headkey2 now only fires on Enter, no need to check which key brought us here.
-
leo.plugins.bibtex.
onIconDoubleClick
(tag, keywords)[source]¶ Read or write a bibtex file when the node is double-clicked.
Write the @bibtex tree as bibtex file when the root node is double-clicked. If it has no child nodes, read bibtex file.
bigdash
Module¶
bookmarks
Module¶
bzr_qcommands
Module¶
Adds a context menu to each node containing all the commands in the bzr Qt interface. Bzr is invoked based on the path of the current node.
Requires contextmenu.py.
chapter_hoist
Module¶
codewisecompleter
Module¶
colorize_headlines
Module¶
Manipulates appearance of individual tree widget items. (Qt only).
This plugin is mostly an example of how to change the appearance of headlines. As such, it does a relatively mundane chore of highlighting @thin, @auto, @shadow nodes in bold.
ctagscompleter
Module¶
cursesGui
Module¶
datenodes
Module¶
Allows users to insert headlines containing dates.
‘Date nodes’ are nodes that have dates in their headlines. They may be added to the outline one at a time, a month’s-worth at a time, or a year’s-worth at a time. The format of the labels (headlines) is configurable.
There are options to omit Saturdays and Sundays.
An ‘Insert Date Nodes …’ submenu will be created (by default) in the ‘Outline’ menu. This menu can be suppressed by using either of the following settings:
- @bool suppress-datenodes-menus
- @bool suppress-all-plugins-menus
The following commands are available for use via the minibuffer or in @menu/@popup settings.
- datenodes-today
- datenodes-this-month
- datenodes-this-year
-
class
leo.plugins.datenodes.
DateNodes
(c)[source]¶ Bases:
object
Main DateNodes class
-
ascii_encoder
()¶
-
boolean_settings
= ['datenodes_month_node_omit_saturdays', 'datenodes_month_node_omit_sundays', 'datenodes_year_node_omit_saturdays', 'datenodes_year_node_omit_sundays']¶
-
default_settings
= {'datenodes_body_text': 'To do...', 'datenodes_day_node_headline': '%Y-%m-%d', 'datenodes_month_node_day_headline': '%d: %A', 'datenodes_month_node_month_headline': '%B %Y', 'datenodes_month_node_omit_saturdays': True, 'datenodes_month_node_omit_sundays': True, 'datenodes_year_node_day_headline': '%d: %A', 'datenodes_year_node_month_headline': '%B', 'datenodes_year_node_omit_saturdays': True, 'datenodes_year_node_omit_sundays': True, 'datenodes_year_node_year_headline': '%Y'}¶
-
debugger_pudb
Module¶
Makes g.pdb() enter the Pudb debugger instead of pdb.
Pudb is a full-screen Python debugger: http://pypi.python.org/pypi/pudb
dragdropgoodies
Module¶
dtest
Module¶
Sends code to the doctest module and reports the result.
When the Dtest plugin is enabled, the dtest
command is active.
Typing:
Alt-X dtest
will run doctest on a file consisting of the current node and it’s children. If text is selected only the selection is tested.
From Wikipedia:
'Doctest' is a module included in the Python programming language's
standard library that allows for easy generation of tests based on
output from the standard Python interpreter.
http://tinyurl.com/cqh53 - Python.org doctest page
http://tinyurl.com/pxhlq - Jim Fulton’s presentation:
Literate Testing:
Automated Testing with doctest
-
class
leo.plugins.dtest.
DT
(tag, keywords)[source]¶ Bases:
leo.core.leoPlugins.BaseLeoPlugin
Sends code to the doctest module and reports the result If text is selected, tests only the selection.
>>> print("hello world") hello world >>> g.es('hello world') >>> print(c.p.h) Docstring >>> import notfound Traceback (most recent call last): ... ImportError: No module named notfound >>>
dump_globals
Module¶
Dumps Python globals at startup.
empty_leo_file
Module¶
Allows Leo to open any empty file as a minimal .leo file.
enable_gc
Module¶
Enables debugging and tracing for Python’s garbage collector.
expfolder
Module¶
Adds @expfolder nodes that represent folders in the file system.
The double-click-icon-box command on an @expfolder node reads the files in the directory at the path specified and creates child nodes for each file in the subfolder. Subdirectories are made into child @expfolder nodes so the tree can be easily traversed. If files have extensions specified in the expfolder.ini file they are made into @text nodes so the content of the files can be easily loaded into leo and edited. Double clicking a second time will delete all child nodes and refresh the directory listing. If there are any changed @text nodes contained inside you will be prompted about saving them.
The textextensions field on the expfolder Properties page contains a list of extensions which will be made into @text nodes, separated by spaces.
For the @text and @expfolder nodes to interact correctly, the textnode plugin must load before the expfolder plugin. This can be set using the Plugin Manager’s Plugin Load Order pane.
free_layout
Module¶
ftp
Module¶
geotag
Module¶
Tags nodes with latitude and longitude.
gitarchive
Module¶
Store snapshots of outline in git.
graphcanvas
Module¶
gtkDialogs
Module¶
gtkGui
Module¶
import_cisco_config
Module¶
Allows the user to import Cisco configuration files.
Adds the “File:Import:Import Cisco Configuration” menu item. The plugin will:
- Create a new node, under the current node, where the configuration will be written. This node will typically have references to several sections (see below).
- Create sections (child nodes) for the indented blocks present in the original config file. These child nodes will have sub-nodes grouping similar blocks (e.g. there will be an ‘interface’ child node, with as many sub-nodes as there are real interfaces in the configuration file).
- Create sections for the custom keywords specified in the customBlocks[] list in importCiscoConfig(). You can modify this list to specify different keywords. DO NOT put keywords that are followed by indented blocks (these are taken care of by point 2 above). The negated form of the keywords (for example, if the keyword is ‘service’, the negated form is ‘no service’) is also included in the sections.
- Not display consecutive empty comment lines (lines with only a ‘!’).
All created sections are alphabetically ordered.
initinclass
Module¶
Modifies the Python @auto importer so that the importer puts the __init__ method (ctor) into the body of the class node.
This makes it easier to keep the instance variable docs in the class docstring in sync. with the ivars as manipulated by __init__, saves repeating explanations in both places.
Note that this is done after the consistency checks by the @auto import code, so using this plugin is at your own risk. It will change the order of declarations if other methods are declared before __init__.
interact
Module¶
internal_ipkernel
Module¶
ipython
Module¶
ironPythonGui
Module¶
jinjarender
Module¶
Render @jinja nodes.
- sudo apt-get install python-jinja2
Create headline like this:
@jinja ~/foo.txt
Select the node and do alt-x act-on-node
Conceptually, acts like @nosent - tree is parsed, template is expanded and content is written to the file.
Requires “valuespace” plugin. Fetches vars from valuespace.
leoOPML
Module¶
A plugin to read and write Leo outlines in .opml (http://en.wikipedia.org/wiki/OPML) format.
The OPML plugin creates two new commands that read and write Leo outlines in OPML format. The read-opml-file command creates a Leo outline from an .opml file. The write-opml-file command writes the present Leo outline to an .opml file.
Various settings control what gets written to .opml files, and in what format. As usual, you specify settings for the OPML plugin using leoSettings.leo. The settings for the OPML are found in the node: @settings–>Plugins–>opml plugin.
Here are the settings that control the format of .opml files. The default values are shown.
- @string opml_namespace = leo:com:leo-opml-version-1
The namespace urn for the xmlns attribute of <opml> elements. This value typically is not used, but it should refer to Leo in some way.
- @bool opml_use_outline_elements = True
- If True, Leo writes body text to <leo:body> elements nested in <outline> elements. Otherwise, Leo writes body text to leo:body attributes of <outline> elements.
- @string opml_version = 2.0
The opml version string written to the <OPML> element. Use 2.0 unless there is a specific reason to use 1.0.
- @bool opml_write_body_text = True
Leo writes body text to the OPML file only if this is True.
- @bool opml_write_leo_details = True
If True, Leo writes the native attributes of Leo’s <v> elements as attributes of the opml <outline> elements.
The native attributes of <v> elements are a, t, vtag (new), tnodeList, marks, expanded and descendentTnodeUnknownAttributes.
- @bool opml_write_leo_globals_attributes = True
If True, Leo writes body_outline_ratio` and global_window_position attributes to the <head> element of the .opml file.
- @bool opml_write_ua_attributes
If True, write unknownAttributes NOTE: ua_attributes are not currently read from opml.
- @bool opml_expand_ua_dictionary
If True, expand an unknownAttriubte ‘x’ of type dict to ‘ua_x_key0’, ‘ua_x_key1’ etc. WARNING: using this feature may prevent reading these ua_attributes from opml, if that feature is implemented in the future.
- @bool opml_skip_ua_dictionary_blanks
If True, when expanding as above, skip blank dict entries.
-
class
leo.plugins.leoOPML.
NodeClass
[source]¶ Bases:
object
A class representing one outline element.
Use getters to access the attributes, properties and rules of this mode.
-
class
leo.plugins.leoOPML.
OpmlController
(c)[source]¶ Bases:
object
The controller class for this plugin.
-
cleanSaxInputString
(s)[source]¶ Clean control characters from s. s may be a bytes or a (unicode) string.
-
createTnodesDict
()[source]¶ Create c.tnodesDict by from self.generated_gnxs by converting VNode entries to tnodes.
-
-
class
leo.plugins.leoOPML.
PutToOPML
(owner)[source]¶ Bases:
object
Write c.p’s tree as OPML, using the owner’s put method.
-
putAll
()[source]¶ Put the selected outline as OPML. All elements and attributes prefixed by ‘leo:’ are leo-specific. All other elements and attributes are specified by the OPML 1 spec.
-
-
class
leo.plugins.leoOPML.
SaxContentHandler
(c, inputFileName)[source]¶ Bases:
xml.sax.saxutils.XMLGenerator
A sax content handler class that reads OPML files.
-
attrsToList
(attrs)[source]¶ Convert the attributes to a list of g.Bunches. attrs: an Attributes item passed to startElement.
-
leo_interface
Module¶
Allows the user to browse XML documents in Leo.
This plugin implements an interface to XML generation, so that the resulting file can be processed by leo.
class leo_file represents the whole leo file. class leo_node has a headline and body text.
See the end of this file for a minimal example on how to use these classes.
If you encounter the first of a set of clones, create a leo_node. If you encounter the same set of clones later, create a leo_clone node and refer back to the first element.
-
class
leo.plugins.leo_interface.
leo_clone
(orig)[source]¶ Bases:
leo.plugins.leo_interface.node_with_parent
Class representing a clone.
The (only) data of a clone is the reference to a leo_node.
When you encounter the first clone of a set of clones, generate a leo_node. The second clone should then reference this leo_node, and contain no other data.
Since clones are indistinguishable, there is really not much to do in this class.
-
class
leo.plugins.leo_interface.
leo_file
[source]¶ Bases:
leo.plugins.leo_interface.LeoNode
Leo specific class representing a file.
-
class
leo.plugins.leo_interface.
leo_node
(headline='', body='')[source]¶ Bases:
leo.plugins.leo_interface.LeoNode
,leo.plugins.leo_interface.node_with_parent
Leo specific class representing a node.
These nodes correspond to tnodes in LEO. They have a headline and a body.
They also represent the (only) vnode in an outline without clones.
-
count
= 0¶
-
leo_pdf
Module¶
This NOT a Leo plugin: this is a docutils writer for .pdf files.
That file uses the reportlab module to convert html markup to pdf.
The original code written by Engelbert Gruber.
Rewritten by Edward K. Ream for the Leo rst3 plugin.
-
class
leo.plugins.leo_pdf.
Bunch
(**keywords)[source]¶ Bases:
object
A class that represents a colection of things.
Especially useful for representing a collection of related variables.
-
class
leo.plugins.leo_pdf.
PDFTranslator
(writer, doctree)[source]¶ Bases:
docutils.nodes.NodeVisitor
-
depart_comment
(node)¶ Invisible nodes should be ignored.
-
depart_figure
(node)¶ Invisible nodes should be ignored.
-
depart_pending
(node)¶ Invisible nodes should be ignored.
Invisible nodes should be ignored.
-
depart_substitution_definition
(node)¶ Invisible nodes should be ignored.
-
depart_table
(node)¶ Invisible nodes should be ignored.
-
depart_tbody
(node)¶ Invisible nodes should be ignored.
-
depart_tgroup
(node)¶ Invisible nodes should be ignored.
-
depart_thead
(node)¶ Invisible nodes should be ignored.
-
depart_tip
(node)¶ Invisible nodes should be ignored.
-
depart_title_reference
(node)¶ Invisible nodes should be ignored.
-
depart_transition
(node)¶ Invisible nodes should be ignored.
-
depart_warning
(node)¶ Invisible nodes should be ignored.
-
pdfMunge
(s)[source]¶ Duplicate the munging done (somewhere in docutils) of section names.
This allows us to use the nameids attribute in the document element.
-
visit_figure
(node)¶
-
visit_pending
(node)¶ Invisible nodes should be ignored.
Invisible nodes should be ignored.
-
visit_substitution_definition
(node)¶
-
visit_table
(node)¶ Invisible nodes should be ignored.
-
visit_tbody
(node)¶ Invisible nodes should be ignored.
-
visit_tgroup
(node)¶ Invisible nodes should be ignored.
-
visit_thead
(node)¶ Invisible nodes should be ignored.
-
visit_tip
(node)¶ Invisible nodes should be ignored.
-
visit_title_reference
(node)¶ Invisible nodes should be ignored.
-
visit_transition
(node)¶ Invisible nodes should be ignored.
-
visit_warning
(node)¶ Invisible nodes should be ignored.
-
-
class
leo.plugins.leo_pdf.
Writer
[source]¶ Bases:
docutils.writers.Writer
-
output
= None¶
-
settings_spec
= ('PDF-Specific Options', None, (('Specify a stylesheet URL, used verbatim. Overrides --stylesheet-path. Either --stylesheet or --stylesheet-path must be specified.', ['--stylesheet'], {'overrides': 'stylesheet_path', 'metavar': '<URL>'}), ('Specify a stylesheet file, relative to the current working directory. The path is adjusted relative to the output HTML file. Overrides --stylesheet.', ['--stylesheet-path'], {'overrides': 'stylesheet', 'metavar': '<file>'}), ('Format for footnote references: one of "superscript" or "brackets". Default is "brackets".', ['--footnote-references'], {'default': 'brackets', 'metavar': '<FORMAT>', 'choices': ['superscript', 'brackets']})))¶
-
supported
= ('pdf', 'rlpdf')¶
-
-
leo.plugins.leo_pdf.
bunch
¶ alias of
leo.plugins.leo_pdf.Bunch
-
class
leo.plugins.leo_pdf.
dummyPDFTranslator
(writer, doctree, contents)[source]¶ Bases:
docutils.nodes.NodeVisitor
leo_to_html
Module¶
Converts a leo outline to an html web page.
This plugin takes an outline stored in Leo and converts it to html which is then either saved in a file or shown in a browser. It is based on the original leoToHTML 1.0 plugin by Dan Rahmel which had bullet list code by Mike Crowe.
The outline can be represented as a bullet list, a numbered list or using html <h?> type headings. Optionally, the body text may be included in the output.
If desired, only the current node will be included in the output rather than the entire outline.
An xhtml header may be included in the output, in which case the code will be valid XHTML 1.0 Strict.
The plugin is fully scriptable as all its functionality is available through a Leo_to_HTML object which can be imported and used in scripts.
Menu items and @settings
If this plugin loads properly, the following menu items should appear in your File > Export… menu in Leo:
Save Outline as HTML (equivalent to export-html)
Save Node as HTML (equivalent to export-html-node)
Show Outline as HTML (equivalent to show-html)
Show Node as HTML (equivalent to show-html-node)
Unless the following appears in an @setting tree:
@bool leo_to_html_no_menus = True
in which case the menus will not be created. This is so that the user can use @menu and @item to decide which commands will appear in the menu and where.
Commands
Several commands will also be made available
- export-html
- will export to a file according to current settings.
- export-html-*
- will export to a file using bullet type ‘*’ which can be number, bullet or head.
The following commands will start a browser showing the html.
- show-html
- will show the outline according to current settings.
- show-html-*
- will show the outline using bullet type ‘*’ which can be number, bullet or head.
The following commands are the same as above except only the current node is converted:
export-html-node
export-html-node-*
show-html-node
show-html-node-*
Properties
Note
As of Mar. 2014 regular Leo @string settings starting with
leo_to_html_ are checked first, before the .ini
file.
E.g. @string leo_to_html_flagjustheadlines = No
has the
same effect as flagjustheadlines = No
in the .ini
, and
takes precedence.
There are several settings that can appear in the leo_to_html.ini properties file in leo’s plugins folder or be set via the Plugins > leo_to_html > Properties… menu. These are:
- exportpath:
- The path to the folder where you want to store the generated html file. Default: c:\
- flagjustheadlines:
- Default: ‘Yes’ to include only headlines in the output.
- flagignorefiles:
- Default: ‘Yes’ to ignore @file nodes.
- use_xhtml:
- Yes to include xhtml doctype declarations and make the file valid XHTML 1.0 Strict. Otherwise only a simple <html> tag is used although the output will be xhtml compliant otherwise. Default: Yes
- bullet_type:
If this is ‘bullet’ then the output will be in the form of a bulleted list. If this is ‘number’ then the output will be in the form of a numbered list. If this is ‘heading’ then the output will use <h?> style headers.
Anything else will result in <h?> type tags being used where ‘?’ will be a digit starting at 1 and increasing up to a maximum of six depending on depth of nesting. Default: number
- browser_command:
Set this to the command needed to launch a browser on your system or leave it blank to use your systems default browser.
If this is an empty string or the browser can not be launched using this command then python’s webbrowser module will be tried. Using a bad command here will slow down the launch of the default browser, better to leave it blank. Default: empty string
Configuration
At present, the file leo/plugins/leo_to_html.ini contains configuration settings. In particular, the default export path, “c:” must be changed for *nix systems.
-
class
leo.plugins.leo_to_html.
Leo_to_HTML
(c=None)[source]¶ Bases:
object
This class provides all the functionality of the leo_to_html plugin.
See the docstring for the leo_to_html module for details.
-
applyTemplate
(template=None)[source]¶ Fit self.xhtml and self.title into an (x)html template.
Plaace the result in self.xhtml.
The template string in self.template should have too %s place holders. The first for the title the second for the body.
-
do_xhtml
(node=False)[source]¶ Convert the tree to xhtml.
Return the result as a string in self.xhtml.
Only the code to represent the tree is generated, not the wraper code to turn it into a file.
-
getPlainTemplate
()[source]¶ Returns a string containing a template for the outline page.
- The string should have positions in order, for:
- title and body text.
-
getXHTMLTemplate
()[source]¶ Returns a string containing a template for the outline page.
- The string should have positions in order, for:
- title and body text.
-
main
(bullet=None, show=False, node=False)[source]¶ Generate the html and write the files.
If ‘bullet’ is not recognized then the value of bullet_type from the the properties file will be used.
If ‘show’ is True then the file will be saved to a temp dir and shown in a browser.
-
show
()[source]¶ Convert the outline to xhtml and display the results in a browser.
If browser_command is set, this command will be used to launch the browser. If it is not set, or if the command fails, the default browser will be used. Setting browser_command to a bad command will slow down browser launch.
-
showSubtree
(p)[source]¶ Return True if subtree should be shown.
subtree should be shown if it is not an @file node or if it is an @file node and flags say it should be shown.
-
-
leo.plugins.leo_to_html.
abspath
(*args)[source]¶ Join the arguments and convert to an absolute file path.
-
leo.plugins.leo_to_html.
createExportMenus
(tag, keywords)[source]¶ Create menu items in File -> Export menu.
Menu’s will not be created if the following appears in an @setting tree:
@bool leo_to_html_no_menus = True
This is so that the user can use @menu to decide which commands will appear in the menu and where.
-
leo.plugins.leo_to_html.
onCreate
(tag, keys)[source]¶ Handle ‘after-create-leo-frame’ hooks by creating a plugin controller for the commander issuing the hook.
-
class
leo.plugins.leo_to_html.
pluginController
(c)[source]¶ Bases:
object
A per commander plugin controller to create and handle minibuffer commands that control the plugins functions.
-
export_html
(event=None, bullet=None, show=False, node=False)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
export_html_bullet
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
export_html_head
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
export_html_node
(event=None, bullet=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
export_html_node_bullet
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
export_html_node_head
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
export_html_node_number
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
export_html_number
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
show_html
(event=None, bullet=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
show_html_bullet
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
show_html_head
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
show_html_node
(event=None, bullet=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
show_html_node_bullet
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
show_html_node_head
(event=None)[source]¶ Command handler for leo_to_html. See modules docstring for details.
-
leo_to_rtf
Module¶
Outputs a Leo outline as a numbered list to an RTF file. The RTF file can be loaded into Microsoft Word and formatted as a proper outline.
This plug-in loads installs an “Outline to Microsoft RTF” menu item in your File > Export… menu in Leo.
Settings such as outputting just the headlines (vs. headlines & body text) and whether to include or ignore the contents of @file nodes are stored in the rtf_export.ini file in your Leoplugins folder.
The default export path is also stored in the INI file. By default, it’s set to c:so you may need to modify it depending on your system.
leocursor
Module¶
Creates a LeoCursor object that can walk around a Leo outline and decode attributes from nodes.
Node names can be used through . (dot) notation so cursor.Data.Name._B
for
example returns the body text of the Name node which is a child of the Data node
which is a child of the cursors current location.
See …/plugins/examples/leocursorexample.leo for application.
-
class
leo.plugins.leocursor.
AM_CapColon
[source]¶ Bases:
leo.plugins.leocursor.AM_Colon
Like AM_Colon, but first letter must be capital.
-
pattern
= '^([A-Z][A-Za-z0-9_]*:)(\\s+(\\S.*))*$'¶
-
-
class
leo.plugins.leocursor.
AM_Colon
[source]¶ Bases:
leo.plugins.leocursor.AttribManager
Attributes are in the body text as:
start-of-line letter letters-or-numbers colon space(s) attribute-value
Both:
foo:
and:
foo: all this is the value
are attributes (first one is value==’‘), but:
foo:value
is not (because there’s no space after the colon).
-
filterBody
(b)[source]¶ Return the body string without any parts used to store attributes, if this flavor of attribute manager stores attributes in the body. If not, just return the whole body string.
-
pattern
= <_sre.SRE_Pattern object>¶
-
-
class
leo.plugins.leocursor.
AttribManager
[source]¶ Bases:
object
Class responsible for reading / writing attributes from vnodes for LeoCursor
leofeeds
Module¶
Read feeds from rss / atom / whatever sources
Usage: Create node with a headline like:
(or somesuch).
Do alt-x act-on-node on that node to populate the subtree from the feed data. Requires “feedparser” python module
leofts
Module¶
leomail
Module¶
Sync local mailbox files over to Leo.
Creates mail-refresh command, which can only be applied to @mbox nodes of the form:
@mbox <path to .mbox file>
The command parses the .mbox file and creates a separate node for each thread.
Replies to the original messages become children of that message.
leomylyn
Module¶
Provides an experience like Mylyn:http://en.wikipedia.org/wiki/Mylyn for Leo.
It “scores” the nodes based on how interesting they probably are for you, allowing you to focus on your “working set”.
Scoring is based on how much you edit the nodes.
leoremote
Module¶
leoscreen
Module¶
lineNumbers
Module¶
Adds #line directives in perl and perlpod programs.
Over-rides two methods in leoAtFile.py to write #line directives after node sentinels. This allows compilers to give locations of errors in relation to the node name rather than the filename. Currently supports only perl and perlpod.
livecode
Module¶
macros
Module¶
Creates new nodes containing parameterized section reference.
This plugin adds nodes under the currently selected tree that are to act as section references. To do so, go the Outline menu and select the ‘Parameterize Section Reference’ command. This plugin looks for a top level node called ‘Parameterized Nodes’. If it finds a headline that matches the section reference it adds a node/nodes to the current tree.
To see this in action, do the following:
Important: in the examples below, type << instead of < < and type >> instead of > >. Docstrings can not contain section references!
Create a node called ‘Parameterized Nodes’, with a sub-node called < < Meow >>. The body of < < Meow > > should have the text:
I mmmm sooo happy I could < < 1$ > >. But I don't know if I have all the < < 2$ > > money in the world.
In a node called A, type:
< < meow( purrrrrr, zzooot ) > > (leave the cursor at the end of the line)
In a node called B, type:
< < meow ( spit or puke, blinkin ) > > (leave the cursor at the end of the line)
Leave the cursor in Node A at the designated point.
Go to Outline and select Parameterize Section Reference.
The plugin searches the outline, goes to level one and finds a Node with the Headline, “Parameterized Nodes”. It looks for nodes under that headline with the the headline << meow >>. It then creates this node structure under Node A:
< < meow ( purrrrrr, zzooot ) > >
< <2$> >
< <1$> >
Examine the new subnodes of Node A:
- < < meow ( purrrrrr, zzooot ) > >
contains the body text of the < < meow > > node.
< < 1$ > > contains the word purrrrrr. < < 2$ > > contains the word zzooot.
Go to Node B, and leave the cursor at the designated point.
Go to Outline Menu and select Parameterize Section Reference command.
- Examine the new subnodes of Node B.
It’s a lot easier to use than to explain!
maximizeNewWindows
Module¶
Maximizes all new windows.
mime
Module¶
Opens files with their default platform program.
The double-click-icon-box command on @mime nodes will attempt to open the named file as if opened from a file manager. @path parent nodes are used to find the full filename path. For example:
@mime foodir/document.pdf
The string setting ‘mime_open_cmd’ allows specifying a program to handle opening files:
@settings
@string mime_open_cmd = see
.. or ..
@string mime_open_cmd = see %s
Where ‘%s’ is replaced with the full pathname.
Note: This plugin terminates handling of the ‘icondclick1’ event by returning True. If another plugin using this event (e.g. vim.py) is also enabled, the order in @enabled-plugins matters. For example: if vim.py is enabled before mime.py, double-clicking on an @mime node will both open the body text in [g]vim AND call the mime_open_cmd.
Use @url for opening either URLs or Uniform Node Locators in “*.leo” files and use @mime nodes for opening files on the local file system. It also replaces the startfile.py plugin, where here the headline must start with @mime to activate this plugin.
For other sys.platform’s, add an elif case to the section “guess file association handler” and either define a default _mime_open_cmd string, where “%s” will be replaced with the filename, or define a function taking the filename string as its only argument and set as open_func.
-
leo.plugins.mime.
exec_full_cmd
(cmd)[source]¶ Accept a command string including filename and return a function which executes the command.
-
leo.plugins.mime.
exec_string_cmd
(cmd)[source]¶ Accept a command string and return a function which opens executes the command, replacing %s with the full file path.
-
leo.plugins.mime.
open_mimetype
(tag, keywords, val=None)[source]¶ Simulate double-clicking on the filename in a file manager. Order of preference is:
- @string mime_open_cmd setting
- _mime_open_cmd, defined per sys.platform detection
- open_func(fpath), defined per sys.platform detection
- mailcap file for mimetype handling
mnplugins
Module¶
mnplugins.py
mnplugins shows how to : define new Commands “insertOK” + “insertUser” create Usermenu with new Commands
new Commands: insertOK:
insert ‘OK’ in headline and a stamp in the first body line are there child nodes without ‘OK’ verhindern OK in actual node. The right-click-icon command also inserts ‘OK’.
- insertUser : Shift-F6
- insert a <user/date/time> stamp at the current location in body text
mod_autosave
Module¶
mod_framesize
Module¶
Sets a hardcoded frame size.
Prevents Leo from setting custom frame size (e.g. from an external .leo document)
mod_http
Module¶
An http plug-in for LEO, based on AsyncHttpServer.py.
Adapted and extended from the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259148
This plug-in has three distinct behaviors:
- Viewing loaded outlines in a browser, e.g. at http://localhost:8130/
- Storing web bookmarks in Leo outlines from a browser, e.g. at http://localhost:8130/_/add/bkmk/
- Remotely executing code in a running Leo instance, e.g. at http://localhost:8130/_/exec/?cmd=nd=p.insertAsLastChild()
Install this plug-in is as follows:
Start Leo with the plug-in enabled. You will see a purple message that says something like:
"http serving enabled at 127.0.0.1:8130"
Settings¶
@bool http_active = True
- required for plug-in to be active
@string http_ip = 127.0.0.1
- address to bind to, see notes below
@int http_port = 8130
- port to use (1 3 0 ~= L E O)
@bool http_allow_remote_exec = False
- must be changed to True for remote code execution
@string rst_http_attributename = 'rst_http_attribute'
- link to obsolete rst3 plugin
@data user_bookmark_stylesheet
- Additional .css for bookmarks.
@data http_stylesheet
- The default .css for this page.
@data user_http_stylesheet
- Additional .css for this page.
Note: The html generated by the server contains both stylesheets as inline <style> elements, with the user_http_stylesheet contents last.
@data mod_http script
- The body text of this @data setting contains all the javascript used in the page.
Note The html generated by the server handles the <script> elements:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script>..the contents of @data mod_http_script..
</script>
Browsing Leo files¶
Start a web browser, and enter the following URL: http://localhost:8130/
You will see a a “top” level page containing one link for every open .leo file. Start clicking :-)
You can use the browser’s refresh button to update the top-level view in the browser after you have opened or closed files.
Note: IP address 127.0.0.1 is accessible by all users logged into your local machine. That means while Leo and mod_http is running anyone logged into your machine will be able to browse all your leo outlines and add bookmarks.
Note: If you want all other network accessible machines to have access to your mod_http instance, then use @string http_ip = 0.0.0.0.
Note: the browser_encoding constant (defined in the top node of this file) must match the character encoding used in the browser. If it does not, non-ascii characters will look strange.
Saving bookmarks from browser to Leo¶
To do this, add a bookmark to the browser with the following URL / Location:
javascript:w=window; d=w.document; ln=[];if(w.location.href.indexOf('one-tab')>-1){el=d.querySelectorAll('a');for (i in el){ln.push({url:el[i].href,txt:el[i].innerHTML});};};w.open('http://localhost:8130/_/add/bkmk/?&name=' + escape(d.title) + '&selection=' + escape(window.getSelection()) + '&ln=' + escape(JSON.stringify(ln)) + '&url=' + escape(w.location.href),"_blank","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=800, height=300, status=no");void(0); # NOQA
and edit the port (8130 in the example above) to match the port you’re using for mod_http.
Bookmarks are created as the first node in the outline which has been opened
longest. You can set the @string
http_bookmark_unl
to specify an
alternative location, e.g.:
@string http_bookmark_unl = /home/tbrown/.bookmarks.leo#@bookmarks-->Incoming
to place them in the Incoming node in the @bookmarks node in the .bookmarks.leo outline.
The headline is preceded with ‘@url ‘ unless the bookmarks
plug-in is
loaded. If the bookmarks
plug-in is loaded the bookmark will have to be moved
to a @bookmarks
tree to be useful.
Note: there is special support for Chrome’s OneTab extension as a mechanism for saving all tabs open. Click the OneTab button to get a list of tabs, then click the “Share all as web page” link to show the list on www.one-tab.com. Bookmark as usual as described above. You can then delete the shared list with the “Delete this shared page” button. The Leo node created will have a child node for each of the listed tabs.
The browser may or may not be able to close the bookmark form window for you,
depending on settings - set dom.allow_scripts_to_close_windows
to true in
about:config
in Firefox.
Executing code remotely¶
Warning:
Allowing remote code execution is a HUGE SECURITY HOLE, you need to be sure that the url from which you access Leo (typically http://localhost:8130/) is accessible only by people and software you trust.
Remote execution is turned off by default, you need to manually / locally change the @setting
@bool http_allow_remote_exec = False
toTrue
to enable it.
Commands to be executed are submitted via HTTP GET requests, which can be generated in almost any language and also triggered from shortcuts, links in other documents or applications, etc. etc.
The basic form is:
http://localhost:8130/_/exec/?cmd=<python code for Leo to execute>
The query parameters are:
cmd
(required)- A valid python snippet for Leo to execute. Executed by the
eval
command in themod_scripting
plug-in. Can be specified multiple times, each is executed in order. May contain newlines, see examples. c
(optional)- Which currently loaded outline to use, can be an integer, starting from zero, or the full path+filename, or just the base filename. Defaults to 0 (zero), i.e. the “first” open outline.
enc
(optional)- Encoding for response, ‘str’, ‘repr’, or ‘json’. Used to render the returned value.
mime_type
(optional)- Defaults to
text/plain
. Could be useful to usetext/html
etc.
A special variant url is:
http://localhost:8130/_/exec/commanders/
which returns a list of open outlines.
This command:
curl http://localhost:8130/_/exec/?cmd='c.bringToFront()' >/dev/null
will raise the Leo window, or at least make the window manager signal the need to raise it.
curl --get --data-urlencode cmd='g.handleUrl("file:///home/tbrown/.leo/.contacts.leo#Contacts", c)' http://localhost:8130/_/exec/ >/dev/null
will cause a running Leo instance to open /some/path/contacts.leo
and select
the Contacts
node. A desktop icon link, browser bookmark, or link in a
spread-sheet or other document could be used the same way.
In the bash
shell language, this code:
TEXT="$@"
curl --silent --show-error --get --data-urlencode cmd="
nd = c.rootPosition().insertAfter()
nd.h = 'TODO: $TEXT'
import time
nd.b = '# created %s' % time.asctime()
c.selectPosition(nd)
c.redraw()
'To do item created
could be written in a file called td
, and then, assuming that file is
executable and on the shell’s path, entering:
td remember to vacuum the cat
on the command line would create a node at the top of the first open outline in
Leo with a headline TODO: remember to vacuum the cat
and a body text #
created Wed Jul 29 16:42:26 2015
. The command vs-eval
returns the value of
the last expression in a block, so the trailing 'To do item created
'
gives
better feedback than None
generated by c.redraw()
.
c.selectPosition(nd)
is important ant to stop Leo getting confused about
which node is selected.
-
class
leo.plugins.mod_http.
ExecHandler
(request_handler)[source]¶ Bases:
object
Quasi-RPC GET based interface
-
class
leo.plugins.mod_http.
LeoActions
(request_handler)[source]¶ Bases:
object
A place to collect other URL based actions like saving bookmarks from the browser. Conceptually this stuff could go in class leo_interface but putting it here for separation for now.
-
add_bookmark_selection
(node, text)[source]¶ Insert the selected text into the bookmark node, after any earlier selections but before the users comments.
Tags: tags, are here
Full title of the page
Collected: timestamp
“”” The first saved selection “”“
“”” The second saved selection “”“
Users comments
i.e. just above the “Users comments” line.
-
-
class
leo.plugins.mod_http.
RequestHandler
(conn, addr, server)[source]¶ Bases:
leo.plugins.mod_http.leo_interface
,asynchat.async_chat
,SimpleHTTPServer.SimpleHTTPRequestHandler
-
copyfile
(source, outputfile)[source]¶ Copy all data between two file objects.
The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method).
The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF – note however that this the default server uses this to copy binary data as well.
-
do_POST
()[source]¶ Begins serving a POST request. The request data must be readable on a file-like object called self.rfile
-
log_message
(format, *args)[source]¶ Log an arbitrary message.
This is used by all other logging functions. Override it if you have specific logging wishes.
The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it’s just like printf!).
The client host and current date/time are prefixed to every message.
-
-
class
leo.plugins.mod_http.
Server
(ip, port, handler)[source]¶ Bases:
asyncore.dispatcher
Copied from http_server in medusa
-
class
leo.plugins.mod_http.
config
[source]¶ Bases:
object
-
http_active
= False¶
-
http_ip
= '127.0.0.1'¶
-
http_port
= 8130¶
-
http_timeout
= 0¶
-
rst2_http_attributename
= 'rst_http_attribute'¶
-
-
class
leo.plugins.mod_http.
leo_interface
[source]¶ Bases:
object
-
add_leo_links
(window, node, f)[source]¶ - Given a node ‘node’, add links to:
- The next sibling, if any. the next node. the parent. The children, if any.
-
create_leo_reference
(window, node, text, f)[source]¶ Create a reference to ‘node’ in ‘window’, displaying ‘text’
-
find_window_and_root
(path)[source]¶ - given a path of the form:
[<short filename>,<number1>,<number2>…<numbern>] identify the leo node which is in that file, and, from top to bottom, is the <number1> child of the topmost node, the <number2> child of that node, and so on.
Return None if that node can not be identified that way.
-
node_reference
(vnode)[source]¶ Given a position p, return the name of the node.
This is called from leo.core.leoRst.
-
send_head
()[source]¶ Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do.
-
-
leo.plugins.mod_http.
loop
(timeout=5.0, use_poll=0, map=None)[source]¶ Override the loop function of asynchore. We poll only until there is not read or write request pending.
-
exception
leo.plugins.mod_http.
noLeoNodePath
[source]¶ Bases:
exceptions.Exception
Raised if the path can not be converted a filename and a series of numbers. Most likely a reference to a picture.
mod_leo2ascd
Module¶
-
leo.plugins.mod_leo2ascd.
CodeChunk
(text, width=72)[source]¶ Split a line of text into a list of chunks not longer than width.
-
leo.plugins.mod_leo2ascd.
CreateAscMenu
(tag, keywords)[source]¶ Create the Outline to AsciiDoc menu item in the Export menu.
-
leo.plugins.mod_leo2ascd.
WriteAllRoots
(c)[source]¶ Writes @root directive and/or @ascfile directive to log pane.
mod_read_dir_outline
Module¶
Allows Leo to read a complete directory tree into a Leo outline. Converts directories into headlines and puts the list of file names into bodies.
Ce plug-in permet de traduire l’arborescence d’un répertoire en une arborescence Leo : Chaque dossier est converti en noeud dans Leo ; son nom est placé dans l’entête du noeud et chaque nom de fichier qu’il contient est listé dans son contenu.
Feedback on this plugin can be sent to:
Frédéric Momméja
<frederic [point] mommeja [at] laposte [point] net>
mod_scripting
Module¶
mod_speedups
Module¶
Experimental speedups
Various optimizations. Use at your own risk.
If stuff breaks, disable this plugin before reporting bugs.
mod_tempfname
Module¶
mod_timestamp
Module¶
Timestamps all save operations to show when they occur.
multifile
Module¶
Allows Leo to write a file to multiple locations.
This plugin acts as a post-write mechanism, a file must be written to the file system for it to work. At this point it is not a replacement for @path or an absolute path, it works in tandem with them.
To use, place @multipath at the start of a line in the root node or an ancestor of the node. The format is (On Unix-like systems):
@multipath /machine/unit/:/machine/robot/:/machine/
New in version 0.6 of this plugin: the separator used above is ‘;’ not ‘:’, for example:
@multipath c:\prog\test;c:\prog\unittest
It will places copy of the written file in each of these directories.
There is an additional directive that simplifies common paths, it is called @multiprefix. By typing @multiprefix with a path following it, before a @multipath directive you set the beginning of the paths in the @multipath directive. For example:
#@verbatim
#@multiprefix /leo #@multipath /plugins
or:
#@verbatim
#@multiprefix /leo/
- #@verbatim
- #@multipath plugins: fungus : drain
copies a file to /leo/plugins /leo/fungus /leo/drain.
Note: I put # in front of the directives here because I don’t want someone browsing this file to accidentally save multiple copies of this file to their system :)
The @multiprefix stays in effect for the entire tree until reset with another @multiprefix directive. @multipath is cumulative, in that for each @multipath in an ancestor a copy of the file is created. These directives must at the beginning of the line and by themselves.
nested_splitter
Module¶
niceNosent
Module¶
Ensures that all descendants of @file-nosent nodes end with exactly one newline, replaces all tabs with spaces, and adds a newline before class and functions in the derived file.
nodeActions
Module¶
Allows the definition of double-click actions.
The double-click-icon-box command causes this plugin checks for a match of the clicked node’s headline text with a list of patterns. If a match occurs, the plugin executes the associated script.
nodeAction nodes may be located anywhere in the outline. Such nodes should contain one or more pattern nodes as children. The headline of each pattern node contains the pattern; the body text contains the script to be executed when the pattern matches the double-clicked node.
For example, the “nodeActions” node containing a “launch URL” pattern node and a “pre-process python code” node could be placed under an “@settings” node:
@settings
|
+- nodeActions
|
+- http:\\*
|
+- @file *.py
Configuration
The nodeActions plugin supports the following global configurations using Leo’s support for setting global variables within an @settings node’s sub-nodes in the leoSettings.leo, myLeoSettings.leo, and the project Leo file:
@bool nodeActions_save_atFile_nodes = False
True: The double-click-icon-box command on an @file type node will save the file to disk before executing the script. False: The double-click-icon-box command on an @file type node will not save the file to disk before executing the script. (default)
@int nodeActions_message_level = 1
Specifies the type of messages to be sent to the log pane. Specifying a higher message level will display that level and all lower levels. The following integer values are supported:
0 no messages 1 Plugin triggered and the patterns that were matched (default) 2 Double-click event passed or not to next plugin 3 Patterns that did not match 4 Code debugging messages
Patterns
Pattern matching is performed using python’s support for Unix shell-style patterns unless overwritten by the “X” pattern directive. The following pattern elements are supported:
* matches everything
? matches any single character
[<seq>] matches any character in <seq>
[!<seq>] matches any character **not** in <seq>
Unix shell-style pattern matching is case insensitive and always starts from the beginning of the headline. For example:
Pattern Matches Does not match *.py Abc_Test.py .py .py - Test Abc_Test.py test* Test_Abc.py Abc_Test.py
To enable a script to run on any type of @file node (@thin, @shadow, …), the pattern can start with “@files” to match on any external file type. For example, the pattern “@files *.py” will match a node with the headline “@file abcd.py”.
The double-click-icon-box command matches the headline of the node against the patterns starting from the first sub-node under the “nodeActions” node to the last sub-node.
Only the script associated with the first matching pattern is invoked unless overwritten by the “V” pattern directive.
Using the “V” pattern directive allows a broad pattern such as “@files *.py” to be invoked, and then, by placing a more restrictive pattern above it, such as “@files *_test.py”, a different script can be executed for those files requiring pre-processing:
+- nodeActions
|
+- @files *_test.py
|
+- @files *.py
Note: To prevent Leo from trying to save patterns that begin with a derived file directive (@file, @auto, …) to disk, such as “@file *.py”, place the “@ignore” directive in the body of the “nodeActions” node.
Pattern nodes can be placed at any level under the “nodeActions” node. Only nodes with no child nodes are considered pattern nodes. This allows patterns that are to be used in multiple Leo files to be read from a file. For example, the following structure reads the pattern definition from the “C:\Leo\nodeActions_Patterns.txt” file:
+- nodeActions
|
+- @files C:\\Leo\\nodeActions_Patterns.txt
|
+- http:\\*
|
+- @file *.py
Pattern directives
The following pattern specific directives can be appended to the end of a pattern (do not include the ‘:’):
[X]: | Use python’s regular expression type patterns instead of the Unix shell-style pattern syntax. For example, the following patterns will match the same headline string: Unix shell-style pattern:
@files *.py
Regular Expression pattern:
^@files .*\.py$ [X]
|
---|---|
[V]: | Matching the pattern will not block the double-click event from being passed to the remaining patterns. The “V” represents a down arrow that symbolizes the passing of the event to the next pattern below it. For example, adding the “[V]” directive to the “@files *_test.py” in the Patterns section above, changes its script from being ‘an alternate to’ to being ‘a pre-processor for’ the “@files *.py” script: +- nodeActions
|
+- @files *_test.py [V]
|
+- @files *.py
|
[>]: | Matching the pattern will not block the double-click event from being passed to other plugins. The “>” represents a right arrow that symbolizes the passing of the event to the next plugin. If the headline matched more than one headline, the double-click event will be passed to the next plugin if the directive is associated with any of the matched patterns. |
The directive(s) for a pattern must be contained within a single set of brackets, separated from the pattern by a space, with or without a comma separator. For example, the following specifies all three directives:
^@files .*\.py$ [X,V>]
Scripts
The script for a pattern is located in the body of the pattern’s node. The following global variables are available to the script:
c
g
pClicked - node position of the double-clicked node
pScript - node position of the invoked script
Examples
The double-click-icon-box command on a node with a “http:\www.google.com” headline will invoke the script associated with the “http:\*” pattern. The following script in the body of the pattern’s node displays the URL in a browser:
import webbrowser
hClicked = pClicked.h #Clicked node's Headline text
webbrowser.open(hClicked) #Invoke browser
The following script can be placed in the body of a pattern’s node to execute a command in the first line of the body of a double-clicked node:
g.os.system('"Start /b ' + pClicked.bodyString() + '"')
nodediff
Module¶
Provides commands to run text diffs on node bodies within Leo.
By Jacob M. Peck
Configuration Settings¶
This plugin is configured with the following @settings:
One of ‘compare’, ‘ndiff’, or ‘unified_diff’. Chooses which diff output method difflib uses to provide the diff. Defaults to ‘compare’.
The various diff output methods are explained in the difflib documentation.
Commands¶
This plugin defines the following commands:
Runs a diff on the marked nodes. Only works if there are exactly two nodes marked in the current outline.
Runs a diff on the selected nodes. Only works if there are exactly two selected nodes in the current outline.
Runs a diff on the children of the currently selected node. Only works if the selected node has exactly two children.
Runs a diff on the current node and the same node in the .leo file on disk, i.e. changes in the node since last save. This does not work for derived @<files> (@auto, @edit, etc.), only nodes which are part of the Leo outline itself.
Runs a diff on the current node and the same node in the most recent commit of the .leo file to a VCS like git or bzr (currently only git and bzr supported), i.e. changes in the node since last commit. This does not work for derived @<files> (@auto, @edit, etc.), only nodes which are part of the Leo outline itself.
Common Usage¶
For those who don’t use marked nodes for much else, the ‘diff-marked’ option is probably the best. Mark two nodes and then execute ‘diff-marked’.
The ‘diff-subtree’ option is the second most common option, and makes a lot of sense for those who use clones regularly. Create an organizer node and clone your two nodes to be diffed under that organizer node, then select the organizer node and execute ‘diff-subtree’.
The ‘diff-selected’ option is for those who use the mouse. Using Ctrl+click or Shift+click, select exactly two nodes in the outline pane, and then execute ‘diff-selected’.
Scripting¶
nodediff.py can be used by scripts to run any of the three styles of diff. The following are available to scripts, and all of them take a list of two positions as input:
c.theNodeDiffController.run_compare()
c.theNodeDiffController.run_ndiff()
c.theNodeDiffController.run_unified_diff()
-
class
leo.plugins.nodediff.
NodeDiffController
(c)[source]¶ Bases:
object
-
run_diff_on_marked
(event=None)[source]¶ Runs a diff on the marked nodes. Will only work if exactly 2 marked nodes exist in the outline.
-
run_diff_on_saved
(event=None)[source]¶ run_diff_on_saved - compare current node content to saved content
Parameters: - event: Leo event
-
run_diff_on_selected
(event=None)[source]¶ Runs a diff on the selected nodes. Will only work if exactly two nodes are selected.
-
run_diff_on_subtree
(event=None)[source]¶ Runs a diff on the children of the currently selected node. Will only work if the node has exactly two children.
-
nodetags
Module¶
nodewatch
Module¶
notebook
Module¶
open_shell
Module¶
Creates an ‘Extensions’ menu containing two commands: Open Console Window and Open Explorer.
The Open Console Window command opens xterm on Linux. The Open Explorer command Opens a Windows explorer window.
This allows quick navigation to facilitate testing and navigating large systems with complex directories.
Please submit bugs / feature requests to etaekema@earthlink.net
Current limitations: - Not tested on Mac OS X … - On Linux, xterm must be in your path.
outline_export
Module¶
Modifies the way exported outlines are written.
paste_as_headlines
Module¶
Creates new headlines from clipboard text.
If the pasted text would be greater than 50 characters in length, the plugin truncates the headline to 50 characters and pastes the entire line into the body text of that node. Creates a “Paste as Headlines” option the Edit menu directly under the existing Paste option.
pluginsTest
Module¶
pretty_print
Module¶
Customizes pretty printing.
The plugin creates a do-nothing subclass of Leo’s tokenizing pretty printer. To customize, simply override in this file the methods of the base prettyPrinter class in leoBeautify.py. You would typically want to override putNormalToken or its allies. Templates for these methods have been provided. You may, however, override any methods you like. You could even define your own class entirely, provided you implement the prettyPrintNode method.
projectwizard
Module¶
python_terminal
Module¶
qtGui
Module¶
qt gui plugin.
qt_main
Module¶
qt_quicksearch
Module¶
qtframecommands
Module¶
quickMove
Module¶
quicksearch
Module¶
quit_leo
Module¶
Shows how to force Leo to quit.
read_only_nodes
Module¶
redirect_to_log
Module¶
Sends all output to the log pane.
rss
Module¶
Adds primitive RSS reader functionality to Leo.
By Jacob M. Peck.
RSS feeds¶
This plugin requires the python module ‘feedparser’ to be installed.
This plugin operates on RSS feed definitions, which are defined as nodes with headlines that start with @feed, and with bodies that contain a valid @url directive.
For example, the following is a valid feed definition:
@feed Hack a Day
@url http://feeds2.feedburner.com/hackaday/LgoM
Hack a Day's feed. Awesome tech stuff.
Each @feed node also stores a viewed history of previous stories, so that the next time the feed is parsed, you will only see new stories. This history can be reset with the rss-clear-etc commands below.
Important Note¶
This plugin currently doesn’t have any undo capability - any changes performed by the following commands are not undoable.
Configuration Settings¶
This plugin is configured with the following @settings:
Format string to provide datetime.time.strftime, to format entry dates. Defaults to ‘%Y-%m-%d %I:%M %p’ if not provided.
If True, newest entries are placed before older entries. If False, older entries are placed before newer entries.
The format of an entry headline, specified with various tokens. Defaults to ‘[<date>] <title>’ if not provided.
Valid tokens are:
Anything that isn’t a valid token is retained untouched, such as the square brackets in the default setting.
The body of this node will provide the structure of the body of parsed entry nodes. Empty lines should be denoted with ‘n’ on a line by itself. It defaults to the following, if not provided:
@url <link>
<title>
<date>
<summary>
Valid tokens are the same as for @string rss-headline-format. Any instance of ‘ ‘ on a line by itself is replaced with an empty line. All other strings that are not valid tokens are retained untouched, such as the @url directive in the default.
Commands¶
This plugin uses commands to operate on these @feed definitions. The following commands are available:
Parses the selected @feed node, creating entries for each story as children of the @feed node. Can be SLOW for large feeds.
Parses all @feed nodes in the current outline, creating entries for each story as children of the appropriate @feed nodes. Not recommended, as it can make Leo appear to be locked up while running.
Deletes all the children of the selected @feed node.
Deletes all children of all @feed nodes in the current outline.
Clears the selected @feed node’s viewed stories history.
Clears the viewed stories history of every @feed node in the current outline.
-
class
leo.plugins.rss.
RSSController
(c)[source]¶ Bases:
object
-
clear_all_feed_histories
(event=None)[source]¶ Clears the viewed stories history of every @feed node in the current outline.
-
clear_selected_feed_history
(event=None)[source]¶ Clears the selected @feed node’s viewed stories history.
-
delete_all_feed_stories
(event=None)[source]¶ Deletes all children of all @feed nodes in the current outline.
-
delete_selected_feed_stories
(event=None)[source]¶ Deletes all the children of the selected @feed node.
-
parse_all_feeds
(event=None)[source]¶ Parses all @feed nodes in the current outline, creating entries for each story as children of the appropriate @feed nodes. Not recommended, as it can make Leo appear to be locked up while running.
-
rst3
Module¶
run_nodes
Module¶
Runs a program and interface Leo through its input/output/error streams.
The double-click-icon-box command on a node whose headlines is @run ‘cmd args’ will execute the command. There are several other features, including @arg and @input nodes.
The run_nodes.py plugin introduce two new nodes that transform leo into a terminal. It was mostly intended to run compilers and debuggers while having the possibility to send messages to the program.
The double-click-icon-box command on a node whose headline is @run <command> <args> will launch <command> with the given arguments. It will also mark the node. # Terminates the argument list. @run # <comment> is also valid.
@in nodes are used to send input to the running process. Double clicking on the icon of an @in <message> node will append a “n” to <message> and write it to the program, no matter where the node is placed. If no @run node is active, nothing happens.
The body text of every child, in which the headlines do not begin with ‘@run’ or ‘@in’, will be appended to <command>, allowing you to add an unlimited number of arguments to <command>.
The output of the program is written in the log pane (Error output in red). When the program exit the node is set unmarked and the return value is displayed… When the enter key is pressed in the body pane of an active @run node the content of it body pane is written to the program and then emptied ready for another line of input. If the node have @run nodes in its descendants, they will be launched successively. (Unless one returned an exit code other than 0, then it will stop there)
By Alexis Gendron Paquette. Please send comments to the Leo forums.
screen_capture
Module¶
screencast
Module¶
screenshots
Module¶
script_io_to_body
Module¶
Sends output from the Execute Script command to the end of the body pane.
setHomeDirectory
Module¶
Sets g.app.homeDir to a hard-coded path.
sftp
Module¶
slideshow
Module¶
Supports slideshows in Leo outlines.
This plugin defines four new commands:
- next-slide-show: move to the start of the next slide show, or the first slide show if no slide show has been seen yet.
- prev-slide-show: move to the start of the previous slide show, or the first slide show if no slide show has been seen yet.
- next-slide: move to the next slide of a present slide show.
- prev-slide: move to the previous slide of the present slide show.
Slides shows consist of a root @slideshow node with descendant @slide nodes. @slide nodes may be organized via non-@slide nodes that do not appear in the slideshow.
All these commands ignore @ignore trees.
spydershell
Module¶
startfile
Module¶
Launches (starts) a file given by a headline when executing the double-click-icon-box
This plugin ignores headlines starting with an ‘@’. Uses the @folder path if the headline is under an @folder headline. Otherwise the path is relative to the Leo file.
This does not work on Linux, because os.startfile does not exist.
stickynotes
Module¶
stickynotes_plus
Module¶
swing_gui
Module¶
systray
Module¶
testRegisterCommand
Module¶
A plugin to test k.registerCommand.
textnode
Module¶
Supports @text nodes for reading and writing external files.
This plugin has been superceded by @edit nodes.
The @text node is for embedding text files in a leo node that won’t be saved with the leo file, and won’t contain any sentinel leo comments. Children of @text nodes are not saved with the derived file, though they will stay in the outline. When a outline is first loaded any @text nodes are filled with the contents of the text files on disk. To refresh the contents of an @text node, execute the double-click-icon-box command on the node.
threadutil
Module¶
timestamp
Module¶
If this plugin is enabled, the following node attributes will be managed: - str_ctime: creation time - str_mtime: time node was last modified - str_atime: time node contents were last viewed
-
leo.plugins.timestamp.
create_node_hook
(tag, keywords)[source]¶ Hooked to <create-node> = set all 3 timestamps to now
tkGui
Module¶
todo
Module¶
tomboy_import
Module¶
Allows imports of notes created in Tomboy / gnote.
Usage:
- Create a node with the headline ‘tomboy’
- Select the node, and do alt+x act-on-node
- The notes will appear as children of ‘tomboy’ node
- The next time you do act-on-node, existing notes will be updated (they don’t need to be under ‘tomboy’ node anymore) and new notes added.
trace_gc_plugin
Module¶
Traces changes to Leo’s objects at idle time.
trace_keys
Module¶
Traces keystrokes in the outline and body panes.
trace_tags
Module¶
Trace most common hooks, but not key, drag or idle hooks.
Return True if the plugin has loaded successfully.
valuespace
Module¶
Supports Leo scripting using per-Leo-outline namespaces.
Commands¶
This plugin supports the following commands:
Creates a tree whose root node is named ‘valuespace’ containing one child node for every entry in the namespace. The headline of each child is @@r <key>, where <key> is one of the keys of the namespace. The body text of the child node is the value for <key>.
Prints key/value pairs of the namespace.
Clears the namespace.
Scans the entire Leo outline twice, processing @=, @a and @r nodes.
Pass 1 evaluates all @= and @a nodes in the outline as follows:
@= (assignment) nodes should have headlines of the the form:
@= <var>
Pass 1 evaluates the body text and assigns the result to <var>.
@a (anchor) nodes should have headlines of one of two forms:
@a
@a <var>
The first form evaluates the script in the parent node of the @a node. Such bare @a nodes serve as markers that the parent contains code to be executed.
The second form evaluates the body of the parent of the @a node and assigns the result to <var>.
Important: Both forms of @a nodes support the following @x convention when evaluating the parent’s body text. Before evaluating the body text, pass1 scans the body text looking for @x lines. Such lines have two forms:
- @x <python statement>
Pass 1 executes <python statement>.
The second form spans multiple lines of the body text:
@x { python statements @x }
Pass 1 executes all the python statements between the @x { and the @x }
Assign block of text to variable:
@x =<var> { Some Text @x }
Pass 1 assigns the block of text to <var>. The type of value is SList, a special subclass of standard ‘list’ that makes operating with string lists convenient. Notably, you can do <var>.n to get the content as plain string.
A special case of this is the “list append” notation:
@x =<var>+ {
Some
Text
@x }
This assumes that <var> is a list, and appends the content as SList to this list. You will typically do ‘@x var = []’ earlier in the document to make this construct work.
<var> in all constructs above can be arbitrary expression that can be on left hand side of assignment. E.g. you can use foo.bar, foo[‘bar’], foo().bar etc.
Pass 2 “renders” all @r nodes in the outline into body text. @r nodes should have the form:
@r <expression>
Pass 2 evaluates <expression> and places the result in the body pane.
TODO: discuss SList expressions.
Evaluating expressions¶
All expression are evaluated in a context that predefines Leo’s c, g and p vars. In addition, g.vs is a dictionary whose keys are c.hash() and whose values are the namespaces for each commander. This allows communication between different namespaces, while keeping namespaces generally separate.
-
class
leo.plugins.valuespace.
ValueSpaceController
(c=None, ns=None)[source]¶ Bases:
object
A class supporting per-commander evaluation spaces containing @a, @r and @= nodes.
-
let
(var, val)[source]¶ Enter var into self.d with the given value. Both var and val must be strings.
-
viewrendered
Module¶
viewrendered2
Module¶
vim
Module¶
#@@language rest
Enables two-way communication with gVim (recommended) or Vim.
Commands¶
vim-open-file
- Opens the nearest ancestor @file or @clean node in vim. Leo will update the file in the outline when you save the file in vim.
vim-open-node
- Opens the selected node in vim. Leo will update the node in the outline when you save the file in vim.
Installation¶
Set the vim_cmd
and vim_exe
settings as shown below.
Alternatively, you can put gvim.exe is on your PATH.
Settings¶
@string vim_cmd
The command to execute to start gvim. Something like:
<path-to-gvim>/gvim --servername LEO
@string vim_exe
- The path to the gvim executable.
vim_plugin_uses_tab_feature
- True: Leo will put the node or file in a Vim tab card.
word_count
Module¶
Counts characters, words, lines, and paragraphs in the body pane.
It adds a “Word Count…” option to the bottom of the Edit menu that will activate the command.
wikiview
Module¶
word_export
Module¶
Adds the Plugins:Word Export:Export menu item to format and export the selected outline to a Word document, starting Word if necessary.
wxGui
Module¶
xemacs
Module¶
Allows you to edit nodes in emacs/xemacs.
Provides the emacs-open-node command which passes the body text of the node to emacs.
You may edit the node in the emacs buffer and changes will appear in Leo.
xml_edit
Module¶
Provides commands (Alt-x) for importing and exporting XML from a Leo
outline. These commands are to XML what @auto-rst
is to
reStructuredText.
xml2leo
imports an .xml file into the node following the currently
selected node. leo2xml
exports the current subtree to an .xml file
the user selects.
xml_validate
, if executed on the top node in the
Leo xml tree, reports any errors in XML generation or DTD validation,
based on the DTD referenced from the XML itself. If there’s no DTD
it reports that as an error.
leo2xml2leo
takes the selected Leo subtree representing an XML file,
converts it to XML internally, and then creates a new Leo subtree from
that XML after the original, with ‘NEW ‘ at the start of the top node’s
name. This updates all the headlines, so that the convenience only
previews (see below) are updated. The original can be deleted if the
new subtree seems correct.
Conventions¶
This is a valid XML file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dml SYSTEM "dml.dtd">
<?xml-stylesheet href="common.css"?>
<dml xmlns='http://example.com/' xmlns:other='http://other.com/'/>
<block type='example'>Here's <other:b>some</other:b> text</block>
</dml>
<!-- This is the last line -->
Note the processing instruction (xml-stylesheet), the DTD (DOCTYPE),
the trailing comment (after the closing tag), and the pernicious
mixed content (three separate pieces of text in the <block/>
element).
These commands attempt to deal with all of this.
A top level Leo node is created to hold these top level parts. Its headline is the basename of the file.
The xml declaration is placed in the body of this top level Leo node
Below that, in the same body text, appears a simple namespace map:
http://example.com/ other: http://other.com/ ...i.e. the default namespace first, and then any prefixed name spaces.
Below that, in the same body text, appears the
DOCTYPE
declarationChildren are added to this top level Leo node to represent the top level elements in the xml file. Headlines have the following meanings:
? pi-target some="other" __CHK
- i.e. questionmark, space, name of processing instruction target, start of processing instruction content. Only the questionmark, which indicates the processing instruction, and the first word, which indicates the processing instruction target, matter. The remainder is just a convenience preview of the processing instruction content, which is the Leo node’s body text.# This is *really* imp
- i.e. hash, space, start of comment content. Only the hash, which indicates the comment, matters. The remainder is just a convenience preview of the comment content, which is the Leo node’s body text.tagname name_attribute start of element text
- i.e. the name of an element followed by a convenience preview of the element’s text content. If the element has aname
attribute that’s included at the start of the text preview. Only the first word matters, it’s the name of the element.Element’s text is placed in the Leo node’s body. If the element has tailing text (the
" text"
tailing the<other:b/>
element in the above example), that occurs in the Leo node’s body separated by the tailing text sentinel:@________________________________TAIL_TEXT________________________________@Element’s attributes are stored in a dict
p.v.u['_XML']['_edit']
on the Leo node.'_XML'
is the uA prefix for these commands, and'_edit'
is used by theattrib_edit
plugin to identify attributes it should present to the user for editing. Theattrib_edit
plugin should be enabled and itsv.u mode
activated (through its submenu on the Plugins menu). The attribute edit panel initially appears as a tab in the log pane, although it can be moved around by right clicking on the pane dividers if theviewrendered
andfree_layout
plugins are enabled.
-
leo.plugins.xml_edit.
append_element
(xml_node, to_leo_node)[source]¶ handle appending xml_node which may be Element, Comment, or ProcessingInstruction. Recurses for Element.
-
leo.plugins.xml_edit.
cd_here
(c, p)[source]¶ attempt to cd to the directory in effect at p according to Leo’s @path concept
-
leo.plugins.xml_edit.
get_element
(leo_node)[source]¶ recursively read from leo nodes and write into an Element tree
-
leo.plugins.xml_edit.
get_tag
(xml_node, attrib=None)[source]¶ replace {http://full.name.space.com/}element with fns:element
-
leo.plugins.xml_edit.
leo2xml2leo
(event)[source]¶ wrapper to cycle leo->xml->leo, mostly to clean up headers
-
leo.plugins.xml_edit.
make_tag
(tag)[source]¶ replace fns:element with {http://full.name.space.com/}element
xsltWithNodes
Module¶
Adds the Outline:XSLT menu containing XSLT-related commands.
This menu contains the following items:
- Set StyleSheet Node:
- Selects the current node as the xsl stylesheet the plugin will use.
- Process Node with Stylesheet Node:
- Processes the current node as an xml document, resolving section references and Leo directives.
- Creates a sibling containing the results.
Requires 4Suite 1.0a3 or better, downloadable from http://4Suite.org.
-
leo.plugins.xsltWithNodes.
cleanString
(data)[source]¶ This method cleans a string up for the processor. It currently just removes leading and trailing whitespace
-
leo.plugins.xsltWithNodes.
doMinidomTest
(c)[source]¶ This def performs a simple test on a node. Can the data be successfully parsed by minidom or not? Results are output to the log.
-
leo.plugins.xsltWithNodes.
getString
(c)[source]¶ This def turns a node into a string using Leo’s file-nosent write logic.
-
leo.plugins.xsltWithNodes.
jumpToStyleNode
(c)[source]¶ Simple method that jumps us to the current XSLT node
zenity_file_dialogs
Module¶
Replaces the tk file dialogs on Linux with external calls to the zenity gtk dialog package.
This plugin is more a proof of concept demo than a useful tool. The dialogs presented do not take filters and starting folders can not be specified.
Despite this, some Linux users might prefer it to the tk dialogs.
-
leo.plugins.zenity_file_dialogs.
onStart2
(tag, keywords)[source]¶ Replace tkfile open/save method with external calls to zenity.
-
leo.plugins.zenity_file_dialogs.
runOpenFileDialog
(title=None, filetypes=None, defaultextension=None, multiple=False)[source]¶ Call zenity’s open file(s) dialog.
Subpackages¶
pygeotag Package¶
pygeotag
Module¶-
class
leo.plugins.pygeotag.pygeotag.
GeoTagRequestHandler
(request, client_address, server)[source]¶ Bases:
BaseHTTPServer.BaseHTTPRequestHandler
-
staticMap
= {'': 'template.html', 'jquery.js': 'jquery.js', 'jquery.json-2.2.min.js': 'jquery.json-2.2.min.js', 'map.js': 'map.js'}¶
-