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.

add_callback(callback)[source]

Add a callback to be called at every idle time.

on_idle(timer)[source]

IdleTimeManager: Run all idle-time callbacks.

on_idle_count = 0
start()[source]

Start the idle-time timer.

class leo.core.leoApp.LeoApp[source]

Bases: object

A class representing the Leo application itself.

Ivars of this class are Leo’s global variables.

checkForOpenFile(c, fn)[source]

Warn if fn is already open and add fn to already_open_files list.

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.
cmd()[source]

Command decorator for the LeoApp class.

commanders()[source]

Return list of currently active controllers

computeSignon()[source]
createCursesGui(fileName='', verbose=False)[source]
createDefaultGui(fileName='', verbose=False)[source]

A convenience routines for plugins to create the default gui class.

createNullGuiWithScript(script=None)[source]
createQtGui(fileName='', verbose=False)[source]

A convenience routines for plugins to create the Qt gui class.

createTextGui(fileName='', verbose=False)[source]
createWxGui(fileName='', verbose=False)[source]

A convenience routines for plugins to create the wx gui class.

define_delegate_language_dict()[source]
define_extension_dict()[source]
define_global_constants()[source]
define_language_delims_dict()[source]
define_language_extension_dict()[source]
destroyAllOpenWithFiles()[source]

Remove temp files created with the Open With command.

destroyWindow(frame)[source]

Destroy all ivars in a Leo frame.

finishQuit()[source]
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.

init_at_auto_names()[source]

Init the app.atAutoNames set.

init_at_file_names()[source]

Init the app.atFileNames set.

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.

lockLog()[source]

Disable changes to the log

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.

onQuit(event=None)[source]

Exit Leo, prompting to save unsaved outlines first.

rememberOpenFile(fn)[source]
runAlreadyOpenDialog(c)[source]

Warn about possibly already-open files.

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.

selectLeoWindow(c)[source]
setGlobalDb()[source]

Create global pickleshare db

Usable by:

g.app.db['hello'] = [1,2,5]
setIDFile()[source]

Create leoID.txt.

setIDFromEnv(verbose)[source]

Set leoID from environment vars.

setIDFromFile(verbose)[source]

Attempt to set g.app.leoID from leoID.txt.

setIDFromSys(verbose)[source]

Attempt to set g.app.leoID from sys.leoID.

This might be set by in Python’s sitecustomize.py file.

setIdFromDialog()[source]

Get leoID from a dialog.

setLeoID(useDialog=True, verbose=True)[source]

Get g.app.leoID from various sources.

setLog(log)[source]

set the frame to which log messages will go

unlockLog()[source]

Enable changes to the log

writeWaitingLog(c)[source]

Write all waiting lines to the log.

class leo.core.leoApp.LoadManager[source]

Bases: object

A class to manage loading .leo files, including configuration files.

addOptionsToParser(parser)[source]
adjustSysPath()[source]

Adjust sys.path to enable imports as usual with Leo.

This method is no longer needed:

  1. g.importModule will import from the ‘external’ or ‘extensions’ folders as needed without altering sys.path.
  2. 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.

completeFileName(fileName)[source]
computeBindingLetter(kind)[source]
computeFilesList(options, fileName)[source]

Return the list of files on the command line.

computeGlobalConfigDir()[source]
computeHomeDir()[source]

Returns the user’s home directory.

computeHomeLeoDir()[source]
computeLeoDir()[source]
computeLeoSettingsPath()[source]

Return the full path to leoSettings.leo.

computeLoadDir()[source]

Returns the directory containing leo.py.

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.

computeMachineName()[source]

Return the name of the current machine, i.e, HOSTNAME.

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.

computeThemeFilePath()[source]

Return the absolute path to the theme .leo file.

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.

createDefaultSettingsDicts()[source]

Create lm.globalSettingsDict & lm.globalBindingsDict.

createGui(pymacs)[source]
createImporterData()[source]

Create the data structures describing importer plugins.

createMenu(c, fn=None)[source]
createSettingsDicts(c, localFlag, theme=False)[source]
createSpecialGui(gui, pymacs, script, windowFlag)[source]
createWritersData()[source]

Create the data structures describing writer plugins.

doDiff()[source]

Support –diff option after loading Leo.

doGuiOption(options)[source]
doLoadTypeOption(options)[source]
doPostPluginsInit()[source]

Create a Leo window for each file in the lm.files list.

doPrePluginsInit(fileName, pymacs)[source]

Scan options, set directories and read settings.

doScreenShotOption(options)[source]
doScriptOption(options, parser)[source]
doSimpleOptions(options)[source]

These args just set g.app ivars.

doWindowSizeOption(options)[source]
findOpenFile(fn)[source]
finishOpen(c)[source]
getDefaultFile()[source]
getPreviousSettings(fn)[source]

Return the settings in effect for fn. Typically, this involves pre-reading fn.

initApp(verbose)[source]
initFocusAndDraw(c, fileName)[source]
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.

isLeoFile(fn)[source]
isValidPython()[source]
isZippedFile(fn)[source]
load(fileName=None, pymacs=None)[source]

Load the indicated file

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.

make_screen_shot(fn)[source]

Create a screenshot of the present Leo outline and save it to path.

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.

openEmptyWorkBook()[source]

Open an empty frame and paste the contents of CheatSheet.leo into it.

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.

openLeoFile(fn)[source]
openLeoOrZipFile(fn)[source]
openSettingsFile(fn)[source]

Open a settings file with a null gui. Return the commander.

The caller must init the c.config object.

openZipFile(fn)[source]
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.

readGlobalSettingsFiles()[source]

Read leoSettings.leo and myLeoSettings.leo using a null gui.

readOpenedLeoFile(c, fn, readAtFileNodesFlag, theFile)[source]
reportDirectories(verbose)[source]

Report directories.

resolve_theme_path(fn, tag)[source]

Search theme directories for the given .leo file.

revertCommander(c)[source]

Revert c to the previously saved contents.

scanOptions(fileName, pymacs)[source]

Handle all options, remove them from sys.argv and set lm.options.

setStdStreams()[source]

Make sure that stdout and stderr exist. This is an issue when running Leo with pythonw.exe.

traceSettingsDict(d, verbose=False)[source]
traceShortcutsDict(d, verbose=False)[source]
uninvert(d)[source]

Uninvert an inverted shortcut dict whose keys are strokes, returning a dict whose keys are command names.

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.

appendToRecentFiles(files)[source]
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.

clearRecentFiles(c)[source]

Clear the recent files list, then add the present file.

createRecentFiles()[source]

Try to create .leoRecentFiles.txt, in the users home directory, or in Leo’s config directory if that fails.

createRecentFilesMenuItems(c)[source]
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.

getRecentFiles()[source]
getRecentFilesTable()[source]
readRecentFiles(localConfigFile)[source]

Read all .leoRecentFiles.txt files.

readRecentFilesFile(path)[source]
sanitize(name)[source]

Return a sanitized file name.

setRecentFiles(files)[source]

Update the recent files list.

sortRecentFiles(c)[source]

Sort the recent files list.

updateRecentFiles(fileName)[source]

Create the RecentFiles menu. May be called with Null fileName.

writeEditedRecentFiles(c)[source]

Write content of “edit_headline” node as recentFiles and recreates menues.

writeRecentFilesFile(c, force=False)[source]

Write the appropriate .leoRecentFiles.txt file.

Write a message if force is True, or if it hasn’t been written yet.

writeRecentFilesFileHelper(fileName)[source]
leo.core.leoApp.ctrlClickAtCursor(event)[source]

Simulate a control-click at the cursor.

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 Desktop

The default setting specifies no patterns.

leo.core.leoApp.disable_idle_time_events(event)[source]

Disable default idle-time event handling.

leo.core.leoApp.enable_idle_time_events(event)[source]

Enable default idle-time event handling.

leo.core.leoApp.join_leo_irc(event=None)[source]

Open the web page to Leo’s irc channel on freenode.net.

leo.core.leoApp.openUrl(event=None)[source]

Open the url in the headline or body text of the selected node.

Use the headline if it contains a valid url. Otherwise, look only at the first line of the body.

leo.core.leoApp.openUrlUnderCursor(event=None)[source]

Open the url under the cursor.

leo.core.leoApp.toggle_idle_time_events(event)[source]

Toggle default idle-time event handling.

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
appendToDocPart(s)[source]

Append the next line of the @doc part to docOut.

appendToOut(s)[source]

Append s to at.out (old sentinels) or at.v.tempBodyList (new sentinels).

asisWrite(root, toString=False)[source]
atDirective = 4
at_directive_kind_pattern = <_sre.SRE_Pattern object>
autoBeautify(p)[source]

Auto beautify p’s tree if allowed by settings and directives.

badEndSentinel(expectedKind)[source]

Handle a mismatched ending sentinel.

bodyIsInited(v)[source]

Return True if v.b has been inited.

bodySetInited(v)[source]

Indicate that v.b has been inited.

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.

checkPythonSyntax(p, body, supress=False)[source]
chmod(fileName, mode)[source]
clearAllBodyInited()[source]

Clear all v.b inited bits.

clearAllOrphanBits(p)[source]

Clear orphan bits for all nodes except orphan @file nodes.

closeStringFile(theFile)[source]
closeWriteFile()[source]
cmd()[source]

Command decorator for the AtFileCommands class.

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.

create(fn, s)[source]

Create a file whose contents are s.

createImportedNode(root, headline)[source]
createNewThinNode(gnx, headline, level)[source]

Create a new (new-style) vnode.

createResurrectedNodesNode()[source]

Create a ‘Resurrected Nodes’ node as the last top-level node.

createV5ThinNode(gnx, headline, level)[source]

Create a version 5 vnode.

defineDispatchDict()[source]

Return the dispatch dictionary used by scanText4.

defineResurrectedNodeCallback(r, root)[source]

Define a callback that moves node p as r’s last child.

deleteAllTempBodyStrings()[source]

Delete all temp attributes.

deleteTnodeList(p)[source]

Remove p’s tnodeList.

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’.

directiveKind4(s, i)[source]

Return the kind of at-directive or noDirective.

dispatch(ext, p)[source]

Return the correct writer function for p, an @auto node.

docDirective = 3
dump(lines, tag)[source]

Dump all lines.

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
error(*args)[source]
exception(message)[source]
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!

findReference(name, p)[source]

Find a reference to name. Raise an error if not found.

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.

getPathUa(p)[source]
handleChangedNode(new_body, old_body, p, thinFile)[source]

Set ancestor files dirty and support mod_labels plugin.

ignoreOldSentinel(s, unused_i)[source]

Ignore an 3.x sentinel.

importAtShadowNode(fn, p)[source]
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.

initFileName(fromString, importFileName, root)[source]

Return the fileName to be used in messages.

initReadIvars(root, fileName, importFileName=None, perfectImportRoot=None, atShadow=False)[source]
initReadLine(s)[source]

Init the ivars so that at.readLine will read all of s.

initScanText4(p)[source]

Init all ivars for at.scanText4().

initWriteIvars(root, targetFileName, atEdit=False, atShadow=False, forcePythonSentinels=False, nosentinels=False, toString=False)[source]
isFileLike(s)[source]

Return True if s has file-like sentinels.

isSectionName(s, i)[source]
isSignificantTree(p)[source]

Return True if p’s tree has a significant amount of information.

massageAtDocPart(s)[source]

Compute the final @doc part when block comments are used.

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
nodeSentinelText(p)[source]

Return the text of a @+node or @-node sentinel for p.

oblank()[source]
oblanks(n)[source]
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.

onl()[source]

Write a newline to the output stream.

onl_sent()[source]

Write a newline to the output stream, provided we are outputting sentinels.

openAtShadowFileForReading(fn)[source]

Open an @shadow for reading and return shadow_fn.

openFileForReading(fromString=False)[source]

Open the file given by at.root. This will be the private file for @shadow nodes.

openFileForWriting(root, fileName, toString)[source]
openFileForWritingHelper(fileName)[source]

Open the file and return True if all went well.

openFileHelper(fn)[source]

Open a file, reporting all exceptions.

openForWrite(filename, wb='wb')[source]

Open a file for writes, handling shadow files.

openStringFile(fn, encoding='utf-8')[source]
os(s)[source]

Write a string to the output stream.

All output produced by leoAtFile module goes here.

otabs(n)[source]
othersDirective = 7
outputStringWithLineEndings(s)[source]
parseLeoSentinel(s)[source]

Parse the sentinel line s. If the sentinel is valid, set at.encoding, at.readVersion, at.readVersion5.

parseNodeSentinel(s, i, middle)[source]
parseThinNodeSentinel(s, i)[source]
parseUnderindentTag(s)[source]
popSentinelStack(expectedKind)[source]

Pop an entry from endSentinelStack and check it.

printError(*args)[source]

Print an error message that may contain non-ascii characters.

promptForDangerousWrite(fileName, kind, message=None)[source]

Raise a dialog asking the user whether to overwrite an existing file.

putAfterLastRef(s, start, delta)[source]

Handle whatever follows the last ref of a line.

putAfterMiddleRef(s, delta)[source]

Handle whatever follows a ref that is not the last ref of a line.

putAtAllBody(p)[source]

Generate the body enclosed in sentinel lines.

putAtAllChild(p)[source]
putAtAllLine(s, i, p)[source]

Put the expansion of @all.

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.

putAtOthersChild(p)[source]
putAtOthersLine(s, i, p)[source]

Put the expansion of @others.

putBlankDocLine()[source]
putBody(p, fromString='')[source]

Generate the body enclosed in sentinel lines. Return True if the body contains an @others line.

putBuffered(s)[source]

Put s, converting all tabs to blanks as necessary.

putCloseNodeSentinel(p)[source]

End a node.

putCodeLine(s, i)[source]

Put a normal code line.

putDelims(directive, s, k)[source]

Put an @delims directive.

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.

putEndDocLine()[source]

Write the conclusion of a doc part.

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

putInitialComment()[source]
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.

putOpenLeoSentinel(s)[source]

Write @+leo sentinel.

putOpenNodeSentinel(p, inAtAll=False)[source]

Write @+node sentinel for p.

putPending(split)[source]

Write the pending part of a doc part.

We retain trailing whitespace iff the split flag is True.

putRefAt(name, ref, delta)[source]
putRefLine(s, i, n1, n2, name, p)[source]

Put a line containing one or more references.

putSentinel(s)[source]

Write a sentinel whose text is s, applying the CWEB hack if needed.

putStartDocLine(s, i, kind)[source]

Write the start of a doc part.

rawDirective = 9
read(root, importFileName=None, fromString=None, atShadow=False, force=False)[source]

Read an @thin or @file tree.

readAfterRef(s, i)[source]

Read an @afterref sentinel.

readAll(root, force=False)[source]

Scan positions, looking for @<file> nodes to read.

readAtShadowNodes(p)[source]

Read all @shadow nodes in the p’s tree.

readClone(s, i)[source]
readComment(s, i)[source]

Read an @comment sentinel.

readDelims(s, i)[source]

Read an @delims sentinel.

readDirective(s, i)[source]

Read an @@sentinel.

readEndAll(unused_s, unused_i)[source]

Read an @-all sentinel.

readEndAt(unused_s, unused_i)[source]

Read an @-at sentinel.

readEndDoc(unused_s, unused_i)[source]

Read an @-doc sentinel.

readEndLeo(unused_s, unused_i)[source]

Read an @-leo sentinel.

readEndMiddle(s, i)[source]

Read an @-middle sentinel.

readEndNode(unused_s, unused_i, middle=False)[source]

Handle old-style @-node sentinels. In the new scheme, only the post-pass terminates nodes.

readEndOthers(unused_s, unused_i)[source]

Read an @-others sentinel.

readEndRef(unused_s, unused_i)[source]

Read an @-<< sentinel.

readError(message)[source]
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:

  1. An @encoding directive, found by at.scanAllDirectives.
  2. 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++]

readNl(s, i)[source]

Handle an @nonl sentinel.

readNonl(s, i)[source]

