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

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.

lockLog()[source]

Disable changes to the log

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

A factory returning a scanner function for p, an @auto node.

scanner_for_ext(c, ext)[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]
setLeoID(verbose=True)[source]
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.

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 ShortcutInfo nodes.

Duplicates happen only if panes conflict.

completeFileName(fileName)[source]
computeBindingLetter(kind)[source]
computeFilesList(fileName)[source]
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, shortcuts_d, localFlag)[source]

Merge the settings dicts from c’s outline into new copies of settings_d and shortcuts_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.

computeWorkbookFileName()[source]
createAllImporetersData()[source]

New in Leo 5.5:

Create global data structures describing importers and writers.

createDefaultSettingsDicts()[source]

Create lm.globalSettingsDict & lm.globalShortcutsDict.

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

Create the data structures describing importer plugins.

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

Create the data structures describing writer plugins.

doDiff()[source]

Support –diff option after loading Leo.

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.

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

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 are no longer valid.

clearRecentFiles(c)[source]

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

createRecentFiles()[source]

Trye to reate .leoRecentFiles.txt in - the users home directory first, - Leo’s config directory second.

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

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

checkPythonCode(root, s=None, targetFn=None)[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(name)[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)[source]

Delete unvisited nodes in root’s subtree, not including root.

Actually, instead of deleting the nodes, we move them to be children of the ‘Resurrected Nodes’ r.

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

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, atAuto=False, atEdit=False, atShadow=False, forcePythonSentinels=None, nosentinels=False, perfectImportFlag=False, scriptWrite=False, thinFile=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]
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, start, end, 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, oneNodeOnly=False, 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.

putDirective(s, i)[source]

Output a sentinel a directive or reference s.

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.

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(s, i, n1, n2, p, delta)[source]

Put a reference at s[n1:n2+2] from p.

putRefLine(s, i, n1, n2, 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, partialFlag=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.

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.

ref_warning_given = False
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]
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]
runPyflakes(root)[source]

Run pyflakes on the selected node.

saveOutlineIfPossible()[source]

Save the outline if only persistence data nodes are dirty.

scanAllDirectives(p, scripting=False, importing=False, reading=False, forcePythonSentinels=False, createPath=True, issuePathWarning=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 = {'@verbatim': 64, '@clone': 81, '@+all': 72, '@verbatimAfterRef': 65, '@-middle': 71, '@+others': 46, '@+body': 42, '@+node': 45, '@nonl': 83, '@-at': 21, '@-leo': 25, '@+leo': 44, '@+middle': 73, '@comment': 60, '@+at': 41, '@-body': 22, '@nl': 82, '@+doc': 43, '@afterref': 80, '@-node': 26, '@delims': 61, '@-others': 27, '@-all': 70, '@-doc': 24}
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(nosentinels, root, thinFile, 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, perfectImportFlag=False, scriptWrite=False, thinFile=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.

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]
writeOneAtAutoNode(p, toString, force, trialWrite=False, forceSentinels=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, forceSentinels=False)[source]

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

writer_for_ext(ext, forceSentinels=False)[source]

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

leo.core.leoAtFile.atFile

alias of 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]
getLeoID()[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.

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.

createOutlineFromCacheList(parent_v, aList, fileName, top=True)[source]

Create outline structure from recursive aList built by makeCacheList.

fastAddLastChild(parent_v, gnxString)[source]

Create new VNode as last child of the receiver. If the gnx exists already, create a clone instead of new VNode.

fileKey(s, content, requireEncodedString=False)[source]

Compute the hash of s (usually a headline) and content. s 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)

reportChangedClone(child_v, b, h, gnx)[source]
save(fn, changeName)[source]
setCachedGlobalsElement(fn)[source]
setCachedStringPosition(str_pos)[source]
test()[source]
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.

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

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.

BeginUpdate()

Deprecated: does nothing.

BringToFront(c2=None, set_focus=True)
EndUpdate(flag=True)

Request a redraw of the screen if flag is True.

about(event=None)[source]

Bring up an About Leo Dialog.

addComments(event=None)[source]

