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.