.. @+leo-ver=5-thin
.. @+node:ekr.20031218072017.329: * @file ../doc/leoNotes.txt
.. @@language rest

.. @+all
.. @+node:ekr.20131030053655.17092: ** bzr hooks: prototypes
.. @+node:ekr.20131030053655.17093: *3* @@file c:\apps\Bazaar\plugins\push_hook.py
from bzrlib import branch

def post_push_hook(arg):
    # print "The new revno is %d" % push_result.new_revno
    print('post_push_hook')
    # print('\n'.join(dir(arg)))
    
if 0: # Disable.
    branch.Branch.hooks.install_named_hook(
        'post_push', post_push_hook,'EKR post_push hook')
.. @+node:ekr.20131030053655.17094: *3* @@file c:\apps\Bazaar\plugins\status_hook.py
from bzrlib import status

def post_status_hook(args):
    print('status_hook.py: post_status_hook')
    if 0:
        # args.old_tree, args.new_tree, args.to_file,
        # args.versioned, args.show_ids, args.short, args.verbose
        print('\n'.join(
            ['%s %s' % (z,getattr(args,z)) for z in sorted(dir(args))
                if not z.startswith('_')]))

if 0: # disable
    status.StatusHooks().install_named_hook(
        'post_status',post_status_hook,'EKR post_status hook')
.. @+node:ekr.20131030053655.17095: *3* @@file c:\apps\Bazaar\plugins\command_hook.py
@language python

from bzrlib import commands
from bzrlib import mutabletree

def pre_command_hook(*args,**keys):
    print('command_hook.py: pre_command_hook')
    
def post_commit_hook(args):
    print('command_hook.py: post_commit_hook')
    if 0:
        print('\n'.join(
            ['%s %s' % (z,getattr(args,z)) for z in sorted(dir(args))
                if not z.startswith('_')]))

if 0: # does not work.
    commands.CommandHooks().install_named_hook(
        'pre_command',pre_command_hook,'EKR pre_command hook')
        
if 0: # works.
    mutabletree.MutableTreeHooks().install_named_hook(
        'post_commit',post_commit_hook,'EKR post_commit hook')
.. @+node:ekr.20131005214621.16081: ** Notes
.. @+node:ekr.20090202064534.4: *3*  Your mission, should you choose to accept it
@language rest

.. @+node:ekr.20100223100750.5843: *4* Original post by Robin Dunn
Here are the emacs features that I use very often that any editor would
need to have in order for me to switch.  I've seen some editors with
some of these, but none with all unless it is an emacs clone.  I'll
leave out the obvious things like platform independence, good syntax
highlighting, calltips or auto-completion.  Also, these features are
just dealing with the code editor portion of the app, if it is more than
that (like a full IDE) then some of these things may or may not apply to
the non code editor parts:

* (done) Python should be just one of the languages that this editor supports,
not the primary target.  I spend as much time in C/C++ as I do Python,
and my editor of choice needs to help me with C/C++ coding just as much
as it does with Python.  So some sort of support for calltips and
auto-completion would be marvelous, and also being able to act as a
front-end for gdb since I currently use emacs for that most of the time.

* (done) Absolutely every feature or action must be able to be done with just
the keyboard.  Moving the hand back and forth to the mouse wastes time,
breaks concentration and contributes to RSI.  Multi-key sequences are
fine as long as they are grouped in a logical fashion.  For example in
emacs all of the version control features are accessible via the
Ctrl-x,v sequence plus one more letter.

* (done) Incremental search, both forward and reverse, and wrapping around
after you've reached the end or the beginning of the document.  I like
to have the same key to start the search and also do a search-next after
you've typed all the characters you are searching for, and also to have
backspace go back one search position and/or remove one character from
the search text.

* (done) Multiple top level windows, and able to show any buffer in any TLW,
including those that are already displayed in another TLW.  Of course
there should be key-bindings available for opening a new TLW, cycling
forward and backward through the buffer list, and a way to select a
buffer from a popup list of buffer/file names.

* (to be improved) The Kill-Ring.  For those of you that have never used an emacs-like
editor it works like this:  There is a collection of the N previous
blocks of text that have been cut or copied (in emacs 'cut' == 'kill'
more or less)  When I do a yank (paste) it uses the last thing put in
the kill-ring.  If I then immediately use another key-binding then it
replaces that pasted text with the next item in the kill ring, and so on
until I eventually wrap around get back to the first one in the ring, or
I do some other command or move the cursor somewhere else.

* (done) Registers.  A text snippet can be copied into a register, which is
like the kill ring except you refer to each one by name, where the names
are 'a' through 'z'.  You can also append to a register that already has
text in it, and you can paste the contents of a register into the
document at the current cursor location.

* (done) Able to have selections be either a stream of characters or a
rectangle.  A stream selection is like what you have in all text
editors, it starts from position a on line N and continues forward or
back to position b on line M and includes all the characters in between.

  A rectangle selection is all the characters between position a and b
on lines N to M.  In other words, it has width and height and it might
be something like positions 5 through 10 on lines 20 to 25.  Cutting or
deleting a rectangle removes the text in the rectangle and shifts any
text to the right of the rectangle over.  It does not remove any lines
although they may end up being empty.  Pasting a rectangle inserts the
new text with the upper-left of the rectangle at the current cursor
position, shifts existing text to the right if needed, and fills with
spaces on the left if a line affected by the paste is not long enough.
New lines are not added unless the file needs to be extended to
accommodate the rectangle paste.  Rectangles can also be put into registers.

* (to be improved) Good keystroke macro recording and the ability to save and load
keystroke macros, and the ability to assign a key-binding to a saved
recorded macro. Any time I need to make the same edits to a bunch of
lines or groups of lines I'll record doing it on the first one including
the keystrokes needed to reposition for the next line, and then stop
recording and then it's just one keystroke to replay the keystrokes for
every other line that needs it done.  I record, use and throw away up to
a dozen or so macros per day.

* (done, and better than asserted) If you must have a toolbar make it optional
and keep it simple. Toolbars require the mouse and the goal is to keep the hand
off the mouse as much as possible.

* (done) Similarly, avoid using popup dialogs whenever possible.  This includes
things like the file dialog.  I don't mind seeing the file dialog if I
select a menu item, because most likely my hand is already on the mouse,
but the rest of the time I just want to hit a key, type a path name
(with tab-completion to help find stuff, up/down keys to cycle through
past selections) and press enter.  So I would prefer this editor to have
something like emacs' minibuffer, or the QuickFind panel in Firefox.  In
other words, when there is something you would normally use a dialog for
just create a small panel that rolls up from the bottom of the frame,
put the keyboard focus there, perhaps do stuff in the main buffer as
they are typing if appropriate, and then when the user is done the panel
rolls out of sight again and keyboard focus is restored to their active
buffer.  This can be done for file open/saves, search & replace,
specifying build or grep commands (see next item) choosing to execute
some editor function by name that may not have some key-binding yet (see
item after next) etc.

* (done, with user @commands)

Flexible build/grep commands.  Emacs handles both of these in almost
the same way so I'll list them together here.  I hit a key and am
presented with either the default, or the most recently used compile or
grep command.  I can edit the command or use the up/down arrows to
select previous commands that I've used.  I then hit enter and emacs
runs the command putting the output in an editor buffer.  There is a key
I can hit to kill the compile if needed.  It then parses the output and
there is a key I can use to find the file listed in the compile or grep
output, load it, and position the cursor on the reported line.  (This
can even be done while the compile/grep is still running.)

* (done) For access to editor commands/functionality that may not be bound to a
keystroke it's real nice to have the ability to hit a key, type the
command name, press enter and then it's done.  This can also allow for
commands that might need to prompt for parameters, be interactive, etc.
  All editor commands should be named and can be bound to keys by name
or executed by name in this way.

* (done) def aproposFindCommands (self, event=None):

    '''Prints a discussion of of Leo's find commands.'''

    << define s >>

    self.c.putApropos(s)
 search.  Emacs has support for regular expression search modes
for all of the search types, incremental search, search/replace,
although I don't use it that much.

* (done, or not needed, depending on your point of view)
Multi-file search and replace.  Be able to select files interactively,
or by wildcard, or both.  Enter search string, or regex, and replace
text.  The editor loads each file and does the search, allowing you to
choose for each one whether to do the replacement, or replace all.

* If it is a full IDE it would be nice to have a way to start just the
code editor portion for quick edits.

Things that would be nice to have, but that I could live without:

(All of these things can be done easily with @command)

* Interactive diffs, merges and applying of patches.

* Able to be a front-end for gdb.

* Able to be a front-end for CVS, SVN, etc.

* (done) Be able to run shell commands, or the shell itself in an editor buffer.

* (easy) have a built-in psychotherapist or be able to play towers of hanoi.  ;-) 
.. @+node:ekr.20100223100750.5842: *4* Post to pyxides, 2010/02/23
http://groups.google.com/group/pyxides

Robin Dunn's post, reproduced at:
http://groups.google.com/group/leo-editor/browse_thread/thread/4f76a0f57759aba
continues to be one of the benchmarks for Leo.

Leo 4.7 went out the door today.  It contains many important
improvements, but few directly related to Robin's important post.
That doesn't mean Robin's post is irrelevant, but it does mean that
other considerations were more relevant :-)  In particular, Leo passes
all unit tests with Python 2.6 and Python 3.1.

Leo 4.8 will concentrate on better support for vim-like bindings.  As
a happy side effect, this will make Leo compliant with almost all
unfinished aspects of Robin's mission.

There are two major items from Robin's list that are incomplete in
Leo:

* The Kill-Ring.  Leo does have a kill ring.  The vim work will fix
discrepancies between how Leo, emacs and vim handle the kill ring.

* Good keystroke macro recording and the ability to save and load
keystroke macros.  This happen as part of support for vim's "dot"
command.  To some extent, Leo's execute-script command compensates for
wimpy macro support, but I'd like to do better.

The following could be done easily using Leo's @command or @button
features.  There doesn't seem to be much demand for them in Leo, but
I'll list them here for completeness.

- Flexible build/grep commands.
- Interactive diffs, merges and applying of patches.
- Able to be a front-end for gdb. (Leo has a plugin to do this).
- Able to be a front-end for CVS, SVN, etc.
- Have a built-in psychotherapist or be able to play towers of
hanoi.  ;-)

As always, I invite you all to try Leo, and to ask for features that
would be important to you.

======

P.S. Leo does have auto-completion.  It will be improved in Leo 4.9.

.. @+node:ekr.20110616084347.14800: *4* Post to pyxides, 2011/07/10
http://groups.google.com/group/pyxides

On 2010/02/23 I commented about Leo 4.7 as it relates to Robin Dunn's post,
http://groups.google.com/group/leo-editor/browse_thread/thread/4f76a0f57759aba

A few weeks ago Leo 4.9 went out the door. Imo, this version of Leo has
accomplished the mission. Leo has all the important features that Leo's users
have requested. Yes, wishlist items remain. See:
https://bugs.launchpad.net/leo-editor/+bugs

None of these wish-list items interferes in any way with Leo's day-to-day
operation. Furthermore, many of Leo's essential features moot the need for more
traditional features.

For example, Leo 4.9 adds full support for macros. Recording, saving, editing
and retrieving macros is easier in Leo than in other editors because Leo stores
macros in @macro nodes, not external files. But few, if any, of Leo's users are
likely to use macros because Leo's @button nodes make all of Python's scripting
abilities easily available on a node-by-node or outline-wide basis.

It may be that Leo could benefit from some Emacs-like or vim-like features, but
that doesn't seem so likely.  Leo has many users who also use Emacs and vim, and
they seem happy enough :-)

Finally, Leo offers features that have no counterpart at all in editors like
Emacs and vim. For example, the rst3 command converts an outline to restructured
text. See: http://webpages.charter.net/edreamleo/rstplugin3.html Yes, one could
imagine an org-mode command that does this, but the fact is that Leo's outline
orientation has given it abilities possessed by no other editor or IDE.

I invite you to try Leo. If, after using Leo for
real work, you find you would like some new feature, then by all means ask.

Edward
.. @+node:ekr.20061116060847: *3* @url http://www.jhorman.org/wikidPad/
.. @+node:ekr.20131011050613.16839: *3* About autocompletion
.. @+node:ekr.20131011050613.16840: *4* UI notes
Both the legacy and new completer now work *exactly* the same way, because
they both use the AutoCompleterClass to compute the list of completions.

The strict "stateless" requirement means that the "intermediate"
completions must be entered into the body pane while completion is active.
It works well as a visual cue when using the tabbed completer: indeed, the
tabbed completer would be difficult to use without this cue.

The situation is slightly different with the qcompleter. Adding code before
the user accepts the completion might be considered an "advanced" feature.
However, it does have two important advantages, especially when "chaining"
across periods: it indicates the status of the chaining and it limits what
must appear in the qcompleter window.
.. @+node:ekr.20131011050613.16841: *4* Appearance
There is little change to the legacy completer, except that no text is
highlighted in the body pane during completion. This is calmer than before.
Furthermore, there is no longer any need for highlighting, because when the
user types a backspace the legacy completer now simply deletes a single
character instead of the highlighted text.

One minor change: the legacy completer now *does* insert characters that do
not match the start of any possible completion. This is an experimental
feature, but it might play well with using codewise completions as a
fallback to Leo-related completions.

.. @+node:ekr.20131011050613.16842: *4* Performance
Performance of Leo-related completions is *much* better than before. The
old code used Python's inspect module and was horribly complex. The new
code uses eval and is perfectly straightforward.

The present codewise-related code caches completions for all
previously-seen prefixes. This dramatically speeds up backspacing. Global
caching is possible because completions depend *only* on the present
prefix, *not* on the presently selected node. If ContextSniffer were used,
completions would depend on the selected node and caching would likely be
impractical. Despite these improvements, the performance of
codewise-oriented completions is noticeably slower than Leo-related
completions.

The ac.get_cached_options cuts back the prefix until it finds a cached
prefix. ac.compute_completion_list then uses this
(perhaps-way-too-long-list) as a starting point, and computes the final
completion list by calling g.itemsMatchingPrefixInList.

This may not be absolutely the fastest way, but it is much simpler and more
robust than attempting to do "prefix AI" based on comparing old and new
prefixes. Furthermore, this scheme is completely independent of the how
completions are actually computed. The autocompleter now caches options
lists, regardless of whether using eval or codewise.

In most cases the scheme is extremely fast: calls to get_completions
replace calls to g.itemsMatchingPrefixInList. However, for short prefixes,
the list that g.g.itemsMatchingPrefixInList scans can have thousands of
items. Scanning large lists can't be helped in any case for short prefixes.

Happily, the new scheme is still *completely* stateless: the completionDict
does *not* define state (it is valid everywhere) and no state variables had
to be added. In short, the new caching scheme is much better than before,
and it probably is close to optimal in most situations.
.. @+node:ekr.20131011050613.16843: *3* About Key handling
@language rest

The following sections deal with different aspects of how Leo handle's
keystrokes that the user types. This is the most complex code in Leo.
.. @+node:ekr.20131011050613.16849: *4* Key bindings
There are two kinds of bindings, gui bindings and pane bindings.

**Gui bindings** are the actual binding as seen by  whatever gui is in effect.
Leo binds every key that has a binding to k.masterKeyHander.

At present Leo makes gui bindings in several places, all equivalent.
Bindings are made to callbacks, all of which have this form::

     def callback(event=None,k=k,stroke=stroke):
        return k.masterKeyHandler(event,stroke)

As a result, changing gui bindings actually has no effect whatever.
It would be clearer to have a single place to make these bindings...

In any case, the purpose of these callbacks is to capture the value of 'stroke' so
that it can be passed to k.masterKeyHandler.
This relieves k.masterKeyHandler of the impossible task of computing the stroke from the event.

**Important**:  No function argument is ever passed to k.masterKeyHandler from these callbacks,
because k.masterKeyHandler binds keys to command handlers as described next.

**Pane bindings** are bindings represented by various Python dictionaries in the
keyHandlerClass (see below). k.masterKeyHandler and its helpers use these
dictionaries to call the proper command or mode handler. This logic is hairy,
but it is completely separate from the gui binding logic.

Here are the dictionaries that k.masterKeyHandler uses:

- c.commandsDict:
  Keys are minibuffer command names; values are functions f.

- k.inverseCommandsDict:
  Keys are f.__name__l values are emacs command names.

- k.bindingsDict:
  Keys are shortcuts; values are *lists* of g.bunch(func,name,warningGiven).

- k.masterBindingsDict:
  Keys are pane names: 'all','text',etc. or mode names.
  Values are dicts:  keys are strokes; values are g.Bunch(commandName,func,pane,stroke).

- k.modeWidgetsDict:
  Keys are mode names; values are lists of widgets to which bindings have been made.

- k.settingsNameDict:
  Keys are lowercase settings; values are 'real' Tk key specifiers.
  Important: this table has no inverse.

- inverseBindingDict:
  This is *not* an ivar; it is computed by k.computeInverseBindingDict().
  Keys are emacs command names; values are *lists* of shortcuts.
.. @+node:ekr.20131011050613.16850: *4* Handling key events
.. @+node:ekr.20131011050613.16851: *5* All events are key events
All event objects passed around Leo are *key* event objects. Taking a look
at the eventFilter method, we see clearly see that *only* key events ever
get passed to Leo's core. All other events are handled by Qt-specific event
handlers.

As can be seen, these non-key events *can* be passed to Leo, but only as
the event arg in g.doHook (!) At present, no plugin ever calls
k.masterKeyHandler. The only call to k.masterKeyHandler in qtGui.py is the
expected call in eventFilter.

There are other calls to k.masterKeyHandler in Leo's core, but we can prove
(by induction, if you will), that all events passed to k.masterKeyHandler
are proper leoKeyEvent objects.
.. @+node:ekr.20131011050613.16852: *5* c.check_event
The essential invariant is that the events passed to Leo's core methods
really are leoKeyEvent objects created by qtGui.py. Rather than asserting
this invariant, the code will contains calls to c.check_event in essential
places. c.check_event is a "relaxed" place to do as much error checking is
needed. In particular, running the unit tests calls c.check_event many
times.

c.check_event is a happy "accident". It turns out to be the essential
consistency check that continually verifies that the Qt event methods are
delivering the expected keys to k.masterKeyHandler.
.. @+node:ekr.20131011050613.16853: *4* About the KeyStroke class
The KeyStroke class distinguish between "raw" user settings
and the "canonicalized" form used throughout Leo. Indeed,
the ability to explicitly distinguish between the two, using
type checking, substantially clarifies and simplifies the
code.

The KeyStroke class makes possible vital type-related
assertions. Knowing *for sure* exactly what crucial data is
and what it means is a huge step forward.

Objects of the KeyStroke class can be used *exactly* as a
strings may be used:

A. KeyStroke objects may be used as dictionary keys, because
they have __hash__ methods and all the so-called rich
comparison methods: __eq__, __ne__, __ge__, __gt__, __le__
and __lt__. Note that KeyStroke objects may be compared with
other KeyStroke objects, strings and None.

B. At present, KeyStroke objects supports the find, lower
and startswith methods. This simplifies the code
substantially: we can apply these methods to either strings
or KeyStroke objects, so there is no need to create
different versions of the code depending on the value of
g.new_strokes.

However, having the KeyStroke class support string methods
is bad design. Indeed, it is a symptom that the client code
that uses KeyStroke objects knows too much about the
internals of KeyStroke objects. Instead, the KeyStroke class
should have higher-level methods that use s.find, s.lower
and s.startswith internally.

You could say that the fact that code in leoKeys.py calls
s.find, s.lower and s.startswith is a symptom of non OO
programming. The internal details of settings and strokes
"pollutes" the code. This must be fixed. This will likely
create opportunities for further simplifications.

> Why not just have .s attribute in KeyStroke, that contains
the string version?

It is truly impossible to understand the key code without
knowing whether an object is a string representing a user
setting or the canonicalized version used in Leo's core,
that is, a KeyStroke object. Using ks.s instead of ks
destroys precisely the information needed to understand the
code.

Again, this is not a theoretical concern. The key code now
contains assertions of the form::

    assert g.isStroke(stroke)

or::

    assert g.isStrokeOrNone(stroke)

Getting these assertions to pass in *all* situations
required several important revisions of the code. The code
that makes the assertions pass is "innocuous", that is,
almost invisible in the mass of code, but obviously, these
small pieces of code are vital.

This is in no way a violation of OO principles. The code is
not dispatching on the type of objects, it is merely
enforcing vital consistency checks. This code is complex:
confusion about the types of objects is intolerable.
Happily, the resulting clarity allows the code to be
substantially simpler than it would otherwise be, which in
turn clarifies the code further, and so on...
.. @+node:ekr.20131011050613.16854: *4* Simplifying the Qt input code
The Qt key input code can be greatly simplified by calling a
new k.makeKeyStrokeFromData factory method. At present, the
Qt key input code knows *all* the details of the format of
*canonicalized* settings. This is absolutely wretched
design.

Instead, the Qt input key code should simply pass the key
modifiers and other key information to
k.makeKeyStrokeFromData, in a some kind of "easy" format.
For example, the Qt input key code would represent the
internal Qt modifiers as lists of strings like "alt",
"ctrl", "meta", "shift". k.makeKeyStrokeFromData would then
create a *user* setting from the components, and then call
k.strokeFromSetting to complete the transformation.
.. @+node:ekr.20131011050613.16855: *4* Typed dicts
Leo's key dictionaries will always be complex, but basing
them on the TypedDict class was a major improvement.

The g.TypedDict and g.TypedDictOfLists classes are useful
for more than type checking: they have unique names and a
dump method that dumps the dict in an easy-to-read format
that includes the name, and valid types for keys and values.

Plain dicts do have their uses, but for "long-lived" dicts,
and dicts passed around between methods, plain dicts are as
ill-advised as g.Bunches.

.. @+node:ekr.20091218120633.6299: *3* Bzr
.. @+node:ekr.20080917153158.10: *4* Bzr notes
How to create launchpad key pairs
=================================

http://help.launchpad.net/YourAccount/CreatingAnSSHKeyPair

How to create/use branches
=========================

pushes a branch after it has been created on launchpad::

    bzr push --use-existing-dir lp:leo-editor/whatever (private)

    bzr push --use-existing-dir bzr+ssh://edreamleo@bazaar.launchpad.net/~edreamleo/leo-editor/whatever (private)

remembers the push::

    bzr push --remember bzr+ssh://edreamleo@bazaar.launchpad.net/~edreamleo/leo-editor/whatever

creates branch on local machine: do this from leo.repo directory::

    bzr branch old-branch-name new-branch-name

    bzr branch lp:leo-editor new-branch-name 

    bzr branch bzr+ssh://edreamleo@bazaar.launchpad.net/~edreamleo/leo-editor/whatever new-branch-name

To resolve conflicts
====================

kdiff3 file1 file2 file3 -m


Docs
====
- http://doc.bazaar-vcs.org/latest/en/user-guide/index.html
    - http://bazaar-vcs.org/BzrWhy (referenced in sec 1.1.3 of the guide)
        - http://ianclatworthy.files.wordpress.com/2007/10/dvcs-why-and-how3.pdf
        - PQM: https://launchpad.net/pqm (google)
        - BB Bundle buggy: http://bundlebuggy.aaronbentley.com/help (google)
        - Spike solution: http://www.extremeprogramming.org/rules/spike.html (google)
- My log was at: http://bzr.arbash-meinel.com/irc_log/bzr/2008/02/bzr-2008-02-25.html


Configuration files
===================

.bzrignore in each repository contains the patterns to ignore.

EKR:  do ed-bzr

Windows: c:\Users\edreamleo\AppData\Roaming\bazaar\2.0\bazaar.conf

Linux:  ~/.bazaar/bazaar.conf
.. @+node:ekr.20090713080429.6042: *4* Bzr workflow notes
http://groups.google.com/group/leo-editor/browse_thread/thread/bd3e06a8a34a1938

This is the first time we have done this ("stable" branch + trunk),
so it might be good to bring this up:

- When doing a bugfix/improvement, always do it in the oldest branch that will
  receive it.

- Only after that, merge it to trunk

This prevents "manual" merges, and accidental incorporation of unwanted fixes.
It also gives us clean merge history.

I think this is the process python-the-project will use with mercurial. If they
find a bug in python 2.6.whatever, they fix it in that branch first, then merge
from that branch to trunk (so python 2.7 will receive it).

===================

http://groups.google.com/group/leo-editor/browse_thread/thread/3f24628c7f735c42

> I'll probably open a branch (based on the 4-6-final branch) to
  attempt a fix for an rst bug.

You don't need to create the branch on launchpad to do little fixes. The local
branch you create with "bzr branch" is a full-blown branch.

Here's how I do all my commits to trunk:

I have ~/leotrunk. I always keep this up to date with "bzr pull", but never
develop here.  (But I merge from leo-editor, as shown below.)
EKR: I call this main-trunk.

I have ~/leo-editor, also created from trunk. I develop here normally.
Occasionally, I just "bzr push", but often it fails because "branches have
diverged". I resist the temptation to "bzr merge" here, because it screws up
history. Rather, I:

- cd ~/leotrunk
- bzr pull (this always succeeds)
- bzr merge ~/leo-editor
- (investigate diffs)
- bzr qcommit (select the files I really want to commit--usually .py files)
- bzr push

Then, to get my ~/leo-editor up to date again:

cd ~/leo-editor
bzr pull 
.. @+node:ekr.20081113095540.1: *4* Bzr/ubuntu notes
/etc/apt/sources.list.d is a directory
It contains, on my machine, files called edgy-universe.list.x
The prefix doesn't matter, but the contents of these files must contain the proper ubuntu distro name,
for example, gutsy, hardy, intrepid.
.. @+node:ekr.20101024062147.6004: *3* Documentation notes
.. @+node:ekr.20060306194040: *4* The curse of knowledge
The curse of knowledge
http://groups.google.com/group/leo-editor/browse_thread/thread/3e75787223ee9303

(Rich) I'd like to see something like:

[Buttons]
...[What are Buttons good for?]
...[How do I make my own buttons?]
......[Some commands you can use with buttons]
......[Where to find button commands]
.. @+node:ekr.20100828074347.5828: *4* Slide show resources
http://sourceforge.net/forum/message.php?msg_id=3615177
By: ktenney

High on my ToLearn list is vnc2swf
http://www.unixuser.org/~euske/vnc2swf/

http://sourceforge.net/forum/message.php?msg_id=3615278
By: James

A lot of people are now using Wink for demonstrations
(http://www.debugmode.com/wink/), it's is free and seems to work well.

Check out http://murl.se/11332
At the bottom they talk about tools and techniques.
http://showmedo.com seems like it would be a good
place to host vids also.

I've listened/watched a fair number of things like this;
my recomendation is to get a good microphone and
pre-amp to record your voice, and prepare the audio
track carefully. It is so aggravating when
it's hard to discern the words being spoken.

http://sourceforge.net/forum/message.php?msg_id=3758271

From: Rich

Tutorials would be great. I use Liberty BASIC, (http://libertybasic.conforums.com)
and it has a very good tutorial -- leads the beginner by the hand through much
of the language. Also the help file has working code snippets
to cut-n-paste-n-play-with. 
.. @+node:ekr.20100904134301.8336: *4* Generate pdf on Linux
El 01/05/09 15:12, Ville M. Vainio escribió:

- make latex
- cd _build/latex
- make all-pdf
.. @+node:ekr.20130807203905.16683: *3* ENB: fixing the key binding bug
From: "Edward K. Ream" <edreamleo@gmail.com>

As the title indicates, this thread will consist of what could be
called an online engineering notebook.  Please feel free to ignore.

Key bindings are one of the most difficult and complex parts of Leo.
This can't be helped: Leo's goals for key bindings are ambitious.

The present bug, https://bugs.launchpad.net/leo-editor/+bug/879331, is
due to a significant design oversight.  Redefining a binding for a
command x to key y affects not just command x but all other commands
presently bound to y!

Alas, the present binding tables are already complex.  I am almost at
the limit of what I can hold in working memory as it is.  Adding
significant additional complexity risks creating virtually impossible-
to-understand code.

There are two conflicting desires in play here:

1. To make the minimum changes needed.  While reasonable in itself,
this promises to increase overall complexity.

2. To decrease overall complexity.  While reasonable in itself, this
promises significant overall changes to the code.

Combining these two desires yields a strategy of finding a minimal
change that reduces overall complexity :-)  It's a big ask.
.. @+node:ekr.20130502104323.10581: *3* github notes
Used for Leo's blog.

bzr ci => git commit -a
bzr add => git add
bzr push => git push
bzr revert => git reset --hard
.. @+node:ekr.20031218072017.365: *3* How to...
.. @+node:ekr.20060208112908: *4* BZR stuff...
.. @+node:ekr.20060331094112: *5* How to generate keys using putty
To generate a SSH key using PuTTY:

Execute c:\"Program Files"\tortoiseCVS\PUTTYGEN.EXE

Select "SSH2 DSA", within the "Parameters" section.

Click on the "Generate" button. Follow the instruction to move the mouse over
the blank area of the program in order to create random data used by PUTTYGEN to
generate secure keys. Key generation will occur once PUTTYGEN has collected
sufficient random data.

Enter edream@cvs.sourceforge.net for the key comment (depends on what host the
key is for)

(Omit) Enter the desired passphrase in the "Key passphrase" and "Confirm passphrase"
fields. If the key will be used for automation of operations (i.e. as part of a
script), you may choose to omit this step from the key generation process.

Click on the "Save private key" button. Use the resulting dialog to save your
private key data for future use. You may use a filename such as
"SourceForge-Shell.ppk" or "SourceForge-CF.ppk". The .ppk extension is used for
PuTTY Private Key files.

Go to the SSH key posting page on the SourceForge.net site: http://sourceforge.net/account/

Copy your public key data from the "Public key for pasting into OpenSSH
authorized_keys2 file" section of the PuTTY Key Generator, and paste the key
data to the provided form on the SourceForge.net site. Click on the "Update"
button to complete the posting process.

Exit the PuTTY Key Generator (PUTTYGEN).

Key data sync to hosts from the SourceForge.net site occurs on regular
intervals. Your key data will be synchronized to the designated servers (either
shell and CVS, or the Compile Farm) after a short delay.
.. @+node:ekr.20031218072017.366: *5* How to add and remove files from CVS repository
use the command line option in the admin menu to do the following:

add leoConfig.py and leoConfig.txt
    cvs add leoConfig.txt
    cvs add leoConfig.py
    (then do commit)

remove readme*.doc
    remove files from working area (done)
    cvs remove readme1.doc
    cvs remove readme2.doc
    ...
    (then do commit)
.. @+node:ekr.20031218072017.391: *5* How to use CVS branches
I have a fair bit of expertise on CVS branches. It's late at night, so I
don't have time for a long soapbox spiel at the moment. I will try to post
something tomorrow.

The brief picture is: 

* Check out code from CVS at the point you want to create the branch.

* Make sure none of the files in your sandbox is modified.

* Create the branch (cvs tag -b branchname). The branch name must start
  with a letter (upper or lower case) and thereafter can have alphanumeric
  characters, hyphens, and underscores (no periods or spaces).

* The branch is created on the repository, but your sandbox is still
  checked out on the main branch. To check out on the new branch, do "cvs
  up -r branchname".

When you want to merge changes back into the main branch, you can use "cvs
up -r MAIN" to retrieve the main branch, then "cvs up -j branchname" to
merge changes, then "cvs commit" to commit the merged version to the main
branch AFTER YOU HAVE VERIFIED IT.

I would recommend caution with merging because as you have noted, leo files
are not well set up for CVS. They don't merge well because of inconsistent
sentinel values.

You may want to look at manually merging changes back into the main branch
until leo implements invariant unique (UUID) sentinel indices.

This will not hurt your ability to use branches, only your ability to
automatically merge changes from one branch onto another.
.. @+node:ekr.20031218072017.367: *4* How to add support for a new language
- Add new entries in the following Python dictionariues in leoApp.py:
  self.language_delims_dict, self.language_extension_dict and self.extension_dict

- Add an entry to the languages list in <<configure language-specific settings>>

- Add a list of the keywords of the language to << define colorizer keywords >>

  N.B.: the name of this list must be x_keywords, where x is the entry in language in step a.

- Add any language-specifig code to leoColor.colorizeAnyLanguage.
  For most languages nothing need be done.

- If the language is case insensitive, add it to the list of
case_insensitiveLanguages found in  << define global colorizer data >>

- Create the files theLanguage.xml and theLanguage.py file was added to the leo\modes directory.
  See Chapter 15 of Leo's users guide for full details.

TESTS

- Test the syntax coloring for the new language by using the @language directive.

@color
.. @+node:ekr.20080814134319.1: *4* How to create and push to a private bzr branch
C:\leo.repo\trunk>bzr push --use-existing-dir bzr+ssh://edreamleo@bazaar.launchpad.net/~edreamleo/leo-editor/leo-4-5-1

C:\leo.repo\trunk>bzr push --use-existing-dir bzr+ssh://edreamleo@bazaar.launchpad.net/~edreamleo/leo-editor/leo-4-5-1

.. @+node:ekr.20051203084725: *4* How to expand java .jar files
- Put whatever.jar in c:\prog
- cd: c:\prog
- jar xvf whatever.jar
.. @+node:ekr.20031218072017.384: *4* How to export syntax colored code preserving colors
Scite has the option to "Export as html" and "export as rtf", and it will be
full of colour and fonts - and you can define them in properties, so it will be
the same as during editing.
.. @+node:ekr.20031218072017.385: *4* How to Increase environment space
To increase the size of environment space, add the following to config.sys:

shell=C:\windows\command\command.com /p:4096

Notes:

1. The path C:\windows\command\command.com may vary.
Check you system for the location of command.com.

2. This works for versions of Windows prior to Me.
On Me you set the registry somehow.
No information on XP.
.. @+node:ekr.20051203084725.1: *4* How to install and run jythonShell
Install:

Put JythonShellEA.jar in c:\prog\JythonShell

(optional) Expand the jar so you can see the code:

jar xvf JythonShellEA.jar

Run:

Here is the contents of jythonShell.bat:

cd c:\prog\jythonShell
java -cp c:\jython-2.2a1\jython.jar;c:\prog\jythonShell\JythonShellEA2.1.jar org.leo.shell.JythonShell
.. @+node:ekr.20050316092232: *4* How to install jyLeo
- Unpack the .zip file, placing the result somewhere, say in c:\prog\jyleo-Jan-11-06

- Edit jleo.bat so it refers to jyleo-Jan-11-06.  For example:

rem open jyLeo
set ARGS= 
:loop 
if [%1] == [] goto end 
set ARGS=%ARGS% %1 
shift 
goto loop 
:end 

cd c:\prog\jyleo-Jan-11-06
java -jar c:\jython-2.2a1\jython.jar src\leo.py
.. @+node:ekr.20050716104357: *5* Old instructions
@language rest
- put the jyleo-nnn.jar file in c:\prog

- Execute the following command in a console window
    cd c:\prog
    jar xvf j-leo-nnn.jar

This creates a folder called j-leo-nnn

- Do the following, or execute jleo.bat

cd c:\prog\j-leo-nnn\src
java -jar c:\jython22a0\jython.jar leo.py

Note:  at present this gives KeyError: HOME
@language python

In leo.py, in computeHomeDir, I changed::

    home = os.getenv('HOME' )#,default=dotDir)

to::
    
    try:
        home = os.getenv('HOME' )#,default=dotDir)
    except Exception:
        home = ''

.. @+node:ekr.20050317153447: *5* jy-Leo install instructions by Paul Paterson
http://sourceforge.net/forum/message.php?msg_id=3053534
By: paulpaterson

Very interesting indeed - great work! 

I didn't have Java/Jython installed so for others in the same boat here's
what I had to do to get it work on my platform (Win2k). Some of this is in
the README but I had to do some extra but I'm not sure why.

1. Install 1.5 JDK  
http://java.sun.com/j2se/1.5.0/download.jsp 

2. Install Jython 
http://www.jython.org/jython22a1.zip 

3. Edit Jython.bat file - the part that calls Java.exe to ... 
"C:\Program Files\Java\jdk1.5.0_02\jre\bin\java" -cp "C:\Program Files\Java\jdk1.5.0_02\jre\lib";"c:\Apps\Python23\Jython";"C:\Apps\jLeo\j-leo-MAR15\Icons";"C:\Apps\jLeo\j-leo-MAR15\skins";"C:\Apps\jLeo\j-leo-MAR15\src";"C:\Apps\jLeo\j-leo-MAR15\skinimages" -Dpython.home="c:\Apps\Python23\Jython" -jar jython.jar %ARGS% 

Where  
- Java installed at C:\Program Files\Java\jdk1.5.0_02 
- Jython at c:\Apps\Python23\Jython 
- jLeo at C:\Apps\jLeo\j-leo-MAR15 

Change your paths as appropriate! There must be a better way to do this - Java confuses me! 

4. Edit leo.py in jleo/src directory to fix failure to find HOME env variable. 

line 241 becomes ... 

....try:home = os.getenv('HOME' )#,default=dotDir) 
....except KeyError:home="" 


Then, from the Jython install directory ... 

Jython " 
C:\Apps\jLeo\j-leo-MAR15\src\leo.py" 

Works a treat!  

Paul
.. @+node:ekr.20051129084430: *4* How to install jython
- Download jython_Release_2_2alpha1.jar and put it anywhere (say on the desktop)

- Double-click the file.  This brings up an installer.  Follow the direction.
  (I installed to c:\jython-2.2a1

- Using the Control Panel, System, Advanced tab, environment variables,
  add c:\jython-2.2a1\jython.jar to CLASSPATH (in user variables)
.. @+node:ekr.20051129084430.1: *5* @url http://www.jython.org/install.html
.. @+node:ekr.20101004092958.6050: *4* How to make codewise work
http://groups.google.com/group/leo-editor/browse_thread/thread/ac3f8789010c882e/a1558a10eb8537c0?lnk=gst&q=codewise#a1558a10eb8537c0

1. Make sure you have exuberant ctags (not just regular ctags)
installed.  It's an Ubuntu package, so easy if you're using Ubuntu.

2. Install Ville's python module "codewise".  This is a small module on
which the Leo plugin relies.

   bzr branch lp:codewise
   cd codewise
   sudo python setup.py install

3. You need a recent trunk version of leo to get the plugin which uses
the above module.

4. Enable the plugin by putting "codewisecompleter.py" on an
uncommented line in your @enabled-plugins @settings node.

5. On the command line:

if you have an existing ~/.ctags for some reason, and it's nothing you
need to keep:

  rm ~/.ctags

then

  codewise setup
  codewise init
  codewise parse .../path/to/leo/  # assuming you want completion on
                                   # leo code
  codewise parse .../some/other/project/

Then, after restarting leo if necessary, type

c.op<Alt-0> in the body editor to find all the c. methods starting
with 'op' etc.

Nice work Ville, thanks.

==================

Thanks for this, I hope others will take a stab at it as well, given
sane instructions (I burned my free cycles frantically coding this
thing and neglected the all-important HOWTO). This is important
because functional completion is the single most important thing still
missing from Leo. Or, well, was ;-).

Especially the presentation part (QCompleter) needs some care, so you
can operate it from your keyboard alone. It should probably be moved
to core (qtgui, perhaps leoQTextEditWIdget), so codewise completer can
just invoke w.complete(list_of_completions) that will bring up the
QCompleter popup.

> Then, after restarting leo if necessary, type

> c.op<Alt-0> in the body editor to find all the c. methods starting
> with 'op' etc.

Also, try the explicit declarations:

# w : SomeClass

w.<alt+0>

And self.<alt+0> 
.. @+node:ekr.20070623150151: *4* How to make Leo commands undoable
The chapter commands provide a good example.  In this file, see the node:

Code-->Core classes...-->@thin leoChapters.py-->class chapterController-->Undo

The general plan is this:

1. The command handler calls a **beforeCommand** method before changing the outline.

The beforeCommand method creates a g.Bunch that contains all the information needed to
restore the outline to its previous state. Typically, the beforeCommand method
will call c.undoer.createCommonBunch(p), where p is, as usual, c.p.

2. After changing the outline the command handler calls an **afterCommand** method.

This method should take as one argument the g.Bunch returned by the
beforeCommand method. In the discussion below, denote this bunch by b. The
afterCommand method adds any information required to redo the operation after
the operation has been undone.

The afterCommand method also sets b.undoHelper and b.redoHelper to two method
that actually perform the undo and redo operations. (Actually, the beforeCommand
method could also set these two entries).

When the afterCommand method has 'filled in' all the entries of b, the
afterCommand method must call u.pushBead(b). This pushes all the undo
operation on a stack managed by the Leo's undoer, i.e., c.commands.undoer.

3. The undoer calls the undoHelper and redoHelper methods to perform the actual undo and redo operations.

The undoer handles most of the housekeeping chores related to undo and redo.  All the undoHelper and redoHelper methods have to do is actually alter Leo's outline.

**Note**: the undoer creates an ivar (instance variable) of the *undoer* class for every entry in the bunch b passed as an argument to u.pushBead(b).  For example, suppose u = c.commands.under and that b has ivars 'a','b' and 'c'.  Then, on entry to the undoHelper and the redoHelper the u.a, u.b and u.c ivars will be defined.  This makes it unnecessary for the undoHelper or the redoHelper to 'unpack' b explicitly.

Writing correct undo and redo helpers is usually a bit tricky.  The code is often subtly different from the original code that implements a command.  That just can't be helped.




.. @+node:ekr.20091217112515.6070: *4* How to make the codewise completer work
http://groups.google.com/group/leo-editor/browse_thread/thread/ac3f8789010c882e

Ville's completer is working and very cool, here are instructions for
making it go.  They're like the instructions Ville gave, only usable ;-)

1. (done) Make sure you have exuberant ctags (not just regular ctags)
installed.  It's an Ubuntu package, so easy if you're using Ubuntu.

2. (done) Install Ville's python module "codewise".  This is a small module on
which the Leo plugin relies.

   bzr branch lp:codewise
   cd codewise
   sudo python setup.py install

3. (done) You need a recent trunk version of leo to get the plugin which uses
the above module.

4. (done) Enable the plugin by putting "codewisecompleter.py" on an
uncommented line in your @enabled-plugins @settings node.

5. On the command line:

if you have an existing ~/.ctags for some reason, and it's nothing you
need to keep:

  rm ~/.ctags

then

  codewise setup
  codewise init
  codewise parse .../path/to/leo/  # assuming you want completion on
                                   # leo code
  codewise parse .../some/other/project/

Then, after restarting leo if necessary, type

c.op<Alt-0> in the body editor to find all the c. methods starting
with 'op' etc.


===== Ville's response

Especially the presentation part (QCompleter) needs some care, so you
can operate it from your keyboard alone. It should probably be moved
to core (qtgui, perhaps leoQTextEditWIdget), so codewise completer can
just invoke w.complete(list_of_completions) that will bring up the
QCompleter popup.

> Then, after restarting leo if necessary, type

> c.op<Alt-0> in the body editor to find all the c. methods starting
> with 'op' etc.

Also, try the explicit declarations:

# w : SomeClass

w.<alt+0>

And self.<alt+0>
.. @+node:ekr.20091217112515.6069: *5* Others posts
1. codewisecompleter.py now completes by explicit type hints (as seen in
screenhots). p, c also work, as does 'self'.

self works by scanning for parent headlines looking for "class Foo"

Work remains for presentation part (it's mouse only now) but Edward
will probably do it :-).

2. > Would codewise work outside of leo, as stand-alone plugin for a text
> editor?

Yes, currently Leo uses it as an external program ("codewise m
MyClass" dumps the methods in MyClass to stdout).

Someone just has to write the vim integration plugin (or whatever they
call it). OTOH, vim already has "pysmell" and the likes that do the
same thing.

==============

The version of codewise completer that works with Tk is now on trunk.
.. @+node:ekr.20091217112515.6071: *5* plugin docs
- You need to create ctags file to ~/.leo/tags. Example::

    cd ~/.leo
    ctags -R /usr/lib/python2.5 ~/leo-editor ~/my-project

- Enter text you want to complete and press alt+0 to show completions
  (or bind/execute ctags-complete command yourself).

Attempting to complete 'foo->' is useless, but 'foo->ba' will work (provided you
don't have 2000 functions/methods starting with 'ba'. 'foo->' portion is ignored
in completion search.
.. @+node:ekr.20131017100502.16702: *4* How to profile Leo
To gather statistics, do the following in a console window, not idle::

    > python
    >>> import leo
    >>> import leo.core.runLeo as r
    >>> r.prof()  (this runs leo)
    load any .leo file from Leo
    quit Leo

This writes intermediate data to cwd.leoProfile.txt.
The statistics are written to stdout.
.. @+node:ekr.20031218072017.386: *4* How to remove cursed newlines: use binary mode
teknico ( Nicola Larosa ) 
 RE: Removing '\r' characters?   
2002-09-16 14:27  
> I am plowing through old bug reports, and I found the following, from whom 
> I don't know: 

That's from me, *again*. You are kindly advised to stop forgetting the attribution to all my bug reports. ;^) 

>> - Source files still have the dreaded \r in them. Why don't you switch 
>> to \n only, once and for all, and live happily ever after? ;^) 

> I sure whould like to do that, and I'm not sure how to do this. All 
> versions of the read code attempt to remove '\r' characters, and all 
> versions of the write code write '\n' only for newlines. 

Sorry for being a bit vague, I was talking about the Leo source files themselves. I don't know what you use to edit them, ;^))) but in version 3.6 they still have \r\n as end-of-line. 

If Leo itself does not solve the problem, may I suggest the 
Tools/scripts/crlf.py script in the Python source distibution? It's nice and simple, and skips binary files, too. That's what I use every time I install a new version of Leo. :^) 

.. @+node:ekr.20031218072017.387: *5* The solution
Under unix, python writes "\n" as "\n"; under windows, it writes it as "\r\n". The unix python interpreter ignores trailing "\r" in python source files. There are no such guarantees for other languages. Unix users should be able to get rid of the cosmetically detrimental "\r" either by running dos2unix on the offending files, or, if they're part of a .leo project, reading them into leo and writing them out again.  


By: edream ( Edward K. Ream ) 
 RE: Removing '\r' characters?   
2002-09-17 09:34  
Oh, I see. Thanks very much for this clarification. 

Just to make sure I understand you: the problem with '\r' characters is that: 

1. I am creating LeoPy.leo and LeoDocs.leo on Windows and 
2. People are then using these files on Linux. 

and the way to remove the '\r' characters: 

1. I could run dos2unix on all distributed files just before committing to CVS or making a final distribution or 
2. People could, say, do the following: 

Step 1: Read and Save the .leo files, thereby eliminating the '\r' in those files and 
Step 2: Use the Write @file nodes command on all derived files to clear the '\r' in those files. 

Do you agree so far? 

> Under unix, python writes "\n" as "\n"; under windows, it writes it as "\r\n". 

I am going to see if there is any way to get Python to write a "raw" '\n' to a file. I think there must be. This would solve the problem once and for all. 

Thanks again for this most helpful comment. 

Edward
.. @+node:ekr.20031218072017.388: *5* cursed newline answer
In 2.3 you can open files with the "U" flag and get "universal newline"
support: 

% python
Python 2.3a0 (#86, Sep 4 2002, 21:13:00) 
[GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("crlf.txt")
>>> line = f.readline()
>>> line
'This is an example of what I have come to call the "cursed newline"
problem,\r\n'
>>> f = open("crlf.txt", "rU")
>>> line = f.readline()
>>> line
'This is an example of what I have come to call the "cursed newline" problem,\n'

.. @+node:ekr.20031218072017.389: *5* cursed newline answer 2
> You can open the file in 'binary' mode (adding 'b' to the mode string) and
> the file will contain '\r\n' on both platforms (and any other platforms.)

Nope. Exactly wrong. In 2.2 and those before, when files are opened in
*text* mode (no "b") then reading them will provide Unix-style line endings
(newline only). When you open files in binary mode then you see the bytes
stored in the file.

On Unix systems there's no difference in the contents of a file whether in
binary or text mode. On Windows a file is shorter by the number of carriage
returns. On the Mac I have no idea what they do. Probably just carriage
returns, to be different :-)

2.3 will be a bit more flexible about such mattrers.
.. @+node:ekr.20061023153133: *4* How to run patch
patch -p1 < patchfile
.. @+node:ekr.20050510071834: *4* How to use a temp file with pdb
@killcolor

http://sourceforge.net/forum/message.php?msg_id=3137690
By: nobody

I dont know if anyone has solved this for regular Leo, but in the JyLeo JythonShell,
when the user executes a script with Pdb it:
1. dumps the script in a tmp file system's tmp directory.
2. Executes pdb based off of that tmp file.

that way you get all the goodness that pdb can offer.
.. @+node:ekr.20130812034101.12581: *3* Installation Notes
.. @+node:ekr.20130807090137.11461: *4* Linux
.. @+node:ekr.20130806072439.20730: *5* PyPi package: 4.11 test release: Matt
From: Matt Wilkie <maphew@gmail.com>

I've just uploaded Leo-4.11-devel-build-5769 to the Python Package Index:
https://pypi.python.org/pypi/leo

(todo: fix the readme, which is for 4.10, the 4.11 version remains to be
written)

It can be downloaded from there and installed manually or, better yet,
installed with `pip install leo`.

Pre-requisites are:

1. Python
2. PyQt
3. Distribute / Setuptools

Improvements over previous pypi package:

 - Sports Leo splash screen while installing on Windows

 - Installs "leo" and "leoc" wrappers to PYTHONHOME\\Scripts, so as long as
this directory is in PATH you don't need to create your own launcher (this
is the part that requires Distribute. I'm working an way to include this
automatically, http://stackoverflow.com/questions/16702658). It is common
for this to be set.

- all the other changes in trunk over the last couple of weeks (
http://bazaar.launchpad.net/~leo-editor-team/leo-editor/trunk3/changes)
.. @+node:ekr.20130806072439.20664: *5* finding debian package
From: Geoff Evans <gtevansai@nl.rogers.com>

The Leo installation instructions for Ubuntu still say merely "find and
install the debian package". Can someone tell me where to find it? Several
minutes searching on google has not got me anywhere.

===== From: Matt Wilkie <maphew@gmail.com>

Please try the instructions here and report if they are still relevant:
https://groups.google.com/d/msg/leo-editor/9yqhWD90Vtg/yCR8O_FBvIwJ ?

===== From: Geoff Evans <gtevansai@nl.rogers.com>

Excellent! Thanks very much Matt (and Ville for creating it). There was one
error message about a signature that could not be verified, and a syntax
error while compiling /usr/lib/pymodules/python2.7/leo/external/edb.py but
they haven't stopped leo from opening files from my previous computer. The
new one is running precise, in case it matters.

Minor supplementary question: What search strategy would have led me there
on my own? I agree that "Leo now apt-gettable" is perfectly understandable
once I see it (and indeed I have a vague memory of having seen it before),
but I don't know how I would have arrived at it without your help.

.. @+node:ekr.20130806072439.20683: *5* linux users: please test pip install
From: Matt Wilkie <maphew@gmail.com>

Can someone on linux please test whether

   pip install -i https://testpypi.python.org/pypi leo-editor

successfully installs a working Leo on their system?

You can use `virtualenv` to create an isolated test environment
http://www.virtualenv.org/en/latest/ if needed.

===== From: Terry Brown <terry_n_brown@yahoo.com>

seemed to work for my in a fresh python 3.3 virtualenv

i.e.
import leo
leo.run()
ImportError: No module named 'PyQt4'

so in the shell

cp -rv /usr/lib/python3/dist-packages/PyQt4 p3/lib/python3.3/site-packages/
cp -rv /usr/lib/python3/dist-packages/sip* p3/lib/python3.3/site-packages/

and then the above worked.

remember also:

https://groups.google.com/forum/?fromgroups=#!searchin/leo-editor/Runnable$20Leo$20in$20one$20.zip$20file./leo-editor/jnpkrQeo9Hk/Ds3QsUe1W-QJ

including HansBKK's good point.

===== Matt

The take away is that there is a pure python method to install pip, which
in turn can easily install Leo and docutils, meaning the two don't have to
be bundled.

There is still more work to do get PyQt + SIP install automated in a way
that integrates nicely with Start Menu etc., but we have proof of concept
that it is possible.

At the very least we have a recipe that can easily build a complete ready
to run all-in-one zip bundle for Windows. I'll work on this next, and then
dig more into the pyqt+sip aspect.

.. @+node:ekr.20130807090137.11462: *4* Windows
.. @+node:ekr.20130806072439.20677: *5* Installing pip on windows
On Monday, 15 April 2013 13:06:39 UTC-7, Matt Wilkie wrote:

Installing pip on Windows is easy enough, but involves silly monkey work
(install this pre-requiste, copy this text and paste it there, twiddling
X,Y,Z for your machine. etc.) It's easy to make small stupid mistakes that
make one have to repeat parts of the operation. So I automated installing
pip all in one go. Nothing but an available python interpreter is required
(and an internet connection).

http://www.maphew.com/2013/install-pip-script/
.. @+node:ekr.20130806072439.20707: *5* Portable Leo from scratch on Windows
@language rest

Edward, Ville, please pay attention to this message even if just nodding at
the others passing by.

>pip install -i https://testpypi.python.org/pypi leo-editor

I built and uploaded to this package to the pypi testing server. Other than
the fact it seems to work in so far as it installs without spewing errors
I've no idea if it was done properly. Or even if it was appropriate for me
to build a leo package. This is the first pypi package I've built.

The package page: https://testpypi.python.org/pypi/leo-editor/4.10-final

I'll upload the changed `setup.py` and the build recipe I used for your
inspection after I re-learn how to create a branch and issue a pull/merge
request in bazaar.


===== Matt

https://code.launchpad.net/~maphew/leo-editor/pypi-packaging/+merge/159561

Description of the Change

Updated `setup.py` for Leo-4.10-final, added "Classifiers" as made sense to
me. The resultant source build package was uploaded to the testing Python
Package Index server, from which `pip install leo-editor` is successful.

A windows binary distribution build does not appear to be necessary.

Known limitations: __py-cache__ files are included, but shouldn't be.

===== Matt

The created .zip file:

Here is the result of that recipe, with some very small hand edits,
packaged up in an all-in-one ready to go portable Leo zipfile (52mb).
Simply unpack somewhere and run Leo.bat.

https://googledrive.com/host/0BxjYoJ7VMm5VbE11NHM3Q3RIRVk/
.. @+node:ekr.20130807090137.11463: *6* script
@language python
@ Matt Wilkie <maphew@gmail.com>

Here is a recipe for installing Leo from scratch on Windows (Win7 tested).
The only prerequisites are command line `wget` in PATH and an internet
connection.

About 50mb of files are downloaded and 200mb consumed when done.

Run this script from a console.

After this the directory "X:\\testing\\root" can be renamed and/or moved
anywhere.

To run leo in future sessions, simply call "x:\\path\\to\\root\\osgeo4w.bat
python apps\\Python27\\Scripts\\leo", either as a batch file or windows
shortcut.

**Important**: this is just a proof of concept. It is not ready for prime
time. Feedback welcome.
@c

mkdir X:\\testing
pushd X:\\testing

wget -O apt.exe --no-clobber
http://download.osgeo.org/osgeo4w/release/apt/apt-r1193M.exe
SET OSGEO4W_ROOT=%~dp0\\root
apt setup
apt update
apt install pyqt4 sip

call root\\osgeo4w.bat

wget --no-check-certificate
http://gist.github.com/maphew/5393935/raw/install-pip.py
python install-pip.py GO
python install-pip.py GO

pip install -i https://testpypi.python.org/pypi leo-editor

python apps\\Python27\\Scripts\\leo
.. @+node:ekr.20130806072439.20712: *6* Re: Portable Leo from scratch on Windows
From: Matt Wilkie <maphew@gmail.com>

>call root\\osgeo4w.bat

Adds ...\\bin (for python) and ...\\apps\\python27\\scripts (for pip) to PATH,
and sets PYTHONHOME.

>wget --no-check-certificate
http://gist.github.com/maphew/5393935/raw/install-pip.py
>python install-pip.py GO
>python install-pip.py GO

Download and install `distribute` and `pip`, the python tools which enable
automated downloading and installing of programs and modules from the
Python Package Index. `install-pip.py` is of my own devising. All it does
is reduce the dependency on curl or wget by one step, using native urlib
(py3) or urllib2 (py2) instead.

   http://pythonhosted.org/distribute/
   http://www.pip-installer.org/en/latest/
   https://pypi.python.org/pypi

>pip install -i https://testpypi.python.org/pypi leo-editor

Install Leo (more background for this one in next message).

> python apps\\Python27\\Scripts\\leo

All done, let's run Leo! :)
.. @+node:ekr.20130806072439.20722: *5* apt on windows
From: Matt Wilkie <maphew@gmail.com>

Use the `apt` command line package management tool from Osgeo4w
http://trac.osgeo.org/osgeo4w/ to install python and all the other
requirements that can't be installed with `pip` or `easy_install`, meaning
PyQt and SIP.

The resultant dir structure follows a cygwin model, which in turn follows
linux:

    \apps\Python27 - python libraries, site-packages, etc. This is PYTHONHOME.
    \bin - exe's and dll's, including python.exe, qt*.dll, etc.

There are also `etc, include, lib, var` which can all be discarded, unless
you intend to use apt again or other programs from the osgeo4w ecosystem).
`var` in particular you might want to clean out, it is the local cache for
apt downloaded packages.


===== Whoa, apt on windows, cool.

Thanks! It's been the gravity well powering my plunge into python. It's a
testament to python's power that it enables someone like me, with no
programming background, to build something that does real work.

The original genius is Jan Nieuwenhuizen, who wrote `cyg-apt` in python but
made lots of calls to bash and tools like tar and curl. All I've done is
take each function and convert them as best I could to pure python, to the
point where it now has zero dependencies on cygwin (though it does still
use the cygwin package and mirror structure).

More history and details at http://trac.osgeo.org/osgeo4w/wiki/pkg-apt
.. @+node:ekr.20130806072439.20643: *5* Tip about install leo with EPD
From: HaveF <iamaplayer@gmail.com>

I used python xy before. After I finish install python xy, the leo is ready
to use.

Today I try EPD(https://www.enthought.com/downloads/), and install pyqt4 at
its package manager.

After that, I try to start Leo, it failed, but I success at last.

the batch file should be:

C:\Users\HaveF\AppData\Local\Enthought\Canopy\User\Scripts\python.exe
D:\lib\leo\leo-editor-snapshot\launchLeo.py %*

not:

C:\Users\HaveF\AppData\Local\Enthought\Canopy\App\python.exe
D:\lib\leo\leo-editor-snapshot\launchLeo.py %*

or:

C:\Users\HaveF\AppData\Local\Enthought\Canopy\System\Scripts\python.exe
D:\lib\leo\leo-editor-snapshot\launchLeo.py %*

===== From: HaveF <iamaplayer@gmail.com>

the tip is for install Canopy just for yourself (per-user install)
.. @+node:ekr.20130814140750.17191: *3* IPython notes
.. @+node:ekr.20130814140750.17192: *4* Ipython now has cell magic
From: Alia K <alia_khouri@yahoo.com>

Fernando Perez of IPython fame just announced recently that IPython
trunk has the cell magic functionality that was discussed earlier
[http://groups.google.com/group/leo-editor/browse_thread/thread/
7d910a68072dda1/b14e84fc3cfddbf6?lnk=gst&q=ipython#b14e84fc3cfddbf6].
As this could work very nicely with leo as an ipython editor, I will
include his text verbatim here:

===== Fernando

I'm excited to report that we now have cell magics in IPython... PR
1732 [1] has just been merged [2], which implements the design
discussed in IPEP 1 [3]. This is probably one of the largest PRs we've
had so far, with over 100 commits, over 100 comments and a diff that's
almost 11000 lines long (a lot of it moving code around, obviously
it's not all new code).  But it brings two very important thigns:

1) a refactor of the magic system to finally remove the old mixin
class we'd had since the very first days of IPython in 2001.  This is
a cleanup I've been wanting to do for over 10 years!  The new setup
makes the magic system have  a very clean api, that is easy to use
both for the implementation of core features and for users to create
their own magics.

2) the new concept of cell magics: these are magics that get not only
the line they're on, but the entire cell body as well.  And while
these are most naturally used in the notebook, as you would expect
we've built them at the core of IPython, so you can use them with all
the clients (terminal, qt console, notebook).  For example, this is a
Cython magic that Brian just prototyped out (we'll have a production
version of it soon included).  Note that this was copied *from a
regular text terminal*, not from the notebook:

In [3]: from IPython.core.magic import register_line_cell_magic

In [4]: @register_line_cell_magic
   ...: def cython(line, cell):
   ...:     """Compile and import a cell as a .pyx file."""
   ...:     import sys
   ...:     from importlib import import_module
   ...:     module = line.strip()
   ...:     fname = module + '.pyx'
   ...:     with open(fname,'w') as f:
   ...:         f.write(cell)
   ...:     if 'pyximport' not in sys.modules:
   ...:         import pyximport
   ...:         pyximport.install(reload_support=True)
   ...:     globals()[module] = import_module(module)
   ...:

In [5]: %%cython bam
   ...: def f(x):
   ...:     return 2.0*x
   ...:

In [6]: bam.f(10)
Out[6]: 20.0

In a similar spirit, Jonathan Taylor recently created one to call R
transparently in the notebook:

https://github.com/jonathan-taylor/Rmagic

This one hasn't been fully updated to the final API, but the core code
is there and now it should be a trivial matter to update it.


I want to thank everyone who pitched in with ideas during the
discussion and review period, and I hope you'll all enjoy this and
come up with great ways to use the system.  For now, you can see how
the system works by playing with %%timeit and %%prun, the only two
builtins that I extended to work also as cell magics.

For more details, see the documentation where we've added also a long
new section with details and examples of how to create your own [4].

Cheers,

f

[1] https://github.com/ipython/ipython/pull/1732
[2] https://github.com/ipython/ipython/commit/61eb2ffeebb91a94fe9befe2c30e7839781ddc52
[2] https://github.com/ipython/ipython/issues/1611
[3] http://ipython.org/ipython-doc/dev/interactive/reference.html#magic-command-system

.. @+node:ekr.20130814140750.17193: *4* IPython code notes
Investigate how IPython hijacks event loops
http://groups.google.com/group/leo-editor/browse_thread/thread/e1dc6439bf8b17f9

pyos_inputhook is relevant

IPython lib.inputhook
http://ipython.org/ipython-doc/stable/api/generated/IPython.lib.inputhook.html

* IPython seems to require Python 2.x.
* I can run IPython from either C:\prog\ipython-0.12 or from python\lib\site-packages

From C:\prog\ipython-0.12\IPython\scripts

#!/usr/bin/env python
"""Terminal-based IPython entry point.
"""

from IPython.frontend.terminal.ipapp import launch_new_instance

launch_new_instance()

Here is ipapi.get::

@language python

    def get():
        """Get the global InteractiveShell instance."""
        from IPython.core.interactiveshell import InteractiveShell
        return InteractiveShell.instance()
        
See also:
    
http://ipython.org/ipython-doc/rel-0.12/api/index.html
http://ipython.org/ipython-doc/rel-0.12/api/generated/IPython.core.interactiveshell.html


.. @+node:ekr.20091218120633.6300: *3* Other notes
.. @+node:ekr.20090601083544.6066: *4* Cool plugins & Leo code
These are plugins/projects that I'd like to investigate further.

interact.py:  Add buttons so leo can interact with command line environments.
.. @+node:ekr.20070614094933: *4* EasyInstall installation notes--XP
C:\prog>c:\python25\python ez_setup.py
Downloading http://cheeseshop.python.org/packages/2.5/s/setuptools/setuptools-0.6c6-py2.5.egg
Processing setuptools-0.6c6-py2.5.egg
Copying setuptools-0.6c6-py2.5.egg to c:\python25\lib\site-packages
Adding setuptools 0.6c6 to easy-install.pth file
Installing easy_install-script.py script to c:\python25\Scripts
Installing easy_install.exe script to c:\python25\Scripts
Installing easy_install-2.5-script.py script to c:\python25\Scripts
Installing easy_install-2.5.exe script to c:\python25\Scripts

Installed c:\python25\lib\site-packages\setuptools-0.6c6-py2.5.egg
Processing dependencies for setuptools==0.6c6
Finished processing dependencies for setuptools==0.6c6

C:\prog>c:\python24\python ez_setup.py
Downloading http://cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0.6c6-py2.4.egg
Processing setuptools-0.6c6-py2.4.egg
creating c:\python24\lib\site-packages\setuptools-0.6c6-py2.4.egg
Extracting setuptools-0.6c6-py2.4.egg to c:\python24\lib\site-packages
Adding setuptools 0.6c6 to easy-install.pth file
Installing easy_install-script.py script to c:\python24\Scripts
Installing easy_install.exe script to c:\python24\Scripts
Installing easy_install-2.4-script.py script to c:\python24\Scripts
Installing easy_install-2.4.exe script to c:\python24\Scripts

Installed c:\python24\lib\site-packages\setuptools-0.6c6-py2.4.egg
Processing dependencies for setuptools==0.6c6
.. @+node:ekr.20071104222805: *4* Emacs/Pymacs notes
.. @+node:ekr.20071102191642.1: *5* xemacs/pymacs install notes
Added the following line to setup.py and setup files.

# -*- coding: utf-8 -*-

The second installation script installs the Emacs Lisp part only.
[snip]
I couldn't get this script to work.  Instead, I just created a pymacs folder at::

    C:\XEmacs\xemacs-packages\lisp\pymacs

For Win32 systems, I created create c:\Windows\pymacs-services.bat containing::

    c:\Python25\python C:\prog\Pymacs-0.22\scripts\pymacs-services

To check that pymacs.el is properly installed, start Emacs and do::

    M-x load-library RET pymacs

You should not receive any error.
(works)

To check that pymacs.py is properly installed, start an interactive Python session and type::

    from Pymacs import lisp

you should not receive any error.
(works)

To check that pymacs-services is properly installed, type the following in a console::

    pymacs-services </dev/null

You should then get a line ending with (pymacs-version version), and another saying : Protocol error : `>' expected..
(works, mostly: I omitted the </dev/null

The rest is from Leo's Chapter 18::

    ; Step 1: load leoPymacs if it has not already been loaded.
    (setq reload nil)
    (if (or reload (not (boundp 'leoPymacs)))
        (setq leoPymacs (pymacs-load "leoPymacs" "leo-"))
        (message "leoPymacs already loaded")
    )

    ; Step 2: compute the path to leo/test/ut.leo using a Leo script.
    (setq script
        "g.app.scriptResult = g.os_path_abspath(
            g.os_path_join(g.app.loadDir,'..','test','ut.leo'))"
    )
    (setq fileName (leo-run-script nil script))

    ; Step 3: execute a script in ut.leo.
    (setq c (leo-open fileName))
    (setq script "print 'c',c.shortFileName() ,'current:',c.p.h")
    (leo-run-script c script)
.. @+node:ekr.20071103090504: *5* Pymacs docs
@killcolor
.. @+node:ekr.20071103090504.1: *6* Emacs Lisp structures and Python objects
.. @+node:ekr.20071103090504.2: *7* Emacs lisp structures and Python
Conversions

Whenever Emacs Lisp calls Python functions giving them arguments, these arguments are Emacs Lisp structures that should be converted into Python objects in some way. Conversely, whenever Python calls Emacs Lisp functions, the arguments are Python objects that should be received as Emacs Lisp structures. We need some conventions for doing such conversions.

Conversions generally transmit mutable Emacs Lisp structures as mutable objects on the Python side, in such a way that transforming the object in Python will effectively transform the structure on the Emacs Lisp side (strings are handled a bit specially however, see below). The other way around, Python objects transmitted to Emacs Lisp often loose their mutability, so transforming the Emacs Lisp structure is not reflected on the Python side.

Pymacs sticks to standard Emacs Lisp, it explicitly avoids various Emacs Lisp extensions. One goal for many Pymacs users is taking some distance from Emacs Lisp, so Pymacs is not overly pushing users deeper into it.
.. @+node:ekr.20071103090504.3: *7* Simple objects
Simple objects

Emacs Lisp nil and the equivalent Emacs Lisp () yield Python None. Python None and the Python empty list [] are returned as nil in Emacs Lisp.

Emacs Lisp numbers, either integer or floating, are converted in equivalent Python numbers. Emacs Lisp characters are really numbers and yield Python numbers. In the other direction, Python numbers are converted into Emacs Lisp numbers, with the exception of long Python integers and complex numbers.

Emacs Lisp strings are usually converted into equivalent Python narrow strings. As Python strings do not have text properties, these are not reflected. This may be changed by setting the pymacs-mutable-strings option : if this variable is not nil, Emacs Lisp strings are then transmitted opaquely. Python strings, except Unicode, are always converted into Emacs Lisp strings.

Emacs Lisp symbols yield the special lisp.symbol or lisp[string] notations on the Python side. The first notation is used when the Emacs Lisp symbol starts with a letter, and contains only letters, digits and hyphens, in which case Emacs Lisp hyphens get replaced by Python underscores. This convention is welcome, as Emacs Lisp programmers commonly prefer using dashes, where Python programmers use underlines. Otherwise, the second notation is used. Conversely, lisp.symbol on the Python side yields an Emacs Lisp symbol with underscores replaced with hyphens, while lisp[string] corresponds to an Emacs Lisp symbol printed with that string which, of course, should then be a valid Emacs Lisp symbol name.
.. @+node:ekr.20071103090504.4: *7* Sequences
Sequences

The case of strings has been discussed in the previous section.

Proper Emacs Lisp lists, those for which the cdr of last cell is nil, are normally transmitted opaquely to Python. If pymacs-forget-mutability is set, or if Python later asks for these to be expanded, proper Emacs Lisp lists get converted into Python lists, if we except the empty list, which is always converted as Python None. In the other direction, Python lists are always converted into proper Emacs Lisp lists.

Emacs Lisp vectors are normally transmitted opaquely to Python. However, if pymacs-forget-mutability is set, or if Python later asks for these to be expanded, Emacs Lisp vectors get converted into Python tuples. In the other direction, Python tuples are always converted into Emacs Lisp vectors.

Remember the rule : Round parentheses correspond to square brackets!. It works for lists, vectors, tuples, seen from either Emacs Lisp or Python.

The above choices were debatable. Since Emacs Lisp proper lists and Python lists are the bread-and-butter of algorithms modifying structures, at least in my experience, I guess they are more naturally mapped into one another, this spares many casts in practice. While in Python, the most usual idiom for growing lists is appending to their end, the most usual idiom in Emacs Lisp to grow a list is by cons'ing new items at its beginning :

     (setq accumulator (cons 'new-item accumulator))


or more simply :

     (push 'new-item accumulator)


So, in case speed is especially important and many modifications happen in a row on the same side, while order of elements ought to be preserved, some (nreverse ...) on the Emacs Lisp side or .reverse() on the Python side side might be needed. Surely, proper lists in Emacs Lisp and lists in Python are the normal structure for which length is easily modified.

We cannot so easily change the size of a vector, the same as it is a bit more of a stunt to modify a tuple. The shape of these objects is fixed. Mapping vectors to tuples, which is admittedly strange, will only be done if the Python side requests an expanded copy, otherwise an opaque Emacs Lisp object is seen in Python. In the other direction, whenever an Emacs Lisp vector is needed, one has to write tuple(python_list) while transmitting the object. Such transmissions are most probably to be unusual, as people are not going to blindly transmit whole big structures back and forth between Emacs and Python, they would rather do it once in a while only, and do only local modifications afterwards. The infrequent casting to tuple for getting an Emacs Lisp vector seems to suggest that we did a reasonable compromise.

In Python, both tuples and lists have O(1) access, so there is no real speed consideration there. Emacs Lisp is different : vectors have O(1) access while lists have O(N) access. The rigidity of Emacs Lisp vectors is such that people do not resort to vectors unless there is a speed issue, so in real Emacs Lisp practice, vectors are used rather parsimoniously. So much, in fact, that Emacs Lisp vectors are overloaded for what they are not meant : for example, very small vectors are used to represent X events in key-maps, programmers only want to test vectors for their type, or users just like bracketed syntax. The speed of access is hardly an issue then.
.. @+node:ekr.20071103090504.5: *6* Opaque objects
.. @+node:ekr.20071103090504.6: *7* Emacs lisp handles
Emacs Lisp handles

When a Python function is called from Emacs Lisp, the function arguments have already been converted to Python types from Emacs Lisp types and the function result is going to be converted back to Emacs Lisp.

Several Emacs Lisp objects do not have Python equivalents, like for Emacs windows, buffers, markers, overlays, etc. It is nevertheless useful to pass them to Python functions, hoping that these Python functions will operate on these Emacs Lisp objects. Of course, the Python side may not itself modify such objects, it has to call for Emacs services to do so. Emacs Lisp handles are a mean to ease this communication.

Whenever an Emacs Lisp object may not be converted to a Python object, an Emacs Lisp handle is created and used instead. Whenever that Emacs Lisp handle is returned into Emacs Lisp from a Python function, or is used as an argument to an Emacs Lisp function from Python, the original Emacs Lisp object behind the Emacs Lisp handle is automatically retrieved.

Emacs Lisp handles are either instances of the internal Lisp class, or of one of its subclasses. If object is an Emacs Lisp handle, and if the underlying Emacs Lisp object is an Emacs Lisp sequence, then whenever object[index], object[index] = value and len(object) are meaningful, these may be used to fetch or alter an element of the sequence directly in Emacs Lisp space. Also, if object corresponds to an Emacs Lisp function, object(arguments) may be used to apply the Emacs Lisp function over the given arguments. Since arguments have been evaluated the Python way on the Python side, it would be conceptual overkill evaluating them again the Emacs Lisp way on the Emacs Lisp side, so Pymacs manage to quote arguments for defeating Emacs Lisp evaluation. The same logic applies the other way around.

Emacs Lisp handles have a value() method, which merely returns self. They also have a copy() method, which tries to open the box if possible. Emacs Lisp proper lists are turned into Python lists, Emacs Lisp vectors are turned into Python tuples. Then, modifying the structure of the copy on the Python side has no effect on the Emacs Lisp side.

For Emacs Lisp handles, str() returns an Emacs Lisp representation of the handle which should be eq to the original object if read back and evaluated in Emacs Lisp. repr() returns a Python representation of the expanded Emacs Lisp object. If that Emacs Lisp object has an Emacs Lisp representation which Emacs Lisp could read back, then repr() value is such that it could be read back and evaluated in Python as well, this would result in another object which is equal to the original, but not neccessarily eq.
.. @+node:ekr.20071103090504.7: *7* Python handles
Python handles

The same as Emacs Lisp handles are useful for handling Emacs Lisp objects on the Python side, Python handles are useful for handling Python objects on the Emacs Lisp side.

Many Python objects do not have direct Emacs Lisp equivalents, including long integers, complex numbers, Unicode strings, modules, classes, instances and surely a lot of others. When such are being transmitted to the Emacs Lisp side, Pymacs use Python handles. These are automatically recovered into the original Python objects whenever transmitted back to Python, either as arguments to a Python function, as the Python function itself, or as the return value of an Emacs Lisp function called from Python.

The objects represented by these Python handles may be inspected or modified using the basic library of Python functions. For example, in :

     (setq matcher (pymacs-eval "re.compile('pattern').match"))
     (pymacs-call matcher argument)


the initial setq above could be decomposed into :

           (setq compiled (pymacs-eval "re.compile('pattern')")
            matcher (pymacs-call "getattr" compiled "match"))


This example shows that one may use pymacs-call with getattr as the function, to get a wanted attribute for a Python object.
.. @+node:ekr.20071103090504.8: *6* Usages on the Emacs lisp side
.. @+node:ekr.20071103090504.9: *7* pymacs-eval/apply

pymacs-eval

Function (pymacs-eval text) gets text evaluated as a Python expression, and returns the value of that expression converted back to Emacs Lisp.

pymacs-call

Function (pymacs-call function argument...) will get Python to apply the given function over zero or more argument. function is either a string holding Python source code for a function (like a mere name, or even an expression), or else, a Python handle previously received from Python, and hopefully holding a callable Python object. Each argument gets separately converted to Python before the function is called. pymacs-call returns the resulting value of the function call, converted back to Emacs Lisp.

pymacs-apply

Function (pymacs-apply function arguments) will get Python to apply the given function over the given arguments. arguments is a list containing all arguments, or nil if there is none. Besides arguments being bundled together instead of given separately, the function acts pretty much like pymacs-call.

We do not expect that pymacs-eval, pymacs-call or pymacs-apply will be much used, if ever. In practice, the Emacs Lisp side of a Pymacs application might call pymacs-load a few times for linking into the Python modules, with the indirect effect of defining trampoline functions for these modules on the Emacs Lisp side, which can later be called like usual Emacs Lisp functions.
.. @+node:ekr.20071103090504.10: *7* pymacs-load
pymacs-load

Function (pymacs-load module prefix) imports the Python module into Emacs Lisp space.

module is the name of the file containing the module, without any .py or .pyc extension. If the directory part is omitted in module, the module will be looked into the current Python search path. Dot notation may be used when the module is part of a package. Each top-level function in the module produces a trampoline function in Emacs Lisp having the same name, except that underlines in Python names are turned into dashes in Emacs Lisp, and that prefix is uniformly added before the Emacs Lisp name (as a way to avoid name clashes).

prefix may be omitted, in which case it defaults to base name of module with underlines turned into dashes, and followed by a dash.

Whenever pymacs_load_hook is defined in the loaded Python module, pymacs-load calls it without arguments, but before creating the Emacs view for that module. So, the pymacs_load_hook function may create new definitions or even add interaction attributes to functions.

The return value of a successful pymacs-load is the module object. An optional third argument, noerror, when given and not nil, will have pymacs-load to return nil instead of raising an error, if the Python module could not be found.

When later calling one of these trampoline functions, all provided arguments are converted to Python and transmitted, and the function return value is later converted back to Emacs Lisp. It is left to the Python side to check for argument consistency. However, for an interactive function, the interaction specification drives some checking on the Emacs Lisp side. Currently, there is no provision for collecting keyword arguments in Emacs Lisp.
.. @+node:ekr.20071103091052: *6* Usage on the Python side
.. @+node:ekr.20071103091052.1: *7* Python setup
Python setup

Pymacs requires little or no setup in the Python modules which are meant to be used from Emacs, for the simple situations where these modules receive nothing but Emacs nil, numbers or strings, or return nothing but Python None, numbers or strings.

Otherwise, use from Pymacs import lisp. If you need more Pymacs features, like the Let class, write from Pymacs import lisp, Let.
.. @+node:ekr.20071103091052.2: *7* Response mode
Response mode

When Python receives a request from Emacs in the context of Pymacs, and until it returns the reply, Emacs keeps listening to serve Python requests. Emacs is not listening otherwise. Other Python threads, if any, may not call Emacs without very careful synchronisation.
.. @+node:ekr.20071103091052.3: *7* Emacs lisp symbols
Emacs Lisp symbols

lisp is a special object which has useful built-in magic. Its attributes do nothing but represent Emacs Lisp symbols, created on the fly as needed (symbols also have their built-in magic).

lisp.nil or lisp["nil"], are the same as None.

Otherwise, lisp.symbol and lisp[string] yield objects of the internal Symbol type. These are genuine Python objects, that could be referred to by simple Python variables. One may write quote = lisp.quote, for example, and use quote afterwards to mean that Emacs Lisp symbol. If a Python function received an Emacs Lisp symbol as an argument, it can check with == if that argument is lisp.never or lisp.ask, say. A Python function may well choose to return lisp.t.

In Python, writing lisp.symbol = value or lisp[string] = value does assign value to the corresponding symbol in Emacs Lisp space. Beware that in such cases, the lisp. prefix may not be [omitted] spared. After result = lisp.result, one cannot hope that a later result = 3 will have any effect in the Emacs Lisp space : this would merely change the Python variable result, which was a reference to a Symbol instance, so it is now a reference to the number 3.

The Symbol class has value() and copy() methods. One can use either lisp.symbol.value() or lisp.symbol.copy() to access the Emacs Lisp value of a symbol, after conversion to some Python object, of course. However, if value() would have given an Emacs Lisp handle, lisp.symbol.copy() has the effect of lisp.symbol.value().copy(), that is, it returns the value of the symbol as opened as possible.

A symbol may also be used as if it was a Python function, in which case it really names an Emacs Lisp function that should be applied over the following function arguments. The result of the Emacs Lisp function becomes the value of the call, with all due conversions of course.
.. @+node:ekr.20071103091052.4: *7* Dynamic bindings (The let class)
Dynamic bindings

As Emacs Lisp uses dynamic bindings, it is common that Emacs Lisp programs use
let for temporarily setting new values for some Emacs Lisp variables having
global scope. These variables recover their previous value automatically when
the let gets completed, even if an error occurs which interrupts the normal flow
of execution.

Pymacs has a Let class to represent such temporary settings. Suppose for example
that you want to recover the value of lisp.mark() when the transient mark mode
is active on the Emacs Lisp side. One could surely use lisp.mark(lisp.t) to
force reading the mark in such cases, but for the sake of illustration, let's
ignore that, and temporarily deactivate transient mark mode instead. This could
be done this way :

        try :
        let = Let()
        let.push(transient_mark_mode=None)
        ... user code ...
        finally :
        let.pop()

let.push() accepts any number of keywords arguments. Each keyword name is
interpreted as an Emacs Lisp symbol written the Pymacs way, with underlines. The
value of that Emacs Lisp symbol is saved on the Python side, and the value of
the keyword becomes the new temporary value for this Emacs Lisp symbol. A later
let.pop() restores the previous value for all symbols which were saved together
at the time of the corresponding let.push(). There may be more than one
let.push() call for a single Let instance, they stack within that instance. Each
let.pop() will undo one and only one let.push() from the stack, in the reverse
order or the pushes.

When the Let instance disappears, either because the programmer does del let or
let = None, or just because the Python let variable goes out of scope, all
remaining let.pop() get automatically executed, so the try/finally statement may
be omitted in practice. For this omission to work flawlessly, the programmer
should be careful at not keeping extra references to the Let instance.

The constructor call let = Let() also has an implied initial .push() over all
given arguments, so the explicit let.push() may be omitted as well. In practice,
this sums up and the above code could be reduced to a mere :

     let = Let(transient_mark_mode=None)
     ... user code ...

Be careful at assigning the result of the constructor to some Python variable.
Otherwise, the instance would disappear immediately after having been created,
restoring the Emacs Lisp variable much too soon.

Any variable to be bound with Let should have been bound in advance on the Emacs
Lisp side. This restriction usually does no kind of harm. Yet, it will likely be
lifted in some later version of Pymacs.

The Let class has other methods meant for some macros which are common in Emacs
Lisp programming, in the spirit of let bindings. These method names look like
push_* or pop_*, where Emacs Lisp macros are save-*. One has to use the matching
pop_* for undoing the effect of a given push_* rather than a mere .pop() : the
Python code is clearer, this also ensures that things are undone in the proper
order. The same Let instance may use many push_* methods, their effects nest.

push_excursion() and pop_excursion() save and restore the current buffer, point
and mark. push_match_data() and pop_match_data() save and restore the state of
the last regular expression match. push_restriction() and pop_restriction() save
and restore the current narrowing limits. push_selected_window() and
pop_selected_window() save and restore the fact that a window holds the cursor.
push_window_excursion() and pop_window_excursion() save and restore the current
window configuration in the Emacs display.

As a convenience, let.push() and all other push_* methods return the Let
instance. This helps chaining various push_* right after the instance
generation. For example, one may write :

         let = Let().push_excursion()
         if True :
         ... user code ...
         del let

The if True: (use if 1: with older Python releases, some people might prefer
writing if let: anyway), has the only goal of indenting user code, so the scope
of the let variable is made very explicit. This is purely stylistic, and not at
all necessary. The last del let might be omitted in a few circumstances, for
example if the excursion lasts until the end of the Python function.
.. @+node:ekr.20071103091052.5: *7* Raw Emacs lisp expression
Raw Emacs Lisp expressions

Pymacs offers a device for evaluating a raw Emacs Lisp expression, or a sequence of such, expressed as a string. One merely uses lisp as a function, like this :

     lisp("""
     ...
     possibly-long-sequence-of-lisp-expressions
     ...
     """)


The Emacs Lisp value of the last or only expression in the sequence becomes the value of the lisp call, after conversion back to Python.
.. @+node:ekr.20071103091052.6: *7* User interaction
User interaction

Emacs functions have the concept of user interaction for completing the specification of their arguments while being called. This happens only when a function is interactively called by the user, it does not happen when a function is programmatically called by another. As Python does not have a corresponding facility, a bit of trickery was needed to retrofit that facility on the Python side.

After loading a Python module but prior to creating an Emacs view for this
module, Pymacs decides whether loaded functions will be interactively callable
from Emacs, or not. Whenever a function has an interaction attribute, this
attribute holds the Emacs interaction specification for this function. The
specification is either another Python function or a string. In the former case,
that other function is called without arguments and should, maybe after having
consulted the user, return a list of the actual arguments to be used for the
original function. In the latter case, the specification string is used verbatim
as the argument to the (interactive ...) function on the Emacs side. To get a
short reminder about how this string is interpreted on the Emacs side, try C-h f
interactive within Emacs. Here is an example where an empty string is used to
specify that an interactive has no arguments::

    from Pymacs import lisp

    def hello_world() :
        "`Hello world' from Python."
        lisp.insert("Hello from Python!")
        hello_world.interaction = ''

Versions of Python released before the integration of PEP 232 do not allow users
to add attributes to functions, so there is a fallback mechanism. Let's presume
that a given function does not have an interaction attribute as explained above.
If the Python module contains an interactions global variable which is a
dictionary, if that dictionary has an entry for the given function with a value
other than None, that function is going to be interactive on the Emacs side.
Here is how the preceeding example should be written for an older version of
Python, or when portability is at premium::

    from Pymacs import lisp
    interactions = {}

    def hello_world() :
        "`Hello world' from Python."
        lisp.insert("Hello from Python!")
        interactions[hello_world] = ''

One might wonder why we do not merely use lisp.interactive(...) from within
Python. There is some magic in the Emacs Lisp interpreter itself, looking for
that call before the function is actually entered, this explains why
(interactive ...) has to appear first in an Emacs Lisp defun. Pymacs could try
to scan the already compiled form of the Python code, seeking for
lisp.interactive, but as the evaluation of lisp.interactive arguments could get
arbitrarily complex, it would a real challenge un-compiling that evaluation into
Emacs Lisp.
.. @+node:ekr.20071103091052.7: *7* Key bindings
Keybindings

An interactive function may be bound to a key sequence.

To translate bindings like C-x w, say, one might have to know a bit more how
Emacs Lisp processes string escapes like \C-x or \M-\C-x in Emacs Lisp, and
emulate it within Python strings, since Python does not have such escapes. \C-L,
where L is an upper case letter, produces a character which ordinal is the
result of subtracting 0x40 from ordinal of L. \M- has the ordinal one gets by
adding 0x80 to the ordinal of following described character. So people can use
self-inserting non-ASCII characters, \M- is given another representation, which
is to replace the addition of 0x80 by prefixing with `ESC', that is 0x1b.

So \C-x in Emacs is '\x18' in Python. This is easily found, using an interactive
Python session, by givin it : chr(ord('X') - ord('A') + 1). An easier way would
be using the kbd function on the Emacs Lisp side, like with lisp.kbd('C-x w') or
lisp.kbd('M-<f2>').

To bind the F1 key to the helper function in some module :

     lisp.global_set_key((lisp.f1,), lisp.module_helper)

(item,) is a Python tuple yielding an Emacs Lisp vector. lisp.f1 translates to
the Emacs Lisp symbol f1. So, Python (lisp.f1,) is Emacs Lisp [f1]. Keys like
[M-f2] might require some more ingenuity, one may write either (lisp['M-f2'],)
or (lisp.M_f2,) on the Python side.
.. @+node:ekr.20071103092153: *6* Debugging
.. @+node:ekr.20071103092153.1: *7* The *pymacs* buffer
The *Pymacs* buffer

Emacs and Python are two separate processes (well, each may use more than one process). Pymacs implements a simple communication protocol between both, and does whatever needed so the programmers do not have to worry about details. The main debugging tool is the communication buffer between Emacs and Python, which is named *Pymacs*. As it is sometimes helpful to understand the communication protocol, it is briefly explained here, using an artificially complex example to do so. Consider :

     (pymacs-eval "lisp('(pymacs-eval \"`2L**111`\")')")
     "2596148429267413814265248164610048L"

Here, Emacs asks Python to ask Emacs to ask Python for a simple bignum computation. Note that Emacs does not natively know how to handle big integers, nor has an internal representation for them. This is why I use backticks, so Python returns a string representation of the result, instead of the result itself. Here is a trace for this example. The < character flags a message going from Python to Emacs and is followed by an expression written in Emacs Lisp. The > character flags a message going from Emacs to Python and is followed by a expression written in Python. The number gives the length of the message.

     <22   (pymacs-version "0.3")
     >49   eval("lisp('(pymacs-eval \"`2L**111`\")')")
     <25   (pymacs-eval "`2L**111`")
     >18   eval("`2L**111`")
     <47   (pymacs-reply "2596148429267413814265248164610048L")
     >45   reply("2596148429267413814265248164610048L")
     <47   (pymacs-reply "2596148429267413814265248164610048L")

Python evaluation is done in the context of the Pymacs.pymacs module, so for example a mere reply really means Pymacs.pymacs.reply. On the Emacs Lisp side, there is no concept of module namespaces, so we use the pymacs- prefix as an attempt to stay clean. Users should ideally refrain from naming their Emacs Lisp objects with a pymacs- prefix.

reply and pymacs-reply are special functions meant to indicate that an expected result is finally transmitted. error and pymacs-error are special functions that introduce a string which explains an exception which recently occurred. pymacs-expand is a special function implementing the copy() methods of Emacs Lisp handles or symbols. In all other cases, the expression is a request for the other side, that request stacks until a corresponding reply is received.

Part of the protocol manages memory, and this management generates some extra-noise in the *Pymacs* buffer. Whenever Emacs passes a structure to Python, an extra pointer is generated on the Emacs side to inhibit garbage collection by Emacs. Python garbage collector detects when the received structure is no longer needed on the Python side, at which time the next communication will tell Emacs to remove the extra pointer. It works symmetrically as well, that is, whenever Python passes a structure to Emacs, an extra Python reference is generated to inhibit garbage collection on the Python side. Emacs garbage collector detects when the received structure is no longer needed on the Emacs side, after which Python will be told to remove the extra reference. For efficiency, those allocation-related messages are delayed, merged and batched together within the next communication having another purpose.

Variable pymacs-trace-transit may be modified for controlling how and when the *Pymacs* buffer, or parts thereof, get erased.
.. @+node:ekr.20071103092153.2: *7* Usual Emacs debugging
Emacs usual debugging

If cross-calls between Emacs Lisp and Python nest deeply, an error will raise
successive exceptions alternatively on both sides as requests unstack, and the
diagnostic gets transmitted back and forth, slightly growing as we go. So,
errors will eventually be reported by Emacs. I made no kind of effort to
transmit the Emacs Lisp backtrace on the Python side, as I do not see a purpose
for it : all debugging is done within Emacs windows anyway.

On recent Emacses, the Python backtrace gets displayed in the mini-buffer, and
the Emacs Lisp backtrace is simultaneously shown in the *Backtrace* window. One
useful thing is to allow to mini-buffer to grow big, so it has more chance to
fully contain the Python backtrace, the last lines of which are often especially
useful. Here, I use :

         (setq resize-mini-windows t
          max-mini-window-height .85)

in my .emacs file, so the mini-buffer may use 85% of the screen, and quickly
shrinks when fewer lines are needed. The mini-buffer contents disappear at the
next keystroke, but you can recover the Python backtrace by looking at the end
of the *Messages* buffer. In which case the ffap package in Emacs may be yet
another friend! From the *Messages* buffer, once ffap activated, merely put the
cursor on the file name of a Python module from the backtrace, and C-x C-f RET
will quickly open that source for you.
.. @+node:ekr.20071103092153.3: *7* Auto-reloading on save
Auto-reloading on save

I found useful to automatically pymacs-load some Python files whenever they get
saved from Emacs. This can be decided on a per-file or per-directory basis. To
get a particular Python file to be reloaded automatically on save, add the
following lines at the end :

     # Local Variables :
     # pymacs-auto-reload : t
     # End :

Here is an example of automatic reloading on a per-directory basis. The code
below assumes that Python files meant for Pymacs are kept in
~/share/emacs/python.

    (defun fp-maybe-pymacs-reload ()
        (let ((pymacsdir (expand-file-name "~/share/emacs/python/")))
         (when (and (string-equal (file-name-directory buffer-file-name)
                  pymacsdir)
              (string-match "\\.py\\'" buffer-file-name))
          (pymacs-load (substring buffer-file-name 0 -3)))))
         (add-hook 'after-save-hook 'fp-maybe-pymacs-reload)
.. @+node:ekr.20071103092153.4: *6* Example 1: defining an Emacs command in Python
@language rest

Let's say I have a a module, call it manglers.py, containing this simple python
function::

    def break_on_whitespace(some_string) :
         words = some_string.split()
         return '\n'.join(words)

The goal is telling Emacs about this function so that I can call it on a region
of text and replace the region with the result of the call. We shall also bind
this function to the key [f7].

Here is the Python side::

    from Pymacs import lisp
    interactions = {}

    def break_on_whitespace():
        # start and end may be given in any order.
        start,end = lisp.point(),lisp.mark(lisp.t)
        words = lisp.buffer_substring(start, end).split()
        lisp.delete_region(start,end)
        lisp.insert('\n'.join(words))

    interactions[break_on_whitespace] = ''

Here is the emacs side::

    (pymacs-load "manglers")
    (global-set-key [f7] 'manglers-break-on-whitespace)
.. @+node:ekr.20071103093725: *6* Example 3: defining a rebox tool
For comments held within boxes, it is painful to fill paragraphs, while
stretching or shrinking the surrounding box by hand, as needed. This piece of
Python code eases my life on this. It may be used interactively from within
Emacs through the Pymacs interface, or in batch as a script which filters a
single region to be reformatted.

In batch mode, the reboxing is driven by command options and arguments and expects a
complete, self-contained boxed comment from a file.

Emacs function rebox-region also presumes that the region encloses a single
boxed comment.

Emacs rebox-comment is different, as it has to chase itself the extent of the
surrounding boxed comment.

.. @+node:ekr.20071103094355: *7* The python side
Design notes for rebox.py:

Pymacs specific features are used exclusively from within the pymacs_load_hook
function and the Emacs_Rebox class. In batch mode, Pymacs is not even imported.

In batch mode, as well as with rebox-region, the text to handle is turned over
to Python, and fully processed in Python, with practically no Pymacs interaction
while the work gets done. On the other hand, rebox-comment is rather Pymacs
intensive: the comment boundaries are chased right from the Emacs buffer, as
directed by the function Emacs_Rebox.find_comment. Once the boundaries are
found, the remainder of the work is essentially done on the Python side.

Once the boxed comment has been reformatted in Python, the old comment is
removed in a single delete operation, the new comment is inserted in a second
operation. This occurs in Emacs_Rebox.process_emacs_region. But by doing so, if
point was within the boxed comment before the reformatting, its precise position
is lost. To well preserve point, Python might have driven all reformatting
details directly in the Emacs buffer. We really preferred doing it all on the
Python side : as we gain legibility by expressing the algorithms in pure Python,
the same Python code may be used in batch or interactively, and we avoid the
slowdown that would result from heavy use of Emacs services.

To avoid completely loosing point, I kludged a Marker class, which goal is to
estimate the new value of point from the old. Reformatting may change the amount
of white space, and either delete or insert an arbitrary number characters meant
to draw the box. The idea is to initially count the number of characters between
the beginning of the region and point, while ignoring any problematic character.
Once the comment has been reboxed, point is advanced from the beginning of the
region until we get the same count of characters, skipping all problematic
characters. This Marker class works fully on the Python side, it does not
involve Pymacs at all, but it does solve a problem that resulted from my choice
of keeping the data on the Python side instead of handling it directly in the
Emacs buffer.

We want a comment reformatting to appear as a single operation, in the context
of Emacs Undo. The method Emacs_Rebox.clean_undo_after handles the general case
for this. Not that we do so much in practice : a reformatting implies one
delete-region and one insert, and maybe some other little adjustements at
Emacs_Rebox.find_comment time. Even if this method scans and mofifies an Emacs
Lisp list directly in the Emacs memory, the code doing this stays neat and
legible. However, I found out that the undo list may grow quickly when the Emacs
buffer use markers, with the consequence of making this routine so Pymacs
intensive that most of the CPU is spent there. I rewrote that routine in Emacs
Lisp so it executes in a single Pymacs interaction.

Function Emacs_Rebox.remainder_of_line could have been written in Python, but it
was probably not worth going away from this one-liner in Emacs Lisp. Also, given
this routine is often called by find_comment, a few Pymacs protocol interactions
are spared this way. This function is useful when there is a need to apply a
regexp already compiled on the Python side, it is probably better fetching the
line from Emacs and do the pattern match on the Python side, than transmitting
the source of the regexp to Emacs for it to compile and apply it.

For refilling, I could have either used the refill algorithm built within in
Emacs, programmed a new one in Python, or relied on Ross Paterson's fmt,
distributed by GNU and available on most Linuxes. In fact, refill_lines prefers
the latter. My own Emacs setup is such that the built-in refill algorithm is
already overridden by GNU fmt, and it really does a much better job. Experience
taught me that calling an external program is fast enough to be very bearable,
even interactively. If Python called Emacs to do the refilling, Emacs would
itself call GNU fmt in my case, I preferred that Python calls GNU fmt directly.
I could have reprogrammed GNU fmt in Python. Despite interesting, this is an
uneasy project : fmt implements the Knuth refilling algorithm, which depends on
dynamic programming techniques; Ross did carefully fine tune them, and took care
of many details. If GNU fmt fails, for not being available, say, refill_lines
falls back on a dumb refilling algorithm, which is better than none.
.. @+node:ekr.20071103094355.1: *7* The emacs side
For most Emacs language editing modes, refilling does not make sense
outside comments, one may redefine the `M-q' command and link it to this
Pymacs module.  For example, I use this in my `.emacs' file::

    (add-hook 'c-mode-hook 'fp-c-mode-routine)
    (defun fp-c-mode-routine ()
        (local-set-key "\M-q" 'rebox-comment))
    (autoload 'rebox-comment "rebox" nil t)
    (autoload 'rebox-region "rebox" nil t)

with a "rebox.el" file having this single line:

    (pymacs-load "Pymacs.rebox")

The Emacs function `rebox-comment' automatically discovers the extent of the
boxed comment near the cursor, possibly refills the text, then adjusts the box
style. When this command is executed, the cursor should be within a comment, or
else it should be between two comments, in which case the command applies to the
next comment.

The Emacs function `rebox-region' does the same, except that it takes the
current region as a boxed comment. Both commands obey numeric prefixes to add or
remove a box, force a particular box style, or to prevent refilling of text.
Without such prefixes, the commands may deduce the current box style from the
comment itself so the style is preserved.

The default style initial value is nil or 0.  It may be preset to another
value through calling `rebox-set-default-style' from Emacs LISP, or changed
to anything else though using a negative value for a prefix, in which case
the default style is set to the absolute value of the prefix.

A `C-u' prefix avoids refilling the text, but forces using the default box
style.  `C-u -' lets the user interact to select one attribute at a time.

Adding new styles
-----------------

Let's suppose you want to add your own boxed comment style, say:

    //--------------------------------------------+
    // This is the style mandated in our company.
    //--------------------------------------------+

You might modify `rebox.py' but then, you will have to edit it whenever you
get a new release of `pybox.py'.  Emacs users might modify their `.emacs'
file or their `rebox.el' bootstrap, if they use one.  In either cases,
after the `(pymacs-load "Pymacs.rebox")' line, merely add:

    (rebox-Template NNN MMM ["//-----+"
                             "// box  "
                             "//-----+"])

In batch mode [If you use the `rebox' script rather than Emacs], the simplest is to make
your own.  This is easy, as it is very small.  For example, the above
style could be implemented by using this script instead of `rebox':

    #!/usr/bin/env python
    import sys
    from Pymacs import rebox
    rebox.Template(226, 325, ('//-----+',
                              '// box  ',
                              '//-----+'))
    apply(rebox.main, tuple(sys.argv[1:]))

In all cases, NNN is the style three-digit number, with no zero digit.
Pick any free style number, you are safe with 911 and up.  MMM is the
recognition priority, only used to disambiguate the style of a given boxed
comments, when it matches many styles at once.  Try something like 400.
Raise or lower that number as needed if you observe false matches.

Usually, the template uses three lines of equal length.  Do not worry if
this implies a few trailing spaces, they will be cleaned up automatically
at box generation time.  The first line or the third line may be omitted
to create vertically opened boxes.  But the middle line may not be omitted,
it ought to include the word `box', which will get replaced by your actual
comment.  If the first line is shorter than the middle one, it gets merged
at the start of the comment.  If the last line is shorter than the middle
one, it gets merged at the end of the comment and is refilled with it.
.. @+node:ekr.20071103093725.1: *7* rebox.py
@color
@language python
@tabwidth -4

@others
<< templates >>

if __name__ == '__main__':
    apply(main, sys.argv[1:])
.. @+node:ekr.20071103093725.2: *8* rebox declarations
#!/usr/bin/env python
# Copyright © 1991-1998, 2000, 2002 Progiciels Bourbeau-Pinard inc.
# François Pinard <pinard@iro.umontreal.ca>, April 1991.

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

"""\
Handling of boxed comments in various box styles.

Introduction
------------

For comments held within boxes, it is painful to fill paragraphs, while
stretching or shrinking the surrounding box "by hand", as needed.  This piece
of Python code eases my life on this.  It may be used interactively from
within Emacs through the Pymacs interface, or in batch as a script which
filters a single region to be reformatted.  I find only fair, while giving
all sources for a package using such boxed comments, to also give the
means I use for nicely modifying comments.  So here they are!

Box styles
----------

Each supported box style has a number associated with it.  This number is
arbitrary, yet by _convention_, it holds three non-zero digits such the the
hundreds digit roughly represents the programming language, the tens digit
roughly represents a box quality (or weight) and the units digit roughly
a box type (or figure).  An unboxed comment is merely one of box styles.
Language, quality and types are collectively referred to as style attributes.

When rebuilding a boxed comment, attributes are selected independently
of each other.  They may be specified by the digits of the value given
as Emacs commands argument prefix, or as the `-s' argument to the `rebox'
script when called from the shell.  If there is no such prefix, or if the
corresponding digit is zero, the attribute is taken from the value of the
default style instead.  If the corresponding digit of the default style
is also zero, than the attribute is recognised and taken from the actual
boxed comment, as it existed before prior to the command.  The value 1,
which is the simplest attribute, is ultimately taken if the parsing fails.

A programming language is associated with comment delimiters.  Values are
100 for none or unknown, 200 for `/*' and `*/' as in plain C, 300 for `//'
as in C++, 400 for `#' as in most scripting languages, 500 for `;' as in
LISP or assembler and 600 for `%' as in TeX or PostScript.

Box quality differs according to language. For unknown languages (100) or
for the C language (200), values are 10 for simple, 20 for rounded, and
30 or 40 for starred.  Simple quality boxes (10) use comment delimiters
to left and right of each comment line, and also for the top or bottom
line when applicable. Rounded quality boxes (20) try to suggest rounded
corners in boxes.  Starred quality boxes (40) mostly use a left margin of
asterisks or X'es, and use them also in box surroundings.  For all others
languages, box quality indicates the thickness in characters of the left
and right sides of the box: values are 10, 20, 30 or 40 for 1, 2, 3 or 4
characters wide.  With C++, quality 10 is not useful, it is not allowed.

Box type values are 1 for fully opened boxes for which boxing is done
only for the left and right but not for top or bottom, 2 for half
single lined boxes for which boxing is done on all sides except top,
3 for fully single lined boxes for which boxing is done on all sides,
4 for half double lined boxes which is like type 2 but more bold,
or 5 for fully double lined boxes which is like type 3 but more bold.

The special style 221 is for C comments between a single opening `/*'
and a single closing `*/'.  The special style 111 deletes a box.

Batch usage
-----------

Usage is `rebox [OPTION]... [FILE]'.  By default, FILE is reformatted to
standard output by refilling the comment up to column 79, while preserving
existing boxed comment style.  If FILE is not given, standard input is read.
Options may be:

  -n         Do not refill the comment inside its box, and ignore -w.
  -s STYLE   Replace box style according to STYLE, as explained above.
  -t         Replace initial sequence of spaces by TABs on each line.
  -v         Echo both the old and the new box styles on standard error.
  -w WIDTH   Try to avoid going over WIDTH columns per line.

So, a single boxed comment is reformatted by invocation.  `vi' users, for
example, would need to delimit the boxed comment first, before executing
the `!}rebox' command (is this correct? my `vi' recollection is far away).

Batch usage is also slow, as internal structures have to be reinitialised
at every call.  Producing a box in a single style is fast, but recognising
the previous style requires setting up for all possible styles.

Emacs usage
-----------

For most Emacs language editing modes, refilling does not make sense
outside comments, one may redefine the `M-q' command and link it to this
Pymacs module.  For example, I use this in my `.emacs' file:

     (add-hook 'c-mode-hook 'fp-c-mode-routine)
     (defun fp-c-mode-routine ()
       (local-set-key "\M-q" 'rebox-comment))
     (autoload 'rebox-comment "rebox" nil t)
     (autoload 'rebox-region "rebox" nil t)

with a "rebox.el" file having this single line:

     (pymacs-load "Pymacs.rebox")

Install Pymacs from `http://www.iro.umontreal.ca/~pinard/pymacs.tar.gz'.

The Emacs function `rebox-comment' automatically discovers the extent of
the boxed comment near the cursor, possibly refills the text, then adjusts
the box style.  When this command is executed, the cursor should be within
a comment, or else it should be between two comments, in which case the
command applies to the next comment.  The function `rebox-region' does
the same, except that it takes the current region as a boxed comment.
Both commands obey numeric prefixes to add or remove a box, force a
particular box style, or to prevent refilling of text.  Without such
prefixes, the commands may deduce the current box style from the comment
itself so the style is preserved.

The default style initial value is nil or 0.  It may be preset to another
value through calling `rebox-set-default-style' from Emacs LISP, or changed
to anything else though using a negative value for a prefix, in which case
the default style is set to the absolute value of the prefix.

A `C-u' prefix avoids refilling the text, but forces using the default box
style.  `C-u -' lets the user interact to select one attribute at a time.

Adding new styles
-----------------

Let's suppose you want to add your own boxed comment style, say:

    //--------------------------------------------+
    // This is the style mandated in our company.
    //--------------------------------------------+

You might modify `rebox.py' but then, you will have to edit it whenever you
get a new release of `pybox.py'.  Emacs users might modify their `.emacs'
file or their `rebox.el' bootstrap, if they use one.  In either cases,
after the `(pymacs-load "Pymacs.rebox")' line, merely add:

    (rebox-Template NNN MMM ["//-----+"
                             "// box  "
                             "//-----+"])

If you use the `rebox' script rather than Emacs, the simplest is to make
your own.  This is easy, as it is very small.  For example, the above
style could be implemented by using this script instead of `rebox':

    #!/usr/bin/env python
    import sys
    from Pymacs import rebox
    rebox.Template(226, 325, ('//-----+',
                              '// box  ',
                              '//-----+'))
    apply(rebox.main, tuple(sys.argv[1:]))

In all cases, NNN is the style three-digit number, with no zero digit.
Pick any free style number, you are safe with 911 and up.  MMM is the
recognition priority, only used to disambiguate the style of a given boxed
comments, when it matches many styles at once.  Try something like 400.
Raise or lower that number as needed if you observe false matches.

On average, the template uses three lines of equal length.  Do not worry if
this implies a few trailing spaces, they will be cleaned up automatically
at box generation time.  The first line or the third line may be omitted
to create vertically opened boxes.  But the middle line may not be omitted,
it ought to include the word `box', which will get replaced by your actual
comment.  If the first line is shorter than the middle one, it gets merged
at the start of the comment.  If the last line is shorter than the middle
one, it gets merged at the end of the comment and is refilled with it.

History
-------

I first observed rounded corners, as in style 223 boxes, in code from
Warren Tucker, a previous maintainer of the `shar' package, circa 1980.

Except for very special files, I carefully avoided boxed comments for
real work, as I found them much too hard to maintain.  My friend Paul
Provost was working at Taarna, a computer graphics place, which had boxes
as part of their coding standards.  He asked that we try something to get
him out of his misery, and this how `rebox.el' was originally written.
I did not plan to use it for myself, but Paul was so enthusiastic that I
timidly started to use boxes in my things, very little at first, but more
and more as time passed, still in doubt that it was a good move.  Later,
many friends spontaneously started to use this tool for real, some being very
serious workers.  This convinced me that boxes are acceptable, after all.

I do not use boxes much with Python code.  It is so legible that boxing
is not that useful.  Vertical white space is less necessary, too.  I even
avoid white lines within functions.  Comments appear prominent enough when
using highlighting editors like Emacs or nice printer tools like `enscript'.

After Emacs could be extended with Python, in 2001, I translated `rebox.el'
into `rebox.py', and added the facility to use it as a batch script.
"""

## Note: This code is currently compatible down to Python version 1.5.2.
## It is probably worth keeping it that way for a good while, still.

## Note: a double hash comment introduces a group of functions or methods.

import re, string, sys

.. @+node:ekr.20071103093725.3: *8* main
def main(*arguments):
    refill = 1
    style = None
    tabify = 0
    verbose = 0
    width = 79
    import getopt
    options, arguments = getopt.getopt(arguments, 'ns:tvw:', ['help'])
    for option, value in options:
        if option == '--help':
            sys.stdout.write(__doc__)
            sys.exit(0)
        elif option == '-n':
            refill = 0
        elif option == '-s':
            style = int(value)
        elif option == '-t':
            tabify = 1
        elif option == '-v':
            verbose = 1
        elif option == '-w':
            width = int(value)
    if len(arguments) == 0:
        text = sys.stdin.read()
    elif len(arguments) == 1:
        text = open(arguments[0]).read()
    else:
        sys.stderr.write("Invalid usage, try `rebox --help' for help.\n")
        sys.exit(1)
    old_style, new_style, text, position = engine(
        text, style=style, width=width, refill=refill, tabify=tabify)
    if text is None:
        sys.stderr.write("* Cannot rebox to style %d.\n" % new_style)
        sys.exit(1)
    sys.stdout.write(text)
    if verbose:
        if old_style == new_style:
            sys.stderr.write("Reboxed with style %d.\n" % old_style)
        else:
            sys.stderr.write("Reboxed from style %d to %d.\n"
                             % (old_style, new_style))

.. @+node:ekr.20071103093725.4: *8* pymacs_load_hook
def pymacs_load_hook():
    global interactions, lisp, Let, region, comment, set_default_style
    from Pymacs import lisp, Let
    emacs_rebox = Emacs_Rebox()
    # Declare functions for Emacs to import.
    interactions = {}
    region = emacs_rebox.region
    interactions[region] = 'P'
    comment = emacs_rebox.comment
    interactions[comment] = 'P'
    set_default_style = emacs_rebox.set_default_style

.. @+node:ekr.20071103093725.5: *8* class Emacs_Rebox
class Emacs_Rebox:
    @others
.. @+node:ekr.20071103093725.6: *9* __init__ (Emacs_Rebox)

def __init__(self):
    self.default_style = None

.. @+node:ekr.20071103093725.7: *9* set_default_style
def set_default_style(self, style):
    """\
Set the default style to STYLE.
"""
    self.default_style = style

.. @+node:ekr.20071103093725.8: *9* region
def region(self, flag):
    """\
Rebox the boxed comment in the current region, obeying FLAG.
"""
    self.emacs_engine(flag, self.find_region)

.. @+node:ekr.20071103093725.9: *9* comment
def comment(self, flag):
    """\
Rebox the surrounding boxed comment, obeying FLAG.
"""
    self.emacs_engine(flag, self.find_comment)

.. @+node:ekr.20071103093725.10: *9* emacs_engine
def emacs_engine(self, flag, find_limits):
    """\
Rebox text while obeying FLAG.  Call FIND_LIMITS to discover the extent
of the boxed comment.
"""
    # `C-u -' means that box style is to be decided interactively.
    if flag == lisp['-']:
        flag = self.ask_for_style()
    # If FLAG is zero or negative, only change default box style.
    if type(flag) is type(0) and flag <= 0:
        self.default_style = -flag
        lisp.message("Default style set to %d" % -flag)
        return
    # Decide box style and refilling.
    if flag is None:
        style = self.default_style
        refill = 1
    elif type(flag) == type(0):
        if self.default_style is None:
            style = flag
        else:
            style = merge_styles(self.default_style, flag)
        refill = 1
    else:
        flag = flag.copy()
        if type(flag) == type([]):
            style = self.default_style
            refill = 0
        else:
            lisp.error("Unexpected flag value %s" % flag)
    # Prepare for reboxing.
    lisp.message("Reboxing...")
    checkpoint = lisp.buffer_undo_list.value()
    start, end = find_limits()
    text = lisp.buffer_substring(start, end)
    width = lisp.fill_column.value()
    tabify = lisp.indent_tabs_mode.value() is not None
    point = lisp.point()
    if start <= point < end:
        position = point - start
    else:
        position = None
    # Rebox the text and replace it in Emacs buffer.
    old_style, new_style, text, position = engine(
        text, style=style, width=width,
        refill=refill, tabify=tabify, position=position)
    if text is None:
        lisp.error("Cannot rebox to style %d" % new_style)
    lisp.delete_region(start, end)
    lisp.insert(text)
    if position is not None:
        lisp.goto_char(start + position)
    # Collapse all operations into a single one, for Undo.
    self.clean_undo_after(checkpoint)
    # We are finished, tell the user.
    if old_style == new_style:
        lisp.message("Reboxed with style %d" % old_style)
    else:
        lisp.message("Reboxed from style %d to %d"
                     % (old_style, new_style))

.. @+node:ekr.20071103093725.11: *9* ask_for_style
def ask_for_style(self):
    """\
Request the style interactively, using the minibuffer.
"""
    language = quality = type = None
    while language is None:
        lisp.message("\
Box language is 100-none, 200-/*, 300-//, 400-#, 500-;, 600-%%")
        key = lisp.read_char()
        if key >= ord('0') and key <= ord('6'):
            language = key - ord('0')
    while quality is None:
        lisp.message("\
Box quality/width is 10-simple/1, 20-rounded/2, 30-starred/3 or 40-starred/4")
        key = lisp.read_char()
        if key >= ord('0') and key <= ord('4'):
            quality = key - ord('0')
    while type is None:
        lisp.message("\
Box type is 1-opened, 2-half-single, 3-single, 4-half-double or 5-double")
        key = lisp.read_char()
        if key >= ord('0') and key <= ord('5'):
            type = key - ord('0')
    return 100*language + 10*quality + type

.. @+node:ekr.20071103093725.12: *9* find_region
def find_region(self):
    """\
Return the limits of the region.
"""
    return lisp.point(), lisp.mark(lisp.t)

.. @+node:ekr.20071103093725.13: *9* find_comment
def find_comment(self):
    """\
Find and return the limits of the block of comments following or enclosing
the cursor, or return an error if the cursor is not within such a block
of comments.  Extend it as far as possible in both directions.
"""
    let = Let()
    let.push_excursion()
    # Find the start of the current or immediately following comment.
    lisp.beginning_of_line()
    lisp.skip_chars_forward(' \t\n')
    lisp.beginning_of_line()
    if not language_matcher[0](self.remainder_of_line()):
        temp = lisp.point()
        if not lisp.re_search_forward('\\*/', None, lisp.t):
            lisp.error("outside any comment block")
        lisp.re_search_backward('/\\*')
        if lisp.point() > temp:
            lisp.error("outside any comment block")
        temp = lisp.point()
        lisp.beginning_of_line()
        lisp.skip_chars_forward(' \t')
        if lisp.point() != temp:
            lisp.error("text before start of comment")
        lisp.beginning_of_line()
    start = lisp.point()
    language = guess_language(self.remainder_of_line())
    # Find the end of this comment.
    if language == 2:
        lisp.search_forward('*/')
        if not lisp.looking_at('[ \t]*$'):
            lisp.error("text after end of comment")
    lisp.end_of_line()
    if lisp.eobp():
        lisp.insert('\n')
    else:
        lisp.forward_char(1)
    end = lisp.point()
    # Try to extend the comment block backwards.
    lisp.goto_char(start)
    while not lisp.bobp():
        if language == 2:
            lisp.skip_chars_backward(' \t\n')
            if not lisp.looking_at('[ \t]*\n[ \t]*/\\*'):
                break
            if lisp.point() < 2:
                break
            lisp.backward_char(2)
            if not lisp.looking_at('\\*/'):
                break
            lisp.re_search_backward('/\\*')
            temp = lisp.point()
            lisp.beginning_of_line()
            lisp.skip_chars_forward(' \t')
            if lisp.point() != temp:
                break
            lisp.beginning_of_line()
        else:
            lisp.previous_line(1)
            if not language_matcher[language](self.remainder_of_line()):
                break
        start = lisp.point()
    # Try to extend the comment block forward.
    lisp.goto_char(end)
    while language_matcher[language](self.remainder_of_line()):
        if language == 2:
            lisp.re_search_forward('[ \t]*/\\*')
            lisp.re_search_forward('\\*/')
            if lisp.looking_at('[ \t]*$'):
                lisp.beginning_of_line()
                lisp.forward_line(1)
                end = lisp.point()
        else:
            lisp.forward_line(1)
            end = lisp.point()
    return start, end

.. @+node:ekr.20071103093725.14: *9* remainder_of_line
def remainder_of_line(self):
    """\
Return all characters between point and end of line in Emacs buffer.
"""
    return lisp('''\
(buffer-substring (point) (save-excursion (skip-chars-forward "^\n") (point)))
''')

.. @+node:ekr.20071103093725.15: *9* clean_undo_after_old
def clean_undo_after_old(self, checkpoint):
    """\
Remove all intermediate boundaries from the Undo list since CHECKPOINT.
"""
    # Declare some LISP functions.
    car = lisp.car
    cdr = lisp.cdr
    eq = lisp.eq
    setcdr = lisp.setcdr
    # Remove any `nil' delimiter recently added to the Undo list.
    cursor = lisp.buffer_undo_list.value()
    if not eq(cursor, checkpoint):
        tail = cdr(cursor)
        while not eq(tail, checkpoint):
            if car(tail):
                cursor = tail
                tail = cdr(cursor)
            else:
                tail = cdr(tail)
                setcdr(cursor, tail)

.. @+node:ekr.20071103093725.16: *9* clean_undo_after
def clean_undo_after(self, checkpoint):
    """\
Remove all intermediate boundaries from the Undo list since CHECKPOINT.
"""
    lisp("""
(let ((undo-list %s))
(if (not (eq buffer-undo-list undo-list))
  (let ((cursor buffer-undo-list))
(while (not (eq (cdr cursor) undo-list))
  (if (car (cdr cursor))
      (setq cursor (cdr cursor))
    (setcdr cursor (cdr (cdr cursor)))))))
nil)
"""
         % (checkpoint or 'nil'))

.. @+node:ekr.20071103093725.17: *8* engine
def engine(text, style=None, width=79, refill=1, tabify=0, position=None):
    """\
Add, delete or adjust a boxed comment held in TEXT, according to STYLE.
STYLE values are explained at beginning of this file.  Any zero attribute
in STYLE indicates that the corresponding attribute should be recovered
from the currently existing box.  Produced lines will not go over WIDTH
columns if possible, if refilling gets done.  But if REFILL is false, WIDTH
is ignored.  If TABIFY is true, the beginning of produced lines will have
spaces replace by TABs.  POSITION is either None, or a character position
within TEXT.  Returns four values: the old box style, the new box style,
the reformatted text, and either None or the adjusted value of POSITION in
the new text.  The reformatted text is returned as None if the requested
style does not exist.
"""
    last_line_complete = text and text[-1] == '\n'
    if last_line_complete:
        text = text[:-1]
    lines = string.split(string.expandtabs(text), '\n')
    # Decide about refilling and the box style to use.
    new_style = 111
    old_template = guess_template(lines)
    new_style = merge_styles(new_style, old_template.style)
    if style is not None:
        new_style = merge_styles(new_style, style)
    new_template = template_registry.get(new_style)
    # Interrupt processing if STYLE does not exist.
    if not new_template:
        return old_template.style, new_style, None, None
    # Remove all previous comment marks, and left margin.
    if position is not None:
        marker = Marker()
        marker.save_position(text, position, old_template.characters())
    lines, margin = old_template.unbuild(lines)
    # Ensure only one white line between paragraphs.
    counter = 1
    while counter < len(lines) - 1:
        if lines[counter] == '' and lines[counter-1] == '':
            del lines[counter]
        else:
            counter = counter + 1
    # Rebuild the boxed comment.
    lines = new_template.build(lines, width, refill, margin)
    # Retabify to the left only.
    if tabify:
        for counter in range(len(lines)):
            tabs = len(re.match(' *', lines[counter]).group()) / 8
            lines[counter] = '\t' * tabs + lines[counter][8*tabs:]
    # Restore the point position.
    text = string.join(lines, '\n')
    if last_line_complete:
        text = text + '\n'
    if position is not None:
        position = marker.get_position(text, new_template.characters())
    return old_template.style, new_style, text, position

.. @+node:ekr.20071103093725.18: *8* guess_language
def guess_language(line):
    """\
Guess the language in use for LINE.
"""
    for language in range(len(language_matcher) - 1, 1, -1):
        if language_matcher[language](line):
            return language
    return 1

.. @+node:ekr.20071103093725.19: *8* guess_template
def guess_template(lines):
    """\
Find the heaviest box template matching LINES.
"""
    best_template = None
    for template in template_registry.values():
        if best_template is None or template > best_template:
            if template.match(lines):
                best_template = template
    return best_template

.. @+node:ekr.20071103093725.20: *8* left_margin_size
def left_margin_size(lines):
    """\
Return the width of the left margin for all LINES.  Ignore white lines.
"""
    margin = None
    for line in lines:
        counter = len(re.match(' *', line).group())
        if counter != len(line):
            if margin is None or counter < margin:
                margin = counter
    if margin is None:
        margin = 0
    return margin

.. @+node:ekr.20071103093725.21: *8* merge_styles
def merge_styles(original, update):
    """\
Return style attributes as per ORIGINAL, in which attributes have been
overridden by non-zero corresponding style attributes from UPDATE.
"""
    style = [original / 100, original / 10 % 10, original % 10]
    merge = update / 100, update / 10 % 10, update % 10
    for counter in range(3):
        if merge[counter]:
            style[counter] = merge[counter]
    return 100*style[0] + 10*style[1] + style[2]

.. @+node:ekr.20071103093725.22: *8* refill_lines
def refill_lines(lines, width):
    """\
Refill LINES, trying to not produce lines having more than WIDTH columns.
"""
    # Try using GNU `fmt'.
    import tempfile, os
    name = tempfile.mktemp()
    open(name, 'w').write(string.join(lines, '\n') + '\n')
    process = os.popen('fmt -cuw %d %s' % (width, name))
    text = process.read()
    os.remove(name)
    if process.close() is None:
        return map(string.expandtabs, string.split(text, '\n')[:-1])
    # If `fmt' failed, do refilling more naively, wihtout using the
    # Knuth algorithm, nor protecting full stops at end of sentences.
    lines.append(None)
    new_lines = []
    new_line = ''
    start = 0
    for end in range(len(lines)):
        if not lines[end]:
            margin = left_margin_size(lines[start:end])
            for line in lines[start:end]:
                counter = len(re.match(' *', line).group())
                if counter > margin:
                    if new_line:
                        new_lines.append(' ' * margin + new_line)
                        new_line = ''
                    indent = counter - margin
                else:
                    indent = 0
                for word in string.split(line):
                    if new_line:
                        if len(new_line) + 1 + len(word) > width:
                            new_lines.append(' ' * margin + new_line)
                            new_line = word
                        else:
                            new_line = new_line + ' ' + word
                    else:
                        new_line = ' ' * indent + word
                        indent = 0
            if new_line:
                new_lines.append(' ' * margin + new_line)
                new_line = ''
            if lines[end] is not None:
                new_lines.append('')
                start = end + 1
    return new_lines

.. @+node:ekr.20071103093725.23: *8* class Marker
class Marker:
    @others
.. @+node:ekr.20071103093725.24: *9* save_position

## Heuristic to simulate a marker while reformatting boxes.

def save_position(self, text, position, ignorable):
    """\
Given a TEXT and a POSITION in that text, save the adjusted position
by faking that all IGNORABLE characters before POSITION were removed.
"""
    ignore = {}
    for character in ' \t\r\n' + ignorable:
        ignore[character] = None
    counter = 0
    for character in text[:position]:
        if character in ignore:
            counter = counter + 1
    self.position = position - counter

.. @+node:ekr.20071103093725.25: *9* get_position
def get_position(self, text, ignorable, latest=0):
    """\
Given a TEXT, return the value that would yield the currently saved position,
if it was saved by `save_position' with IGNORABLE.  Unless the position lies
within a series of ignorable characters, LATEST has no effect in practice.
If LATEST is true, return the biggest possible value instead of the smallest.
"""
    ignore = {}
    for character in ' \t\r\n' + ignorable:
        ignore[character] = None
    counter = 0
    position = 0
    if latest:
        for character in text:
            if character in ignore:
                counter = counter + 1
            else:
                if position == self.position:
                    break
                position = position + 1
    elif self.position > 0:
        for character in text:
            if character in ignore:
                counter = counter + 1
            else:
                position = position + 1
                if position == self.position:
                    break
    return position + counter

.. @+node:ekr.20071103093725.26: *8* class Template
## Template processing.

class Template:
    @others
.. @+node:ekr.20071103093725.27: *9* __init_ (Template)_

def __init__(self, style, weight, lines):
    """\
Digest and register a single template.  The template is numbered STYLE,
has a parsing WEIGHT, and is described by one to three LINES.
STYLE should be used only once through all `declare_template' calls.

One of the lines should contain the substring `box' to represent the comment
to be boxed, and if three lines are given, `box' should appear in the middle
one.  Lines containing only spaces are implied as necessary before and after
the the `box' line, so we have three lines.

Normally, all three template lines should be of the same length.  If the first
line is shorter, it represents a start comment string to be bundled within the
first line of the comment text.  If the third line is shorter, it represents
an end comment string to be bundled at the end of the comment text, and
refilled with it.
"""
    assert style not in template_registry, \
           "Style %d defined more than once" % style
    self.style = style
    self.weight = weight
    # Make it exactly three lines, with `box' in the middle.
    start = string.find(lines[0], 'box')
    if start >= 0:
        line1 = None
        line2 = lines[0]
        if len(lines) > 1:
            line3 = lines[1]
        else:
            line3 = None
    else:
        start = string.find(lines[1], 'box')
        if start >= 0:
            line1 = lines[0]
            line2 = lines[1]
            if len(lines) > 2:
                line3 = lines[2]
            else:
                line3 = None
        else:
            assert 0, "Erroneous template for %d style" % style
    end = start + len('box')
    # Define a few booleans.
    self.merge_nw = line1 is not None and len(line1) < len(line2)
    self.merge_se = line3 is not None and len(line3) < len(line2)
    # Define strings at various cardinal directions.
    if line1 is None:
        self.nw = self.nn = self.ne = None
    elif self.merge_nw:
        self.nw = line1
        self.nn = self.ne = None
    else:
        if start > 0:
            self.nw = line1[:start]
        else:
            self.nw = None
        if line1[start] != ' ':
            self.nn = line1[start]
        else:
            self.nn = None
        if end < len(line1):
            self.ne = string.rstrip(line1[end:])
        else:
            self.ne = None
    if start > 0:
        self.ww = line2[:start]
    else:
        self.ww = None
    if end < len(line2):
        self.ee = line2[end:]
    else:
        self.ee = None
    if line3 is None:
        self.sw = self.ss = self.se = None
    elif self.merge_se:
        self.sw = self.ss = None
        self.se = string.rstrip(line3)
    else:
        if start > 0:
            self.sw = line3[:start]
        else:
            self.sw = None
        if line3[start] != ' ':
            self.ss = line3[start]
        else:
            self.ss = None
        if end < len(line3):
            self.se = string.rstrip(line3[end:])
        else:
            self.se = None
    # Define parsing regexps.
    if self.merge_nw:
        self.regexp1 = re.compile(' *' + regexp_quote(self.nw) + '.*$')
    elif self.nw and not self.nn and not self.ne:
        self.regexp1 = re.compile(' *' + regexp_quote(self.nw) + '$')
    elif self.nw or self.nn or self.ne:
        self.regexp1 = re.compile(
            ' *' + regexp_quote(self.nw) + regexp_ruler(self.nn)
            + regexp_quote(self.ne) + '$')
    else:
        self.regexp1 = None
    if self.ww or self.ee:
        self.regexp2 = re.compile(
            ' *' + regexp_quote(self.ww) + '.*'
            + regexp_quote(self.ee) + '$')
    else:
        self.regexp2 = None
    if self.merge_se:
        self.regexp3 = re.compile('.*' + regexp_quote(self.se) + '$')
    elif self.sw and not self.ss and not self.se:
        self.regexp3 = re.compile(' *' + regexp_quote(self.sw) + '$')
    elif self.sw or self.ss or self.se:
        self.regexp3 = re.compile(
            ' *' + regexp_quote(self.sw) + regexp_ruler(self.ss)
            + regexp_quote(self.se) + '$')
    else:
        self.regexp3 = None
    # Save results.
    template_registry[style] = self

.. @+node:ekr.20071103093725.28: *9* __cmp__
def __cmp__(self, other):
    return cmp(self.weight, other.weight)

.. @+node:ekr.20071103093725.29: *9* characters
def characters(self):
    """\
Return a string of characters which may be used to draw the box.
"""
    characters = ''
    for text in (self.nw, self.nn, self.ne,
                 self.ww, self.ee,
                 self.sw, self.ss, self.se):
        if text:
            for character in text:
                if character not in characters:
                    characters = characters + character
    return characters

.. @+node:ekr.20071103093725.30: *9* match
def match(self, lines):
    """\
Returns true if LINES exactly match this template.
"""
    start = 0
    end = len(lines)
    if self.regexp1 is not None:
        if start == end or not self.regexp1.match(lines[start]):
            return 0
        start = start + 1
    if self.regexp3 is not None:
        if end == 0 or not self.regexp3.match(lines[end-1]):
            return 0
        end = end - 1
    if self.regexp2 is not None:
        for line in lines[start:end]:
            if not self.regexp2.match(line):
                return 0
    return 1

.. @+node:ekr.20071103093725.31: *9* unbuild
def unbuild(self, lines):
    """\
Remove all comment marks from LINES, as hinted by this template.  Returns the
cleaned up set of lines, and the size of the left margin.
"""
    margin = left_margin_size(lines)
    # Remove box style marks.
    start = 0
    end = len(lines)
    if self.regexp1 is not None:
        lines[start] = unbuild_clean(lines[start], self.regexp1)
        start = start + 1
    if self.regexp3 is not None:
        lines[end-1] = unbuild_clean(lines[end-1], self.regexp3)
        end = end - 1
    if self.regexp2 is not None:
        for counter in range(start, end):
            lines[counter] = unbuild_clean(lines[counter], self.regexp2)
    # Remove the left side of the box after it turned into spaces.
    delta = left_margin_size(lines) - margin
    for counter in range(len(lines)):
        lines[counter] = lines[counter][delta:]
    # Remove leading and trailing white lines.
    start = 0
    end = len(lines)
    while start < end and lines[start] == '':
        start = start + 1
    while end > start and lines[end-1] == '':
        end = end - 1
    return lines[start:end], margin

.. @+node:ekr.20071103093725.32: *9* build
def build(self, lines, width, refill, margin):
    """\
Put LINES back into a boxed comment according to this template, after
having refilled them if REFILL.  The box should start at column MARGIN,
and the total size of each line should ideally not go over WIDTH.
"""
    # Merge a short end delimiter now, so it gets refilled with text.
    if self.merge_se:
        if lines:
            lines[-1] = lines[-1] + '  ' + self.se
        else:
            lines = [self.se]
    # Reduce WIDTH according to left and right inserts, then refill.
    if self.ww:
        width = width - len(self.ww)
    if self.ee:
        width = width - len(self.ee)
    if refill:
        lines = refill_lines(lines, width)
    # Reduce WIDTH further according to the current right margin,
    # and excluding the left margin.
    maximum = 0
    for line in lines:
        if line:
            if line[-1] in '.!?':
                length = len(line) + 1
            else:
                length = len(line)
            if length > maximum:
                maximum = length
    width = maximum - margin
    # Construct the top line.
    if self.merge_nw:
        lines[0] = ' ' * margin + self.nw + lines[0][margin:]
        start = 1
    elif self.nw or self.nn or self.ne:
        if self.nn:
            line = self.nn * width
        else:
            line = ' ' * width
        if self.nw:
            line = self.nw + line
        if self.ne:
            line = line + self.ne
        lines.insert(0, string.rstrip(' ' * margin + line))
        start = 1
    else:
        start = 0
    # Construct all middle lines.
    for counter in range(start, len(lines)):
        line = lines[counter][margin:]
        line = line + ' ' * (width - len(line))
        if self.ww:
            line = self.ww + line
        if self.ee:
            line = line + self.ee
        lines[counter] = string.rstrip(' ' * margin + line)
    # Construct the bottom line.
    if self.sw or self.ss or self.se and not self.merge_se:
        if self.ss:
            line = self.ss * width
        else:
            line = ' ' * width
        if self.sw:
            line = self.sw + line
        if self.se and not self.merge_se:
            line = line + self.se
        lines.append(string.rstrip(' ' * margin + line))
    return lines

.. @+node:ekr.20071103093725.33: *8* regexp_quote
def regexp_quote(text):
    """\
Return a regexp matching TEXT without its surrounding space, maybe
followed by spaces.  If STRING is nil, return the empty regexp.
Unless spaces, the text is nested within a regexp parenthetical group.
"""
    if text is None:
        return ''
    if text == ' ' * len(text):
        return ' *'
    return '(' + re.escape(text.strip() + ') *'

.. @+node:ekr.20071103093725.34: *8* regexp_ruler
def regexp_ruler(character):
    """\
Return a regexp matching two or more repetitions of CHARACTER, maybe
followed by spaces.  Is CHARACTER is nil, return the empty regexp.
Unless spaces, the ruler is nested within a regexp parenthetical group.
"""
    if character is None:
        return ''
    if character == ' ':
        return '  +'
    return '(' + re.escape(character + character) + '+) *'

.. @+node:ekr.20071103093725.35: *8* unbuild_clean
def unbuild_clean(line, regexp):
    """\
Return LINE with all parenthetical groups in REGEXP erased and replaced by an
equivalent number of spaces, except for trailing spaces, which get removed.
"""
    match = re.match(regexp, line)
    groups = match.groups()
    for counter in range(len(groups)):
        if groups[counter] is not None:
            start, end = match.span(1 + counter)
            line = line[:start] + ' ' * (end - start) + line[end:]
    return string.rstrip(line)

.. @+node:ekr.20071103093725.36: *8* make_generic
## Template data.

# Matcher functions for a comment start, indexed by numeric LANGUAGE.
language_matcher = []
for pattern in (r' *(/\*|//+|#+|;+|%+)',
                r'',            # 1
                r' */\*',       # 2
                r' *//+',       # 3
                r' *#+',        # 4
                r' *;+',        # 5
                r' *%+'):       # 6
    language_matcher.append(re.compile(pattern).match)

# Template objects, indexed by numeric style.
template_registry = {}

def make_generic(style, weight, lines):
    """\
Add various language digit to STYLE and generate one template per language,
all using the same WEIGHT.  Replace `?' in LINES accordingly.
"""
    for language, character in ((300, '/'),  # C++ style comments
                                (400, '#'),  # scripting languages
                                (500, ';'),  # LISP and assembler
                                (600, '%')): # TeX and PostScript
        new_style = language + style
        if 310 < new_style <= 319:
            # Disallow quality 10 with C++.
            continue
        new_lines = []
        for line in lines:
            new_lines.append(string.replace(line, '?', character))
        Template(new_style, weight, new_lines)

.. @+node:ekr.20071103093725.37: *8* << templates >>

make_generic(11, 115, ('? box',))

make_generic(12, 215, ('? box ?',
                       '? --- ?'))

make_generic(13, 315, ('? --- ?',
                       '? box ?',
                       '? --- ?'))

make_generic(14, 415, ('? box ?',
                       '???????'))

make_generic(15, 515, ('???????',
                       '? box ?',
                       '???????'))

make_generic(21, 125, ('?? box',))

make_generic(22, 225, ('?? box ??',
                       '?? --- ??'))

make_generic(23, 325, ('?? --- ??',
                       '?? box ??',
                       '?? --- ??'))

make_generic(24, 425, ('?? box ??',
                       '?????????'))

make_generic(25, 525, ('?????????',
                       '?? box ??',
                       '?????????'))

make_generic(31, 135, ('??? box',))

make_generic(32, 235, ('??? box ???',
                       '??? --- ???'))

make_generic(33, 335, ('??? --- ???',
                       '??? box ???',
                       '??? --- ???'))

make_generic(34, 435, ('??? box ???',
                       '???????????'))

make_generic(35, 535, ('???????????',
                       '??? box ???',
                       '???????????'))

make_generic(41, 145, ('???? box',))

make_generic(42, 245, ('???? box ????',
                       '???? --- ????'))

make_generic(43, 345, ('???? --- ????',
                       '???? box ????',
                       '???? --- ????'))

make_generic(44, 445, ('???? box ????',
                       '?????????????'))

make_generic(45, 545, ('?????????????',
                       '???? box ????',
                       '?????????????'))

# Textual (non programming) templates.

Template(111, 113, ('box',))

Template(112, 213, ('| box |',
                    '+-----+'))

Template(113, 313, ('+-----+',
                    '| box |',
                    '+-----+'))

Template(114, 413, ('| box |',
                    '*=====*'))

Template(115, 513, ('*=====*',
                    '| box |',
                    '*=====*'))

Template(121, 123, ('| box |',))

Template(122, 223, ('| box |',
                    '`-----\''))

Template(123, 323, ('.-----.',
                    '| box |',
                    '`-----\''))

Template(124, 423, ('| box |',
                    '\\=====/'))

Template(125, 523, ('/=====\\',
                    '| box |',
                    '\\=====/'))

Template(141, 143, ('| box ',))

Template(142, 243, ('* box *',
                    '*******'))

Template(143, 343, ('*******',
                    '* box *',
                    '*******'))

Template(144, 443, ('X box X',
                    'XXXXXXX'))

Template(145, 543, ('XXXXXXX',
                    'X box X',
                    'XXXXXXX'))
# C language templates.

Template(211, 118, ('/* box */',))

Template(212, 218, ('/* box */',
                    '/* --- */'))

Template(213, 318, ('/* --- */',
                    '/* box */',
                    '/* --- */'))

Template(214, 418, ('/* box */',
                    '/* === */'))

Template(215, 518, ('/* === */',
                    '/* box */',
                    '/* === */'))

Template(221, 128, ('/* ',
                    '   box',
                    '*/'))

Template(222, 228, ('/*    .',
                    '| box |',
                    '`----*/'))

Template(223, 328, ('/*----.',
                    '| box |',
                    '`----*/'))

Template(224, 428, ('/*    \\',
                    '| box |',
                    '\\====*/'))

Template(225, 528, ('/*====\\',
                    '| box |',
                    '\\====*/'))

Template(231, 138, ('/*    ',
                    ' | box',
                    ' */   '))

Template(232, 238, ('/*        ',
                    ' | box | ',
                    ' *-----*/'))

Template(233, 338, ('/*-----* ',
                    ' | box | ',
                    ' *-----*/'))

Template(234, 438, ('/* box */',
                    '/*-----*/'))

Template(235, 538, ('/*-----*/',
                    '/* box */',
                    '/*-----*/'))

Template(241, 148, ('/*    ',
                    ' * box',
                    ' */   '))

Template(242, 248, ('/*     * ',
                    ' * box * ',
                    ' *******/'))

Template(243, 348, ('/******* ',
                    ' * box * ',
                    ' *******/'))

Template(244, 448, ('/* box */',
                    '/*******/'))

Template(245, 548, ('/*******/',
                    '/* box */',
                    '/*******/'))

Template(251, 158, ('/* ',
                    ' * box',
                    ' */   '))

.. @+node:ekr.20070215183046: *4* IronPython notes
- IronPython does not accept 'from __future__ import x'
  I could work around this, but perhaps it is time to abandon Python 2.2.2.

- Amazingly, it is possible to add Python24\Lib to IronPython's path!
  Almost all of those modules import correct.

- IronPython has troubles with the xml modules.
  It complains about a missing 'strict' codec.

- IronPython has trouble with the pdb module, so some other way must be found to debug IronPython programs.
.. @+node:ekr.20050214055018: *4* Mac Notes
.. @+node:ekr.20050221054932: *5* How to make monolithic Leo app on MacOS X
 @killcolor
http://sourceforge.net/forum/message.php?msg_id=3007062
By: jgleeson

Sorry to take so long to reply.  I've been buried in work and haven't kept up
with some email.

Here's the link to the site where I posted the folder you have:
<http://homepage.mac.com/jdgleeson/>  It's the small file named "Leo.zip" (23
KB), not the large file "Leo-4.3-alpha-2.dmg" (20 MB).

I agree that I did not write very clear instructions, beginnng with the first
step, where I should have also said:  "It is important to use version 1.1.8
of py2app, which is only available through svn.  The version on the py2app website
is 1.1.7, which creates buggy Tkinter apps. If you try to use version 1.1.7,
the Leo app it creates will give you a message saying that Tkinter is not properly
installed.  Your installation is fine; otherwise you could not have even built
Leo.app with py2app, because py2app copies the essential parts of Tcl/Tk into
the application bundle to make the app completely standalone."

I haven't tried intalling the Fink subversion -- I'm using DarwinPorts
<http://darwinports.opendarwin.org/>.  But there's a simpler alternative than
DarwinPorts. Metissian releases OS X packages of Subversion clients
<http://metissian.com/projects/macosx/subversion/>

AFAIK, the command "python setup.py bdist_mpkg --open" only applies to the py2app
1.1.8 distribution.  By the way, bdist_mpkg is distributed with py2app. It creates
a package around the setup.py script (more specialized than Platypus).  I don't
have any experience with bdist_mpkg yet.

'Copy the leo folder into this directory' is horrible. I'm glad you figured
it out -- I'm not sure I could have.

"python setup.py py2app -a" should be run in the folder with the readme file,
which also contains the setup.py file that the command refers to.  Most importantly,
the folder in which this command is run must contain the leo folder -- which
it does only if you are brilliant enough to decode my instructions.   ;) 

HTH

-John
.. @+node:ekr.20050214055018.4: *5* @url http://idisk.mac.com/genthaler-Public/Leo.zip (download)
.. @+node:ekr.20050214055018.5: *5* @url http://www.wordtech-software.com/leo.html  (Mac Bundle)
.. @+node:ekr.20050513164506: *5* Problems with run script command on Mac x11
@killcolor

Jon Schull <jschull@softlock.com>  
Date:  2003/12/30 Tue PM 05:50:51 EST 
To:  edreamleo@charter.net 
Subject:  Leo, Mac OS X 10.3, and VPython 

I've been evaluating leo or vpython programming on  Mac OS X 10.3, and 
have some observations and a suggestion.

Observations:
- Leo runs under X11 as well as under OS X.
- My X11 python configuration was created using the recipe at XXX (which enables vpython).
- The OS X configuration is vanilla MacPython from MacPython.org, along with AquaTclTk batteries included XXX.

In both environments I can run leo under python leo.py and under idle.
Under OS X we get font smoothing, but we can't run visual python programs (python crashes;  this is a known incompatibility with  MacPython.)

- Under X11 we can run visual python programs like this one
    #box.py
    from visual import *
    box()

And we can even run them under leo (under X11). HOWEVER, when the visual python program is terminated, leo vanishes (leo and the vp program apparently run in the same space)

Under x11, we can keep leo alive by putting the vp program in its own space:

    os.popen3('/sw/bin/python /Users/jis/box.py')

However,  this doesn't let us see the output of stderr and stdout.  
Those text streams are available...

    def do(cmd='ls'):
        from os import popen3
        pIn,pOut,pErr=0,1,2
        popenResults=popen3(cmd)
        print popenResults[pOut].read()
        print popenResults[pErr].read()

    import os
    do('/sw/bin/python /Users/jis/box.py')

...but only when the vpython program terminates.

Here's the good news:  if we execute our vp program with 
/sw/bin/idle.py rather than with python, we get to see the program 
output in real time (under idle, under X11).

    import os
    os.chdir('/sw/lib/python2.3/idlelib')
    os.popen3('/sw/bin/python idle.py -r /Users/jis/box.py')

#this runs as an executed script in leo, and produces a live idle 
with real time ongoing output.

Now, while idle is running, leo sits in suspended animation.  But when 
the vpython program terminates, we are left in idle, and when idle is 
terminated, leo becomes active again.

It would be even better if leo were not suspended (using os.spawn, 
perhaps) but the real point is that I would really really like leo's 
"Execute script" command to execute code this way and spare me having 
to  hard-write the path to box.py.  It ought to be possible to 
eliminate os.chdir as well.

------------------
Jon Schull, Ph.D.
Associate Professor
Information Technology
Rochester Institute of Technology
schull@digitalgoods.com 585-738-6696
.. @+node:ekr.20040104162835.8: *5* Linux/Mac notes: Dan Winkler
.. @+node:ekr.20040104162835.13: *6* Fink & aqua
Yes, fink does have pre-built Pythons, both 2.1 and 2.2.  (If you don't 
see them it probably means you don't have the right servers listed in 
your /sw/etc/apt/sources.list file.)  However, the versions of Python 
you'd get through fink are set up to run under X Windows, which I don't 
think is what you want.

I think what you want is MacPython which can run Tk programs like Leo 
under Aqua.  That's what I use these days.

I can tell from your question that you don't understand the following 
differences between the versions of Python available:

1) The version that comes with OS X is a text only one which doesn't 
have Tk.  Leo can't run under that.  Also, I hate Apple for including 
this instead of one that does have Tk and I hope they'll fix it some 
day.

2) You can get a version of Python from fink with has Tk but which runs 
under X Windows.  I don't think you want that.

3). You can also get MacPython which has Tk but it's a version of Tk 
that uses the Aqua windowing system, not X Windows.

So Tk can either be present or not and if it is present it can use 
either X Windows or Aqua.  You want it present and using Aqua, I think.


.. @+node:ekr.20040104162835.14: *6* Mac, Fink, etc.
> 1. The python that FC installs is MacPython.  I think that because the
> MacPython docs talk about Fink.

Nope.  The python installed by FC knows nothing about the Mac.  It 
thinks it's running on a Unix machine.  And it uses a version of Tk 
which thinks it's running on a Unix machine.  The window standard on 
Unix is called X (or X11 or XFree86, all the same thing).  So the main 
reason to run Leo this way would be to get an idea of how it works for 
Unix/Linux users.  But when programs run under X, they don't look like 
Mac programs.  They don't get all those glossy, translucent widgets 
that Aqua provides.  They really look like they would on a Unix/Linux 
machine.

Aqua is the native windowing system on Mac.  MacPython is set up to 
work with it.  Most Mac users will want Leo to work this way.  That's 
what I do.

>
>
> I have the TkTclAquBI (Batteries included) installer.  Is installing 
> this
> enough to get Leo to work with Aqua?  Do I have to de-install the
> present tk stuff that I installed with FC?

Yes, I think that's all I installed to get Tk to work under Aqua.  You 
don't have to deinstall the FC stuff.  All the FC stuff lives in its 
own world under /sw and runs under X.  It won't conflict with the Mac 
world.

.. @+node:ekr.20040104162835.15: *6* Double clicking on Linux
Double-clickable things (i.e. Macintosh applications) are usually 
actually folders with a name that ends in .app.  The file you found is 
probably executable only from the command line, not by double clicking 
it.  So I think if you run it from the command line it will work but 
will not know about Tk because Apple's version was built without Tk 
support.

You can also execute the .app programs from the command line by using 
the open command, so "open foo.app" will do the same thing as double 
clicking on foo in the finder (the .app extension is suppressed).  The 
idea behind this is that an application can look like just one opaque 
icon in the finder but actually have all its resources nicely organized 
in subfolders.
.. @+node:ekr.20060111112513.1: *4* New jyLeo notes
http://sourceforge.net/forum/message.php?msg_id=3516227
By: leouser

Some highlights:
* simpler startup:
jyleo leo.py
should be sufficient to start it up.
* new editor colorization
* the JythonShell is much more powerful and cooler
* new plugins
* Chapters support
* mod_script is in place.
* dyna-menu was converted.  I guess 'e' will have to judge the conversion.
* multi-language script support.
* drag and drop
* some powerful new editor commands.  Try keyword completing on the language
in effect.  Say if it is python:
se(Tab)
becomes
self

Some warnings:
1. Be careful about reading your regular leo files into jyleo and saving them.
Its quite conceivable that jyleo will write it out to an XML format that regular
leo can't handle.  Why?  Well jyleo is using an XML library to spit its XML
out while leo uses a home grown method.  The library can handle leo's XML, but
Ive seen regular leo not be able to handle jyleo's XML.  Its based around <tag/>
I believe.

2. If you move jyleo after executing it you will need to clear out your compiled
py files as the __file__ attribute is hard compiled into the resulting objects.
Not what we want.  We want it to be set at runtime.  Ive been waiting a long
time for jython to release again and hopefully fix this, but Im not holding
my breath anymore.

----------
Its hard to give this thing a number, I want to call it jyleo2, but jyleo is
sufficient.  Dependent upon bug reports the next release could be much sooner
than before, maybe even weeks.  I hope one thing, that the dreaded "I can't
get it to start" problems are gone.  I took the snapshot and expanded it in
Windows XP.  Went to the src directory and typed: jython leo.py
and it started.  That's what I wanted to see.  I didn't have to mess with the
CLASSPATH or anything.

things needed:
java 5
a jython2.2a1 or beyond.  jython2.2a1 is the most recent snapshot.

Beyond bug fixing, I will be planning to add more SwingMacs command as time
goes along.  But I think most major features are in place.  Of course the 3D
experiments in the future could change that... :D

A NOTE ON STARTUP TIMES: In my experience it takes awhile for jyleo to start.
It will take much longer the first time you execute it because the py files
are being compiled.  Ive haven't been able to figure out what eats the time,
it may just have a slow startup in the aggregate.  So don't think its not doing
anything, it probably is.
.. @+node:ekr.20031218072017.392: *4* Python Notes...
.. @+node:ekr.20031218072017.398: *5* How to call any Python method from the C API
In general, everything you can do in Python is accessible through the C API.

    lines = block.split('\n');

> That will be

    lines = PyObject_CallMethod(block, "split", "s", "\n");
.. @+node:ekr.20031218072017.399: *5* How to run Python programs easily on NT,2K,XP
.. @+node:ekr.20031218072017.400: *6* setting the PATHEXT env var
It is worth noting that NT, Win2K and XP all have an alternative which is
to add .PY to the PATHEXT environment variable. Then you can run any .PY
file directly just by typing the name of the script without the extension. 

e.g.
C:\>set PATHEXT=.COM;.EXE;.BAT;.CMD

C:\>set PATH=%PATH%;c:\python22\tools\Scripts

C:\>google
'google' is not recognized as an internal or external command,
operable program or batch file.

C:\>set PATHEXT=.COM;.EXE;.BAT;.CMD;.PY

C:\>google
Usage: C:\python22\tools\Scripts\google.py querystring

C:\>
.. @+node:ekr.20031218072017.401: *6* Yet another Python .bat wrapper
>> It has a header of just one line. All the ugly stuff is at the end.
>>
>> -------------------------------------------------------------------
>> goto ="python"
>>
>> # Python code goes here
>>
>> ''' hybrid python/batch footer:
>> @:="python"
>> @python.exe %0 %1 %2 %3 %4 %5 %6 %7 %8 %9
>> @if errorlevel 9009 echo Python may be downloaded from
>www.python.org/download
>> @rem '''
>> -------------------------------------------------------------------
>>
>>         Oren
>>
>

It's for running python scripts on windows, without having to type:

[<path to python>\]python[.exe] <scriptname> [<arguments>*]

and almost takes the place of the "shabang" line at the top of *nix
scripts.

.. @+node:ekr.20080110082845: *4* pyxides: code completion
Python code completion module

From: "Tal Einat" <talei...@gmail.com>
Date: Wed, 6 Jun 2007 20:57:18 +0300

I've been developing IDLE over the past 2 years or so. Even before
that, I helped a friend of mine, Noam Raphael, write IDLE's
auto-completion, which is included in recent versions of IDLE.

Noam wrote the original completion code from scratch, and AFAIK every
Python IDE which features code completion has done the same. Surely
there is -some- functionality which could be useful cross-IDE?
Retrieving possible completions from the namespace, for example. And
we should be learning from each-others' ideas and experiences.

So how about we design a generic Python completion module, that
each IDE could extend, and use for the completion logic?



From: "Ali Afshar" <aafs...@gmail.com>
Date: Wed, 6 Jun 2007 19:06:01 +0100

I am very keen for this. I will help where it is required. PIDA
currently has no code completion (outside what vim/emacs provide),



From: "phil jones" <inters...@gmail.com>
Date: Wed, 6 Jun 2007 11:07:33 -0700

What functions would we ask for a code completion module?

Presumably recognition of the beginnings of
- a) python keywords
- b) classes and functions defined earlier in this file?
- c) in scope variables?

As python is dynamically typed, I guess we can't expect to know the
names of methods of objects?



From: "Ali Afshar" <aafs...@gmail.com>
Date: Wed, 6 Jun 2007 19:13:10 +0100

> Presumably recognition of the beginnings of
> - a) python keywords
> - b) classes and functions defined earlier in this file?
> - c) in scope variables?

does c) include: d) imported modules



From: Nicolas Chauvat <nicolas.chau...@logilab.fr>
Date: Wed, 6 Jun 2007 20:17:30 +0200

> >Presumably recognition of the beginnings of
> >- a) python keywords
> >- b) classes and functions defined earlier in this file?
> >- c) in scope variables?

> does c) include: d) imported modules

For code-completion, I suppose astng[1] could be useful.

1: http://www.logilab.org/project/eid/856


From: Stani's Python Editor <spe.stani...@gmail.com>
Date: Wed, 06 Jun 2007 20:48:41 +0200

A good point. I think we all have been thinking about this. Important
issues for the design is the extraction method and the sources.

*the method*
Importing is a lazy, but accurate way of importing, but is security wise
not such a good idea. Parsing throught an AST compiler is better,
however more difficult. Here are two options.

From version 2.5 the standard Python compiler converts internally the
source code to an abstract syntax tree (AST) before producing the
bytecode. So probably that is a good way to go as every python
distribution has this battery included.

As Nicolas suggested earlier on this mailing list, there is another
option: the AST compiler in python or PyPy:

On Mar 14 2006, 12:16 am, Nicolas Chauvat <nicolas.chau...@logilab.fr>
wrote:

> > WingIDE use anASTgenerator written in C (but cross-platform),
> > lightningly quick, and open sourced. This could be a potential
> > starting point.

> > Additionally isn't Python2.5 planned to have a C-written compiler?

> PyPy also produced an improved parser/compiler.

> http://codespeak.net/pypy/dist/pypy/doc/index.html
> http://codespeak.net/pypy/dist/pypy/module/recparser/

But if it could be done with the standard one it is one dependency less.

*the sources*
In the design we could define first the sources:
1 external imported modules from the pythonpath
2 local modules relative to the current file or context dependent
(Blender, Gimp, ...)
3 inner code

For 1:
It might be a good idea to have a function which scans all the modules
from the pythonpath or one specific module to cache all autocompletion
and calltip information of all classes, methods and doc strings. Why?
Modules in the pythonpath don't change so often. With some criteria
(file name, time stamp, size, ...) you could check if updates are
necessary at startup. Having a readymade 'database' (could be python
dictionary or sqlite database) for autocompletion/call tips would speed
up things (and is also more secure if you are importing rather than
parsing. For example trying to provide gtk autocompletion in a wxPython
by importing is problematic).

For 2:
Here you load the parser on demand. Autocompletion/calltip information
can be added to the database.

For 3:
A different kind of parser needs to be used here as per definition code
you edit contains errors while typing. External modules are retrieved
from 1 and 2, for internal code you can scan all the words and add them
to the autocomplete database. As a refinement you can give special
attention to 'self'. Also for calltips you can inherit when there are
assignments, eg
frame = Frame()
than frame inherits autocomplete & calltip information from Frame.

So autocompletion & calltips deals with two steps: extraction and
'database'. If someone has a good parser already, we could use it.
Otherwise we can define an API for the extraction and maybe lazily
implement it first with importing and concentrate first on the
'database'. When the database is ready we can implement the parsing. You
could also implement the parsing first, but than it takes longer before
you have results. Of course the library is GUI independent, it only
works with strings or lists.

What concerns SPE, it uses importing for autocompletion (1+2) and does
internal code analysis for local code (however without the inheriting).

Tal, how does IDLE's autocompletion works?

Stani



From: Stani's Python Editor <spe.stani...@gmail.com>
Date: Wed, 06 Jun 2007 20:53:10 +0200

Nicolas Chauvat wrote:
> On Wed, Jun 06, 2007 at 07:13:10PM +0100, Ali Afshar wrote:
>>> Presumably recognition of the beginnings of
>>> - a) python keywords
>>> - b) classes and functions defined earlier in this file?
>>> - c) in scope variables?
>> does c) include: d) imported modules

> For code-completion, I suppose astng[1] could be useful.

> 1: http://www.logilab.org/project/eid/856

How dependent/independent is this from the standard AST compiler or
PyPy? Is it more IDE friendly? Is it based on it or a total independent
implementation?



From: "Ali Afshar" <aafs...@gmail.com>
Date: Wed, 6 Jun 2007 19:59:13 +0100

> A good point. I think we all have been thinking about this. Important
> issues for the design is the extraction method and the sources.

> *the method*
> Importing is a lazy, but accurate way of importing, but is security wise
> not such a good idea. Parsing throught an AST compiler is better,
> however more difficult. Here are two options.

> From version 2.5 the standard Python compiler converts internally the
> source code to an abstract syntax tree (AST) before producing the
> bytecode. So probably that is a good way to go as every python
> distribution has this battery included.

> As Nicolas suggested earlier on this mailing list, there is another
> option: the AST compiler in python or PyPy:

What concerns me about these is whether they would work in a module
which has a syntax error.

I believe Wing's compiler bit of their code completion is open source.
I remember having seen the code.



From: Stani <spe.stani...@gmail.com>
Date: Wed, 06 Jun 2007 12:08:00 -0700

> What concerns me about these is whether they would work in a module
> which has a syntax error.

> I believe Wing's compiler bit of their code completion is open source.
> I remember having seen the code.

It is indeed, but is implemented in C, which means an extra dependency
and not a 100% python solution. Normally modules (especially in the
pythonpath) which you import don't have syntax errors. Maybe logilabs
implementation handles syntax errors well as it is developed for
PyLint. Nicolas?



From: "Tal Einat" <talei...@gmail.com>
Date: Wed, 6 Jun 2007 22:34:41 +0300

> As python is dynamically typed, I guess we can't expect to know the
> names of methods of objects?

Well, the dir() builtin does just that, though there can be attributes
which won't be included therein. However, the builtin dir() can be
overridden... and ignoring it can break libraries like RPyC which
define a custom dir() function just for this purpose.

This issue has already been run in to by RPyC (an Python RPC lib). The
main developr went ahead and suggested adding a __dir__ method which
will return a list of attributes, and IIRC he has already implemented
a patch for this, and it will likely enter Python2.6.

Until then, I guess we're going to have to rely on dir for this.



From: "Josiah Carlson" <josiah.carl...@gmail.com>
Date: Wed, 6 Jun 2007 12:42:01 -0700

For reference, PyPE auto-parses source code in the background, generating
(among other things) a function/class/method hierarchy.  Its autocomplete
generally sticks to global functions and keywords, but when doing
self.method lookups, it checks the current source code line, looks up in its
index of classes/methods, and trims the results based on known methods in
the current class in the current source file.

It certainly isn't complete (it should try to check base classes of the
class in the same file, it could certainly pay attention to names assigned
in the current scope, the global scope, imports, types of objects as per
WingIDE's assert isinstance(obj, type), etc.), but it also makes the
computation fairly straightforward, fast, and only in reference to the
current document.



From: "Tal Einat" <talei...@gmail.com>
Date: Wed, 6 Jun 2007 22:52:08 +0300

> Tal, how does IDLE's autocompletion works?

Much like Stani said, since Python is interpreted, collection of
possible completions splits into two methods:
1) source code analysis
2) dynamic introspection

Of course, we could do either or a combination of both.

IDLE just uses introspection: since IDLE always has a python shell
running, it just completes according to the shell's state (plus
built-in keywords and modules). This is a very simple method,
obviously lacking. It does allow the user some control of the
completion, though - just import whatever you want to be completable
in the shell. However, introspection is all that is needed in a Python
shell, which is the major reason this is the method used in IDLE.



From: Nicolas Chauvat <nicolas.chau...@logilab.fr>
Date: Wed, 6 Jun 2007 23:59:32 +0200


> How dependent/independent is this from the standard AST compiler or
> PyPy? Is it more IDE friendly? Is it based on it or a total independent
> implementation?

It is independent from PyPy.

The above web page says:

"""
Python Abstract Syntax Tree New Generation

The aim of this module is to provide a common base representation of
python source code for projects such as pychecker, pyreverse,
pylint... Well, actually the development of this library is essentialy
governed by pylint's needs.

It extends class defined in the compiler.ast [1] module with some
additional methods and attributes. Instance attributes are added by a
builder object, which can either generate extended ast (let's call
them astng ;) by visiting an existant ast tree or by inspecting living
object. Methods are added by monkey patching ast classes.Python
Abstract Syntax Tree New Generation

The aim of this module is to provide a common base representation of
python source code for projects such as pychecker, pyreverse,
pylint... Well, actually the development of this library is essentialy
governed by pylint's needs.

It extends class defined in the compiler.ast [1] module with some
additional methods and attributes. Instance attributes are added by a
builder object, which can either generate extended ast (let's call
them astng ;) by visiting an existant ast tree or by inspecting living
object. Methods are added by monkey patching ast classes.
"""

From: "Sylvain Thénault" <thena...@gmail.com>
Date: Wed, 13 Jun 2007 10:51:04 +0200

> Please let me involve Sylvain in the discussion. As the main author of
> pylint and astng, he will provide better answers.

well logilab-astng is basically a big monkey patching of the compiler
package from the stdlib, so you can't get an astng representation from a
module with syntax errors in. However inference and most others
navigation methods (which are basically the value added by astng) are
"syntax error resilient" : if a dependency module (direct or indirect)
contains a syntax error, you don't get any exception, though since some
information is missing you can miss some results you'ld get if the
faulting module were parseable.



From: "Tal Einat" <talei...@gmail.com>
Date: Tue, 31 Jul 2007 10:33:33 +0300

Since astng already does some inference (which we definitely want!)
and is based on the standard Python AST compiler, it sounds like our
#1 candidate. I think we should give the code a serious once-over and
see how well it fits our requirements, and if it can be adapted to
better handle errors. Any volunteers?

Also, has anyone used astng for completion, calltips, or something
similar? Or the standard AST compiler, for that matter?



From: "Tal Einat" <talei...@gmail.com>
Date: Tue, 31 Jul 2007 10:40:11 +0300

How does PyPE parse code? Home-rolled, standard AST compiler, something else?

It seems to me we should try to come up with an algorithm for parsing,
before getting to the code. All of the details you mentioned -
noticing assignments, using base-class methods, etc. - could be better
defined and organized this way. Perhaps we could brainstorm on this in
a wiki?



From: "Tal Einat" <talei...@gmail.com>
Date: Tue, 31 Jul 2007 11:38:40 +0300

Sorry for being away for such a long time. I hope we can get this
conversation rolling again, and get started with the actual work.

I'll try to sum up what has been said so far, and how I see things.

== Top Priorities ==
* Can we implement a parser based on the standard Python AST compiler
(or astng)? For example, can syntax errors be handled well?
* Is importing reasonable security-wise? If not, can it be made secure?

== General issues ==
* Do we aim for just completion, or also calltips? Perhaps also other
meta-data, e.g. place defined, source code, ... (see IPython's '??')
* Dependencies - do we want to allow C-extensions, or are we going for
a Python-only solution? (IDLE would only use such a Python-only tool.)
It seems that we want to pre-process most of the data in the
background, so I don't see why we would want to do this in C for
efficiency reasons.

== Completion sources ==
1) Importing "external" modules
2) Importing/Parsing "local" modules
3) Parsing the current file
4) Using objects/modules from the shell (e.g. IDLE has both editor
windows and a Python shell)

== Importing ==
* Stani mentioned that importing is problematic from a security point
of view. What are the security issues? Are they really an issue for an
IDE? If so, perhaps we could overcome this by importing in some kind
of "sandbox"?
* What are the pros and cons of Importing vs. Parsing?
* If importing is always preferable to parsing unless there's a syntax
error, perhaps try to import and parse on failure?

== Parsing ==
* This is going to be the most complex method - I think we should have
a general idea of how this should work before starting an
implementation. I suggest hashing ideas out on a wiki, since there a
lot of details to consider.
* Can a parser based on the standard AST compiler (or astng) work? Is
there a way to deal with errors? (HIGH PRIORITY!)
* There are other existing, open-source implementations out there -
WingIDE, PyPE have been mentioned. Any others? We should collect these
so we can use the code for learning, and perhaps direct use (if
possible license-wise).

== Shell ==
This is relatively straight-forward - just use dir(). This should be
optional, for use by IDEs which have a shell (support multiple
shells?).

Some known issues from IDLE and PyCrust:
* Handle object proxies such as RPC proxies (e.g. RPyC)
* Handle ZODB "ghost" objects
* Watch out for circular references
* Watch out for objects with special __getattr__/__hasattr__
implementations (for example xmlrpc, soap)

== Persistence ==
* Stani mentioned a 'database'. I feel Sqlite should be at most
optional, to reduce dependencies.
* Do we really want to have the data persistent (between IDE
sessiosns)? If so, we need to support simultaneous instances of the
IDE so they don't corrupt the data. Any other issues? (I have a
feeling this would better be left for later stages of development.)



From: "Tal Einat" <talei...@gmail.com>
Date: Tue, 31 Jul 2007 12:22:59 +0300

One more note: We should distinguish between completion in an editor
and completion in a shell. The conversation up until now has focused
on editors, which is reasonable since that is the problematic scene. I
think a generic Python completion library should support completion in
both contexts, especially if it uses can use a shell's namespace for
completion in the editor.



From: "Ali Afshar" <aafs...@gmail.com>
Date: Tue, 31 Jul 2007 11:20:19 +0100

I have just implemented a completion mockup using Rope (which is a
refactoring library). It works quite nicely, and definitely worth a
look.

http://rope.sourceforge.net/

It even achieves this kind of completion:

class Banana(object):
    def do_something(self):
         return

def foo():
    return [Banana(), Banana()]

foo()[0].<complete> includes do_something

Which seems pretty impressive to me.



From: "Tal Einat" <talei...@gmail.com>
Date: Tue, 31 Jul 2007 20:12:50 +0300

Wow, Rope does look very impressive! A quick look at the code tells me
that a lot of work has been invested in it.

So we have one existing Python-only solution. We should evaluate it -
see what it can and can't do, and perhaps take a look at the overall
design.

I'm CC-ing Rope's developer, Ali. Hopefully Ali can help us quickly
understand Rope's code analysis capabilities.

Ali, could you elaborate a bit on what kinds of completion Rope can
do, and the methods it uses? We would especially like to know how your
static and dynamic inference work, what they can accomplish, and what
their limitations are.



From: "Ali Afshar" <aafs...@gmail.com>
Date: Tue, 31 Jul 2007 19:45:15 +0100

> Ali, could you elaborate a bit on what kinds of completion Rope can
> do, and the methods it uses? We would especially like to know how your
> static and dynamic inference work, what they can accomplish, and what
> their limitations are.

Well, I haven't really looked at the code. But I can tell you this:

from rope.ide.codeassist import PythonCodeAssist
from rope.base.project import Project
for compl in PythonCodeAssist(Project(package_root)).assist(buffer,
offset).completions:
    print compl

And that is as far as I really got. I expect to get a better look at
it later in the week though...


From: "Josiah Carlson" <josiah.carl...@gmail.com>
Date: Wed, 1 Aug 2007 00:26:14 -0700

> How does PyPE parse code? Home-rolled, standard AST compiler, something else?

The compiler for syntactically correct Python, a line-based compiler
for broken Python.  TO generate a method list for self.methods, using
the current line number, I discover the enclosing class, check the
listing of methods for that class (generated by the compiler or
line-based parsers), and return a valid list for the specified prefix.
 It doesn't walk the inheritance tree, it doesn't do imports, etc.

> It seems to me we should try to come up with an algorithm for parsing,
> before getting to the code. All of the details you mentioned -
> noticing assignments, using base-class methods, etc. - could be better
> defined and organized this way. Perhaps we could brainstorm on this in
> a wiki?

A wiki would be fine, the one for this mailing list would likely be
best (if it is still up and working).  Then again, Rope looks quite
nifty.  I may have to borrow some of that source ;)


Discussion subject changed to "Fwd: Python code completion module" by Tal Einat

From: Ali Gholami Rudi <aligr...@gmail.com>
Date: Aug 1, 2007 5:50 PM

First of all I should note that rope's main goal was being a
refactoring tool and a refactoring tool needs to know a lot about
python modules.  `rope.base` package provides information about python
modules.

Actually what ropeide provides as auto-completion is defined in
`rope.ide.codeassist` module.  This module almost does nothing but use
`rope.base`.  Since `rope.ide` package is not included in the rope
library (which has been separated from ropeide since 0.6m4) it lacks
good documentation and the API might not be easy to use (most of it is
written in the first months of rope's birth).

> ..., could you elaborate a bit on what kinds of completion Rope can
> do, ...

I don't know what to say here.  Well, actually it tries to use the
source code as much as possible and infer things from it.  So I can
say that it can complete any obvious thing that can be inferred by a
human.  Like this is the first parameter of a method and after dots
its attributes can appear or these modules are imported so their names
and contents are available or this is an instance of some known type
and we know its attributes and ... .  Try ropeide (it uses emacs-like
keybinding, C-/ for completion; see ~/.rope if you want to change
that); it completes common cases (and sometimes completes things you
don't expect it to!).

> ..., and the methods it uses?

Rope analyzes python source code and AST.  Rope used to use the
`compiler` module till 0.5 and now it uses `_ast` module.

> We would especially like to know how your
> static and dynamic inference work, what they can accomplish

There are a few examples in docs/overview.txt.  Unit-test modules like
`ropetest.base.objectinfertest` and `advanced_oi_test` might help,
too.  Also have a look at `rope.base.oi.__init__` pydoc for an
overview of how they work; (I'm afraid it is a bit out of date and
carelessly written.)  The idea behind rope's object inference is to
guess what references (names in source-code) hold.  They collect
information about code when they can and use them later.

>..., and what their limitations are.

Many things in rope are approximations that might be exact if some
conditions hold.  For instance rope might assume that every normal
reference in module scope holds only one kind of object.  Apart from
these assumptions both SOI and DOI have their own disadvantages; For
instance SOI fails when dynamic code is evaluated while DOI does not.
Or DOI is slower than SOI.  (Well, after recent enhancements to rope's
SOI I rarely use DOI).

I tried to answer as short as possible.  If there are questions on
specific parts of rope, I'll be happy to answer.

By the way, I tried to reply this mail to the group, but it seems that
your group requires subscription for posting, so I've sent it to you,
instead.
.. @+node:ekr.20070308062440: *4* Thread notes
.. @+node:ekr.20070308062440.1: *5* Posting 2
On 2/26/07, Edward Ream <edreamleo@charter.net> wrote:

> threads will swap after sys.getcheckinterval() bytecodes have been
> processed for that thread.

Many thanks for this detailed summary.  I think this is the guarantee I need
a) to experiment with threads and b) to fiddle with settings should that 
appear to be necessary.

Just be careful.  Test your assumptions before you rely on them, especially regarding threads.  Generally threading is seen as a "hard" problem.  If you want to help make them easier, use Queues to handle inter-thread communication. 


> you can use a technique known as 'cooperative multithreading with 
> generators'.

Googling this leads directly to an entry in the Python Cookbook.  The site
is down at present.  I'll study this entry when it's back up.

The basic idea is to have each task be a generator, with each generator giving up control after some amount of work.  Here's a variant of the recipe in the cookbook... 

 - Josiah

import collections

tasks = collections.deque()

def busy():
    while 1:
        yield None

def delay(v):
    import time
    while 1:
        time.sleep(v)
        yield None 

def xpasses(x):
    while x > 0:
        x -= 1
        yield None

def runtasks():
    while 1:
        task = tasks.popleft()
        try:
            task.next()
        except StopIteration: 
            pass
        else:
            tasks.append(task)
.. @+node:ekr.20050306070535: *4* Tk Notes
@killcolor
.. @+node:ekr.20050306070535.3: *5* How to detect changes in text
http://sourceforge.net/forum/message.php?msg_id=1864564
By: btheado

WAS:RE: Leo 3.10 comments
edream wrote:

>This is due to apparent glitches in the Tk event dispatching. The problem is
that pressing a control or alt or shift key _all by themselves_ will generate
keypress events that are passed on to Leo's key handlers

This should be easy to make simpler--just bind an empty script to <Alt-KeyPress>,
<Shift-KeyPress>, etc.  Tk chooses the most specific event it can find, so the
more general <KeyPress> handler will not fire.

On a broader note, when programming the text widget in Tcl/Tk, watching key
events is not the easiest way to detect changes in the text.  The only way the
text in a text widget can change is if either the delete or the insert subcommands
(methods) are called.  Any keypresses that end up changing text will have called
one of these subcommands.

So the simplest way to detect changes is to just intercept the calls to insert
and delete.  In Tcl/Tk intercepting these calls is pretty straightforward. 
I don't know if the same is true in Tkinter.

Also note the text widget in Tk8.4 (http://www.tcl.tk/man/tcl8.4/TkCmd/text.htm#M72)
has a built-in way of seeing if the text has changed

Brian Theado
.. @+node:ekr.20130807203905.16727: *3* Porting docutils (failed)
# This project has failed.
.. @+node:ekr.20130807203905.16728: *4* notes re 2to3 fixers
A fixes:
--fix=except
--fix=raise 
--fix=print
--fix=callable # no changes.
--fix=dict # changes suggested, but they don't look like they are needed.
--fix=exec # no changes.
--fix=execfile # no changes.
--fix=filter # one change, but this should be needed.
--fix=funcattrs # no changes.
--fix=has_key # changes suggested, but this code is weird.  Not sure it is wise to do this.
--fix=idioms # optional.  Not made yet.
--fix=input # no changes.
--fix=intern # no changes.
--fix=isinstance # no changes.
--fix=itertool_imports # no changes.
--fix=itertoos # no changes.
--fix=long # no changes.
--fix=map # one change suggested, suppressed by adding from future_builtins import map.
--fix=metaclass # no changes.
--fix=methodattrs # no changes.
--fix=ne # no changes.
--fix=numliterals # no changes.
--fix=paren # no changes.
--fix=raw_input # no changes.
--fix=reduce # no changes.
--fix=renames # two files changed automatically.
--fix=repr # no changes.
--fix=set_literal # no changes.
--fix=standard_error # no such fixer!
--fix=sys_exc # no changes.
--fix=throw # no changes.
--fix=tuple_params # no changes.
--fix=xrange ### Several changes.  Can be done automatically.
--fix=xreadlines # no changes.

B fixes:
--fix=basestring
    OK: docutils\nodes.py
    docutils\utils\math\math2html.py
--fix=buffer # no changes.
--fix=getcwdu # *** applied change by hand.
--fix=imports2 # no changes.
--fix=imports # see below
    These must be modified:
        docutils\writers\docutils_xml.py
        docutils\writers\odf_odt\__init__.py
--fix=next # Changes suggested.  Not sure what to do about them.
--fix=nonzero # changed nodes.py by hand.
--fix=types ### Two changes needed.
--fix=unicode # This removes U from U'string', and is probably not necessary (because the files compile correctly)
--fix=urrlib ### Several changes needed.
.. @+node:ekr.20130807203905.16729: *4* New 2to3 fixers
# The python-modernize package makes these unnecessary.
.. @+node:ekr.20130807203905.16730: *5* @@nosent C:\Python27\Lib\lib2to3\fixes\fix_unified_unicode.py
"""Fixer that changes u"..." into u("...") and ur("...") into u(r"...").

"""

@language python
@tabwidth -4

import re
from .. import fixer_base

_literal_re = re.compile(ur"[uU][rR]?[\'\"]")

class FixUnifiedUnicode(fixer_base.BaseFix):
    
    BM_compatible = True
    PATTERN = "STRING"

    def transform(self, node, results):
        if _literal_re.match(node.value):
            node.value = "u(%s)" % node.value[1:]
            node.changed()
.. @+node:ekr.20130807203905.16731: *5* @@nosent C:\Python27\Lib\lib2to3\fixes\fix_unified_imports.py
"""
Fix incompatible imports and module references so the work with Python 2 and 3.
"""

# Authors: Collin Winter, Nick Edds, Edward K. Ream.

@language python
@tabwidth -4

<< imports >>
<< define mapping >>

@others
.. @+node:ekr.20130807203905.16732: *6* << imports >>

# Local imports
from .. import fixer_base
from ..fixer_util import Name,Newline,Node,Leaf,String,attr_chain,find_binding

# EKR imports
from ..pgen2 import token

import pprint
pp = pprint.PrettyPrinter(indent=4)

import leo.core.leoGlobals as g
.. @+node:ekr.20130807203905.16733: *6* << define mapping >>
MAPPING = {
    'StringIO':  'io',
    'cStringIO': 'io',
    'cPickle': 'pickle',
    '__builtin__' : 'builtins',
    'copy_reg': 'copyreg',
    'Queue': 'queue',
    'SocketServer': 'socketserver',
    'ConfigParser': 'configparser',
    'repr': 'reprlib',
    'FileDialog': 'tkinter.filedialog',
    'tkFileDialog': 'tkinter.filedialog',
    'SimpleDialog': 'tkinter.simpledialog',
    'tkSimpleDialog': 'tkinter.simpledialog',
    'tkColorChooser': 'tkinter.colorchooser',
    'tkCommonDialog': 'tkinter.commondialog',
    'Dialog': 'tkinter.dialog',
    'Tkdnd': 'tkinter.dnd',
    'tkFont': 'tkinter.font',
    'tkMessageBox': 'tkinter.messagebox',
    'ScrolledText': 'tkinter.scrolledtext',
    'Tkconstants': 'tkinter.constants',
    'Tix': 'tkinter.tix',
    'ttk': 'tkinter.ttk',
    'Tkinter': 'tkinter',
    'markupbase': '_markupbase',
    '_winreg': 'winreg',
    'thread': '_thread',
    'dummy_thread': '_dummy_thread',
    # anydbm and whichdb are handled by fix_imports2
    'dbhash': 'dbm.bsd',
    'dumbdbm': 'dbm.dumb',
    'dbm': 'dbm.ndbm',
    'gdbm': 'dbm.gnu',
    'xmlrpclib': 'xmlrpc.client',
    'DocXMLRPCServer': 'xmlrpc.server',
    'SimpleXMLRPCServer': 'xmlrpc.server',
    'httplib': 'http.client',
    'htmlentitydefs' : 'html.entities',
    'HTMLParser' : 'html.parser',
    'Cookie': 'http.cookies',
    'cookielib': 'http.cookiejar',
    'BaseHTTPServer': 'http.server',
    'SimpleHTTPServer': 'http.server',
    'CGIHTTPServer': 'http.server',
    #'test.test_support': 'test.support',
    'commands': 'subprocess',
    'UserString' : 'collections',
    'UserList' : 'collections',
    'urlparse' : 'urllib.parse',
    'robotparser' : 'urllib.robotparser',
}
.. @+node:ekr.20130807203905.16734: *6* alternates
def alternates(members):
    return "(" + "|".join(map(repr, members)) + ")"

.. @+node:ekr.20130807203905.16735: *6* build_pattern
def build_pattern(mapping=MAPPING):
    mod_list = ' | '.join(["module_name='%s'" % key for key in mapping])
    bare_names = alternates(mapping.keys())
    yield """name_import=import_name< 'import' ((%s) |
               multiple_imports=dotted_as_names< any* (%s) any* >) >
          """ % (mod_list, mod_list)
    yield """import_from< 'from' (%s) 'import' ['(']
              ( any | import_as_name< any 'as' any > |
                import_as_names< any* >)  [')'] >
          """ % mod_list
    yield """import_name< 'import' (dotted_as_name< (%s) 'as' any > |
               multiple_imports=dotted_as_names<
                 any* dotted_as_name< (%s) 'as' any > any* >) >
          """ % (mod_list, mod_list)

    # Find usages of module members in code e.g. thread.foo(bar)
    yield "power< bare_with_attr=(%s) trailer<'.' any > any* >" % bare_names

.. @+node:ekr.20130807203905.16736: *6* class FixUnifiedImports
class FixUnifiedImports(fixer_base.BaseFix):

    BM_compatible = True
    keep_line_order = True
    # This is overridden in fix_imports2.
    mapping = MAPPING

    # We want to run this fixer late, so fix_import doesn't try to make stdlib
    # renames into relative imports.
    run_order = 6

    @others
.. @+node:ekr.20130807203905.16737: *7* build_pattern
def build_pattern(self):
    return "|".join(build_pattern(self.mapping))

.. @+node:ekr.20130807203905.16738: *7* compile_pattern
def compile_pattern(self):
    # We override this, so MAPPING can be pragmatically altered and the
    # changes will be reflected in PATTERN.
    self.PATTERN = self.build_pattern()
    super(FixUnifiedImports, self).compile_pattern()

.. @+node:ekr.20130807203905.16739: *7* dump
def dump(self,aDict):
    if not aDict: return '<None>'
    result = []
    for key in aDict:
        result.append('')
        val = aDict.get(key)
        result.append('%s: %s' % (key,pp.pformat(val)))
    return '\n'.join(result)

.. @+node:ekr.20130807203905.16740: *7* match
# Don't match the node if it's within another match.

def match(self, node):
    match = super(FixUnifiedImports, self).match
    results = match(node)
    if results:
        # Module usage could be in the trailer of an attribute lookup, so we
        # might have nested matches when "bare_with_attr" is present.
        if (
            "bare_with_attr" not in results and 
            any(match(obj) for obj in attr_chain(node, "parent"))
        ):
            return False
        return results
    return False

.. @+node:ekr.20130807203905.16741: *7* start_tree
def start_tree(self, tree, filename):
    super(FixUnifiedImports, self).start_tree(tree, filename)
    self.replace = {}
    
.. @+node:ekr.20130807203905.16742: *7* transform (fix_unified_imports)
@
mod_list = ' | '.join(["module_name='%s'" % key for key in mapping])

bare_names = alternates(mapping.keys())
    
"""name_import=import_name<
    'import' ((%s) |
    multiple_imports=dotted_as_names< any* (%s) any* >)
>
""" % (mod_list, mod_list)
          
"""import_from<
    'from' (%s) 'import' ['('] ( any |
    import_as_name< any 'as' any > |
    import_as_names< any* >)  [')']
>
""" % mod_list

"""import_name<
    'import' (dotted_as_name< (%s) 'as' any > |
    multiple_imports=dotted_as_names< any* dotted_as_name< (%s) 'as' any > any* >)
>
""" % (mod_list, mod_list)
@c


def transform(self, node, results):
    trace = False
    if 0:
        # print('\ntransform: node:\n%s' % node)
        print('\ntransform: results: %s\n' % self.dump(results))
    # g.trace(sorted(results.keys()))
    import_mod = results.get("module_name")
    name_import = results.get('name_import')
    # print('transform',import_mod,sorted(results.keys()))
    if import_mod:
        mod_name = import_mod.value
        new_name = unicode(self.mapping[mod_name])
        if 0: #original
            import_mod.replace(Name(new_name, prefix=import_mod.prefix))
        else:
            prefix = node.prefix # was import_mod.prefix
            clone = node.clone()
            clone2 = node.clone()
            node2 = self.find_name(clone2,mod_name)
            node2.replace(Name(new_name,prefix=import_mod.prefix))
            indent = Name('    ',prefix=prefix) # A hack.
            node.replace([ # was node.replace.
                String('if sys.version_info < (3,):',prefix=prefix),
                Newline(),indent,
                clone,
                Newline(),
                Name('else:',prefix=prefix),
                Newline(),indent,
                clone2,
                Newline(),
            ])
            
        if 1: # old code.
            if "name_import" in results:
                # If it's not a "from x import x, y" or "import x as y" import,
                # marked its usage to be replaced.
                g.trace('******',mod_name,new_name)
                self.replace[mod_name] = new_name
            if "multiple_imports" in results:
                # This is a nasty hack to fix multiple imports on a line (e.g.,
                # "import StringIO, urlparse"). The problem is that I can't
                # figure out an easy way to make a pattern recognize the keys of
                # MAPPING randomly sprinkled in an import statement.
                results = self.match(node)
                if results:
                    self.transform(node, results)
    elif 1:
        # Replace usage of the module.
        bare_name = results["bare_with_attr"][0]
        new_name = self.replace.get(bare_name.value)
        old = results.get('node').clone()
        if trace: g.trace('==== old',old)
        if new_name:
            if trace: g.trace('===== replace',bare_name,bare_name.value,new_name)
            if 0:
                bare_name.replace(Name(new_name, prefix=bare_name.prefix))
            else:
                bare_name.replace([
                    old,
                    String(' if sys.version_info < (3,) else '),
                    Name(new_name),
                ])
.. @+node:ekr.20130807203905.16743: *7* find_name (EKR)
def find_name(self,root,name):
    '''Find a Name subnode of root defining name'''
    
    # print('find_name',name,root)
    for node in root.post_order():
        # print('find_name',node)
        if node.type == 1 and node.value == name:
            # print('find_name: found',node)
            return node
    return None
.. @+node:ekr.20130807203905.16744: *5* trace
transform: node:
    Node(import_from, [
        Leaf(1, u'from'),
        Leaf(1, u'StringIO'),
        Leaf(1, u'import'),
        Node(import_as_name, [
            Leaf(1, u'StringIO'),
            Leaf(1, u'as'),
            Leaf(1, u'BytesIO')
        ])
    ])

transform: results: {
    'module_name': Leaf(1, u'StringIO'),
    'node': Node(import_from, [
        Leaf(1, u'from'),
        Leaf(1, u'StringIO'),
        Leaf(1, u'import'),
        Node(import_as_name, [
            Leaf(1,u'StringIO'),
            Leaf(1, u'as'),
            Leaf(1, u'BytesIO')
        ])
    ])
}

transform: node:
    Node(import_name, [
        Leaf(1, u'import'),
        Leaf(1, u'__builtin__')
    ])

transform: results: {
    'module_name': Leaf(1, u'__builtin__'),
    'name_import': Node(import_name, [Leaf(1, u'import'), Leaf(1, u'__builtin__')]),
    'node': Node(import_name, [
        Leaf(1, u'import'),
        Leaf(1, u'__builtin__')
    ])
}

transform: node:
    Node(power, [
        Leaf(1, u'__builtin__'),
        Node(trailer, [
            Leaf(23, u'.'), Leaf(1, u'__import__')
        ]),
        Node(trailer, [
            Leaf(7, u'('), Node(arglist, [
                Leaf(1, u'name'),
                Leaf(12, u','),
                Leaf(1, u'globals'),
                Leaf(12, u','),
                Leaf(1, u'locals'), Leaf(12, u','),
                Leaf(1, u'fromlist')
            ]),
            Leaf(8, u')')
        ])
    ])

transform: results: {
    'bare_with_attr': [Leaf(1, u'__builtin__')],
    'node': Node(power, [
        Leaf(1, u'__builtin__'),
        Node(trailer, [
            Leaf(23, u'.'),
            Leaf(1, u'__import__')
        ]),
        Node(trailer, [
            Leaf(7, u'('),
            Node(arglist, [
                Leaf(1, u'name'),
                Leaf(12, u','),
                Leaf(1, u'globals'),
                Leaf(12, u','),
                Leaf(1, u'locals'),
                Leaf(12, u','),
                Leaf(1, u'fromlist')
            ]), 
            Leaf(8, u')')
        ])
    ])
}

RefactoringTool: Refactored docutils\_compat.py
--- docutils\_compat.py (original)
+++ docutils\_compat.py (refactored)
@@ -20,7 +20,7 @@
 if sys.version_info < (3,0):
     b = bytes = str
     u_prefix = 'u'
-    from StringIO import StringIO as BytesIO
+    from io import StringIO as BytesIO
 else:
     import builtins
     bytes = builtins.bytes
@@ -37,7 +37,7 @@
     BytesIO = __import__('io').BytesIO

 if sys.version_info < (2,5):
-    import __builtin__
+    import builtins

     def __import__(name, globals={}, locals={}, fromlist=[], level=-1):
         """Compatibility definition for Python 2.4.
@@ -45,4 +45,4 @@
         Silently ignore the `level` argument missing in Python < 2.5.
         """
         # we need the level arg because the default changed in Python 3.3
-        return __builtin__.__import__(name, globals, locals, fromlist)
+        return builtins.__import__(name, globals, locals, fromlist)

transform: node:
    Node(import_name, [
        Leaf(1, u'import'),
        Node(dotted_as_name, [
            Leaf(1, u'ConfigParser'),
            Leaf(1, u'as'),
            Leaf(1, u'CP')
        ])
    )]

transform: results: {
    'module_name': Leaf(1, u'ConfigParser'),
    'node': Node(import_name, [
        Leaf(1, u'import'),
        Node(dotted_as_name, [
            Leaf(1, u'ConfigParser'),
            Leaf(1, u'as'),
            Leaf(1, u'CP')
        ])
    ])
}

RefactoringTool: Refactored docutils\frontend.py
--- docutils\frontend.py        (original)
+++ docutils\frontend.py        (refactored)
@@ -35,7 +35,7 @@
 import warnings
 ### 2to3.
 if sys.version_info < (3,0):
-    import ConfigParser as CP
+    import configparser as CP
 else:
     import configparser as CP
 import codecs

transform: node:
    Node(import_from, [
        Leaf(1, u'from'),
        Leaf(1, u'StringIO'),
        Leaf(1, u'import'),
        Leaf(1, u'StringIO')
    ])

transform: results: {
    'module_name': Leaf(1, u'StringIO'),
    'node': Node(import_from, [
        Leaf(1, u'from'),
        Leaf(1, u'StringIO'),
        Leaf(1, u'import'),
        Leaf(1, u'StringIO')
    ])
}

RefactoringTool: Refactored docutils\writers\docutils_xml.py
--- docutils\writers\docutils_xml.py    (original)
+++ docutils\writers\docutils_xml.py    (refactored)
@@ -25,7 +25,7 @@
     xml.__path__.reverse() # If both are available, prefer stdlib over PyXML

 import xml.sax.saxutils
-from StringIO import StringIO
+from io import StringIO

 import docutils
 from docutils import frontend, writers, nodes

transform: node:
    Node(import_name, [
        Leaf(1, u'import'),
        Leaf(1, u'StringIO')
    ])

transform: results: {
    'module_name': Leaf(1, u'StringIO'),
    'name_import': Node(import_name, [
        Leaf(1, u'import'),
        Leaf(1, u'StringIO')
    ]),
    'node': Node(import_name, [
        Leaf(1, u'import'),
        Leaf(1, u'StringIO')
    ])
}

transform: node:
    Node(power, [
        Leaf(1, u'StringIO'),
        Node(trailer, [
            Leaf(23, u'.'),
            Leaf(1, u'StringIO')
        ]), 
        Node(trailer, [
            Leaf(7, u'('),
            Leaf(8, u')')
        ])
    ])

transform: results: {
    'bare_with_attr': [Leaf(1, u'StringIO')],
    'node': Node(power, [
        Leaf(1, u'StringIO'),
        Node(trailer, [
            Leaf(23, u'.'),
            Leaf(1, u'StringIO')
        ]),
        Node(trailer, [
            Leaf(7, u'('),
            Leaf(8, u')')
        ])
    ])
}

transform: node:
    Node(import_from, [
        Leaf(1, u'from'),
        Leaf(1, u'ConfigParser'),
        Leaf(1, u'import'),
        Leaf(1, u'ConfigParser')
    ])

transform: results: {
    'module_name': Leaf(1, u'ConfigParser'),
    'node': Node(import_from, [
        Leaf(1, u'from'),
        Leaf(1, u'ConfigParser'),
        Leaf(1, u'import'),
        Leaf(1, u'ConfigParser')
    ])
}

RefactoringTool: Refactored docutils\writers\odf_odt\__init__.py
--- docutils\writers\odf_odt\__init__.py        (original)
+++ docutils\writers\odf_odt\__init__.py        (refactored)
@@ -22,7 +22,7 @@
 from xml.dom import minidom
 import time
 import re
-import StringIO
+import io
 import copy
 import urllib2
 import docutils
@@ -306,7 +306,7 @@
     return tag

 def ToString(et):
-    outstream = StringIO.StringIO()
+    outstream = io.StringIO()
     if sys.version_info >= (3, 2):
         et.write(outstream, encoding="unicode")
     else:
@@ -795,7 +795,7 @@
         self.language = languages.get_language(lcode, document.reporter)
         self.format_map = { }
         if self.settings.odf_config_file:
-            from ConfigParser import ConfigParser
+            from configparser import ConfigParser

             parser = ConfigParser()
             parser.read(self.settings.odf_config_file)
.. @+node:ekr.20130807203905.16745: *4* Scripts
.. @+node:ekr.20130807203905.16746: *5* Script: write constants to log pane
# -*- coding: utf8 -*-

# Define the constants for the define_xxx functions in the new punctuations_chars.py.
import unicodedata
s =  ur"\.\,\;\!\?"
assert not g.isPython3
d = {}
for uc in s:
    assert isinstance(uc,(str,unicode)),type(uc)
    comment = unicodedata.name(uc,'Unknown') if isinstance(uc,unicode) else 'ascii'
    d[ord(uc)] = comment
for i in sorted(d.keys()):
    g.es('%5s, # %s' % (i,d.get(i)))
.. @+node:ekr.20130807203905.16747: *5* Script: check syntax of all docutils files
# The following files fail on Python 3 because of Python 2.x syntax for unicode characters:
# (now passes) utils/punctuation_chars.py, 
# utils/math/latex2mathml.py,
# writers/manpage.py,
# writers/latex2e/__init__.py

g.cls()
import os
path = g.os_path_finalize_join(g.app.loadDir,'..','extensions','docutils')
if g.isPython3:
    exclude = ('punctuation2.py',)
else:
    exclude = ('punctuation3.py',)
for root, dirs, files in os.walk(path):
    for fn in files:
        if fn.endswith('.py'):
            fn = g.os_path_join(root,fn)
            if not g.shortFileName(fn) in exclude:
                s,e = g.readFileIntoString(fn)
                c.testManager.checkFileSyntax(fn,s,reraise=False,suppress=False)
print('all files in leo/extensions/docutils pass')
.. @+node:ekr.20130807203905.16748: *5* Script: restore newlines
# From Python/tools/scripts/crlf.py
"Replace CRLF with LF in docutils files."

g.cls()
write = True
import os
def fix(filename):
    if os.path.isdir(filename):
        # print filename, "Directory!"
        return
    data = open(filename,"rb").read()
    if '\0' in data:
        print('binary: %s' % filename)
        return
    newdata = data.replace("\r\n","\n")
    if newdata != data:
        print('changed: %s' % g.shortFileName(filename,2))
        if write:
            f = open(filename,"wb")
            f.write(newdata)
            f.close()

path = g.os_path_finalize_join(g.app.loadDir,'..','extensions','docutils')
for root, dirs, files in os.walk(path):
    for fn in files:
        if fn.endswith('.py'):
            fn = g.os_path_join(root,fn)
            fix(fn)
print('done')
.. @+node:ekr.20130807203905.16749: *5* Script: create ords arrays
# -*- coding: utf8 -*-
import sys
import unicodedata

@others

openers_original = ur"""\"\'\(\<\[\{༺༼᚛⁅⁽₍〈❨❪❬❮❰❲❴⟅⟦⟨⟪⟬⟮⦃⦅⦇⦉⦋⦍⦏⦑⦓⦕⦗⧘⧚⧼⸢⸤⸦⸨〈《「『【〔〖〘〚〝〝﴾︗︵︷︹︻︽︿﹁﹃﹇﹙﹛﹝（［｛｟｢«‘“‹⸂⸄⸉⸌⸜⸠‚„»’”›⸃⸅⸊⸍⸝⸡‛‟"""
openers_ords = [ord(ch) for ch in openers_original if unicodedata.name(ch,'Unknown') != 'Unknown']
openers = ''.join([unichr(n) for n in openers_ords])
assert openers_original == openers

closers_original = ur"""\"\'\)\>\]\}༻༽᚜⁆⁾₎〉❩❫❭❯❱❳❵⟆⟧⟩⟫⟭⟯⦄⦆⦈⦊⦌⦎⦐⦒⦔⦖⦘⧙⧛⧽⸣⸥⸧⸩〉》」』】〕〗〙〛〞〟﴿︘︶︸︺︼︾﹀﹂﹄﹈﹚﹜﹞）］｝｠｣»’”›⸃⸅⸊⸍⸝⸡‛‟«‘“‹⸂⸄⸉⸌⸜⸠‚„"""
closers_ords = [ord(ch) for ch in closers_original if unicodedata.name(ch,'Unknown') != 'Unknown']
closers = ''.join([unichr(n) for n in closers_ords])
assert closers_original == closers

delimiters_original = u"\\-\\/\\:֊־᐀᠆‐‑‒–—―⸗⸚〜〰゠︱︲﹘﹣－¡·¿;·՚՛՜՝՞՟։׀׃׆׳״؉؊،؍؛؞؟٪٫٬٭۔܀܁܂܃܄܅܆܇܈܉܊܋܌܍߷߸߹࠰࠱࠲࠳࠴࠵࠶࠷࠸࠹࠺࠻࠼࠽࠾।॥॰෴๏๚๛༄༅༆༇༈༉༊་༌།༎༏༐༑༒྅࿐࿑࿒࿓࿔၊။၌၍၎၏჻፡።፣፤፥፦፧፨᙭᙮᛫᛬᛭᜵᜶។៕៖៘៙៚᠀᠁᠂᠃᠄᠅᠇᠈᠉᠊᥄᥅᧞᧟᨞᨟᪠᪡᪢᪣᪤᪥᪦᪨᪩᪪᪫᪬᪭᭚᭛᭜᭝᭞᭟᭠᰻᰼᰽᰾᰿᱾᱿᳓‖‗†‡•‣․‥…‧‰‱′″‴‵‶‷‸※‼‽‾⁁⁂⁃⁇⁈⁉⁊⁋⁌⁍⁎⁏⁐⁑⁓⁕⁖⁗⁘⁙⁚⁛⁜⁝⁞⳹⳺⳻⳼⳾⳿⸀⸁⸆⸇⸈⸋⸎⸏⸐⸑⸒⸓⸔⸕⸖⸘⸙⸛⸞⸟⸪⸫⸬⸭⸮⸰⸱、。〃〽・꓾꓿꘍꘎꘏꙳꙾꛲꛳꛴꛵꛶꛷꡴꡵꡶꡷꣎꣏꣸꣹꣺꤮꤯꥟꧁꧂꧃꧄꧅꧆꧇꧈꧉꧊꧋꧌꧍꧞꧟꩜꩝꩞꩟꫞꫟꯫︐︑︒︓︔︕︖︙︰﹅﹆﹉﹊﹋﹌﹐﹑﹒﹔﹕﹖﹗﹟﹠﹡﹨﹪﹫！＂＃％＆＇＊，．／：；？＠＼｡､･"
delimiter_ords = [ord(ch) for ch in delimiters_original if unicodedata.name(ch,'Unknown') != 'Unknown']
delimiters = ''.join([unichr(n) for n in delimiter_ords])

quote_pairs_original = {
    u'\xbb':   u'\xbb',         # Swedish
    u'\u2018': u'\u201a',       # Greek
    u'\u2019': u'\u2019',       # Swedish
    u'\u201a': u'\u2018\u2019', # German, Polish
    u'\u201c': u'\u201e',       # German
    u'\u201e': u'\u201c\u201d',
    u'\u201d': u'\u201d',       # Swedish
    u'\u203a': u'\u203a',       # Swedish
}

# Compute the quote pairs array.
d = quote_pairs_original
d2 = {}
for ch in d.keys():
    val = d.get(ch)
    n = ord(ch)
    d2[n] = [ord(z) for z in val]
for n in sorted(d2.keys()):
    g.es('0x%x: [%s],' % (n,','.join(['0x%x' % (z) for z in d2.get(n)])))


# No need to compute 

assert compare(openers_original,openers)
assert compare(closers_original,closers)
assert compare(delimiters_original,delimiters)

if 0: # Create the ords array.
    for n in closers_ords:
        ch = unichr(n)
        g.es('%s, # %s' % (n,unicodedata.name(ch,'Unknown')))
    
print('done')
.. @+node:ekr.20130807203905.16750: *6* compare and helper
def unknown(ch):
    return unicodedata.name(ch,'Unknown') == 'Unknown'

def compare(s1,s2):
    i1,i2,n1,n2 = 0,0,len(s1),len(s2)
    while True:
        while i1 < n1 and unknown(s1[i1]):
            i1 += 1
        # while i2 < n2 and unknown(s2[i2]):
            # i2 += 1
        if i1 < n1 and i2 < n2 and s1[i1] == s2[i2]:
            i1 += 1 ; i2 += 1
        else:
            return i1 == n1 and i2 == n2
.. @+node:ekr.20130807203905.16751: *5* Script: test quote_pairs
quote_pairs_original = {
    u'\xbb':   u'\xbb', # Swedish
    u'\u2018': u'\u201a', # Greek
    u'\u2019': u'\u2019', # Swedish
    u'\u201a': u'\u2018\u2019', # German, Polish
    u'\u201c': u'\u201e', # German
    u'\u201e': u'\u201c\u201d',
    u'\u201d': u'\u201d', # Swedish
    u'\u203a': u'\u203a', # Swedish
}
          
quote_pairs_ord_d = {
    0xbb:   [0xbb],
    0x2018: [0x201a],
    0x2019: [0x2019],
    0x201a: [0x2018,0x2019],
    0x201c: [0x201e],
    0x201d: [0x201d],
    0x201e: [0x201c,0x201d],
    0x203a: [0x203a],
}

quote_pairs = {}
d = quote_pairs_ord_d
for n in d.keys():
    ch = unichr(n)
    quote_pairs [ch] = ''.join([unichr(n2) for n2 in d.get(n)])
d = quote_pairs
for ch in sorted(d.keys()):
    g.es('0x%x: %s' % (ord(ch),['0x%s' % (ord(z)) for z in d.get(ch)]))
    
assert quote_pairs == quote_pairs_original
g.es('pass!')
.. @+node:ekr.20130807203905.16752: *4* Tests
.. @+node:ekr.20130807203905.16753: *5* @@test special chars script & helpers
# -*- coding: utf8 -*-

from __future__ import print_function

g.cls()

import re
import sys
import unicodedata

openers = ur"""\"\'\(\<\[\{༺༼᚛⁅⁽₍〈❨❪❬❮❰❲❴⟅⟦⟨⟪⟬⟮⦃⦅⦇⦉⦋⦍⦏⦑⦓⦕⦗⧘⧚⧼⸢⸤⸦⸨〈《「『【〔〖〘〚〝〝﴾︗︵︷︹︻︽︿﹁﹃﹇﹙﹛﹝（［｛｟｢«‘“‹⸂⸄⸉⸌⸜⸠‚„»’”›⸃⸅⸊⸍⸝⸡‛‟"""
closers = ur"""\"\'\)\>\]\}༻༽᚜⁆⁾₎〉❩❫❭❯❱❳❵⟆⟧⟩⟫⟭⟯⦄⦆⦈⦊⦌⦎⦐⦒⦔⦖⦘⧙⧛⧽⸣⸥⸧⸩〉》」』】〕〗〙〛〞〟﴿︘︶︸︺︼︾﹀﹂﹄﹈﹚﹜﹞）］｝｠｣»’”›⸃⸅⸊⸍⸝⸡‛‟«‘“‹⸂⸄⸉⸌⸜⸠‚„"""
delimiters = ur"\-\/\:֊־᐀᠆‐‑‒–—―⸗⸚〜〰゠︱︲﹘﹣－¡·¿;·՚՛՜՝՞՟։׀׃׆׳״؉؊،؍؛؞؟٪٫٬٭۔܀܁܂܃܄܅܆܇܈܉܊܋܌܍߷߸߹࠰࠱࠲࠳࠴࠵࠶࠷࠸࠹࠺࠻࠼࠽࠾।॥॰෴๏๚๛༄༅༆༇༈༉༊་༌།༎༏༐༑༒྅࿐࿑࿒࿓࿔၊။၌၍၎၏჻፡።፣፤፥፦፧፨᙭᙮᛫᛬᛭᜵᜶។៕៖៘៙៚᠀᠁᠂᠃᠄᠅᠇᠈᠉᠊᥄᥅᧞᧟᨞᨟᪠᪡᪢᪣᪤᪥᪦᪨᪩᪪᪫᪬᪭᭚᭛᭜᭝᭞᭟᭠᰻᰼᰽᰾᰿᱾᱿᳓‖‗†‡•‣․‥…‧‰‱′″‴‵‶‷‸※‼‽‾⁁⁂⁃⁇⁈⁉⁊⁋⁌⁍⁎⁏⁐⁑⁓⁕⁖⁗⁘⁙⁚⁛⁜⁝⁞⳹⳺⳻⳼⳾⳿⸀⸁⸆⸇⸈⸋⸎⸏⸐⸑⸒⸓⸔⸕⸖⸘⸙⸛⸞⸟⸪⸫⸬⸭⸮⸰⸱、。〃〽・꓾꓿꘍꘎꘏꙳꙾꛲꛳꛴꛵꛶꛷꡴꡵꡶꡷꣎꣏꣸꣹꣺꤮꤯꥟꧁꧂꧃꧄꧅꧆꧇꧈꧉꧊꧋꧌꧍꧞꧟꩜꩝꩞꩟꫞꫟꯫︐︑︒︓︔︕︖︙︰﹅﹆﹉﹊﹋﹌﹐﹑﹒﹔﹕﹖﹗﹟﹠﹡﹨﹪﹫！＂＃％＆＇＊，．／：；？＠＼｡､･𐄀𐄁𐎟𐏐𐡗𐤟𐤿𐩐𐩑𐩒𐩓𐩔𐩕𐩖𐩗𐩘𐩿𐬹𐬺𐬻𐬼𐬽𐬾𐬿𑂻𑂼𑂾𑂿𑃀𑃁𒑰𒑱𒑲𒑳"
closing_delimiters = ur"\.\,\;\!\?"

unicode_punctuation_categories = {
    # 'Pc': 'Connector', # not used in Docutils inline markup recognition
    'Pd': 'Dash',
    'Ps': 'Open',
    'Pe': 'Close',
    'Pi': 'Initial quote', # may behave like Ps or Pe depending on usage
    'Pf': 'Final quote', # may behave like Ps or Pe depending on usage
    'Po': 'Other'
    }
"""Unicode character categories for punctuation"""

@others

test()
.. @+node:ekr.20130807203905.16754: *6* punctuation_samples
def punctuation_samples():

    """Docutils punctuation category sample strings.

    Return list of sample strings for the categories "Open", "Close",
    "Delimiters" and "Closing-Delimiters" used in the `inline markup
    recognition rules`_.
    """

    # Lists with characters in Unicode punctuation character categories
    cp_min = 160 # ASCII chars have special rules for backwards compatibility
    ucharlists = unicode_charlists(unicode_punctuation_categories, cp_min)

    # match opening/closing characters
    # --------------------------------
    # Rearange the lists to ensure matching characters at the same
    # index position.

    # low quotation marks are also used as closers (e.g. in Greek)
    # move them to category Pi:
    ucharlists['Ps'].remove(u'‚') # 201A  SINGLE LOW-9 QUOTATION MARK
    ucharlists['Ps'].remove(u'„') # 201E  DOUBLE LOW-9 QUOTATION MARK
    ucharlists['Pi'] += [u'‚', u'„']

    ucharlists['Pi'].remove(u'‛') # 201B  SINGLE HIGH-REVERSED-9 QUOTATION MARK
    ucharlists['Pi'].remove(u'‟') # 201F  DOUBLE HIGH-REVERSED-9 QUOTATION MARK
    ucharlists['Pf'] += [u'‛', u'‟']

    # 301F  LOW DOUBLE PRIME QUOTATION MARK misses the opening pendant:
    ucharlists['Ps'].insert(ucharlists['Pe'].index(u'\u301f'), u'\u301d')

    # print u''.join(ucharlists['Ps']).encode('utf8')
    # print u''.join(ucharlists['Pe']).encode('utf8')
    # print u''.join(ucharlists['Pi']).encode('utf8')
    # print u''.join(ucharlists['Pf']).encode('utf8')

    # The Docutils character categories
    # ---------------------------------
    #
    # The categorization of ASCII chars is non-standard to reduce both
    # false positives and need for escaping. (see `inline markup recognition
    # rules`_)

    # matching, allowed before markup
    openers = [re.escape('"\'(<[{')]
    for cat in ('Ps', 'Pi', 'Pf'):
        openers.extend(ucharlists[cat])

    # matching, allowed after markup
    closers = [re.escape('"\')>]}')]
    for cat in ('Pe', 'Pf', 'Pi'):
        closers.extend(ucharlists[cat])

    # non-matching, allowed on both sides
    delimiters = [re.escape('-/:')]
    for cat in ('Pd', 'Po'):
        delimiters.extend(ucharlists[cat])

    # non-matching, after markup
    closing_delimiters = [re.escape('.,;!?')]

    # # Test open/close matching:
    # for i in range(min(len(openers),len(closers))):
    #     print '%4d    %s    %s' % (i, openers[i].encode('utf8'),
    #                                closers[i].encode('utf8'))
    # dump(delimiters)
    
    return [u''.join(chars)
            for chars in (openers, closers, delimiters, closing_delimiters)]
.. @+node:ekr.20130807203905.16755: *6* unicode_charlists
def unicode_charlists(categories, cp_min=0, cp_max=None):
    """Return dictionary of Unicode character lists.

    For each of the `catagories`, an item contains a list with all Unicode
    characters with `cp_min` <= code-point <= `cp_max` that belong to the
    category. (The default values check every code-point supported by Python.)
    """
    # Determine highest code point with one of the given categories
    # (may shorten the search time considerably if there are many
    # categories with not too high characters):
    if cp_max is None:
        cp_max = max(x for x in xrange(sys.maxunicode + 1)
                     if unicodedata.category(unichr(x)) in categories)
        # print cp_max # => 74867 for unicode_punctuation_categories
    charlists = {}
    for cat in categories:
        charlists[cat] = [unichr(x) for x in xrange(cp_min, cp_max+1)
                          if unicodedata.category(unichr(x)) == cat]
    return charlists
.. @+node:ekr.20130807203905.16756: *6* compare
def compare(s1,s2):
    
    print(len(s1),len(s2))
    d1,d2 = {},{}
    for uc in s1:
        assert isinstance(uc,(str,unicode)),type(uc)
        n = ord(uc)
        d1[n] = uc
    for uc in s2:
        assert isinstance(uc,(str,unicode)),type(uc)
        n = ord(uc)
        d2[n] = uc
    nset = set()
    for n in d1.keys():
        nset.add(n)
    for n in d2.keys():
        nset.add(n)
    matches = 0
    for n in sorted(nset):
        uc1 = d1.get(n)
        uc2 = d2.get(n)
        if uc1 is None and uc2 is None:
            print('%5s hu??' % (n))
        elif uc1 is None:
            print('%5s' % (n),'missing1',uc2,unicodedata.name(uc2,'Unknown'))
        elif uc2 is None:
            pass # print('%5s' % (n),'missing2',uc1,unicodedata.name(uc1,'Unknown'))
        elif uc1 == uc2:
            # print('%5s' % (n),'match',uc1,unicodedata.name(uc1,'Unknown'))
            # print('%s, # %s' % (n,unicodedata.name(uc1,'Unknown').lower()))
            matches += 1
        else:
            print('%5s' % (n),uc1,unicodedata.name(uc1,'Unknown'),uc2,unicodedata.name(uc2,'Unknown'))
    print('matches: %s' % matches)
.. @+node:ekr.20130807203905.16757: *6* dump
def dump(s):
    for uc in s:
        assert isinstance(uc,(str,unicode)),type(uc)
        if isinstance(uc,unicode):
            print('%5s' % (ord(uc)),uc,unicodedata.name(uc,'Unknown'))
.. @+node:ekr.20130807203905.16758: *6* test
# The if __name__ == '__main__' part of puntuation_chars.py

def test():
    
    # (re) create and compare the samples:
    (o, c, d, cd) = punctuation_samples()
    if o != openers:
        print('- openers = ur"""%s"""' % openers.encode('utf8'))
        print('+ openers = ur"""%s"""' % o.encode('utf8'))
    if c != closers:
        print('- closers = ur"""%s"""' % closers.encode('utf8'))
        print('+ closers = ur"""%s"""' % c.encode('utf8'))
    if d != delimiters:
        print('- delimiters = ur"%s"' % delimiters.encode('utf8'))
        # dump(delimiters)
        print('+ delimiters = ur"%s"' % d.encode('utf8'))
        # dump(d)
        compare(delimiters,d)
    if cd != closing_delimiters:
        print('- closing_delimiters = ur"%s"' % closing_delimiters.encode('utf8'))
        print('+ closing_delimiters = ur"%s"' % cd.encode('utf8'))
.. @+node:ekr.20130807203905.16759: *5* consistency check (was in punctuation chars
import sys, re
import unicodedata

# Unicode punctuation character categories
# ----------------------------------------

unicode_punctuation_categories = {
    # 'Pc': 'Connector', # not used in Docutils inline markup recognition
    'Pd': 'Dash',
    'Ps': 'Open',
    'Pe': 'Close',
    'Pi': 'Initial quote', # may behave like Ps or Pe depending on usage
    'Pf': 'Final quote', # may behave like Ps or Pe depending on usage
    'Po': 'Other'
    }
"""Unicode character categories for punctuation"""


# generate character pattern strings
# ==================================

def unicode_charlists(categories, cp_min=0, cp_max=None):
    """Return dictionary of Unicode character lists.

    For each of the `catagories`, an item contains a list with all Unicode
    characters with `cp_min` <= code-point <= `cp_max` that belong to the
    category. (The default values check every code-point supported by Python.)
    """
    # Determine highest code point with one of the given categories
    # (may shorten the search time considerably if there are many
    # categories with not too high characters):
    if cp_max is None:
        cp_max = max(x for x in xrange(sys.maxunicode + 1)
                     if unicodedata.category(unichr(x)) in categories)
        # print cp_max # => 74867 for unicode_punctuation_categories
    charlists = {}
    for cat in categories:
        charlists[cat] = [unichr(x) for x in xrange(cp_min, cp_max+1)
                          if unicodedata.category(unichr(x)) == cat]
    return charlists


# Character categories in Docutils
# --------------------------------

def punctuation_samples():

    """Docutils punctuation category sample strings.

    Return list of sample strings for the categories "Open", "Close",
    "Delimiters" and "Closing-Delimiters" used in the `inline markup
    recognition rules`_.
    """

    # Lists with characters in Unicode punctuation character categories
    cp_min = 160 # ASCII chars have special rules for backwards compatibility
    ucharlists = unicode_charlists(unicode_punctuation_categories, cp_min)

    # match opening/closing characters
    # --------------------------------
    # Rearange the lists to ensure matching characters at the same
    # index position.

    # low quotation marks are also used as closers (e.g. in Greek)
    # move them to category Pi:
    ucharlists['Ps'].remove(u'‚') # 201A  SINGLE LOW-9 QUOTATION MARK
    ucharlists['Ps'].remove(u'„') # 201E  DOUBLE LOW-9 QUOTATION MARK
    ucharlists['Pi'] += [u'‚', u'„']

    ucharlists['Pi'].remove(u'‛') # 201B  SINGLE HIGH-REVERSED-9 QUOTATION MARK
    ucharlists['Pi'].remove(u'‟') # 201F  DOUBLE HIGH-REVERSED-9 QUOTATION MARK
    ucharlists['Pf'] += [u'‛', u'‟']

    # 301F  LOW DOUBLE PRIME QUOTATION MARK misses the opening pendant:
    ucharlists['Ps'].insert(ucharlists['Pe'].index(u'\u301f'), u'\u301d')

    # print u''.join(ucharlists['Ps']).encode('utf8')
    # print u''.join(ucharlists['Pe']).encode('utf8')
    # print u''.join(ucharlists['Pi']).encode('utf8')
    # print u''.join(ucharlists['Pf']).encode('utf8')

    # The Docutils character categories
    # ---------------------------------
    #
    # The categorization of ASCII chars is non-standard to reduce both
    # false positives and need for escaping. (see `inline markup recognition
    # rules`_)

    # matching, allowed before markup
    openers = [re.escape('"\'(<[{')]
    for cat in ('Ps', 'Pi', 'Pf'):
        openers.extend(ucharlists[cat])

    # matching, allowed after markup
    closers = [re.escape('"\')>]}')]
    for cat in ('Pe', 'Pf', 'Pi'):
        closers.extend(ucharlists[cat])

    # non-matching, allowed on both sides
    delimiters = [re.escape('-/:')]
    for cat in ('Pd', 'Po'):
        delimiters.extend(ucharlists[cat])

    # non-matching, after markup
    closing_delimiters = [re.escape('.,;!?')]

    # # Test open/close matching:
    # for i in range(min(len(openers),len(closers))):
    #     print '%4d    %s    %s' % (i, openers[i].encode('utf8'),
    #                                closers[i].encode('utf8'))

    return [u''.join(chars)
            for chars in (openers, closers, delimiters, closing_delimiters)]


# Matching open/close quotes
# --------------------------

# Rule (5) requires determination of matching open/close pairs. However,
# the pairing of open/close quotes is ambigue due to  different typographic
# conventions in different languages.

quote_pairs = {u'\xbb': u'\xbb', # Swedish
               u'\u2018': u'\u201a', # Greek
               u'\u2019': u'\u2019', # Swedish
               u'\u201a': u'\u2018\u2019', # German, Polish
               u'\u201c': u'\u201e', # German
               u'\u201e': u'\u201c\u201d',
               u'\u201d': u'\u201d', # Swedish
               u'\u203a': u'\u203a', # Swedish
              }

def match_chars(c1, c2):
    try:
        i = openers.index(c1)
    except ValueError:  # c1 not in openers
        return False
    return c2 == closers[i] or c2 in quote_pairs.get(c1, '')




# print results
# =============

if __name__ == '__main__':

    # (re) create and compare the samples:
    (o, c, d, cd) = punctuation_samples()
    if o != openers:
        print '- openers = ur"""%s"""' % openers.encode('utf8')
        print '+ openers = ur"""%s"""' % o.encode('utf8')
    if c != closers:
        print '- closers = ur"""%s"""' % closers.encode('utf8')
        print '+ closers = ur"""%s"""' % c.encode('utf8')
    if d != delimiters:
        print '- delimiters = ur"%s"' % delimiters.encode('utf8')
        print '+ delimiters = ur"%s"' % d.encode('utf8')
    if cd != closing_delimiters:
        print '- closing_delimiters = ur"%s"' % closing_delimiters.encode('utf8')
        print '+ closing_delimiters = ur"%s"' % cd.encode('utf8')

    # # test prints
    # print 'openers = ', repr(openers)
    # print 'closers = ', repr(closers)
    # print 'delimiters = ', repr(delimiters)
    # print 'closing_delimiters = ', repr(closing_delimiters)

    # ucharlists = unicode_charlists(unicode_punctuation_categories)
    # for cat, chars in ucharlists.items():
    #     # print cat, chars
    #     # compact output (visible with a comprehensive font):
    #     print (u":%s: %s" % (cat, u''.join(chars))).encode('utf8')
.. @+node:ekr.20130807203905.16760: *5* docutils test imports
docutils = g.importExtension('docutils',pluginName='leoRst.py',verbose=True)
print(docutils)
from docutils import parsers
print(parsers)
from docutils.parsers import rst
print(rst)
import docutils.parsers.rst
print(docutils.parsers.rst)
from docutils.parsers.rst import directives
.. @+node:ekr.20130807203905.16761: *5* six.u tests
# -*- coding: utf8 -*-
g.cls()
import leo.extensions.six as six
# import imp
# imp.reload(six)
# u = six.u
<< tex2unichar dicts >>
result = []
i = 0
for d in (
    mathaccent,
    mathalpha,
    mathbin,
    mathclose,
    mathfence,
    mathop,
    mathopen,
    mathord,
    mathover,
    mathradical,
    mathrel,
    mathunder,
    space,
):
    for key in d:
        ch = d.get(key)
        result.append(ch)
        six.u(ch)
    i += 1
g.es('\n'.join(result))
print('done')
.. @+node:ekr.20130807203905.16762: *6* << tex2unichar dicts >>
# -*- coding: utf8 -*-

# LaTeX math to Unicode symbols translation dictionaries.
# Generated with ``write_tex2unichar.py`` from the data in
# http://milde.users.sourceforge.net/LUCR/Math/

# Includes commands from: wasysym, stmaryrd, mathdots, mathabx, esint, bbold, amsxtra, amsmath, amssymb, standard LaTeX

mathaccent = {
    'acute': u('\u0301'), # xÌ COMBINING ACUTE ACCENT
    'bar': u('\u0304'), # xÌ„ COMBINING MACRON
    'breve': u('\u0306'), # xÌ† COMBINING BREVE
    'check': u('\u030c'), # xÌŒ COMBINING CARON
    'ddddot': u('\u20dc'), # xâƒœ COMBINING FOUR DOTS ABOVE
    'dddot': u('\u20db'), # xâƒ› COMBINING THREE DOTS ABOVE
    'ddot': u('\u0308'), # xÌˆ COMBINING DIAERESIS
    'dot': u('\u0307'), # xÌ‡ COMBINING DOT ABOVE
    'grave': u('\u0300'), # xÌ€ COMBINING GRAVE ACCENT
    'hat': u('\u0302'), # xÌ‚ COMBINING CIRCUMFLEX ACCENT
    'mathring': u('\u030a'), # xÌŠ COMBINING RING ABOVE
    'not': u('\u0338'), # xÌ¸ COMBINING LONG SOLIDUS OVERLAY
    'overleftarrow': u('\u20d6'), # xâƒ– COMBINING LEFT ARROW ABOVE
    'overleftrightarrow': u('\u20e1'), # xâƒ¡ COMBINING LEFT RIGHT ARROW ABOVE
    'overline': u('\u0305'), # xÌ… COMBINING OVERLINE
    'overrightarrow': u('\u20d7'), # xâƒ— COMBINING RIGHT ARROW ABOVE
    'tilde': u('\u0303'), # xÌƒ COMBINING TILDE
    'underbar': u('\u0331'), # xÌ± COMBINING MACRON BELOW
    'underleftarrow': u('\u20ee'), # xâƒ® COMBINING LEFT ARROW BELOW
    'underline': u('\u0332'), # xÌ² COMBINING LOW LINE
    'underrightarrow': u('\u20ef'), # xâƒ¯ COMBINING RIGHT ARROW BELOW
    'vec': u('\u20d7'), # xâƒ— COMBINING RIGHT ARROW ABOVE
    'widehat': u('\u0302'), # xÌ‚ COMBINING CIRCUMFLEX ACCENT
    'widetilde': u('\u0303'), # xÌƒ COMBINING TILDE
    }
mathalpha = {
    'Bbbk': u('\U0001d55c'), # ð•œ MATHEMATICAL DOUBLE-STRUCK SMALL K
    'Delta': u('\u0394'), # Î” GREEK CAPITAL LETTER DELTA
    'Gamma': u('\u0393'), # Î“ GREEK CAPITAL LETTER GAMMA
    'Im': u('\u2111'), # â„‘ BLACK-LETTER CAPITAL I
    'Lambda': u('\u039b'), # Î› GREEK CAPITAL LETTER LAMDA
    'Omega': u('\u03a9'), # Î© GREEK CAPITAL LETTER OMEGA
    'Phi': u('\u03a6'), # Î¦ GREEK CAPITAL LETTER PHI
    'Pi': u('\u03a0'), # Î  GREEK CAPITAL LETTER PI
    'Psi': u('\u03a8'), # Î¨ GREEK CAPITAL LETTER PSI
    'Re': u('\u211c'), # â„œ BLACK-LETTER CAPITAL R
    'Sigma': u('\u03a3'), # Î£ GREEK CAPITAL LETTER SIGMA
    'Theta': u('\u0398'), # Î˜ GREEK CAPITAL LETTER THETA
    'Upsilon': u('\u03a5'), # Î¥ GREEK CAPITAL LETTER UPSILON
    'Xi': u('\u039e'), # Îž GREEK CAPITAL LETTER XI
    'aleph': u('\u2135'), # â„µ ALEF SYMBOL
    'alpha': u('\u03b1'), # Î± GREEK SMALL LETTER ALPHA
    'beta': u('\u03b2'), # Î² GREEK SMALL LETTER BETA
    'beth': u('\u2136'), # â„¶ BET SYMBOL
    'chi': u('\u03c7'), # Ï‡ GREEK SMALL LETTER CHI
    'daleth': u('\u2138'), # â„¸ DALET SYMBOL
    'delta': u('\u03b4'), # Î´ GREEK SMALL LETTER DELTA
    'digamma': u('\u03dc'), # Ïœ GREEK LETTER DIGAMMA
    'ell': u('\u2113'), # â„“ SCRIPT SMALL L
    'epsilon': u('\u03f5'), # Ïµ GREEK LUNATE EPSILON SYMBOL
    'eta': u('\u03b7'), # Î· GREEK SMALL LETTER ETA
    'eth': u('\xf0'), # Ã° LATIN SMALL LETTER ETH
    'gamma': u('\u03b3'), # Î³ GREEK SMALL LETTER GAMMA
    'gimel': u('\u2137'), # â„· GIMEL SYMBOL
    'hbar': u('\u210f'), # â„ PLANCK CONSTANT OVER TWO PI
    'hslash': u('\u210f'), # â„ PLANCK CONSTANT OVER TWO PI
    'imath': u('\u0131'), # Ä± LATIN SMALL LETTER DOTLESS I
    'iota': u('\u03b9'), # Î¹ GREEK SMALL LETTER IOTA
    'jmath': u('\u0237'), # È· LATIN SMALL LETTER DOTLESS J
    'kappa': u('\u03ba'), # Îº GREEK SMALL LETTER KAPPA
    'lambda': u('\u03bb'), # Î» GREEK SMALL LETTER LAMDA
    'mu': u('\u03bc'), # Î¼ GREEK SMALL LETTER MU
    'nu': u('\u03bd'), # Î½ GREEK SMALL LETTER NU
    'omega': u('\u03c9'), # Ï‰ GREEK SMALL LETTER OMEGA
    'phi': u('\u03d5'), # Ï• GREEK PHI SYMBOL
    'pi': u('\u03c0'), # Ï€ GREEK SMALL LETTER PI
    'psi': u('\u03c8'), # Ïˆ GREEK SMALL LETTER PSI
    'rho': u('\u03c1'), # Ï GREEK SMALL LETTER RHO
    'sigma': u('\u03c3'), # Ïƒ GREEK SMALL LETTER SIGMA
    'tau': u('\u03c4'), # Ï„ GREEK SMALL LETTER TAU
    'theta': u('\u03b8'), # Î¸ GREEK SMALL LETTER THETA
    'upsilon': u('\u03c5'), # Ï… GREEK SMALL LETTER UPSILON
    'varDelta': u('\U0001d6e5'), # ð›¥ MATHEMATICAL ITALIC CAPITAL DELTA
    'varGamma': u('\U0001d6e4'), # ð›¤ MATHEMATICAL ITALIC CAPITAL GAMMA
    'varLambda': u('\U0001d6ec'), # ð›¬ MATHEMATICAL ITALIC CAPITAL LAMDA
    'varOmega': u('\U0001d6fa'), # ð›º MATHEMATICAL ITALIC CAPITAL OMEGA
    'varPhi': u('\U0001d6f7'), # ð›· MATHEMATICAL ITALIC CAPITAL PHI
    'varPi': u('\U0001d6f1'), # ð›± MATHEMATICAL ITALIC CAPITAL PI
    'varPsi': u('\U0001d6f9'), # ð›¹ MATHEMATICAL ITALIC CAPITAL PSI
    'varSigma': u('\U0001d6f4'), # ð›´ MATHEMATICAL ITALIC CAPITAL SIGMA
    'varTheta': u('\U0001d6e9'), # ð›© MATHEMATICAL ITALIC CAPITAL THETA
    'varUpsilon': u('\U0001d6f6'), # ð›¶ MATHEMATICAL ITALIC CAPITAL UPSILON
    'varXi': u('\U0001d6ef'), # ð›¯ MATHEMATICAL ITALIC CAPITAL XI
    'varepsilon': u('\u03b5'), # Îµ GREEK SMALL LETTER EPSILON
    'varkappa': u('\U0001d718'), # ðœ˜ MATHEMATICAL ITALIC KAPPA SYMBOL
    'varphi': u('\u03c6'), # Ï† GREEK SMALL LETTER PHI
    'varpi': u('\u03d6'), # Ï– GREEK PI SYMBOL
    'varrho': u('\u03f1'), # Ï± GREEK RHO SYMBOL
    'varsigma': u('\u03c2'), # Ï‚ GREEK SMALL LETTER FINAL SIGMA
    'vartheta': u('\u03d1'), # Ï‘ GREEK THETA SYMBOL
    'wp': u('\u2118'), # â„˜ SCRIPT CAPITAL P
    'xi': u('\u03be'), # Î¾ GREEK SMALL LETTER XI
    'zeta': u('\u03b6'), # Î¶ GREEK SMALL LETTER ZETA
    }
mathbin = {
    'Cap': u('\u22d2'), # â‹’ DOUBLE INTERSECTION
    'Circle': u('\u25cb'), # â—‹ WHITE CIRCLE
    'Cup': u('\u22d3'), # â‹“ DOUBLE UNION
    'LHD': u('\u25c0'), # â—€ BLACK LEFT-POINTING TRIANGLE
    'RHD': u('\u25b6'), # â–¶ BLACK RIGHT-POINTING TRIANGLE
    'amalg': u('\u2a3f'), # â¨¿ AMALGAMATION OR COPRODUCT
    'ast': u('\u2217'), # âˆ— ASTERISK OPERATOR
    'barwedge': u('\u22bc'), # âŠ¼ NAND
    'bigtriangledown': u('\u25bd'), # â–½ WHITE DOWN-POINTING TRIANGLE
    'bigtriangleup': u('\u25b3'), # â–³ WHITE UP-POINTING TRIANGLE
    'bindnasrepma': u('\u214b'), # â…‹ TURNED AMPERSAND
    'blacklozenge': u('\u29eb'), # â§« BLACK LOZENGE
    'blacktriangledown': u('\u25be'), # â–¾ BLACK DOWN-POINTING SMALL TRIANGLE
    'blacktriangleleft': u('\u25c2'), # â—‚ BLACK LEFT-POINTING SMALL TRIANGLE
    'blacktriangleright': u('\u25b8'), # â–¸ BLACK RIGHT-POINTING SMALL TRIANGLE
    'blacktriangleup': u('\u25b4'), # â–´ BLACK UP-POINTING SMALL TRIANGLE
    'boxast': u('\u29c6'), # â§† SQUARED ASTERISK
    'boxbar': u('\u25eb'), # â—« WHITE SQUARE WITH VERTICAL BISECTING LINE
    'boxbox': u('\u29c8'), # â§ˆ SQUARED SQUARE
    'boxbslash': u('\u29c5'), # â§… SQUARED FALLING DIAGONAL SLASH
    'boxcircle': u('\u29c7'), # â§‡ SQUARED SMALL CIRCLE
    'boxdot': u('\u22a1'), # âŠ¡ SQUARED DOT OPERATOR
    'boxminus': u('\u229f'), # âŠŸ SQUARED MINUS
    'boxplus': u('\u229e'), # âŠž SQUARED PLUS
    'boxslash': u('\u29c4'), # â§„ SQUARED RISING DIAGONAL SLASH
    'boxtimes': u('\u22a0'), # âŠ  SQUARED TIMES
    'bullet': u('\u2219'), # âˆ™ BULLET OPERATOR
    'cap': u('\u2229'), # âˆ© INTERSECTION
    'cdot': u('\u22c5'), # â‹… DOT OPERATOR
    'circ': u('\u2218'), # âˆ˜ RING OPERATOR
    'circledast': u('\u229b'), # âŠ› CIRCLED ASTERISK OPERATOR
    'circledcirc': u('\u229a'), # âŠš CIRCLED RING OPERATOR
    'circleddash': u('\u229d'), # âŠ CIRCLED DASH
    'cup': u('\u222a'), # âˆª UNION
    'curlyvee': u('\u22ce'), # â‹Ž CURLY LOGICAL OR
    'curlywedge': u('\u22cf'), # â‹ CURLY LOGICAL AND
    'dagger': u('\u2020'), # â€  DAGGER
    'ddagger': u('\u2021'), # â€¡ DOUBLE DAGGER
    'diamond': u('\u22c4'), # â‹„ DIAMOND OPERATOR
    'div': u('\xf7'), # Ã· DIVISION SIGN
    'divideontimes': u('\u22c7'), # â‹‡ DIVISION TIMES
    'dotplus': u('\u2214'), # âˆ” DOT PLUS
    'doublebarwedge': u('\u2a5e'), # â©ž LOGICAL AND WITH DOUBLE OVERBAR
    'intercal': u('\u22ba'), # âŠº INTERCALATE
    'interleave': u('\u2af4'), # â«´ TRIPLE VERTICAL BAR BINARY RELATION
    'land': u('\u2227'), # âˆ§ LOGICAL AND
    'leftthreetimes': u('\u22cb'), # â‹‹ LEFT SEMIDIRECT PRODUCT
    'lhd': u('\u25c1'), # â— WHITE LEFT-POINTING TRIANGLE
    'lor': u('\u2228'), # âˆ¨ LOGICAL OR
    'ltimes': u('\u22c9'), # â‹‰ LEFT NORMAL FACTOR SEMIDIRECT PRODUCT
    'mp': u('\u2213'), # âˆ“ MINUS-OR-PLUS SIGN
    'odot': u('\u2299'), # âŠ™ CIRCLED DOT OPERATOR
    'ominus': u('\u2296'), # âŠ– CIRCLED MINUS
    'oplus': u('\u2295'), # âŠ• CIRCLED PLUS
    'oslash': u('\u2298'), # âŠ˜ CIRCLED DIVISION SLASH
    'otimes': u('\u2297'), # âŠ— CIRCLED TIMES
    'pm': u('\xb1'), # Â± PLUS-MINUS SIGN
    'rhd': u('\u25b7'), # â–· WHITE RIGHT-POINTING TRIANGLE
    'rightthreetimes': u('\u22cc'), # â‹Œ RIGHT SEMIDIRECT PRODUCT
    'rtimes': u('\u22ca'), # â‹Š RIGHT NORMAL FACTOR SEMIDIRECT PRODUCT
    'setminus': u('\u29f5'), # â§µ REVERSE SOLIDUS OPERATOR
    'slash': u('\u2215'), # âˆ• DIVISION SLASH
    'smallsetminus': u('\u2216'), # âˆ– SET MINUS
    'smalltriangledown': u('\u25bf'), # â–¿ WHITE DOWN-POINTING SMALL TRIANGLE
    'smalltriangleleft': u('\u25c3'), # â—ƒ WHITE LEFT-POINTING SMALL TRIANGLE
    'smalltriangleright': u('\u25b9'), # â–¹ WHITE RIGHT-POINTING SMALL TRIANGLE
    'smalltriangleup': u('\u25b5'), # â–µ WHITE UP-POINTING SMALL TRIANGLE
    'sqcap': u('\u2293'), # âŠ“ SQUARE CAP
    'sqcup': u('\u2294'), # âŠ” SQUARE CUP
    'sslash': u('\u2afd'), # â«½ DOUBLE SOLIDUS OPERATOR
    'star': u('\u22c6'), # â‹† STAR OPERATOR
    'talloblong': u('\u2afe'), # â«¾ WHITE VERTICAL BAR
    'times': u('\xd7'), # Ã— MULTIPLICATION SIGN
    'triangle': u('\u25b3'), # â–³ WHITE UP-POINTING TRIANGLE
    'triangledown': u('\u25bf'), # â–¿ WHITE DOWN-POINTING SMALL TRIANGLE
    'triangleleft': u('\u25c3'), # â—ƒ WHITE LEFT-POINTING SMALL TRIANGLE
    'triangleright': u('\u25b9'), # â–¹ WHITE RIGHT-POINTING SMALL TRIANGLE
    'uplus': u('\u228e'), # âŠŽ MULTISET UNION
    'vartriangle': u('\u25b3'), # â–³ WHITE UP-POINTING TRIANGLE
    'vee': u('\u2228'), # âˆ¨ LOGICAL OR
    'veebar': u('\u22bb'), # âŠ» XOR
    'wedge': u('\u2227'), # âˆ§ LOGICAL AND
    'wr': u('\u2240'), # â‰€ WREATH PRODUCT
    }
mathclose = {
    'Rbag': u('\u27c6'), # âŸ† RIGHT S-SHAPED BAG DELIMITER
    'lrcorner': u('\u231f'), # âŒŸ BOTTOM RIGHT CORNER
    'rangle': u('\u27e9'), # âŸ© MATHEMATICAL RIGHT ANGLE BRACKET
    'rbag': u('\u27c6'), # âŸ† RIGHT S-SHAPED BAG DELIMITER
    'rbrace': u('}'), # } RIGHT CURLY BRACKET
    'rbrack': u(']'), # ] RIGHT SQUARE BRACKET
    'rceil': u('\u2309'), # âŒ‰ RIGHT CEILING
    'rfloor': u('\u230b'), # âŒ‹ RIGHT FLOOR
    'rgroup': u('\u27ef'), # âŸ¯ MATHEMATICAL RIGHT FLATTENED PARENTHESIS
    'rrbracket': u('\u27e7'), # âŸ§ MATHEMATICAL RIGHT WHITE SQUARE BRACKET
    'rrparenthesis': u('\u2988'), # â¦ˆ Z NOTATION RIGHT IMAGE BRACKET
    'urcorner': u('\u231d'), # âŒ TOP RIGHT CORNER
    '}': u('}'), # } RIGHT CURLY BRACKET
    }
mathfence = {
    'Vert': u('\u2016'), # â€– DOUBLE VERTICAL LINE
    'vert': u('|'), # | VERTICAL LINE
    '|': u('\u2016'), # â€– DOUBLE VERTICAL LINE
    }
mathop = {
    'Join': u('\u2a1d'), # â¨ JOIN
    'bigcap': u('\u22c2'), # â‹‚ N-ARY INTERSECTION
    'bigcup': u('\u22c3'), # â‹ƒ N-ARY UNION
    'biginterleave': u('\u2afc'), # â«¼ LARGE TRIPLE VERTICAL BAR OPERATOR
    'bigodot': u('\u2a00'), # â¨€ N-ARY CIRCLED DOT OPERATOR
    'bigoplus': u('\u2a01'), # â¨ N-ARY CIRCLED PLUS OPERATOR
    'bigotimes': u('\u2a02'), # â¨‚ N-ARY CIRCLED TIMES OPERATOR
    'bigsqcup': u('\u2a06'), # â¨† N-ARY SQUARE UNION OPERATOR
    'biguplus': u('\u2a04'), # â¨„ N-ARY UNION OPERATOR WITH PLUS
    'bigvee': u('\u22c1'), # â‹ N-ARY LOGICAL OR
    'bigwedge': u('\u22c0'), # â‹€ N-ARY LOGICAL AND
    'coprod': u('\u2210'), # âˆ N-ARY COPRODUCT
    'fatsemi': u('\u2a1f'), # â¨Ÿ Z NOTATION SCHEMA COMPOSITION
    'fint': u('\u2a0f'), # â¨ INTEGRAL AVERAGE WITH SLASH
    'iiiint': u('\u2a0c'), # â¨Œ QUADRUPLE INTEGRAL OPERATOR
    'iiint': u('\u222d'), # âˆ­ TRIPLE INTEGRAL
    'iint': u('\u222c'), # âˆ¬ DOUBLE INTEGRAL
    'int': u('\u222b'), # âˆ« INTEGRAL
    'oiint': u('\u222f'), # âˆ¯ SURFACE INTEGRAL
    'oint': u('\u222e'), # âˆ® CONTOUR INTEGRAL
    'ointctrclockwise': u('\u2233'), # âˆ³ ANTICLOCKWISE CONTOUR INTEGRAL
    'prod': u('\u220f'), # âˆ N-ARY PRODUCT
    'sqint': u('\u2a16'), # â¨– QUATERNION INTEGRAL OPERATOR
    'sum': u('\u2211'), # âˆ‘ N-ARY SUMMATION
    'varointclockwise': u('\u2232'), # âˆ² CLOCKWISE CONTOUR INTEGRAL
    }
mathopen = {
    'Lbag': u('\u27c5'), # âŸ… LEFT S-SHAPED BAG DELIMITER
    'langle': u('\u27e8'), # âŸ¨ MATHEMATICAL LEFT ANGLE BRACKET
    'lbag': u('\u27c5'), # âŸ… LEFT S-SHAPED BAG DELIMITER
    'lbrace': u('{'), # { LEFT CURLY BRACKET
    'lbrack': u('['), # [ LEFT SQUARE BRACKET
    'lceil': u('\u2308'), # âŒˆ LEFT CEILING
    'lfloor': u('\u230a'), # âŒŠ LEFT FLOOR
    'lgroup': u('\u27ee'), # âŸ® MATHEMATICAL LEFT FLATTENED PARENTHESIS
    'llbracket': u('\u27e6'), # âŸ¦ MATHEMATICAL LEFT WHITE SQUARE BRACKET
    'llcorner': u('\u231e'), # âŒž BOTTOM LEFT CORNER
    'llparenthesis': u('\u2987'), # â¦‡ Z NOTATION LEFT IMAGE BRACKET
    'ulcorner': u('\u231c'), # âŒœ TOP LEFT CORNER
    '{': u('{'), # { LEFT CURLY BRACKET
    }
mathord = {
    '#': u('#'), # # NUMBER SIGN
    '$': u('$'), # $ DOLLAR SIGN
    '%': u('%'), # % PERCENT SIGN
    '&': u('&'), # & AMPERSAND
    'AC': u('\u223f'), # âˆ¿ SINE WAVE
    'APLcomment': u('\u235d'), # â APL FUNCTIONAL SYMBOL UP SHOE JOT
    'APLdownarrowbox': u('\u2357'), # â— APL FUNCTIONAL SYMBOL QUAD DOWNWARDS ARROW
    'APLinput': u('\u235e'), # âž APL FUNCTIONAL SYMBOL QUOTE QUAD
    'APLinv': u('\u2339'), # âŒ¹ APL FUNCTIONAL SYMBOL QUAD DIVIDE
    'APLleftarrowbox': u('\u2347'), # â‡ APL FUNCTIONAL SYMBOL QUAD LEFTWARDS ARROW
    'APLlog': u('\u235f'), # âŸ APL FUNCTIONAL SYMBOL CIRCLE STAR
    'APLrightarrowbox': u('\u2348'), # âˆ APL FUNCTIONAL SYMBOL QUAD RIGHTWARDS ARROW
    'APLuparrowbox': u('\u2350'), # â APL FUNCTIONAL SYMBOL QUAD UPWARDS ARROW
    'Aries': u('\u2648'), # â™ˆ ARIES
    'CIRCLE': u('\u25cf'), # â— BLACK CIRCLE
    'CheckedBox': u('\u2611'), # â˜‘ BALLOT BOX WITH CHECK
    'Diamond': u('\u25c7'), # â—‡ WHITE DIAMOND
    'Finv': u('\u2132'), # â„² TURNED CAPITAL F
    'Game': u('\u2141'), # â… TURNED SANS-SERIF CAPITAL G
    'Gemini': u('\u264a'), # â™Š GEMINI
    'Jupiter': u('\u2643'), # â™ƒ JUPITER
    'LEFTCIRCLE': u('\u25d6'), # â—– LEFT HALF BLACK CIRCLE
    'LEFTcircle': u('\u25d0'), # â— CIRCLE WITH LEFT HALF BLACK
    'Leo': u('\u264c'), # â™Œ LEO
    'Libra': u('\u264e'), # â™Ž LIBRA
    'Mars': u('\u2642'), # â™‚ MALE SIGN
    'Mercury': u('\u263f'), # â˜¿ MERCURY
    'Neptune': u('\u2646'), # â™† NEPTUNE
    'Pluto': u('\u2647'), # â™‡ PLUTO
    'RIGHTCIRCLE': u('\u25d7'), # â—— RIGHT HALF BLACK CIRCLE
    'RIGHTcircle': u('\u25d1'), # â—‘ CIRCLE WITH RIGHT HALF BLACK
    'Saturn': u('\u2644'), # â™„ SATURN
    'Scorpio': u('\u264f'), # â™ SCORPIUS
    'Square': u('\u2610'), # â˜ BALLOT BOX
    'Sun': u('\u2609'), # â˜‰ SUN
    'Taurus': u('\u2649'), # â™‰ TAURUS
    'Uranus': u('\u2645'), # â™… URANUS
    'Venus': u('\u2640'), # â™€ FEMALE SIGN
    'XBox': u('\u2612'), # â˜’ BALLOT BOX WITH X
    'Yup': u('\u2144'), # â…„ TURNED SANS-SERIF CAPITAL Y
    '_': u('_'), # _ LOW LINE
    'angle': u('\u2220'), # âˆ  ANGLE
    'aquarius': u('\u2652'), # â™’ AQUARIUS
    'aries': u('\u2648'), # â™ˆ ARIES
    'ast': u('*'), # * ASTERISK
    'backepsilon': u('\u03f6'), # Ï¶ GREEK REVERSED LUNATE EPSILON SYMBOL
    'backprime': u('\u2035'), # â€µ REVERSED PRIME
    'backslash': unicode('\\'), # \ REVERSE SOLIDUS  #### Changed. was u'\'
    'because': u('\u2235'), # âˆµ BECAUSE
    'bigstar': u('\u2605'), # â˜… BLACK STAR
    'binampersand': u('&'), # & AMPERSAND
    'blacklozenge': u('\u2b27'), # â¬§ BLACK MEDIUM LOZENGE
    'blacksmiley': u('\u263b'), # â˜» BLACK SMILING FACE
    'blacksquare': u('\u25fc'), # â—¼ BLACK MEDIUM SQUARE
    'bot': u('\u22a5'), # âŠ¥ UP TACK
    'boy': u('\u2642'), # â™‚ MALE SIGN
    'cancer': u('\u264b'), # â™‹ CANCER
    'capricornus': u('\u2651'), # â™‘ CAPRICORN
    'cdots': u('\u22ef'), # â‹¯ MIDLINE HORIZONTAL ELLIPSIS
    'cent': u('\xa2'), # Â¢ CENT SIGN
    'centerdot': u('\u2b1d'), # â¬ BLACK VERY SMALL SQUARE
    'checkmark': u('\u2713'), # âœ“ CHECK MARK
    'circlearrowleft': u('\u21ba'), # â†º ANTICLOCKWISE OPEN CIRCLE ARROW
    'circlearrowright': u('\u21bb'), # â†» CLOCKWISE OPEN CIRCLE ARROW
    'circledR': u('\xae'), # Â® REGISTERED SIGN
    'circledcirc': u('\u25ce'), # â—Ž BULLSEYE
    'clubsuit': u('\u2663'), # â™£ BLACK CLUB SUIT
    'complement': u('\u2201'), # âˆ COMPLEMENT
    'dasharrow': u('\u21e2'), # â‡¢ RIGHTWARDS DASHED ARROW
    'dashleftarrow': u('\u21e0'), # â‡  LEFTWARDS DASHED ARROW
    'dashrightarrow': u('\u21e2'), # â‡¢ RIGHTWARDS DASHED ARROW
    'diameter': u('\u2300'), # âŒ€ DIAMETER SIGN
    'diamondsuit': u('\u2662'), # â™¢ WHITE DIAMOND SUIT
    'earth': u('\u2641'), # â™ EARTH
    'exists': u('\u2203'), # âˆƒ THERE EXISTS
    'female': u('\u2640'), # â™€ FEMALE SIGN
    'flat': u('\u266d'), # â™­ MUSIC FLAT SIGN
    'forall': u('\u2200'), # âˆ€ FOR ALL
    'fourth': u('\u2057'), # â— QUADRUPLE PRIME
    'frownie': u('\u2639'), # â˜¹ WHITE FROWNING FACE
    'gemini': u('\u264a'), # â™Š GEMINI
    'girl': u('\u2640'), # â™€ FEMALE SIGN
    'heartsuit': u('\u2661'), # â™¡ WHITE HEART SUIT
    'infty': u('\u221e'), # âˆž INFINITY
    'invneg': u('\u2310'), # âŒ REVERSED NOT SIGN
    'jupiter': u('\u2643'), # â™ƒ JUPITER
    'ldots': u('\u2026'), # â€¦ HORIZONTAL ELLIPSIS
    'leftmoon': u('\u263e'), # â˜¾ LAST QUARTER MOON
    'leftturn': u('\u21ba'), # â†º ANTICLOCKWISE OPEN CIRCLE ARROW
    'leo': u('\u264c'), # â™Œ LEO
    'libra': u('\u264e'), # â™Ž LIBRA
    'lnot': u('\xac'), # Â¬ NOT SIGN
    'lozenge': u('\u25ca'), # â—Š LOZENGE
    'male': u('\u2642'), # â™‚ MALE SIGN
    'maltese': u('\u2720'), # âœ  MALTESE CROSS
    'mathdollar': u('$'), # $ DOLLAR SIGN
    'measuredangle': u('\u2221'), # âˆ¡ MEASURED ANGLE
    'mercury': u('\u263f'), # â˜¿ MERCURY
    'mho': u('\u2127'), # â„§ INVERTED OHM SIGN
    'nabla': u('\u2207'), # âˆ‡ NABLA
    'natural': u('\u266e'), # â™® MUSIC NATURAL SIGN
    'neg': u('\xac'), # Â¬ NOT SIGN
    'neptune': u('\u2646'), # â™† NEPTUNE
    'nexists': u('\u2204'), # âˆ„ THERE DOES NOT EXIST
    'notbackslash': u('\u2340'), # â€ APL FUNCTIONAL SYMBOL BACKSLASH BAR
    'partial': u('\u2202'), # âˆ‚ PARTIAL DIFFERENTIAL
    'pisces': u('\u2653'), # â™“ PISCES
    'pluto': u('\u2647'), # â™‡ PLUTO
    'pounds': u('\xa3'), # Â£ POUND SIGN
    'prime': u('\u2032'), # â€² PRIME
    'quarternote': u('\u2669'), # â™© QUARTER NOTE
    'rightmoon': u('\u263d'), # â˜½ FIRST QUARTER MOON
    'rightturn': u('\u21bb'), # â†» CLOCKWISE OPEN CIRCLE ARROW
    'sagittarius': u('\u2650'), # â™ SAGITTARIUS
    'saturn': u('\u2644'), # â™„ SATURN
    'scorpio': u('\u264f'), # â™ SCORPIUS
    'second': u('\u2033'), # â€³ DOUBLE PRIME
    'sharp': u('\u266f'), # â™¯ MUSIC SHARP SIGN
    'sim': u('~'), # ~ TILDE
    'slash': u('/'), # / SOLIDUS
    'smiley': u('\u263a'), # â˜º WHITE SMILING FACE
    'spadesuit': u('\u2660'), # â™  BLACK SPADE SUIT
    'spddot': u('\xa8'), # Â¨ DIAERESIS
    'sphat': u('^'), # ^ CIRCUMFLEX ACCENT
    'sphericalangle': u('\u2222'), # âˆ¢ SPHERICAL ANGLE
    'sptilde': u('~'), # ~ TILDE
    'square': u('\u25fb'), # â—» WHITE MEDIUM SQUARE
    'sun': u('\u263c'), # â˜¼ WHITE SUN WITH RAYS
    'taurus': u('\u2649'), # â™‰ TAURUS
    'therefore': u('\u2234'), # âˆ´ THEREFORE
    'third': u('\u2034'), # â€´ TRIPLE PRIME
    'top': u('\u22a4'), # âŠ¤ DOWN TACK
    'triangleleft': u('\u25c5'), # â—… WHITE LEFT-POINTING POINTER
    'triangleright': u('\u25bb'), # â–» WHITE RIGHT-POINTING POINTER
    'twonotes': u('\u266b'), # â™« BEAMED EIGHTH NOTES
    'uranus': u('\u2645'), # â™… URANUS
    'varEarth': u('\u2641'), # â™ EARTH
    'varnothing': u('\u2205'), # âˆ… EMPTY SET
    'virgo': u('\u264d'), # â™ VIRGO
    'wasylozenge': u('\u2311'), # âŒ‘ SQUARE LOZENGE
    'wasytherefore': u('\u2234'), # âˆ´ THEREFORE
    'yen': u('\xa5'), # Â¥ YEN SIGN
    }
mathover = {
    'overbrace': u('\u23de'), # âž TOP CURLY BRACKET
    'wideparen': u('\u23dc'), # âœ TOP PARENTHESIS
    }
mathradical = {
    'sqrt': u('\u221a'), # âˆš SQUARE ROOT
    'sqrt[3]': u('\u221b'), # âˆ› CUBE ROOT
    'sqrt[4]': u('\u221c'), # âˆœ FOURTH ROOT
    }
mathrel = {
    'Bumpeq': u('\u224e'), # â‰Ž GEOMETRICALLY EQUIVALENT TO
    'Doteq': u('\u2251'), # â‰‘ GEOMETRICALLY EQUAL TO
    'Downarrow': u('\u21d3'), # â‡“ DOWNWARDS DOUBLE ARROW
    'Leftarrow': u('\u21d0'), # â‡ LEFTWARDS DOUBLE ARROW
    'Leftrightarrow': u('\u21d4'), # â‡” LEFT RIGHT DOUBLE ARROW
    'Lleftarrow': u('\u21da'), # â‡š LEFTWARDS TRIPLE ARROW
    'Longleftarrow': u('\u27f8'), # âŸ¸ LONG LEFTWARDS DOUBLE ARROW
    'Longleftrightarrow': u('\u27fa'), # âŸº LONG LEFT RIGHT DOUBLE ARROW
    'Longmapsfrom': u('\u27fd'), # âŸ½ LONG LEFTWARDS DOUBLE ARROW FROM BAR
    'Longmapsto': u('\u27fe'), # âŸ¾ LONG RIGHTWARDS DOUBLE ARROW FROM BAR
    'Longrightarrow': u('\u27f9'), # âŸ¹ LONG RIGHTWARDS DOUBLE ARROW
    'Lsh': u('\u21b0'), # â†° UPWARDS ARROW WITH TIP LEFTWARDS
    'Mapsfrom': u('\u2906'), # â¤† LEFTWARDS DOUBLE ARROW FROM BAR
    'Mapsto': u('\u2907'), # â¤‡ RIGHTWARDS DOUBLE ARROW FROM BAR
    'Rightarrow': u('\u21d2'), # â‡’ RIGHTWARDS DOUBLE ARROW
    'Rrightarrow': u('\u21db'), # â‡› RIGHTWARDS TRIPLE ARROW
    'Rsh': u('\u21b1'), # â†± UPWARDS ARROW WITH TIP RIGHTWARDS
    'Subset': u('\u22d0'), # â‹ DOUBLE SUBSET
    'Supset': u('\u22d1'), # â‹‘ DOUBLE SUPERSET
    'Uparrow': u('\u21d1'), # â‡‘ UPWARDS DOUBLE ARROW
    'Updownarrow': u('\u21d5'), # â‡• UP DOWN DOUBLE ARROW
    'VDash': u('\u22ab'), # âŠ« DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE
    'Vdash': u('\u22a9'), # âŠ© FORCES
    'Vvdash': u('\u22aa'), # âŠª TRIPLE VERTICAL BAR RIGHT TURNSTILE
    'apprge': u('\u2273'), # â‰³ GREATER-THAN OR EQUIVALENT TO
    'apprle': u('\u2272'), # â‰² LESS-THAN OR EQUIVALENT TO
    'approx': u('\u2248'), # â‰ˆ ALMOST EQUAL TO
    'approxeq': u('\u224a'), # â‰Š ALMOST EQUAL OR EQUAL TO
    'asymp': u('\u224d'), # â‰ EQUIVALENT TO
    'backsim': u('\u223d'), # âˆ½ REVERSED TILDE
    'backsimeq': u('\u22cd'), # â‹ REVERSED TILDE EQUALS
    'barin': u('\u22f6'), # â‹¶ ELEMENT OF WITH OVERBAR
    'barleftharpoon': u('\u296b'), # â¥« LEFTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH
    'barrightharpoon': u('\u296d'), # â¥­ RIGHTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH
    'between': u('\u226c'), # â‰¬ BETWEEN
    'bowtie': u('\u22c8'), # â‹ˆ BOWTIE
    'bumpeq': u('\u224f'), # â‰ DIFFERENCE BETWEEN
    'circeq': u('\u2257'), # â‰— RING EQUAL TO
    'coloneq': u('\u2254'), # â‰” COLON EQUALS
    'cong': u('\u2245'), # â‰… APPROXIMATELY EQUAL TO
    'corresponds': u('\u2259'), # â‰™ ESTIMATES
    'curlyeqprec': u('\u22de'), # â‹ž EQUAL TO OR PRECEDES
    'curlyeqsucc': u('\u22df'), # â‹Ÿ EQUAL TO OR SUCCEEDS
    'curvearrowleft': u('\u21b6'), # â†¶ ANTICLOCKWISE TOP SEMICIRCLE ARROW
    'curvearrowright': u('\u21b7'), # â†· CLOCKWISE TOP SEMICIRCLE ARROW
    'dashv': u('\u22a3'), # âŠ£ LEFT TACK
    'ddots': u('\u22f1'), # â‹± DOWN RIGHT DIAGONAL ELLIPSIS
    'dlsh': u('\u21b2'), # â†² DOWNWARDS ARROW WITH TIP LEFTWARDS
    'doteq': u('\u2250'), # â‰ APPROACHES THE LIMIT
    'doteqdot': u('\u2251'), # â‰‘ GEOMETRICALLY EQUAL TO
    'downarrow': u('\u2193'), # â†“ DOWNWARDS ARROW
    'downdownarrows': u('\u21ca'), # â‡Š DOWNWARDS PAIRED ARROWS
    'downdownharpoons': u('\u2965'), # â¥¥ DOWNWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT
    'downharpoonleft': u('\u21c3'), # â‡ƒ DOWNWARDS HARPOON WITH BARB LEFTWARDS
    'downharpoonright': u('\u21c2'), # â‡‚ DOWNWARDS HARPOON WITH BARB RIGHTWARDS
    'downuparrows': u('\u21f5'), # â‡µ DOWNWARDS ARROW LEFTWARDS OF UPWARDS ARROW
    'downupharpoons': u('\u296f'), # â¥¯ DOWNWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT
    'drsh': u('\u21b3'), # â†³ DOWNWARDS ARROW WITH TIP RIGHTWARDS
    'eqcirc': u('\u2256'), # â‰– RING IN EQUAL TO
    'eqcolon': u('\u2255'), # â‰• EQUALS COLON
    'eqsim': u('\u2242'), # â‰‚ MINUS TILDE
    'eqslantgtr': u('\u2a96'), # âª– SLANTED EQUAL TO OR GREATER-THAN
    'eqslantless': u('\u2a95'), # âª• SLANTED EQUAL TO OR LESS-THAN
    'equiv': u('\u2261'), # â‰¡ IDENTICAL TO
    'fallingdotseq': u('\u2252'), # â‰’ APPROXIMATELY EQUAL TO OR THE IMAGE OF
    'frown': u('\u2322'), # âŒ¢ FROWN
    'ge': u('\u2265'), # â‰¥ GREATER-THAN OR EQUAL TO
    'geq': u('\u2265'), # â‰¥ GREATER-THAN OR EQUAL TO
    'geqq': u('\u2267'), # â‰§ GREATER-THAN OVER EQUAL TO
    'geqslant': u('\u2a7e'), # â©¾ GREATER-THAN OR SLANTED EQUAL TO
    'gets': u('\u2190'), # â† LEFTWARDS ARROW
    'gg': u('\u226b'), # â‰« MUCH GREATER-THAN
    'ggcurly': u('\u2abc'), # âª¼ DOUBLE SUCCEEDS
    'ggg': u('\u22d9'), # â‹™ VERY MUCH GREATER-THAN
    'gnapprox': u('\u2a8a'), # âªŠ GREATER-THAN AND NOT APPROXIMATE
    'gneq': u('\u2a88'), # âªˆ GREATER-THAN AND SINGLE-LINE NOT EQUAL TO
    'gneqq': u('\u2269'), # â‰© GREATER-THAN BUT NOT EQUAL TO
    'gnsim': u('\u22e7'), # â‹§ GREATER-THAN BUT NOT EQUIVALENT TO
    'gtrapprox': u('\u2a86'), # âª† GREATER-THAN OR APPROXIMATE
    'gtrdot': u('\u22d7'), # â‹— GREATER-THAN WITH DOT
    'gtreqless': u('\u22db'), # â‹› GREATER-THAN EQUAL TO OR LESS-THAN
    'gtreqqless': u('\u2a8c'), # âªŒ GREATER-THAN ABOVE DOUBLE-LINE EQUAL ABOVE LESS-THAN
    'gtrless': u('\u2277'), # â‰· GREATER-THAN OR LESS-THAN
    'gtrsim': u('\u2273'), # â‰³ GREATER-THAN OR EQUIVALENT TO
    'hash': u('\u22d5'), # â‹• EQUAL AND PARALLEL TO
    'hookleftarrow': u('\u21a9'), # â†© LEFTWARDS ARROW WITH HOOK
    'hookrightarrow': u('\u21aa'), # â†ª RIGHTWARDS ARROW WITH HOOK
    'iddots': u('\u22f0'), # â‹° UP RIGHT DIAGONAL ELLIPSIS
    'impliedby': u('\u27f8'), # âŸ¸ LONG LEFTWARDS DOUBLE ARROW
    'implies': u('\u27f9'), # âŸ¹ LONG RIGHTWARDS DOUBLE ARROW
    'in': u('\u2208'), # âˆˆ ELEMENT OF
    'le': u('\u2264'), # â‰¤ LESS-THAN OR EQUAL TO
    'leftarrow': u('\u2190'), # â† LEFTWARDS ARROW
    'leftarrowtail': u('\u21a2'), # â†¢ LEFTWARDS ARROW WITH TAIL
    'leftarrowtriangle': u('\u21fd'), # â‡½ LEFTWARDS OPEN-HEADED ARROW
    'leftbarharpoon': u('\u296a'), # â¥ª LEFTWARDS HARPOON WITH BARB UP ABOVE LONG DASH
    'leftharpoondown': u('\u21bd'), # â†½ LEFTWARDS HARPOON WITH BARB DOWNWARDS
    'leftharpoonup': u('\u21bc'), # â†¼ LEFTWARDS HARPOON WITH BARB UPWARDS
    'leftleftarrows': u('\u21c7'), # â‡‡ LEFTWARDS PAIRED ARROWS
    'leftleftharpoons': u('\u2962'), # â¥¢ LEFTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB DOWN
    'leftrightarrow': u('\u2194'), # â†” LEFT RIGHT ARROW
    'leftrightarrows': u('\u21c6'), # â‡† LEFTWARDS ARROW OVER RIGHTWARDS ARROW
    'leftrightarrowtriangle': u('\u21ff'), # â‡¿ LEFT RIGHT OPEN-HEADED ARROW
    'leftrightharpoon': u('\u294a'), # â¥Š LEFT BARB UP RIGHT BARB DOWN HARPOON
    'leftrightharpoons': u('\u21cb'), # â‡‹ LEFTWARDS HARPOON OVER RIGHTWARDS HARPOON
    'leftrightsquigarrow': u('\u21ad'), # â†­ LEFT RIGHT WAVE ARROW
    'leftslice': u('\u2aa6'), # âª¦ LESS-THAN CLOSED BY CURVE
    'leftsquigarrow': u('\u21dc'), # â‡œ LEFTWARDS SQUIGGLE ARROW
    'leq': u('\u2264'), # â‰¤ LESS-THAN OR EQUAL TO
    'leqq': u('\u2266'), # â‰¦ LESS-THAN OVER EQUAL TO
    'leqslant': u('\u2a7d'), # â©½ LESS-THAN OR SLANTED EQUAL TO
    'lessapprox': u('\u2a85'), # âª… LESS-THAN OR APPROXIMATE
    'lessdot': u('\u22d6'), # â‹– LESS-THAN WITH DOT
    'lesseqgtr': u('\u22da'), # â‹š LESS-THAN EQUAL TO OR GREATER-THAN
    'lesseqqgtr': u('\u2a8b'), # âª‹ LESS-THAN ABOVE DOUBLE-LINE EQUAL ABOVE GREATER-THAN
    'lessgtr': u('\u2276'), # â‰¶ LESS-THAN OR GREATER-THAN
    'lesssim': u('\u2272'), # â‰² LESS-THAN OR EQUIVALENT TO
    'lightning': u('\u21af'), # â†¯ DOWNWARDS ZIGZAG ARROW
    'll': u('\u226a'), # â‰ª MUCH LESS-THAN
    'llcurly': u('\u2abb'), # âª» DOUBLE PRECEDES
    'lll': u('\u22d8'), # â‹˜ VERY MUCH LESS-THAN
    'lnapprox': u('\u2a89'), # âª‰ LESS-THAN AND NOT APPROXIMATE
    'lneq': u('\u2a87'), # âª‡ LESS-THAN AND SINGLE-LINE NOT EQUAL TO
    'lneqq': u('\u2268'), # â‰¨ LESS-THAN BUT NOT EQUAL TO
    'lnsim': u('\u22e6'), # â‹¦ LESS-THAN BUT NOT EQUIVALENT TO
    'longleftarrow': u('\u27f5'), # âŸµ LONG LEFTWARDS ARROW
    'longleftrightarrow': u('\u27f7'), # âŸ· LONG LEFT RIGHT ARROW
    'longmapsfrom': u('\u27fb'), # âŸ» LONG LEFTWARDS ARROW FROM BAR
    'longmapsto': u('\u27fc'), # âŸ¼ LONG RIGHTWARDS ARROW FROM BAR
    'longrightarrow': u('\u27f6'), # âŸ¶ LONG RIGHTWARDS ARROW
    'looparrowleft': u('\u21ab'), # â†« LEFTWARDS ARROW WITH LOOP
    'looparrowright': u('\u21ac'), # â†¬ RIGHTWARDS ARROW WITH LOOP
    'mapsfrom': u('\u21a4'), # â†¤ LEFTWARDS ARROW FROM BAR
    'mapsto': u('\u21a6'), # â†¦ RIGHTWARDS ARROW FROM BAR
    'mid': u('\u2223'), # âˆ£ DIVIDES
    'models': u('\u22a7'), # âŠ§ MODELS
    'multimap': u('\u22b8'), # âŠ¸ MULTIMAP
    'nLeftarrow': u('\u21cd'), # â‡ LEFTWARDS DOUBLE ARROW WITH STROKE
    'nLeftrightarrow': u('\u21ce'), # â‡Ž LEFT RIGHT DOUBLE ARROW WITH STROKE
    'nRightarrow': u('\u21cf'), # â‡ RIGHTWARDS DOUBLE ARROW WITH STROKE
    'nVDash': u('\u22af'), # âŠ¯ NEGATED DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE
    'nVdash': u('\u22ae'), # âŠ® DOES NOT FORCE
    'ncong': u('\u2247'), # â‰‡ NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO
    'ne': u('\u2260'), # â‰  NOT EQUAL TO
    'nearrow': u('\u2197'), # â†— NORTH EAST ARROW
    'neq': u('\u2260'), # â‰  NOT EQUAL TO
    'ngeq': u('\u2271'), # â‰± NEITHER GREATER-THAN NOR EQUAL TO
    'ngtr': u('\u226f'), # â‰¯ NOT GREATER-THAN
    'ni': u('\u220b'), # âˆ‹ CONTAINS AS MEMBER
    'nleftarrow': u('\u219a'), # â†š LEFTWARDS ARROW WITH STROKE
    'nleftrightarrow': u('\u21ae'), # â†® LEFT RIGHT ARROW WITH STROKE
    'nleq': u('\u2270'), # â‰° NEITHER LESS-THAN NOR EQUAL TO
    'nless': u('\u226e'), # â‰® NOT LESS-THAN
    'nmid': u('\u2224'), # âˆ¤ DOES NOT DIVIDE
    'notasymp': u('\u226d'), # â‰­ NOT EQUIVALENT TO
    'notin': u('\u2209'), # âˆ‰ NOT AN ELEMENT OF
    'notowner': u('\u220c'), # âˆŒ DOES NOT CONTAIN AS MEMBER
    'notslash': u('\u233f'), # âŒ¿ APL FUNCTIONAL SYMBOL SLASH BAR
    'nparallel': u('\u2226'), # âˆ¦ NOT PARALLEL TO
    'nprec': u('\u2280'), # âŠ€ DOES NOT PRECEDE
    'npreceq': u('\u22e0'), # â‹  DOES NOT PRECEDE OR EQUAL
    'nrightarrow': u('\u219b'), # â†› RIGHTWARDS ARROW WITH STROKE
    'nsim': u('\u2241'), # â‰ NOT TILDE
    'nsubseteq': u('\u2288'), # âŠˆ NEITHER A SUBSET OF NOR EQUAL TO
    'nsucc': u('\u2281'), # âŠ DOES NOT SUCCEED
    'nsucceq': u('\u22e1'), # â‹¡ DOES NOT SUCCEED OR EQUAL
    'nsupseteq': u('\u2289'), # âŠ‰ NEITHER A SUPERSET OF NOR EQUAL TO
    'ntriangleleft': u('\u22ea'), # â‹ª NOT NORMAL SUBGROUP OF
    'ntrianglelefteq': u('\u22ec'), # â‹¬ NOT NORMAL SUBGROUP OF OR EQUAL TO
    'ntriangleright': u('\u22eb'), # â‹« DOES NOT CONTAIN AS NORMAL SUBGROUP
    'ntrianglerighteq': u('\u22ed'), # â‹­ DOES NOT CONTAIN AS NORMAL SUBGROUP OR EQUAL
    'nvDash': u('\u22ad'), # âŠ­ NOT TRUE
    'nvdash': u('\u22ac'), # âŠ¬ DOES NOT PROVE
    'nwarrow': u('\u2196'), # â†– NORTH WEST ARROW
    'owns': u('\u220b'), # âˆ‹ CONTAINS AS MEMBER
    'parallel': u('\u2225'), # âˆ¥ PARALLEL TO
    'perp': u('\u27c2'), # âŸ‚ PERPENDICULAR
    'pitchfork': u('\u22d4'), # â‹” PITCHFORK
    'prec': u('\u227a'), # â‰º PRECEDES
    'precapprox': u('\u2ab7'), # âª· PRECEDES ABOVE ALMOST EQUAL TO
    'preccurlyeq': u('\u227c'), # â‰¼ PRECEDES OR EQUAL TO
    'preceq': u('\u2aaf'), # âª¯ PRECEDES ABOVE SINGLE-LINE EQUALS SIGN
    'precnapprox': u('\u2ab9'), # âª¹ PRECEDES ABOVE NOT ALMOST EQUAL TO
    'precnsim': u('\u22e8'), # â‹¨ PRECEDES BUT NOT EQUIVALENT TO
    'precsim': u('\u227e'), # â‰¾ PRECEDES OR EQUIVALENT TO
    'propto': u('\u221d'), # âˆ PROPORTIONAL TO
    'restriction': u('\u21be'), # â†¾ UPWARDS HARPOON WITH BARB RIGHTWARDS
    'rightarrow': u('\u2192'), # â†’ RIGHTWARDS ARROW
    'rightarrowtail': u('\u21a3'), # â†£ RIGHTWARDS ARROW WITH TAIL
    'rightarrowtriangle': u('\u21fe'), # â‡¾ RIGHTWARDS OPEN-HEADED ARROW
    'rightbarharpoon': u('\u296c'), # â¥¬ RIGHTWARDS HARPOON WITH BARB UP ABOVE LONG DASH
    'rightharpoondown': u('\u21c1'), # â‡ RIGHTWARDS HARPOON WITH BARB DOWNWARDS
    'rightharpoonup': u('\u21c0'), # â‡€ RIGHTWARDS HARPOON WITH BARB UPWARDS
    'rightleftarrows': u('\u21c4'), # â‡„ RIGHTWARDS ARROW OVER LEFTWARDS ARROW
    'rightleftharpoon': u('\u294b'), # â¥‹ LEFT BARB DOWN RIGHT BARB UP HARPOON
    'rightleftharpoons': u('\u21cc'), # â‡Œ RIGHTWARDS HARPOON OVER LEFTWARDS HARPOON
    'rightrightarrows': u('\u21c9'), # â‡‰ RIGHTWARDS PAIRED ARROWS
    'rightrightharpoons': u('\u2964'), # â¥¤ RIGHTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB DOWN
    'rightslice': u('\u2aa7'), # âª§ GREATER-THAN CLOSED BY CURVE
    'rightsquigarrow': u('\u21dd'), # â‡ RIGHTWARDS SQUIGGLE ARROW
    'risingdotseq': u('\u2253'), # â‰“ IMAGE OF OR APPROXIMATELY EQUAL TO
    'searrow': u('\u2198'), # â†˜ SOUTH EAST ARROW
    'sim': u('\u223c'), # âˆ¼ TILDE OPERATOR
    'simeq': u('\u2243'), # â‰ƒ ASYMPTOTICALLY EQUAL TO
    'smallfrown': u('\u2322'), # âŒ¢ FROWN
    'smallsmile': u('\u2323'), # âŒ£ SMILE
    'smile': u('\u2323'), # âŒ£ SMILE
    'sqsubset': u('\u228f'), # âŠ SQUARE IMAGE OF
    'sqsubseteq': u('\u2291'), # âŠ‘ SQUARE IMAGE OF OR EQUAL TO
    'sqsupset': u('\u2290'), # âŠ SQUARE ORIGINAL OF
    'sqsupseteq': u('\u2292'), # âŠ’ SQUARE ORIGINAL OF OR EQUAL TO
    'subset': u('\u2282'), # âŠ‚ SUBSET OF
    'subseteq': u('\u2286'), # âŠ† SUBSET OF OR EQUAL TO
    'subseteqq': u('\u2ac5'), # â«… SUBSET OF ABOVE EQUALS SIGN
    'subsetneq': u('\u228a'), # âŠŠ SUBSET OF WITH NOT EQUAL TO
    'subsetneqq': u('\u2acb'), # â«‹ SUBSET OF ABOVE NOT EQUAL TO
    'succ': u('\u227b'), # â‰» SUCCEEDS
    'succapprox': u('\u2ab8'), # âª¸ SUCCEEDS ABOVE ALMOST EQUAL TO
    'succcurlyeq': u('\u227d'), # â‰½ SUCCEEDS OR EQUAL TO
    'succeq': u('\u2ab0'), # âª° SUCCEEDS ABOVE SINGLE-LINE EQUALS SIGN
    'succnapprox': u('\u2aba'), # âªº SUCCEEDS ABOVE NOT ALMOST EQUAL TO
    'succnsim': u('\u22e9'), # â‹© SUCCEEDS BUT NOT EQUIVALENT TO
    'succsim': u('\u227f'), # â‰¿ SUCCEEDS OR EQUIVALENT TO
    'supset': u('\u2283'), # âŠƒ SUPERSET OF
    'supseteq': u('\u2287'), # âŠ‡ SUPERSET OF OR EQUAL TO
    'supseteqq': u('\u2ac6'), # â«† SUPERSET OF ABOVE EQUALS SIGN
    'supsetneq': u('\u228b'), # âŠ‹ SUPERSET OF WITH NOT EQUAL TO
    'supsetneqq': u('\u2acc'), # â«Œ SUPERSET OF ABOVE NOT EQUAL TO
    'swarrow': u('\u2199'), # â†™ SOUTH WEST ARROW
    'to': u('\u2192'), # â†’ RIGHTWARDS ARROW
    'trianglelefteq': u('\u22b4'), # âŠ´ NORMAL SUBGROUP OF OR EQUAL TO
    'triangleq': u('\u225c'), # â‰œ DELTA EQUAL TO
    'trianglerighteq': u('\u22b5'), # âŠµ CONTAINS AS NORMAL SUBGROUP OR EQUAL TO
    'twoheadleftarrow': u('\u219e'), # â†ž LEFTWARDS TWO HEADED ARROW
    'twoheadrightarrow': u('\u21a0'), # â†  RIGHTWARDS TWO HEADED ARROW
    'uparrow': u('\u2191'), # â†‘ UPWARDS ARROW
    'updownarrow': u('\u2195'), # â†• UP DOWN ARROW
    'updownarrows': u('\u21c5'), # â‡… UPWARDS ARROW LEFTWARDS OF DOWNWARDS ARROW
    'updownharpoons': u('\u296e'), # â¥® UPWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT
    'upharpoonleft': u('\u21bf'), # â†¿ UPWARDS HARPOON WITH BARB LEFTWARDS
    'upharpoonright': u('\u21be'), # â†¾ UPWARDS HARPOON WITH BARB RIGHTWARDS
    'upuparrows': u('\u21c8'), # â‡ˆ UPWARDS PAIRED ARROWS
    'upupharpoons': u('\u2963'), # â¥£ UPWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT
    'vDash': u('\u22a8'), # âŠ¨ TRUE
    'varpropto': u('\u221d'), # âˆ PROPORTIONAL TO
    'vartriangleleft': u('\u22b2'), # âŠ² NORMAL SUBGROUP OF
    'vartriangleright': u('\u22b3'), # âŠ³ CONTAINS AS NORMAL SUBGROUP
    'vdash': u('\u22a2'), # âŠ¢ RIGHT TACK
    'vdots': u('\u22ee'), # â‹® VERTICAL ELLIPSIS
    }
mathunder = {
    'underbrace': u('\u23df'), # âŸ BOTTOM CURLY BRACKET
    }
space = {
    ':': u('\u205f'), # âŸ MEDIUM MATHEMATICAL SPACE
    'medspace': u('\u205f'), # âŸ MEDIUM MATHEMATICAL SPACE
    'quad': u('\u2001'), # â€ EM QUAD
    }
.. @+node:ekr.20130807203905.16763: *5* u test
@first # -*- coding: utf8 -*-

import sys

g.cls()

def u(s):
    try:
        val = None
        if sys.version_info < (3,):
            val = s if isinstance(s,unicode) else unicode(s,"unicode_escape")
        else:
            val = s if isinstance(s,str) else str(s,"unicode_escape")
    except UnicodeDecodeError:
        ### There seems to be a bug: '\\uxxx' is not handled properly.
        if 1:
            g.trace('UnicodeDecodeError',repr(s),'isunicode',isinstance(s,unicode))
        else:
            try:
                val = unicode(s,'ascii')
            except UnicodeDecodeError:
                g.trace('UnicodeDecodeError',repr(s))
    return val
        
@others

for ch in aList:
    # print(ch)
    assert not isinstance(ch,unicode),repr(ch)
    ch2 = u(ch)
    # print(repr(ch))
    # assert unicode(ch,"unicode_escape") == ch2,repr(ch)
print('pass')
.. @+node:ekr.20130807203905.16764: *6* from latex2e/__init__py
if 0:
    aList_with_u = (
    u('"'),
    u(r'\dq{}'),
    u(r'{\char`\"}'),
    u(r'\#'),
    u(r'\$'),
    u(r'\%'),
    u(r'\&'),
    u(r'\textasciitilde{}'),
    u(r'\_'),
    u(r'\textasciicircum{}'),
    u(r'\textbackslash{}'),
    u(r'\{'),
    u(r'\}'),
    u(r'{[}'),
    u(r'{]}'),
    u(r'\-'),                           # SOFT HYPHEN
    u(r'~'),                            # NO-BREAK SPACE
    u(r'\leavevmode\nobreak\vadjust{}~'),
    u(r'\,'),                           # PUNCTUATION SPACEâ€ˆâ€ˆâ€ˆ
    u(r'\hbox{-}'),                     # NON-BREAKING HYPHEN
    u(r'\,'),                           # NARROW NO-BREAK SPACE
    u(r'$\Leftrightarrow$'),
    u(r'$\spadesuit$'),
    u(r'$\clubsuit$'),
    u(r'\guillemotleft'),   # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
    u(r'\guillemotright'),  # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
    u(r'\textcompwordmark'), # ZERO WIDTH NON-JOINER
    u(r'\textendash{}'),
    u(r'\textemdash{}'),
    u(r'\textquoteleft{}'),
    u(r'\textquoteright{}'),
    u(r'\quotesinglbase{}'),    # SINGLE LOW-9 QUOTATION MARK
    u(r'\textquotedblleft{}'),
    u(r'\textquotedblright{}'),
    u(r'\quotedblbase{}'),      # DOUBLE LOW-9 QUOTATION MARK
    u(r'\textperthousand{}'),   # PER MILLE SIGN
    u(r'\textpertenthousand{}'), # PER TEN THOUSAND SIGN
    u(r'\guilsinglleft{}'),
    u(r'\guilsinglright{}'),
    u(r'\textvisiblespace{}'),  # OPEN BOX
    u(r'\dag{}'),
    u(r'\ddag{}'),
    u(r'\dots{}'),
    u(r'\texttrademark{}'),
    u(r'\textcent{}'),          # Â¢ CENT SIGN
    u(r'\textcurrency{}'),      # Â¤ CURRENCY SYMBOL
    u(r'\textyen{}'),           # Â¥ YEN SIGN
    u(r'\textbrokenbar{}'),     # Â¦ BROKEN BAR
    u(r'\textsection{}'),       # Â§ SECTION SIGN
    u(r'\textasciidieresis{}'), # Â¨ DIAERESIS
    u(r'\textcopyright{}'),     # Â© COPYRIGHT SIGN
    u(r'\textordfeminine{}'),   # Âª FEMININE ORDINAL INDICATOR
    u(r'\textlnot{}'),          # Â¬ NOT SIGN
    u(r'\textregistered{}'),    # Â® REGISTERED SIGN
    u(r'\textasciimacron{}'),   # Â¯ MACRON
    u(r'\textdegree{}'),        # Â° DEGREE SIGN
    u(r'\textpm{}'),            # Â± PLUS-MINUS SIGN
    u(r'\texttwosuperior{}'),   # Â² SUPERSCRIPT TWO
    u(r'\textthreesuperior{}'), # Â³ SUPERSCRIPT THREE
    u(r'\textasciiacute{}'),    # Â´ ACUTE ACCENT
    u(r'\textmu{}'),            # Âµ MICRO SIGN
    u(r'\textparagraph{}'),     # Â¶ PILCROW SIGN # not equal to \textpilcrow
    u(r'\textonesuperior{}'),   # Â¹ SUPERSCRIPT ONE
    u(r'\textordmasculine{}'),  # Âº MASCULINE ORDINAL INDICATOR
    u(r'\textonequarter{}'),    # 1/4 FRACTION
    u(r'\textonehalf{}'),       # 1/2 FRACTION
    u(r'\textthreequarters{}'), # 3/4 FRACTION
    u(r'\texttimes{}'),         # Ã— MULTIPLICATION SIGN
    u(r'\textdiv{}'),           # Ã· DIVISION SIGN
    u(r'\textflorin{}'),        # LATIN SMALL LETTER F WITH HOOK
    u(r'\textasciiacute{}'),    # MODIFIER LETTER PRIME
    u(r'\textacutedbl{}'),      # MODIFIER LETTER DOUBLE PRIME
    u(r'\textbardbl{}'),        # DOUBLE VERTICAL LINE
    u(r'\textbullet{}'),        # BULLET
    u(r'\textasciiacute{}'),    # PRIME
    u(r'\textacutedbl{}'),      # DOUBLE PRIME
    u(r'\textasciigrave{}'),    # REVERSED PRIME
    u(r'\textgravedbl{}'),      # REVERSED DOUBLE PRIME
    u(r'\textreferencemark{}'), # REFERENCE MARK
    u(r'\textinterrobang{}'),   # INTERROBANG
    u(r'\textfractionsolidus{}'), # FRACTION SLASH
    u(r'\textlquill{}'),        # LEFT SQUARE BRACKET WITH QUILL
    u(r'\textrquill{}'),        # RIGHT SQUARE BRACKET WITH QUILL
    u(r'\textdiscount{}'),      # COMMERCIAL MINUS SIGN
    u(r'\textcolonmonetary{}'), # COLON SIGN
    u(r'\textfrenchfranc{}'),   # FRENCH FRANC SIGN
    u(r'\textlira{}'),          # LIRA SIGN
    u(r'\textnaira{}'),         # NAIRA SIGN
    u(r'\textwon{}'),           # WON SIGN
    u(r'\textdong{}'),          # DONG SIGN
    u(r'\texteuro{}'),          # EURO SIGN
    u(r'\textpeso{}'),          # PESO SIGN
    u(r'\textguarani{}'),       # GUARANI SIGN
    u(r'\textcelsius{}'),       # DEGREE CELSIUS
    u(r'\textnumero{}'),        # NUMERO SIGN
    u(r'\textcircledP{}'),      # SOUND RECORDING COYRIGHT
    u(r'\textrecipe{}'),        # PRESCRIPTION TAKE
    u(r'\textservicemark{}'),   # SERVICE MARK
    u(r'\texttrademark{}'),     # TRADE MARK SIGN
    u(r'\textohm{}'),           # OHM SIGN
    u(r'\textmho{}'),           # INVERTED OHM SIGN
    u(r'\textestimated{}'),     # ESTIMATED SYMBOL
    u(r'\textleftarrow{}'),     # LEFTWARDS ARROW
    u(r'\textuparrow{}'),       # UPWARDS ARROW
    u(r'\textrightarrow{}'),    # RIGHTWARDS ARROW
    u(r'\textdownarrow{}'),     # DOWNWARDS ARROW
    u(r'\textminus{}'),         # MINUS SIGN
    u(r'\textasteriskcentered{}'), # ASTERISK OPERATOR
    u(r'\textsurd{}'),          # SQUARE ROOT
    u(r'\textblank{}'),         # BLANK SYMBOL
    u(r'\textopenbullet{}'),    # WHITE BULLET
    u(r'\textbigcircle{}'),     # LARGE CIRCLE
    u(r'\textmusicalnote{}'),   # EIGHTH NOTE
    u(r'\textmarried{}'),       # MARRIAGE SYMBOL
    u(r'\textdivorced{}'),      # DIVORCE SYMBOL
    u(r'\textlangle{}'),        # MATHEMATICAL LEFT ANGLE BRACKET
    u(r'\textrangle{}'),        # MATHEMATICAL RIGHT ANGLE BRACKET
    u(r'\ding{170}'),     # black heartsuit
    u(r'\ding{169}'),     # black diamondsuit
    u(r'\ding{51}'),      # check mark
    u(r'\ding{55}'),      # check mark
    u("Cannot embed stylesheet '%s':\n  %s."),
    # Causes problems.     
    u('\\underline{~}'), 
    u(r'\reflectbox{/}'),
    u(r'\textbar{}'),
    u(r'\textless{}'),
    u(r'\textgreater{}'),
    u(r'~'),
    u('$%s$'),                        
    u(r'\#'),
    u(r'\%'),
    u(r'\\'),       
    u('â€”'),
)

# wrapper = u('\n').join(['%%',
     # r'\begin{%s}' % math_env,
     # '%s',
     # r'\end{%s}' % math_env])

unicode_aList = (
    u'"',
    ur'\dq{}',
    ur'{\char`\"}',
    ur'\#',
    ur'\$',
    ur'\%',
    ur'\&',
    ur'\textasciitilde{}',
    ur'\_',
    ur'\textasciicircum{}',
    ur'\textbackslash{}',
    ur'\{',
    ur'\}',
    ur'{[}',
    ur'{]}',
    ur'\-',
    ur'~',
    ur'\leavevmode\nobreak\vadjust{}~',
    ur'\,',
    ur'\hbox{-}',
    ur'\,',
    ur'$\Leftrightarrow$',
    ur'$\spadesuit$',
    ur'$\clubsuit$',
    ur'\guillemotleft',
    ur'\guillemotright',
    ur'\textcompwordmark',
    ur'\textendash{}',
    ur'\textemdash{}',
    ur'\textquoteleft{}',
    ur'\textquoteright{}',
    ur'\quotesinglbase{}',
    ur'\textquotedblleft{}',
    ur'\textquotedblright{}',
    ur'\quotedblbase{}',
    ur'\textperthousand{}',
    ur'\textpertenthousand{}',
    ur'\guilsinglleft{}',
    ur'\guilsinglright{}',
    ur'\textvisiblespace{}',
    ur'\dag{}',
    ur'\ddag{}',
    ur'\dots{}',
    ur'\texttrademark{}',
    ur'\textcent{}',
    ur'\textcurrency{}',
    ur'\textyen{}',
    ur'\textbrokenbar{}',
    ur'\textsection{}',
    ur'\textasciidieresis{}',
    ur'\textcopyright{}',
    ur'\textordfeminine{}',
    ur'\textlnot{}',
    ur'\textregistered{}',
    ur'\textasciimacron{}',
    ur'\textdegree{}',
    ur'\textpm{}',
    ur'\texttwosuperior{}',
    ur'\textthreesuperior{}',
    ur'\textasciiacute{}',
    ur'\textmu{}',
    ur'\textparagraph{}',
    ur'\textonesuperior{}',
    ur'\textordmasculine{}',
    ur'\textonequarter{}',
    ur'\textonehalf{}',
    ur'\textthreequarters{}',
    ur'\texttimes{}',
    ur'\textdiv{}',
    ur'\textflorin{}',
    ur'\textasciiacute{}',
    ur'\textacutedbl{}',
    ur'\textbardbl{}',
    ur'\textbullet{}',
    ur'\textasciiacute{}',
    ur'\textacutedbl{}',
    ur'\textasciigrave{}',
    ur'\textgravedbl{}',
    ur'\textreferencemark{}',
    ur'\textinterrobang{}',
    ur'\textfractionsolidus{}',
    ur'\textlquill{}',
    ur'\textrquill{}',
    ur'\textdiscount{}',
    ur'\textcolonmonetary{}',
    ur'\textfrenchfranc{}',
    ur'\textlira{}',
    ur'\textnaira{}',
    ur'\textwon{}',
    ur'\textdong{}',
    ur'\texteuro{}',
    ur'\textpeso{}',
    ur'\textguarani{}',
    ur'\textcelsius{}',
    ur'\textnumero{}',
    ur'\textcircledP{}',
    ur'\textrecipe{}',
    ur'\textservicemark{}',
    ur'\texttrademark{}',
    ur'\textohm{}',
    ur'\textmho{}',
    ur'\textestimated{}',
    ur'\textleftarrow{}',
    ur'\textuparrow{}',
    ur'\textrightarrow{}',
    ur'\textdownarrow{}',
    ur'\textminus{}',
    ur'\textasteriskcentered{}',
    ur'\textsurd{}',
    ur'\textblank{}',
    ur'\textopenbullet{}',
    ur'\textbigcircle{}',
    ur'\textmusicalnote{}',
    ur'\textmarried{}',
    ur'\textdivorced{}',
    ur'\textlangle{}',
    ur'\textrangle{}',
    ur'\ding{170}',
    ur'\ding{169}',
    ur'\ding{51}',
    ur'\ding{55}',
    u"Cannot embed stylesheet '%s':\n  %s.",
    u'\\underline{~}', # Can not use ur('\uxxxx) because that is a unicode escapse!!
    ur'\reflectbox{/}',
    ur'\textbar{}',
    ur'\textless{}',
    ur'\textgreater{}',
    ur'~',
    u'$%s$',
    # ur'\'
    ur'\%',
    ur'\\',
    u'â€”',
)

aList = (
    '"',
    r'\dq{}',
    r'{\char`\"}',
    r'\#',
    r'\$',
    r'\%',
    r'\&',
    r'\textasciitilde{}',
    r'\_',
    r'\textasciicircum{}',
    r'\textbackslash{}',
    r'\{',
    r'\}',
    r'{[}',
    r'{]}',
    r'\-',
    r'~',
    r'\leavevmode\nobreak\vadjust{}~',
    r'\,',
    r'\hbox{-}',
    r'\,',
    r'$\Leftrightarrow$',
    r'$\spadesuit$',
    r'$\clubsuit$',
    r'\guillemotleft',
    r'\guillemotright',
    r'\textcompwordmark',
    r'\textendash{}',
    r'\textemdash{}',
    r'\textquoteleft{}',
    r'\textquoteright{}',
    r'\quotesinglbase{}',
    r'\textquotedblleft{}',
    r'\textquotedblright{}',
    r'\quotedblbase{}',
    r'\textperthousand{}',
    r'\textpertenthousand{}',
    r'\guilsinglleft{}',
    r'\guilsinglright{}',
    r'\textvisiblespace{}',
    r'\dag{}',
    r'\ddag{}',
    r'\dots{}',
    r'\texttrademark{}',
    r'\textcent{}',
    r'\textcurrency{}',
    r'\textyen{}',
    r'\textbrokenbar{}',
    r'\textsection{}',
    r'\textasciidieresis{}',
    r'\textcopyright{}',
    r'\textordfeminine{}',
    r'\textlnot{}',
    r'\textregistered{}',
    r'\textasciimacron{}',
    r'\textdegree{}',
    r'\textpm{}',
    r'\texttwosuperior{}',
    r'\textthreesuperior{}',
    r'\textasciiacute{}',
    r'\textmu{}',
    r'\textparagraph{}',
    r'\textonesuperior{}',
    r'\textordmasculine{}',
    r'\textonequarter{}',
    r'\textonehalf{}',
    r'\textthreequarters{}',
    r'\texttimes{}',
    r'\textdiv{}',
    r'\textflorin{}',
    r'\textasciiacute{}',
    r'\textacutedbl{}',
    r'\textbardbl{}',
    r'\textbullet{}',
    r'\textasciiacute{}',
    r'\textacutedbl{}',
    r'\textasciigrave{}',
    r'\textgravedbl{}',
    r'\textreferencemark{}',
    r'\textinterrobang{}',
    r'\textfractionsolidus{}',
    r'\textlquill{}',
    r'\textrquill{}',
    r'\textdiscount{}',
    r'\textcolonmonetary{}',
    r'\textfrenchfranc{}',
    r'\textlira{}',
    r'\textnaira{}',
    r'\textwon{}',
    r'\textdong{}',
    r'\texteuro{}',
    r'\textpeso{}',
    r'\textguarani{}',
    r'\textcelsius{}',
    r'\textnumero{}',
    r'\textcircledP{}',
    r'\textrecipe{}',
    r'\textservicemark{}',
    r'\texttrademark{}',
    r'\textohm{}',
    r'\textmho{}',
    r'\textestimated{}',
    r'\textleftarrow{}',
    r'\textuparrow{}',
    r'\textrightarrow{}',
    r'\textdownarrow{}',
    r'\textminus{}',
    r'\textasteriskcentered{}',
    r'\textsurd{}',
    r'\textblank{}',
    r'\textopenbullet{}',
    r'\textbigcircle{}',
    r'\textmusicalnote{}',
    r'\textmarried{}',
    r'\textdivorced{}',
    r'\textlangle{}',
    r'\textrangle{}',
    r'\ding{170}',
    r'\ding{169}',
    r'\ding{51}',
    r'\ding{55}',
    "Cannot embed stylesheet '%s':\n  %s.",
    '\\' + 'underline{~}', # Can not use ur('\uxxxx) because that is a unicode escapse!!
    r'\reflectbox{/}',
    r'\textbar{}',
    r'\textless{}',
    r'\textgreater{}',
    r'~',
    '$%s$',
    # r'\'
    r'\%',
    r'\\',
    # u'â€”',
)

# wrapper = u('\n').join(['%%',
     # r'\begin{%s}' % math_env,
     # '%s',
     # r'\end{%s}' % math_env])

.. @+node:ekr.20130807203905.16765: *4* Files with u and ur constants
ur constants:
    
writers\manpage.py
writers\latex2e\__init__.py
utils\math\latex2matchml.py

u constants:

core.py
frontend.py
io.py
nodes.py
statemachine.py
__init__.py
languages\ca.py
languages\cs.py
languages\eo.py
languages\es.py
languages\fi.py
languages\fr.py
languages\gl.py
languages\he.py
languages\ja.py
languages\lt.py
languages\pl.py
languages\pt_br.py
languages\ru.py
languages\sk.py
languages\sv.py
languages\zh_cn.py
languages\zh_tw.py
parsers\rst\states.py
parsers\rst\directives\body.py
parsers\rst\directives\misc.py
parsers\rst\directives\tables.py
parsers\rst\directives\__init__.py
parsers\rst\languages\af.py
parsers\rst\languages\ca.py
parsers\rst\languages\cs.py
parsers\rst\languages\de.py
parsers\rst\languages\eo.py
parsers\rst\languages\es.py
parsers\rst\languages\fi.py
parsers\rst\languages\fr.py
parsers\rst\languages\gl.py
parsers\rst\languages\he.py
parsers\rst\languages\it.py
parsers\rst\languages\ja.py
parsers\rst\languages\lt.py
parsers\rst\languages\nl.py
parsers\rst\languages\pl.py
parsers\rst\languages\pt_br.py
parsers\rst\languages\ru.py
parsers\rst\languages\sk.py
parsers\rst\languages\sv.py
parsers\rst\languages\zh_cn.py
parsers\rst\languages\zh_tw.py
transforms\parts.py
transforms\references.py
utils\error_reporting.py
utils\punctuation_chars.py
utils\smartquotes.py
utils\__init__.py
utils\math\latex2mathml.py
utils\math\math2html.py
utils\math\tex2unichar.py
utils\math\unichar2tex.py
writers\manpage.py
writers\html4css1\__init__.py
writers\latex2e\__init__.py
writers\odf_odt\__init__.py
writers\xetex\__init__.py
.. @+node:ekr.20131001045038.19027: *3* Quotes from "Why Leo isn't more popular"
@language rest
.. @+node:ekr.20131001045038.19028: *4* Fidel
When I say Learn Leo, I don't mean Learn or understand the code, I mean
learn what you can do with it.

My true feeling is that Leo is like an infinite ground, where amazing
things can be built. Some of Leo users are already doing incredible things
with it. But when you are new to Leo, you first have to learn the physics
of this new world (Leo Code), and then develop your own engineering (Useful
outlines structures) for building your "information cities"...

Possibly, experienced leo users dont share this view since they learned Leo
physics and engineering long time ago, but those look like a big wall when
starting with Leo.

So Leo files with samples would be like delivering this infinite ground
with some pre-built "information cities" so people can begin using them
right away. Ideally, those leo files should guide the user on how to build
new structures, and in the end, be able to lead him to generate new
structures.

My (again, personal) feeling is that the current policy right now is: Let
him read the code to understand how it works. So only the users willing to
go through the (1) Learn the physics then (2) develop your own way to
develop "information cities" can actually use leo and use its potential.

Since most of the internet users are the ones who need the cities already
built for them to use software, thats the chunk we are loosing.

On the other hand, coming to why programmers (who have the skills to go
through Leo learning process) dont come and use it, its the same story:

Before coming into Leo, what I was doing was actually search for an IDE
that I liked. I went through several, and in the ones I "liked" the most,
it would take you around two hours learning for having a folder with your
scripts and being able to edit them. With Leo, you first have to study and
understand what are directives, how do they work, how everything interacts
in the tree, etc. It takes more than two hours. I would say that it can be
measured in weeks or months until you really know what you are doing.

And here is where the "information cities" come again. If Leo were provided
with an interactive Leo file, which would guide you into: - Importing your
scripts to Leo - Clearly create folders and move/manage your files there -
Suggest directives for those files. - Etc.

That Leo file would save the new user many many hours and he would
instantly start using leo, so we would help him skip the first wall and
begin to get interested.

So then again, this is why I still see that Leo default workbook should be
dispatched with a Leo cheatsheet open by default, so new users begin to
play with it as soon as they open Leo.
.. @+node:ekr.20131001045038.19029: *4* Jacob Peck
Leo represents a completely new paradigm for editing, programming, and
interacting with data. Well, not completely new, but for many the surface
level seems extremely foreign.

Leo is primarily a tool aimed at python...the paradigm it exposes to the
user is far more like Lisp (homoiconicity via the Node and Tree structure)
and Smalltalk (.leo files save *most* of your programming environment's
state, including data). This is a huge cognitive leap for people only
accustomed to more imperative languages like Python...Leo asks a lot of

-----

​The PIM aspect was what initially led me to Leo. Wikipedia pointed me in
Leo's direction while searching for some good open-source PIM tools. I
tried Chandler but it didn't do what I wanted. Leo did.

.. @+node:ekr.20131001045038.19030: *4* Kent
Re: the original question "Why isn't Leo more popular" I can ask myself
"Why don't I adopt tools which promise a better way to work?" I do a lot of
grazing, and encounter very many such tools.

A tool which does everything doesn't grab me, I don't need to do
everything. A tool which, in it's few moments of my attention, describes a
better way to do something I need, gets additional moments. If the tool
salesperson mentions a task I encounter and a better way to do it, with a
learning curve which justifies the benefit ... I will settle in for a
while.

Easier, more powerful boilerplates / templates / completion is the kind of
bait I'll bite on, there's potential for decent return on investment.
.. @+node:ekr.20131001045038.19031: *4* Fidel
With "bread crumbs" I refer to...the interactive tutorial creator I have
talked so much about. My aim with this tool is that anything you do,
instantly becomes a tutorial, that can be done again and played forward and
backwards. Basically, your actions become an outline, and other users can
"play them" again. This should mean that making a tutorial will take as
much time as it takes for you to perform the action originally.
.. @+node:ekr.20131001045038.19032: *4* dufriz
As a newbie, I agree. At least, that is the perception, which is
discouraging. I believe it also has to do with the lack of learning
material. The only manual is not very newbie-friendly. It contains a lot of
cross-references to advanced internal commands (@xyz stuff) which put off
newcomers, especially where they are thrown in altogether and may look
scary.

Currently the learning curve does nor _appear_ to be gentle at all. But it
does not necessarily have to be like this. Even if Leo is indeed very
complex and very advanced, I am sure that at least a subset of Leo
functionality can be selected and presented in a nicer way, to attract more
users and help newbies.

Why can't we have some more accessible tutorial, with gentle, self
contained lessons (maybe webcasts, or slides, or simple HTML pages) which
_focus on the basic functionality_? Or perhaps, a two-tiered series of such
lessons, i.e. basic and advanced levels. I think this would be very
helpful.

-----

Another point: Leo is commonly advertised as a programming editor, but it
should be made more clear that it is more than that.

I believe you would attract more users if you also mentioned its usefulness
for general-purpose editing and PIM functionality. Of course, that may be
implicit, but I think you should be putting some more emphasis on this
aspect.

----- 

For me, the trajectory was KeyNote --> MyBase --> NotecasePro/RightNote -->
Leo (!!)

Leo is the best, because it is fully customizable, and gives you seemingly
infinite power. Only, it takes a lot to learn how to use that power.
.. @+node:ekr.20131001045038.19034: *4* dufriz
Consider that Leo is actively developed, and has a responsive community.
When I requested the support for Rich Text, a couple of months ago, it was
promptly implemented in a matter of days.

As for the power, of course Leo can do whatever other PIMs can do, because
it is extensible by Python. The question is whether enough people are
interested in Leo as a PIM, so as to have enough user contributions. I am
still at the beginning, so I have no idea how difficult it may be,
technically, to impement all the PIM features that we need. But if we
succeed in getting enough people interested, I am sure that nothing is
beyond our reach.

As far as PIM features go the next step, I believe, is implementing a good
tagging system.
.. @+node:ekr.20131003040744.18223: *4* dufriz **
As a newbie who still has zero knowledge of Leo's technical details, I can
say: I have absolutely no problem in conceptualizing what Leo is and what
it can do, and probably I also get the Leo's aha -- the difficulty is in
getting into the actual technical aspects of the program. Again, in the end
this all boils down to newbie-friendly tutorials and learning materials...
Something like Leo for dummies would be greatly appreciated.

.. @+node:ekr.20131001045038.19035: *4* Terry
I think a lot of the problem is defining what Leo is. In some ways I think
it's Python's Squeak (Squeak http://www.squeak.org/Screenshots/ being a
SmallTalk environment where everything's an object).

If all you want is an off the shelf turn key text editor with perhaps
completion and syntax highlighting as its most advanced features, then
there are several out there that are probably going to appeal more than
Leo.

If you're looking for an off the shelf turn key outliner, without the
intent to use scripts etc., then again there are lots of alternatives, some
of which probably seem more intuitive / simpler / even more feature rich
than Leo. (The feature rich part is probably misleading, but they may seem
that way initially).

If your looking for an *environment* which includes a good editor and
outliner and is completely scriptable / interactive / "live-code" in
Python, then Leo wins hands down. Of course, it's basically alone in this
field, as far as I know, but I'm sure it would do well even if it
wasn't...I guess Emacs is sort of an environment like this, only in Lisp
with a prehistoric GUI system.

Sometimes I've wondered why Leo seems to appeal to people who aren't
comfortable in Python, I think now it's because they still recognize the
value of an *environment*, and there's just not much in this niche. So to
me it's more why don't more people want an environment like this...

My feeling, talking generally and not about Leo in particular, is that
while not everyone needs to be a "programmer", everyone who uses computers
would benefit from being able to interact with them with more of the
flexibility and efficiency that comes with even relatively simple
"scripting", and less of the limitations that come with the "buy our latest
product and you'll be able to do anything you want with a click" view
pushed by other suppliers of computing environments.
.. @+node:ekr.20131001045038.19036: *4* Miles Fidelman (improve wiki)
In that regard, Leo is barely mentioned on WikiPedia - it has a simple
descriptive page, but on the list of text editors it's listed, but there's
no information about o/s support or features.

For marketing, packaging, features, documentation, tutorials,
extensions,... - do a side by side comparison of Vim and Leo - and the
answer(s) to "why leo isn't more popular" leap out at you.
.. @+node:ekr.20131001045038.19038: *4* Chris George
I came to Leo because it is the only outliner for Linux that supports
cloning that doesn't require an internet connection.

I am struggling to implement it into my workflow though, simply because I
do not have time to figure out the simplest things. (full time university
student) Right now I simply do not have the 200 minutes available to figure
this out. Yet I can see that if I took the time to do my own setup it would
save me far more time in the future. Leo would be a wonderful platform for
writing anything, but especially for fiction. If there was a tutorial on
setting up Leo to do the following, I know there would be immediate
interest from people who write on Linux as there simply is not an outliner
that meets the needs of the average writer.

I need basic text formatting at the standard hot key level. ie. Ctrl-B for
bold, Ctrl-I for italic etc. while in the edit window. I know this can be
done, I almost had it working once but then got busy and by the time I came
back it had escaped me how I had done it. I don't need buttons, I don't
need WSIWYG, RST markup works fine as it gives me lots of output options. I
just need the ability to put my head down and write, using the shortcuts
that are baked into my fingertips at this point, and not having to relearn
those keys. Support for standard word-processing keys are important for
writers. :-)

I think that by creating tutorials that address the basics for different
groups of users who are not programmers, Leo could be an extremely popular
program. I would be willing to contribute to such an effort for writers if
I can get a workflow setup that makes sense for me. My current editor of
choice is Scrivener for Windows run using Crossover. No cloning. :-(

Leo is far too complex for the average person who simply wants to
accomplish a task. Simplifying things for specific classes of users would
open Leo up to many more people who share those requirements and may be
interested in learning the rest of the power of Leo as their use of it
increases. Give people a foot in the door and they will figure out how to
open it the rest of the way as needed.
.. @+node:ekr.20131001045038.19039: *4* Chris George
i.e. RST markup for "bold".  Is that the goal?

Cheers -Terry

Almost. That plus the ability to be writing along and hit
Ctrl-b s u d d e n l y Ctrl-b and continue on.

I had Leo working to the extent that I could type suddenly Ctrl-Alt-b and
have it retroactively add the markup but it was simply too much of a leap
to change my work habits. Body memory takes years to develop and is not
trivial to attempt to change.

A set of keybindings that mimic the standard word processing key bindings
that then markup the text using RST or Markdown would be a huge step
forward for me in using Leo. Right now I try to find time to fiddle and
play with it, but that has been going on for almost two years now and I
have yet to commit to any serious work in Leo.

===== Terry

Which boils down to Ctrl-b inserting '*' if there's no selection?

I guess it does.

It may seem silly, as I could just type the *, but Shift-8 isn't baked into
muscle memory, Ctrl-b is.

It boils down to being able to replicate those standard word processing
shortcuts in the edit pane and having them not conflict with other key
combos in Leo. Abstracting it to other markup languages would be cool as
well, some people like RST, some people like Markdown. Everyone can use
Ctrl-b.

Ckeditor looks interesting, but it isn't the buttons that matter. I rarely
use the mouse for marking up text.

==== Terry

Quick stab at
https://github.com/leo-editor/snippets/blob/master/ctrl_b_i_u.py
not very tested.

.. @+node:ekr.20131001045038.19040: *4* Terry's new code
In you myLeoSettings.leo file, under @settings-->@keys-->@shortcuts,
add the shrotcuts (in the body text of the '@shortcuts' node:

markup_inline_bold ! body = Ctrl-B
markup_inline_italic ! body = Ctrl-I
markup_inline_underline ! body = Ctrl-U

restart Leo

Put the downloaded code in a node, and run it... normally you'd do that
by hitting Ctrl-B, but we just redefined that :-)  So use alt-x
execute-script instead.

Now in the body you should be able to get

**bold** *italic* :ul:`underline`

with the expected keys.  It should be fairly predictable when there's a
selection active.  When there isn't, it just opens or closes the markup
type depending on whether the last action was an open or close, so I
guess nesting would be problem, but rst doesn't understand nesting
inline markup anyway.

The difference between open and close only applies to underline, where
the beginning and end delimiters are different - more a demo than
anything.

To make the code active without the execute-script step it could be
placed in a node which starts with @script, although you need
@bool scripting-at-script-nodes = True
under your @settings node then.

Ideally it would be in a plugin (although it seems heavy to put
essentially one function in a plugin) or core, so it didn't need its
own node in the target outline or @settings.
.. @+node:ekr.20131001045038.19041: *4* Chris George
I would like to start putting together everything that it would take to
make Leo the default choice for writers on Linux. If it works for me, it'll
work for many others.
.. @+node:ekr.20131001045038.19042: *4* Terry's new markup_inline plugin
> How difficult would a plugin be?

Easy enough I guess, included in revision 6083, just pushed.

In myLeoSettings.leo, under @settings-->@keys-->@shortcuts::

    markup-inline-bold ! body = Ctrl-B
    markup-inline-italic ! body = Ctrl-I
    markup-inline-underline ! body = Ctrl-U

  - Use Help -> leoSettings.leo to open leoSettings.leo, and copy
    the @enabled-plugins node
    
  - paste this node into your myLeoSettings.leo as a child of the
    @settings node
    
  - just before the line in @enabled-plugins where it says
    "# Alphabetical list of all Leo plugins" add a line:

    markup_inline.py
.. @+node:ekr.20131001045038.19043: *4* Ludwig Schwardt: MacOS brew instructions
Miles's comments inspired me to do something about the Homebrew version of
Leo. Instead of following a long-winded and increasingly out-of-date set of
installation instructions you will soon be able to go (if all goes well!):

brew install leo

I've created a rough formula for Leo and uploaded it to my Homebrew tap. To
try it out, do the following:

- Get Homebrew from http://brew.sh/, following their instructions on how to
install it

- Pay special attention to Python - if you have already installed a bunch
of Python stuff, it's best to keep using the existing Python. Otherwise, if
this is your first Python experience it is safe to install the Homebrew
Python (which will make your life easier) via

  brew install python

  (If all your existing Python tools suddenly disappear, go 'brew remove
  python' to restore order :-))

- Get my formulas:

  brew tap ska-sa/tap

- Et voila:

  brew install leo

- If you kept your old Python, follow the instruction in the caveat printed
at the end of:

  brew info leo

  (I.e. add the suggested line to your ~/.bash_profile file if you are not
  using Homebrew Python)

The formula has three versions:

  brew install leo => installs the latest stable release (4.10)
  brew install --devel leo => installs latest alpha (4.11-a2)
  brew install --HEAD leo => installs the bleeding-edge bzr version from Launchpad

It also installs PyEnchant by default (which can be disabled).

I would love some testing of the installation before I submit it to the
main Homebrew repository (if you guys think the formula is a good idea). I
don't use Leo myself and have only done some cursory poking around.

Miles's point about using a Ruby-based installer to install a Python
package also rings true (although this is becoming more popular these days
on the Mac given how awesome Homebrew is for dependencies and Python
extensions, and this is not any stranger than the C-based "apt-get install
leo").

I would expect to install a Python package such as Leo using "pip install
leo" or "easy_install leo". The main problem has always been that Leo has a
non-standard package layout.

I (only now!) see that Ville, Matt and others have created a setup.py and
leo even exists on PyPI so that these installation commands actually do
something. Unfortunately, for me "pip install leo" results in a Leo that
throws an AssertionError upon running. What is the status of this
installation route? (It is not even mentioned on the installation page!)
Also, "leo 4.10-final" on PyPI actually installs "4.11-devel"...
.. @+node:ekr.20131001045038.19044: *4* EKR
> My (again, personal) feeling is that the current policy right now is: Let
him read the code to understand how it works. So only the users willing to
go through the (1) Learn the physics then (2) develop your own way to
develop "information cities" can actually use leo and use its potential.

​I've spent a lot of time on tutorials, slideshows, etc. However, in light
of your first sentence quoted above, it does seem like I have neglected to
show what people can really do with Leo, at least in the tutorial docs. ​
 
> With Leo, you first have to study and understand what are directives, how
do they work, how everything interacts in the tree, etc. It takes more than
two hours. I would say that it can be measured in weeks or months until you
really know what you are doing.

Maybe, but there is a tantalizing possibility. ​I prototyped Leo in about
two hours, using the MORE outliner as a prototype, and inventing @others in
the process. (I was already deeply involved with sections and section
references.)

So for *me*, the Leo aha was almost instantaneous, once I had an outliner
to prototype my thoughts. Since then, things have become more "voluminous",
yet Leo's DOM is so much simpler and more powerful than it was in the early
days. Do these improvement make Leo *more* difficult to learn? It's hard to
believe so, but then nobody is closer to Leo than I.

> And here is where the "information cities" come again. If Leo were
provided with an interactive Leo file, which would guide you ​...

​The idea of putting a cheat sheet into the default workbook.leo is a great
one. There will be a default_workbook.leo in leo/docs, and the code that
creates ~/workbook.leo will make a copy of the default file. This will
allow continuous improvement on default_workbook.leo.
.. @+node:ekr.20131001045038.19045: *4* EKR
> For marketing, packaging, features, documentation, tutorials,
extensions,... - do a side by side comparison of Vim and Leo - and the
answer(s) to "why leo isn't more popular" leap out at you.


​The answer is not so clear cut.​ Consider the first item returned by
Google for the search "emacs tutorial":
http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html

This is hardly a breathtaking introduction to emacs. It would not *by
itself* convert people to emacs. It doesn't even highlight what I consider
the most important Aha about emacs, namely that you don't have to remember
(or type) commands with long names!

No, the reason emacs is popular is that it continues to be taught as *the*
programming editor to generations of computer-programming students. The
students learn *from each other*, using a tedious "tutorial" as a
reference. They learn from looking over each other's shoulders.

Leo would be just as popular, imo, if thousands of college students learned
Leo from each other. This does not excuse lack of further work on Leo
tutorials, but this *is* the essence of the situation.
.. @+node:ekr.20131001100335.15927: *4* Links to Book about Leo
This e-book has a whole sub-heading on using Leo for Joomla:
http://www.gandsnut.net/downloads/Beginning_Joomla!_From_Novice_to_Professional.pdf

amazon link:
http://www.amazon.com/Beginning-Joomla-From-Novice-Professional/dp/1590598482/ref=sr_1_1?ie=UTF8&qid=1380681874&sr=8-1&keywords=beginning+joomla+from+novice+to+professional
.. @+node:ekr.20131001100335.15926: *4* derwish
To me, it's to directed acyclic graphs what MS Excel is to tables. 
.. @+node:ekr.20131012060912.16765: *4* matt
What an enormously long and interesting thread!

Thanks for the sub-thread on using Leo for plain ol' writing. It rings true
for me. Leo doesn't leverage much of my prior muscle memory, and that leads
me away from it, and once away it takes awhile to return. This is still
true even though I've been using Leo for half a decade now, and have even
contributed a small thing or two to the bzr repository.

I generally use notepad2, notepad++ for quick and dirty scripts (usually
Windows batch files), editing .ini,.conf, xml etc., etc. files. Way fast
startup time and their syntax highlighting know more file types and is more
reliable (complete). They also grok (some) regular expressions.

I use vim (+cream) when I want to do search and replace, which happens a
lot. I just never figured out how to use this properly in Leo;
`[esc]:%s/old-thing/new-thing/g` is just so much faster (modulo the
significant time it takes to construct regular expressions that actually
work!). Saved mini-buffer commands across sessions is also very handy. If
vim+cream was faster to start I'd never use the notepad replacements.

Weirdly, even for python I often use PyScripter instead of Leo. Sometimes
it's because I need to write for a different version of python than I'm
running Leo from. Others it's because the output I get from running a Leo
node as a script differs from the same thing from a cmd
shell/IDLE/PyScripter console. I also find PyScripter's code completion a
bit more intuitive for the way I type (though, I didn't discover that until
I'd already wandered away from Leo for a time).

None of this is meant as a slam against or complaint about Leo! It's just
sharing observations of my personal use/not-use patterns.

Part of my difficulty in becoming comfortable with Leo is that I'm also not
that comfortable with python, or even general programming. I'm not a
software developer; this is changing, but very slowly. Consequently I spend
a lot of in-Leo time in a state of confusion, often unsure whether I'm
trying to learn programming or python or Leo or more about the actual
problem I'm started out trying to solve this morning. :)

Anyway, the point touched on earlier about leveraging the skills and
experience people already have before they encounter Leo is pretty key to
the overall adoption rate, I think.

cheers,

-matt
.. @+node:ekr.20090105132011.6: *3* Regex notes
# *** match pat2 if not preceded by pat1::

(?<!pat1)pat2

.  any char
^  start line
$  end of line
\w alphanum: [a-zA-Z0-9_]
\W non-alphanum
\s whitespace
\S non-whitespace

These can be done with regexps:

copy-to-end-of-each-line:   (.)$        -->  \1x
copy-to-start-of-each-line: ^([ \t]+)   -->  \1x
remove-leading-ws:  ^[ \t]+             -->  empty
remove-trailing-ws: [ \t]+$             -->  empty
paste-at-column:    ^(.{4})             -->  \1x
paste-after-lws:    ^([ \t]+)           -->  \1x

[]
    Used to indicate a set of characters. Characters can be listed individually,
    or a range of characters can be indicated by giving two characters and
    separating them by a '-'. Special characters are not active inside sets.

    [akm$] will match any of the characters 'a', 'k', 'm', or '$';
    [a-z] will match any lowercase letter.
    [a-zA-Z0-9] matches any letter or digit.

    Character classes such as \w or \S (defined below) are also
    acceptable inside a range, although the characters they match depends on
    whether LOCALE or UNICODE mode is in force. If you want to include a ']' or
    a '-' inside a set, precede it with a backslash, or place it as the first
    character. The pattern []] will match ']', for example.

    You can match the characters not within a range by complementing the set.
    This is indicated by including a '^' as the first character of the set; '^'
    elsewhere will simply match the '^' character. For example, [^5] will match
    any character except '5', and [^^] will match any character except '^'.

(?=...)
    Matches if ... matches next, but doesnt consume any of the string.
    This is called a lookahead assertion.
    For example, Isaac (?=Asimov) will match 'Isaac ' only if it's followed by 'Asimov'.

(?!...)
    Matches if ... doesn't match next.
    This is a negative lookahead assertion.
    For example, Isaac (?!Asimov) will match 'Isaac ' only if it is not followed by 'Asimov'.

(?<=...)
    Matches if the current position in the string is preceded by a match for ...
    that ends at the current position. This is called a positive lookbehind assertion.
    The contained pattern must only match strings of some fixed length,
    meaning that abc or a|b are allowed, but a* and a{3,4} are not.

(?<!...) Matches if the current position in the string is not preceded by a
    match for .... This is called a negative lookbehind assertion. Similar to
    positive lookbehind assertions, the contained pattern must only match
    strings of some fixed length. Patterns which start with negative lookbehind
    assertions may match at the beginning of the string being searched.
.. @+node:ekr.20060217111834: *4* @url http://docs.python.org/lib/re-syntax.html
.. @+node:ekr.20110527084258.18374: *3* Summary of the Ashland sprint
http://groups.google.com/group/leo-editor/browse_thread/thread/9b1dbebd56d50e14/d5a690127ddad38e
 
"Sprint" isn't really the correct term.  We wrote no code.  Instead,
we discussed what seemed to each of us as the most important
directions for Leo.

After much pleasant discussion, we reached agreement, dreaded or not,
on just about everything. I'll summarize the topics here, and
elaborate about file format issues in a separate thread.

1.  (Done) Make .leo files as standards-compliant as possible.

This will demonstrate to newbies that we have some sophistication re
web standards, and it will allow external tools to handle .leo files
in the easiest possible way.

I've delegated the design of this project to Kent.  I'll be in charge
of implementation.

2. Simplify and revise Leo's file format.

Details in a separate thread: some items deserve just a bit more
discussion.  In particular, we want the about-to-be-renamed <t>
elements to contain headline text so that <t> elements represent key/
value pairs directly.  The question is, should the about-to-be-renamed
<v> elements contain headline text (readable, but "denormalized")?

3. Support reading and writing Leo outlines in JSON format.

This will allow closer cooperation with databases and other tools.
I'll do this.

4. Complete the transition to Terry's free_layout plugin.

A. Place separate body editors in free_layout areas.  This should
*easy* to do!  Almost nothing changes in the code, but the visual
effect should be much better.

B. Allow any pane to be "tabified" (placed in a tab in the Log pane)
and "untabified."  There are a few details to be handled, but nothing
major.

Terry and I will collaborate on this.

5. Add global search to the quicksearch plugin and to Leo's find
command.

6. (Abandoned) Add node-specific undo asap.

The present undo is almost useless after a few levels.  Node-specific
undo would be much more useful. This has been on the list forever.  It
should be done yesterday.

7.  Rejected direct support for .ini files instead of Leo's @settings
nodes.

After some discussion we decided that the present .ini importer should
suffice.  In other words, it seems like a bad idea to support .ini
settings *instead* of, or in *addition* to, .ini files.  However,
scripts or commands to import/export Leo settings to one or more .ini
files would be fine.

8.  (done) Make uA's first class citizens.

There should be commands to get and set uA's.  This is easy to do:
it's just an oversight.

Summary
=======

Looking back on the discussions, I am struck once again by how minor
the suggestions are.  Most of these items can be done in a day or two,
or a week or two at most.  The conclusion is that Leo has reached a
mature state.

Kent, Terry, did I omit anything?  Misstate anything? 
.. @+node:ekr.20101127152442.5878: *3* Url's
@color

@language rest
.. @+node:ekr.20101127154340.5929: *4*  To investigate first
.. @+node:ekr.20101127154340.5928: *5* @url pyexpect: spawn child apps
http://pexpect.sourceforge.net/pexpect.html

@language rest

pexpect: a Python module for spawning child applications and
controlling them automatically. 
.. @+node:ekr.20101127154340.5930: *5* @url pyjamas: AJAX tool kit
http://pyjs.org/

@language rest

Pyjamas: AJAX tool kit.
.. @+node:ekr.20101127154340.5936: *5* @url proto of a Leo forum
http://groups.google.com/group/leo-editor/browse_thread/thread/db6e75d82da4b41d

@language rest

A few buttons turns Leo into a competitor for google groups.

.. @+node:ekr.20101129064803.6060: *5* @url server code to interact with a running Leo
http://groups.google.com/group/leo-editor/browse_thread/thread/278aa85d7298a319/ef6446fcf6268c0d

leoRemote.py
.. @+node:ekr.20101129064803.6061: *5* @url problem solving with graph traversals
http://groups.google.com/group/leo-editor/browse_thread/thread/2e1b240b023b545e/8e9164b52ff25199

Cool slide show: very technical, about graph traversals, from AT&T technical talk

http://www.slideshare.net/slidarko/problemsolving-using-graph-traversals-searching-scoring-ranking-and-recommendation
.. @+node:ekr.20101127154340.5935: *4* Apps
.. @+node:ekr.20101127154340.6806: *5* @url review board: code review
http://www.reviewboard.org/

@language rest
.. @+node:ekr.20101127154340.6824: *5* @url scrivener: cool MacOS outliner
http://www.literatureandlatte.com/scrivener.html

@language rest
.. @+node:ekr.20101127154340.5934: *5* @url tomboy: wiki-like notes
http://projects.gnome.org/tomboy/index.html

http://groups.google.com/group/leo-editor/browse_thread/thread/18d4af19686f2ead
.. @+node:ekr.20101127152442.5879: *4* Autocompletion
.. @+node:ekr.20101127154340.6852: *5* @url codewise: ville's code completer
http://www.mail-archive.com/leo-editor@googlegroups.com/msg10145.html
.. @+node:ekr.20101127152442.5881: *5* @url ctagscompleter.py (Ville's suggestion)
http://groups.google.com/group/leo-editor/browse_thread/thread/c537f3bc8328a938
.. @+node:ekr.20101127152442.5880: *5* @url pydiction (autocompletion for vim)
http://www.vim.org/scripts/script.php?script_id=850
.. @+node:ekr.20101127154340.5931: *5* @url pysmell: python IDE completion helper
http://code.google.com/p/pysmell/

@language rest
.. @+node:ekr.20101127154340.6828: *5* @url SciTe Java api
http://www.burgaud.com/scite-java-api/

@language rest
.. @+node:ekr.20101127154340.6829: *6* @url tags2api.py: python
http://www.scintilla.org/tags2api.py

@language rest

Produces a .api file for SciTE's identifier completion and calltip features.
.. @+node:ekr.20101127154340.6830: *6* @url generates python api for scite
http://www.koders.com/python/fid7000B9C96CF2C6FB5BCE9DF700365C5B2A1F36A7.aspx?s=gtk#L53

@language rest

gen_python_api.py generates a python.api file for SciTE
.. @+node:ekr.20101127201907.5952: *4* Data bases
.. @+node:ekr.20101127154340.6856: *5* @url lazysoft: cool db (sentences)
http://www.lazysoft.com/

@language rest
.. @+node:ekr.20101127201907.5953: *5* @url persistent trees: couchDB
http://eclipsesource.com/blogs/2009/12/13/persistent-trees-in-git-clojure-and-couchdb-data-structure-convergence/

@language rest


Thread: Interesting post on data tree design

http://groups.google.com/group/leo-editor/browse_thread/thread/e4646371478cd30/44eba97b45bd53b3
.. @+node:ekr.20101127201907.5947: *4* Docs
.. @+node:ekr.20101127201907.5949: *5* @url new design for colorer
http://groups.google.com/group/leo-editor/browse_thread/thread/9fb569af95eee493/00c3bbe120567771

Thread: A new design for the incremental colorer

This long posting will discuss a new design for an incremental
colorizer using QSyntaxHighlighter.  The essential features of this
design became apparent during yesterday's walk. 
.. @+node:ekr.20101127201907.5945: *5* @url docs for my successor
http://groups.google.com/group/leo-editor/browse_thread/thread/440bbf170787c5ed/c228a9fd1d429fa6

@language rest
.. @+node:ekr.20101127201907.5946: *5* @url Leo's MVC architecture
http://groups.google.com/group/leo-editor/browse_thread/thread/6b77a59a3a5c7cbb/f26164f24bee68d2

@language rest
.. @+node:ekr.20101127201907.5948: *5* @url one damn fine checkin
http://groups.google.com/group/leo-editor/browse_thread/thread/278442febf1a1965/6a6640976c23935f

@language rest

configure_tags killing performance again

EKR:

Rev 2119 contains what appears to be a major improvement in speed:

- leoQTextEditWidget.SetAllText now sets a lockout that prevents a duplicate
  recoloring of text. This doubles the speed of the syntax colorer, and almost
  doubles the speed of unit tests!

- updateSyntaxColorer and colorize set self.flag = False for large body text.
  This doesn't prevent recolor from being called, but it does short-circuit
  recolor.

And yes, configure_tags is called only by the ctor, that is, just once. 

Ville:

Now that was one damn fine checkin... 
.. @+node:ekr.20101127201907.5951: *5* @url Stupendous Aha re unit tests
http://groups.google.com/group/leo-editor/browse_thread/thread/47dfb2e1767d2cda/8e658c5b73406a8d

@language rest

I have gotten *zero* responses to my 42 post:
http://groups.google.com/group/leo-and-pylint/browse_thread/thread/3c...

I should have remembered that nobody reads long posts. So here is the
Aha in a nutshell:

Unit tests are not just for testing!  They are *the* master tool for
programming, design, testing, refactoring, studying code, or *anything
else*. 
.. @+node:ekr.20101127154340.6805: *4* Editors
.. @+node:ekr.20101127154340.6807: *5* @url pyxides
http://groups.google.com/group/pyxides

@language rest
.. @+node:ekr.20101127154340.6813: *5* Vim
.. @+node:ekr.20101127154340.6814: *6* @url vim cheat sheet
http://www.fprintf.net/vimCheatSheet.html

@language rest
.. @+node:ekr.20101127154340.6815: *6* @url vim reference guide
http://www.dc.turkuamk.fi/docs/soft/vim/vim.html

@language rest
.. @+node:ekr.20101127154340.6816: *6* @url slight advance intro to vim
http://linuxgazette.net/152/srinivasan.html

@language rest
.. @+node:ekr.20101127154340.6817: *6* @url voom: vim 2-page outliner
http://vim-voom.webs.com/

@language rest
.. @+node:ekr.20101127154340.6818: *6* @url why do those nutheads use vim
http://www.viemu.com/a-why-vi-vim.html

@language rest
.. @+node:ekr.20101127154340.6819: *6* @url viper
http://www.delorie.com/gnu/docs/emacs/viper.html

@language rest
.. @+node:ekr.20101127154340.6820: *6* @ulr learning vim the pragmatic way
http://jrmiii.com/2009/03/06/learning-vim-the-pragmatic-way.html

@language rest
.. @+node:ekr.20101127154340.6822: *5* @url python-UNO (Open Office)
http://udk.openoffice.org/python/python-bridge.html

@language rest

http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/ProUNO/Professional_UNO
.. @+node:ekr.20101127154340.6823: *5* @url open komodo forums
http://community.activestate.com/forums/komodo/open-komodo

@language rest

archives:

http://lists.openkomodo.com/pipermail/openkomodo-dev/
.. @+node:ekr.20101127154340.6825: *5* @url org-babel
http://orgmode.org/worg/org-contrib/babel/intro.php

@language rest
.. @+node:ekr.20101127152442.5884: *4* Feature requests
.. @+node:ekr.20101127152442.5885: *5* Better find/replace dialog
For newbies (and for power users too, for that matter), it may be helpful to
have a "Find and Replace" dialog box similar to the one below:

.. image:: c:/prog/findReplace.jpg

.. @+node:ekr.20101127152442.5886: *5* @image find/replace dialog
c:/prog/findReplace.jpg
.. @+node:ekr.20101127154340.6808: *4* Graphics
.. @+node:ekr.20101127154340.6843: *5* @url inkscape: open source svg editor
http://inkscape.org/

@language rest

.. @+node:ekr.20101127154340.6835: *5* @url interactive map of Linux kernel
http://www.makelinux.net/kernel_map

@language rest
.. @+node:ekr.20101127154340.6836: *5* @url blender: open source content creation
http://www.blender.org/

@language rest
.. @+node:ekr.20101127154340.6809: *5* @url tinkerpop: graphics tools
http://www.tinkerpop.com/
.. @+node:ekr.20101129064803.6061: *5* @url problem solving with graph traversals
http://groups.google.com/group/leo-editor/browse_thread/thread/2e1b240b023b545e/8e9164b52ff25199

Cool slide show: very technical, about graph traversals, from AT&T technical talk

http://www.slideshare.net/slidarko/problemsolving-using-graph-traversals-searching-scoring-ranking-and-recommendation
.. @+node:ekr.20101127152442.5887: *4* Gui
.. @+node:ekr.20101127152442.5888: *5* @url cool hack: detach body editor
http://groups.google.com/group/leo-editor/browse_thread/thread/8616f4e171e1a24b

@language rest

This features a long an important discussion of using Leo with vim.
.. @+node:ekr.20101127152442.5889: *5* @url fast syntax highlighting
http://groups.google.com/group/leo-editor/browse_thread/thread/bdcbe3a4ffb5ac61/7dbeea85f671cfe9

@language rest

Source-highlight Qt Library 0.2.2
http://srchiliteqt.sourceforge.net/source-highlight-qt.html

This seems to be a (c++ based) syntax highlighting package that would
allow us to avoid running any python code for syntax highlighting.
Needless to say this is probably very fast.

Investigation needed how easy this would be to deploy in python & leo.
I might(!) make a plugin that allows you to use it instead of leo's
own highlighters...

t seems to support lots of languages already:

http://www.gnu.org/software/src-highlite/

seems you can define your own languages:

http://www.gnu.org/software/src-highlite/source-highlight.html#Language-Definitions

lots of stuff there, but the simple case (keywords) seem to be simple:

http://www.gnu.org/software/src-highlite/source-highlight.html#Simple-definitions

EKR: We would have to support coloring of Leo directives.

.. @+node:ekr.20101127152442.5890: *5* @url code bubbles: an alternative to clones
http://groups.google.com/group/leo-editor/browse_thread/thread/d030a9eccfae2aa2/3a951894e0c15f72

@language rest

This is a cool video:

http://www.cs.brown.edu/people/acb/codebubbles_site.htm
.. @+node:ekr.20101127154340.6840: *5* @url SIKULI: test gui's
http://groups.csail.mit.edu/uid/sikuli/

@language rest
.. @+node:ekr.20101127152442.5882: *4* Leo projects
.. @+node:ekr.20101127152442.5883: *5* @url @data contextmenu_commands
http://groups.google.com/group/leo-editor/browse_thread/thread/e236feb5bd2a097a/d261f6dbdb7eb950

@language rest

As requested, there is now user-friendly way of adding minibuffer
commands to context menu (in trunk, qt only).

I also added example to quickstart.leo, but all you need to know is
that you need to create

@settings
  @data contextmenu_commands

And the content is like:

# The format is <command> SPACE <description>

stickynote Create a sticky note
read-at-file-nodes Read file nodes 
.. @+node:ekr.20101127152442.5912: *5* @url fuse: Leo as a file system
http://leo.zwiki.org/LeoAsAFileSystem

@language rest

.. @+node:ekr.20101127154340.5936: *5* @url proto of a Leo forum
http://groups.google.com/group/leo-editor/browse_thread/thread/db6e75d82da4b41d

@language rest

A few buttons turns Leo into a competitor for google groups.

.. @+node:ekr.20101129064803.6062: *5* @url stickynotes_plus and markdown
http://groups.google.com/group/leo-editor/browse_thread/thread/f8234a8fdeb08d22/4f42eafa955eae9b

Rich text editing in Leo

markdown: http://www.freewisdom.org/projects/python-markdown/

his is a Python implementation of John Gruber's Markdown. It is almost
completely compliant with the reference implementation.

http://daringfireball.net/projects/markdown/

Markdown is a text-to-HTML conversion tool for web writers. Markdown allows you
to write using an easy-to-read, easy-to-write plain text format, then convert it
to structurally valid XHTML (or HTML).
.. @+node:ekr.20101129064803.6063: *5* @url leo+emacs+pida
http://groups.google.com/group/leo-editor/browse_thread/thread/f65470074f6573ab/c73d5b313526d5af

pida: http://pida.co.uk/

PIDA is an IDE (integrated development environment). PIDA is different from
other IDEs in that it will use the tools you already have available rather than
attempting to reinvent each one. PIDA is written in Python with the PyGTK
toolkit, and although is designed to be used to program in any language, PIDA
has fancy Python IDE.
.. @+node:ekr.20101129064803.6065: *5* @url leoremote.py
http://groups.google.com/group/leo-editor/browse_thread/thread/66bcdc5cac03f5ad/0528c66838f1726d

communicating with a running Leo

@language rest

Terry Brown

For some time I've wanted a simple way to make an running leo session
load a file from the command line, like emacs-client.\

Now, thanks to Ville, I also want a way to make an running leo session
pop up a stickynote window (which would correspond to an automatically
created node which would probably use current data and time as a
headstring).

Ville

First working version of this (using qt) is now on trunk.

Testing it requires some manual work:

1. bzr pull
2. Put this script (it's a simple example client) to your leo-editor
directory: http://pastebin.com/f2bcbfd36
3. Enable leoremote.py plugin
4. Launch leo, do alt-x leoserv-start. The leo process where you last
ran leoserv-start is always the session that will receive your
commands
5. Try running the script (it's a python script, not leo script) you
created at #2 from another command prompt 

Terry

Very very cool Ville, thanks.

Here http://pastebin.com/mf678e24 is my version of a functioning
stickynote script. 

And here: http://pastebin.com/m236194c

is a quick hack at a script to edit (or create and edit) a file in leo
from the command line. 

Terry -> EKR

> Can you explain in more detail.  I am totally lost about why this
> gives us anything new.  Thanks.

It's probably of little benefit to people who work with mouse, menus, and icons
all the time. But if you do everything from the command line (i.e. your OS's
shell), then it makes moving things into leo much smoother.

Suppose I've run leo and checked my todo items for the day, and now
leo's buried under some other window and I'm working in the shell in
some directory I've just created where I've just unzipped something and
now I want to edit a file that was in the .zip.

I can either:

  - find the leo window
  - insert a node
  - active the open file dialog
  - navigate to the directory containing this file
  - select the file
  - and finally do the editing I want to do

or, with Ville's communication to the running leo:

  - enter on the command line `led foo.txt`
  - and do the editing I want to do

where led is a script which causes the running leo to create an @edit
node containing foo.txt and pop to the front with the node selected.

Previously I was much more likely to use emacs, just because it was
easier to invoke that way from the command line.

So, opening files, creating sticky notes, invoking leo to handle output
from grep or diff or whatever - all these things are better now. 


Matt Wilkie

The corresponding point and click process for this scenario is

a) select > r-click > Edit with Leo
b) or drag'n'drop from folder to Leo icon on task bar (or window if visible)

In short, I see this being a productivity boost for all users. 
.. @+node:ekr.20101129064803.6066: *6* @url  Ville's script
http://pastebin.com/f2bcbfd36

from leo.external import lproto
import os

addr = open(os.path.expanduser('~/.leo/leoserv_sockname')).read()
print "will connect to",addr
pc  = lproto.LProtoClient(addr)
pc.send('''

g.es("hello world from remote") 
c = g.app.commanders()[0]

''')
.. @+node:ekr.20101129064803.6067: *6* @url Terry's led script
http://pastebin.com/m236194c
.. @+node:ekr.20101127152442.5903: *5* Ville
.. @+node:ekr.20101127152442.5904: *6* @url use json to represent trees
http://mail.google.com/mail/#label/Cool/121a1f23e75fc348

@language rest

Often, it' useful to decouple node creation from data processing. Case
in point is the read code & the hash based speedup scheme I described
(and referred to again in previous thread!)

(for every instance of 'json' below, you can substitute "hierarchical
python object". I'm thinking of json because of interoperability &
human-readablity of json vs. pickle).

What I mean is:

- Provide a way to create tree structure from json object. This is
easy, just add function

c.createSubTreeFromJson(p, json)

The 'json' arg is just a string with subtree encoded in json. Something like

[ ('h1', 'body1', 'gnx1', [ ('h1.1' , 'body1.1' , 'gnx1.1'), ('h1.2' ,
'body1.2' , 'gnx1.2')], ('h2', ......]

i.e. it's a recursive data structure with list of nodes as tuples (h,
b, gnx, children) where 'children' is the recursive part. So far, so
good. That's the easy part - it's just like xml, apart from the fact
that xml is overkill for this problem, requiring nontrivial parser
code (and thus being of lower usability & speed). Yes, the json is
pretty much the same as repr(python_object).

Now, for the important part.

All code that creates trees (read code as the most relevant example!)
probably shouldn't create the tree directly. Rather, it should use c
and p to learn what it needs to, then compose a result json object and
pass it on to c.createSubTreeFromJson(p, json). This is important &
elegant distinction from current behaviour where the data processing
code also modify the tree. We can basically have tests for most of the
stuff without altering the tree in any way, allowing the tree to stay
"read only" as long as possible.

The hash speedup I've been talking about will execute the auto/thin
parsing code exactly once for the particular file content, store away
the json, and just read that json file on subsequent runs. There is no
need to speculate on feasibility of this scheme, we've already had
that particular discussion. It really is the simplest & fastest
possible solution.

We could also add lazy loading (though this is not as important), but
*also this* will be easier with this scheme. Basically, the lazy
loading would:

- Run in a thread in the background, collecting stuff from external
files to json objects
- Every once in a while, do the "destructive" thing and update the
tree from these json objects, redrawing if necessary.

Also this will be perfectly safe - the background thread never does
gui manipulation. At any given time, it's only reading a file, and
writing the json obj to buffer. No communication with leo gui is
necessary. If position with root obj no longer exist, we just throw
the json away and rescan if needed.
.. @+node:ekr.20101127152442.5905: *6* @url dump snippets as yaml
http://mail.google.com/mail/#label/Cool/121b225322eb0a6a

@language rest

I experimented with creating a "direct" recursive data structure for leo trees.

It's pretty simple (who needs Haskell & friends when we have python):

def p_to_obj(p):
   return [p.h, p.b, p.gnx, [p_to_obj(po) for po in p.children_iter()]]

Yes, I removed utf8 encoding to keep it more elegant ;-).

The whole snippet is somewhat like this:

http://pastebin.com/f6a30f859

It creates a python object like this:

http://pastebin.com/f17a3a285

(list of p,h,gnx, children...)

Now, the interesting part. This can be directly encoded as Yaml, to
render the rather readable:

http://pastebin.com/f3d750af3

The part that needs work is the body text, it should probably be
improvable by using "block scalars".

This idea is related to my "jsonification" refactoring suggestion a
while ago. If functions like read code emitted stuff that p_to_obj
returns, the yaml structure could be used to debug / trace the data
(but still in machine-readable form). This could also be used to
communicate outline structure so that it can be both read, and copy
pasted from emails to real tree structure.

No need to take any action regarding this email. Just a food for
thought, perhaps for inspiration...
.. @+node:ekr.20101127152442.5906: *6* @url creating debian packages
http://groups.google.com/group/leo-editor/browse_thread/thread/f83704ecc4ba225a/9e75ecc105aab953

@language rest

> Would it be possible to publish somewhere the scripts or other files you use
> to create the .deb files?

It's somewhat of a nontrivial effort (that I do manually), but the
debian/ directory is here:

https://code.launchpad.net/~leo-editor-team/leo-editor/packaging-jaunty

In order to build the package, I have set up the ubuntu "ppa" (you can
register it at launchpad), use "debuild -S -sa" to build the package
when everything is at correct place (it's picky about directory & file
names and such), and use "dput" to upload it to launchpad servers.
After a while (one hour?), the package is built.

I have a .leo file that I use to trace these steps. I can push it to
trunk. But there is no automatic script to do it; it's possible to
just run "dpkg-buildpackage -rfakeroot" when the debian/ directory is
at leo-editor directory, but that's not the "proper" way, as your
environment is almost never clean enough to get a reliable package
that directly reflects the source snapshot at that tag. 
.. @+node:ekr.20101127154340.5927: *6* @url objtrees: object trees for unit testing
http://groups.google.com/group/leo-editor/browse_thread/thread/32c3a295d2dae35b
.. @+node:ekr.20101127154340.6852: *6* @url codewise: ville's code completer
http://www.mail-archive.com/leo-editor@googlegroups.com/msg10145.html
.. @+node:ekr.20101129064803.6060: *6* @url server code to interact with a running Leo
http://groups.google.com/group/leo-editor/browse_thread/thread/278aa85d7298a319/ef6446fcf6268c0d

leoRemote.py
.. @+node:ekr.20101127154340.6826: *4* Leo urls
.. @+node:ekr.20101127154340.6827: *5* @url NSIS manual
http://nsis.sourceforge.net/Docs/Contents.html

@language rest
.. @+node:ekr.20101127154340.6833: *5* @url leo-editor-files
http://tinyurl.com/35ddr4w

@language rest
.. @+node:ekr.20101127154340.6851: *5* @url upload to source forge
https://sourceforge.net/project/admin/explorer.php?group_id=3458

@language rest
.. @+node:ekr.20101127154340.6837: *4* Math
.. @+node:ekr.20101127154340.6838: *5* @url sage: mathematics software system
http://sagemath.org/

@language rest
.. @+node:ekr.20101127154340.6839: *5* @url viewdog: viewer for math functions
http://gul.sourceforge.net/viewdog-manual/node3.html

@language rest
.. @+node:ekr.20101127152442.5910: *4* Python tools
.. @+node:ekr.20101127152442.5911: *5* @url clonedigger: find similar code
http://clonedigger.sourceforge.net/
.. @+node:ekr.20101127154340.5928: *5* @url pyexpect: spawn child apps
http://pexpect.sourceforge.net/pexpect.html

@language rest

pexpect: a Python module for spawning child applications and
controlling them automatically. 
.. @+node:ekr.20101129064803.6059: *5* @url pynotify: wait for a file to change
http://groups.google.com/group/leo-editor/browse_thread/thread/2b6cceebd7cd2e3/dddcb73e2a6469b9

@language rest

Linux only

For using inotify from Python, I've used pyinotify; it seems to be a
bit more mature: 

http://pypi.python.org/pypi/pyinotify/0.9.1

There's also inotifyx: (more portable?)

http://pypi.python.org/pypi/inotifyx/0.1.1 
.. @+node:ekr.20101127154340.6804: *5* @url python trace module
http://docs.python.org/library/trace.html

@language rest

See the child node for a cool script.
(It is also in scripts.leo).
.. @+node:ekr.20101127154340.6803: *6* Call hierarchy tracing (using python 'trace' module)
@language python
@tabwidth -4

"""
Analyzing program flow.

Run (ctrl+b) this script after 

cd ~/leo-editor
python -m trace --trackcalls launchLeo.py --gui=qt >trace.txt

"""

tracefile = '~/leo-editor/trace.txt'

import os

tr = open(os.path.expanduser(tracefile))
print tr
top = p.insertAsLastChild().copy()
top.h = 'trace session'
cur = None
no = None
for l in tr:
    if l.startswith('***'):
        cur = top.insertAsLastChild().copy()
        cur.h = os.path.basename(l.split()[1])
    elif l.startswith('  -->'):
        no = cur.insertAsLastChild().copy()
        no.h = os.path.basename(l.split()[1].strip())
    else:
        if no:
            no.b += l.strip() + '\n'

    print ".",
.. @+node:ekr.20101127154340.5932: *5* @url pythoscope: create unit tests automatically
http://pythoscope.org/

@language rest
.. @+node:ekr.20101127154340.5933: *5* @url rope: refactoring library
http://rope.sourceforge.net/

@language rest
.. @+node:ekr.20101127152442.5891: *4* Scientific
.. @+node:ekr.20101127152442.5892: *5* @url calioPY Scientific environment using Leo
http://www.caliopywork.org/
.. @+node:ekr.20101127154340.6812: *5* @url reinteract: scientific platform
http://fishsoup.net/software/reinteract/

@language rest

.. @+node:ekr.20101127152442.5893: *4* Text
.. @+node:ekr.20101127152442.5894: *5* Related to viewrendered plugin
.. @+node:ekr.20101127152442.5895: *6* @url enthought editor for restructured text
http://blog.enthought.com/?p=127

rst project of interest 2009/07/14

http://mail.google.com/mail/#label/Cool/1227cc2c66c976ec

It may be that the codebase could be worth looking at.  I find the
prospect of doing a full sphinx rendering of a document in real time
quite fascinating :-).

Requires ETS (Enthought Tool Suite)
http://code.enthought.com/projects/index.php
.. @+node:ekr.20101127152442.5896: *6* @url autosphinx (related to enthought editor)
https://code.launchpad.net/~villemvainio/leo-editor/autosphinx

http://groups.google.com/group/leo-editor/browse_thread/thread/f292f7c9f2fd66d8

bzr branch lp:~villemvainio/leo-editor/autosphinx 

@language rest


No, we want *another window*, like with @button rst-preview, that is
updated in real time. The html output is not editable anyway.

>> Now, the thing is to
>> update this in real time (as you are editing, i.e. not on save or
>> explicit tangle step).

> How about doing it at idle time, that is, at most every half second?

It needs to happen in another process in order to not bog down normal
editing (if we stop doing that, the ui will hang). Generating sphinx
output is somewhat expensive operation.

> I don't want to involve any part of the file logic in rendering: it's too
> complex as it is.

With @auto-rst, we get this for free (i.e. rendering every time you
save). Barring that, we could do the rendering just for current node,
but that is not faithful to the final output.

I think the best implementation is a new process that monitors a file.
That way, it's not really leo-specific, and it's easy to do. Leo just
needs to tell it what file to monitor.

-- 
.. @+node:ekr.20101127152442.5913: *6* @url manuel: rST testing tool
http://pypi.python.org/pypi/manuel

@language rest

Manuel parses documents, evaluates their contents,
then formats the result of the evaluation.
.. @+node:ekr.20101127152442.5897: *5* @url controlling tex parameter from rst markup
http://groups.google.com/group/leo-editor/browse_thread/thread/20ec9f3ec33eb174/dacfce8823e727c1

@language rest

.. @+node:ekr.20101127152442.5898: *6* solution 1: use @raw
@language rest

> On a related note, is there a good example somewhere of embedding
> LaTeX markup in rst?

You can use the ..raw directive

Here is a quote from another thread
http://groups.google.com/group/leo-editor/browse_thread/thread/16272e...

QQQ
One of the difficulties was how to "convince" Leo to write raw code, I
wanted to write some equations and tables, so it was necessary to use
symbols like \, { }, and so on, i. e., what is required by LaTeX. The
problem was that all these symbols were "interpreted" wrongly and
replaced by an unreadable code. The solution was to use the raw
directive. An example is much better to show this. Assume the
following LaTeX code for an equation and a table in a Leo node:

@
.. raw:: latex html

 \begin{equation}  f(x)=\frac{e^{X\beta}}{1-e^{X\beta}}  \end
{equation}

 \newline
 \begin{tabular}[b]{|r|l||c|r|}
    <content deleted ...>
 \end{tabular}

@c

Attention: RsT code requires an indentation with respect to the raw
directive. I didn't know it. It is here a leading blank space for all
LaTeX code inside the raw directive. And then it worked fine.
QQQ 
.. @+node:ekr.20101127152442.5899: *6* solution 2: use make
I think you get the most control by having leo generate an rst file and
then processing it yourself.

Like this somewhat dated page (skip the first section):
http://leo.zwiki.org/RstEmacs

For a project I'm currently working on, currently :), my set up is like
this:

Edit rst in leo using an @auto-rst node.

Run this script (it is (pointlessly) a Makefile):

.. sourcecode:: make

  all:
        rst2html.py report2.rst report2.html
        itex2MML < report2.html > report2.xhtml
        rst2latex.py --documentoptions=letterpaper --stylesheet-path=myprefs.inc \
          --reference-label="ref*" --use-latex-citations report2.rst report2.tex
        echo | pdflatex -draftmode report2 >/dev/null 2>&1
        echo | pdflatex -draftmode report2 >/dev/null 2>&1
        echo | pdflatex report2 2>&1 | tr \\n \\r
        rst2latex.py --documentoptions=letterpaper --stylesheet-path=myprefs.inc \
          report2.rst report2.tex

The two -draftmode parses take care of references etc. much quick than
non-draft, because they don't chew up time turning pngs and pdfs into
part of the pdf output.  I.e. they don't produce pdf output.

``myprefs.inc`` looks like:

.. sourcecode:: latex

  \usepackage{pslatex}
  \usepackage{mathptmx}
  \usepackage[scaled=.90]{helvet}
  \usepackage{courier}
  \renewcommand\sfdefault{phv}%               use helvetica for sans serif
  \renewcommand\familydefault{\sfdefault}%    use sans serif by default
  \renewcommand{\topfraction}{0.85}
  \renewcommand{\textfraction}{0.1}
  \renewcommand{\floatpagefraction}{0.75}
  \setcounter{bottomnumber}{2}
  \renewcommand{\bottomfraction}{0.8}

  \setlength{\parskip}{2ex}
  \setlength{\parindent}{0pt}

  \addtolength{\oddsidemargin}{-1.5cm}
  \addtolength{\evensidemargin}{-1.5cm}
  \addtolength{\textwidth}{3cm}
  \addtolength{\topmargin}{-2cm}
  \addtolength{\textheight}{4cm}

  \usepackage{fancyhdr}
  \pagestyle{fancy}
  \lhead{Synoptic mapping of Native Plant Communities}
  \rhead{}
  \lfoot{\footnotesize 20091203-draft }

itex2MML (referenced in the ``Makefile``) converts latex math notation to MathML in the .xhtml output.

To insert raw latex in the latex output from rst, use

.. sourcecode:: rst

  .. raw:: latex

     \some{latex here}

Cheers -Terry 
.. @+node:ekr.20101127152442.5900: *5* @url rst to anything
http://rst2a.com/

@language rest

A web service that converts reStructuredText to pdf or other formats.

You can use that to, say, quickly generate pdf from an (@auto-) rst file.

There is an api for the web service:

http://rst2a.com/api/
.. @+node:ekr.20101127154340.6845: *5* @url mxTextTools: python text tools
http://www.egenix.com/products/python/mxBase/mxTextTools/

@language rest
.. @+node:ekr.20101127154340.6847: *5* @url 2die4 games: TL (very cool rst stuff)
http://www.2die4games.com/

Thread: TL's 2die4games web site

http://groups.google.com/group/leo-editor/browse_thread/thread/cace15fe101e4844/6acd66a982bc063b
.. @+node:ekr.20101127201907.5950: *5* @url idea - presentation tool
http://groups.google.com/group/leo-editor/browse_thread/thread/4ea2d3f7d2c68106/478c773f875815db

@language rest

- Create one QWebView window, zoom it in to have large fonts
- Create @button that converts current node containing
  restructuredtext to html, and pushes that html to QWebView.

Voila', instant presentation tool. The webview window would be on projector, and
leo would be in your private computer. You can easily edit the text, or find new
interesting slides to present in privacy of your own screen.

=====

Terry:
.. @+node:ekr.20101127201907.5954: *5* @url rst/html in email
http://groups.google.com/group/leo-editor/browse_thread/thread/d119424cbccc96df/379a0600dfb8f4ca?lnk=gst&q=terry+brown#379a0600dfb8f4ca

@language rest

Was: "Anchors" as pseudo-persistent positions

Now: OT: rst/html in email

Important : You should try and view the HTML version of this message!

On Thu, 10 Dec 2009 10:46:05 -0600 Terry Brown <terry_n_brown@yahoo.com> wrote:

> Hey - would it be cool to have an email system which lets you write
> in rst and then sends both text (rst) and html forms...

Despite the fact y'all failed to chorus "Yes it would" ;-) I went ahead and set
it up in Claws-mail

   1.

      Add an rst-preview button to the Claws-mail compose window. It just runs a
      user command on the body text:

      | rst2pyg >~/.tmp.html; x-www-browser ~/.tmp.html

      rst2pyg is included below.
   2.

      Add an indent button to the Claws-mail compose window. It just runs a user command on the selected text:

          | sed 's/^/  /' |

   3.

      Write rst2email, included below.
   4.

      Use Send Later for messages you want to process, so rst2email can get at them in the queue directory.
   5.

      You can get rst2email_pygments.py (as imported by both rst2email and rst2pyg) from my blog, it's the file at the end of this page.

rst2email::

    #!/usr/bin/python
    """rst2email - look for messages in an email queue folder and
    add an html part by processing the text part as rst

    Terry Brown, terry_n_brown@yahoo.com
    """

    import email
    import mailbox
    from email.mime.text import MIMEText
    from docutils.core import publish_string

    # this import adds the sourcecode:: directive to rst
    import rst2email_pygments

    queue = "/home/tbrown/Mail/queue"

    mbox = mailbox.MH(queue, email.message_from_file)

    for msgkey in mbox.iterkeys():
        # d = email.utils.parsedate(msg.get('Date'))

        msg = mbox[msgkey]

        if not msg.is_multipart():
            txt = msg.get_payload()
            html = publish_string(txt, writer_name='html')
            part1 = MIMEText(txt, 'plain')
            part2 = MIMEText(html, 'html')
            part1["X-rst2email"] = "rst"
            part2["X-rst2email"] = "html"
            msg.set_type("multipart/alternative")
            msg.set_payload([])
            msg.attach(part1)
            msg.attach(part2)
            mbox[msgkey] = msg
        else:
            txtpart = None
            htmlpart = None
            for part in msg.walk():
                if part.get_content_type() == "text/plain":
                    if txtpart:  # can't handle more than one
                        txtpart = None
                        break
                    txtpart = part
                if part.get_content_type() == "text/html":
                    if htmlpart:  # can't handle more than one
                        htmlpart = None
                        break
                    htmlpart = part
            if txtpart and htmlpart and not txtpart.is_multipart():
                htmlpart.set_payload(
                    publish_string(txtpart.get_payload(),
    writer_name='html')) txtpart["X-rst2email"] = "rst"
                htmlpart["X-rst2email"] = "html"
                msg.set_type("multipart/alternative")
                mbox[msgkey] = msg

rst2pyg::



    #!/usr/bin/python

    from docutils.core import publish_string
    import rst2email_pygments
    import sys

    print publish_string(sys.stdin.read(), writer_name='html')

===== Ville M. Vainio	

This kind of stuff makes me think html email is actually a somewhat tolerable concept.

For thunderbird, there is pasteCode:

https://addons.mozilla.org/en-US/thunderbird/addon/4046

===== Terry Brown

Maybe :-) even as I wrote it it was more because I thought email
rendered (to html) from rst was cool, rather than that I think html
email is necessary.  It's funny looking at postings in this list vs. my
main inbox, here very very few msgs have html parts, whereas in the
main inbox at least 50% do.

Did occur to me that it would probably be possibly to set up some
combination of unicode chrs and css which would render leo trees
nicely in an html email.
.. @+node:ekr.20101129064803.6064: *5* @url rst/latex tricks
http://groups.google.com/group/leo-editor/browse_thread/thread/d052979864a278bc/3ff8f82b2a80774d

@language rest

python in leo to generate rst

Here's a fun example of rst / latex tricks.  I want (well, the report
recipients want) 16 similar figures included.  I write a little python
in an rst comment, use ``Ctrl-b`` to execute it, and then an rst ``..
include::`` directive to include its output.  Here's the rst:

.. sourcecode:: rst

  The range of each input variable which occurs within each cluster
  could be examined to assign a biological meaning to each cluster.
  Figures `Upland cluster 1 and variables`_ through
  `Wetland cluster 8 and variables`_ show the
  relationships between clusters and variables.  The maps
  give a more general view of the clusters, and
  a variable by variable interpretation of each cluster may
  not add much useful information.

  ..  python

    out = file('/home/tbrown/Desktop/Proj/AitkinMap/varvsclust.rst', 'w')
    def pnt(x): out.write(x+'\n')
    for uw in 'Upland', 'Wetland':
      for i in range(1,9):
        pnt(".. figure:: plots/%s_Cluster_%d.pdf" % (uw,i))
        pnt("   :width: 95%")
        pnt("")
        pnt("   %s cluster %d and variables" % (uw,i))
        pnt("")
    out.close()

  .. include:: varvsclust.rst

Note: The .. python is just a comment.  "Empty" comments like::

    ..
      print 40+2
      print 'done'

don't work, because empty comments don't consume indented blocks
.. @+node:ekr.20101127152442.5901: *4* Video tools
.. @+node:ekr.20101127154340.6841: *5* @url screenr: instant screencasts for twitter
http://screenr.com/
.. @+node:ekr.20101127154340.6842: *5* @url jing
http://jingproject.com
.. @+node:ekr.20101127152442.5907: *4* Web technologies
.. @+node:ekr.20101127154340.6811: *5* @url 0mq: socket library
http://www.zeromq.org/
.. @+node:ekr.20101127154340.6810: *5* @url flask: micro devel framework for python
http://flask.pocoo.org/docs/

@language rest
.. @+node:ekr.20101127154340.6848: *5* @url google app engine
http://code.google.com/appengine/

@language rest
.. @+node:ekr.20101127154340.6849: *5* @url browser shots: web page testing
http://browsershots.org/

@language rest
.. @+node:ekr.20101127154340.6850: *5* @url goosh: google shell
http://goosh.org/

@language rest
.. @+node:ekr.20101127152442.5908: *5* @url json
http://www.json.org/

@language rest

**object**:

{   string : value,
    string : value,
    ...
} 

**array**:

[ value, value...]

**value**: string object array true false null

**number**: 
    int
    int frac
    int e digits
    int frac e digits 
.. @+node:ekr.20101127152442.5909: *5* @url places to ask questions
serverfault.com
stackoverflow.com

@language rest

Quora
.. @+node:ekr.20101127154340.5930: *5* @url pyjamas: AJAX tool kit
http://pyjs.org/

@language rest

Pyjamas: AJAX tool kit.
.. @+node:ekr.20101127154340.6846: *5* @url w3c: web standards page
http://www.w3.org/

@language rest
.. @+node:ekr.20101127154340.6853: *4* Windows
.. @+node:ekr.20101127154340.6854: *5* @url cmd
http://commandwindows.com/command1.htm

@language rest
.. @+node:ekr.20101127154340.6844: *5* @url process monitor for windows
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx?PHPSESSID=d926

@language rest
.. @+node:ekr.20101127154340.6855: *5* @url windows shortcuts
http://www.codeproject.com/Articles/36538/Windows-7-Tricks-and-Keyboard-Shortcuts.aspx

@language rest
.. @+node:ekr.20031218072017.434: ** Unused code
@ignore
@language python
@color
.. @+node:ekr.20050920084036.207: *3* queryReplaceCommandsClass (limited to single node)
class queryReplaceCommandsClass (baseEditCommandsClass):

    '''A class to handle query replace commands.'''

    @others
.. @+node:ekr.20050920084036.208: *4*  ctor & init (queryReplaceCommandsClass)
def __init__ (self,c):

    baseEditCommandsClass.__init__(self,c) # init the base class.
    self.regexp = False # True: do query-replace-regexp.  Set in stateHandler.

def init (self):

    self.qQ = None
    self.qR = None
    self.replaced = 0 # The number of replacements.
.. @+node:ekr.20050920084036.209: *4*  getPublicCommands
def getPublicCommands (self):

    return {
        'query-replace':        self.queryReplace,
        'query-replace-regex':  self.queryReplaceRegex,
    }
.. @+node:ekr.20050920084036.210: *4* Entry points
def queryReplace (self,event):

    '''Interactively find and replace text.
    This is not recommended: Leo's other find and change commands are more capable.'''
    self.regexp = False
    self.stateHandler(event)

def queryReplaceRegex (self,event):
    '''Interactively find and replace text using regular expressions.
    This is not recommended: Leo's other find and change commands are more capable.'''
    self.regexp = True
    self.stateHandler(event)
.. @+node:ekr.20051005151838: *4* Helpers
.. @+node:ekr.20050920084036.212: *5* doOneReplace
def doOneReplace (self,event):

    w = self.editWidget(event)
    if not w: return

    i = w.tag_ranges('qR')
    w.delete(i[0],i[1])
    ins = w.getInsertPoint()
    w.insert(ins,self.qR)
    self.replaced += 1
.. @+node:ekr.20050920084036.219: *5* findNextMatch (query-replace)
def findNextMatch (self,event):

    '''Find the next match and select it.
    Return True if a match was found.
    Otherwise, call quitSearch and return False.'''

    k = self.k
    w = self.editWidget(event)
    if not w: return

    if g.app.gui.guiName() != 'tkinter':
        return g.es('command not ready yet',color='blue')

    w.tag_delete('qR')
    if self.regexp:
        << handle regexp >>
    else:
        << handle plain search >>
.. @+node:ekr.20051005155611: *6* << handle regexp >>
try:
    regex = re.compile(self.qQ)
except Exception:
    self.quitSearch(event,'Illegal regular expression')
    return False

i = w.getInsertPoint()
txt = w.get(i,'end')
match = regex.search(txt)

if match:
    start = match.start()
    end = match.end()
    length = end - start
    i = w.getInsertPoint()
    w.setInsertPoint(i+start)
    w.tag_add('qR','insert','insert +%sc' % length)
    w.tag_config('qR',background='lightblue')
    i = w.getInsertPoint()
    txt = w.get(i,i+length)
    return True
else:
    self.quitSearch(event)
    return False
.. @+node:ekr.20051005160923: *6* << handle plain search >> (tag_add & tag_config) LATER
i = w.search(self.qQ,'insert',stopindex='end')

if i:
    w.setInsertPoint(i)
    w.tag_add('qR','insert','insert +%sc' % len(self.qQ))
    w.tag_config('qR',background='lightblue')
    return True
else:
    self.quitSearch(event)
    return False
.. @+node:ekr.20050920084036.211: *5* getUserResponse
def getUserResponse (self,event):

    w = self.editWidget(event)
    char = event and event.char or ''
    
    if not w or not char return

    if char in ('Y','y'):
        self.doOneReplace(event)
        if not self.findNextMatch(event):
            self.quitSearch(event)
    elif char in ('Q','q','\n','Return'):
        self.quitSearch(event)
    elif char == '!':
        while self.findNextMatch(event):
            self.doOneReplace(event)
    elif char in ('N','n','Delete'):
        # Skip over the present match.
        i = w.getInsertPoint()
        w.setInsertPoint(i + len(self.qQ))
        if not self.findNextMatch(event):
            self.quitSearch(event)

    w.seeInsertPoint()
.. @+node:ekr.20050920084036.220: *5* quitSearch
def quitSearch (self,event,message=None):

    k = self.k
    w = self.editWidget(event)
    if not w: return

    w.tag_delete('qR')
    k.clearState()
    if message is None:
        message = 'Replaced %d occurences' % self.replaced
    k.setLabelGrey(message)
.. @+node:ekr.20050920084036.215: *5* stateHandler
def stateHandler (self,event):

    k = self.k ; state = k.getState('query-replace')

    prompt = g.choose(self.regexp,'Query replace regexp','Query replace')

    if state == 0: # Get the first arg.
        self.init()
        k.setLabelBlue(prompt + ': ',protect=True)
        k.getArg(event,'query-replace',1,self.stateHandler)
    elif state == 1: # Get the second arg.
        self.qQ = k.arg
        if len(k.arg) > 0:
            prompt = '%s %s with: ' % (prompt,k.arg)
            k.setLabelBlue(prompt)
            k.getArg(event,'query-replace',2,self.stateHandler)
        else:
            k.resetLabel()
            k.clearState()
    elif state == 2: # Set the prompt and find the first match.
        self.qR = k.arg # Null replacement arg is ok.
        k.setLabelBlue('Query replacing %s with %s\n' % (self.qQ,self.qR) +
            'y: replace, (n or Delete): skip, !: replace all, (q or Return): quit',
            protect=True)
        k.setState('query-replace',3,self.stateHandler)
        self.findNextMatch(event)
    elif state == 3:
        self.getUserResponse(event)
.. @+node:ekr.20101031172539.5880: *3* Existing autocompleter: do not delete
.. @+node:ekr.20061031131434.43: *4* completeSelf (not used yet)
def completeSelf (self):

    g.trace(g.callers(4))

    # This scan will be fast if an instant object already exists.
    className,obj,p,s = self.classScanner.scan()
    # g.trace(className,obj,p,s and len(s))

    # First, look up the className.
    if not obj and className:
        obj = self.allClassesDict.get(className)
        # if obj: g.trace('found in allClassesDict: %s = %s' % (className,obj))

    # Second, create the object from class definition.
    if not obj and s:
        theClass = self.computeClassObjectFromString(className,s)
        if theClass:
            obj = self.createProxyObjectFromClass(className,theClass)
            if obj:
                self.selfObjectsDict [className] = obj
                # This prevents future rescanning, even if the node moves.
                self.selfVnodesDict [p.v] = obj
    if obj:
        self.selfClassName = className
        self.push(self.theObject)
        self.theObject = obj
        self.membersList = self.getMembersList(obj=obj)
    else:
        # No further action possible or desirable.
        self.selfClassName = None
        self.theObject = None
        self.clear()
        self.membersList = []
.. @+node:ekr.20061031131434.60: *4* class forgivingParserClass (not used)
class forgivingParserClass:

    '''A class to create a valid class instances from
    a class definition that may contain syntax errors.'''

    @others
.. @+node:ekr.20061031131434.61: *5* ctor (forgivingParserClass)
def __init__ (self,c):

    self.c = c
    self.excludedTnodesList = []
    self.old_putBody = None # Set in parse for communication with newPutBody.
.. @+node:ekr.20061031131434.62: *5* parse
def parse (self,p):

    '''The top-level parser method.

    It patches c.atFileCommands.putBody, calls the forgiving parser and finally
    restores c.atFileCommands.putBody.'''

    c = self.c

    # Create an ivar for communication with newPutBody.
    self.old_putBody = c.atFileCommands.putBody

    # Override atFile.putBody.
    c.atFileCommands.putBody = self.newPutBody

    try:
        s = None
        s = self.forgivingParser(p)
    finally:
        c.atFileCommands.putBody = self.old_putBody

    return s # Don't put a return in a finally clause.


.. @+node:ekr.20061031131434.63: *5* forgivingParser (leoKeys)
def forgivingParser (self,p,suppress=False):

    c = self.c ; root = p.copy()
    self.excludedTnodesList = []
    s = g.getScript(c,root,useSelectedText=False)
    while s:
        try:
            if not g.isPython3:
                s = g.toEncodedString(s)
            compile(s+'\n','<string>','exec')
            break
        except SyntaxError:
            fileName, n = g.getLastTracebackFileAndLineNumber()
            p = self.computeErrorNode(c,root,n,lines=g.splitLines(s))
            if not p or p == root:
                if not suppress:
                    g.es_print('syntax error in class node: can not continue')
                s = None ; break
            else:
                # g.es_print('syntax error: deleting',p.h)
                self.excludedTnodesList.append(p.v)
                s = g.getScript(c,root,useSelectedText=False)
        except Exception:
            g.trace('unexpected exception')
            g.es_exception()
            break
    return s or ''
.. @+node:ekr.20061031131434.64: *5* computeErrorNode (leoKeys)
def computeErrorNode (self,c,root,n,lines):

    '''The from c.goToLineNumber that applies to scripts.
    Unlike c.gotoLineNumberOpen, this function returns a position.'''

    if n == 1 or n >= len(lines):
        return root

    # vnodeName, junk, junk, junk, junk = c.convertLineToVnodeNameIndexLine(
        # lines, n, root, scriptFind = True)

    goto = goToLineNumber(c)
    vnodeName,junk,junk,junk = goto.findVnode(
        root,lines,n,ignoreSentinels)

    if vnodeName:
        for p in root.self_and_subtree():
            if p.matchHeadline(vnodeName):
                return p

    return None
.. @+node:ekr.20061031131434.65: *5* newPutBody
def newPutBody (self,p,oneNodeOnly=False,fromString=''):

    if p.v in self.excludedTnodesList:
        pass
        # g.trace('ignoring',p.h)
    else:
        self.old_putBody(p,oneNodeOnly,fromString)
.. @+node:ekr.20061031131434.66: *4* class classScannerClass (not used)
# Called by completeSelf, which is not used.

class classScannerClass:

    '''A class to find class definitions in a node or its parents.'''

    @others
.. @+node:ekr.20061031131434.67: *5* ctor (classScannerClass)
def __init__ (self,c):

    self.c = c

    # Ignore @root for now:
    # self.start_in_doc = c.config.getBool('at_root_bodies_start_in_doc_mode')

    self.start_in_doc = False
.. @+node:ekr.20061031131434.68: *5* scan
def scan (self):

    c = self.c

    className,obj,p = self.findParentClass(c.p)
    # g.trace(className,obj,p)

    if p and not obj:
        parser = c.k.autoCompleter.forgivingParser
        s = parser.parse(p)
    else:
        s = None

    return className,obj,p,s
.. @+node:ekr.20061031131434.69: *5* findParentClass
def findParentClass (self,root):

    autoCompleter = self.c.k.autoCompleter

    # First, see if any parent has already been scanned.
    for p in root.self_and_parents():
        obj = autoCompleter.selfVnodesDict.get(p.v)
        if obj:
            # g.trace('found',obj,'in',p.h)
            return None,obj,p

    # Next, do a much slower scan.
    # g.trace('slow scanning...')
    for p in root.self_and_parents():
        className = self.findClass(p)
        if className:
            # g.trace('found',className,'in',p.h)
            return className,None,p

    return None,None,None
.. @+node:ekr.20061031131434.70: *5* findClass & helpers
def findClass (self,p):

    lines = g.splitLines(p.b)
    inDoc = self.start_in_doc
    # g.trace(p.h)
    for s in lines:
        if inDoc:
            if self.endsDoc(s):
                inDoc = False
        else:
            if self.startsDoc(s):
                inDoc = True
            else:
                # Not a perfect scan: a triple-string could start with 'class',
                # but perfection is not important.
                className = self.startsClass(s)
                if className: return className
    else:
        return None
.. @+node:ekr.20061031131434.71: *6* endsDoc
def endsDoc (self,s):

    return s.startswith('@c')
.. @+node:ekr.20061031131434.72: *6* startsClass
def startsClass (self,s):

    if s.startswith('class'):
        i = 5
        i = g.skip_ws(s,i)
        j = g.skip_id(s,i)
        word = s[i:j]
        # g.trace(word)
        return word
    else:
        return None
.. @+node:ekr.20061031131434.73: *6* startsDoc
def startsDoc (self,s):

    for s2 in ('@doc','@ ','@\n', '@r', '@\t'):
        if s.startswith(s2):
            return True
    else:
        return False
.. @+node:ekr.20061031131434.57: *4* Proxy classes and objects
.. @+node:ekr.20061031131434.58: *5* createProxyObjectFromClass
def createProxyObjectFromClass (self,className,theClass):

    '''Create a dummy instance object by instantiating theClass with a dummy ctor.'''

    if 0: # Calling the real ctor is way too dangerous.
        # Set args to the list of required arguments.
        args = inspect.getargs(theClass.__init__.im_func.func_code)
        args = args[0] ; n = len(args)-1
        args = [None for z in range(n)]

    def dummyCtor (self):
        pass

    try:
        obj = None
        old_init = hasattr(theClass,'__init__') and theClass.__init__
        theClass.__init__ = dummyCtor
        obj = theClass()
    finally:
        if old_init:
            theClass.__init__ = old_init
        else:
            delattr(theClass,'__init__')

    g.trace(type(theClass),obj)

    # Verify that it has all the proper attributes.
    # g.trace(g.listToString(dir(obj)))
    return obj
.. @+node:ekr.20061031131434.59: *5* createClassObjectFromString
def computeClassObjectFromString (self,className,s):

    try:
        # Add the the class definition to the present environment.
        exec(s) # Security violation!

        # Get the newly created object from the locals dict.
        theClass = locals().get(className)
        return theClass

    except Exception:
        if 1: # Could be a weird kind of user error.
            g.es_print('unexpected exception in',computeProxyObject)
            g.es_exception()
        return None
.. @+node:ekr.20080924032842.3: *4* getExternalCompletions
def getExternalCompletions (self,s,p=None,language='python'):

    '''Return the completions possible at the end of string 's'.
       Return (theObject,completions):
    - theObject is None unless the last character is 's' is a period.
    - completions is the list of valid completions.'''

    c = self.c ; k = c.k
    if not p: p = c.p

    # Use a separate widget containing just s.
    self.widget = w = leoFrame.stringTextWidget(c,'compute-completions-widget')
    w.setAllText(s)

    # Scan back for the first period.
    i = len(s)-1
    # while i > 0 and s[i] != '.':
    while i > 0 and g.isWordChar(s[i]):
        i -= 1
    if s[i] == '.': i += 1
    prefix = s[i:].strip()

    # Remember the prefix, but put the insert before the period.
    w.setSelectionRange(i, len(s)-1, insert=i)

    # Init the ivars...
    self.language = p and g.scanForAtLanguage(c,p) or language
    self.tabName = ''
    old_enable = c.k.enable_autocompleter

    # Get the completions.
    try:
        c.k.enable_autocompleter = True
        self.useTabs = False
        self.start(prefix=prefix)
    finally:
        c.k.enable_autocompleter = old_enable
        self.useTabs = True

    theObject,tabList = self.theObject,self.tabList
    self.exit() # Not called from the autocompleter itself.
    return theObject,tabList
.. @+node:ekr.20131105122124.16479: ** vim reference card
@killcolor
.. @+node:ekr.20131105122124.16482: *3*  keys (do not sort!!)
    <BS>                    delete the character in front of the cursor
N   <Del>                   delete N characters under and after the cursor
    <Del>                   delete the character under the cursor
    <Del>                   while entering a count: delete last character
    <Esc>                   abandon command-line (if 'wildchar' is <Esc>, type it twice)
    <Left>/<Right>          cursor left/right
    <S-Left>/<S-Right>      cursor one word left/right
    <S-Up>/<S-Down>         recall older/newer command-line from history
    <Up>/<Down>             recall older/newer command-line that starts with current command

N   CTRL-^                  Edit alternate file N (equivalent to ":e #N").
N   CTRL-A                  add N to the number at or after the cursor
N   CTRL-B                  window N pages Backwards (upwards)
    CTRL-B                  cursor to beginning of command-line
    CTRL-BREAK              MS-DOS: during searches: interrupt the search
    CTRL-C                  during searches: interrupt the search
N   CTRL-D                  window N lines Downwards (default: 1/2 window)
N   CTRL-E                  window N lines downwards (default: 1)
    CTRL-E                  cursor to end of command-line
N   CTRL-F                  window N pages Forwards (downwards)
    CTRL-G                  show current file name (with path) and cursor position
N   CTRL-I                  go to Nth newer position in jump list
    CTRL-K {char1} {char2}  enter digraph
    CTRL-L                  Clear and redraw the screen.
N   CTRL-O                  go to Nth older position in jump list
N   CTRL-R                  redo last N undone changes
    CTRL-R <0-9a-z"%:->     insert contents of register <0-9a-z"%:->
N   CTRL-T                  Jump back from Nth older tag in tag list
N   CTRL-U                  window N lines Upwards (default: 1/2 window)
    CTRL-U                  remove all characters
    CTRL-V                  highlight blockwise or stop highlighting
    CTRL-V                  start highlighting blockwise   }  highlighted text
    CTRL-V {char}           insert {char} literally
    CTRL-V {number}         enter decimal value of character (up to three digits)
    CTRL-W                  delete the word in front of the cursor
    CTRL-W +                Increase current window height
    CTRL-W -                Decrease current window height
    CTRL-W =                Make all windows equal height
    CTRL-W CTRL-W           Move cursor to window below (wrap)
    CTRL-W CTRL-^           Split window and edit alternate file
    CTRL-W R                Rotate windows upwards
    CTRL-W W                Move cursor to window above (wrap)
    CTRL-W ]                Split window and jump to tag under cursor
    CTRL-W _                Set current window height (default: very high)
    CTRL-W b                Move cursor to bottom window
    CTRL-W c  or :cl[ose]   Make buffer hidden and close window
    CTRL-W f                Split window and edit file name under the cursor
    CTRL-W j                Move cursor to window below
    CTRL-W k                Move cursor to window above
    CTRL-W n  or :new       Create new empty window
    CTRL-W o  or :on[ly]    Make current window only one on the screen
    CTRL-W p                Move cursor to previous active window
    CTRL-W q  or :q[uit]    Quit editing and close window
    CTRL-W r                Rotate windows downwards
    CTRL-W s                Split window into two parts
    CTRL-W t                Move cursor to top window
    CTRL-W x                Exchange current window with next one
N   CTRL-X                  subtract N from the number at or after the cursor
N   CTRL-Y                  window N lines upwards (default: 1)
    CTRL-Z                  Same as ":stop!"
    CTRL-]                  Jump to the tag under cursor, unless changes have been made
    
VIS ~               switch case for highlighted text
N   ~               switch case for N characters and advance cursor

N   +               down N lines, on the first non-blank character (also: CTRL-M and <CR>)
N   _               down N-1 lines, on the first non-blank character
N   -               up N lines, on the first non-blank character

N   ,               repeat the last "f", "F", "t", or "T" N times in opposite direction
N   .               repeat last change (with count replaced with N)
N   ;               repeat the last "f", "F", "t", or "T" N times

N   (               N sentences backward
N   )               N sentences forward
N   {               N paragraphs backward
N   }               N paragraphs forward
N   |               to column N (default: 1)

    `"              go to the position when last editing this file
    '<a-zA-Z0-9[]'"<>>  same as `, but on the first non-blank in the line
    `<              go to the start of the (previous) Visual area
    `<0-9>          go to the position where Vim was last exited
    `<A-Z>          go to mark <A-Z> in any file
    `<a-z>          go to mark <a-z> within current file
    `>              go to the end of the (previous) Visual area
    `[              go to the start of the previously operated or put text
    `]              go to the end of the previously operated or put text
    ``              go to the position before the last jump
N   $               go to the last character in the line (N-1 lines lower) (also: <End> key)
    ^               go to first non-blank character in the line
N   %               goto line N percentage down in the file.  N must be given, otherwise it is the % command.
    %               find the next brace, bracket, comment, or "#if"/ "#else"/"#endif" in this line and go to its match
    
N   <{motion}       move the lines that are moved over with {motion} one shiftwidth left
N   >{motion}       move the lines that are moved over with {motion} one shiftwidth right
N   <<              move N lines one shiftwidth left
N   >>              move N lines one shiftwidth right

N   #                           search backward for the identifier under the cursor
N   *                           search forward for the identifier under the cursor
N   /<CR>                       repeat last search, in the forward direction
N   /{pattern}[/[offset]]<CR>   search forward for the Nth occurrence of {pattern}
N   ?<CR>                       repeat last search, in the backward direction
N   ?{pattern}[?[offset]]<CR>   search backward for the Nth occurrence of {pattern}

N   @<a-z>          execute the contents of register <a-z> (N times)
N   @@              repeat previous @<a-z> (N times)

    "<char>         use register <char> for the next delete, yank, or put

N   [#              N times back to unclosed "#if" or "#else"
N   [(              N times back to unclosed '('
N   [*              N times back to start of comment "/*"
N   [[              N sections backward, at start of section
N   []              N sections backward, at end of section
N   [p              like P, but adjust indent to current line
N   [{              N times back to unclosed '{'
N   ]#              N times forward to unclosed "#else" or "#endif"
N   ])              N times forward to unclosed ')'
N   ]*              N times forward to end of comment "*/"
N   ][              N sections forward, at end of section
N   ]]              N sections forward, at start of section
N   ]p              like p, but adjust indent to current line
N   ]}              N times forward to unclosed '}'

N   A               append text at the end of the line (N times)
N   B               N blank-separated WORDS backward
N   C               change to end-of-line (and N-1 more lines)
N   D               delete to end-of-line (and N-1 more lines)
N   E               forward to the end of the Nth blank-separated WORD
N   F<char>         to the Nth occurrence of <char> to the left
N   G               goto line N (default: last line), on the first non-blank character
N   H               go to the Nth line in the window, on the first non-blank
N   I               insert text before the first non-blank in the line (N times)
N   J               join N-1 lines (delete newlines)
VIS J               join the highlighted lines
    K               lookup keyword under the cursor with 'keywordprg' program (default: "man")
    M               go to the middle line in the window, on the first non-blank
N   L               go to the Nth line from the bottom, on the first non-blank
N   N               repeat last search, in opposite direction
N   O               open a new line above the current line, append text (N times)
N   P               put a register before the cursor position (N times)
N   R               enter Replace mode (repeat the entered text N times)
N   S               change N lines
N   T<char>         till before the Nth occurrence of <char> to the left
    U               restore last changed line
VIS U               make highlighted text uppercase
    V               highlight linewise or stop highlighting
    V               start highlighting linewise    }  operator to affect
N   W               N blank-separated WORDS forward
N   X               delete N characters before the cursor
N   Y               yank N lines
    ZQ              Same as ":q!".
    ZZ              Same as ":x".
    0               to first character in the line (also: <Home> key)
N   a               append text after the cursor (N times)
N   b               N words backward
N   cc              change N lines
N   c{motion}       change the text that is moved over with {motion}
VIS c               change the highlighted text
VIS d               delete the highlighted text
N   dd              delete N lines
N   d{motion}       delete the text that is moved over with {motion}
N   e               forward to the end of the Nth word
N   f<char>         to the Nth occurrence of <char> to the right
    g CTRL-G        show cursor column, line, and character position
N   g^              to first non-blank character in screen line (differs from "^" when lines wrap)
    g~{motion}      switch case for the text that is moved over with {motion}
N   g#              like "#", but also find partial matches
N   g$              to last character in screen line (differs from "$" when lines wrap)
N   g*              like "*", but also find partial matches
N   g0              to first character in screen line (differs from "0" when lines wrap)
    gD              goto global declaration of identifier under the cursor
N   gE              backward to the end of the Nth blank-separated WORD
N   gI              insert text in column 1 (N times)
    gU{motion}      make the text that is moved over with {motion} uppercase
    ga              show ascii value of character under cursor in decimal, hex, and octal
    gd              goto local declaration of identifier under the cursor
    gf  or ]f       Edit the file whose name is under the cursor
N   ge              backward to the end of the Nth word
N   gg              goto line N (default: first line), on the first non-blank character
N   gj              down N screen lines (differs from "j" when line wraps)
N   gk              up N screen lines (differs from "k" when line wraps)
N   gq{motion}      format the lines that are moved over with {motion} to 'textwidth' length
N   gs              Goto Sleep for N seconds
    gu{motion}      make the text that is moved over with {motion} lowercase
    gv              start highlighting on previous visual area
N   h               left (also: CTRL-H, <BS>, or <Left> key)
N   i               insert text before the cursor (N times) (also: <Insert>)
N   j               down N lines (also: CTRL-J, CTRL-N, <NL>, and <Down>)
N   k               up N lines (also: CTRL-P and <Up>)
N   l               right (also: <Space> or <Right> key)
N   n               repeat last search
    m<a-zA-Z>       mark current position with mark <a-zA-Z>
N   o               open a new line below the current line, append text (N times)
    o               exchange cursor position with start of highlighting
N   p               put a register after the cursor position (N times)
    q               stop recording
    q<A-Z>          record typed characters, appended to register <a-z>
    q<a-z>          record typed characters into register <a-z>
N   r<char>         replace N characters with <char>
N   s               change N characters
N   t<char>         till before the Nth occurrence of <char> to the right
N   u               undo last N changes
VIS u               make highlighted text lowercase
    v               highlight characters or stop highlighting
    v               start highlighting characters  }  move cursor and use
N   w               N words forward
N   x               delete N characters under and after the cursor
N   yy              yank N lines 
N   y{motion}       yank the text moved over with {motion} 
VIS y               yank the highlighted text 
    z- or zb        redraw, current line at bottom of window
    z. or zz        redraw, current line at center of window
    z<CR> or zt     redraw, current line at top of window
N   zh              scroll screen N characters to the right
N   zl              scroll screen N characters to the left
.. @+node:ekr.20131105122124.16483: *3* vim regex
                                           Value of magic option
                                           ---------------------
                        meaning            magic       nomagic

           matches any single character      .            \.
                  matches start of line      ^            ^
                    matches end of line      $            $
                  matches start of word      \<           \<
                    matches end of word      \>           \>
   matches a single char from the range      [a-z]        \[a-z]
 matches a single char not in the range      [^a-z]       \[^a-z]
             matches an identifier char      \i           \i
              idem but excluding digits      \I           \I
            matches a keyword character      \k           \k
              idem but excluding digits      \K           \K
           matches a filename character      \f           \f
              idem but excluding digits      \F           \F
          matches a printable character      \p           \p
              idem but excluding digits      \P           \P

                          matches <Esc>      \e           \e
                          matches <Tab>      \t           \t
                           matches <CR>      \r           \r
                           matches <BS>      \b           \b

matches 0 or more of the preceding atom      *            \*
matches 1 or more of the preceding atom      \+           \+
   matches 0 or 1 of the preceding atom      \=           \=
                 separates two branches      \|           \|
           group a pattern into an atom      \(\)         \(\)
.. @+node:ekr.20131105122124.16484: *3* keys in insert mode
    char                action in Insert mode
    ----                --------------------- 
 
    <Esc>               end Insert mode, back to Normal mode
    <BS> or CTRL-H      delete the character before the cursor
    {char1} <BS> {char2}    enter digraph if 'digraph' option set
    <Del>               delete the character under the cursor
    <End>               cursor after last character in the line
    <Home>              cursor to first character in the line
    <NL> or <CR>        begin new line
    
    cursor keys         move cursor left/right/up/down
    shift-left/right    one word left/right
    shift-up/down       one screenful backward/forward

    CTRL-@              insert previously inserted text and stop insert
    CTRL-A              insert previously inserted text
    CTRL-B              toggle 'revins' (reverse insert) option
    CTRL-C              like <Esc>, but do not do an abbreviation
    CTRL-D              delete one shiftwidth of indent in front of the current line
0   CTRL-D              delete all indent in the current line
^   CTRL-D              delete all indent in the current line, restore indent in next line
    CTRL-E              insert the character from below the cursor
    CTRL-K {char1} {char2}  enter digraph
    CTRL-M or CTRL-J    begin new line
    CTRL-N              insert next match of identifier before the cursor
    CTRL-O {command}    execute {command}
    CTRL-P              insert previous match of identifier before the cursor
    CTRL-R <0-9a-z%:.-"> insert contents of register <0-9a-z%:.-">
    CTRL-T              insert one shiftwidth of indent in front of the current line
    CTRL-U              delete all entered characters in the current line
    CTRL-V <char>..     insert character literally, or enter decimal byte value
    CTRL-W              delete word before the cursor
    CTRL-X ...          complete the word before the cursor in various ways
    CTRL-Y              insert the character from above the cursor
.. @+node:ekr.20131105122124.16485: *3* complex
N  !{motion}{command}<CR>  filter the lines that are moved over through {command}
N  !!{command}<CR>         filter N lines through {command}
   {visual}!{command}<CR>  filter the highlighted lines through {command}
   :[range]! {command}<CR> filter [range] lines through {command}
N  ={motion}               filter the lines that are moved over through "indent"
N  ==                      filter N lines through "indent"
   {visual}=               filter the highlighted lines through "indent"
   
:[range]s[ubstitute]/{pattern}/{string}/[g][c]
:[range]s[ubstitute] [g][c]
   &         Repeat previous ":s" on current line without options
:[range]ret[ab][!] [tabstop]
.. @+node:ekr.20131105122124.16486: *3* text object
Used only in Visual mode or after an operator

a            Select current word
A            Select current WORD
s            Select current sentence
p            Select current paragraph
S            Select current block (from "[(" to "])")
P            Select current block (from "[{" to "]}")
.. @+node:ekr.20131105122124.16487: *3* offsets after search command
[num]       [num] lines downwards, in column 1
+[num]      [num] lines downwards, in column 1
-[num]      [num] lines upwards, in column 1
e[+num]     [num] characters to the right of the end of the match
e[-num]     [num] characters to the left of the end of the match
s[+num]     [num] characters to the right of the start of the match
s[-num]     [num] characters to the left of the start of the match
b[+num]     [num] characters to the right of the start (begin) of the match
b[-num]     [num] characters to the left of the start (begin) of the match
;{search command}   execute {search command} next


/test/+1		one line below "test", in column 1
/test/e			on the last t of "test"
/test/s+2		on the 's' of "test"
/test/b-3		three characters before "test"
.. @+node:ekr.20131105122124.16488: *3* Examples
:%g/^a/-1join     join lines starting with character 'a' to previous line
:%g/^ *$/d        delete empty lines
:%v/vim/m 1       move lines not matching the word 'vim' to line 1
:%g/^a/+1d        delete lines after the ones starting with character 'a'

:so[urce] {file}    Read Ex commands from {file}.
:so[urce]! {file}   Read Vim commands from {file}.
:sl[eep] [N]        don't do anything for N seconds
.. @+node:ekr.20131105122124.16489: *3* Options overview

name       short name   explanation
----       ----------   -----------
aleph          al       ASCII code of the letter Aleph (RIGHTLEFT)
autoindent     ai       take indent for new line from previous line
autowrite      aw       automatically write file if changed
backspace      bs       how backspace works at start of line
backup         bk       keep backup file after overwriting a file
backupdir      bdir     list of directories for the backup file
backupext      bex      extension used for the backup file
binary         bin      edit binary file mode
bioskey        biosk    MS-DOS: use bios calls for input characters
breakat        brk      characters that may cause a line break
cindent        cin      do C program indenting
cinkeys        cink     keys that trigger indent when 'cindent' is set
cinoptions     cino     how to do indenting when 'cindent' is set
cinwords       cinw     words where 'si' and 'cin' add an indent
cmdheight      ch       number of lines to use for the command-line
columns        co       number of columns in the display
comments       com      patterns that can start a comment line
compatible     cp       behave Vi-compatibly as much as possible
cpoptions      cpo      flags for Vi-compatible behaviour
define         def      pattern to be used to find a macro definition
dictionary     dict     list of filenames used for keyword completion
digraph        dg       enable the entering of digraphs in Insert mode
directory      dir      list of directory names for the swapfile
edcompatible   ed       toggle flags of ":substitute" command
endofline      eol      write end-of-line for last line in file
equalalways    ea       windows are automatically made the same size
equalprg       ep       external program to use for "=" command
errorbells     eb       ring the bell for error messages
errorfile      ef       name of the error file for the QuickFix mode
errorformat    efm      description of the lines in the error file
esckeys        ek       recognize function keys in Insert mode
expandtab      et       use spaces when <Tab> is inserted
exrc                    read .vimrc and .exrc in the current directory
formatoptions  fo       how automatic formatting is to be done
formatprg      fp       name of external program used with "gq" command
gdefault       gd       the ":substitute" flag 'g' is default on
guifont        gfn      GUI: Name(s) of font(s) to be used
guioptions     go       GUI: Which components and options are used
guipty                  GUI: try to use a pseudo-tty for ":!" commands
helpfile       hf       name of this help file
helpheight     hh       minimum height of a new help window
hidden         hid      don't unload buffer when it is abandoned
highlight      hl       sets highlighting mode for various occasions
history        hi       number of command-lines that are remembered
hkmap          hk       Hebrew keyboard mapping (RIGHTLEFT)
icon                    set icon of the window to the name of the file
ignorecase     ic       ignore case in search patterns
include        inc      pattern to be used to find an include file
incsearch      is       highlight match while typing search pattern
infercase      inf      adjust case of match for keyword completion
insertmode     im       start the edit of a file in Insert mode
isfname        isf      characters included in filenames and pathnames
isident        isi      characters included in identifiers
isprint        isp      printable characters
iskeyword      isk      characters included in keywords
joinspaces     js       two spaces after a period with a join command
keywordprg     kp       program to use for the "K" command
langmap        lmap     alphabetic characters for other language mode
laststatus     ls       tells when last window has status lines
linebreak      lbr      wrap long lines at a blank
lines                   number of lines in the display
lisp                    automatic indenting for Lisp
list                    show <Tab> and end-of-line
magic                   changes special characters in search patterns
makeprg        mp       program to use for the ":make" command
maxmapdepth    mmd      maximum recursive depth for mapping
maxmem         mm       maximum memory (in Kbyte) used for one buffer
maxmemtot      mmt      maximum memory (in Kbyte) used for all buffers
modeline       ml       recognize modelines at start or end of file
modelines      mls      number of lines checked for modelines
modified       mod      buffer has been modified
more                    pause listings when the whole screen is filled
mouse                   enable the use of mouse clicks
mousetime      mouset   max time between mouse double-click
number         nu       print the line number in front of each line
paragraphs     para     nroff macros that separate paragraphs
paste                   allow pasting text
patchmode      pm       keep the oldest version of a file
path           pa       list of directories searched with "gf" et.al.
readonly       ro       disallow writing the buffer
remap                   allow mappings to work recursively
report                  threshold for reporting nr. of lines changed
restorescreen  rs       Win32: restore screen when exiting
revins         ri       inserting characters will work backwards
rightleft      rl       window is right-to-left oriented (RIGHTLEFT)
ruler          ru       show cursor line and column in the status line
scroll         scr      lines to scroll with CTRL-U and CTRL-D
scrolljump     sj       minimum number of lines to scroll
scrolloff      so       minimum nr. of lines above and below cursor
sections       sect     nroff macros that separate sections
secure                  secure mode for reading .vimrc in current dir
shell          sh       name of shell to use for external commands
shellcmdflag   shcf     flag to shell to execute one command
shellpipe      sp       string to put output of ":make" in error file
shellquote     shq      quote character(s) for around shell command
shellredir     srr      string to put output of filter in a temp file
shelltype      st       Amiga: influences how to use a shell
shiftround     sr       round indent to multiple of shiftwidth
shiftwidth     sw       number of spaces to use for (auto)indent step
shortmess      shm      list of flags, reduce length of messages
shortname      sn       non-MS-DOS: File names assumed to be 8.3 chars
showbreak      sbr      string to use at the start of wrapped lines
showcmd        sc       show (partial) command in status line
showmatch      sm       briefly jump to matching bracket if insert one
showmode       smd      message on status line to show current mode
sidescroll     ss       minimum number of columns to scroll horizontal
smartcase      scs      no ignore case when pattern has uppercase
smartindent    si       smart autoindenting for C programs. For perl
                        script editing set this option and the following
                        key mapping: inoremap # x<BS># 
smarttab       sta      use 'shiftwidth' when inserting <Tab>
splitbelow     sb       new window from split is below the current one
startofline    sol      commands move cursor to first blank in line
suffixes       su       suffixes that are ignored with multiple match
swapsync       sws      how to sync swapfile
tabstop        ts       number of spaces that <Tab> in file uses
taglength      tl       number of significant characters for a tag
tagrelative    tr       filenames in tag file are relative
tags           tag      list of filenames used by the tag command
term                    name of the terminal
terse                   shorten some messages
textauto       ta       set 'textmode' automatically when reading file
textmode       tx       lines are separated by <CR><NL>
textwidth      tw       maximum width of text that is being inserted
tildeop        top      tilde command "~" behaves like an operator
timeout        to       time out on mappings and key codes
ttimeout                time out on mappings
timeoutlen     tm       time out time in milliseconds
ttimeoutlen    ttm      time out time for key codes in milliseconds
title                   set title of window to the name of the file
ttybuiltin     tbi      use built-in termcap before external termcap
ttyfast        tf       indicates a fast terminal connection
ttyscroll      tsl      maximum number of lines for a scroll
ttytype        tty      alias for 'term'
undolevels     ul       maximum number of changes that can be undone
updatecount    uc       after this many characters flush swapfile
updatetime     ut       after this many milliseconds flush swapfile
viminfo        vi       use .viminfo file upon startup and exiting
visualbell     vb       use visual bell instead of beeping
warn                    warn for shell command when buffer was changed
weirdinvert    wi       for terminals that have weird inversion method
whichwrap      ww       allow specified keys to cross line boundaries
wildchar       wc       command-line character for wildcard expansion
winheight      wh       minimum number of lines for the current window
wrap                    long lines wrap and continue on the next line
wrapmargin     wm       chars from the right where wrapping starts
wrapscan       ws       searches wrap around the end of the file
writeany       wa       write to file with no need for "!" override
writebackup    wb       make a backup before overwriting a file
writedelay     wd       delay this many msec for each char (for debug)
.. @+node:ekr.20131105122124.16490: *3* Command-line completion
'wildchar' (default: <Tab>)
    do completion on the pattern in front of the cursor. If there are
    multiple matches, beep and show the first one; further 'wildchar' will
    show the next ones.
                   
CTRL-A  insert all names that match pattern in front of cursor
CTRL-D  list all names that match the pattern in front of the cursor
CTRL-L  insert longest common part of names that match pattern
CTRL-N  after 'wildchar' with multiple matches: go to next match
CTRL-P  after 'wildchar' with multiple matches: go to previous match
.. @+node:ekr.20131105122124.16491: *3* Special Ex characters

|           separates two commands (not for ":global" and ":!")
"           begins comment

%           current filename (only where filename is expected)
#[number]   alternate filename [number] (only where filename is expected)

Note: The next four are typed literally; these are not special keys!

<cword>     word under the cursor (only where filename is expected)
<cWORD>     WORD under the cursor (only where filename is expected)
<cfile>     file name under the cursor (only where filename is expected)
<afile>     file name for autocommand (only where filename is expected)

After "%", "#", "<cfile>", or "<afile>"
:p          full path
:h          head
:t          tail
:r          root
:e          extension
.. @+node:ekr.20131105122124.16492: *3* Ex ranges
,               separates two line numbers
;               idem, set cursor to the first line number
                before interpreting the second one
{number}        an absolute line number
.               the current line
$               the last line in the file
%               equal to 1,$ (the entire file)
*               equal to '<,'> (visual area)
't              position of mark t
/{pattern}[/]   the next line where {pattern} matches
?{pattern}[?]   the previous line where {pattern} matches
+[num]          add [num] to the preceding line number (default: 1)
-[num]          subtract [num] from the preceding line number (default: 1)
.. @+node:ekr.20131105122124.16493: *3* Starting vim
38 -- Starting VIM


vim [options]                start editing with an empty buffer
vim [options] {file ..}      start editing one or more files
vim [options] -t {tag}       edit the file associated with {tag}
vim [options] -e [fname]     start editing in QuickFix mode, display the first error


39 -- Vim Command Line Arguments


-g                  start GUI (also allows other options)

+[num]              put the cursor at line [num] (default: last line)
+{command}          execute {command} after loading the file
+/{pat} {file ..}   put the cursor at the first occurrence of {pat}
-v                  read-only mode (View), implies -n
-R                  read-only mode, same as -v
-b                  binary mode
-l                  lisp mode
-H                  Hebrew mode ('hkmap' and 'rightleft' are set)
-r                  give list of swap files
-r {file ..}        recover aborted edit session
-n                  do not create swapfile
-o [N]              open N windows (default: one for each file)
-x                  Amiga: do not restart VIM to open a window (for
                        e.g., mail)
-s {scriptin}       first read commands from the file {scriptin}
-w {scriptout}      write typed chars to file {scriptout} (append)
-W {scriptout}      write typed chars to file {scriptout} (overwrite)
-T {terminal}       set terminal name
-d {device}         Amiga: open {device} to be used as a console
-u {vimrc}          read inits from {vimrc} instead of other inits
-i {viminfo}        read info from {viminfo} instead of other files
--                  end of options, other arguments are file names

Automatic option setting when editing a file

vim:{set-arg}: ..       In the first and last lines of the
                        file (see 'ml' option), {set-arg} is
                        given as an argument to ":set"
                        
Automatic execution of commands on certain events.

:au                     List all autocommands
:au {event}             List all autocommands for {event}
:au {event} {pat}       List all autocommands for {event} with {pat}
:au {event} {pat} {cmd} Enter new autocommands for {event} with {pat}
:au!                    Remove all autocommands
:au! {event}            Remove all autocommands for {event}
:au! * {pat}            Remove all autocommands for {pat}
:au! {event} {pat}      Remove all autocommands for {event} with {pat}
:au! {event} {pat} {cmd}  Remove all autocommands for {event} with {pat} and enter new one
.. @+node:ekr.20131105122124.16494: *3* : commands unsorted
:marks                  print the active marks
:ju[mps]                print the jump list
:ta[g][!] {tag}         Jump to tag {tag}
:[count]ta[g][!]        Jump to [count]'th newer tag in tag list
:[count]po[p][!]        Jump back from [count]'th older tag in tag list
:tags                   Print tag list
:dig[raphs]                                 show current list of digraphs
:dig[raphs] {char1}{char2} {number} ...     add digraph(s) to the list
:r [file]               insert the contents of [file] below the cursor
:r! {command}           insert the standard output of {command} below the cursor
:[range]d [x]           delete [range] lines [into register x]
:reg                    show the contents of all registers
:reg {arg}              show the contents of registers mentioned in {arg}
:[range]ce[nter] [width] center the lines in [range]
:[range]le[ft] [indent]  left-align the lines in [range] [with indent]
:[range]ri[ght] [width]  right-align the lines in [range]
:@<a-z>                 execute the contents of register <a-z> as an Ex command
:@@                     repeat previous :@<a-z>
:[range]g[lobal]/{pattern}/[cmd] 
:[range]g[lobal]!/{pattern}/[cmd]     or    :[range]v/{pattern}/[cmd]
:ma[p] {lhs} {rhs}          Map {lhs} to {rhs} in Normal and Visual mode.
:ma[p]! {lhs} {rhs}         Map {lhs} to {rhs} in Insert and Command-line mode.
:no[remap][!] {lhs} {rhs}   Same as ":map", no remapping for this {rhs}
:unm[ap] {lhs}              Remove the mapping of {lhs} for Normal and Visual mode.
:unm[ap]! {lhs}             Remove the mapping of {lhs} for Insert and Command-line mode.
:ma[p] [lhs]         List mappings (starting with [lhs]) for Normal and Visual mode.
:ma[p]! [lhs]        List mappings (starting with [lhs]) for Insert and Command-line mode.
:cmap/:cunmap/:cnoremap 
:imap/:iunmap/:inoremap
:nmap/:nunmap/:nnoremap
:vmap/:vunmap/:vnoremap
:mk[exrc][!] [file]  write current mappings, abbreviations, and settings to [file] (default: ".exrc"; use ! to overwrite)
:mkv[imrc][!] [file] same as ":mkexrc", but with default ".vimrc"
:mapc[lear]          remove mappings for Normal and Visual mode
:mapc[lear]!         remove mappings for Insert and Cmdline mode
:imapc[lear]         remove mappings for Insert mode
:vmapc[lear]         remove mappings for Visual mode
:nmapc[lear]         remove mappings for Normal mode
:cmapc[lear]         remove mappings for Cmdline mode

:ab[breviate] {lhs} {rhs}  add abbreviation for {lhs} to {rhs}
:ab[breviate] {lhs}        show abbr's that start with {lhs}
:ab[breviate]              show all abbreviations
:una[bbreviate] {lhs}      remove abbreviation for {lhs}
:norea[bbrev] [lhs] [rhs]  like ":ab", but don't remap [rhs]
:iab/:iunab/:inoreab       like ":ab", but only for Insert mode
:cab/:cunab/:cnoreab       like ":ab", but only for Command-line mode
:abc[lear]                 remove all abbreviations
:cabc[lear]                remove all abbr's for Cmdline mode
:iabc[lear]                remove all abbr's for Insert mode
:se[t]                  Show all modified options.
:se[t] all              Show all options.
:se[t] {option}         Set toggle option on, show string or number option.
:se[t] no{option}       Set toggle option off.
:se[t] inv{option}      invert toggle option.
:se[t] {option}={value} Set string or number option to {value}.
:se[t] {option}?        Show value of {option}.
:se[t] {option}&        Reset {option} to its default value.
:fix[del]               Set value of 't_kD' according to value of 't_kb'.
:sh[ell]        start a shell
:!{command}     execute {command} with a shell
:cc [nr]        display error [nr] (default is the same again)
:cn             display the next error
:cp             display the previous error
:cl             list all errors
:cf             read errors from the file 'errorfile'
:cq             quit without writing and return error code (to the compiler)
:make [args]    start make, read errors, and jump to first error
:ve[rsion]      show exact version number of this Vim
:mode N         MS-DOS: set screen mode to N (number, C80, C4350, etc.)
:norm[al][!] {commands} Execute Normal mode commands.
:e[dit]              Edit the current file, unless changes have been made.
:e[dit]!             Edit the current file always.  Discard any changes.
:e[dit] {file}       Edit {file}, unless changes have been made.
:e[dit]! {file}      Edit {file} always.  Discard any changes.
:pwd                 Print the current directory name.
:cd [path]           Change the current directory to [path].
:f[ile]              Print the current filename and the cursor position.
:f[ile] {name}       Set the current filename to {name}.
:files               Show alternate filenames.

:argu[ment] N       edit file N
:n[ext]             edit next file
:n[ext] {arglist}   define new arg list and edit first file
:N[ext]             edit previous file
:rew[ind][!]        edit first file
:last               edit last file
:sar[gument] N      edit file N (new window)
:sn[ext]            edit next file (new window)
:sn[ext] {arglist}  define new arg list and edit first file (new window)
:sN[ext]            Edit previous file (new window)
:srew[ind]          Edit first file (new window)
:slast              Edit last file (new window)


:ar[gs]              Print the argument list, with the current file in "[]".
:all  or :sall       Open a window for every file in the arg list.
:wn[ext][!]          Write file and edit next file.
:wn[ext][!] {file}   Write to {file} and edit next file, unless {file} exists.  With !, overwrite existing file.
:wN[ext][!] [file]   Write file and edit previous file.
:[range]w[rite][!]            Write to the current file.
:[range]w[rite] {file}        Write to {file}, unless it already exists.
:[range]w[rite]! {file}       Write to {file}.  Overwrite an existing file.
:[range]w[rite][!] >>         Append to the current file.
:[range]w[rite][!] >> {file}  Append to {file}.
:[range]w[rite] !{cmd}        Execute {cmd} with [range] lines as standard input.
:wall[!]                      write all changed buffers

:q[uit]               Quit current buffer.
:q[uit]!              Quit current buffer always.
:qall                 Exit Vim, unless changes have been made.
:qall!                Exit Vim always, discard any changes.
:cq                   Quit without writing and return error code.

:wq[!]                Write the current file and exit.
:wq[!] {file}         Write to {file} and exit.
:x[it][!] [file]      Like ":wq" but write only when changes have been made
:xall[!]  or :wqall[!]  Write all changed buffers and exit
:st[op][!]              Suspend VIM or start new shell. If 'aw' option is set and [!] not given write the buffer.

:rv[iminfo] [file]      Read info from viminfo file [file]
:rv[iminfo]! [file]     idem, overwrite exisiting info
:wv[iminfo] [file]      Add info to viminfo file [file]
:wv[iminfo]! [file]     Write info to viminfo file [file]

:split                  Split window into two parts
:split {file}           Split window and edit {file} in one of them

:buffers  or  :files    list all known buffer and file names
:ball     or  :sball    edit all args/buffers
:unhide   or  :sunhide  edit all loaded buffers

:bunload[!] [N]         unload buffer [N] from memory
:bdelete[!] [N]         unload buffer [N] and delete it from the buffer list

:[N]buffer [N]      to arg/buf N
:[N]bnext [N]       to Nth next arg/buf
:[N]bNext [N]       to Nth previous arg/buf
:[N]bprevious [N]   to Nth previous arg/buf
:brewind            to first arg/buf
:blast              to last arg/buf
:[N]bmod [N]        to Nth modified buf

:[N]sbuffer [N]     to arg/buf N (in new window)
:[N]sbnext [N]      to Nth next arg/buf (in new window)
:[N]sbNext [N]      to Nth previous arg/buf (in new window)
:[N]sbprevious [N]  to Nth previous arg/buf (in new window)
:sbrewind           to first arg/buf (in new window)
:sblast             to last arg/buf (in new window)
:[N]sbmod [N]       to Nth modified buf (in new window)
.. @+node:ekr.20131105122124.16495: *3* : commands merged (do not sort!)
:!{command}                     execute {command} with a shell
:@<a-z>                         execute the contents of register <a-z> as an Ex command
:@@                             repeat previous :@<a-z>
:N[ext]                         edit previous file
:ab[breviate]                   show all abbreviations
:ab[breviate] {lhs}             show abbr's that start with {lhs}
:ab[breviate] {lhs} {rhs}       add abbreviation for {lhs} to {rhs}
:abc[lear]                      remove all abbreviations
:all  or :sall                  open a window for every file in the arg list.
:ar[gs]                         print the argument list, with the current file in "[]".
:argu[ment] N                   edit file N
:[N]bNext [N]                   to Nth previous arg/buf
:ball     or  :sball            edit all args/buffers
:bdelete[!] [N]                 unload buffer [N] and delete it from the buffer list
:blast                          to last arg/buf
:[N]bmod [N]                    to Nth modified buf
:[N]bnext [N]                   to Nth next arg/buf
:[N]bprevious [N]               to Nth previous arg/buf
:[N]buffer [N]                  to arg/buf N
:brewind                        to first arg/buf
:buffers  or  :files            list all known buffer and file names
:bunload[!] [N]                 unload buffer [N] from memory
:cab/:cunab/:cnoreab            like ":ab", but only for Command-line mode
:cabc[lear]                     remove all abbr's for Cmdline mode
:cc [nr]                        display error [nr] (default is the same again)
:cd [path]                      change the current directory to [path].
:[range]ce[nter] [width]        center the lines in [range]
:cf                             read errors from the file 'errorfile'
:cl                             list all errors
:cmap/:cunmap/:cnoremap 
:cmapc[lear]                    remove mappings for Cmdline mode
:cn                             display the next error
:cp                             display the previous error
:cq                             quit without writing and return error code.
:cq                             quit without writing and return error code (to the compiler)
:[range]d [x]                   delete [range] lines [into register x]
:dig[raphs]                     show current list of digraphs
:dig[raphs] {char1}{char2} {number} ...     add digraph(s) to the list
:e[dit]                         edit the current file, unless changes have been made.
:e[dit] {file}                  edit {file}, unless changes have been made.
:e[dit]!                        edit the current file always.  Discard any changes.
:e[dit]! {file}                 edit {file} always.  Discard any changes.
:f[ile]                         print the current filename and the cursor position.
:f[ile] {name}                  set the current filename to {name}.
:files                          show alternate filenames.
:fix[del]                       set value of 't_kD' according to value of 't_kb'.
:[range]g[lobal]!/{pattern}/[cmd]
:[range]g[lobal]/{pattern}/[cmd] 
:iab/:iunab/:inoreab            like ":ab", but only for Insert mode
:iabc[lear]                     remove all abbr's for Insert mode
:imap/:iunmap/:inoremap
:imapc[lear]                    remove mappings for Insert mode
:ju[mps]                        print the jump list
:last                           edit last file
:[range]le[ft] [indent]         left-align the lines in [range] [with indent]
:ma[p] [lhs]                    list mappings (starting with [lhs]) for Normal and Visual mode.
:ma[p] {lhs} {rhs}              map {lhs} to {rhs} in Normal and Visual mode.
:ma[p]! [lhs]                   list mappings (starting with [lhs]) for Insert and Command-line mode.
:ma[p]! {lhs} {rhs}             map {lhs} to {rhs} in Insert and Command-line mode.
:make [args]                    start make, read errors, and jump to first error
:mapc[lear]                     remove mappings for Normal and Visual mode
:mapc[lear]!                    remove mappings for Insert and Cmdline mode
:marks                          print the active marks
:mk[exrc][!] [file]             write current mappings, abbreviations, and settings to [file] (default: ".exrc"; use ! to overwrite)
:mkv[imrc][!] [file]            same as ":mkexrc", but with default ".vimrc"
:mode N                         MS-DOS: set screen mode to N (number, C80, C4350, etc.)
:n[ext]                         edit next file
:n[ext] {arglist}               define new arg list and edit first file
:nmap/:nunmap/:nnoremap
:nmapc[lear]                    remove mappings for Normal mode
:no[remap][!] {lhs} {rhs}       same as ":map", no remapping for this {rhs}
:norea[bbrev] [lhs] [rhs]       like ":ab", but don't remap [rhs]
:norm[al][!] {commands}         execute Normal mode commands.
:[count]po[p][!]                jump back from [count]'th older tag in tag list
:pwd                            print the current directory name.
:q[uit]                         quit current buffer.
:q[uit]!                        quit current buffer always.
:qall                           exit Vim, unless changes have been made.
:qall!                          exit Vim always, discard any changes.
:r [file]                       insert the contents of [file] below the cursor
:r! {command}                   insert the standard output of {command} below the cursor
:reg                            show the contents of all registers
:reg {arg}                      show the contents of registers mentioned in {arg}
:rew[ind][!]                    edit first file
:[range]ri[ght] [width]         right-align the lines in [range]
:rv[iminfo] [file]              read info from viminfo file [file]
:rv[iminfo]! [file]             idem, overwrite exisiting info
:sN[ext]                        edit previous file (new window)
:sar[gument] N                  edit file N (new window)
:sblast                         to last arg/buf (in new window)
:[N]sbNext [N]                  to Nth previous arg/buf (in new window)
:[N]sbmod [N]                   to Nth modified buf (in new window)
:[N]sbnext [N]                  to Nth next arg/buf (in new window)
:[N]sbprevious [N]              to Nth previous arg/buf (in new window)
:[N]sbuffer [N]                 to arg/buf N (in new window)
:sbrewind                       to first arg/buf (in new window)
:se[t]                          show all modified options.
:se[t] all                      show all options.
:se[t] inv{option}              invert toggle option.
:se[t] no{option}               set toggle option off.
:se[t] {option}                 set toggle option on, show string or number option.
:se[t] {option}&                reset {option} to its default value.
:se[t] {option}={value}         set string or number option to {value}.
:se[t] {option}?                show value of {option}.
:sh[ell]                        start a shell
:slast                          edit last file (new window)
:sn[ext]                        edit next file (new window)
:sn[ext] {arglist}              define new arg list and edit first file (new window)
:split                          Split window into two parts
:split {file}                   Split window and edit {file} in one of them
:srew[ind]                      Edit first file (new window)
:st[op][!]                      Suspend VIM or start new shell. If 'aw' option is set and [!] not given write the buffer.
:[count]ta[g][!]                jump to [count]'th newer tag in tag list
:ta[g][!] {tag}                 jump to tag {tag}
:tags                           print tag list
:una[bbreviate] {lhs}           remove abbreviation for {lhs}
:unhide   or  :sunhide          edit all loaded buffers
:unm[ap] {lhs}                  remove the mapping of {lhs} for Normal and Visual mode.
:unm[ap]! {lhs}                 remove the mapping of {lhs} for Insert and Command-line mode.
:[range]v/{pattern}/[cmd]
:ve[rsion]                      show exact version number of this Vim
:vmap/:vunmap/:vnoremap
:vmapc[lear]                    remove mappings for Visual mode
:[range]w[rite] !{cmd}          execute {cmd} with [range] lines as standard input.
:[range]w[rite] {file}          write to {file}, unless it already exists.
:[range]w[rite]! {file}         write to {file}.  Overwrite an existing file.
:[range]w[rite][!]              write to the current file.
:[range]w[rite][!] >>           append to the current file.
:[range]w[rite][!] >> {file}    append to {file}.
:wN[ext][!] [file]              write file and edit previous file.
:wall[!]                        write all changed buffers
:wn[ext][!]                     write file and edit next file.
:wn[ext][!] {file}              write to {file} and edit next file, unless {file} exists.  With !, overwrite existing file.
:wq[!]                          write the current file and exit.
:wq[!] {file}                   write to {file} and exit.
:wv[iminfo] [file]              add info to viminfo file [file]
:wv[iminfo]! [file]             write info to viminfo file [file]
:x[it][!] [file]                like ":wq" but write only when changes have been made
:xall[!]  or :wqall[!]          Write all changed buffers and exit
.. @-all
.. @-leo