Handle an @nonl sentinel.

readNormalLine(s, i=0)[source]
readOneAtAutoNode(fileName, p)[source]

Read an @auto file into p. Return the new position.

readOneAtCleanNode(root)[source]

Update the @clean/@nosent node at root.

readOneAtEditNode(fn, p)[source]
readOneAtShadowNode(fn, p, force=False)[source]
readOpenFile(root, fileName, deleteNodes=False)[source]

Read an open derived file. Leo 4.5 and later can only read 4.x derived files.

readPostPass(root, thinFile)[source]

Post-process all vnodes.

readRef(s, i)[source]

Handle an @<< sentinel.

readStartAll(s, i)[source]

Read an @+all sentinel.

readStartAt(s, i)[source]

Read an @+at sentinel.

readStartDoc(s, i)[source]

Read an @+doc sentinel.

readStartLeo(s, i)[source]

Read an unexpected @+leo sentinel.

readStartMiddle(s, i)[source]

Read an @+middle sentinel.

readStartNode(s, i, middle=False)[source]

Read an @+node or @+middle sentinel. This will terminate the previous node.

readStartOthers(s, i)[source]

Read an @+others sentinel.

readVerbatim(s, i)[source]

Read an @verbatim sentinel.

read_at_clean_lines(fn)[source]

Return all lines of the @clean/@nosent file at fn.

reloadSettings()[source]
rememberReadPath(fn, p)[source]

Remember the files that have been read and the full headline (@<file> type) that caused the read.

remove(fileName, verbose=True)[source]
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.

reportCorrection(old, new, v)[source]

Debugging only. Report changed perfect import lines.

runPyflakes(root, pyflakes_errors_only)[source]

Run pyflakes on the selected node.

saveOutlineIfPossible()[source]

Save the outline if only persistence data nodes are dirty.

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.

scanText4(fileName, p, verbose=False)[source]

Scan a 4.x derived file non-recursively.

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}
sentinelKind4(s)[source]

Return the kind of sentinel at s.

sentinelKind4_helper(s)[source]
sentinelName(kind)[source]

Returns the name of the sentinel for warnings..

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.

setPathUa(p, path)[source]
setTargetFileName(root, toString)[source]

Set the target file name for at.write.

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)
skipIndent(s, i, width)[source]
skipSentinelStart4(s, i)[source]

Skip the start of a sentinel.

skipToEndSentinel(s, i)[source]

Skip to the end of the sentinel line.

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.

syntaxError(p, body)[source]

Report a syntax error.

tabNannyNode(p, body, suppress=False)[source]
terminateBody(v, postPass=False)[source]

Terminate scanning of body text for node v. Set v.b.

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.

warnAboutOrphandAndIgnoredNodes()[source]
warnOnReadOnlyFile(fn)[source]
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.

writeAsisNode(p)[source]

Write the p’s node to an @asis file.

writeAtAutoNodes(event=None)[source]

Write all @auto nodes in the selected outline.

writeAtAutoNodesHelper(toString=False, writeDirtyOnly=True)[source]

Write @auto nodes in the selected outline

writeAtShadowNodes(event=None)[source]

Write all @shadow nodes in the selected outline.

writeAtShadowNodesHelper(toString=False, writeDirtyOnly=True)[source]

Write @shadow nodes in the selected outline

writeDirtyAtAutoNodes(event=None)[source]

Write all dirty @auto nodes in the selected outline.

writeDirtyAtShadowNodes(event=None)[source]

Write all dirty @shadow nodes in the selected outline.

writeError(message=None)[source]

Issue an error while writing an @<file> node.

writeException(root=None)[source]
writeFromString(root, s, forcePythonSentinels=True, useSentinels=True)[source]

Write a 4.x derived file from a string.

This is at.write specialized for scripting.

writeMissing(p, toString=False)[source]
writeMissingNode(p)[source]
writeOneAtAutoNode(p, force=False, toString=False, trialWrite=False)[source]

Write p, an @auto node. File indices must have already been assigned.

writeOneAtEditNode(p, toString, force=False)[source]

Write one @edit node.

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.

writer_for_at_auto(root)[source]

A factory returning a writer function for the given kind of @auto directive.

writer_for_ext(ext)[source]

A factory returning a writer function for the given file extension.

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.

adjustSysPath()[source]

Adjust sys.path to enable imports as usual with Leo.

completeFileName(fileName)[source]
createFrame(fileName)[source]

Create a commander and frame for the given file. Create a new frame if the fileName is empty or non-exisent.

createGui()[source]
globals()[source]

Return a fully initialized leoGlobals module.

initLeo()[source]

Init the Leo app to which this class gives access. This code is based on leo.run().

isOpen()[source]

Return True if the bridge is open.

isValidPython()[source]
openLeoFile(fileName)[source]

Open a .leo file, or create a new Leo frame if no fileName is given.

reportDirectories()[source]
leo.core.leoBridge.controller(gui='nullGui', loadPlugins=True, readSettings=True, silent=False, tracePlugins=False, verbose=False)[source]

Create an singleton instance of a bridge controller.

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.

leo.core.leoBridgeTest.main()[source]

The main line of leoBridgeTest.py.

leo.core.leoBridgeTest.runUnitTests(c, g)[source]

Run all the unit tests from the leoBridge.

leo.core.leoBridgeTest.scanOptions()[source]

Handle all options and remove them from sys.argv.

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.

clearCache()[source]

Clear the cache for the open window.

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.

commit(close=True)[source]
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).

getCachedGlobalFileRatios()[source]
getCachedStringPosition()[source]
getCachedWindowPositionDict(fn)[source]

Return a dict containing window positions.

initFileDB(fn)[source]
initGlobalDB()[source]
makeCacheList(p)[source]

Create a recursive list describing a tree for use by createOutlineFromCacheList.

readFile(fileName, root)[source]

Read the file from the cache if possible. Return (s,ok,key)

reportIfNodeChanged(child_tuple, child_v, fileName, parent_v)[source]

Schedule a recovered node if child_v is substantially different from an earlier version.

Issue a (rare) warning if two different files are involved.

save(fn, changeName)[source]
setCachedGlobalsElement(fn)[source]
setCachedStringPosition(str_pos)[source]
test()[source]
warning(s)[source]

Print a warning message in red.

writeFile(p, fileKey)[source]

Update the cache after reading the file.

class leo.core.leoCache.PickleShareDB(root)[source]

Bases: object

The main ‘connection’ object for PickleShare database

clear(verbose=False)[source]
get(key, default=None)[source]
has_key(key)[source]
items()[source]
keys(globpat=None)[source]

Return all keys in DB, or all keys matching a glob

uncache(*items)[source]

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.

class leo.core.leoCache.SqlitePickleShare(root)[source]

Bases: object

The main ‘connection’ object for SqlitePickleShare database

clear(verbose=False)[source]
get(key, default=None)[source]
has_key(key)[source]
init_dbtables(conn)[source]
items()[source]
keys(globpat=None)[source]

Return all keys in DB, or all keys matching a glob

reset_protocol_in_values()[source]
uncache(*items)[source]

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.

chapterSelectHelper(w=None, selectEditor=True)[source]
findEditorInChapter(p)[source]

return w, an editor displaying position p.

findPositionInChapter(p1, strict=False)[source]

Return a valid position p such that p.v == v.

findRootNode()[source]

Return the @chapter node for this chapter.

positionIsInChapter(p)[source]
select(w=None, selectEditor=True)[source]

Restore chapter information and redraw the tree when a chapter is selected.

unselect()[source]

Remember chapter info when a chapter is about to be unselected.

class leo.core.leoChapters.ChapterController(c)[source]

Bases: object

A per-commander controller that manages chapters and related nodes.

backChapter(event=None)[source]
cmd()[source]

Command decorator for the ChapterController class.

createIcon()[source]

Create chapter-selection Qt ListBox in the icon area.

error(s)[source]
findAnyChapterNode()[source]

Return True if the outline contains any @chapter node.

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.

finishCreate()[source]

Create the box in the icon area.

getChapter(name)[source]
getSelectedChapter()[source]
inChapter()[source]
makeCommand(chapterName, binding=None)[source]

Make chapter-select-<chapterName> command.

nextChapter(event=None)[source]
note(s, killUnitTest=False)[source]
parseHeadline(p)[source]

Return the chapter name and key binding for p.h.

reloadSettings()[source]
sanitize(s)[source]

Convert s to a safe chapter name.

selectChapter(event=None)[source]

Use the minibuffer to get a chapter name, then create the chapter.

selectChapter1(event)[source]
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.

selectChapterForPosition(p, chapter=None)[source]

Select a chapter containing position p. New in Leo 4.11: prefer the given chapter if possible. Do nothing if p if p does not exist or is in the presently selected chapter.

Note: this code calls c.redraw() if the chapter changes.

setAllChapterNames()[source]

Called early and often to discover all chapter names.

warning(s)[source]

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.

add_command(menu, **keys)[source]
alert(message)[source]
allNodes_iter()

A generator return all positions of the outline, in outline order.

all_nodes()[source]

A generator returning all vnodes in the outline, in outline order.

all_positions()[source]

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_nodes()[source]

A generator returning each vnode of the outline.

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.

appendStringToBody(p, s)[source]
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).

beginUpdate()[source]

Deprecated: does nothing.

bodyWantsFocus()[source]
bodyWantsFocusNow()[source]
bringToFront(c2=None, set_focus=True)[source]
canClone()[source]
canContractAllHeadlines()[source]

Contract all nodes in the tree.

canContractAllSubheads()[source]
canContractParent()[source]
canContractSubheads()[source]
canCutOutline()
canDehoist()[source]

Return True if do-hoist should be enabled in a menu. Should not be used in any other context.

canDeleteHeadline()[source]
canDemote()[source]
canExpandAllHeadlines()[source]

Return True if the Expand All Nodes menu item should be enabled.

canExpandAllSubheads()[source]
canExpandSubheads()[source]
canExtract()[source]
canExtractSection()[source]
canExtractSectionNames()
canFindMatchingBracket()[source]
canGoToNextDirtyHeadline()[source]
canGoToNextMarkedHeadline()[source]
canHoist()[source]

Return True if hoist should be enabled in a menu. Should not be used in any other context.

canMarkChangedHeadlines()[source]
canMarkChangedRoots()[source]
canMoveOutlineDown()[source]
canMoveOutlineLeft()[source]
canMoveOutlineRight()[source]
canMoveOutlineUp()[source]
canPasteOutline(s=None)[source]
canPromote()[source]
canRedo()[source]
canSelectThreadBack()[source]
canSelectThreadNext()[source]
canSelectVisBack()[source]
canSelectVisNext()[source]
canShiftBodyLeft()[source]
canShiftBodyRight()
canSortChildren()[source]
canSortSiblings()[source]
canUndo()[source]
canUnmarkAll()[source]
checkAllPythonCode(event=None, unittest=False, ignoreAtIgnore=True)[source]

Check all nodes in the selected tree for syntax and tab errors.

checkBatchOperationsList(aList)[source]
checkDrag(root, target)[source]

Return False if target is any descendant of root.

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.

Check the consistency of all links in the outline.

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.

checkParentAndChildren(p)[source]

Check consistency of parent and child data structures.

checkPythonCode(event=None, unittest=False, ignoreAtIgnore=True, suppressErrors=False, checkOnSave=False)[source]

Check the selected tree for syntax and tab errors.

checkPythonNode(p, unittest=False, suppressErrors=False)[source]
checkSiblings(p)[source]

Check the consistency of next and back links.

Check consistency of threadNext & threadBack links.

check_event(event)[source]

Check an event object.

clearAllMarked()[source]
clearAllVisited()[source]
clearMarked(p)[source]
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
computeWindowTitle(fileName)[source]

Set the window title and fileName.

contractAllHeadlines(event=None, redrawFlag=True)[source]

Contract all nodes in the outline.

contractSubtree(p)[source]
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.

disable_redraw()[source]

Disable all redrawing until enabled.

doBatchOperations(aList=None)[source]
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.

dragAfter(p, after)[source]
dragCloneAfter(p, after)[source]
dragCloneToNthChildOf(p, parent, n)[source]
dragToNthChildOf(p, parent, n)[source]
dumpPosition(p)[source]

Dump position p and it’s ancestors.

edit_widget(p)[source]
enable_redraw()[source]
endEditing()[source]
endUpdate(flag=True)[source]

Request a redraw of the screen if flag is True.

executeAnyCommand(command, event)[source]

Execute a command, no matter how defined.

Supports @g.commander_command and @g.new_cmd_decorator and plain methods.

executeMinibufferCommand(commandName)[source]
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.

executeScriptHelper(args, define_g, define_name, namespace, script)[source]
expandAllAncestors(p)[source]

Expand all ancestors without redrawing. Return a flag telling whether a redraw is needed.

expandSubtree(v)[source]
expandToLevel(level)[source]
fileName()[source]
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.

firstVisible()[source]

Move to the first visible node of the present chapter or hoist.

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.

getNodePath(p)[source]

Return the path in effect at node p.

getSelectedPositions()[source]

Get list (PosList) of currently selected positions

So far only makes sense on qt gui (which supports multiselection)

getTabWidth(p)[source]

Return the tab width in effect at p.

getTime(body=True)[source]
get_focus()[source]
get_requested_focus()[source]
git_diff(rev1='HEAD', rev2='', directory=None)[source]
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.

hasAmbiguousLanguage(p)[source]

Return True if p.b contains different @language directives.

hash()[source]
idle_focus_count = 0
idle_focus_helper(tag, keys)[source]

An idle-tme handler that ensures that focus is somewhere.

initAfterLoad()[source]

Provide an offical hook for late inits of the commander.

initCommandIvars()[source]

Init ivars used while executing a command.

initConfigSettings()[source]

Init all cached commander config settings.

initDebugIvars()[source]

Init Commander debugging ivars.

initDocumentIvars()[source]

Init per-document ivars.

initEventIvars()[source]

Init ivars relating to gui events.

initFileIvars(fileName, relativeFileName)[source]

Init file-related ivars of the commander.

initObjectIvars()[source]
initObjects(gui)[source]
initOptionsIvars()[source]

Init Commander ivars corresponding to user options.

initSettings(previousSettings)[source]

Init the settings before initing the objects.

init_error_dialogs()[source]
initialFocusHelper()[source]
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: ‘])
interactive1(callback, event, prompts)[source]
interactive2(callback, event, prompts)[source]
interactive3(callback, event, prompts)[source]
invalidateFocus()[source]

Indicate that the focus is in an invalid location, or is unknown.

isChanged()[source]
isCurrentPosition(p)[source]
isRootPosition(p)[source]
is_unusual_focus(w)[source]

Return True if w is not in an expected place.

lastTopLevel()[source]

Return the last top-level position in the outline.

lastVisible()[source]

Move to the last visible node of the present chapter or hoist.

last_unusual_focus = None
logWantsFocus()[source]
logWantsFocusNow()[source]
looksLikeDerivedFile(fn)[source]

Return True if fn names a file that looks like an external file written by Leo.

markAllAtFileNodesDirty(event=None)[source]

Mark all @file nodes as changed.

markAtFileNodesDirty(event=None)[source]

Mark all @file nodes in the selected tree as changed.

minibufferWantsFocus()[source]
minibufferWantsFocusNow()[source]
navHelper(p, ch, extend)[source]
navQuickKey()[source]

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.

notValidInBatchMode(commandName)[source]
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.

os_path_finalize(path, **keys)[source]
os_path_finalize_join(*args, **keys)[source]
outerUpdate()[source]

Handle delayed focus requests and modified events.

p

commander current position property

positionExists(p, root=None, trace=False)[source]

Return True if a position exists in c’s tree

printCommandsDict()[source]
putHelpFor(s, short_title='')[source]

Helper for various help commands.

raise_error_dialogs(kind='read')[source]

Warn abouit read/write failures.

recolor(**kwargs)[source]
recolorCommand(event=None)[source]

Force a full recolor.