Converts all selected lines to comment lines using the comment delimiters given by the applicable @language directive.

Inserts single-line comments if possible; inserts block comments for languages like html that lack single-line comments.

@bool indent_added_comments

If True (the default), inserts opening comment delimiters just before the first non-whitespace character of each line. Otherwise, inserts opening comment delimiters at the start of each line.

See also: delete-comments.

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, useTimeStamp=True)[source]

Back up given fileName or c.fileName(). If useTimeStamp is True, append a timestamp to the filename.

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

cleanRecentFiles(event=None)[source]

Remove items from the recent files list that are no longer valid.

clearAllHoists()[source]

Undo a previous hoist of an outline.

clearAllMarked()[source]
clearAllVisited()[source]
clearMarked(p)[source]
clearRecentFiles(event=None)[source]

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

clone(event=None)[source]

Create a clone of the selected outline.

cloneFindAllFlattenedMarked(event=None)[source]

clone-find-all-flattened-marked, aka cffm.

Create an organizer node whose direct children are clones of all marked nodes. 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.

cloneFindAllMarked(event=None)[source]

clone-find-all-marked, aka cfam.

Create an organizer node whose descendants contain clones of all marked nodes. The list is not flattened: clones appear only once in the descendants of the organizer node.

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’
cloneFindMarkedHelper(flatten)[source]

Helper for clone-find-marked commands.

cloneFindParents(event=None)[source]

Create an organizer node whose direct children are clones of all parents of the selected node, which must be a clone.

cloneMarked(event=None)[source]

Clone all marked nodes as children of a new node.

cloneToAtSpot(event=None)[source]

Create a clone of the selected node and move it to the last @spot node of the outline. Create the @spot node if necessary.

cloneToLastNode(event=None)[source]

Clone the selected node and move it to the last node. Do not change the selected node.

close(event=None, new_c=None)[source]

Close the Leo window, prompting to save it if it has been changed.

colorPanel(event=None)[source]

Open the color dialog.

command_count = 0
computeCopiedBunchList(pasted, vnodeInfoDict)[source]
computeVnodeInfoDict()[source]
computeWindowTitle(fileName)[source]

Set the window title and fileName.

contractAllHeadlines(event=None)[source]

Contract all nodes in the outline.

contractAllOtherNodes(event=None)[source]

Contract all nodes except those needed to make the presently selected node visible.

contractIfNotCurrent(p, leaveOpen)[source]
contractNode(event=None)[source]

Contract the presently selected node.

contractNodeOrGoToParent(event=None)[source]

Simulate the left Arrow Key in folder of Windows Explorer.

contractParent(event=None)[source]

Contract the parent of the presently selected node.

contractSubtree(p)[source]
convertAllBlanks(event=None)[source]

Convert all blanks to tabs in the selected outline.

convertAllTabs(event=None)[source]

Convert all tabs to blanks in the selected outline.

convertBlanks(event=None)[source]

Convert all blanks to tabs in the selected node.

convertTabs(event=None)[source]

Convert all tabs to blanks in the selected node.

copyMarked(event=None)[source]

Copy all marked nodes as children of a new node.

copyOutline(event=None)[source]

Copy the selected outline to the clipboard.

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.

createLastChildNode(parent, headline, body)[source]

A helper function for the three extract commands.

createMoveMarkedNode()[source]
createMyLeoSettings()[source]

createMyLeoSettings - Return true if myLeoSettings.leo created ok

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.

cutOutline(event=None)[source]

Delete the selected outline and send it to the clipboard.

dedentBody(event=None)[source]

Remove one tab’s worth of indentation from all presently selected lines.

dehoist(event=None)[source]

Undo a previous hoist of an outline.

deleteComments(event=None)[source]

Removes one level of comment delimiters from all selected lines. The applicable @language directive determines the comment delimiters to be removed.

Removes single-line comments if possible; removes block comments for languages like html that lack single-line comments.

See also: add-comments.

deleteMarked(event=None)[source]

Delete all marked nodes.

deleteOutline(event=None, op_name='Delete Node')[source]

Deletes the selected outline.

