Leo 作弊条儿

注意: The easiest way to find documentation is to search LeoDocs.leo.

Key bindings

Selecting outline nodes

When focus is in the outline pane:

Right-arrow (expand-and-go-right)
Left-arrow (contract-or-go-left)
Up-arrow (goto-prev-visible)
Down-arrow (goto-next-visible)

Regardless of focus:

Alt-Home (goto-first-visible-node)
Alt-End (goto-last-visible-node)
Alt-Right-arrow (expand-and-go-right)
Alt-Left-arrow (contract-or-go-left)
Alt-Up-arrow (goto-prev-visible)
Alt-Down-arrow (goto-next-visible)

Moving outline nodes

When focus is in the outline:

Shift-Down-arrow (move-outline-down)
Shift-Left-arrow (move-outline-left)
Shift-Right-arrow (move-outline-right)
Shift-Up-arrow (move-outline-up)

Regardless of focus:

Alt-Shift-Down-arrow (move-outline-down)
Alt-Shift-Left-arrow (move-outline-left)
Alt-Shift-Right-arrow (move-outline-right)
Alt-Shift-Up-arrow (move-outline-up)
Ctrl-D (move-outline-down)
Ctrl-L (move-outline-left)
Ctrl-R (move-outline-right)
Ctrl-U (move-outline-up)

Moving the cursor

When focus is in any of Leo’s text panes (body pane, log pane, headlines):

Key Move Cursor
Arrow keys one character
Ctrl-LeftArrow back one word
Ctrl-RightArrow forward one word
Home beginning of line
End end of line
Ctrl-Home beginning of the body
Ctrl-End end of body
PageDown down one page
PageUp up one page

Adding the Shift key modifier to any of the keys above moves the cursor and extends the selected text.

Frequently used commands

For much more information, see the Commands Reference.

Copy/Paste (text):

Ctrl-C (copy-text)
Ctrl-K (kill)
Ctrl-V (paste-text)
Ctrl-X (cut-text)
Ctrl-Y (yank)
Alt-Y  (yank-pop)
kill-...

Files:

Ctrl-N (new)
Ctrl-O (open-outline)
Ctrl-S (save-file)
Ctrl-Q (exit-leo)

Focus:

Alt-T (focus-to-tree)
Ctrl-T (toggle-active-pane)
Ctrl-Tab (tab-cycle-next)

Help:

Alt-0 (vr-toggle)
F1 (help)
F11 (help-for-command)
F12 (help-for-python)
print-bindings
print-settings
help-for-...

Find/Replace:

Ctrl-F (search-with-present-options)
Shift-Ctrl-R (replace-string)
Ctrl-minus (replace-then-find)
F3 (find-next)
F2 (find-previous)

Minibuffer:

Alt-X (full-command)
Ctrl-G (keyboard-quit)
Tab (not a command, completes typing)

Nodes:

Ctrl-I or Insert (insert-node)
Ctrl-H (edit-headline)
<Return> (when editing a headline) (end-edit-headline)
Ctrl-Shift-C (copy-node)
Ctrl-Shift-X (cut-node)
Ctrl-Shift-V (paste-node)
Ctrl-{ (promote)
Ctrl-} (demote)
Ctrl-M (mark)

Undo:

Ctrl-Z (undo)
Ctrl-Shift-Z (redo)

Gathering find commands

The clone find commands, cfa and cff, move clones of all nodes matching the search pattern under a single organizer node, created as the last top-level node. Flattened searches put all nodes as direct children of the organizer node:

cfa     clone-find-all
cff     clone-find-all-flattened

The clone-marked commands move clones of all marked nodes under an organizer node. Especially useful for gathering nodes by hand:

cfam    clone-find-marked
cffm    clone-find-flattened-marked

Leo directives

Directives starting with ‘@ in the leftmost column

See the Directives reference for full details:

@                       # starts doc part
@c                      # ends doc part
@color
@doc                    # starts doc part
@killcolor
@nocolor
@language python
@language c
@language rest          # restructured text
@language plain         # plain text: no syntax coloring.
@lineending lineending
@nosearch               # suppress searching for cff & cfa commands.
@pagewidth 100
@raw, @end_raw          # @file only.
@tabwidth -4            # use spaces
@tabwidth 8             # use tabs
@nowrap
@wrap