recolor_now(**kwargs)
recreateGnxDict()[source]

Recreate the gnx dict prior to refreshing nodes from disk.

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.
redirectScriptOutput()[source]
redraw(p=None, setFocus=False)[source]

Redraw the screen immediately.

redrawAndEdit(p, selectAll=False, selection=None, keepMinibuffer=False)[source]

Redraw the screen and edit p’s headline.

redraw_after_contract(p=None, setFocus=False)[source]
redraw_after_expand(p=None, setFocus=False)[source]
redraw_after_head_changed()[source]

Redraw the screen (if needed) when editing ends. This may be a do-nothing for some gui’s.

redraw_after_icons_changed()[source]

Update the icon for the presently selected node

redraw_after_select(p)[source]

Redraw the screen after node p has been selected.

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.

registerReloadSettings(obj)[source]

Enter object into c.configurables.

relativeFileName()[source]
reloadConfigurableSettings()[source]

Call all reloadSettings method in c.subcommanders, c.configurables and other known classes.

request_focus(w)[source]
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.

scanAtRootDirectives(aList)[source]

Scan aList for @root-code and @root-doc directives.

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.

setBodyString(p, s)[source]
setChanged(changedFlag=True, redrawFlag=True)[source]

Set or clear the marker that indicates that the .leo file has been changed.

setCloneFindByPredicateIcon(iconPath, p)[source]

Attach an icon to p.v.u.

setComplexCommand(commandName)[source]

Make commandName the command to be executed by repeat-complex-command.

setCurrentDirectoryFromContext(p)[source]
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.

setFileTimeStamp(fn)[source]

Update the timestamp for fn..

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.

setLog()[source]
setMarked(p)[source]
setPositionAfterSort(sortChildren)[source]
setRootPosition(unused_p=None)[source]

Set c._rootPosition.

setRootVnode(v)[source]
setTopPosition(p)[source]

Set the root positioin.

setTopVnode(p)

Set the root positioin.

setWindowPosition()[source]
set_focus(w, force=False)[source]
shortFileName()[source]
shortFilename()
shouldBeExpanded(p)[source]

Return True if the node at position p should be expanded.

syntaxErrorDialog()[source]

Warn about syntax errors in files.

tabNannyNode(p, headline, body, unittest=False, suppressErrors=False)[source]

Check indentation using tabnanny.

topPosition()[source]

Return the root position.

topVnode()

Return the root position.

traceFocus(w)[source]
trace_idle_focus(w)[source]

Trace the focus for w, minimizing chatter.

treeFocusHelper()[source]
treeSelectHelper(p)[source]
treeWantsFocus()[source]
treeWantsFocusNow()[source]
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.

unredirectScriptOutput()[source]
updateBodyPane(head, middle, tail, undoType, oldSel, oldYview, preserveSel=False)[source]

Handle changed text in the body pane.

updateSyntaxColorer(v)[source]
validateOutline(event=None)[source]
visLimit()[source]

Return the topmost visible node. This is affected by chapters and hoists.

vnode2allPositions(v)[source]

Given a VNode v, find all valid positions p such that p.v = v.

Not really all, just all for each of v’s distinct immediate parents.

vnode2position(v)[source]

Given a VNode v, construct a valid position p such that p.v = v.

widgetWantsFocus(w)[source]
widgetWantsFocusNow(w)[source]
widget_name(widget)[source]
writeScriptFile(script)[source]
leo.core.leoCommands.cmd(name)[source]

Command decorator for the Commands class.

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.

compare_directories(path1, path2)[source]
compare_files(name1, name2)[source]
compare_lines(s1, s2)[source]
compare_list_of_files(aList1)[source]
compare_open_files(f1, f2, name1, name2)[source]
compare_two_files(name1, name2)[source]

A helper function.

doOpen(name)[source]
dump(tag, s)[source]
dumpToEndOfFile(tag, f, s, line, printTrailing)[source]
filecmp(f1, f2)[source]
isLeoHeader(s)[source]
isSentinel(s, sentinelComment)[source]
openOutputFile()[source]
show(s)[source]
showIvars()[source]
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.

compute_dicts(c1, c2)[source]

Compute inserted, deleted, changed dictionaries.

create_compare_node(c1, c2, d, kind)[source]

Create nodes describing the changes.

create_file_node(diff_list, fn1, fn2)[source]

Create an organizer node for the file.

create_root(aList)[source]

Create the top-level organizer node describing all the diffs.

diff_list_of_files(aList, visible=True)[source]

The main entry point for scripts.

diff_two_files(fn1, fn2)[source]

Create an outline describing the git diffs for fn.

find_gnx(c, gnx)[source]

Return a position in c having the given gnx.

finish()[source]

Finish execution of this command.

get_file(path)[source]

Return the contents of the file whose path is given.

make_diff_outlines(c1, c2)[source]

Create an outline-oriented diff from the outlines c1 and c2.

open_outline(fn)[source]

Find the commander for fn, creating a new outline tab if necessary.

Using open commanders works because we always read entire .leo files.

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.

leo.core.leoCompare.diff_leo_files_helper(event, title, visible)[source]

Prompt for a list of .leo files to open.

leo.core.leoCompare.go()[source]

leoConfig Module

leoDebugger Module

Per-commander debugging class.

class leo.core.leoDebugger.leoDebugger(c)[source]

Bases: pdb.Pdb

Leo’s debugger class: a thin wrapper around Python’s pdb class.

leo.core.leoDebugger.set_trace(c)[source]

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.

leo.core.leoDynamicTest.main()[source]

Run a dynamic test using the Leo bridge.

leo.core.leoDynamicTest.runUnitTests(c, g)[source]
leo.core.leoDynamicTest.scanOptions()[source]

Handle all options and remove them from sys.argv.

leoEditCommands Module

leoFileCommands Module

Classes relating to reading and writing .leo files.

exception leo.core.leoFileCommands.BadLeoFile(message)[source]

Bases: exceptions.Exception

class leo.core.leoFileCommands.FileCommands(c)[source]

Bases: object

A class creating the FileCommands subcommander.

archivedPositionToPosition(s)[source]
assignFileIndices()[source]

Assign a file index to all tnodes

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()

canonicalTnodeIndex(index)[source]

Convert Tnnn to nnn, leaving gnx’s unchanged.

checkLeoFile(event=None)[source]

The check-leo-file command.

checkPaste(parent, p)[source]

Return True if p may be pasted as a child of parent.

cleanSaxInputString(s)[source]

Clean control characters from s. s may be a bytes or a (unicode) string.

cmd()[source]

Command decorator for the FileCommands class.

compactFileIndices()

Assign a file index to all tnodes

compute_attribute_bits(forceWrite, p)[source]

Return the initial values of v’s attributes.

createActualFile(fileName, toOPML, toZip)[source]
createBackupFile(fileName)[source]

Create a closed backup file and copy the file to it, but only if the original file exists.

createSaxChildren(sax_node, parent_v)[source]

Create vnodes for all children in sax_node.children.

createSaxVnode(sax_node, parent_v)[source]

Create a vnode, or use an existing vnode.

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.

deleteFileWithMessage(fileName, unused_kind)[source]
dumpSaxTree(root, dummy)[source]
encodePosition(p)[source]

New schema for encoding current position hopefully simplier one.

exportDbVersion(conn)[source]
exportGeomToSqlite(conn)[source]
exportHashesToSqlite(conn)[source]
exportToSqlite(fileName)[source]

Dump all vnodes to sqlite database. Returns True on success.

exportVnodesToSqlite(conn, rows)[source]
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().

getLeoFileHelper(theFile, fileName, silent)[source]

Read the .leo file and create the outline.

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.

getPosFromClipboard(s)[source]
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.

getVnodeFromClipboard(s)[source]
getWindowGeometryFromDb(conn)[source]
handleNodeConflicts()[source]

Create a ‘Recovered Nodes’ node for each entry in c.nodeConflictList.

handleTnodeSaxAttributes(sax_node, v)[source]
handleVnodeSaxAttributes(sax_node, v)[source]

The native attributes of <v> elements are a, t, vtag, tnodeList, marks, expanded, and descendentTnode/VnodeUnknownAttributes.

handleWriteLeoFileException(fileName, backupName, theActualFile)[source]
initIvars()[source]

Init ivars of the FileCommands class.

initNewDb(conn)[source]

Initializes tables and returns None

initReadIvars()[source]
isReadOnly(fileName)[source]
linkChildrenToParents(p)[source]

Populate the parent links in all children of p.

openLeoFile(theFile, fileName, readAtFileNodesFlag=True, silent=False)[source]

Open a Leo file.

parse_leo_file(theFile, inputFileName, silent, inClipboard, s=None)[source]
pickle(torv, val, tag)[source]

Pickle val and return the hexlified result.

prepareDbTables(conn)[source]
propegateDirtyNodes()[source]
put(s)[source]

Put string s to self.outputFile. All output eventually comes here.

putClipboardHeader()[source]
putDescendentAttributes(p)[source]
putDescendentVnodeUas(p)[source]

Return the a uA field for descendent VNode attributes, suitable for reconstituting uA’s for anonymous vnodes.

putFindSettings()[source]
putGlobals()[source]
putHeader()[source]
putLeoFile()[source]
putLeoOutline(p=None)[source]

Return a string, not unicode, encoded with self.leo_file_encoding, suitable for pasting to the clipboard.

putPostlog()[source]
putPrefs()[source]
putProlog()[source]

Put the prolog of the xml file.

putReferencedTnodes()[source]

Put all referenced tnodes.

putSavedMessage(fileName)[source]
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.

putTnode(v)[source]
putTnodes()[source]

Puts all tnodes as required for copy or save commands

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.

putVnode(p, isIgnore=False)[source]

Write a <v> element corresponding to a VNode.

putVnodes(p=None)[source]

Puts all <v> elements in the order in which they appear in the outline.

putXMLLine()[source]

Put the properly encoded <?xml> element.

put_dquote()[source]
put_dquoted_bool(b)[source]
put_flag(a, b)[source]
put_in_dquotes(a)[source]
put_nl()[source]
put_tab()[source]
put_tabs(n)[source]
readAtFileNodes()[source]
readExternalFiles(fileName)[source]

Read all external files.

readOutlineOnly(theFile, fileName)[source]
readSaxFile(theFile, fileName, silent, inClipboard, reassignIndices, s=None)[source]

Read the entire .leo file using the sax parser.

reassignAllIndices(p)[source]

Reassign all indices in p’s subtree.

resolveArchivedPosition(archivedPosition, root_v)[source]

Return a VNode corresponding to the archived position relative to root node root_v.

resolveTnodeLists()[source]

Called before reading external files.

restoreDescendentAttributes()[source]
retrieveVnodesFromDb(conn)[source]

Recreates tree from the data contained in table vnodes. This method follows behavior of readSaxFile.

save(fileName, silent=False)[source]
saveAs(fileName)[source]
saveTo(fileName, silent=False)[source]
save_ref()[source]

Saves reference outline file

setDefaultDirectoryForNewFiles(fileName)[source]

Set c.openDirectory for new files for the benefit of leoAtFile.scanAllDirectives.

setPositionsFromVnodes()[source]
setReferenceFile(fileName)[source]
updateFixedStatus()[source]
updateFromRefFile()[source]

Updates public part of outline from the specified file.

updateSaxClone(sax_node, parent_v, v)[source]

Update the body text of v. It overrides any previous body text.

warnOnReadOnlyFiles(fileName)[source]
writeAllAtFileNodesHelper()[source]

Write all @<file> nodes and set orphan bits.

writeAtFileNodes(event=None)[source]

Write all @file nodes in the selected outline.

writeAtShadowNodes(event=None)[source]

Write all @file nodes in the selected outline.

writeDirtyAtFileNodes(event=None)[source]

Write all changed @file Nodes.

writeDirtyAtShadowNodes(event=None)[source]

Write all changed @shadow Nodes.

writeMissingAtFileNodes(event=None)[source]

Write all @file nodes for which the corresponding external file does not exist.

writeOutlineOnly(event=None)[source]

Write the entire outline without writing any derived files.

writeToFileHelper(fileName, toOPML)[source]
writeToStringHelper(fileName)[source]
writeZipFile(s)[source]
write_LEO_file(fileName, outlineOnlyFlag, toString=False, toOPML=False)

Write the .leo file.

write_Leo_file(fileName, outlineOnlyFlag, toString=False, toOPML=False)[source]

Write the .leo file.

exception leo.core.leoFileCommands.InvalidPaste[source]

Bases: exceptions.Exception

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.

characters(content)[source]

Handle the characters element.

clean(s)[source]
endDocument()[source]
endElement(name)[source]

Handle the end of any xml element.

endElementNS(unused_name, unused_qname)[source]
endTnode()[source]

Handle the end of a <tnode> element.

endVH()[source]

Handle the end of a <vh> element.

endVnode()[source]

Handle the end of a <vnode> element.

error(message)[source]
getRootNode()[source]
getWindowPositionAttributes(attrs)[source]
ignorableWhitespace(unused_whitespace)[source]
inElement(name)[source]
printStartElement(name, attrs)[source]
processingInstruction(target, data)[source]

sax: handle an xml processing instruction. We expect the target to be ‘xml-stylesheet’.

skippedEntity(name)[source]
startDocument()[source]
startElement(name, attrs)[source]
startElementNS(unused_name, unused_qname, unused_attrs)[source]
startGlobals(attrs)[source]
startLeoHeader(unused_attrs)[source]
startTnode(attrs)[source]
startVH(unused_attrs)[source]
startVnode(attrs)[source]
startVnodes(unused_attrs)[source]
startWinPos(attrs)[source]
tnodeAttributes(attrs)[source]
vnodeAttributes(attrs)[source]
class leo.core.leoFileCommands.SaxNodeClass[source]

A class representing one <v> element.

Use getters to access the attributes, properties and rules of this mode.

dump()[source]

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.

abortSearch()[source]

Restore the original position and selection.

addChangeStringToLabel()[source]

Add an unprotected change string to the minibuffer label.

addFindStringToLabel(protect=True)[source]
backwardsHelper(s, i, j, pattern, nocase, word)[source]
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.

change(event=None)[source]
changeAll()[source]
changeAllButton(event=None)[source]

Handle Replace All button.

changeAllCommand(event=None)[source]
changeButton(event=None)[source]

Handle Change button.

changeCommand(event=None)[source]

Handle replace command.

changeSelection()[source]
changeThenFind()[source]
changeThenFindButton(event=None)[source]

Handle Change, Then Find button.

changeThenFindCommand(event=None)[source]

Handle the replace-then-find command.

checkArgs()[source]
cloneFindAllCommand(event=None)[source]
cloneFindAllFlattenedCommand(event=None)[source]
cloneFindTag(tag)[source]

Handle the clone-find-tag command.

cmd()[source]

Command decorator for the findCommands class.

computeFindOptions()[source]

Return the status line as two strings.

computeFindOptionsInStatusArea()[source]
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.

createFindAllNode(result)[source]

Create a “Found All” node as the last node of the outline.

createFindUniqueNode()[source]

Create a “Found Unique” node as the last node of the outline.

debugIndices = []
doCloneFindAll(after, data, flatten, p, undoType)[source]

Handle the clone-find-all command, from p to after.

doCloneFindAllHelper(clones, count, flatten, p, skip)[source]

Handle the cff or cfa at node p.

doFindAll(after, data, p, undoType)[source]

Handle the find-all command from p to after.

doWrap()[source]

Return the position resulting from a wrap.

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.

endSearch()[source]
escapeCommand(event)[source]

Return the escaped command to execute.

findAll(clone_find_all=False, clone_find_all_flattened=False)[source]
findAllButton(event=None)[source]

Handle Find All button.

findAllCommand(event=None)[source]
findButton(event=None)[source]

Handle pressing the “Find” button in the find panel.

findDef(event=None)[source]

Find the def or class under the cursor.

findDefHelper(event, defFlag)[source]

Find the definition of the class, def or var under the cursor.

findEscapes()[source]