deletePositionsInList(aList, callback=None)[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.

demote(event=None)[source]

Make all following siblings children of the selected node.

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

Dump all nodes in the outline.

dumpPosition(p)[source]

Dump position p and it’s ancestors.

editHeadline(event=None)[source]

Begin editing the headline of the selected node.

edit_widget(p)[source]
enableMenuBar()[source]

A failed attempt to work around Ubuntu Unity memory bugs.

endEditing()[source]
endUpdate(flag=True)[source]

Request a redraw of the screen if flag is True.

endsParagraph(s)[source]

Return True if s is a blank line.

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.

expandAllHeadlines(event=None)[source]

Expand all headlines. Warning: this can take a long time for large outlines.

expandAllSubheads(event=None)[source]

Expand all children of the presently selected node.

expandLevel1(event=None)[source]

Expand the outline to level 1

expandLevel2(event=None)[source]

Expand the outline to level 2

expandLevel3(event=None)[source]

Expand the outline to level 3

expandLevel4(event=None)[source]

Expand the outline to level 4

expandLevel5(event=None)[source]

Expand the outline to level 5

expandLevel6(event=None)[source]

Expand the outline to level 6

expandLevel7(event=None)[source]

Expand the outline to level 7

expandLevel8(event=None)[source]

Expand the outline to level 8

expandLevel9(event=None)[source]

Expand the outline to level 9

expandNextLevel(event=None)[source]

Increase the expansion level of the outline and Expand all nodes at that level or lower.

expandNode(event=None)[source]

Expand the presently selected node.

expandNodeAndGoToFirstChild(event=None)[source]

If a node has children, expand it if needed and go to the first child.

expandNodeOrGoToFirstChild(event=None)[source]

Simulate the Right Arrow Key in folder of Windows Explorer.

expandOnlyAncestorsOfNode(event=None, p=None)[source]

Contract all nodes in the outline.

expandPrevLevel(event=None)[source]

Decrease the expansion level of the outline and Expand all nodes at that level or lower.

expandSubtree(v)[source]
expandToLevel(level)[source]
exportHeadlines(event=None)[source]

Export all headlines to an external file.

extract(event=None)[source]

Create child node from the selected body text.

  1. If the selection starts with a section reference, the section name become the child’s headline. All following lines become the child’s body text. The section reference line remains in the original body text.
  2. If the selection looks like a Python class or definition line, the class/function/method name becomes the child’s headline and all selected lines become the child’s body text.
  3. Otherwise, the first line becomes the child’s headline, and all selected lines become the child’s body text.
extractDef(s)[source]

Return the defined function/method name if s looks like Python def or class line.

extractPythonMethod(event=None)

Create child node from the selected body text.

  1. If the selection starts with a section reference, the section name become the child’s headline. All following lines become the child’s body text. The section reference line remains in the original body text.
  2. If the selection looks like a Python class or definition line, the class/function/method name becomes the child’s headline and all selected lines become the child’s body text.
  3. Otherwise, the first line becomes the child’s headline, and all selected lines become the child’s body text.
extractRef(s)[source]

Return s if it starts with a section name.

extractSection(event=None)

Create child node from the selected body text.

  1. If the selection starts with a section reference, the section name become the child’s headline. All following lines become the child’s body text. The section reference line remains in the original body text.
  2. If the selection looks like a Python class or definition line, the class/function/method name becomes the child’s headline and all selected lines become the child’s body text.
  3. Otherwise, the first line becomes the child’s headline, and all selected lines become the child’s body text.
extractSectionNames(event=None)[source]

Create child nodes for every section reference in the selected text. The headline of each new child node is the section reference. The body of each child node is empty.

fileName()[source]
findBoundParagraph(event=None)[source]

Return the lines of a paragraph to be reformatted.

findMatchingBracket(event=None)[source]

Select the text between matching brackets.

findNextClone(event=None)[source]

Select the next cloned node.

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.

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

flattenOutline(event=None)[source]

Export the selected outline to an external file. The outline is represented in MORE format.

flattenOutlineToNode(event=None)[source]

Append the body text of all descendants of the selected node to the body text of the selected node.

fontPanel(event=None)[source]

Open the font dialog.

force_redraw(p=None, setFocus=False)

Redraw the screen immediately.

fullCheckOutline(event=None)[source]

Performs a full check of the consistency of a .leo file.

As of Leo 5.1, Leo performs checks of gnx’s and outline structure before writes and after reads, pastes and undo/redo.

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

Select the next visited node.

goPrevVisitedNode(event=None)[source]

Select the previously visited node.

goToFirstNode(event=None)[source]

Select the first node of the entire outline.

goToFirstSibling(event=None)[source]

Select the first sibling of the selected node.

goToFirstVisibleNode(event=None)[source]

Select the first visible node of the selected chapter or hoist.

goToLastNode(event=None)[source]

Select the last node in the entire tree.

goToLastSibling(event=None)[source]

Select the last sibling of the selected node.

goToLastVisibleNode(event=None)[source]

Select the last visible node of selected chapter or hoist.

goToLineNumber(n)[source]

Go to line n (zero-based) of a script. Called from g.handleScriptException.

goToNextClone(event=None)[source]

Select the next node that is a clone of the selected node. If the selected node is not a clone, do find-next-clone.

goToNextDirtyHeadline(event=None)[source]

Select the node that is marked as changed.

goToNextHistory(event=None)[source]

Go to the next node in the history list.

goToNextMarkedHeadline(event=None)[source]

Select the next marked node.

goToNextSibling(event=None)[source]

Select the next sibling of the selected node.

goToParent(event=None)[source]

Select the parent of the selected node.

goToPrevHistory(event=None)[source]

Go to the previous node in the history list.

goToPrevSibling(event=None)[source]

Select the previous sibling of the selected node.

goToScriptLineNumber(n, p)[source]

Go to line n (zero-based) of a script. Called from g.handleScriptException.

hasAmbiguousLanguage(p)[source]

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

hash()[source]
hideInvisibles(event=None)[source]

Hide invisible (whitespace) characters.

hoist(event=None)[source]

Make only the selected outline visible.

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

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

importAnyFile(event=None)[source]

Import one or more files.

importAtFile(event=None)

Import one or more files.

importAtRoot(event=None)

Import one or more files.

importCWEBFiles(event=None)

Import one or more files.

importDerivedFile(event=None)

Import one or more files.

importFlattenedOutline(event=None)

Import one or more files.

importMOREFiles(event=None)

Import one or more files.

importNowebFiles(event=None)

Import one or more files.

importTabFiles(event=None)

Import one or more files.

indentBody(event=None)[source]

The indent-region command indents each line of the selected body text, or each line of a node if there is no selected text. The @tabwidth directive in effect determines amount of indentation. (not yet) A numeric argument specifies the column to indent to.

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

Insert a time/date stamp at the cursor.

insertChild(event=None)[source]

Insert a node after the presently selected node.

insertHeadline(event=None, op_name='Insert Node', as_child=False)[source]

Insert a node after the presently selected node.

insertHeadlineBefore(event=None)[source]

Insert a node before the presently selected node.

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.

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

Open LeoDocs.leo in a new Leo window.

leoHome(event=None)[source]

Open Leo’s Home page in a web browser.

leoQuickStart(event=None)[source]

Open quickstart.leo in a new Leo window.

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.

markChangedHeadlines(event=None)[source]

Mark all nodes that have been changed.

markChangedRoots(event=None)[source]

Mark all changed @root nodes.

markHeadline(event=None)[source]

Toggle the mark of the selected node.

markSubheads(event=None)[source]

Mark all children of the selected node as changed.

minibufferWantsFocus()[source]
minibufferWantsFocusNow()[source]
moveMarked(event=None)[source]

Move all marked nodes as children of a new node. This command is not undoable. Consider using clone-marked-nodes, followed by copy/paste instead.

moveOutlineDown(event=None)[source]

Move the selected node down.

moveOutlineLeft(event=None)[source]

Move the selected node left if possible.

moveOutlineRight(event=None)[source]

Move the selected node right if possible.

moveOutlineUp(event=None)[source]

Move the selected node up if possible.

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.

new(event=None, gui=None)[source]

Create a new Leo window.

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.

open(event=None)[source]

Open a Leo window containing the contents of a .leo file.

openCheatSheet(event=None, redraw=True)[source]

Open leo/doc/cheatSheet.leo

openCompareWindow(event=None)[source]

Open a dialog for comparing files and directories.

openLeoDist(event=None)[source]

Open leoDist.leo in a new Leo window.

openLeoPlugins(event=None)[source]

Open leoPlugins.leo in a new Leo window.

openLeoPy(event=None)[source]

Open leoPy.leo in a new Leo window.

openLeoScripts(event=None)[source]

Open scripts.leo.

openLeoSettings(event=None)[source]

Open leoSettings.leo in a new Leo window.

openLeoTOC(event=None)[source]

Open Leo’s tutorials page in a web browser.

openLeoTutorials(event=None)[source]

Open Leo’s tutorials page in a web browser.

openLeoUsersGuide(event=None)[source]

Open Leo’s users guide in a web browser.

openLeoVideos(event=None)[source]

Open Leo’s videos page in a web browser.

openMyLeoSettings(event=None)[source]

Open myLeoSettings.leo in a new Leo window.

openPythonWindow(event=None)[source]

Open Python’s Idle debugger in a separate process.

openRecentFile(fn=None)[source]
openUnittest(event=None)[source]

Open unittest.leo.

openWith(event=None, d=None)[source]

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

Export the selected outline to an external file. The outline is represented in CWEB format.

outlineToNoweb(event=None)[source]

Export the selected outline to an external file. The outline is represented in noweb format.

p

commander current position property

pasteOutline(event=None, reassignIndices=True, redrawFlag=True, s=None, tempOutline=False, undoFlag=True)[source]

Paste an outline into the present outline from the clipboard. Nodes do not retain their original identify.

pasteOutlineRetainingClones(event=None)[source]

Paste an outline into the present outline from the clipboard. Nodes retain their original identify.

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

Return True if a position exists in c’s tree

preferences(event=None)[source]

Handle the preferences command.

printCommandsDict()[source]
promote(event=None, undoFlag=True, redrawFlag=True)[source]

Make all children of the selected nodes siblings of the selected node.

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

Helper for various help commands.

raise_error_dialogs(kind='read')[source]

Warn abouit read/write failures.

readAtAutoNodes(event=None)[source]

Read all @auto nodes in the presently selected outline.

readAtFileNodes(event=None)[source]

Read all @file nodes in the presently selected outline.

readAtShadowNodes(event=None)[source]

Read all @shadow nodes in the presently selected outline.

readFileIntoNode(event=None)[source]

Read a file into a single node.

readOutlineOnly(event=None)[source]

Open a Leo outline from a .leo file, but do not read any derived files.

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

Force a full recolor.

recolor_now(p=None, incremental=False, interruptable=True)[source]
recreateGnxDict()[source]

Recreate the gnx dict prior to refreshing nodes from disk.

recursiveImport(dir_, kind, one_file=False, 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’). one_file True: import only the file given by dir_. safe_at_file True: produce @@file nodes instead of @file nodes. theTypes 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, or all icons if the ‘all’ flag is true.

redraw_after_select(p)[source]

Redraw the screen after node p has been selected.

redraw_now(p=None, setFocus=False)

Redraw the screen immediately.

reformatBody(event=None)[source]

Reformat all paragraphs in the body.

reformatParagraph(event=None, undoType='Reformat Paragraph')[source]

Reformat a text paragraph

Wraps the concatenated text to present page width setting. Leading tabs are sized to present tab width setting. First and second line of original text is used to determine leading whitespace in reformatted text. Hanging indentation is honored.

Paragraph is bound by start of body, end of body and blank lines. Paragraph is selected by position of current insertion cursor.

refreshFromDisk(event=None)[source]

Refresh an @<file> node from disk.

relativeFileName()[source]
reloadAllSettings(event=None)[source]

Reload all static abbreviations from all config files.

reloadSettings(event=None)[source]

Reload all static abbreviations from all config files.

reloadSettingsHelper(all)[source]

Reload settings in all commanders, or just self.

reloadSubcommanderSettings()[source]

Reload settings in all subcommanders that have either a reload_settings or reloadSettings method.

removeSentinels(event=None)[source]

Import one or more files, removing any sentinels.

requestRecolor()[source]
request_focus(w)[source]
revert(event=None)[source]

Revert the contents of a Leo outline to last saved contents.

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.

rp_get_args()[source]

Compute and return oldSel,oldYview,original,pageWidth,tabWidth.

rp_get_leading_ws(lines, tabWidth)[source]

Compute and return indents and leading_ws.

rp_reformat(head, oldSel, oldYview, original, result, tail, undoType)[source]

Reformat the body and update the selection.

rp_wrap_all_lines(indents, leading_ws, lines, pageWidth)[source]

Compute the result of wrapping all lines.

safe_all_positions()[source]

A generator returning all positions of the outline. This generator does not assume that vnodes are never their own ancestors.

save(event=None, fileName=None)[source]

Save a Leo outline to a file.

saveAll(event=None)[source]

Save all open tabs windows/tabs.

saveAs(event=None, fileName=None)[source]

Save a Leo outline to a file with a new filename.

saveAsUnzipped(event=None)[source]

Save a Leo outline to a file with a new filename, ensuring that the file is not compressed.

saveAsZipped(event=None)[source]

Save a Leo outline to a file with a new filename, ensuring that the file is compressed.

saveAsZippedHelper(isZipped)[source]
saveTo(event=None, fileName=None)[source]

Save a Leo outline to a file, leaving the file associated with the Leo outline unchanged.

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.

selectAtSettingsNode(event=None)[source]

Select the @settings node, if there is one.

selectPosition(p, enableRedrawFlag=True)[source]

Select a new position.

selectThreadBack(event=None)[source]

Select the node preceding the selected node in outline order.

selectThreadNext(event=None)[source]

Select the node following the selected node in outline order.

selectVisBack(event=None)[source]

Select the visible node preceding the presently selected node.

selectVisNext(event=None)[source]

Select the visible node following the presently selected node.

selectVnode(p, enableRedrawFlag=True)

Select a new position.

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.

showInvisibles(event=None)[source]

Show invisible (whitespace) characters.

showInvisiblesHelper(val)[source]
singleLineParagraph(s)[source]

Return True if s is a single-line paragraph.

sortChildren(event=None, key=None, reverse=False)[source]

Sort the children of a node.

sortRecentFiles(event=None)[source]

Sort the recent files list.

sortSiblings(event=None, key=None, p=None, sortChildren=False, reverse=False)[source]

Sort the siblings of a node.

startsParagraph(s)[source]

Return True if line s starts a paragraph.

syntaxErrorDialog()[source]

Warn about syntax errors in files.

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

Check indentation using tabnanny.

tangle(event=None)[source]

Tangle all @root nodes in the selected outline.

Important: @root and all tangle and untangle commands are deprecated. They are documented nowhere but in these docstrings.

tangleAll(event=None)[source]

Tangle all @root nodes in the entire outline.

Important: @root and all tangle and untangle commands are deprecated. They are documented nowhere but in these docstrings.

tangleMarked(event=None)[source]

Tangle all marked @root nodes in the entire outline.

Important: @root and all tangle and untangle commands are deprecated. They are documented nowhere but in these docstrings.

toggleAngleBrackets(event=None)[source]

Add or remove double angle brackets from the headline of the selected node.

toggleShowInvisibles(event=None)[source]

Toggle showing of invisible (whitespace) characters.

toggleSparseMove(event=None)[source]

Toggle whether moves collapse the outline.

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.

unformatParagraph(event=None, undoType='Unformat Paragraph')[source]

Unformat a text paragraph. Removes all extra whitespace in a paragraph.

Paragraph is bound by start of body, end of body and blank lines. Paragraph is selected by position of current insertion cursor.

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.

unmarkAll(event=None)[source]

Unmark all nodes in the entire outline.

unredirectScriptOutput()[source]
unreformat(head, oldSel, oldYview, original, result, tail, undoType)[source]

unformat the body and update the selection.

untangle(event=None)[source]

Untangle all @root nodes in the selected outline.

Important: @root and all tangle and untangle commands are deprecated. They are documented nowhere but in these docstrings.

untangleAll(event=None)[source]

Untangle all @root nodes in the entire outline.

Important: @root and all tangle and untangle commands are deprecated. They are documented nowhere but in these docstrings.

untangleMarked(event=None)[source]

Untangle all marked @root nodes in the entire outline.

Important: @root and all tangle and untangle commands are deprecated. They are documented nowhere but in these docstrings.

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.

weave(event=None)[source]

Simulate a literate-programming weave operation by writing the outline to a text file.

widgetWantsFocus(w)[source]
widgetWantsFocusNow(w)[source]
widget_name(widget)[source]
writeFileFromNode(event=None)[source]

If node starts with @read-file-into-node, use the full path name in the headline. Otherwise, prompt for a file name.

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_open_files(f1, f2, name1, name2)[source]
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.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.

leo.core.leoCompare.choose(cond, a, b)[source]
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(name)[source]

Command decorator for the FileCommands class.

compactFileIndices()

Assign a file index to all tnodes

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, v=None)[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.

deleteFileWithMessage(fileName, unused_kind)[source]
dumpSaxTree(root, dummy)[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, tempOutline=False)

Read a Leo outline from string s in clipboard format.

getLeoOutlineFromClipboard(s, reassignIndices=True, tempOutline=False)[source]

Read a Leo outline from string s in clipboard format.

getSaxUa(attr, val, kind=None)[source]

Parse an unknown attribute in a <v> or <t> element. The unknown tag has been pickled and hexlify’d.

handleNodeConflicts()[source]

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

handleTnodeSaxAttributes(sax_node, v)[source]
handleVnodeSaxAttributes(sax_node, v)[source]
handleWriteLeoFileException(fileName, backupName, theActualFile)[source]
initIvars()[source]

Init ivars of the FileCommands class.

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

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

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]
save(fileName, silent=False)[source]
saveAs(fileName)[source]
saveTo(fileName)[source]
setDefaultDirectoryForNewFiles(fileName)[source]

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