Leading whitespace is allowed (and significant) for:

@all
@others

Settings

For documentation see node: “About this file” in leoSettings.leo:

Command history:    @history-list
Key bindings:       @shortcuts
Visual settings:    @data qt-gui-plugin-style-sheet
Enabling plugins:   @enabled-plugins

To disable a binding for a key, bind it to do-nothing:

do-nothing = Insert

This overrides the following default binding in leoSettings.leo:

insert-node = Insert

Node types

Supported by Leo’s core:

@chapter
@rst, @rst-no-head, @rst-ignore, @rst-ignore-tree
@settings
@test, @testsetup, @testclass
@url

Within @settings trees:

@bool, @buttons, @color, @commands
@directory, @encoding
@enabled-plugins, @float, @font,
@history-list, @int
@menus, @menu, @menuat, @item
@openwith, @path, @shortcuts, @string

Supported by plugins:

bookmarks.py:       @bookmarks, @bookmark
at_folder.py:       @folder
at_produce.py:      @produce
at_view.py:         @clip, @strip, @view
expfolder.py:       @expfolder
mod_scripting.py:   @button, @command, @script
viewrendered.py:    @graphics-script, @image
                    @html, @movie, @svg

Notable Plugins

See the docstring of these plugins for more details:

bookmarks.py:       Manages URL's used as bookmarks.
contextmenu.py:     Creates context menus for headlines.
demo.py:            Creates demos and slides.
mod_scripting.py:   Supports @button and @command nodes.
quicksearch.py:     Adds Nav tab for searching.
todo.py:            To-do lists and simple project management.
valuespace.py:      Creates an outline-oriented spreadsheet.
viewrendered.py:    Creates a rendering pane.
                    Automatically loaded by Leo's help commands.
                    Supports @graphics-script, @image, @html,
                    @movie and @svg nodes.
vim.py & xemacs.py  Interface with vim and xemacs.

External files (@<file> nodes)

@<file> nodes create external files:

@asis <filename>        write only, no sentinels, exact line endings
@auto <filename>        recommended
@clean <filename>       recommended
@edit <filename>        @edit node contains entire file
@file <filename>        recommended
@nosent <filename>      write only, no sentinels

This table summarizes the differences between @<file> nodes:

                         Sections &   File data in
@<file> kind  Sentinels?  @others?    .leo file?    Notes
------------  ---------- -----------  ------------  -----
@asis          no          no          yes
@auto          no          yes         no           1, 2
@auto-xx       no          yes         no           1, 2
@clean         no          yes         yes
@edit          no          no          no
@file          yes         yes         no
@nosent        no          yes         yes

@auto nodes read files using language-specific importers. By default, the file’s extension determines the importer:

Extensions                  Importer
----------                  --------
.c, .cc, .c++, .cpp,.cxx    C
.cs', .c#'                  C Sharp
.el                         Elisp
.h, .h++                    C
.html, .htm                 HTML
.ini                        Config file
.ipynb                      Jupyter notebook
.java                       Java
.js                         JavaScript
.md                         Markdown
.org                        Org Mode
.otl                        Vim outline
.pas                        Pascal
.php                        PHP
.py, .pyi, .pyw             Python
.rest, .rst                 reStructuredText
.ts                         TypeScript
.xml                        XML

You can also specify importers explicitly as follows:

@auto-xxx           Importer
---------           --------
@auto-ctext         ctext
@auto-markdown      markdown
@auto-md            markdown
@auto-org           org-mode
@auto-org-mode      org-mode
@auto-otl           vimoutline
@auto-vim-outline   vimoutline
@auto-rst           reStructuredText

Important: The importers/exporters for markdown, org-mode, reStructuredText and vimoutline files automatically generate section headings corresponding to Leo’s outline level. Body text of the top-level @auto node is ignored.

See the Directives reference for full details.

Sections

Section names have the form:

<< any text, except double closing angle brackets >>

Section-definition nodes have headlines starting with a section name.

Leo performs expansions for all @<file> nodes except @asis.

Expansion of @all:

  • Leo replaces @all by the unexpanded body text of all nodes.