Return the keystrokes corresponding to find-next & find-prev commands.

findNext(initFlag=True)[source]

Find the next instance of the pattern.

findNextBatchMatch(p)[source]

Find the next batch match at p.

findNextCommand(event=None)[source]

The find-next command.

findNextMatch()[source]

Resume the search where it left off.

findPrevCommand(event=None)[source]

Handle F2 (find-previous)

findPreviousButton(event=None)[source]

Handle the Find Previous button.

findVar(event=None)[source]

Find the var under the cursor.

finishCreate()[source]
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.

focusToFind(event=None)[source]
generalChangeHelper(find_pattern, change_pattern, changeAll=False)[source]
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.

getStrokes(commandName)[source]
helpForFindCommands(event=None)[source]

Called from Find panel. Redirect.

hideFindTab(event=None)[source]

Hide the Find tab.

iSearch(again=False)[source]

Handle the actual incremental search.

iSearchBackspace()[source]
iSearchStateHandler(event)[source]

The state manager when the state is ‘isearch

initBatchCommands()[source]

Init for find-all and replace-all commands.

initBatchText(ins=None)[source]

Init s_ctrl from self.p and ins at the beginning of a search.

initFindDef(event)[source]

Init the find-def command. Return the word to find or None.

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.

init_s_ctrl(s, ins)[source]

Init the contents of s_ctrl from s and ins.

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.
lastStateHelper()[source]
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.

matchWord(s, i, pattern)[source]

Do a whole-word search.

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.

minibufferCloneFindAll1(event)[source]
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.

minibufferCloneFindAllFlattened1(event)[source]
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.

minibufferCloneFindTag1(event)[source]
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.

minibufferTagChildren1(event)[source]
nextNodeAfterFail(p)[source]

Return the next node after a failed search or None.

openFindTab(event=None, show=True)[source]

Open the Find tab in the log pane.

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.

passedWrapPoint(p, pos, newpos)[source]

Return True if the search has gone beyond the wrap point.

plainHelper(s, i, j, pattern, nocase, word)[source]

Do a plain search.

pop()[source]
precompilePattern()[source]

Precompile the regexp pattern if necessary.

preloadFindPattern(w)[source]

Preload the find pattern from the selected text of widget w.

printLine(line, allFlag=False)[source]
push(p, i, j, in_headline)[source]
reSearch1(event)[source]
reSearchBackward(event)[source]
reSearchForward(event)[source]
regexHelper(s, i, j, pattern, backwards, nocase)[source]
reloadSettings()[source]

LeoFind.reloadSettings.

replace(event=None)
replaceBackSlashes(s)[source]

Carefully replace backslashes in a search pattern.

resetWrap(event=None)[source]
reset_state_ivars()[source]

Reset ivars related to suboutline-only and wrapped searches.

restore(data)[source]

Restore the screen and clear state after a search fails.

restoreAfterFindDef()[source]

Restore find settings in effect before a find-def command.

restoreAllExpansionStates(expanded, redraw=False)[source]

expanded is a set of gnx of nodes that should be expanded

returnToOrigin(event)[source]
save()[source]

Save everything needed to restore after a search fails.

saveBeforeFindDef(p)[source]

Save the find settings in effect before a find-def command.

search()[source]

Search s_ctrl for self.find_text with present options. Returns (pos, newpos) or (None,None).

search1(event)[source]
searchBackward(event)[source]
searchForward(event)[source]
searchHelper(s, i, j, pattern)[source]

Dispatch the proper search method based on settings.

searchWithPresentOptions(event, findAllFlag=False, findAllUniqueFlag=False, changeAllFlag=False)[source]

Open the search pane and get the search string.

searchWithPresentOptions1(event)[source]
setFindDefOptions(p)[source]

Set the find options needed for the find-def command.

setFindScope(where)[source]

Set the radio buttons to the given scope

setFindScopeEveryWhere(event=None)[source]

Set the ‘Entire Outline’ radio button in the Find tab.

setFindScopeNodeOnly(event=None)[source]

Set the ‘Node Only’ radio button in the Find tab.

setFindScopeSuboutlineOnly(event=None)[source]

Set the ‘Suboutline Only’ radio button in the Find tab.

setReplaceString(event)[source]

A state handler to get the replacement string.

setReplaceString1(event)[source]
setReplaceString2(event)[source]
setWidget()[source]
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.

setupChangePattern(pattern)[source]
setupSearchPattern(pattern)[source]
setup_button()[source]

Init a search started by a button in the Find panel.

setup_command()[source]
shouldStayInNode(p)[source]

Return True if the find should simply switch panes.

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.

showFindOptionsInStatusArea()[source]

Show find options in the status area.

showStatus(found)[source]

Show the find status the Find dialog, if present, and the status line.

showSuccess(pos, newpos, showState=True)[source]

Display the result of a successful find operation.

startIncremental(event, commandName, forward, ignoreCase, regexp)[source]
startSearch(event)[source]
stateZeroHelper(event, prefix, handler, escapes=None)[source]
switchStyle(word)[source]

Switch between camelCase and underscore_style function defintiions. Return None if there would be no change.

tagChildren(tag)[source]

Handle the clone-find-tag command.

toggleFindCollapesNodes(event)[source]

Toggle the ‘Collapse Nodes’ checkbox in the find tab.

toggleIgnoreCaseOption(event)[source]

Toggle the ‘Ignore Case’ checkbox in the Find tab.

toggleMarkChangesOption(event)[source]

Toggle the ‘Mark Changes’ checkbox in the Find tab.

toggleMarkFindsOption(event)[source]

Toggle the ‘Mark Finds’ checkbox in the Find tab.

toggleOption(checkbox_name)[source]
toggleRegexOption(event)[source]

Toggle the ‘Regexp’ checkbox in the Find tab.

toggleSearchBodyOption(event)[source]

Set the ‘Search Body’ checkbox in the Find tab.

toggleSearchHeadlineOption(event)[source]

Toggle the ‘Search Headline’ checkbox in the Find tab.

toggleWholeWordOption(event)[source]

Toggle the ‘Whole Word’ checkbox in the Find tab.

toggleWrapSearchOption(event)[source]

Toggle the ‘Wrap Around’ checkbox in the Find tab.

updateChangeList(s)[source]
updateFindList(s)[source]
update_ivars()[source]

Update ivars from the find panel.

wordSearch1(event)[source]
wordSearchBackward(event)[source]
wordSearchForward(event)[source]
class leo.core.leoFind.SearchWidget(*args, **keys)[source]

Bases: object

A class to simulating high-level interface widget.

delete(i, j=None)[source]
getAllText()[source]
getInsertPoint()[source]
getSelectionRange()[source]
insert(i, s)[source]
setAllText(s)[source]
setInsertPoint(i, s=None)[source]
setSelectionRange(i, j, insert=None)[source]
toPythonIndex(i)[source]

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.

dump()[source]
isModeBinding()[source]
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.