setPositionsFromVnodes()[source]
updateFixedStatus()[source]
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]
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(name)[source]

Command decorator for the findCommands class.

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.

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.

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

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, 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]
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.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.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()
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,timer.c.shortFileName(),'%2.4f' % (delta_t))
    if timer.count >= 5:
        g.trace('done')
        timer.stop()

# Execute handler every 500 msec. at idle time.
timer = g.IdleTime(c,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 %s %2.4f' % (timer.count,timer.c.shortFileName(),delta_t))
    if timer.count >= 5:
        g.trace('done')
        timer.stop()

def handler2(timer):
    delta_t = timer.time-timer.starting_time
    g.trace('%2s %s %2.4f' % (timer.count,timer.c.shortFileName(),delta_t))
    if timer.count >= 10:
        g.trace('done')
        timer.stop()

timer1 = g.IdleTime(c,handler1,delay=500)
timer2 = g.IdleTime(c,handler2,delay=1000)
if timer1 and timer2:
    timer1.start()
    timer2.start()
class leo.core.leoGlobals.KeyStroke(s)[source]

Bases: object

A class that announces that its contents has been canonicalized by k.strokeFromSetting.

This allows type-checking assertions in the code.

find(pattern)[source]
isFKey()[source]
lower()[source]
startswith(s)[source]
toGuiChar()[source]

Replace special chars by the actual gui 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.

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.

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.ShortcutInfo(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.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]
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]
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.blue(*args, **keys)[source]
leo.core.leoGlobals.bunch