Expansion of section names and @others:

  • Leo replaces section names in body text by the expanded text of the corresponding section definition node.
  • Leo replaces @others with the expanded text of all nodes that aren’t section-definition nodes.

Scripting

This section lists the ivars, properties, functions and methods most commonly used in Leo scripts.

Very important: use Alt-1 (toggle-autocompleter) and Alt-2 (toggle-calltips) to recreate these lists as you type.

Pre-defined symbols

execute-script predefines:

c: The commander of the present outline.
g: The leo.core.leoGlobals module.
p: The presently selected position, c.p.

@test scripts predefine all the above, plus:

self: The instance of unittest.TestCase

LeoApp class

Ivars:

g.app                   A LeoApp instance.
g.app.gui               A LeoGui instance.
g.app.pluginsController A LeoPluginsController instance.
g.app.*                 Leo's global variables.

Commands class

Ivars:

c.config                c's configuration object
c.frame                 c's outer frame, a leoFrame instance.
c.undoer                c's undo handler.
c.user_dict             A temporary dict for use of scripts and plugins.

SubCommanders:

# In leo/core...
c.atFileCommands
c.chapterController
c.fileCommands
c.findCommands
c.importCommands
c.keyHandler = c.k
c.persistenceController
c.printingController
c.rstCommands
c.shadowController
c.tangleCommands
c.testManager
c.vimCommands

# In leo/commands...
c.abbrevCommands
c.controlCommands
c.convertCommands
c.debugCommands
c.editCommands
c.editFileCommands
c.gotoCommands
c.helpCommands
c.keyHandlerCommands
c.killBufferCommands
c.rectangleCommands
c.spellCommands

Generators (New in Leo 5.5: All generators yield distinct positions):

c.all_positions()
c.all_unique_positions()

Most useful methods:

c.isChanged()
c.deletePositionsInList(aList, callback=None)
                        # safely deletes all the positions in aList.
c.positionExists(p)
c.redraw(p=None)        # Redraw the screen. Select p if given.
c.save()                # Save the present outline.
c.selectPosition()

Official ivars of any leoFrame f:

f.c                     is the frame’s commander.
f.body                  is a leoBody instance.
f.body.bodyCtl          is a leoQTextEditWidget instance.
f.body.bodyCtrl.widget  is a LeoQTextBrowser(QTextBrowser) instance.
f.log                   is a leoLog instance.
f.tree                  is a leoQtTree instance.
f.tree.treeWidget       is a LeoQTreeWidget (a QTreeWidget) instance.

Use autocompletion to explore these objects!

VNode class

Ivars:

v.b:    v's body text.
v.gnx   v's gnx.
v.h:    v's headline text.
v.u:    v.unknownAttributes, a persistent Python dictionary.

v.u (uA’s or unknownAttributes or userAttributes) allow plugins or scripts to associate persistent data with vnodes. For details see the section about userAttributes in the Customizing Leo chapter.

Position class

Properties:

p.b: same as p.v.b.  *Warning*: p.b = s is expensive.
p.h: same as p.v.h.  *Warning*: p.h = s is expensive.
p.u: same as p.v.u.

Generators (New in Leo 5.5: All generators yield distinct positions):

p.children()
p.parents()
p.self_and_parents()
p.self_and_siblings()
p.following_siblings()
p.subtree()
p.self_and_subtree()

Getters These return new positions:

p.back()
p.children()
p.copy()
p.firstChild()
p.hasBack()
p.hasChildren()
p.hasNext()
p.hasParent()
p.hasThreadBack()
p.hasThreadNext()
p.isAncestorOf(p2)
p.isAnyAtFileNode()
p.isAt...Node()
p.isCloned()
p.isDirty()
p.isExpanded()
p.isMarked()
p.isRoot()
p.isVisible()
p.lastChild()
p.level()
p.next()
p.nodeAfterTree()
p.nthChild()
p.numberOfChildren()
p.parent()
p.parents()
p.threadBack()
p.threadNext()
p.visBack()
p.visNext()

Setters:

p.setDirty()  *Warning*: p.setDirty() is expensive.
p.setMarked()

Operations on nodes:

p.clone()
p.contract()
p.doDelete(new_position)
p.expand()
p.insertAfter()
p.insertAsNthChild(n)
p.insertBefore()
p.moveAfter(p2)
p.moveToFirstChildOf(parent,n)
p.moveToLastChildOf(parent,n)
p.moveToNthChildOf(parent,n)
p.moveToRoot(oldRoot=None)
    # oldRoot **must** be the old root position if it exists.

Moving positions

The following move positions themselves: they change the node to which a position refers. They do not change outline structure in any way! Use these when generators are not flexible enough:

p.moveToBack()
p.moveToFirstChild()
p.moveToLastChild()
p.moveToLastNode()
p.moveToNext()
p.moveToNodeAfterTree(p2)
p.moveToNthChild(n))
p.moveToParent()
p.moveToThreadBack()
p.moveToThreadNext()
p.moveToVisBack(c)
p.moveToVisNext(c)

leo.core.leoGlobals module

For full details, see @file leoGlobals.py in LeoPyRef.leo.

g vars:

g.app
g.app.gui
g.app.windowlist
g.unitTesting
g.user_dict  # a temporary dict for use of scripts and plugins.

g decorator:

@g.command(command-name)

g functions (the most interesting: there are many more in leoGlobals.py):

g.angleBrackets()
g.app.commanders()
g.app.gui.guiName()
g.es(*args,**keys)
g.es_print(*args,**keys)
g.es_exception()
g.getScript(c,p,
    useSelectedText=True,
    forcePythonSentinels=True,
    useSentinels=True)
g.openWithFileName(fileName,old_c=None,gui=None)
g.os_path_... # Wrappers for os.path methods.
g.pdb(message='')
g.toEncodedString(s,encoding='utf-8',reportErrors=False)
g.toUnicode(s, encoding='utf-8',reportErrors=False)
g.trace(*args,**keys)
g.warning(*args,**keys)

Test driven development

  • Use imp.reload to reload all changed modules.
  • Make sure to instantiate any changed objects.
  • See this section for full details.

Performance gotchas

Warning: The p.b and p.h setters and p.setDirty() are very expensive:

  • p.b = s calls c.setBodyString(p, s) which will recolor body text and update the node’s icon.
  • p.h = s calls c.setHeadString(p, s) which calls p.setDirty().
  • p.setDirty() changes the icons of all ancestor @file nodes.

In contrast, the corresponding p.v.b and p.v.b setters and p.v.setDirty() are extremely fast.

Usually, code should use the p.b and p.h setters and p.setDirty(), despite their cost, because they update Leo’s outline pane properly. Calling c.redraw() is not enough.

These performance gotchas become important for repetitive commands, like cff, replace-all and recursive import. In such situations, code should use p.v.b and p.v.h setters instead of p.b and p.h setters.

About names

Scripts may safely assume that most names defined in Leo’s core will never change. Names used outside their defining module can’t be changed, because doing so would impact existing user scripts. This includes virtually everything in leoGlobals.py, and many names in leoCommands.py and other files. The only names that might change are unlikely every to be of use to scripts anyway. For example, helper functions.

Command-line options

Usage: launchLeo.py [options] file1, file2, ...

Options:
  -h, --help            show this help message and exit
  --debug               enable debug mode
  --diff                use Leo as an external git diff
  --fullscreen          start fullscreen
  --ipython             enable ipython support
  --fail-fast           stop unit tests after the first failure
  --gui=GUI             gui to use (qt/qttabs)
  --load-type=LOAD_TYPE
                        @<file> type for loading non-outlines from command
                        line
  --maximized           start maximized
  --minimized           start minimized
  --no-cache            disable reading of cached files
  --no-plugins          disable all plugins
  --no-splash           disable the splash screen
  --screen-shot=SCREENSHOT_FN
                        take a screen shot and then exit
  --script=SCRIPT       execute a script and then exit
  --script-window=SCRIPT_WINDOW
                        open a window for scripts
  --select=SELECT       headline or gnx of node to select
  --session-restore     restore previously saved session tabs at startup
  --session-save        save session tabs on exit
  --silent              disable all log messages
  --trace-plugins       trace imports of plugins
  -v, --version         print version number and exit
  --window-size=WINDOW_SIZE
                        initial window size (height x width)