get(key, theDefault=None)[source]
ivars()[source]
keys()[source]
toString()[source]
leo.core.leoGlobals.CheckVersion(s1, s2, condition='>=', stringCompare=None, delimiter='.', trace=False)[source]
leo.core.leoGlobals.CheckVersionToInt(s)[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:

@g.command(‘command-name’) def command_name(self, *args, **kwargs):

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.

clear()[source]
close()[source]
flush()[source]
get()[source]
getvalue()
read()
readline()[source]

Read the next line using at.list and at.ptr.

write(s)[source]
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/

backup_issues(base_url, c, label_list, root, state=None)[source]
get_all_issues(label_list, root, state, limit=100)[source]

Get all issues for the base url.

get_issues(base_url, label_list, milestone, root, state)[source]

Create a list of issues for each label in label_list.

get_one_issue(label, state, limit=20)[source]

Create a list of issues with the given label.

get_one_page(label, page, r, root)[source]
print_header(r)[source]
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.

dump()[source]

Show results of printable chars.

finalize_binding(binding)[source]
finalize_char(s)[source]

Perform very-last-minute translations on bindings.

find(pattern)[source]
find_mods(s)[source]

Return the list of all modifiers seen in s.

isAltCtrl()[source]

Return True if this is an Alt-Ctrl character.

isFKey()[source]
isNumPadKey()[source]
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.

isPlainNumPad()[source]
lower()[source]
prettyPrint()[source]
removeNumPadModifier()[source]
startswith(s)[source]
strip_mods(s)[source]

Remove all modifiers from s, without changing the case of s.

strip_shift(s)[source]

Handle supposedly shifted keys.

User settings might specify an already-shifted key, which is not an error.

The legacy Tk binding names have already been translated, so we don’t have to worry about Shift-ampersand, etc.

toGuiChar()[source]

Replace special chars by the actual gui char.

toInsertableChar()[source]

Convert self to an (insertable) char.

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.

back_scan_comment(s, i)[source]

Return the index of the character after a comment.

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.

find_matching_bracket(ch1, s, i)[source]

Find the bracket matching s[i] for self.language.

is_regex(s, i)[source]

Return true if there is another slash on the line.

oops(s)[source]

Report an error in the match-brackets command.

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.

scan(ch1, target, s, i)[source]

Scan forward for target.

scan_back(ch1, target, s, i)[source]

Scan backwards for delim.

scan_comment(s, i)[source]

Return the index of the character after a comment.

scan_regex(s, i)[source]

Scan a regex (or regex substitution for perl).

scan_string(s, i)[source]

Scan the string starting at s[i] (forward or backward). Return the index of the next character.

starts_comment(s, i)[source]

Return True if s[i] starts a comment.

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.
dump(sort=False, verbose=False)[source]
removeClones(aList)[source]
select(pat, regex=False, removeClones=True)[source]

Return a new PosList containing all positions in self that match the given pattern.

class leo.core.leoGlobals.ReadLinesClass(s)[source]

Bases: object

A class whose next method provides a readline method for Python’s tokenize module.

next()[source]
class leo.core.leoGlobals.RedirectClass[source]

Bases: object

A class to redirect stdout and stderr to Leo’s log pane.

flush(*args)[source]
isRedirected()[source]
rawPrint(s)[source]
redirect(stdout=1)[source]
undirect(stdout=1)[source]
write(s)[source]
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.

bad_pattern(pattern)[source]

Report a bad Sherlock pattern.

check_pattern(pattern)[source]

Give an error and return False for an invalid pattern.

dispatch(frame, event, arg)[source]

The dispatch method.

do_call(frame, unused_arg)[source]

Trace through a function call.

do_line(frame, arg)[source]

print each line of enabled functions.

do_return(frame, arg)[source]

Trace a return statement.

fn_is_enabled(fn, patterns)[source]

Return True if tracing for fn is enabled. Used only to enable statistics for fn.

format_ret(arg)[source]

Format arg, the value returned by a “return” statement.

get_args(frame)[source]

Return name=val for each arg in the function call.

get_full_name(locals_, name)[source]

Return class_name::name if possible.

is_enabled(fn, name, patterns=None)[source]

Return True if tracing for name in fn is enabled.

pop()[source]

Restore the pushed patterns.

print_stats(patterns=None)[source]

Print all accumulated statisitics.

push(patterns)[source]

Push the old patterns and set the new.

run(frame=None)[source]

Trace from the given frame or the caller’s frame.

set_patterns(patterns)[source]

Set the patterns in effect.

show(item)[source]

return the best representation of item.

stop()[source]

Stop all tracing.

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()

computeName(frame)[source]
report()[source]
stop()[source]
tracer(frame, event, arg)[source]

A function to be passed to sys.settrace.

updateStats(name)[source]
class leo.core.leoGlobals.TypedDict(name, keyType, valType)[source]

Bases: object

A class containing a name and enforcing type checking.

add(key, val)[source]
copy(name=None)[source]

Return a new dict with the same contents.

dump()[source]
get(key, default=None)[source]
get_setting(key)[source]
get_string_setting(key)[source]
keys()[source]
name()[source]
replace(key, val)[source]
setName(name)[source]
update(d)[source]
class leo.core.leoGlobals.TypedDictOfLists(name, keyType, valType)[source]

Bases: leo.core.leoGlobals.TypedDict

A class whose values are lists of typed values.

copy(name=None)[source]

Return a new dict with the same contents.

exception leo.core.leoGlobals.UiTypeException[source]

Bases: exceptions.Exception

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.angleBrackets(s)[source]
leo.core.leoGlobals.assertUi(uitype)[source]
leo.core.leoGlobals.assert_is(obj, list_or_class, warn=True)[source]
leo.core.leoGlobals.backupGitIssues(c, base_url=None)[source]

Get a list of issues from Leo’s GitHub site.

leo.core.leoGlobals.blue(*args, **keys)[source]
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.caller(i=1)[source]

Return the caller name i levels up the stack.

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.chdir(path)[source]
leo.core.leoGlobals.checkOpenDirectory(c)[source]
leo.core.leoGlobals.checkUnchangedIvars(obj, d, exceptions=None)[source]
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.choose(cond, a, b)[source]

(Deprecated) simulate “a if cond else b”

leo.core.leoGlobals.clearAllIvars(o)[source]

Clear all ivars of o, a member of some class.

leo.core.leoGlobals.clearStats()[source]
leo.core.leoGlobals.cls(event=None)[source]

Clear the screen.

leo.core.leoGlobals.collectGarbage()[source]
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.computeGlobalConfigDir()[source]
leo.core.leoGlobals.computeHomeDir()[source]
leo.core.leoGlobals.computeLeadingWhitespace(width, tab_width)[source]
leo.core.leoGlobals.computeLeadingWhitespaceWidth(s, tab_width)[source]
leo.core.leoGlobals.computeLeoDir()[source]
leo.core.leoGlobals.computeLoadDir()[source]
leo.core.leoGlobals.computeMachineName()[source]
leo.core.leoGlobals.computeStandardDirectories()[source]
leo.core.leoGlobals.computeWidth(s, tab_width)[source]
leo.core.leoGlobals.computeWindowTitle(fileName)[source]
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.createScratchCommander(fileName=None)[source]
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.defaultLeoFileExtension(c=None)[source]
leo.core.leoGlobals.dictToString(d, indent='', tag=None)[source]

Pretty print a Python dict to a string.

leo.core.leoGlobals.disableIdleTimeHook()[source]

Disable the global idle-time hook.

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.dummy_act_on_node(c, p, event)[source]
leo.core.leoGlobals.dump(s)[source]
leo.core.leoGlobals.dump_encoded_string(encoding, s)[source]

Dump s, assumed to be an encoded string.

leo.core.leoGlobals.ecnl(tabName='Log')[source]
leo.core.leoGlobals.ecnls(n, tabName='Log')[source]
leo.core.leoGlobals.enableIdleTimeHook(*args, **keys)[source]

Enable idle-time processing.

leo.core.leoGlobals.enable_gc_debug(event=None)[source]
leo.core.leoGlobals.enl(tabName='Log')[source]
leo.core.leoGlobals.ensureLeadingNewlines(s, n)[source]
leo.core.leoGlobals.ensureTrailingNewlines(s, n)[source]
leo.core.leoGlobals.ensure_extension(name, ext)[source]
leo.core.leoGlobals.error(*args, **keys)[source]
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.esDiffTime(message, start)[source]
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_dump(s, n=30, title=None)[source]
leo.core.leoGlobals.es_error(*args, **keys)[source]
leo.core.leoGlobals.es_event_exception(eventName, full=False)[source]
leo.core.leoGlobals.es_exception(full=True, c=None, color='red')[source]
leo.core.leoGlobals.es_exception_type(c=None, color='red')[source]
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_error(*args, **keys)[source]
leo.core.leoGlobals.es_print_exception(full=True, c=None, color='red')[source]

Print exception info about the last exception.

leo.core.leoGlobals.es_trace(*args, **keys)[source]
leo.core.leoGlobals.escaped(s, i)[source]
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.executeFile(filename, options='')[source]
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.fileFilters(key)[source]
leo.core.leoGlobals.fileLikeObject

alias of leo.core.leoGlobals.FileLikeObject

leo.core.leoGlobals.file_date(theFile, format=None)[source]
leo.core.leoGlobals.findLanguageDirectives(c, p)[source]

Return the language in effect at position p.

leo.core.leoGlobals.findNodeAnywhere(c, headline, exact=True)[source]
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.findTestScript(c, h, where=None, warn=True)[source]
leo.core.leoGlobals.findTopLevelNode(c, headline, exact=True)[source]
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_on_line(s, i, pattern)[source]
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.getBaseDirectory(c)[source]

Convert ‘!’ or ‘.’ to proper directory references.

leo.core.leoGlobals.getDocString(s)[source]

Return the text of the first docstring found in s.

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.getHandlersForTag(tags)[source]
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.getLastTracebackFileAndLineNumber()[source]
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.getLoadedPlugins()[source]
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.getPluginModule(moduleName)[source]
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.getTestVars()[source]
leo.core.leoGlobals.getTime()[source]
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.get_leading_ws(s)[source]

Returns the leading whitespace of ‘s’.

leo.core.leoGlobals.get_line(s, i)[source]
leo.core.leoGlobals.get_line_after(s, i)[source]
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.glob_glob(pattern)[source]

Return the regularized glob.glob(pattern)

leo.core.leoGlobals.goto_last_exception(c)[source]

Go to the line given by sys.last_traceback.

leo.core.leoGlobals.guessExternalEditor(c=None)[source]

Return a ‘sensible’ external editor

leo.core.leoGlobals.handleScriptException(c, p, script, script1)[source]
leo.core.leoGlobals.handleUnl(unl, c)[source]

Handle a Leo UNL. This must never open a browser.

leo.core.leoGlobals.handleUrl(url, c=None, p=None)[source]

Open a url or a unl.

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.idleTimeHookHandler(timer)[source]

This function exists for compatibility.

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.internalError(*args)[source]

Report a serious interal error in Leo.

leo.core.leoGlobals.isBindingInfo(obj)[source]
leo.core.leoGlobals.isBytes(s)[source]

Return True if s is Python3k bytes type.

leo.core.leoGlobals.isCallable(obj)[source]
leo.core.leoGlobals.isDirective(s)[source]

Return True if s starts with a directive.

leo.core.leoGlobals.isGeneralSetting(obj)[source]
leo.core.leoGlobals.isInt(obj)[source]

Return True if obj is an int or a long.

leo.core.leoGlobals.isList(s)[source]

Return True if s is a list.

leo.core.leoGlobals.isMacOS()[source]
leo.core.leoGlobals.isString(s)[source]

Return True if s is any string, but not bytes.

leo.core.leoGlobals.isStroke(obj)[source]
leo.core.leoGlobals.isStrokeOrNone(obj)[source]
leo.core.leoGlobals.isTextWidget(w)[source]
leo.core.leoGlobals.isTextWrapper(w)[source]
leo.core.leoGlobals.isTypedDict(obj)[source]
leo.core.leoGlobals.isTypedDictOfLists(obj)[source]
leo.core.leoGlobals.isUnicode(s)[source]

Return True if s is a unicode string.

leo.core.leoGlobals.isValidEncoding(encoding)[source]

Return True if the encooding is valid.

leo.core.leoGlobals.isValidUrl(url)[source]

Return true if url looks like a valid url.

leo.core.leoGlobals.isWordChar(ch)[source]

Return True if ch should be considered a letter.

leo.core.leoGlobals.isWordChar1(ch)[source]
leo.core.leoGlobals.is_binary_external_file(fileName)[source]
leo.core.leoGlobals.is_binary_file(f)[source]
leo.core.leoGlobals.is_binary_string(s)[source]
leo.core.leoGlobals.is_c_id(ch)[source]
leo.core.leoGlobals.is_nl(s, i)[source]
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.is_ws(c)[source]
leo.core.leoGlobals.is_ws_or_nl(s, i)[source]
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.joinLines(aList)[source]
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.loadOnePlugin(pluginName, verbose=False)[source]
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.log_to_file(s, fn=None)[source]

Write a message to ~/test/leo_log.txt.

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.makePathRelativeTo(fullPath, basePath)[source]
leo.core.leoGlobals.match(s, i, pattern)[source]
leo.core.leoGlobals.match_c_word(s, i, name)[source]
leo.core.leoGlobals.match_ignoring_case(s1, s2)[source]
leo.core.leoGlobals.match_word(s, i, pattern)[source]
leo.core.leoGlobals.module_date(mod, format=None)[source]
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.note(*args, **keys)[source]
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.oldDump(s)[source]
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.optimizeLeadingWhitespace(line, tab_width)[source]
leo.core.leoGlobals.os_path_abspath(path)[source]

Convert a path to an absolute path.

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_exists(path)[source]

Return True if path exists.

leo.core.leoGlobals.os_path_expandExpression(s, **keys)[source]

Expand all {{anExpression}} in c’s context.

leo.core.leoGlobals.os_path_expanduser(path)[source]

wrap os.path.expanduser

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_getmtime(path)[source]

Return the modification time of path.

leo.core.leoGlobals.os_path_getsize(path)[source]

Return the size of path.

leo.core.leoGlobals.os_path_isabs(path)[source]

Return True if path is an absolute path.

leo.core.leoGlobals.os_path_isdir(path)[source]

Return True if the path is a directory.

leo.core.leoGlobals.os_path_isfile(path)[source]

Return True if path is a file.

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_normcase(path)[source]

Normalize the path’s case.

leo.core.leoGlobals.os_path_normpath(path)[source]

Normalize the path.

leo.core.leoGlobals.os_path_normslashes(path)[source]
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.os_path_split(path)[source]
leo.core.leoGlobals.os_path_splitext(path)[source]
leo.core.leoGlobals.os_startfile(fname)[source]
leo.core.leoGlobals.pause(s)[source]
leo.core.leoGlobals.pdb(message='')[source]

Fall into pdb.

leo.core.leoGlobals.pep8_class_name(s)[source]

Return the proper class name for s.

leo.core.leoGlobals.pluginIsLoaded(fn)[source]
leo.core.leoGlobals.plugin_date(plugin_mod, format=None)[source]
leo.core.leoGlobals.plugin_signon(module_name, verbose=False)[source]
leo.core.leoGlobals.plural(obj)[source]

Return “s” or “” depending on n.

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.prettyPrintType(obj)[source]
leo.core.leoGlobals.printDict(obj, indent='', printCaller=False, tag=None)

Pretty print any Python object using g.pr.

leo.core.leoGlobals.printDiffTime(message, start)[source]
leo.core.leoGlobals.printEntireTree(c, tag='')[source]
leo.core.leoGlobals.printGc(tag=None)[source]
leo.core.leoGlobals.printGcAll(tag='')[source]
leo.core.leoGlobals.printGcObjects(tag='')[source]

Print newly allocated objects.

leo.core.leoGlobals.printGcRefs(tag='')[source]
leo.core.leoGlobals.printGcSummary(tag='')[source]
leo.core.leoGlobals.printGcVerbose(tag='')[source]
leo.core.leoGlobals.printGlobals(message=None)[source]
leo.core.leoGlobals.printLeoModules(message=None)[source]
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.printStack()[source]
leo.core.leoGlobals.printStats(name=None)[source]
leo.core.leoGlobals.printTuple(obj, indent='', printCaller=False, tag=None)

Pretty print any Python object using g.pr.

leo.core.leoGlobals.print_bindings(name, window)[source]
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.rawPrint(s)[source]
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.readlineForceUnixNewline(f, fileName=None)[source]
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.red(*args, **keys)[source]
leo.core.leoGlobals.redirectStderr()[source]
leo.core.leoGlobals.redirectStdout()[source]
leo.core.leoGlobals.registerExclusiveHandler(tags, fn)[source]
leo.core.leoGlobals.registerHandler(tags, fn)[source]
leo.core.leoGlobals.regularizeTrailingNewlines(s, kind)[source]

Kind is ‘asis’, ‘zero’ or ‘one’.

leo.core.leoGlobals.removeBlankLines(s)[source]
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.removeLeadingBlankLines(s)[source]
leo.core.leoGlobals.removeLeadingWhitespace(s, first_ws, tab_width)[source]
leo.core.leoGlobals.removeTrailing(s, chars)[source]

Remove all characters in chars from the end of s.

leo.core.leoGlobals.removeTrailingWs(s)[source]
leo.core.leoGlobals.replace_path_expression(c, expr)[source]

local function to replace a single path expression.

leo.core.leoGlobals.restoreStderr()[source]
leo.core.leoGlobals.restoreStdout()[source]
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.scanAllAtPathDirectives(c, p)[source]
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.scanAtEncodingDirectives(aList)[source]

Scan aList for @encoding directives.

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.scanAtPathDirectives(c, aList)[source]
leo.core.leoGlobals.scanAtRootDirectives(aList)[source]

Scan aList for @root directives.

leo.core.leoGlobals.scanAtRootOptions(s, i, err_flag=False)[source]
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.scanDirectives(c, p=None)[source]
leo.core.leoGlobals.scanError(s)[source]

Bump the error count in the tangle command.

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.scanf(s, pat)[source]
leo.core.leoGlobals.setDefaultDirectory(c, p, importing=False)[source]

Return a default directory by scanning @path directives.

leo.core.leoGlobals.setGlobalOpenDir(fileName)[source]
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)[source]

Return the base name of a path.

leo.core.leoGlobals.shortFilename(fileName, n=None)

Return the base name of a path.

leo.core.leoGlobals.skip_blank_lines(s, i)[source]
leo.core.leoGlobals.skip_block_comment(s, i)[source]
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_c_id(s, i)[source]
leo.core.leoGlobals.skip_heredoc_string(s, i)[source]
leo.core.leoGlobals.skip_id(s, i, chars=None)[source]
leo.core.leoGlobals.skip_leading_ws(s, i, ws, tab_width)[source]
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_line(s, i)[source]
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_nl(s, i)[source]

Skips a single “logical” end-of-line character.

leo.core.leoGlobals.skip_non_ws(s, i)[source]
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_pascal_block_comment(s, i)[source]
leo.core.leoGlobals.skip_pascal_braces(s, i)[source]
leo.core.leoGlobals.skip_pascal_string(s, i)[source]
leo.core.leoGlobals.skip_pp_directive(s, i)[source]
leo.core.leoGlobals.skip_pp_if(s, i)[source]
leo.core.leoGlobals.skip_pp_part(s, i)[source]
leo.core.leoGlobals.skip_python_string(s, i, verbose=True)[source]
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.skip_to_char(s, i, ch)[source]
leo.core.leoGlobals.skip_to_end_of_line(s, i)[source]
leo.core.leoGlobals.skip_to_semicolon(s, i)[source]
leo.core.leoGlobals.skip_to_start_of_line(s, i)[source]
leo.core.leoGlobals.skip_typedef(s, i)[source]
leo.core.leoGlobals.skip_ws(s, i)[source]
leo.core.leoGlobals.skip_ws_and_nl(s, i)[source]
leo.core.leoGlobals.sleep(n)[source]

Wait about n milliseconds.

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.startTracer(limit=0, trace=False, verbose=False)[source]
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.stdErrIsRedirected()[source]
leo.core.leoGlobals.stdOutIsRedirected()[source]
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.stripBlankLines(s)[source]
leo.core.leoGlobals.stripBrackets(s)[source]

Same as s.lstrip(‘<’).rstrip(‘>’) except it works for Python 2.2.1.

leo.core.leoGlobals.stripPathCruft(path)[source]

Strip cruft from a path name.

leo.core.leoGlobals.timeSince(start)[source]
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.toUnicodeFileEncoding(path)[source]
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.trace(*args, **keys)[source]

Print a tracing message.

leo.core.leoGlobals.traceUrl(c, path, parsed, url)[source]
leo.core.leoGlobals.translateArgs(args, d)[source]

Return the concatenation of s and all args,

with odd args translated.

leo.core.leoGlobals.translateString(s)[source]

Return the translated text of s.

leo.core.leoGlobals.truncate(s, n)[source]

Return s truncated to n characters.

leo.core.leoGlobals.tupleToString(obj, indent='', tag=None)[source]

Pretty print a Python tuple to a string.

leo.core.leoGlobals.u(s)[source]

Return s, converted to unicode from Qt widgets.

leo.core.leoGlobals.ue(s, encoding)[source]
leo.core.leoGlobals.unCamel(s)[source]

Return a list of sub-words in camelCased string s.

leo.core.leoGlobals.unloadOnePlugin(moduleOrFileName, verbose=False)[source]
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.unregisterHandler(tags, fn)[source]
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.ustr(s)[source]

Define the pyzo ustr function.

leo.core.leoGlobals.utils_chmod(fileName, mode, verbose=True)[source]
leo.core.leoGlobals.utils_remove(fileName, verbose=True)[source]
leo.core.leoGlobals.utils_rename(c, src, dst, verbose=True)[source]

Platform independent rename.

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)
leo.core.leoGlobals.warning(*args, **keys)[source]
leo.core.leoGlobals.windows()[source]
leo.core.leoGlobals.wrap_lines(lines, pageWidth, firstLineWidth=None)[source]

Returns a list of lines, consisting of the input lines wrapped to the given pageWidth.

leoGui Module

leoIPython Module

leoImport Module

class leo.core.leoImport.FreeMindImporter(c)[source]

Bases: object

Importer class for FreeMind (.mmap) files.

add_children(parent, element)[source]

parent is the parent position, element is the parent element. Recursively add all the child elements as descendants of parent_p.

create_outline(path)[source]

Create a tree of nodes from a FreeMind file.

import_file(path)[source]

The main line of the FreeMindImporter class.

import_files(files)[source]

Import a list of FreeMind (.mmap) files.

prompt_for_files()[source]

Prompt for a list of FreeMind (.mm.html) files and import them.

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.

create_nodes(parent, parent_d)[source]

Create the tree of nodes rooted in parent.

create_outline(path)[source]
scan(s, parent)[source]

Create an outline from a MindMap (.csv) file.

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.

appendHeadRef(p, file_name, head_ref, result)[source]
appendRefToFileName(file_name, result)[source]
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.

cSharpUnitTest(p, fileName=None, s=None, showTree=False)[source]
cUnitTest(p, fileName=None, s=None, showTree=False)[source]
coffeeScriptUnitTest(p, fileName=None, s=None, showTree=False)[source]
compute_unit_test_kind(ext, fn)[source]

Return kind from fn’s file extension.

convertCodePartToWeb(s, i, p, result)[source]

# Headlines not containing a section reference are ignored in noweb and generate index index in cweb.

convertDocPartToWeb(s, i, result)[source]
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.

copyPart(s, i, result)[source]
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.

createOutlineFromWeb(path, parent)[source]
cstCanonicalize(s, lower=True)[source]
cstDump()[source]
cstEnter(s)[source]
cstLookup(target)[source]
ctextUnitTest(p, fileName=None, s=None, showTree=False)[source]
dartUnitTest(p, fileName=None, s=None, showTree=False)[source]
defaultImporterUnitTest(p, fileName=None, s=None, showTree=False)[source]
dispatch(ext, p)[source]

Return the correct scanner function for p, an @auto node.

elispUnitTest(p, fileName=None, s=None, showTree=False)[source]
error(s)[source]
exportHeadlines(fileName)[source]
findFunctionDef(s, i)[source]
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.

getFileName(p)[source]

Return the file name from an @file or @root node.

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.

htmlUnitTest(p, fileName=None, s=None, showTree=False)[source]
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.

importFilesCommand(files=None, parent=None, redrawFlag=True, shortFn=False, treeType=None)[source]
importFlattenedOutline(files)[source]
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/

importWebCommand(files, webType)[source]
import_binary_file(fileName, parent)[source]
iniUnitTest(p, fileName=None, s=None, showTree=False)[source]
init_import(atShadow, ext, fileName, s)[source]

Init ivars imports and read the file into s. Return ext, s.