alias of Bunch

leo.core.leoGlobals.callback(func)[source]

A global decorator that protects Leo against crashes in callbacks.

This is the recommended way of defining all callback.

@g.callback def a_callback(...):

c = event.get(‘c’) ...
leo.core.leoGlobals.callers(n=4, count=0, excludeCaller=True, files=False)[source]

Return a list containing the callers of the function that called g.callerList.

If the excludeCaller keyword is True (the default), g.callers is not on the list.

If the files keyword argument is True, filenames are included in the list.

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 Command

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.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.dictToString(d, tag=None, verbose=True, indent='')[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.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.extractExecutableString(c, p, s, language='python')[source]

Return all lines for the given @language directive.

Ignore all lines under control of any other @language directive.

leo.core.leoGlobals.fileLikeObject

alias of 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)[source]
leo.core.leoGlobals.findNodeInChildren(c, p, headline)[source]

Search for a node in v’s tree matching the given headline.

leo.core.leoGlobals.findNodeInTree(c, p, headline)[source]

Search for a node in v’s tree matching the given headline.

leo.core.leoGlobals.findReference(c, 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)[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)[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]
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.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.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.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.isShortcutInfo(obj)[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.listToString(aList, tag=None, sort=False, indent='', toRepr=False)[source]
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(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 NullObject

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 {{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_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, 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.prettyPrintType(obj)[source]
leo.core.leoGlobals.printDict(d, tag='', verbose=True, indent='')[source]

Pretty print a Python dict 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(aList, tag=None, sort=False, indent='')[source]
leo.core.leoGlobals.printNewObjects(tag='')

Print newly allocated objects.

leo.core.leoGlobals.printObj(obj, tag=None, sort=False, verbose=True, indent='')[source]
leo.core.leoGlobals.printStack()[source]
leo.core.leoGlobals.printStats(name=None)[source]
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()

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.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.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]
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_php_braces(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, tag=None, sort=False, verbose=True, indent='')[source]
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.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]
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.

createImportParent(current, files)[source]

Create a parent node for nodes with a common prefix: x.h & x.cpp.

createOutline(fileName, parent, atAuto=False, atShadow=False, s=None, ext=None)[source]

Create an outline by importing a file or string.

createOutlineFromWeb(path, parent)[source]
create_top_node(atAuto, atAutoKind, fileName, parent)[source]

Create the top node.

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, treeType=None, redrawFlag=True, shortFn=False)[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]
iniUnitTest(p, fileName=None, s=None, showTree=False)[source]
init_import(atAuto, atShadow, ext, fileName, s)[source]

Init ivars & vars for imports.

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

Scan the text of an unknown file type.

scanWebFile(fileName, parent)[source]
scannerUnitTest(p, atAuto=False, 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, atAuto=False)[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, one_file=False, safe_at_file=True, theTypes=None)[source]

Bases: object

Recursively import all python files in a directory and clean the result.

clean(p, ext)[source]
  • Move a shebang line from the first child to the root.
  • Move a leading docstring in the first child to the root.
  • Use a section reference for declarations.
  • Remove leading and trailing blank lines from all nodes.
  • Merge a node containing nothing but comments with the next node.
  • Merge a node containing no class or def lines with the previous node.
clean_all(dir_, p)[source]

Clean all imported nodes. This takes a lot of time.

clean_blank_lines(p)[source]

Remove leading and trailing blank lines from all nodes.

clear_dirty_bits(p)[source]
dump_headlines(p)[source]
file_pattern = <_sre.SRE_Pattern object>
fix_back_slashes(p)[source]

Convert backslash to slash in all headlines.

import_dir(dir_, root)[source]

Import selected files from dir_, a directory.

merge_comment_nodes(p, delim)[source]

Merge a node containing nothing but comments with the next node.

merge_extra_nodes(p)[source]

Merge a node containing no class or def lines with the previous node

minimize_headlines(p, prefix)[source]

Create @path nodes to minimize the paths required in descendant nodes.

move_decorator_lines(p)[source]

Move trailing decorator lines to the next node.

move_doc_string(root)[source]

Move a leading docstring in the first child to the root node.

move_shebang_line(root)[source]

Move a shebang line from the first child to the root.

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

Use a section reference for declarations.

run(dir_)[source]

Import all the .py files in dir_.

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(pos, 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. 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()
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(name)[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]
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.

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.

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.