isDocStart(s, i)[source]
isModuleStart(s, i)[source]
javaScriptUnitTest(p, fileName=None, s=None, showTree=False)[source]
javaUnitTest(p, fileName=None, s=None, showTree=False)[source]
languageForExtension(ext)[source]

Return the language corresponding to the extension ext.

markdownUnitTest(p, fileName=None, s=None, showTree=False)[source]
massageWebBody(s)[source]
orgUnitTest(p, fileName=None, s=None, showTree=False)[source]
otlUnitTest(p, fileName=None, s=None, showTree=False)[source]
outlineToWeb(fileName, webType)[source]
parse_body(p)[source]

Parse p.b as source code, creating a tree of descendant nodes. This is essentially an import of p.b.

pascalUnitTest(p, fileName=None, s=None, showTree=False)[source]
perlUnitTest(p, fileName=None, s=None, showTree=False)[source]
phpUnitTest(p, fileName=None, s=None, showTree=False)[source]
pythonUnitTest(p, fileName=None, s=None, showTree=False)[source]
readAtAutoNodes()[source]
reloadSettings()
reload_settings()[source]
removeSentinelLines(s, line_delim, start_delim, unused_end_delim)[source]

Properly remove all sentinle lines in s.

removeSentinelsCommand(paths, toString=False)[source]
rstUnitTest(p, fileName=None, s=None, showTree=False)[source]
scanBodyForHeadline(s)[source]
scanUnknownFileType(s, p, ext)[source]

Scan the text of an unknown file type.

scanWebFile(fileName, parent)[source]
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.

setBodyString(p, s)[source]

Similar to c.setBodyString, but does not recolor the text or redraw the screen.

setEncoding(p=None, default=None)[source]
textUnitTest(p, fileName=None, s=None, showTree=False)[source]
typeScriptUnitTest(p, fileName=None, s=None, showTree=False)[source]
weave(filename)[source]
xmlUnitTest(p, fileName=None, s=None, showTree=False)[source]
class leo.core.leoImport.MORE_Importer(c)[source]

Bases: object

Class to import MORE files.

check(s)[source]
check_lines(strings)[source]
headlineLevel(s)[source]

return the headline level of s,or -1 if the string is not a MORE headline.

import_file(fileName)[source]
import_files(files)[source]

Import a list of MORE (.csv) files.

import_lines(strings, first_p)[source]
prompt_for_files()[source]

Prompt for a list of MORE files and import them.

class leo.core.leoImport.MindMapImporter(c)[source]

Bases: object

Mind Map Importer class.

create_outline(path)[source]
csv_level(row)[source]

Return the level of the given row.

csv_string(row)[source]

Return the string for the given csv row.

import_files(files)[source]

Import a list of MindMap (.csv) files.

prompt_for_files()[source]

Prompt for a list of MindJet (.csv) files and import them.

scan(path, target)[source]

Create an outline from a MindMap (.csv) file.

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.

add_class_names(p)[source]

Add class names to headlines for all descendant nodes.

clear_dirty_bits(p)[source]
dump_headlines(p)[source]
fix_back_slashes(p)[source]

Convert backslash to slash in all headlines.

import_dir(dir_, parent)[source]

Import selected files from dir_, a directory.

import_one_file(path, parent)[source]

Import one file to the last top-level node.

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.

remove_empty_nodes(p)[source]

Remove empty nodes. Not called for @auto or @edit trees.

run(dir_)[source]

Import all files whose extension matches self.theTypes in dir_. In fact, dir_ can be a path to a single file.

strip_prefix(path, prefix)[source]

Strip the prefix from the path and return the result.

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).

check(lines, warn=True)[source]

Return False and warn if lines contains mixed leading tabs/blanks.

dump_stack()[source]

Dump the stack, containing (level, p) tuples.

import_files(files)[source]

Import a list of tab-delimited files.

lws(s)[source]

Return the length of the leading whitespace of s.

prompt_for_files()[source]

Prompt for a list of FreeMind (.mm.html) files and import them.

scan(s1, fn=None, root=None)[source]

Create the outline corresponding to s1.

scan_helper(s)[source]

Update the stack as necessary and return (level, parent, stack).

undent(level, s)[source]

Unindent all lines of p.b by level.

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
clean(zimNode, rstType)[source]

Clean useless nodes

parseZimIndex()[source]

Parse Zim wiki index.rst and return a list of tuples (level, name, path)

rstToLastChild(p, name, rst)[source]

Import an rst file as a last child of pos node with the specified name

run()[source]

Create the zim node as the last top-level node.

leo.core.leoImport.headToPrevNode(event)[source]

Move the code preceding a def to end of previous node.

leo.core.leoImport.import_MORE_files_command(event)[source]

Prompt for MORE files and import them.

leo.core.leoImport.import_free_mind_files(event)[source]

Prompt for free-mind files and import them.

leo.core.leoImport.import_mind_jet_files(event)[source]

Prompt for mind-jet 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
leo.core.leoImport.parse_body_command(event)[source]

The parse-body command.

leo.core.leoImport.tailToNextNode(event=None)[source]

Move the code following a def to start of next node.

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()
add_prefix(prefix, s)[source]

A hack to match the callers expectations.

appendTabName(word)[source]
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.

autoComplete(event=None, force=False)[source]

An event handler for autocompletion.

autoCompleteForce(event=None)[source]

Show autocompletion, even if autocompletion is not presently enabled.

auto_completer_state_handler(event)[source]

Handle all keys while autocompleting.

beginTabName(word)[source]
calltip()[source]

Show the calltips for the present prefix. ch is ‘(‘ if the user has just typed it.

calltip_fail(prefix)[source]

Evaluation of prefix failed.

calltip_success(prefix, obj)[source]
clean(hits)[source]

Clean up hits, a list of ctags patterns, for use in completion lists.

clean_completion_list(header, tabList)[source]

Return aList with header removed from the start of each list item.

clean_for_display(hits)[source]

Clean up hits, a list of ctags patterns, for display purposes.

clearTabName()[source]
cmd()[source]

Command decorator for the AutoCompleter class.

compute_completion_list()[source]

Return the autocompleter completion list.

disableAutocompleter(event=None)[source]

Disable the autocompleter.

disableCalltips(event=None)[source]

Disable calltips.

do_backspace()[source]

Delete the character and recompute the completion list.

do_qcompleter_tab(prefix, options)[source]

Return the longest common prefix of all the options.

enableAutocompleter(event=None)[source]

Enable the autocompleter.

enableCalltips(event=None)[source]

Enable calltips.

exit()[source]
finish()
get_autocompleter_prefix()[source]
get_cached_options(prefix)[source]
get_codewise_completions(prefix)[source]

Use codewise to generate a list of hits.

get_completions(prefix)[source]

Return jedi or codewise completions.

get_jedi_completions(prefix)[source]
get_leo_completions(prefix)[source]

Return completions in an environment defining c, g and p.

get_leo_namespace(prefix)[source]

Return an environment in which to evaluate prefix. Add some common standard library modules as needed.

get_object()[source]

Return the object corresponding to the current prefix.

get_summary_list(header, tabList)[source]

Show the possible starting letters, but only if there are more than one.

guess_class(c, varname)[source]

Return kind, class_list

info()[source]

Show the docstring for the present completion.

init_qcompleter(event=None)[source]
init_tabcompleter(event=None)[source]
insert_general_char(ch)[source]
insert_string(s, select=False)[source]

Insert s at the insertion point.

is_leo_source_file()[source]

Return True if this is one of Leo’s source files.

jedi_warning = False
lookup_functions(prefix)[source]
lookup_methods(aList, prefix)[source]
lookup_modules(aList, prefix)[source]
popTabName()[source]
put(*args, **keys)[source]

Put s to the given tab.

May be overridden in subclasses.

reloadSettings()[source]
setTabName(s)[source]
showAutocompleterStatus()[source]

Show the autocompleter status.

showCalltips(event=None, force=False)[source]

Show the calltips at the cursor.

showCalltipsForce(event=None)[source]

Show the calltips at the cursor, even if calltips are not presently enabled.

showCalltipsStatus()[source]

Show the autocompleter status.

show_completion_list(common_prefix, prefix, tabList)[source]
start(event)[source]
strip_brackets(s)[source]

Return s with all brackets removed.

This (mostly) ensures that eval will not execute function calls, etc.

toggleAutocompleter(event=None)[source]

Toggle whether the autocompleter is enabled.

toggleCalltips(event=None)[source]

Toggle whether calltips are enabled.

class leo.core.leoKeys.ContextSniffer[source]

Bases: object

Class to analyze surrounding context and guess class

For simple dynamic code completion engines.

declare(var, klass)[source]
get_classes(s, varname)[source]

Return a list of classes for string s.

push_declarations(s)[source]
class leo.core.leoKeys.FileNameChooser(c)[source]

Bases: object

A class encapsulation file selection & completion logic.

compute_tab_list()[source]

Compute the list of completions.

do_back_space()[source]

Handle a back space.

do_char(char)[source]

Handle a non-special character.

do_tab()[source]

Handle tab completion.

extend_label(s)[source]

Extend the label by s.

get_file_name(event, callback, filterExt, prompt, tabName)[source]

Get a file name, supporting file completion.

get_label()[source]

Return the label, not including the prompt.

set_label(s)[source]

Set the label after the prompt to s. The prompt never changes.

show_tab_list(tabList)[source]

Show the tab list in the log tab.

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

cancel_after_state()[source]
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_back_space(tabList, completion=True)[source]

Handle a backspace and update the completion list.

do_char(event, char)[source]

Handle a non-special character.

do_end(event, char, stroke)[source]

A return or escape has been seen.

do_state_zero(completion, event, handler, oneCharacter, returnKind, returnState, tabList, useMinibuffer)[source]

Do state 0 processing.

do_tab(tabList, completion=True)[source]

Handle tab completion when the user hits a tab.

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.
get_command(s)[source]

Return the command part of a minibuffer contents s.

get_label()[source]

Return the label, not including the prompt.

get_minibuffer_command_name()[source]

Return the command name in the minibuffer.

is_command(s)[source]

Return False if something, even a blank, follows a command.

reset_tab_cycling()[source]

Reset all tab cycling ivars.

set_label(s)[source]

Set the label after the prompt to s. The prompt never changes.

should_end(char, stroke)[source]

Return True if ga.get_arg should return.

show_tab_list(tabList)[source]

Show the tab list in the log tab.

trace_state(char, completion, handler, state, stroke)[source]

Trace the vars and ivars.

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.

addModeCommands()[source]

Add commands created by @mode settings to c.commandsDict.

addToCommandHistory(commandName)[source]

Add a name to the command history.

badMode(modeName)[source]
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.

bindKeyToDict(pane, stroke, bi)[source]

Update k.masterBindingsDict for the stroke.

bindOpenWith(d)[source]

Register an open-with command.

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.

callAltXFunction(event)[source]

Call the function whose name is in the minibuffer.

callStateFunction(event)[source]

Call the state handler associated with this event.

checkBindings()[source]

Print warnings if commands do not have any @shortcut entry. The entry may be None, of course.

checkKeyEvent(event)[source]

Perform sanity checks on the incoming event.

check_bind_key(commandName, pane, stroke)[source]

Return True if the binding of stroke to commandName for the given pane can be made.

clearState()[source]

Clear the key handler state.

cmd()[source]

Command decorator for the leoKeys class.

commandExists(commandName)[source]

Return the command handler for the given command name, or None.

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.

completeAllBindingsForWidget(w)[source]

Make all a master gui binding for widget w.

computeInverseBindingDict()[source]
createModeBindings(modeName, d, w)[source]

Create mode bindings for the named mode using dictionary d for w, a text widget.

defineExternallyVisibleIvars()[source]
defineInternalIvars()[source]

Define internal ivars of the KeyHandlerClass class.

defineMultiLineCommands()[source]
defineSingleLineCommands()[source]
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.

doControlU(event, stroke)[source]
doDemo(event)[source]

Support the demo.py plugin. Return True if k.masterKeyHandler should return.

doKeyboardQuit(event)[source]

Handle keyboard-quit logic. return True if k.masterKeyHandler should return.

doMode(event)[source]

Handle mode bindings. Return True if k.masterKeyHandler should return.

doTabCompletion(tabList)[source]

Convenience method mapping k.doTabCompletion to ga.do_tab.

doUnboundPlainKey(event)[source]

Handle unbound plain keys. Return True if k.masterKeyHandler should return.

doVim(event)[source]

Handle vim mode. Return True if k.masterKeyHandler should return.

dumpMasterBindingsDict()[source]

Dump k.masterBindingsDict.

editShortcut_do_bind_helper(stroke, cmdname)[source]
endCommand(commandName)[source]

Make sure Leo updates the widget following a command.

Never changes the minibuffer label: individual commands must do that.

endMode()[source]
enterNamedMode(event, commandName)[source]
executeNTimes(event, n)[source]
exitNamedMode(event=None)[source]

Exit an input mode.

extendLabel(s, select=False, protect=False)[source]
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.

getBindingHelper(key, name, stroke, w)[source]

Find a binding for the widget with the given name.

getEditableTextRange()[source]
getFileName(event, callback=None, filterExt=None, prompt='Enter File Name: ', tabName='Dired')[source]

Get a file name from the minibuffer.

getLabel(ignorePrompt=False)[source]
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.

getPaneBinding(stroke, w)[source]
getState(kind)[source]
getStateHandler()[source]
getStateKind()[source]
getStrokeForCommandName(commandName)[source]
handleDefaultChar(event, stroke)[source]

Handle an unbound key, based on the event’s widget. Do not assume that stroke exists.

handleInputShortcut(event, stroke)[source]
handleMiniBindings(event, state, stroke)[source]

Find and execute commands bound to the event.

handleMinibufferHelper(event, pane, state, stroke)[source]

Execute a pane binding in the minibuffer.

Return ‘continue’, ‘ignore’, ‘found’

handleUnboundKeys(event)[source]
inState(kind=None)[source]
initAbbrev()[source]
initCommandHistory()[source]

Init command history from @data command-history nodes.

initMode(event, modeName)[source]
initOneAbbrev(commandName, key)[source]

Enter key as an abbreviation for commandName in c.commandsDict.

initSpecialIvars()[source]

Set ivars for special keystrokes from previously-existing bindings.

isAutoCompleteChar(stroke)[source]

Return True if stroke is bound to the auto-complete in the insert or overwrite state.

isEditShortcutSensible()[source]
isFKey(stroke)[source]
isInShortcutBodyLine()[source]
isPlainKey(stroke)[source]

Return true if the shortcut refers to a plain (non-Alt,non-Ctl) key.

isSpecialKey(event)[source]

Return True if char is a special key.

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.

killLine(protect=True)[source]
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.

makeAllBindings()[source]

Make all key bindings in all of Leo’s panes.

makeBindingsFromCommandsDict()[source]

Add bindings for all entries in c.commandsDict.

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.

masterKeyHandler(event)[source]

The master key handler for almost all key bindings.

menuCommandKey(event=None)[source]
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.

modeHelpHelper(d)[source]
oops()[source]
overrideCommand(commandName, func)[source]
prettyPrintKey(stroke, brief=False)[source]
printBindings(event=None)[source]

Print all the bindings presently in effect.

printBindingsHelper(result, data, prefix)[source]
printButtons(event=None)[source]

Print all @button and @command commands, their bindings and their source.

printCommands(event=None)[source]

Print all the known commands and their bindings, if any.

protectLabel()[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.

reinitMode(modeName)[source]
reloadSettings()[source]
remove_conflicting_definitions(aList, commandName, pane, shortcut)[source]
repeatComplexCommand(event)[source]

Repeat the previously executed minibuffer command.

repeatComplexCommandHelper(event)[source]
resetCommandHistory()[source]

reset the command history index to indicate that we are pointing ‘past’ the last entry

resetLabel()[source]

Reset the minibuffer label.

searchTree(char)[source]

Search all visible nodes for a headline starting with stroke.

selectAll()[source]

Select all the user-editable text of the minibuffer.

setCommandState(event)[source]

Enter the ‘command’ editing state.

setDefaultEditingAction()[source]
setDefaultInputState()[source]
setDefaultUnboundKeyAction(allowCommandState=True)[source]
setEditingState()[source]
setEventWidget(event)[source]

A hack: redirect the event to the text part of the log.

setInputState(state, set_border=False)[source]
setInsertState(event)[source]

Enter the ‘insert’ editing state.

setLabel(s, protect=False)[source]

Set the label of the minibuffer.

setLabelBlue(label, protect=True)[source]

Set the minibuffer label.

setLabelGray(label=None)
setLabelGrey(label=None)[source]
setLabelRed(label=None, protect=False)[source]
setLossage(ch, stroke)[source]
setOverwriteState(event)[source]

Enter the ‘overwrite’ editing state.

setState(kind, n, handler=None)[source]
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.

showStateCursor(state, w)[source]
simulateCommand(commandName, event=None)[source]

Execute a Leo command by name.

sortCommandHistory()[source]

Sort the command history.

stroke2char(stroke)[source]

Convert a stroke to an (insertable) char. This method allows Leo to use strokes everywhere.

toggleInputState(event=None)[source]

The toggle-input-state command.

traceVars(event)[source]
universalDispatcher(event)[source]

Handle accumulation of universal argument.

updateLabel(event)[source]

Mimic what would happen with the keyboard and a Text editor instead of plain accumulation.

class leo.core.leoKeys.ModeInfo(c, name, aList)[source]

Bases: object

computeModeName(name)[source]
computeModePrompt(name)[source]
createModeBindings(w)[source]

Create mode bindings for w, a text widget.

createModeCommand()[source]
enterMode()[source]
init(name, dataList)[source]

aList is a list of tuples (commandName,bi).

initMode()[source]

leoMenu Module

Gui-independent menu handling for Leo.

class leo.core.leoMenu.LeoMenu(frame)[source]

Bases: object

The base class for all Leo menus.

activateMenu(menuName)[source]
add_cascade(parent, label, menu, underline)[source]
add_command(menu, **keys)[source]
add_separator(menu)[source]
canonicalizeMenuName(name)[source]
canonicalizeTranslatedMenuName(name)[source]
capitalizeMinibufferMenuName(s, removeHyphens)[source]
clearAccel(menu, name)[source]
computeOldStyleShortcutKey(s)[source]

Compute the old-style shortcut key for @shortcuts entries.

createMasterMenuCallback(dynamicMenu, command, commandName)[source]
createMenuBar(frame)[source]
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
createMenuItemsFromTable(menuName, table, dynamicMenu=False)[source]
createMenusFromConfigList(aList)[source]

Create menus from aList. The ‘top’ menu has already been created.

createMenusFromTables()[source]

(leoMenu) Usually over-ridden.

createNewMenu(menuName, parentName='top', before=None)[source]
createOpenWithMenu(parent, label, index, amp_index)[source]
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.

defineMenuCallback(command, name, minibufferCommand)[source]
defineOpenWithMenuCallback(d)[source]
define_enable_dict()[source]
delete(menu, realItemName)[source]
deleteMenu(menuName)[source]
deleteMenuItem(itemName, menuName='top')[source]

Delete itemName from the menu whose name is menuName.

deleteRecentFilesMenuItems(menu)[source]

Delete recent file menu entries

delete_range(menu, n1, n2)[source]
destroy(menu)[source]
destroyMenu(menuName)[source]
disableMenu(menu, name)[source]
enableMenu(menu, name, val)[source]
error(s)[source]
finishCreate()[source]
getMacHelpMenu(table)[source]
getMenu(menuName)[source]
getMenuEntryBindings(command, dynamicMenu, label)[source]

Compute commandName from command.

getMenuEntryInfo(data, menu)[source]
getMenuLabel(menu, name)[source]
getRealMenuName(menuName)[source]
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.

hasSelection()[source]
insert(menuName, position, label, command, underline=None)[source]
insert_cascade(parent, index, label, menu, underline)[source]
new_menu(parent, tearoff=0, label='')[source]
oops()[source]
setMenu(menuName, menu)[source]
setMenuLabel(menu, name, label, underline=-1)[source]
setRealMenuName(untrans, trans)[source]
setRealMenuNamesFromTable(table)[source]
traceMenuTable(table)[source]
class leo.core.leoMenu.NullMenu(frame)[source]

Bases: leo.core.leoMenu.LeoMenu

A null menu class for testing and batch execution.

oops()[source]

leoNodes Module

Leo’s fundamental data classes.

class leo.core.leoNodes.NodeIndices(id_)[source]

Bases: object

A class managing global node indices (gnx’s).

check_gnx(c, gnx, v)[source]

Check that no vnode exists with the given gnx in fc.gnxDict.

compute_last_index(c)[source]

Scan the entire leo outline to compute ni.last_index.

getDefaultId()[source]

Return the id to be used by default in all 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.

new_vnode_helper(c, gnx, v)[source]

Handle all gnx-related tasks for VNode.__init__.

scanGnx(s, i=0)[source]

Create a gnx from its string representation.

setDefaultId(theId)[source]

Set the id to be used by default in all gnx’s

setTimeStamp()

Set the timestamp string to be used by getNewIndex until further notice

setTimestamp()[source]

Set the timestamp string to be used by getNewIndex until further notice

tupleToString(aTuple)[source]

Convert a gnx tuple returned by scanGnx to its string representation.

update()[source]

Update self.timeString and self.lastIndex

updateLastIndex(gnx)[source]

Update ni.lastIndex if the gnx affects it.

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.

filter_b(regex, flags=2)[source]

Find all the nodes in PosList self where body matches regex one or more times.

filter_h(regex, flags=2)[source]

Find all the nodes in PosList self where zero or more characters at the beginning of the headline match regex

class leo.core.leoNodes.Position(v, childIndex=0, stack=None)[source]

Bases: object

anyAtFileNodeName()[source]
archivedPosition(root_p=None)[source]

Return a representation of a position suitable for use in .leo files.

atAsisFileNodeName()
atAutoNodeName()[source]
atCleanNodeName()[source]
atEditNodeName()[source]
atFileNodeName()[source]
atNoSentFileNodeName()
atNoSentinelsFileNodeName()[source]
atShadowFileNodeName()[source]
atSilentFileNodeName()[source]
atThinFileNodeName()[source]
b

position body string property

back()
bodyString()[source]
checkVisBackLimit(limit, limitIsVisible, p)[source]

Return done, p or None

checkVisNextLimit(limit, p)[source]

Return True is p is outside limit of visible nodes.

childIndex()[source]
children()[source]

Yield all child positions of p.

children_iter()

Yield all child positions of p.

cleanHeadString()[source]
clearAllVisitedInTree()[source]
clearDirty()[source]
  1. Set p.v dirty.
clearMarked()[source]
clearOrphan()[source]
clearVisited()[source]
clearVisitedInTree()[source]
clone()[source]

Create a clone of back.

Returns the newly created position.

computeIcon()[source]
contract()[source]

Contract p.v and clear p.v.expandedPositions list.

convertTreeToString()[source]

Convert a positions suboutline to a string in MORE format.

copy()[source]

“Return an independent copy of a position.

copyTreeAfter(copyGnxs=False)[source]

Copy p and insert it after itself.

copyTreeFromSelfTo(p2, copyGnxs=False)[source]
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)

deleteAllChildren()[source]

Delete all children of the receiver.

directParents()[source]
doDelete(newNode=None)[source]

Deletes position p from the outline.

dump(label='')[source]
expand()[source]
findAllPotentiallyDirtyNodes()[source]
findRootPosition()[source]
firstChild()
following_siblings()[source]

Yield all siblings positions that follow p, not including p.

following_siblings_iter()

Yield all siblings positions that follow p, not including p.

getBack()[source]
getFirstChild()[source]
getLastChild()[source]
getLastNode()[source]
getNext()[source]
getNodeAfterTree()[source]
getNthChild(n)[source]
getParent()[source]
getThreadBack()[source]
getThreadNext()[source]
getVisBack(c)[source]
getVisNext(c)[source]
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

hasBack()[source]
hasChildren()[source]
hasFirstChild()
hasNext()[source]
hasParent()[source]
hasThreadBack()[source]
hasThreadNext()[source]
hasVisBack(c)
hasVisNext(c)
headString()[source]
inAtIgnoreRange()[source]

Returns True if position p or one of p’s parents is an @ignore node.

in_at_all_tree()[source]

Return True if p or one of p’s ancestors is an @all node.

in_at_ignore_tree()[source]

Return True if p or one of p’s ancestors is an @ignore node.

initBodyString(s)
initExpandedBit()[source]
initHeadString(s)[source]
initMarkedBit()[source]
initStatus(status)[source]
insertAfter()[source]

Inserts a new position after self.

Returns the newly created position.

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.

insertBefore()[source]

Inserts a new position before self.

Returns the newly created position.

invalidOutline(message)[source]
isAncestorOf(p2)[source]

Return True if p is one of the direct ancestors of p2.

isAnyAtFileNode()[source]
isAtAllNode()[source]
isAtAsisFileNode()
isAtAutoNode()[source]
isAtAutoRstNode()[source]
isAtCleanNode()[source]
isAtEditNode()[source]
isAtFileNode()[source]
isAtIgnoreNode()[source]
isAtNoSentFileNode()
isAtNoSentinelsFileNode()[source]
isAtOthersNode()[source]
isAtRstFileNode()[source]
isAtShadowFileNode()[source]
isAtSilentFileNode()[source]
isAtThinFileNode()[source]
isCloned()[source]
isDirty()[source]
isExpanded()[source]
isMarked()[source]
isOrphan()[source]
isOutsideAnyAtFileTree()[source]

Select the first clone of target that is outside any @file node.

isRoot()[source]
isSelected()[source]
isTopBitSet()[source]
isVisible(c)[source]

Return True if p is visible in c’s outline.

isVisited()[source]
is_at_all()[source]

Return True if p.b contains an @all directive.

is_at_ignore()[source]

Return True if p is an @ignore node.

key()[source]
lastChild()
lastNode()
level()[source]

Return the number of p’s parents.

matchHeadline(pattern)[source]
moreBody()[source]

Returns the body string in MORE format.

Inserts a backslash before any leading plus, minus or backslash.

moreHead(firstLevel, useVerticalBar=False)[source]

Return the headline string in MORE format.

moveAfter(a)[source]

Move a position after position a.

moveToBack()[source]

Move self to its previous sibling.

moveToFirstChild()[source]

Move a position to it’s first child’s position.

moveToFirstChildOf(parent)[source]

Move a position to the first child of parent.

moveToLastChild()[source]

Move a position to it’s last child’s position.

moveToLastChildOf(parent)[source]

Move a position to the last child of parent.

moveToLastNode()[source]

Move a position to last node of its tree.

N.B. Returns p if p has no children.

moveToNext()[source]

Move a position to its next sibling.

moveToNodeAfterTree()[source]

Move a position to the node after the position’s tree.

moveToNthChild(n)[source]
moveToNthChildOf(parent, n)[source]

Move a position to the nth child of parent.

moveToParent()[source]

Move a position to its parent position.

moveToRoot(oldRoot=None)[source]

Moves a position to the root position.

Important: oldRoot must the previous root position if it exists.

moveToThreadBack()[source]

Move a position to it’s threadBack position.

moveToThreadNext()[source]

Move a position to threadNext position.

moveToVisBack(c)[source]

Move a position to the position of the previous visible node.

moveToVisNext(c)[source]

Move a position to the position of the next visible node.

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()
nodes()[source]

Yield p.v and all vnodes in p’s subtree.

nosentinels

position property returning the body text without sentinels

nthChild(n)
numberOfChildren()[source]
parent()
parents()[source]

Yield all parent positions of p.

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.

promote()[source]

A low-level promote helper.

restoreCursorAndScroll()[source]
safeMoveToThreadNext()[source]

Move a position to threadNext position. Issue an error if any vnode is an ancestor of itself.

saveCursorAndScroll()[source]
script

position property returning the script formed by p and its descendants

scriptSetBodyString(s)
self_and_parents()[source]

Yield p and all parent positions of p.

self_and_parents_iter()

Yield p and all parent positions of p.

self_and_siblings()[source]

Yield all sibling positions of p including p.

self_and_siblings_iter()

Yield all sibling positions of p including p.

self_and_subtree()[source]

Yield p and all positions in p’s subtree.

self_and_subtree_iter()

Yield p and all positions in p’s subtree.

setAllAncestorAtFileNodesDirty(setDescendentsDirty=False)[source]
setBodyString(s)[source]
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.

setHeadString(s)[source]
setIcon()[source]
setMarked()[source]
setOrphan()[source]
setSelected()[source]
setSelection(start, length)[source]
setTnodeText(s)
setVisited()[source]
simpleLevel()

Return the number of p’s parents.

sort_key(p)[source]
status()[source]
subtree()[source]

Yield all positions in p’s subtree, but not p.

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_nodes()[source]

Yield p.v and all unique vnodes in p’s subtree.

unique_subtree()[source]

Yield p and all other unique positions in p’s subtree.

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.

validateOutlineWithParent(pv)[source]
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

anyAtFileNodeName()[source]

Return the file name following an @file node or an empty string.

atAsisFileNodeName()
atAutoNodeName(h=None)[source]
atAutoRstNodeName(h=None)[source]
atCleanNodeName()[source]
atEditNodeName()[source]
atFileNodeName()[source]
atNoSentFileNodeName()
atNoSentinelsFileNodeName()[source]
atRstFileNodeName()[source]
atShadowFileNodeName()[source]
atSilentFileNodeName()[source]
atThinFileNodeName()[source]
b

VNode body string property

bodyString()[source]
body_unicode_warning = False
childrenModified()[source]
cleanHeadString()[source]
clearClonedBit()[source]
clearDirty()[source]

Clear the vnode dirty bit.

clearMarked()[source]
clearOrphan()[source]
clearVisited()[source]
clearWriteBit()[source]
cloneAsNthChild(parent_v, n)[source]
clonedBit = 1
computeIcon()[source]
contentModified()[source]
contract()[source]

Contract the node.

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
dump(label='')[source]
expand()[source]

Expand the node.

expandedBit = 4
findAllPotentiallyDirtyNodes()[source]
findAtFileName(names, h='')[source]

Return the name following one of the names in nameList or “”

firstChild()[source]
getBody()
gnx

VNode gnx property

h

VNode headline string property

hasBody()[source]

Return True if this VNode contains body text.

hasChildren()[source]
hasFirstChild()
headString()[source]

Return the headline string.

head_unicode_warning = False
initBodyString(s)
initClonedBit(val)[source]
initExpandedBit()[source]

Init self.statusBits.

initHeadString(s)
initMarkedBit()[source]
initStatus(status)[source]
insertAsFirstChild()[source]
insertAsLastChild()[source]
insertAsNthChild(n)[source]
isAnyAtFileNode()[source]

Return True if v is any kind of @file or related node.

isAtAllNode()[source]

Returns True if the receiver contains @others in its body at the start of a line.

isAtAsisFileNode()
isAtAutoNode()[source]
isAtAutoRstNode()[source]
isAtCleanNode()[source]
isAtEditNode()[source]
isAtFileNode()[source]
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()
isAtNoSentinelsFileNode()[source]
isAtOthersNode()[source]

Returns True if the receiver contains @others in its body at the start of a line.

isAtRstFileNode()[source]
isAtShadowFileNode()[source]
isAtSilentFileNode()[source]
isAtThinFileNode()[source]
isCloned()[source]
isDirty()[source]
isExpanded()[source]

Return True if the VNode expansion bit is set.

isMarked()[source]
isNthChildOf(n, parent_v)[source]

Return True if v is the n’th child of parent_v.

isOrphan()[source]
isSelected()[source]
isTopBitSet()[source]
isVisited()[source]
isWriteBit()[source]
lastChild()[source]
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.

nthChild(n)[source]
numberOfChildren()[source]
orphanBit = 2048
restoreCursorAndScroll()[source]

Restore the cursor position and scroll so it is visible.

richTextBit = 128
saveCursorAndScroll()[source]
selectedBit = 32
setAllAncestorAtFileNodesDirty()[source]
setBodyString(s)[source]
setClonedBit()[source]
setDirty()[source]

Set the vnode dirty bit.

setHeadString(s)[source]
setHeadText(s)
setIcon()[source]
setMarked()[source]
setOrphan()[source]

Set the vnode’s orphan bit.

setSelected()[source]
setSelection(start, length)[source]
setTnodeText(s)
setVisited()[source]
setWriteBit()[source]
status()[source]
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’

setCommand(commandName, handler, shortcut='', pane='all', verbose=True)[source]

Associate a command name with handler code, optionally defining a keystroke shortcut

setMenuItem(menu, commandName=None, handler=None)[source]

Create a menu item in ‘menu’ using text ‘commandName’ calling handler ‘handler’ if commandName and handler are none, use the most recently defined values

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.

add(func, priority=0)[source]

Add a func to the cmd chain with given priority

class leo.core.leoPlugins.LeoPluginsController[source]

Bases: object

The global plugins controller, g.app.pluginsController

callTagHandler(bunch, tag, keywords)[source]

Call the event handler.

doHandlersForTag(tag, keywords)[source]

Execute all handlers for a given tag, in alphabetical order. The caller, doHook, catches all exceptions.

doPlugins(tag, keywords)[source]

The default g.app.hookFunction.

finishCreate()[source]
getHandlersForOneTag(tag)[source]
getHandlersForTag(tags)[source]
getLoadedPlugins()[source]
getPluginModule(moduleName)[source]
isLoaded(fn)[source]
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.

on_idle()[source]

Call all idle-time hooks.

plugin_signon(module_name, verbose=False)[source]

Print the plugin signon.

printHandlers(c, moduleName=None)[source]

Print the handlers for each plugin.

printPlugins(c)[source]

Print all enabled plugins.

printPluginsInfo(c)[source]

Print the file name responsible for loading a plugin.

This is the first .leo file containing an @enabled-plugins node that enables the plugin.

registerExclusiveHandler(tags, fn)[source]

Register one or more exclusive handlers

registerHandler(tags, fn)[source]

Register one or more handlers

registerOneExclusiveHandler(tag, fn)[source]

Register one exclusive handler

registerOneHandler(tag, fn)[source]

Register one handler

regularizeName(fn)[source]

Return the name used as a key to this modules dictionaries.

reloadSettings()[source]
setLoaded(fn, m)[source]
unloadOnePlugin(moduleOrFileName, verbose=False)[source]
unregisterHandler(tags, fn)[source]
unregisterOneHandler(tag, fn)[source]
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.

leo.core.leoPlugins.init()[source]

Init g.app.pluginsController.

leo.core.leoPlugins.registerHandler(tags, fn)[source]

A wrapper so plugins can still call leoPlugins.registerHandler.

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.

leo.core.leoPymacs.dump(anObject)[source]
leo.core.leoPymacs.get_app()[source]

Scripts can use g.app.scriptDict for communication with pymacs.

leo.core.leoPymacs.get_g()[source]
leo.core.leoPymacs.hello()[source]
leo.core.leoPymacs.init()[source]
leo.core.leoPymacs.open(fileName=None)[source]
leo.core.leoPymacs.run_script(c, script, p=None)[source]
leo.core.leoPymacs.script_result()[source]

leoRst Module

leoSessions Module

Support for sessions in Leo.

exception leo.core.leoSessions.LeoSessionException[source]

Bases: exceptions.Exception

class leo.core.leoSessions.SessionManager[source]

Bases: object

clear_session(c)[source]

Close all tabs except the presently selected tab.

get_session()[source]

Return a list of UNLs for open tabs.

get_session_path()[source]

Return the path to the session file.

load_session(c=None, unls=None)[source]

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

load_snapshot()[source]

Load a snapshot of a session from the leo.session file.

Called when –restore-session is in effect.

save_snapshot(c=None)[source]

Save a snapshot of the present session to the leo.session file.

Called automatically during shutdown when –session-save is in effect.

leo.core.leoSessions.session_clear_command(event)[source]

Close all tabs except the presently selected tab.

leo.core.leoSessions.session_create_command(event)[source]

Create a new @session node.

leo.core.leoSessions.session_refresh_command(event)[source]

Refresh the current @session node.

leo.core.leoSessions.session_restore_command(event)[source]

Open a tab for each item in the @session node & select the indicated node in each.

leo.core.leoSessions.session_snapshot_load_command(event)[source]

Load a snapshot of a session from the leo.session file.

leo.core.leoSessions.session_snapshot_save_command(event)[source]

Save a snapshot of the present session to the leo.session file.

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’.

createSentinelNode(root, p)[source]

Write p’s tree to a string, as if to a file.

fail(msg=None)[source]

Mark an AtShadowTestCase as having failed.

findNode(c, p, headline)[source]

Return the node in p’s subtree with given headline.

makePrivateLines(p)[source]

Return a list of the lines of p containing sentinels.

makePublicLines(lines)[source]

Return the public lines in lines.

mungePrivateLines(lines, find, replace)[source]

Change the ‘find’ the ‘replace’ pattern in sentinel lines.

runTest(define_g=True)[source]

AtShadowTestCase.runTest.

setUp()[source]

AtShadowTestCase.setup.

shortDescription()[source]

AtShadowTestCase.shortDescription.

tearDown()[source]

AtShadowTestCase.tearDown.

class Marker(delims)[source]

Bases: object

A class representing comment delims in @shadow files.

getDelims()[source]

Return the pair of delims to be used in sentinel lines.

isSentinel(s, suffix='')[source]

Return True is line s contains a valid sentinel comment.

isVerbatimSentinel(s)[source]

Return True if s is an @verbatim sentinel.

baseDirName()[source]
check_output()[source]

Check that we produced a valid output.

dirName(filename)[source]

Return the directory for filename.

dump_args()[source]

Dump the argument lines.

dump_lines(lines, title)[source]

Dump the given lines.

error(s, silent=False)[source]
findLeoLine(lines)[source]

Return the @+leo line, or ‘’.

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.

makeShadowDirectory(fn)[source]

Make a shadow directory for the public fn.

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.

message(s)[source]
op_bad(tag, ai, aj, bi, bj)[source]

Report an unexpected opcode.

op_delete(tag, ai, aj, bi, bj)[source]

Handle the ‘delete’ opcode.

op_equal(tag, ai, aj, bi, bj)[source]

Handle the ‘equal’ opcode.

op_insert(tag, ai, aj, bi, bj)[source]

Handle the ‘insert’ opcode.

op_replace(tag, ai, aj, bi, bj)[source]

Handle the ‘replace’ opcode.

pathName(filename)[source]

Return the full path name of 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)

put_plain_line(line)[source]

Put a plain line to x.results, inserting verbatim lines if necessary.

put_sentinels(i)[source]

Put all the sentinels to the results

reloadSettings()[source]

ShadowController.reloadSettings.

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()

show_error(lines1, lines2, message, lines1_message, lines2_message)[source]
show_error_lines(lines, fileName)[source]

Unlink filename from the file system. Give an error on failure.

updatePublicAndPrivateFiles(root, fn, shadow_fn)[source]

handle crucial @shadow read logic.

This will be called only if the public and private files both exist.

verbatim_error()[source]

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>
cleanup()[source]
compare_comments(s1, s2)[source]
compare_section_names(s1, s2)[source]
copy(s)[source]
error(s)[source]
forgiving_compare(name, part, s1, s2)[source]
handle_newline(s, i, delims)[source]
initTangleCommand()[source]
initUntangleCommand()[source]
init_directive_ivars()[source]
init_ivars()[source]
is_end_of_directive(s, i)[source]
is_end_of_string(s, i, delim)[source]
is_escaped(s, i)[source]
is_section_name(s, i)[source]
is_sentinel_line(s, i)[source]
is_sentinel_line_with_data(s, i)[source]
mismatch(message)[source]
oblank()[source]
oblanks(n)[source]
onl()[source]
os(s)[source]
otab()[source]
otabs(n)[source]
parent_language_comment_settings(p, lang_dict)[source]
pathError(s)[source]
push_new_DefNode(name, indent, part, of, nl_flag)[source]
push_parts(reflist)[source]
put_PartNode(part, no_first_lws_flag)[source]
put_all_roots()[source]
put_code(s, no_first_lws_flag, delims)[source]
put_doc(s, delims)[source]
put_leading_ws(n)[source]
put_newline(s, i, no_first_lws_flag)[source]
put_section(s, i, name, name_end, delims)[source]
refpart_stack_dump()[source]
reloadSettings()
reload_settings()[source]
scanAllDirectives(p)[source]

Scan VNode p and p’s ancestors looking for directives, setting corresponding tangle ivars and globals.

scan_derived_file(s)[source]
scan_short_val(s, i)[source]
section_check(name)[source]
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

setRootFromHeadline(p)[source]
setRootFromText(s, report_errors=True)[source]
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.

skip_code(s, i, delims)[source]
skip_doc(s, i, delims)[source]
skip_headline(p)[source]
skip_section_name(s, i)[source]
st_check()[source]

Checks the given symbol table for defined but never referenced sections.

st_dump(verbose_flag=True)[source]
st_dump_node(section)[source]
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_root_name(name, code, doc, delims_begin, delims_end)[source]
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.

tangle(event=None, p=None)[source]
tangleAll(event=None)[source]
tangleMarked(event=None)[source]
tanglePass1(p_in, delims)[source]

The main routine of tangle pass 1

tanglePass2()[source]
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).

untangle(event=None, p=None)[source]
untangleAll(event=None)[source]
untangleMarked(event=None)[source]
untangleRoot(root, begin, end)[source]
untangleTree(p, report_errors)[source]
update_current_vnode(s)[source]

Called from within the Untangle logic to update the body text of self.p.

update_def(name, part_number, head, code, tail, is_root_flag=False)[source]
ust_dump()[source]
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.

ust_warn_about_orphans()[source]

Issues a warning about any sections in the derived file for which no corresponding section has been seen in the outline.

warning(s)[source]
class leo.core.leoTangle.DefNode(name, indent, part, of, nl_flag, code)[source]

Bases: object

class leo.core.leoTangle.PartNode(name, code, doc, is_root, is_dirty, delims)[source]

Bases: object

reflist(refs=False)[source]
class leo.core.leoTangle.RootAttributes(tangle_state)[source]

Bases: object

class leo.core.leoTangle.TangleCommands(c)[source]

Bases: leo.core.leoTangle.BaseTangleCommands

A class that implements Leo’ tangle and untangle commands.

class leo.core.leoTangle.TstNode(name, root_flag)[source]

Bases: object

dump()[source]
class leo.core.leoTangle.UstNode(name, code, part, of, nl_flag, update_flag)[source]

Bases: object

dump()[source]

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

afterClearRecentFiles(bunch)[source]
afterCloneMarkedNodes(p)[source]
afterCloneNode(p, command, bunch, dirtyVnodeList=None)[source]
afterCopyMarkedNodes(p)[source]
afterDehoist(p, command)[source]
afterDeleteMarkedNodes(data, p)[source]
afterDeleteNode(p, command, bunch, dirtyVnodeList=None)[source]
afterDemote(p, followingSibs, dirtyVnodeList)[source]

Create an undo node for demote operations.

afterHoist(p, command)[source]
afterInsertNode(p, command, bunch, dirtyVnodeList=None)[source]
afterMark(p, command, bunch, dirtyVnodeList=None)[source]

Create an undo node for mark and unmark commands.

afterMoveNode(p, command, bunch, dirtyVnodeList=None)[source]
afterPromote(p, children, dirtyVnodeList)[source]

Create an undo node for demote operations.

afterSort(p, bunch, dirtyVnodeList)[source]

Create an undo node for sort operations

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

beforeChangeTree(p)[source]
beforeClearRecentFiles()[source]
beforeCloneNode(p)[source]
beforeDeleteNode(p)[source]
beforeInsertNode(p, pasteAsClone=False, copiedBunchList=None)[source]
beforeMark(p, command)[source]
beforeMoveNode(p)[source]
beforeSort(p, undoType, oldChildren, newChildren, sortChildren)[source]

Create an undo node for sort operations.

canRedo()[source]
canUndo()[source]
clearOptionalIvars()[source]
clearUndoState()[source]

Clears then entire Undo state.

All non-undoable commands should call this method.

cmd()[source]

Command decorator for the Undoer class.

createCommonBunch(p)[source]

Return a bunch containing all common undo info. This is mostly the info for recreating an empty node at position p.

createTnodeUndoInfo(v)[source]

Create a bunch containing all info needed to recreate a VNode.

createVnodeUndoInfo(v)[source]

Create a bunch containing all info needed to recreate a VNode for undo.

cutStack()[source]
dumpBead(n)[source]
dumpTopBead()[source]
enableMenuItems()[source]
getBead(n)[source]

Set Undoer ivars from the bunch at the top of the undo stack.

onSelect(old_p, p)[source]
peekBead(n)[source]
pushBead(bunch)[source]
putIvarsToVnode(p)[source]
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.

redo(event=None)[source]

Redo the operation undone by the last undo.

redoClearRecentFiles()[source]
redoCloneMarkedNodes()[source]
redoCloneNode()[source]
redoCopyMarkedNodes()[source]
redoDehoistNode()[source]
redoDeleteMarkedNodes()[source]
redoDeleteNode()[source]
redoDemote()[source]
redoGroup()[source]

Process beads until the matching ‘afterGroup’ bead is seen.

redoHelper()[source]
redoHoistNode()[source]
redoInsertNode()[source]
redoMark()[source]
redoMenuName(name)[source]
redoMove()[source]
redoNodeContents()[source]
redoPromote()[source]
redoSort()[source]
redoTree()[source]

Redo replacement of an entire tree.

redoTyping()[source]
reloadSettings()[source]

Undoer.reloadSettings.

restoreTnodeUndoInfo(bunch)[source]
restoreTree(treeInfo)[source]

Use the tree info to restore all VNode data, including all links.

restoreVnodeUndoInfo(bunch)[source]

Restore all ivars saved in the bunch.

saveTree(p, treeInfo=None)[source]

Return a list of tuples with all info needed to handle a general undo operation.

setIvarsFromBunch(bunch)[source]
setIvarsFromVnode(p)[source]
setRedoType(theType)[source]
setUndoType(theType)[source]
setUndoTypes()[source]
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.

trace()[source]
undo(event=None)[source]

Undo the operation described by the undo parameters.

undoClearRecentFiles()[source]
undoCloneMarkedNodes()[source]
undoCloneNode()[source]
undoCopyMarkedNodes()[source]
undoDehoistNode()[source]
undoDeleteMarkedNodes()[source]
undoDeleteNode()[source]
undoDemote()[source]
undoGroup()[source]

Process beads until the matching ‘beforeGroup’ bead is seen.

undoHelper()[source]
undoHoistNode()[source]
undoInsertNode()[source]
undoMark()[source]
undoMenuName(name)[source]
undoMove()[source]
undoNodeContents()[source]

Undo all changes to the contents of a node, including headline and body text, and marked bits.

undoPromote()[source]
undoRedoText(p, leading, trailing, oldMidLines, newMidLines, oldNewlines, newNewlines, tag='undo', undoType=None)[source]

Handle text undo and redo: converts _new_ text into _old_ text.

undoRedoTree(p, new_data, old_data)[source]

Replace p and its subtree using old_data during undo.

undoSort()[source]
undoTree()[source]

Redo replacement of an entire tree.

undoTyping()[source]
updateMarks(oldOrNew)[source]

Update dirty and marked bits.

leoVersion Module

A module holding the following version-related info:

leoVersion.branch: The git branch name, or ‘’. leoVersion.build: The timestamp field from commit_timestamp.json. leoVersion.date: The asctime field from commit_timestamp.json. leoVersion.version: Leo’s version number, set below.

runLeo Module