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

.. @+all
.. @+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.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.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.20131213072223.16396: ** Old screencast scripts
.. @+node:ekr.20131211054925.16385: *3* - Introduction to Leo
@language rest

This screencast is a *brief* introduction to Leo.

Other video tutorials will cover all of Leo's features in more detail.
.. @+node:ekr.20131211054925.16391: *4* Leo has standard outline operations
Leo looks like an ordinary outlining program.

The headline describes the contents of an outline node.

The body pane shows contents (body text) of the selected node.

You can insert, move, delete, copy and paste nodes.
.. @+node:ekr.20131211054925.16392: *4* Leo has three unique features
.. @+node:ekr.20131211054925.16389: *5* Leo outlines can create files
@file nodes create **external files** from outlines.

External files are files on your file system.

Leo outlines work much like project files in an IDE.
.. @+node:ekr.20131211054925.16390: *5* Leo outlines are scriptable
- Every outline node can contain a Python script.

- Leo scripts have *easy* access to all data
  *in the outline in which the script resides*.
  
Example:

    g.es(p.h)
.. @+node:ekr.20131211054925.16393: *5* Nodes can be cloned
Nodes may appear many times within the same outline.

A change to one clone affects all the other clones of that node.
.. @+node:ekr.20131212054637.16399: *6* Node A
This is node A.
.. @+node:ekr.20131212054637.16400: *7* Node B
This is node B.
.. @+node:ekr.20131212054637.16400: *7* Node B
This is node B.
.. @+node:ekr.20131212054637.16399: *6* Node A
This is node A.
.. @+node:ekr.20131212054637.16400: *7* Node B
This is node B.
.. @+node:ekr.20131212054637.16400: *7* Node B
This is node B.
.. @+node:ekr.20131211054925.16394: *4* Summary
1. Leo looks like an ordinary outliner program.

2. Leo really is an IDE.

3. Leo scripts have full, easy access to all outline data.

4. Nodes may be cloned.
.. @+node:ekr.20140212062130.16585: ** Prewriting for theory of operation for @auto-view
@language rest


.. @+node:ekr.20140212062130.16586: *3* Distinction: bare and nested organizers
Two major new Aha's have appeared. As often happens, they were the result
of a new distinction:

  **Nested** organizer nodes will become children of *other* organizer nodes.

  **Bare** organizer nodes will become children of *ordinary* nodes.
.. @+node:ekr.20140212062130.16587: *3* Two Ahas re nested organizers
Aha 1: We don't have to compute child indices for nodes moved to children
of organizer nodes!

We simply put them on a list (in imported outline order) of tuples
(parent,moved_node). There will be only *one* such list, say
vc.global_moved_node_list.

When the time comes to do the actual moves, we do the following:

- Reverse the global list, thereby guaranteeing that positions that appear
   later in the reversed list remain valid.
- Insert each item on the list as the *last* child of the parent
   (organizer) node.
   
​There is a small, easily corrected, hole in this argument. It assumes that
positions appear in the list in outline order. That's usually so, but not
always. Indeed, @organizer: nodes *are* written in outline order, as are
their contents, but rearrangements in the imported outline could
conceivably mean that the nodes corresponding to @organizer nodes would not
be handled in the *new* outline order. This is easily remedied: just sort
the list in (imported) outline order before reversing it

That's all!

Using a global list was hard to see, because typically such schemes don't
work in recursive environments. But the @auto-view algorithms are *not*
recursive. Each @organizer: node is handled separately, in a completely
linear fashion, by vc.demote_helper, the true main line of the code.

Aha 2:  We can treat *nested* organizer nodes just as we treat ordinary nodes!

vc.switch_active_organizer (the code that handles the entry into an
organizer node) will simply add another entry (parent,organizer_node) to
the global move list.

Not having to track most child indices is a major collapse in complexity.
Indeed, the code that moves nodes to their final destinations will have no
"if" statements at all. It doesn't get any more solid than that.
.. @+node:ekr.20140212062130.16588: *3* Moving bare organizers
===== Moving bare organizer nodes.

Now that moving most nodes has become trivial, the only remaining task is
to *safely* move bare organizers. This task has two parts:

1. Determine the proper child index of *bare* organizer nodes.

This will be done in the main line: vc.demote_helper will maintain a count
n of imported nodes that *haven't* been assigned to organizer nodes. This
count must also be incremented to include bare organizer nodes the will be
inserted later. It's just a bit tricky, but there are only a few cases to
get right. Once it works, it will work forever.

There will be another global list, say vc.global_bare_organizer_node_list,
containing tuples (parent,bare_organizer,n). vc.switch_active_organizer
will add entries to this list, but *only* for bare organizer nodes.

2. Actually move the bare organizer nodes.

The children of bare organizer nodes will appear vc.global_moved_node_list.
Each (ordinary) parent node may contain several bare organizer nodes. Here
is how to get the job done safely:

- For each parent, create a new per-parent list, containing all entries of
  the global list with that parent.
- Sort each per-parent list using n as the key.
- Move the nodes in each per-parent list to their destinations, in sorted
  order.

At first glace, this seems entirely bogus. How are we to ensure that
positions stay valid?

Unlike for ordinary nodes, we can't process bare organizer nodes in reverse
outline order: we have to handle them in the *new* sibling order, that is,
sorted by n. In other words, it won't work to move them to the last child
of their parent! Nor can we move nodes to any arbitrary sibling position:
we must move nodes with smaller child indices before moving nodes with
larger child indices.

To solve this problem, the setup code places each organizer node in a
separate **holding cell**. Moving the bare organizer out of a holding cell
to its final resting place affects no other holding cells, and no other
organizer node.


.. @+node:ekr.20140212062130.16589: *3* Intermediate organizers
This post contains important insights for both users and developers.

The symptom of the bugs is that *non-bare* organizer nodes are not placed
in correct sibling order. As you recall, the value of n in the main line,
demote_helper, matters only for *bare* organizer nodes. So the proximate
cause of the problem is that pending nodes aren't entered on the global
node list before entering the organizers.

As we shall see below, the more fundamental problem is that the code does
not fully account for the outline relationships between organizer nodes. As
a result, the existing code does not always open and close organizer nodes
properly. (An organizer node is open when it may accumulated organized
nodes; an organizer node is closed when it can no longer accumulate
organized nodes without changing the order of the nodes in the @auto file.)

Two examples will illustrate the subtleties, and will lead naturally to a
new distinction, that of an **intermediate organizer** node.

Let's start with an easy case.  Suppose the organizer structure is:

  - @auto x.py
    - leading nodes
    - organizer A
       - node 1
       - organizer B
           - node 2
       - organizer C
       - node 3
    - organizer D

Clearly, the children of organizer A should be: node1, organizer B,
organizer C and node 3. That is, we must *not* close organizer A just
because we have entered organizer B or organizer C. Otoh, we *must* close
organizer A when we see organizer D.

The rule is clear: we must close an organizer whenever we see another
organizer that is not a descendant organizer.

The existing code creates parent/child data for OrganizerData instances. It
will be straightforward to add descendant relationships.

Let's consider another case:

- @auto x.py
    - leading nodes
    - organizer A
       - organizer B
         - organizer C
           - node 1
 
Here, organizer B is an **intermediate organizer** node. That is, it occurs
"between" organizers A and C.

Adding node 1 to the global node list should open organizer B, but the
present code does not. The present code opens an organizer node only when
adding a node to the organizer, but this example shows that organizer B
must be added to the global node list *before* any node is added to it.
Failure to do so results in organizer B being put in the wrong place.
.. @+node:ekr.20140212062130.16590: *3* Aha: organizers relationships are stable
As I was thinking about the outline relationships between organizer nodes,
I began to worry that minor changes to the imported @auto file might break
those relationships. In fact, the reverse is true: the relationships
between organizer nodes are *independent* of the @auto file!

The reason is simple: those relationships are created by the unl's in
@organizer: nodes in the .leo file. Furthermore, reorganizing the *outline*
will automatically update the unls in the @organizer nodes (in the @views
node) when the outline is saved. Thus, the *relationships* between
organizer nodes can never be broken by changes to the @auto node! This is
really important for users to know.

And there is more good news. Changing the contents of the @auto files can
indeed change the contents of organizer nodes, but the only way to totally
invalidate an organizer node is to change the *structural* relationships of
data in the @auto file. This almost never happens!

For example, if aClass is defined at the top level of the @auto file, then
the only way to invalidate the organizers that contain aClass or its
members is to move aClass so it is not a top-level node. But Leo's
importers will put aClass at the top level unless it becomes a nested class
in some other class! To repeat, this kind massive change to the context of
a class, function or method almost never happens.

In short, the links between unls (in @organizer: nodes) and imported
classes, methods and functions almost never break! This is truly great
news.
.. @+node:ekr.20140212062130.16591: *3* Summary
The following insights are important for users (and maintainers) to know:

- Changing an @auto file does not change the relationships between its
  organizer nodes in any way.
- Saving an outline automatically updates the relationships between
  organizer nodes.
- Unl's are much more stable than one might suppose: the *only* way to
  "break" organizer nodes is to change the fundamental relationships of
  classes, methods or functions in the imported @auto file. This almost
  *never* happens.
.. @+node:ekr.20140212062130.16592: *3* Headines are important
Headlines matter The unls will break if the headlines produced by *the
importer* don't match those unls. There are two cases to consider:

A. Section references. At present, Leo will abort the writing of an @auto
    tree that contains section references. Instead, Leo could write the
    expansion of the section reference. In practice, changing section
    definition nodes to ordinary nodes by hand isn't a big deal, but it
    would be nice for Leo to do that for the user.

B. Headlines for classes, methods and functions.

This is the important case. Most of my headlines look like x.y (z), where x
is some kind of indication of the class and y is the actual class, method
or function name and z is a optional comment. When converting from @file to
@auto *all* of the organizers will break unless the headline becomes just
"y".

Perhaps the best solution is to ask the importer what name it will give to
the node. Yes, this involves parsing the contents of the node. It will
likely require a new interface method of the baseScannerClass.
.. @+node:ekr.20140212062130.16593: *3* Existing organizer nodes
There are *two* kinds of organizer nodes:

- those that do *not* exist in the imported outline (these now work).
- those that *do* exist in the imported outline.

For example, I usually put the helpers of method X as children of X. There
is *no way* for the read logic to recreate such nodes at present, because
the parent/child relationships are do not exist in the @auto file. So X is
an organizer node!

Happily, it should be relatively straightforward to support **existing
organizers**:

1. The write code will represent existing organizers with
    @existing-organizer: nodes rather than @organizer: nodes. As with
    @organizer: nodes, the headline will contain the headline of the
    organizer node; the body will be a list of unls.

The write code can easily discover existing organizers: they are nodes with
children that contain something other than comments and blank lines.

2. The read code will create OrganizerData entries for @existing-organizer
   nodes just as with @organizer: nodes. A new ivar, data.existing, will
   distinguish between @organizer: and @existing-organizer nodes. These new
   entries will be members of a new global list of all organizer nodes.

The goal will be to confine tests of data.existing to the setup code. That
way, all the hard code will continue to work as is. We shall see whether
this is possible.

3. The code that munges unls will drop unls for a data object only if
   data.existing is False. This may be more tricky than it sounds. In any
   case, this is the fundamental reason why @existing-organizer: nodes
   *must* exist.
.. @+node:ekr.20140212062130.16594: *3* Fixing move_nodes_to_organizers
@language rest

After several hours staring at traces, I realized that *all* the problems
were in vc.move_nodes_to_organizers. That is, vc.global_moved_node_list,
the global move node list, was completely correct! This was not obvious,
because that trace in vc.move_nodes_to_organizers reported the *sorted*
version of the global move list. Bad idea: it was the sorting itself that
was causing all the problems!

Recall that I thought sorting the list was required to keep positions
unchanged until they are moved. But an hour or so of experimentation (at
3am) convinced me that there is *no way* to move items from sorted lists
into the correct positions.

After a few minutes of noodling, the solution finally appeared. Rather than
*moving* nodes by moving positions, the *only* way that leaves
to-be-considered positions intact is to *copy* all the nodes of a
position's tree to the correct place. Eureka! A new method,
vc.copy_tree_to_last_child_of does the actual copying. A final phase in
vc.move_nodes_to_organizers deletes all positions in reverse outline order.
So yes, sorting *is* essential, but only at the very end.

Note: these difficulties do not apply to bare organizer nodes, because each
is placed in its own holding cell. But it's not possible to create holding
cells for non-bare organizers.

.. @+node:ekr.20140212062130.16595: *3* Supporting @existing-organizers
Recall that *existing* organizer nodes are organizer nodes that the
importer will have created. Last night, after everything worked, I
reconsidered the design of existing organizer nodes in the light of the new
code. I wondered whether the existing code would correctly move such nodes
into their correct final positions.

The short answer is yes, because the importer will *not* have created any
children for existing organizer nodes. That being so, everything is
*exactly* as it is for organizer nodes, except that demote_helper and its
helpers never need to create the organizer. Some complications may arise,
but I expect them all to be minor.
.. @+node:ekr.20140212062130.16596: *3* Supporting custom headlines (@headlines)
In a previous post I wrote the new @auto write code could just warn if a
headline has changed since the @auto file was read. Wrong! It would be
*unbearable* to have to lose custom headlines. The new code must save and
restore headlines that don't match the **standard headlines**, the
headlines that the importer will give the node the *next* time the importer
reads the @auto file.

A new @headlines node (a child of the @auto-view node for the @auto file)
will contain the required data. It will contain pairs of lines, much like
@clones::

    unl: <a unl>
    head: <the custom headline>

The unls in the @headlines node must use standard headlines! The "links"
created by @headlines node will break if the body text of a node changes so
as to change its standard headline. That is, @headlines links will break
when class, method or function names change.

To combat such breakage, whenever the body text of a node changes the code
that writes the @headlines node should *recompute* the unl using a
to-be-written convenience method in leoImport.py. The convenience method
will return the new standard headline.
.. @+node:ekr.20140212062130.16597: *3* Automatic conversion of @file to @auto
When converting an @file node to @auto *every* body text must be considered
changed. All unls in the @headlines node must be set using the headline
that the importer will create for the corresponding node.
.. @+node:ekr.20140212062130.16598: *3* Why the new code is solid
​1. The hard part of the code involves moving nodes.

vc.global_moved_node_list is the backbone of the entire algorithm.
vc.demote_helper and its helpers add items to the list. vc.move_nodes and
its helpers remove items from the list. Very few significant "if"
statements exist:

Both vc.demote_helper and vc.move_nodes_to_organizers (the hard part of
vc.move_nodes) are straightforward. Very few if statements exist:

- The "main switch" in demote_helper is likely already correct and will
  have only localized consequences

- The single "if" statement in vc.move_nodes_to_organizers (the hard part
  of vc.move_nodes) reflects the fundamental distinction: nodes that must
  be copied vs. nodes that can be moved immediately.

2. Newly-installed traces make it clear what is happening.

This is surprisingly important. If bugs exist, it will be easy to recreate
them using unit tests that show, in compact, easy-to-understand dumps,
exactly what is happening.

3. Everything is easy after nodes have been moved.

Just for example, remembering nodes initial (standard) headlines is easy:
just create a dict whose keys are *vnodes* and whose values are the
standard headlines. A node's vnode does not change when the node moves, so
complications in the node-moving algorithm have *no* effect.

In short, only the node-moving algorithm (on both "sides" of the global
move list) has any potential for nasty bugs. The vast majority of those
bugs are gone, and will be easily fixed if any remain. Everything else is
completely routine bookkeeping.

4. Minimizing "if" statements.

I've worked hard to make all code as simple as possible.
.. @+node:ekr.20140212062130.16599: *3* docstring for vc.demote (not necessarily correct)
@language rest

'''
The main line of the @auto-view algorithm. Traverse root's entire tree,
placing items on the global work list.

About the algorithm:

Moving *any* kind of node to an *ordinary* (non-existing) organizer is
easy: each node is moved to the last child of the organizer.

Moving nodes to *existing* organizers requires exact housekeeping. This
code must know at what child index to insert a node.

Terminology:
- p is the to-be-moved node.
- a(p) is p's **anchor**, an existing node.  a(p) == p.parent(). 
- o(p) be the *existing* organizer to which p will be moved as a child.  
- d is the global **offset dict**, vc.anchor_offset_d.

There are two cases to consider when moving a node p to an existing node:

Existing organizer case 1: p is *any kind* of existing node (organizer or not).

We insert p as the n'th child of o, where:

    n = p.childIndex() + d.get(p.parent(),0)

Existing organizer case 2: p is an non-existing node.

p must be an organizer node (because it doesn't exist) and it must be a
*bare* organizer node because o(p) is an existing organizer.

Let p2 be the (existing) node that causes p to be inserted.

We insert p as the n'th child of o(p), where:

    n = p2.childIndex() + d.get(p2.parent(),0)

The only remaining part of the puzzle is calculating the offsets, that is,
the entries in d. The simplifying insights:

Insight 1: We only calculate offsets for *existing* nodes.

Insight 2: Because the organizer exists in this case,
           the anchor is the existing organizer: a(p) == o(p)

Insight 3. Only inserting or deleting nodes from existing node can change offsets.

With these insights firmly in mind we can consider the following offset
cases:

Offset case 1: visiting existing children of existing organizers.

By definition, the importer will create children of existing organizers.
These nodes must *not* be moved: they are already in their correct spots!

Offset case 2: adding a non-existing organizer node p to any existing (organizer) node o:

This case adds one to d.get(o)

Offset case 3: moving an existing node p to *any* organizer node, existing or not.

This case subtracts one from d.get(p.parent())
'''

# Note: o may be:
# - a bare (ordinary) organizer node,
# - an ordinary organizer node,
# - a bare existing organizer node
# - an existing organizer node that is a child of another organizer node.
.. @+node:ekr.20140914042331.19494: ** @@data OLD qt-gui-plugin-style-sheet
/* Documentation of Qt stylesheets at http://qt-project.org/doc/qt-4.8/stylesheet.html */

/* 
   Buttons may be styled by name:
      QPushButton#<button text>-button { <style> }
   or by kind:
      QPushButton[button_kind="<button kind>"] { <style> }
   Button kinds are:
   'run-script' (the singleton run-script button),
   'debug-script',
   'script-button-button' (the singleton script-button button), 
   'script-button' (buttons created by the script-button button),
   'generic-button' (default), 
   'quick-move' from the quickMove plugin,
   'interact' from the interact plugin,
   'at-button' (created from @button nodes)
   Search 'button_kind' below for button styling examples.
   
*/

/* Valid color names: http://www.w3.org/TR/SVG/types.html#ColorKeywords */

/*
    Important: this stylesheets is responsible for most, but *not* all, of Leos appearance.
    See also settings in "Colorizer and colors" 
*/

QScrollArea {
    background-color: white;
}

/* Components of the Find Tab */

QWidget#findTab {
    background-color: white;
}

QLabel#findHeading {
    font-family: @font-family;
    font-size: 10pt;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
}

QLabel#findLabel {
    font-family: @font-family;
    font-size: 10pt;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
}

QLabel#changeLabel {
    font-family: @font-family;
    font-size: 10pt;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
}

QLabel#findHelp {
    font-family: @font-family;
    font-size: 10pt;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
}

QLineEdit#findPattern {
    font-family: DejaVu Sans Mono;
    font-size: 10pt;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
}

QLineEdit#findChange {
    font-family: DejaVu Sans Mono;
    font-size: 10pt;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
}

/* A QWidget: supports only background attributes.*/

QSplitter::handle {
    background-color: #CAE1FF; /* lightSteelBlue1 */
}

QStackedWidget {
    /* background-color:lightpink; */
    border-color: red;
    padding: 0px;
    /* border-width: 0px; */
    /* background-color: yellow; */
}

QSplitter {
    border-color: white;
    background-color: white;
    border-style: solid;
}

QTreeWidget {
    /* These apply to the selected item, but not to editing items.*/
    color: @text-foreground-tree;
    background-color: #ffffec; /* Leo's traditional tree color */
    selection-color: black; /* was white */
    selection-background-color: lightgrey;
    /* font-family: SansSerif; */
    font-family: @font-family;
    font-size: @font-size-tree;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal, italic,oblique */
    show-decoration-selected: 1 /* 1: select entire row */
 }

/* Headline edit widgets */
QTreeWidget QLineEdit {
    background-color: cornsilk;
    selection-color: white;
    selection-background-color: blue;
    font-family: @font-family;
    font-size: @font-size-tree;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal, italic,oblique */
}

/* The log panes */
QTextEdit {
    background-color: white; /* #f2fdff; */
    color: @text-foreground-log;
    selection-color: white;
    selection-background-color: blue;
    /* font-family: Courier New; */
    font-family: @font-family;
    font-size: @font-size-log;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal, italic,oblique */
}

/* The body pane */
QTextEdit#richTextEdit {
    background-color: white; /* #fdf5f5; A kind of pink. */
    color: @text-foreground-body;
    selection-color: white;
    selection-background-color: lightgrey;
    font-family: @font-family;
    /* font-family: Courier New; */
    font-size: @font-size-body;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
}

/* Editor labels */
QLineEdit#editorLabel {
    background-color: #ffffec;
    font-family: @font-family;
    font-size: 10pt;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
    border: 2px;
    margin: 2px;
}

/* The text "Minibuffer" in the minibuffer area.

Do not overide QLabel directly.  It is used for dialog text.
*/

QLabel#minibufferLabel {
    font-family: @font-family;
    font-size: 10pt;
    font-weight: normal;
    font-style: normal;
}

/* 
QLabel {
    font-family: @font-family;
    font-size: 10pt;
    font-weight: normal;
    font-style: normal;
    border: 2px;
    margin: 2px;
}
*/


/* The mini-buffer

**Important**: Because Leo changes the color of the minibuffer dynamically,
stylesheets can not be used. Instead, set the desired colors using one of the
following settings, with defaults as shown::

    @color minibuffer-background-color = lightblue
    @color minibuffer-error-color = red
    @color minibuffer-foreground-color = black
    @color minibuffer-warning-color = lightgrey
*/

QLineEdit#lineEdit {
    color: @minibuffer_foreground_color;
    background-color: @minibuffer_background_color;
}

QLineEdit#lineEdit[style_class ~= 'minibuffer_warning'] {
    background-color: @minibuffer_warning_color;
}

QLineEdit#lineEdit[style_class ~= 'minibuffer_error'] {
    color: @minibuffer_error_color;
    background-color: @minibuffer_warning_color;
}


QLineEdit#lineEdit {
    selection-color: white;
    selection-background-color: lightgrey;
    font-family: @font-family;
    font-size: 10pt;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
}

QLineEdit#status1 {
    background-color: lightgrey;
    border-width: 1px;
    border-style: solid;
    border-color: darkgrey;
    font-size: 10pt;
}

QLineEdit#status2 {
    background-color: lightgrey;
    border-width: 1px;
    border-style: solid;
    border-color: darkgrey;
    font-size: 10pt;
}

/* button_kind based button coloring */
QPushButton[button_kind="run-script"] { 
    background-color: @run-script-btn-bg; }
QPushButton[button_kind="debug-script"] { 
    background-color: @debug-script-btn-bg; }
QPushButton[button_kind="generic-button"] { 
    background-color: @generic-button-btn-bg; }
QPushButton[button_kind="quick-move"] { 
    background-color: @quick-move-btn-bg; }
QPushButton[button_kind="interact"] { 
    background-color: @interact-btn-bg; }
QPushButton[button_kind="at-button"] { 
    background-color: @at-button-btn-bg; }
QPushButton[button_kind="script-button"] { 
    background-color: @script-button-btn-bg; }
/* example of name based button coloring.  Coincidentally, the
   name and button_kind of this button are the same */
QPushButton#script-button-button { 
    background-color: @script-button-button-btn-bg; }

QPlainTextEdit#screencastcaption {
    background-color: yellow;
    font-family: @font-family; /* Times New Roman; */
    font-size: 18pt;
    font-weight: normal; /* normal,bold,100,..,900 */
    font-style: normal; /* normal,italic,oblique */
}

/* focused pane border highlight */
QTextEdit#log-widget, LeoQTreeWidget#treeWidget, QTextEdit#richTextEdit { 
  border-style: @focused-border-style;
  border-width: @focused-border-width; 
  border-color: @focused-border-unfocus-color; 
}
QTextEdit:focus#log-widget, LeoQTreeWidget:focus#treeWidget, QTextEdit:focus#richTextEdit { 
  border-style: @focused-border-style;
  border-width: @focused-border-width; 
  border-color: @focused-border-focus-color; 
}

/* bookmarks plugin styling */
#show_bookmarks QPushButton { 
    margin: 0; padding: 1; border: none;
    font-size: @bookmarks_base_size;
    color: @bookmarks_base_color;
    font-weight: @bookmarks_base_weight;
    text-decoration: @bookmarks_base_decoration;
}
#show_bookmarks QPushButton[style_class~='bookmark_children'] {
    font-size: @bookmarks_children_size;
    color: @bookmarks_children_color;
    font-weight: @bookmarks_children_weight;
    text-decoration: @bookmarks_children_decoration;
}
#show_bookmarks QPushButton[style_class~='bookmark_expanded'] {
    font-size: @bookmarks_expanded_size;
    color: @bookmarks_expanded_color;
    font-weight: @bookmarks_expanded_weight;
    text-decoration: @bookmarks_expanded_decoration;
}
#show_bookmarks QPushButton[style_class~='bookmark_current'] {
    font-size: @bookmarks_current_size;
    color: @bookmarks_current_color;
    font-weight: @bookmarks_current_weight;
    text-decoration: @bookmarks_current_decoration;
}

/* Borders for vim mode. */

QTextEdit#richTextEdit[vim_state~="vim_normal"] {
  border: 3px solid #FA8072; /* Salmon */
}
QTextEdit#richTextEdit[vim_state~="vim_insert"] {
  border: 3px solid blue;
}
QTextEdit#richTextEdit[vim_state~="vim_visual"] {
  border: 3px solid gray;
}

.. @+node:ekr.20031218072017.434: ** Unused code
@ignore
@language python
@color
.. @+node:ekr.20140918124632.19462: *3* Keep
.. @+node:ekr.20101031172539.5880: *4* Existing autocompleter: do not delete
.. @+node:ekr.20061031131434.43: *5* 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: *5* 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: *6* 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: *6* 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: *6* 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: *6* 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: *6* 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: *5* 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: *6* 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: *6* 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: *6* 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: *6* 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: *7* endsDoc
def endsDoc (self,s):

    return s.startswith('@c')
.. @+node:ekr.20061031131434.72: *7* 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: *7* 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: *5* Proxy classes and objects
.. @+node:ekr.20061031131434.58: *6* 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: *6* 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: *5* 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.20131230090121.16504: *4* from leoViews.py
@first # -*- coding: utf-8 -*-
'''Support for @views trees and related operations.'''
# Started 2013/12/31.
@language python
@tabwidth -4
from __future__ import print_function
<< imports >>
@others
.. @+node:ekr.20131230090121.16506: *5* << imports >> (leoViews.py)
import leo.core.leoGlobals as g
import copy
import time
.. @+node:ekr.20140106215321.16672: *5* class OrganizerData
class OrganizerData:
    '''A class containing all data for a particular organizer node.'''
    def __init__ (self,h,unl,unls):
        self.anchor = None # The anchor position of this od node.
        self.children = [] # The direct child od nodes of this od node.
        self.closed = False # True: this od node no longer accepts new child od nodes.
        self.drop = True # Drop the unl for this od node when associating positions with unls.
        self.descendants = None # The descendant od nodes of this od node.
        self.exists = False # True: this od was created by @existing-organizer:
        self.h = h # The headline of this od node.
        self.moved = False # True: the od node has been moved to a global move list.
        self.opened = False # True: the od node has been opened.
        self.organized_nodes = [] # The list of positions organized by this od node.
        self.parent_od = None # The parent od node of this od node. (None is valid.)
        self.p = None # The position of this od node.
        self.parent = None # The original parent position of all nodes organized by this od node.
            # If parent_od is None, this will be the parent position of the od node.
        self.source_unl = None # The unl of self.parent.
        self.unl = unl # The unl of this od node.
        self.unls = unls # The unls contained in this od node.
        self.visited = False # True: demote_helper has already handled this od node.
    def __repr__(self):
        return 'OrganizerData: %s' % (self.h or '<no headline>')
    __str__ = __repr__
.. @+node:ekr.20131230090121.16508: *5* class ViewController
class ViewController:
    << docstring >>
    @others
.. @+node:ekr.20131230090121.16507: *6*  << docstring >> (class ViewController)
'''
A class to handle @views trees and related operations.
Such trees have the following structure:

- @views
  - @auto-view <unl of @auto node>
    - @organizers
      - @organizer <headline>
    - @clones
    
The body text of @organizer and @clones consists of unl's, one per line.
'''
.. @+node:ekr.20131230090121.16509: *6*  vc.ctor & vc.init
def __init__ (self,c):
    '''Ctor for ViewController class.'''
    self.c = c
    self.headline_ivar = '_imported_headline'
    self.init()
    
def init(self):
    '''
    Init all ivars of this class.
    Unit tests may call this method to ensure that this class is re-inited properly.
    '''
    self.all_ods = []
        # List of all od nodes.
    self.anchors_d = {}
        # Keys are anchoring positions, values are sorted lists of ods.
    self.anchor_offset_d = {}
        # Keys are anchoring positions, values are ints.
    self.existing_ods = []
        # List of od instances corresponding to @existing-organizer: nodes.
    self.global_bare_organizer_node_list = []
        # List of organizers that have no parent organizer node.
        # This list excludes existing organizer nodes.
    self.headlines_dict = {}
        # Keys are vnodes; values are list of child headlines.
    self.imported_organizers_list = []
        # The list of nodes that have children on entry, such as class nodes.
    self.n_nodes_scanned = 0
        # Number of nodes scanned by demote.
    self.organizer_ods = []
        # List of od instances corresponding to @organizer: nodes.
    self.organizer_unls = []
        # The list of od.unl for all od instances in self.organizer_ods.
    self.root = None
        # The position of the @auto node.
    self.pending = []
        # The list of nodes pending to be added to an organizer.
    self.stack = []
        # The stack containing real and virtual parent nodes during the main loop.
    self.temp_node = None
        # The parent position of all holding cells.
    self.trail_write_1 = None
        # The trial write on entry.
    self.views_node = None
        # The position of the @views node.
    self.work_list = []
        # A gloal list of (parent,child) tuples for all nodes that are
        # to be moved to **non-existing** organizer nodes.
        # **Important**: Nodes are moved in the order they appear in this list:
        # the tuples contain no childIndex component!
        # This list is the "backbone" of this class:
        # - The front end (demote and its helpers) adds items to this list.
        # - The back end (move_nodes and its helpers) moves nodes using this list.
.. @+node:ekr.20131230090121.16514: *6* vc.Entry points
.. @+node:ekr.20140125071842.10474: *7* vc.convert_at_file_to_at_auto
def convert_at_file_to_at_auto(self,root):
    # Define class ConvertController.
    @others
    vc = self
    c = vc.c
    if root.isAtFileNode():
        ConvertController(c,root).run()
    else:
        g.es_print('not an @file node:',root.h)
.. @+node:ekr.20140125071842.10475: *8* class ConvertController
class ConvertController:
    def __init__ (self,c,p):
        self.c = c
        # self.ic = c.importCommands
        self.vc = c.viewController
        self.root = p.copy()
    @others
.. @+node:ekr.20140202110830.17501: *9* cc.delete_at_auto_view_nodes
def delete_at_auto_view_nodes(self,root):
    '''Delete all @auto-view nodes pertaining to root.'''
    cc = self
    vc = cc.vc
    while True:
        p = vc.has_at_auto_view_node(root)
        if not p: break
        p.doDelete()
.. @+node:ekr.20140125071842.10477: *9* cc.import_from_string
def import_from_string(self,s):
    '''Import from s into a temp outline.'''
    cc = self # (ConvertController)
    c = cc.c
    ic = c.importCommands
    root = cc.root
    language = g.scanForAtLanguage(c,root) 
    ext = '.'+g.app.language_extension_dict.get(language)
    scanner = ic.scanner_for_ext(ext)
    # g.trace(language,ext,scanner.__name__)
    p = root.insertAfter()
    ok = scanner(atAuto=True,parent=p,s=s)
    p.h = root.h.replace('@file','@auto' if ok else '@@auto')
    return ok,p
.. @+node:ekr.20140125071842.10478: *9* cc.run
def run(self):
    '''Convert an @file tree to @auto tree.'''
    trace = True and not g.unitTesting
    trace_s = False
    cc = self
    c = cc.c
    root,vc = cc.root,c.viewController
    # set the headline_ivar for all vnodes.
    t1 = time.clock()
    cc.set_expected_imported_headlines(root)
    t2 = time.clock()
    # Delete all previous @auto-view nodes for this tree.
    cc.delete_at_auto_view_nodes(root)
    t3 = time.clock()
    # Ensure that all nodes of the tree are regularized.
    ok = vc.prepass(root)
    t4 = time.clock()
    if not ok:
        g.es_print('Can not convert',root.h,color='red')
        if trace: g.trace(
            '\n  set_expected_imported_headlines: %4.2f sec' % (t2-t1),
            # '\n  delete_at_auto_view_nodes:     %4.2f sec' % (t3-t2),
            '\n  prepass:                         %4.2f sec' % (t4-t3),
            '\n  total:                           %4.2f sec' % (t4-t1))
        return
    # Create the appropriate @auto-view node.
    at_auto_view = vc.update_before_write_at_auto_file(root)
    t5 = time.clock()
    # Write the @file node as if it were an @auto node.
    s = cc.strip_sentinels()
    t6 = time.clock()
    if trace and trace_s:
        g.trace('source file...\n',s)
    # Import the @auto string.
    ok,p = cc.import_from_string(s)
    t7 = time.clock()
    if ok:
        # Change at_auto_view.b so it matches p.gnx.
        at_auto_view.b = vc.at_auto_view_body(p)
        # Recreate the organizer nodes, headlines, etc.
        ok = vc.update_after_read_at_auto_file(p)
        t8 = time.clock()
        if not ok:
            p.h = '@@' + p.h
            g.trace('restoring original @auto file')
            ok,p = cc.import_from_string(s)
            if ok:
                p.h = '@@' + p.h + ' (restored)'
                if p.next():
                    p.moveAfter(p.next())
        t9 = time.clock()
    else:
        t8 = t9 = time.clock()
    if trace: g.trace(
        '\n  set_expected_imported_headlines: %4.2f sec' % (t2-t1),
        # '\n  delete_at_auto_view_nodes:     %4.2f sec' % (t3-t2),
        '\n  prepass:                         %4.2f sec' % (t4-t3),
        '\n  update_before_write_at_auto_file:%4.2f sec' % (t5-t4),
        '\n  strip_sentinels:                 %4.2f sec' % (t6-t5),
        '\n  import_from_string:              %4.2f sec' % (t7-t6),
        '\n  update_after_read_at_auto_file   %4.2f sec' % (t8-t7),
        '\n  import_from_string (restore)     %4.2f sec' % (t9-t8),
        '\n  total:                           %4.2f sec' % (t9-t1))
    if p:
        c.selectPosition(p)
    c.redraw()
.. @+node:ekr.20140125141655.10476: *9* cc.set_expected_imported_headlines
def set_expected_imported_headlines(self,root):
    '''Set the headline_ivar for all vnodes.'''
    trace = False and not g.unitTesting
    cc = self
    c = cc.c
    ic = cc.c.importCommands
    language = g.scanForAtLanguage(c,root) 
    ext = '.'+g.app.language_extension_dict.get(language)
    aClass = ic.classDispatchDict.get(ext)
    scanner = aClass(importCommands=ic,atAuto=True)
    # Duplicate the fn logic from ic.createOutline.
    theDir = g.setDefaultDirectory(c,root,importing=True)
    fn = c.os_path_finalize_join(theDir,root.h)
    fn = root.h.replace('\\','/')
    junk,fn = g.os_path_split(fn)
    fn,junk = g.os_path_splitext(fn)
    if aClass and hasattr(scanner,'headlineForNode'):
        ivar = cc.vc.headline_ivar
        for p in root.subtree():
            if not hasattr(p.v,ivar):
                h = scanner.headlineForNode(fn,p)
                setattr(p.v,ivar,h)
                if trace and h != p.h:
                    g.trace('==>',h) # p.h,'==>',h
.. @+node:ekr.20140125071842.10479: *9* cc.strip_sentinels
def strip_sentinels(self):
    '''Write the file to a string without headlines or sentinels.'''
    trace = False and not g.unitTesting
    cc = self
    at = cc.c.atFileCommands
    # ok = at.writeOneAtAutoNode(cc.root,
        # toString=True,force=True,trialWrite=True)
    at.errors = 0
    at.write(cc.root,
        kind = '@file',
        nosentinels = True,
        perfectImportFlag = False,
        scriptWrite = False,
        thinFile = True,
        toString = True)
    ok = at.errors == 0
    s = at.stringOutput
    if trace: g.trace('ok:',ok,'s:...\n'+s)
    return s
.. @+node:ekr.20140102052259.16394: *7* vc.pack & helper
def pack(self):
    '''
    Undoably convert c.p to a packed @view node, replacing all cloned
    children of c.p by unl lines in c.p.b.
    '''
    vc = self
    c,u = vc.c,vc.c.undoer
    vc.init()
    changed = False
    root = c.p
    # Create an undo group to handle changes to root and @views nodes.
    # Important: creating the @views node does *not* invalidate any positions.'''
    u.beforeChangeGroup(root,'view-pack')
    if not vc.has_at_views_node():
        changed = True
        bunch = u.beforeInsertNode(c.rootPosition())
        views = vc.find_at_views_node()
            # Creates the @views node as the *last* top-level node
            # so that no positions become invalid as a result.
        u.afterInsertNode(views,'create-views-node',bunch)
    # Prepend @view if need.
    if not root.h.strip().startswith('@'):
        changed = True
        bunch = u.beforeChangeNodeContents(root)
        root.h = '@view ' + root.h.strip()
        u.afterChangeNodeContents(root,'view-pack-update-headline',bunch)
    # Create an @view node as a clone of the @views node.
    bunch = u.beforeInsertNode(c.rootPosition())
    new_clone = vc.create_view_node(root)
    if new_clone:
        changed = True
        u.afterInsertNode(new_clone,'create-view-node',bunch)
    # Create a list of clones that have a representative node
    # outside of the root's tree.
    reps = [vc.find_representative_node(root,p)
        for p in root.children()
            if vc.is_cloned_outside_parent_tree(p)]
    reps = [z for z in reps if z is not None]
    if reps:
        changed = True
        bunch = u.beforeChangeTree(root)
        c.setChanged(True)
        # Prepend a unl: line for each cloned child.
        unls = ['unl: %s\n' % (vc.unl(p)) for p in reps]
        root.b = ''.join(unls) + root.b
        # Delete all child clones in the reps list.
        v_reps = set([p.v for p in reps])
        while True:
            for child in root.children():
                if child.v in v_reps:
                    child.doDelete()
                    break
            else: break
        u.afterChangeTree(root,'view-pack-tree',bunch)
    if changed:
        u.afterChangeGroup(root,'view-pack')
        c.selectPosition(root)
        c.redraw()
.. @+node:ekr.20140102052259.16397: *8* vc.create_view_node
def create_view_node(self,root):
    '''
    Create a clone of root as a child of the @views node.
    Return the *newly* cloned node, or None if it already exists.
    '''
    vc = self
    c = vc.c
    # Create a cloned child of the @views node if it doesn't exist.
    views = vc.find_at_views_node()
    for p in views.children():
        if p.v == c.p.v:
            return None
    p = root.clone()
    p.moveToLastChildOf(views)
    return p
.. @+node:ekr.20140102052259.16395: *7* vc.unpack
def unpack(self):
    '''
    Undoably unpack nodes corresponding to leading unl lines in c.p to child clones.
    Return True if the outline has, in fact, been changed.
    '''
    vc = self
    c,root,u = vc.c,vc.c.p,vc.c.undoer
    vc.init()
    # Find the leading unl: lines.
    i,lines,tag = 0,g.splitLines(root.b),'unl:'
    for s in lines:
        if s.startswith(tag): i += 1
        else: break
    changed = i > 0
    if changed:
        bunch = u.beforeChangeTree(root)
        # Restore the body
        root.b = ''.join(lines[i:])
        # Create clones for each unique unl.
        unls = list(set([s[len(tag):].strip() for s in lines[:i]]))
        for unl in unls:
            p = vc.find_absolute_unl_node(unl)
            if p: p.clone().moveToLastChildOf(root)
            else: g.trace('not found: %s' % (unl))
        c.setChanged(True)
        c.undoer.afterChangeTree(root,'view-unpack',bunch)
        c.redraw()
    return changed
.. @+node:ekr.20131230090121.16511: *7* vc.update_before_write_at_auto_file
def update_before_write_at_auto_file(self,root):
    '''
    Update the @auto-view node for root, an @auto node. Create @organizer,
    @existing-organizer, @clones and @headlines nodes as needed.
    This *must not* be called for trial writes.
    '''
    trace = False and not g.unitTesting
    vc = self
    c = vc.c
    changed = False
    t1 = time.clock()
    # Create lists of cloned and organizer nodes.
    clones,existing_organizers,organizers = \
        vc.find_special_nodes(root)
    # Delete all children of the @auto-view node for this @auto node.
    at_auto_view = vc.find_at_auto_view_node(root)
    if at_auto_view.hasChildren():
        changed = True
        at_auto_view.deleteAllChildren()
    # Create the single @clones node.
    if clones:
        at_clones = vc.find_at_clones_node(root)
        at_clones.b = ''.join(
            ['gnx: %s\nunl: %s\n' % (z[0],z[1]) for z in clones])
    # Create the single @organizers node.
    if organizers or existing_organizers:
        at_organizers = vc.find_at_organizers_node(root)
    # Create one @organizers: node for each organizer node.
    for p in organizers:
        # g.trace('organizer',p.h)
        at_organizer = at_organizers.insertAsLastChild()
        at_organizer.h = '@organizer: %s' % p.h
        # The organizer node's unl is implicit in each child's unl.
        at_organizer.b = '\n'.join([
            'unl: '+vc.relative_unl(z,root) for z in p.children()])
    # Create one @existing-organizer node for each existing organizer.
    ivar = vc.headline_ivar
    for p in existing_organizers:
        at_organizer = at_organizers.insertAsLastChild()
        h = getattr(p.v,ivar,p.h)
        if trace and h != p.h: g.trace('==>',h) # p.h,'==>',h
        at_organizer.h = '@existing-organizer: %s' % h
        # The organizer node's unl is implicit in each child's unl.
        at_organizer.b = '\n'.join([
            'unl: '+vc.relative_unl(z,root) for z in p.children()])
    # Create the single @headlines node.
    vc.create_at_headlines(root)
    if changed and not g.unitTesting:
        g.es_print('updated @views node in %4.2f sec.' % (
            time.clock()-t1))
    if changed:
        c.redraw()
    return at_auto_view # For at-file-to-at-auto command.
.. @+node:ekr.20140123132424.10471: *8* vc.create_at_headlines
def create_at_headlines(self,root):
    '''Create the @headlines node for root, an @auto file.'''
    vc = self
    c = vc.c
    result = []
    ivar = vc.headline_ivar
    for p in root.subtree():
        h = getattr(p.v,ivar,None)
        if h is not None and p.h != h:
            # g.trace('custom:',p.h,'imported:',h)
            unl = vc.relative_unl(p,root)
            aList = unl.split('-->')
            aList[-1] = h
            unl = '-->'.join(aList)
            result.append('imported unl: %s\nhead: %s\n' % (
                unl,p.h))
            delattr(p.v,ivar)
    if result:
        p = vc.find_at_headlines_node(root)
        p.b = ''.join(result)
.. @+node:ekr.20140123132424.10472: *8* vc.find_special_nodes
def find_special_nodes(self,root):
    '''
    Scan root's tree, looking for organizer and cloned nodes.
    Exclude organizers on imported organizers list.
    '''
    trace = False and not g.unitTesting
    verbose = False
    vc = self
    clones,existing_organizers,organizers = [],[],[]
    if trace: g.trace('imported existing',
        [v.h for v in vc.imported_organizers_list])
    for p in root.subtree():
        if p.isCloned():
            rep = vc.find_representative_node(root,p)
            if rep:
                unl = vc.relative_unl(p,root)
                gnx = rep.v.gnx
                clones.append((gnx,unl),)
        if p.v in vc.imported_organizers_list:
            # The node had children created by the importer.
            if trace and verbose: g.trace('ignore imported existing',p.h)
        elif vc.is_organizer_node(p,root):
            # p.hasChildren and p.b is empty, except for comments.
            if trace and verbose: g.trace('organizer',p.h)
            organizers.append(p.copy())
        elif p.hasChildren():
            if trace and verbose: g.trace('existing',p.h)
            existing_organizers.append(p.copy())
    return clones,existing_organizers,organizers
.. @+node:ekr.20131230090121.16513: *7* vc.update_after_read_at_auto_file & helpers
def update_after_read_at_auto_file(self,root):
    '''
    Recreate all organizer nodes and clones for a single @auto node
    using the corresponding @organizer: and @clones nodes.
    '''
    trace = True and not g.unitTesting
    vc = self
    c = vc.c
    if not vc.is_at_auto_node(root):
        return # Not an error: it might be and @auto-rst node.
    old_changed = c.isChanged()
    try:
        vc.init()
        vc.root = root.copy()
        t1 = time.clock()
        vc.trial_write_1 = vc.trial_write(root)
        t2 = time.clock()
        at_organizers = vc.has_at_organizers_node(root)
        t3 = time.clock()
        if at_organizers:
            vc.create_organizer_nodes(at_organizers,root)
        t4 = time.clock()
        at_clones = vc.has_at_clones_node(root)
        if at_clones:
            vc.create_clone_links(at_clones,root)
        t5 = time.clock()
        n = len(vc.work_list)
        ok = vc.check(root)
        t6 = time.clock()
        if ok:
            vc.update_headlines_after_read(root)
        t7 = time.clock()
        c.setChanged(old_changed if ok else False)
            ### To do: revert if not ok.
    except Exception:
        g.es_exception()
        n = 0
        ok = False
    if trace:
        if t7-t1 > 0.5: g.trace(
            '\n  trial_write:                 %4.2f sec' % (t2-t1),
            # '\n  has_at_organizers_node:    %4.2f sec' % (t3-t2),
            '\n  create_organizer_nodes:      %4.2f sec' % (t4-t3),
            '\n  create_clone_links:          %4.2f sec' % (t5-t4),
            '\n  check:                       %4.2f sec' % (t6-t5),
            '\n  update_headlines_after_read: %4.2f sec' % (t7-t6),
            '\n  total:                       %4.2f sec' % (t7-t1))
            # '\n  file:',root.h)
        # else: g.trace('total: %4.2f sec' % (t7-t1),root.h)
    if ok and n > 0:
        g.es('rearragned: %s' % (root.h),color='blue')
        g.es('moved %s nodes in %4.2f sec.' % (n,t7-t1))
        g.trace('@auto-view moved %s nodes in %4.2f sec. for' % (
            n,t2),root.h,noname=True)
    c.selectPosition(root)
    c.redraw()
    return ok
.. @+node:ekr.20140109214515.16643: *8* vc.check
def check (self,root):
    '''
    Compare a trial write or root with the vc.trail_write_1.
    Unlike the perfect-import checks done by the importer,
    we expecct an *exact* match, regardless of language.
    '''
    trace = True # and not g.unitTesting
    vc = self
    trial1 = vc.trial_write_1
    trial2 = vc.trial_write(root)
    if trial1 != trial2:
        g.pr('') # Don't use print: it does not appear with the traces.
        g.es_print('perfect import check failed for:',color='red')
        g.es_print(root.h,color='red')
        if trace:
            vc.compare_trial_writes(trial1,trial2)
            g.pr('')
    return trial1 == trial2
.. @+node:ekr.20131230090121.16545: *8* vc.create_clone_link
def create_clone_link(self,gnx,root,unl):
    '''
    Replace the node in the @auto tree with the given unl by a
    clone of the node outside the @auto tree with the given gnx.
    '''
    trace = False and not g.unitTesting
    vc = self
    p1 = vc.find_position_for_relative_unl(root,unl)
    p2 = vc.find_gnx_node(gnx)
    if p1 and p2:
        if trace: g.trace('relink',gnx,p2.h,'->',p1.h)
        if p1.b == p2.b:
            p2._relinkAsCloneOf(p1)
            return True
        else:
            g.es('body text mismatch in relinked node',p1.h)
            return False
    else:
        if trace: g.trace('relink failed',gnx,root.h,unl)
        return False
.. @+node:ekr.20131230090121.16533: *8* vc.create_clone_links
def create_clone_links(self,at_clones,root):
    '''
    Recreate clone links from an @clones node.
    @clones nodes contain pairs of lines (gnx,unl)
    '''
    vc = self
    lines = g.splitLines(at_clones.b)
    gnxs = [s[4:].strip() for s in lines if s.startswith('gnx:')]
    unls = [s[4:].strip() for s in lines if s.startswith('unl:')]
    # g.trace('at_clones.b',at_clones.b)
    if len(gnxs) == len(unls):
        vc.headlines_dict = {} # May be out of date.
        ok = True
        for gnx,unl in zip(gnxs,unls):
            ok = ok and vc.create_clone_link(gnx,root,unl)
        return ok
    else:
        g.trace('bad @clones contents',gnxs,unls)
        return False
.. @+node:ekr.20131230090121.16532: *8* vc.create_organizer_nodes & helpers
def create_organizer_nodes(self,at_organizers,root):
    '''
    root is an @auto node. Create an organizer node in root's tree for each
    child @organizer: node of the given @organizers node.
    '''
    vc = self
    c = vc.c
    trace = False and not g.unitTesting
    t1 = time.clock()
    vc.pre_move_comments(root)
        # Merge comment nodes with the next node.
    t2 = time.clock()
    vc.precompute_all_data(at_organizers,root)
        # Init all data required for reading.
    t3 = time.clock()
    vc.demote(root)
        # Traverse root's tree, adding nodes to vc.work_list.
    t4 = time.clock()
    vc.move_nodes()
        # Move nodes on vc.work_list to their final locations.
    t5 = time.clock()
    vc.post_move_comments(root)
        # Move merged comments to parent organizer nodes.
    t6 = time.clock()
    if trace: g.trace(
        '\n  pre_move_comments:   %4.2f sec' % (t2-t1),
        '\n  precompute_all_data: %4.2f sec' % (t3-t2),
        '\n  demote:              %4.2f sec' % (t4-t3),
        '\n  move_nodes:          %4.2f sec' % (t5-t4),
        '\n  post_move_comments:  %4.2f sec' % (t6-t5))
.. @+node:ekr.20140124111748.10635: *8* vc.update_headlines_after_read
def update_headlines_after_read(self,root):
    '''Handle custom headlines for all imported nodes.'''
    trace = False and not g.unitTesting
    vc = self
    # Remember the original imported headlines.
    ivar = vc.headline_ivar
    for p in root.subtree():
        if not hasattr(p.v,ivar):
            setattr(p.v,ivar,p.h)
    # Update headlines from @headlines nodes.
    at_headlines = vc.has_at_headlines_node(root)
    tag1,tag2 = 'imported unl: ','head: '
    n1,n2 = len(tag1),len(tag2)
    if at_headlines:
        lines = g.splitLines(at_headlines.b)
        unls  = [s[n1:].strip() for s in lines if s.startswith(tag1)]
        heads = [s[n2:].strip() for s in lines if s.startswith(tag2)]
    else:
        unls,heads = [],[]
    if len(unls) == len(heads):
        vc.headlines_dict = {} # May be out of date.
        for unl,head in zip(unls,heads):
            p = vc.find_position_for_relative_unl(root,unl)
            if p:
                if trace: g.trace('unl:',unl,p.h,'==>',head)
                p.h = head
    else:
        g.trace('bad @headlines body',at_headlines.b)
.. @+node:ekr.20140120105910.10488: *6* vc.Main Lines
.. @+node:ekr.20140115180051.16709: *7* vc.precompute_all_data & helpers
def precompute_all_data(self,at_organizers,root):
    '''Precompute all data needed to reorganize nodes.'''
    trace = False and not g.unitTesting
    vc = self
    t1 = time.clock() 
    vc.find_imported_organizer_nodes(root)
        # Put all nodes with children on vc.imported_organizer_node_list
    t2 = time.clock()
    vc.create_organizer_data(at_organizers,root)
        # Create OrganizerData objects for all @organizer:
        # and @existing-organizer: nodes.
    t3 = time.clock()
    vc.create_actual_organizer_nodes()
        # Create the organizer nodes in holding cells so positions remain valid.
    t4 = time.clock()
    vc.create_tree_structure(root)
        # Set od.parent_od, od.children & od.descendants for all ods.
    t5 = time.clock()
    vc.compute_all_organized_positions(root)
        # Compute the positions organized by each organizer.
        # ** Most of the time is spent here **.
    t6 = time.clock()
    vc.create_anchors_d()
        # Create the dictionary that associates positions with ods.
    t7 = time.clock()
    if trace: g.trace(
        '\n  find_imported_organizer_nodes:   %4.2f sec' % (t2-t1),
        '\n  create_organizer_data:           %4.2f sec' % (t3-t2),
        '\n  create_actual_organizer_nodes:   %4.2f sec' % (t4-t3),
        '\n  create_tree_structure:           %4.2f sec' % (t5-t4),
        '\n  compute_all_organized_positions: %4.2f sec' % (t6-t5),
        '\n  create_anchors_d:                %4.2f sec' % (t7-t6))
.. @+node:ekr.20140113181306.16690: *8* 1: vc.find_imported_organizer_nodes
def find_imported_organizer_nodes(self,root):
    '''
    Put the VNode of all imported nodes with children on
    vc.imported_organizers_list.
    '''
    trace = False # and not g.unitTesting
    vc = self
    aList = []
    for p in root.subtree():
        if p.hasChildren():
            aList.append(p.v)
    vc.imported_organizers_list = list(set(aList))
    if trace: g.trace([z.h for z in vc.imported_organizers_list])
.. @+node:ekr.20140106215321.16674: *8* 2: vc.create_organizer_data (od.p & od.parent)
def create_organizer_data(self,at_organizers,root):
    '''
    Create OrganizerData nodes for all @organizer: and @existing-organizer:
    nodes in the given @organizers node.
    '''
    vc = self
    vc.create_ods(at_organizers)
    vc.finish_create_organizers(root)
    vc.finish_create_existing_organizers(root)
    for od in vc.all_ods:
        assert od.parent,(od.exists,od.h)
.. @+node:ekr.20140126044100.15449: *9* vc.create_ods
def create_ods(self,at_organizers):
    '''Create all organizer nodes and the associated lists.'''
    # Important: we must completely reinit all data here.
    vc = self
    tag1 = '@organizer:'
    tag2 = '@existing-organizer:'
    vc.all_ods,vc.existing_ods,vc.organizer_ods = [],[],[]
    for at_organizer in at_organizers.children():
        h = at_organizer.h
        for tag in (tag1,tag2):
            if h.startswith(tag):
                unls = vc.get_at_organizer_unls(at_organizer)
                if unls:
                    organizer_unl = vc.drop_unl_tail(unls[0])
                    h = h[len(tag):].strip()
                    od = OrganizerData(h,organizer_unl,unls)
                    vc.all_ods.append(od)
                    if tag == tag1:
                        vc.organizer_ods.append(od)
                        vc.organizer_unls.append(organizer_unl)
                    else:
                        vc.existing_ods.append(od)
                        # Do *not* append organizer_unl to the unl list.
                else:
                    g.trace('===== no unls:',at_organizer.h)
.. @+node:ekr.20140126044100.15450: *9* vc.finish_create_organizers
def finish_create_organizers(self,root):
    '''Finish creating all organizers.'''
    trace = False # and not g.unitTesting
    vc = self
    # Careful: we may delete items from this list.
    for od in vc.organizer_ods[:]: 
        od.source_unl = vc.source_unl(vc.organizer_unls,od.unl)
        od.parent = vc.find_position_for_relative_unl(root,od.source_unl)
        if od.parent:
            od.anchor = od.parent
            if trace: g.trace(od.h,
                # '\n  exists:',od.exists,
                # '\n  unl:',od.unl,
                # '\n  source (unl):',od.source_unl or repr(''),
                # '\n  anchor (pos):',od.anchor.h,
                # '\n  parent (pos):',od.parent.h,
            )
        else:
            # This is, most likely, a true error.
            g.trace('===== removing od:',od.h)
            vc.organizer_ods.remove(od)
            vc.all_ods.remove(od)
            assert od not in vc.existing_ods
            assert od not in vc.all_ods
.. @+node:ekr.20140126044100.15451: *9* vc.finish_create_existing_organizers
def finish_create_existing_organizers(self,root):
    '''Finish creating existing organizer nodes.'''
    trace = False # and not g.unitTesting
    vc = self
    # Careful: we may delete items from this list.
    for od in vc.existing_ods[:]:
        od.exists = True
        assert od.unl not in vc.organizer_unls
        od.source_unl = vc.source_unl(vc.organizer_unls,od.unl)
        od.p = vc.find_position_for_relative_unl(root,od.source_unl)
        if od.p:
            od.anchor = od.p
            assert od.p.h == od.h,(od.p.h,od.h)  
            od.parent = od.p # Here, od.parent represents the "source" p.
            if trace: g.trace(od.h,
                # '\n  exists:',od.exists,
                # '\n  unl:',od.unl,
                # '\n  source (unl):',od.source_unl or repr(''),
                # '\n  anchor (pos):',od.anchor.h,
                # '\n  parent (pos):',od.parent.h,
            )
        else:
            # This arises when the imported node name doesn't match.
            g.trace('===== removing existing organizer:',od.h)
            vc.existing_ods.remove(od)
            vc.all_ods.remove(od)
            assert od not in vc.existing_ods
            assert od not in vc.all_ods

.. @+node:ekr.20140106215321.16675: *8* 3: vc.create_actual_organizer_nodes
def create_actual_organizer_nodes(self):
    '''
    Create all organizer nodes as children of holding cells. These holding
    cells ensure that moving an organizer node leaves all other positions
    unchanged.
    '''
    vc = self
    c = vc.c
    last = c.lastTopLevel()
    temp = vc.temp_node = last.insertAfter()
    temp.h = 'ViewController.temp_node'
    for od in vc.organizer_ods:
        holding_cell = temp.insertAsLastChild()
        holding_cell.h = 'holding cell for ' + od.h
        od.p = holding_cell.insertAsLastChild()
        od.p.h = od.h
.. @+node:ekr.20140108081031.16612: *8* 4: vc.create_tree_structure & helper
def create_tree_structure(self,root):
    '''Set od.parent_od, od.children & od.descendants for all ods.'''
    trace = False and not g.unitTesting
    vc = self
    # if trace: g.trace([z.h for z in data_list],g.callers())
    organizer_unls = [z.unl for z in vc.all_ods]
    for od in vc.all_ods:
        for unl in od.unls:
            if unl in organizer_unls:
                i = organizer_unls.index(unl)
                d2 = vc.all_ods[i]
                # if trace: g.trace('found organizer unl:',od.h,'==>',d2.h)
                od.children.append(d2)
                d2.parent_od = od
    # create_organizer_data now ensures od.parent is set.
    for od in vc.all_ods:
        assert od.parent,od.h
    # Extend the descendant lists.
    for od in vc.all_ods:
        vc.compute_descendants(od)
        assert od.descendants is not None
    if trace:
        def tail(head,unl):
            return str(unl[len(head):]) if unl.startswith(head) else str(unl)
        for od in vc.all_ods:
            g.trace(
                '\n  od:',od.h,
                '\n  unl:',od.unl,
                '\n  unls:', [tail(od.unl,z) for z in od.unls],
                '\n  source (unl):',od.source_unl or repr(''),
                '\n  parent (pos):', od.parent.h,
                '\n  children:',[z.h for z in od.children],
                '\n  descendants:',[str(z.h) for z in od.descendants])
.. @+node:ekr.20140109214515.16633: *9* vc.compute_descendants
def compute_descendants(self,od,level=0,result=None):
    '''Compute the descendant od nodes of od.'''
    trace = False # and not g.unitTesting
    vc = self
    if level == 0:
        result = []
    if od.descendants is None:
        for child in od.children:
            result.append(child)
            result.extend(vc.compute_descendants(child,level+1,result))
            result = list(set(result))
        if level == 0:
            od.descendants = result
            if trace: g.trace(od.h,[z.h for z in result])
        return result
    else:
        if trace: g.trace('cached',od.h,[z.h for z in od.descendants])
        return od.descendants
.. @+node:ekr.20140115180051.16706: *8* 5: vc.compute_all_organized_positions
def compute_all_organized_positions(self,root):
    '''Compute the list of positions organized by every od.'''
    trace = False and not g.unitTesting
    vc = self
    for od in vc.all_ods:
        if od.unls:
            # Do a full search only for the first unl.
            ### parent = vc.find_position_for_relative_unl(root,od.unls[0])
            if True: ### parent:
                for unl in od.unls:
                    p = vc.find_position_for_relative_unl(root,unl)
                    ### p = vc.find_position_for_relative_unl(parent,vc.unl_tail(unl))
                    if p:
                        od.organized_nodes.append(p.copy())
                    if trace: g.trace('exists:',od.exists,
                        'od:',od.h,'unl:',unl,
                        'p:',p and p.h or '===== None')
            else:
                g.trace('fail',od.unls[0])
.. @+node:ekr.20140117131738.16727: *8* 6: vc.create_anchors_d
def create_anchors_d (self):
    '''
    Create vc.anchors_d.
    Keys are positions, values are lists of ods having that anchor.
    '''
    trace = False # and not g.unitTesting
    vc = self
    d = {}
    if trace: g.trace('all_ods',[z.h for z in vc.all_ods])
    for od in vc.all_ods:
        # Compute the anchor if it does not yet exists.
        # Valid now that p.__hash__ exists.
        key = od.anchor
        # key = '.'.join([str(z) for z in od.anchor.sort_key(od.anchor)])
        # key = '%s (%s)' % (key,od.anchor.h)
        aList = d.get(key,[])
        # g.trace(od.h,od.anchor.h,key,aList)
        aList.append(od)
        d[key] = aList
    if trace:
        for key in sorted(d.keys()):
            g.trace('od.anchor: %s ods: [%s]' % (key.h,','.join(z.h for z in d.get(key))))
    vc.anchors_d = d
.. @+node:ekr.20140104112957.16587: *7* vc.demote & helpers
def demote(self,root):
    '''
    The main line of the @auto-view algorithm. Traverse root's entire tree,
    placing items on the global work list.
    '''
    trace = False # and not g.unitTesting
    trace_loop = True
    vc = self
    active = None # The active od.
    vc.pending = [] # Lists of pending demotions.
    d = vc.anchor_offset_d # For traces.
    for p in root.subtree():
        parent = p.parent()
        if trace and trace_loop:
            if 1:
                g.trace('-----',p.childIndex(),p.h)
            else:
                g.trace(
                    '=====\np:',p.h,
                    'childIndex',p.childIndex(),
                    '\nparent:',parent.h,
                    'parent:offset',d.get(parent,0))
        vc.n_nodes_scanned += 1
        vc.terminate_organizers(active,parent)
        found = vc.find_organizer(parent,p)
        if found:
            pass ### vc.enter_organizers(found,p)
        else:
            pass ### vc.terminate_all_open_organizers()
        if trace and trace_loop:
            g.trace(
                'active:',active and active.h or 'None',
                'found:',found and found.h or 'None')
        # The main case statement...
        if found is None and active:
            vc.add_to_pending(active,p)
        elif found is None and not active:
            # Pending nodes will *not* be organized.
            vc.clear_pending(None,p)
        elif found and found == active:
            # Pending nodes *will* be organized.
            for z in vc.pending:
                active2,child2 = z
                vc.add(active2,child2,'found==active:pending')
            vc.pending = []
            vc.add(active,p,'found==active')
        elif found and found != active:
            # Pending nodes will *not* be organized.
            vc.clear_pending(found,p)
            active = found
            vc.enter_organizers(found,p)
            vc.add(active,p,'found!=active')
        else: assert False,'can not happen'
.. @+node:ekr.20140117131738.16717: *8* vc.add
def add(self,active,p,tag):
    '''
    Add p, an existing (imported) node to the global work list.
    Subtract 1 from the vc.anchor_offset_d entry for p.parent().
    
    Exception: do *nothing* if p is a child of an existing organizer node.
    '''
    trace = False # and not g.unitTesting
    verbose = False
    vc = self
    # g.trace(active,g.callers())
    if active.p == p.parent() and active.exists:
        if trace and verbose: g.trace('===== do nothing',active.h,p.h)
    else:
        data = active.p,p.copy()
        vc.add_to_work_list(data,tag)
        vc.anchor_decr(anchor=p.parent(),p=p)
        
.. @+node:ekr.20140109214515.16646: *8* vc.add_organizer_node
def add_organizer_node (self,od,p):
    '''
    Add od to the appropriate move list.
    p is the existing node that caused od to be added.
    '''
    trace = True # and not g.unitTesting
    verbose = False
    vc = self
    # g.trace(od.h,'parent',od.parent_od and od.parent_od.h or 'None')
    if od.parent_od:
        # Not a bare organizer: a child of another organizer node.
        # If this is an existing organizer, it's *position* may have
        # been moved without active.moved being set.
        data = od.parent_od.p,od.p
        if data in vc.work_list:
            if trace and verbose: g.trace(
                '**** duplicate 1: setting moved bit.',od.h)
            od.moved = True
        elif od.parent_od.exists:    
            anchor = od.parent_od.p
            n = vc.anchor_incr(anchor,p) + p.childIndex()
            data = anchor,od.p,n
            # g.trace('anchor:',anchor.h,'p:',p.h,'childIndex',p.childIndex())
            vc.add_to_bare_list(data,'non-bare existing')
        else:
            vc.add_to_work_list(data,'non-bare')
    elif od.p == od.anchor:
        if trace and verbose: g.trace(
            '***** existing organizer: do not move:',od.h)
    else:
        ### This can be pre-computed?
        bare_list = [p for parent,p,n in vc.global_bare_organizer_node_list]
        if od.p in bare_list:
            if trace and verbose: g.trace(
                '**** duplicate 2: setting moved bit.',od.h)
            od.moved = True
        else:
            # A bare organizer node: a child of an *ordinary* node.
            anchor = p.parent()
            n = vc.anchor_incr(anchor,p) + p.childIndex()
            data = anchor,od.p,n
            vc.add_to_bare_list(data,'bare')
.. @+node:ekr.20140127143108.15463: *8* vc.add_to_bare_list
def add_to_bare_list(self,data,tag):
    '''Add data to the bare organizer list, with tracing.'''
    trace = False # and not g.unitTesting
    vc = self
    # Prevent duplicagtes.
    anchor,p,n = data
    for data2 in vc.global_bare_organizer_node_list:
        a2,p2,n2 = data2
        if p == p2:
            if trace: g.trace('ignore duplicate',
                'n:',n,anchor.h,'==>',p.h)
            return
    vc.global_bare_organizer_node_list.append(data)
    if trace:
        anchor,p,n = data
        g.trace('=====',tag,'n:',n,anchor.h,'==>',p.h)
            # '\n  anchor:',anchor.h,
            # '\n  p:',p.h)
.. @+node:ekr.20140117131738.16719: *8* vc.add_to_pending
def add_to_pending(self,active,p):
    trace = False # and not g.unitTesting
    vc = self
    if trace: g.trace(active.p.h,'==>',p.h)
    vc.pending.append((active,p.copy()),)
.. @+node:ekr.20140127143108.15462: *8* vc.add_to_work_list
def add_to_work_list(self,data,tag):
    '''Append the data to the work list, with tracing.'''
    trace = False # and not g.unitTesting
    vc = self
    vc.work_list.append(data)
    if trace:
        active,p = data
        g.trace('=====',tag,active.h,'==>',p.h)
.. @+node:ekr.20140127143108.15460: *8* vc.anchor_decr
def anchor_decr(self,anchor,p): # p is only for traces.
    '''
    Decrement the anchor dict for the given anchor node.
    Return the *previous* value.
    '''
    trace = False # and not g.unitTesting
    vc = self
    d = vc.anchor_offset_d
    n = d.get(anchor,0)
    d[anchor] = n - 1
    if trace: g.trace(n-1,anchor.h,'==>',p.h)
    return n
.. @+node:ekr.20140127143108.15461: *8* vc.anchor_incr
def anchor_incr(self,anchor,p): # p is only for traces.
    '''
    Increment the anchor dict for the given anchor node.
    Return the *previous* value.
    '''
    trace = False # and not g.unitTesting
    vc = self
    d = vc.anchor_offset_d
    n = d.get(anchor,0)
    d[anchor] = n + 1
    if trace: g.trace(n+1,anchor.h,'==>',p.h)
    return n
.. @+node:ekr.20140129164001.16251: *8* vc.clear_pending
def clear_pending(self,active,p):
    '''Clear the appropriate entries from the pending list.'''
    trace = False # and not g.unitTesting
    vc = self
    if trace: g.trace('===== clear pending',len(vc.pending))
    if False: # active and active.parent_od:
        for data in vc.pending:
            data = active.parent_od.p,data[1]
            vc.add_to_work_list(data,'clear-pending-to-active')
    vc.pending = []
.. @+node:ekr.20140117131738.16723: *8* vc.enter_organizers
def enter_organizers(self,od,p):
    '''Enter all organizers whose anchors are p.'''
    vc = self
    ods = []
    while od:
        ods.append(od)
        od = od.parent_od
    if ods:
        for od in reversed(ods):
            vc.add_organizer_node(od,p)
.. @+node:ekr.20140120105910.10490: *8* vc.find_organizer
def find_organizer(self,parent,p):
    '''Return the organizer that organizers p, if any.'''
    trace = False # and not g.unitTesting
    vc = self
    anchor = parent
    ods = vc.anchors_d.get(anchor,[])
    for od in ods:
        if p in od.organized_nodes:
            if trace: g.trace('found:',od.h,'for',p.h)
            return od
    return None
.. @+node:ekr.20140117131738.16724: *8* vc.terminate_organizers
def terminate_organizers(self,active,p):
    '''Terminate all organizers whose anchors are not ancestors of p.'''
    trace = False # and not g.unitTesting
    od = active
    while od and od.anchor != p and od.anchor.isAncestorOf(p):
        if not od.closed:
            if trace: g.trace('===== closing',od.h)
            od.closed = True
        od = od.parent_od
.. @+node:ekr.20140129164001.16252: *8* vc.terminate_all_open_organizers
def terminate_all_open_organizers(self):
    '''Terminate all open organizers.'''
    trace = True # and not g.unitTesting
    if 0: ###
        g.trace()
        for od in self.all_ods:
            if od.opened and not od.closed:
                if trace: g.trace('===== closing',od.h)
                od.closed = True
.. @+node:ekr.20140106215321.16678: *7* vc.move_nodes & helpers
def move_nodes(self):
    '''Move nodes to their final location and delete the temp node.'''
    trace = False # and not g.unitTesting
    vc = self
    vc.move_nodes_to_organizers(trace)
    vc.move_bare_organizers(trace)
    vc.temp_node.doDelete()
.. @+node:ekr.20140109214515.16636: *8* vc.move_nodes_to_organizers
def move_nodes_to_organizers(self,trace):
    '''Move all nodes in the work_list.'''
    trace = False # and not g.unitTesting
    trace_dict = False
    trace_moves = False
    trace_deletes = False
    vc = self
    if trace: # A highly useful trace!
        g.trace('\n\nunsorted_list...\n%s' % (
            '\n'.join(['%40s ==> %s' % (parent.h,p.h)
                for parent,p in vc.work_list])))
    # Create a dictionary of each organizers children.
    d = {}
    for parent,p in vc.work_list:
        # This key must remain stable if parent moves.
        key = parent
        aList = d.get(key,[])
        aList.append(p)
        # g.trace(key,[z.h for z in aList])
        d[key] = aList
    if trace and trace_dict:
        # g.trace('d...',sorted([z.h for z in d.keys()]))
        g.trace('d{}...')
        for key in sorted(d.keys()):
            aList = [z.h for z in d.get(key)]
            g.trace('%s %-20s %s' % (id(key),key.h,vc.dump_list(aList,indent=29)))
    # Move *copies* of non-organizer nodes to each organizer.
    organizers = list(d.keys())
    existing_organizers = [z.p.copy() for z in vc.existing_ods]
    moved_existing_organizers = {} # Keys are vnodes, values are positions.
    for parent in organizers:
        aList = d.get(parent,[])
        if trace and trace_moves:
            g.trace('===== moving/copying:',parent.h,
                'with %s children:' % (len(aList)),
                '\n  '+'\n  '.join([z.h for z in aList]))
        for p in aList:
            if p in existing_organizers:
                if trace and trace_moves:
                    g.trace('copying existing organizer:',p.h)
                    g.trace('children:',
                    '\n  '+'\n  '.join([z.h for z in p.children()]))
                copy = vc.copy_tree_to_last_child_of(p,parent)
                old = moved_existing_organizers.get(p.v)
                if old and trace_moves:
                    g.trace('*********** overwrite',p.h)
                moved_existing_organizers[p.v] = copy
            elif p in organizers:
                if trace and trace_moves:
                    g.trace('moving organizer:',p.h)
                aList = d.get(p)
                if aList:
                    if trace and trace_moves: g.trace('**** relocating',
                        p.h,'children:',
                        '\n  '+'\n  '.join([z.h for z in p.children()]))
                    del d[p]
                p.moveToLastChildOf(parent)
                if aList:
                    d[p] = aList
            else:
                parent2 = moved_existing_organizers.get(parent.v)
                if parent2:
                    if trace and trace_moves:
                        g.trace('***** copying to relocated parent:',p.h)
                    vc.copy_tree_to_last_child_of(p,parent2)
                else:
                    if trace and trace_moves: g.trace('copying:',p.h)
                    vc.copy_tree_to_last_child_of(p,parent)
    # Finally, delete all the non-organizer nodes, in reverse outline order.
    def sort_key(od):
        parent,p = od
        return p.sort_key(p)
    sorted_list = sorted(vc.work_list,key=sort_key)
    if trace and trace_deletes:
        g.trace('===== deleting nodes in reverse outline order...')
    for parent,p in reversed(sorted_list):
        if p.v in moved_existing_organizers:
            if trace and trace_deletes:
                g.trace('deleting moved existing organizer:',p.h)
            p.doDelete()
        elif p not in organizers:
            if trace and trace_deletes:
                g.trace('deleting non-organizer:',p.h)
            p.doDelete()
.. @+node:ekr.20140109214515.16637: *8* vc.move_bare_organizers
def move_bare_organizers(self,trace):
    '''Move all nodes in global_bare_organizer_node_list.'''
    trace = False # and not g.unitTesting
    trace_data = True
    trace_move = True
    vc = self
    # For each parent, sort nodes on n.
    d = {} # Keys are vnodes, values are lists of tuples (n,parent,p)
    existing_organizers = [od.p for od in vc.existing_ods]
    if trace: g.trace('ignoring existing organizers:',
        [p.h for p in existing_organizers])
    for parent,p,n in vc.global_bare_organizer_node_list:
        if p not in existing_organizers:
            key = parent.v
            aList = d.get(key,[])
            if (parent,p,n) not in aList:
                aList.append((parent,p,n),)
                d[key] = aList
    # For each parent, add nodes in childIndex order.
    def key_func(obj):
        return obj[0]
    for key in d.keys():
        aList = d.get(key)
        for data in sorted(aList,key=key_func):
            parent,p,n = data
            n2 = parent.numberOfChildren()
            if trace and trace_data:
                g.trace(n,parent.h,'==>',p.h)
            if trace and trace_move: g.trace(
                'move: %-20s:' % (p.h),
                'to child: %2s' % (n),
                'of: %-20s' % (parent.h),
                'with:',n2,'children')
            p.moveToNthChildOf(parent,n)
.. @+node:ekr.20140112112622.16663: *8* vc.copy_tree_to_last_child_of
def copy_tree_to_last_child_of(self,p,parent):
    '''Copy p's tree to the last child of parent.'''
    vc = self
    assert p != parent,p
        # A failed assert leads to unbounded recursion.
    # print('copy_tree_to_last_child_of',p.h,parent.h)
    root = parent.insertAsLastChild()
    root.b,root.h = p.b,p.h
    root.v.u = copy.deepcopy(p.v.u)
    for child in p.children():
        vc.copy_tree_to_last_child_of(child,root)
    return root
.. @+node:ekr.20131230090121.16515: *6* vc.Helpers
.. @+node:ekr.20140103105930.16448: *7* vc.at_auto_view_body and match_at_auto_body
def at_auto_view_body(self,p):
    '''Return the body text for the @auto-view node for p.'''
    # Note: the unl of p relative to p is simply p.h,
    # so it is pointless to add that to the @auto-view node.
    return 'gnx: %s\n' % p.v.gnx

def match_at_auto_body(self,p,auto_view):
    '''Return True if any line of auto_view.b matches the expected gnx line.'''
    if 0: g.trace(p.b == 'gnx: %s\n' % auto_view.v.gnx,
        g.shortFileName(p.h),auto_view.v.gnx,p.b.strip())
    return p.b == 'gnx: %s\n' % auto_view.v.gnx
.. @+node:ekr.20131230090121.16522: *7* vc.clean_nodes (not used)
def clean_nodes(self):
    '''Delete @auto-view nodes with no corresponding @auto nodes.'''
    vc = self
    c = vc.c
    views = vc.has_at_views_node()
    if not views:
        return
    # Remember the gnx of all @auto nodes.
    d = {}
    for p in c.all_unique_positions():
        if vc.is_at_auto_node(p):
            d[p.v.gnx] = True
    # Remember all unused @auto-view nodes.
    delete = []
    for child in views.children():
        s = child.b and g.splitlines(child.b)
        gnx = s[len('gnx'):].strip()
        if gnx not in d:
            g.trace(child.h,gnx)
            delete.append(child.copy())
    for p in reversed(delete):
        p.doDelete()
    c.selectPosition(views)
.. @+node:ekr.20140109214515.16640: *7* vc.comments...
.. @+node:ekr.20131230090121.16526: *8* vc.comment_delims
def comment_delims(self,p):
    '''Return the comment delimiter in effect at p, an @auto node.'''
    vc = self
    c = vc.c
    d = g.get_directives_dict(p)
    s = d.get('language') or c.target_language
    language,single,start,end = g.set_language(s,0)
    return single,start,end
.. @+node:ekr.20140109214515.16641: *8* vc.delete_leading_comments
def delete_leading_comments(self,delims,p):
    '''
    Scan for leading comments from p and return them.
    At present, this only works for single-line comments.
    '''
    single,start,end = delims
    if single:
        lines = g.splitLines(p.b)
        result = []
        for s in lines:
            if s.strip().startswith(single):
                result.append(s)
            else: break
        if result:
            p.b = ''.join(lines[len(result):])
            # g.trace('len(result)',len(result),p.h)
            return ''.join(result)
    return None
.. @+node:ekr.20140105055318.16754: *8* vc.is_comment_node
def is_comment_node(self,p,root,delims=None):
    '''Return True if p.b contains nothing but comments or blank lines.'''
    vc = self
    if not delims:
        delims = vc.comment_delims(root)
    # pylint: disable=unpacking-non-sequence
    single,start,end = delims
    assert single or start and end,'bad delims: %r %r %r' % (single,start,end)
    if single:
        for s in g.splitLines(p.b):
            s = s.strip()
            if s and not s.startswith(single) and not g.isDirective(s):
                return False
        return True
    else:
        def check_comment(s):
            done,in_comment = False,True
            i = s.find(end)
            if i > -1:
                tail = s[i+len(end):].strip()
                if tail: done = True
                else: in_comment = False
            return done,in_comment
        
        done,in_comment = False,False
        for s in g.splitLines(p.b):
            s = s.strip()
            if not s:
                pass
            elif in_comment:
                done,in_comment = check_comment(s)
            elif g.isDirective(s):
                pass
            elif s.startswith(start):
                done,in_comment = check_comment(s[len(start):])
            else:
                # g.trace('fail 1: %r %r %r...\n%s' % (single,start,end,s)
                return False
            if done:
                return False
        # All lines pass.
        return True
.. @+node:ekr.20140109214515.16642: *8* vc.is_comment_organizer_node
# def is_comment_organizer_node(self,p,root):
    # '''
    # Return True if p is an organizer node in the given @auto tree.
    # '''
    # return p.hasChildren() and vc.is_comment_node(p,root)
.. @+node:ekr.20140109214515.16639: *8* vc.post_move_comments
def post_move_comments(self,root):
    '''Move comments from the start of nodes to their parent organizer node.'''
    vc = self
    c = vc.c
    delims = vc.comment_delims(root)
    for p in root.subtree():
        if p.hasChildren() and not p.b:
            s = vc.delete_leading_comments(delims,p.firstChild())
            if s:
                p.b = s
                # g.trace(p.h)
.. @+node:ekr.20140106215321.16679: *8* vc.pre_move_comments
def pre_move_comments(self,root):
    '''
    Move comments from comment nodes to the next node.
    This must be done before any other processing.
    '''
    vc = self
    c = vc.c
    delims = vc.comment_delims(root)
    aList = []
    for p in root.subtree():
        if p.hasNext() and vc.is_comment_node(p,root,delims=delims):
            aList.append(p.copy())
            next = p.next()
            if p.b: next.b = p.b + next.b
    # g.trace([z.h for z in aList])
    c.deletePositionsInList(aList)
        # This sets c.changed.
.. @+node:ekr.20140103062103.16442: *7* vc.find...
# The find commands create the node if not found.
.. @+node:ekr.20140102052259.16402: *8* vc.find_absolute_unl_node
def find_absolute_unl_node(self,unl,priority_header=False):
    '''Return a node matching the given absolute unl.
    If priority_header == True and the node is not found, it will return the longest matching UNL starting from the tail
    '''
    import re
    pos_pattern = re.compile(r':(\d+),?(\d+)?$')
    vc = self
    aList = unl.split('-->')
    if aList:
        first,rest = aList[0],'-->'.join(aList[1:])
        count = 0
        pos = re.findall(pos_pattern,first)
        nth_sib,pos = pos[0] if pos else (0,0)
        pos = int(pos) if pos else 0
        nth_sib = int(nth_sib)
        first = re.sub(pos_pattern,"",first).replace('--%3E','-->')
        for parent in vc.c.rootPosition().self_and_siblings():
            if parent.h.strip() == first.strip():
                if pos == count:
                    if rest:
                        return vc.find_position_for_relative_unl(parent,rest,priority_header=priority_header)
                    else:
                        return parent
                count = count+1
        #Here we could find and return the nth_sib if an exact header match was not found
    return None
.. @+node:ekr.20131230090121.16520: *8* vc.find_at_auto_view_node & helper
def find_at_auto_view_node (self,root):
    '''
    Return the @auto-view node for root, an @auto node.
    Create the node if it does not exist.
    '''
    vc = self
    views = vc.find_at_views_node()
    p = vc.has_at_auto_view_node(root)
    if not p:
        p = views.insertAsLastChild()
        p.h = '@auto-view:' + root.h[len('@auto'):].strip()
        p.b = vc.at_auto_view_body(root)
    return p
.. @+node:ekr.20131230090121.16516: *8* vc.find_clones_node
def find_at_clones_node(self,root):
    '''
    Find the @clones node for root, an @auto node.
    Create the @clones node if it does not exist.
    '''
    vc = self
    c = vc.c
    h = '@clones'
    auto_view = vc.find_at_auto_view_node(root)
    p = g.findNodeInTree(c,auto_view,h)
    if not p:
        p = auto_view.insertAsLastChild()
        p.h = h
    return p
.. @+node:ekr.20140123132424.10474: *8* vc.find_at_headlines_node
def find_at_headlines_node(self,root):
    '''
    Find the @headlines node for root, an @auto node.
    Create the @headlines node if it does not exist.
    '''
    vc = self
    c = vc.c
    h = '@headlines'
    auto_view = vc.find_at_auto_view_node(root)
    p = g.findNodeInTree(c,auto_view,h)
    if not p:
        p = auto_view.insertAsLastChild()
        p.h = h
    return p
.. @+node:ekr.20131230090121.16547: *8* vc.find_gnx_node
def find_gnx_node(self,gnx):
    '''Return the first position having the given gnx.'''
    # This is part of the read logic, so newly-imported
    # nodes will never have the given gnx.
    vc = self
    for p in vc.c.all_unique_positions():
        if p.v.gnx == gnx:
            return p
    return None
.. @+node:ekr.20131230090121.16518: *8* vc.find_organizers_node
def find_at_organizers_node(self,root):
    '''
    Find the @organizers node for root, and @auto node.
    Create the @organizers node if it doesn't exist.
    '''
    vc = self
    c = vc.c
    h = '@organizers'
    auto_view = vc.find_at_auto_view_node(root)
    p = g.findNodeInTree(c,auto_view,h)
    if not p:
        p = auto_view.insertAsLastChild()
        p.h = h
    return p
.. @+node:ekr.20131230090121.16539: *8* vc.find_position_for_relative_unl
def find_position_for_relative_unl(self,parent,unl,priority_header=False):
    '''
    Return the node in parent's subtree matching the given unl.
    The unl is relative to the parent position.
    If priority_header == True and the node is not found, it will return the longest matching UNL starting from the tail
    '''
    # This is called from finish_create_organizers & compute_all_organized_positions.
    trace = False # and not g.unitTesting
    trace_loop = True
    trace_success = False
    vc = self
    if not unl:
        if trace and trace_success:
            g.trace('return parent for empty unl:',parent.h)
        return parent
    # The new, simpler way: drop components of the unl automatically.
    drop,p = [],parent # for debugging.
    # if trace: g.trace('p:',p.h,'unl:',unl)
    import re
    pos_pattern = re.compile(r':(\d+),?(\d+)?$')
    for s in unl.split('-->'):
        found = False # The last part must match.
        if 1:
            # Create the list of children on the fly.
            aList = vc.headlines_dict.get(p.v)
            if aList is None:
                aList = [z.h for z in p.children()]
                vc.headlines_dict[p.v] = aList
            try:
                pos = re.findall(pos_pattern,s)
                nth_sib,pos = pos[0] if pos else (0,0)
                pos = int(pos) if pos else 0
                nth_sib = int(nth_sib)
                s = re.sub(pos_pattern,"",s).replace('--%3E','-->')
                indices = [i for i, x in enumerate(aList) if x == s]
                if len(indices)>pos:
                    #First we try the nth node with same header
                    n = indices[pos]
                    p = p.nthChild(n)
                    found = True
                elif len(indices)>0:
                    #Then we try any node with same header
                    n = indices[-1]
                    p = p.nthChild(n)
                    found = True
                elif not priority_header:
                    #Then we go for the child index if return_pos is true
                    if len(aList)>nth_sib:
                        n = nth_sib
                    else:
                        n = len(aList)-1
                    if n>-1:
                        p = p.nthChild(n)
                    else:
                        g.es('Partial UNL match: Referenced level is higher than '+str(p.level()))
                    found = True
                if trace and trace_loop: g.trace('match:',s)
            except ValueError: # s not in aList.
                if trace and trace_loop: g.trace('drop:',s)
                drop.append(s)
        else: # old code.
            for child in p.children():
                if child.h == s:
                    p = child
                    found = True
                    if trace and trace_loop: g.trace('match:',s)
                    break
                # elif trace and trace_loop: g.trace('no match:',child.h)
            else:
                if trace and trace_loop: g.trace('drop:',s)
                drop.append(s)
    if not found and priority_header:
        aList = []
        for p in vc.c.all_unique_positions():
            if p.h.replace('--%3E','-->') in unl:
                aList.append((p.copy(),p.get_UNL(False,False,True)))
        unl_list = [re.sub(pos_pattern,"",x).replace('--%3E','-->') for x in unl.split('-->')]
        for iter_unl in aList:
            maxcount = 0
            count = 0
            compare_list = unl_list[:]
            for header in reversed(iter_unl[1].split('-->')):
                if re.sub(pos_pattern,"",header).replace('--%3E','-->') == compare_list[-1]:
                    count = count+1
                    compare_list.pop(-1)
                else:
                    break
            if count > maxcount:
                p = iter_unl[0]
                found = True
    if found:
        if trace and trace_success:
            g.trace('found unl:',unl,'parent:',p.h,'drop',drop)
    else:
        if trace: g.trace('===== unl not found:',unl,'parent:',p.h,'drop',drop)
    return p if found else None
.. @+node:ekr.20131230090121.16544: *8* vc.find_representative_node
def find_representative_node (self,root,target):
    '''
    root is an @auto node. target is a clones node within root's tree.
    Return a node *outside* of root's tree that is cloned to target,
    preferring nodes outside any @<file> tree.
    Never return any node in any @views or @view tree.
    '''
    trace = False and not g.unitTesting
    assert target
    assert root
    vc = self
    # Pass 1: accept only nodes outside any @file tree.
    p = vc.c.rootPosition()
    while p:
        if p.h.startswith('@view'):
            p.moveToNodeAfterTree()
        elif p.isAnyAtFileNode():
            p.moveToNodeAfterTree()
        elif p.v == target.v:
            if trace: g.trace('success 1:',p,p.parent())
            return p
        else:
            p.moveToThreadNext()
    # Pass 2: accept any node outside the root tree.
    p = vc.c.rootPosition()
    while p:
        if p.h.startswith('@view'):
            p.moveToNodeAfterTree()
        elif p == root:
            p.moveToNodeAfterTree()
        elif p.v == target.v:
            if trace: g.trace('success 2:',p,p.parent())
            return p
        else:
            p.moveToThreadNext()
    g.trace('no representative node for:',target,'parent:',target.parent())
    return None
.. @+node:ekr.20131230090121.16519: *8* vc.find_views_node
def find_at_views_node(self):
    '''
    Find the first @views node in the outline.
    If it does not exist, create it as the *last* top-level node,
    so that no existing positions become invalid.
    '''
    vc = self
    c = vc.c
    p = g.findNodeAnywhere(c,'@views')
    if not p:
        last = c.rootPosition()
        while last.hasNext():
            last.moveToNext()
        p = last.insertAfter()
        p.h = '@views'
        # c.selectPosition(p)
        # c.redraw()
    return p
.. @+node:ekr.20140103062103.16443: *7* vc.has...
# The has commands return None if the node does not exist.
.. @+node:ekr.20140103105930.16447: *8* vc.has_at_auto_view_node
def has_at_auto_view_node(self,root):
    '''
    Return the @auto-view node corresponding to root, an @root node.
    Return None if no such node exists.
    '''
    vc = self
    c = vc.c
    assert vc.is_at_auto_node(root) or vc.is_at_file_node(root),root
    views = g.findNodeAnywhere(c,'@views')
    if views:
        # Find a direct child of views with matching headline and body.
        for p in views.children():
            if vc.match_at_auto_body(p,root):
                return p
    return None
.. @+node:ekr.20131230090121.16529: *8* vc.has_clones_node
def has_at_clones_node(self,root):
    '''
    Find the @clones node for an @auto node with the given unl.
    Return None if it does not exist.
    '''
    vc = self
    p = vc.has_at_auto_view_node(root)
    return p and g.findNodeInTree(vc.c,p,'@clones')
.. @+node:ekr.20140124111748.10637: *8* vc.has_at_headlines_node
def has_at_headlines_node(self,root):
    '''
    Find the @clones node for an @auto node with the given unl.
    Return None if it does not exist.
    '''
    vc = self
    p = vc.has_at_auto_view_node(root)
    return p and g.findNodeInTree(vc.c,p,'@headlines')
.. @+node:ekr.20131230090121.16531: *8* vc.has_organizers_node
def has_at_organizers_node(self,root):
    '''
    Find the @organizers node for root, an @auto node.
    Return None if it does not exist.
    '''
    vc = self
    p = vc.has_at_auto_view_node(root)
    return p and g.findNodeInTree(vc.c,p,'@organizers')
.. @+node:ekr.20131230090121.16535: *8* vc.has_views_node
def has_at_views_node(self):
    '''Return the @views or None if it does not exist.'''
    vc = self
    return g.findNodeAnywhere(vc.c,'@views')
.. @+node:ekr.20140105055318.16755: *7* vc.is...
.. @+node:ekr.20131230090121.16524: *8* vc.is_at_auto_node
def is_at_auto_node(self,p):
    '''Return True if p is an @auto node.'''
    return g.match_word(p.h,0,'@auto') and not g.match(p.h,0,'@auto-')
        # Does not match @auto-rst, etc.

def is_at_file_node(self,p):
    '''Return True if p is an @file node.'''
    return g.match_word(p.h,0,'@file')
.. @+node:ekr.20140102052259.16398: *8* vc.is_cloned_outside_parent_tree
def is_cloned_outside_parent_tree(self,p):
    '''Return True if a clone of p exists outside the tree of p.parent().'''
    return len(list(set(p.v.parents))) > 1
.. @+node:ekr.20131230090121.16525: *8* vc.is_organizer_node
def is_organizer_node(self,p,root):
    '''
    Return True if p is an organizer node in the given @auto tree.
    '''
    vc = self
    return p.hasChildren() and vc.is_comment_node(p,root)

.. @+node:ekr.20140112112622.16660: *7* vc.testing...
.. @+node:ekr.20140109214515.16648: *8* vc.compare_test_trees
def compare_test_trees(self,root1,root2):
    '''
    Compare the subtrees whose roots are given.
    This is called only from unit tests.
    '''
    vc = self
    s1,s2 = vc.trial_write(root1),vc.trial_write(root2)
    if s1 == s2:
        return True
    g.trace('Compare:',root1.h,root2.h)
    p2 = root2.copy().moveToThreadNext()
    for p1 in root1.subtree():
        if p1.h == p2.h:
            g.trace('Match:',p1.h)
        else:
            g.trace('Fail: %s != %s' % (p1.h,p2.h))
            break
        p2.moveToThreadNext()
    return False
.. @+node:ekr.20140115215931.16710: *8* vc.compare_trial_writes
def compare_trial_writes(self,s1,s2):
    '''
    Compare the two strings, the results of trial writes.
    Stop the comparison after the first mismatch.
    '''
    trace_matches = False
    full_compare = False
    lines1,lines2 = g.splitLines(s1),g.splitLines(s2)
    i,n1,n2 = 0,len(lines1),len(lines2)
    while i < n1 and i < n2:
        s1,s2 = lines1[i].rstrip(),lines2[i].rstrip()
        i += 1
        if s1 == s2:
            if trace_matches: g.trace('Match:',s1)
        else:
            g.trace('Fail:  %s != %s' % (s1,s2))
            if not full_compare: return
    if i < n1:
        g.trace('Extra line 1:',lines1[i])
    if i < n2:
        g.trace('Extra line 2:',lines2[i])
.. @+node:ekr.20140115215931.16707: *8* vc.dump_list
def dump_list(self,aList,indent=4):
    '''Dump a list, one item per line.'''
    lead = '\n' + ' '*indent
    return lead+lead.join(sorted(aList))
.. @+node:ekr.20140109214515.16644: *8* vc.trial_write
def trial_write(self,root):
    '''
    Return a trial write of outline whose root is given.
    
    **Important**: the @auto import and write code end all nodes with
    newlines. Because no imported nodes are empty, the code below is
    *exactly* equivalent to the @auto write code as far as trailing
    newlines are concerned. Furthermore, we can treat Leo directives as
    ordinary text here.
    '''
    vc = self
    if 1:
        # Do a full trial write, exactly as will be done later.
        at = vc.c.atFileCommands
        ok = at.writeOneAtAutoNode(root,
            toString=True,force=True,trialWrite=True)
        if ok:
            return at.stringOutput
        else:
            g.trace('===== can not happen')
            return ''
    elif 1:
        # Concatenate all body text.  Close, but not exact.
        return ''.join([p.b for p in root.self_and_subtree()])
    else:
        # Compare headlines, ignoring nodes without body text and comment nodes.
        # This was handy during early development.
        return '\n'.join([p.h for p in root.self_and_subtree()
            if p.b and not p.h.startswith('#')])
.. @+node:ekr.20140105055318.16760: *7* vc.unls...
.. @+node:ekr.20140105055318.16762: *8* vc.drop_all_organizers_in_unl
def drop_all_organizers_in_unl(self,organizer_unls,unl):
    '''Drop all organizer unl's in unl, recreating the imported unl.'''
    vc = self
    def unl_sort_key(s):
        return s.count('-->')
    for s in reversed(sorted(organizer_unls,key=unl_sort_key)):
        if unl.startswith(s):
            s2 = vc.drop_unl_tail(s)
            unl = s2 + unl[len(s):]
    return unl[3:] if unl.startswith('-->') else unl
.. @+node:ekr.20140105055318.16761: *8* vc.drop_unl_tail & vc.drop_unl_parent
def drop_unl_tail(self,unl):
    '''Drop the last part of the unl.'''
    return '-->'.join(unl.split('-->')[:-1])

def drop_unl_parent(self,unl):
    '''Drop the penultimate part of the unl.'''
    aList = unl.split('-->')
    return '-->'.join(aList[:-2] + aList[-1:])
.. @+node:ekr.20140106215321.16673: *8* vc.get_at_organizer_unls
def get_at_organizer_unls(self,p):
    '''Return the unl: lines in an @organizer: node.'''
    return [s[len('unl:'):].strip()
        for s in g.splitLines(p.b)
            if s.startswith('unl:')]

.. @+node:ekr.20131230090121.16541: *8* vc.relative_unl & unl
def relative_unl(self,p,root):
    '''Return the unl of p relative to the root position.'''
    vc = self
    result = []
    ivar = vc.headline_ivar
    for p in p.self_and_parents():
        if p == root:
            break
        else:
            h = getattr(p.v,ivar,p.h)
            result.append(h)
    return '-->'.join(reversed(result))

def unl(self,p):
    '''Return the unl corresponding to the given position.'''
    vc = self
    return '-->'.join(reversed([
        getattr(p.v,vc.headline_ivar,p.h)
            for p in p.self_and_parents()]))
    # return '-->'.join(reversed([p.h for p in p.self_and_parents()]))
.. @+node:ekr.20140106215321.16680: *8* vc.source_unl
def source_unl(self,organizer_unls,organizer_unl):
    '''Return the unl of the source node for the given organizer_unl.'''
    vc = self
    return vc.drop_all_organizers_in_unl(organizer_unls,organizer_unl)
.. @+node:ekr.20140114145953.16696: *8* vc.unl_tail
def unl_tail(self,unl):
    '''Return the last part of a unl.'''
    return unl.split('-->')[:-1][0]
.. @+node:ekr.20140102051335.16506: *5* vc.Commands
@g.command('view-pack')
def view_pack_command(event):
    c = event.get('c')
    if c and c.viewController:
        c.viewController.pack()

@g.command('view-unpack')
def view_unpack_command(event):
    c = event.get('c')
    if c and c.viewController:
        c.viewController.unpack()
        
@g.command('at-file-to-at-auto')
def at_file_to_at_auto_command(event):
    c = event.get('c')
    if c and c.viewController:
        c.viewController.convert_at_file_to_at_auto(c.p)
.. @+node:ekr.20110605121601.18097: *4* lengthHelper (LeoQTextEditWidget)
###
### Do not use this code. It is extremely slow for large text.
###
def lengthHelper(self):
    '''Return the length of the text.'''
    traceTime = False and not g.unitTesting
    if traceTime: t1 = time.time()
    w = self.widget
    tc = w.textCursor()
    tc.movePosition(QtGui.QTextCursor.End)
    n = tc.position()
    if traceTime:
        delta_t = time.time()-t1
        if delta_t > 0.1: g.trace('=========== %2.3f sec' % (delta_t))
    return n
.. @+node:ekr.20140526082700.18006: *4* Old stc classes (keep)
.. @+node:ekr.20140526082700.18397: *5*  Deduction stuff
.. @+node:ekr.20140526082700.18398: *6* DeductionTraverser class
class DeductionTraverser (AstTraverser):

    '''A class to create all Deduction objects by traversing the AST.
    
    This second tree traversal happens after the scope-resolution pass
    has computed the ultimate Context for all names.
    '''

    @others
.. @+node:ekr.20140526082700.18399: *7*  dt.ctor
def __init__(self,fn):

    # Init the base class: calls create_dispatch_table()
    AstTraverser.__init__(self,fn)
    
    self.in_arg_list = False
    self.in_lhs = False
    self.in_rhs = False
.. @+node:ekr.20140526082700.18400: *7*  dt.traverse
def traverse (self,s):
    
    '''Perform all checks on the source in s.'''
    
    t1 = time.time()

    tree = ast.parse(s,filename=self.fn,mode='exec')

    t2 = time.time()
    self.u.stats.parse_time += t2-t1
    
    self.visit(tree)
    
    t3 = time.time()
    self.u.stats.pass1_time += t3-t2
.. @+node:ekr.20140526082700.18401: *7* dt.Contexts
.. @+node:ekr.20140526082700.18402: *8* dt.ClassDef
# ClassDef(identifier name, expr* bases, stmt* body, expr* decorator_list)

def do_ClassDef (self,tree):

    self.visit(tree.name)
    
    for z in tree.body:
        self.visit(z)
.. @+node:ekr.20140526082700.18403: *8* dt.FunctionDef
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)

def do_FunctionDef (self,tree):
    
    self.visit(tree.name)
    
    # No deductions correspond to formal args.
        # assert self.kind(tree.args) == 'arguments'
        # for z in tree.args.args:
            # self.visit(z)
        # for z in tree.args.defaults:
            # self.visit(z)
    
    # Visit the body.
    for z in tree.body:
        self.visit(z)
.. @+node:ekr.20140526082700.18404: *8* dt.Module
def do_Module (self,tree):

    for z in tree.body:
        self.visit(z)
.. @+node:ekr.20140526082700.18405: *7* dt.Operands
.. @+node:ekr.20140526082700.18406: *8* dt.Attribute (rewrite)
def do_Attribute(self,tree):
    
    name = tree.attr
    
    # Use the *formatter* to traverse tree.value.
    expr = g_format_tree(tree.value)
    s = '%s.%s' % (expr,name)
    
    chain = cx.st.add_chain(tree,s)
    
    if use_deductions and self.in_rhs:
        if trace: g.trace('Adding chain to dependencies',chain)
        self.dependencies.append((ast,chain),)
    
    self.u.stats.n_attributes += 1
    return s
        
    
.. @+node:ekr.20140526082700.18407: *8* dt.bool
# Python 2.x only.
def do_bool(self,tree):
    pass
    
.. @+node:ekr.20140526082700.18408: *8* dt.Bytes
# Python 3.x only.
def do_Bytes(self,tree):
    pass

.. @+node:ekr.20140526082700.18409: *8* dt.Call
def do_Call(self,tree):

    self.visit(tree.func)
    for z in tree.args:
        self.visit(z)
    for z in tree.keywords:
        self.visit(z)

    if hasattr(tree,'starargs') and tree.starargs:
        if self.isiterable(tree.starargs):
            for z in tree.starargs:
                self.visit(z)
        else:# Bug fix: 2012/10/22: always visit the tree.
            self.visit(tree.starargs)

    if hasattr(tree,'kwargs') and tree.kwargs:
        if self.isiterable(tree.kwargs):
            for z in tree.kwargs:
                self.visit(z)
        else:
            # Bug fix: 2012/10/22: always visit the tree.
            self.visit(tree.kwargs)
.. @+node:ekr.20140526082700.18410: *8* dt.comprehension
def do_comprehension(self,tree):

    self.visit(tree.target)
    self.visit(tree.iter)
    for z in tree.ifs:
        self.visit(z)

.. @+node:ekr.20140526082700.18411: *8* dt.Dict
def do_Dict(self,tree):

    for z in tree.keys:
        self.visit(z)
    for z in tree.values:
        self.visit(z)

.. @+node:ekr.20140526082700.18412: *8* dt.Ellipsis
def do_Ellipsis(self,tree):
    pass

.. @+node:ekr.20140526082700.18413: *8* dt.ExtSlice
def do_ExtSlice (self,tree):

    for z in tree.dims:
        self.visit(z)

.. @+node:ekr.20140526082700.18414: *8* dt.Index
def do_Index (self,tree):

    self.visit(tree.value)

.. @+node:ekr.20140526082700.18415: *8* dt.int
def do_int (self,s):
    pass

.. @+node:ekr.20140526082700.18416: *8* dt.Keyword
def do_Keyword (self,tree):

    self.visit(tree.arg)
    self.visit(tree.value)

.. @+node:ekr.20140526082700.18417: *8* dt.List
def do_List(self,tree):

    for z in tree.elts:
        self.visit(z)
    self.visit(tree.ctx)

.. @+node:ekr.20140526082700.18418: *8* dt.ListComp
def do_ListComp(self,tree):

    self.visit(tree.elt)

    for z in tree.generators:
        self.visit(z)
        
.. @+node:ekr.20140526082700.18419: *8* dt.Name
def do_Name(self,tree):

    name = tree.id # a string.

    # if isPython3:
        # if name in self.u.module_names:
            # return
    # else:
        # if name in dir(__builtin__) or name in self.u.module_names:
            # return
            
    ctx = self.visit(tree.ctx)
            
    if ctx == 'Load': # Most common.
        pass
    elif ctx == 'Store': # Next most common.
        pass
    elif ctx == 'Param':
        pass
    else:
        assert ctx == 'Del',ctx
        cx.del_names.add(name)
        self.u.stats.n_del_names += 1
.. @+node:ekr.20140526082700.18420: *8* dt.Num
def do_Num(self,tree):
    pass

.. @+node:ekr.20140526082700.18421: *8* dt.Slice
def do_Slice (self,tree):

    if hasattr(tree,'lower') and tree.lower is not None:
        self.visit(tree.lower)
    if hasattr(tree,'upper') and tree.upper is not None:
        self.visit(tree.upper)
    if hasattr(tree,'step') and tree.step is not None:
        self.visit(tree.step)

.. @+node:ekr.20140526082700.18422: *8* dt.Str
def do_Str (self,tree):
    '''This represents a string constant.'''
    pass
.. @+node:ekr.20140526082700.18423: *8* dt.Subscript
def do_Subscript(self,tree):

    self.visit(tree.slice)
    self.visit(tree.ctx)

.. @+node:ekr.20140526082700.18424: *8* dt.Tuple
def do_Tuple(self,tree):

    for z in tree.elts:
        self.visit(z)
    self.visit(tree.ctx)
.. @+node:ekr.20140526082700.18425: *7* dt.Statements
.. @+node:ekr.20140526082700.18426: *8* dt.Assign
def do_Assign(self,tree):
    
    val = self.visit(tree.value)
    
    for z in tree.targets:
        target = self.visit(z)
        Deduction(tree,self.assign_deducer,target,val)
.. @+node:ekr.20140526082700.18427: *8* dt.AugAssign
def do_AugAssign(self,tree):

    Deduction(tree,
        self.visit(tree.op), # deducer method.
        self.visit(tree.target), # lhs
        self.visit(tree.value), # rhs
    )
.. @+node:ekr.20140526082700.18428: *8* dt.Call
def do_Call(self,tree):

    f        = self.visit(tree.func)
    args     = [self.visit(z) for z in tree.args]
    keywords = [self.visit(z) for z in tree.keywords]
    starargs = self.visit(tree.starargs) if  hasattr(tree,'starargs') and tree.starargs else []
    kwargs   = self.visit(tree.kwargs) if hasattr(tree,'kwargs') and tree.kwargs else []
        
    Deduction(tree,self.call_deducer,f,args,keywords,starags,kwargs)
.. @+node:ekr.20140526082700.18429: *8* dt.For
def do_For (self,tree):
    
    self.visit(tree.target)

    self.visit(tree.iter)
    
    for z in tree.body:
        self.visit(z)

    for z in tree.orelse:
        self.visit(z)
.. @+node:ekr.20140526082700.18430: *8* dt.Global
def do_Global(self,tree):

    pass
.. @+node:ekr.20140526082700.18431: *8* dt.Import & helpers
def do_Import(self,tree):

    pass
.. @+node:ekr.20140526082700.18432: *8* dt.ImportFrom
def do_ImportFrom(self,tree):
    
    pass
.. @+node:ekr.20140526082700.18433: *8* dt.Lambda & helper
def do_Lambda (self,tree):
    
    # Lambda args do not create deductions.
        # assert self.kind(tree) == 'arguments'
        # for z in tree.args.args:
            # self.visit(z)
        # for z in tree.args.defaults:
            # self.visit(z)
            
    self.visit(tree.body)
.. @+node:ekr.20140526082700.18434: *8* dt.Return
def do_Return(self,tree):
    
    if tree.value:
        val = self.visit(tree.value)
        Deduction(tree,self.return_deducer,val)
    else:
        Deduction(tree,self.return_deducerd)
.. @+node:ekr.20140526082700.18435: *8* dt.With
def do_With (self,tree):
    
    if hasattr(tree,'context_expression'):
        self.visit(tree.context_expresssion)

    if hasattr(tree,'optional_vars'):
        try:
            for z in tree.optional_vars:
                self.visit(z)
        except TypeError: # Not iterable.
            self.visit(tree.optional_vars)
    
    for z in tree.body:
        self.visit(z)
.. @+node:ekr.20140526082700.18436: *6* old Deduction ctor
def __init__ (sd,target,aList):
    
    if trace:
        name,obj = target
        deps = [b.short_description() for a,b in aList]
        g.trace('(Op) lhs: %s, aList: %s' % (name,deps))
    
    self.deps = aList
        # a list tuples (ast,s)
        # describing the symbols on which the target depends.
        # s is a string, either a plain id or an id chain.
        
    self.sd = sd

    self.target = target
        # A tuple (name,object) representing the target (LHS) of an assignment statement.
        # name is the spelling (a string) of the plain id or id chain.
        # object is a Chain for chains; a SymbolTableEntry for plain ids.
        # Note: chain.e is the SymbolTableEntry for chains.
        
    sd.n_dependencies += 1
    
    self.fold()
.. @+node:ekr.20140526082700.18437: *6* e.become_known (To do)
def remove_symbol (self,e):
    
    '''The type of this SymbolTableEntry has just become known.
    
    Remove e from this Dependency.
    
    If the Dependency becomes known, do the following:
        
    - Call eval_ast to evaluate the type.
    - Assign the type to the Dependency's symbol.
    - Add the symbol to sd.known_types.
    '''
  
    e = self
    
    for dep in e.dependencies:
        dep.remove(e) # May add entries to sd.known_types.
    e.dependencies = []

    g.trace(e)
.. @+node:ekr.20140526082700.18438: *6* e.is_known
def is_known (self):
    
    '''return True if this is a known symbol.'''
    
    return len(self.vals) == 1
.. @+node:ekr.20140527123213.17048: *5*  Inference-related classes
.. @+node:ekr.20140526082700.18046: *6* class CacheTraverser (AstTraverser)
class CacheTraverser(AstTraverser):
    
    '''A class to report the contents of caches.'''
    
    def __init__(self):
    
        AstTraverser.__init__(self)
        self.level = 0
    
    @others
.. @+node:ekr.20140526082700.18047: *7* ct.show_cache
def show_cache(self,obj,cache,tag):
    
    d = cache
    pad = ' '*2*self.level
    result = []
    for key in sorted(d.keys()):
        aList = d.get(key)
        if len(aList) > 1 or (aList and repr(aList[0]) != 'Unknown'):
            # result.append('  %s%20s => %s' % (pad,key,aList))
            result.append('  %s%s' % (pad,aList))
    if result:
        s = self.format(obj) if isinstance(obj,ast.AST) else repr(obj)
        s = s.replace('\n','')
        if len(s) > 40: s = s[:37]+'...'
        if len(result) == 1:
            print('%s%s: %40s -> %s' % (pad,tag,s,result[0].strip()))
        else:
            print('%s%s: %s' % (pad,tag,s))
            for s in result:
                print(s)
.. @+node:ekr.20140526082700.18048: *7* ct.run
def run (self,node):

    self.check_visitor_names()
    fn = ' for %s' % (g.shortFileName(self.fn)) if self.fn else ''
    print('\nDump of caches%s...' % fn)
    self.visit(node)
.. @+node:ekr.20140526082700.18049: *7* ct.traversers
.. @+node:ekr.20140526082700.18050: *8* ct.visit
def visit(self,node):
    
    """Walk a tree of AST nodes."""

    assert isinstance(node,ast.AST),node.__class__.__name__

    method_name = 'do_' + node.__class__.__name__
    method = getattr(self,method_name,None)
    if method:
        # method is responsible for traversing subtrees.
        return method(node)
    else:
        self.visit_cache(node)

        # Traverse subtrees automatically, without calling visit_children.
        for child in self.get_child_nodes(node):
            self.visit(child)
.. @+node:ekr.20140526082700.18051: *8* ct.visit_cache
def visit_cache(self,node):
    
    if hasattr(node,'cache'):
        self.show_cache(node,node.cache,'cache')
        
    if hasattr(node,'e') and hasattr(node.e,'call_cache'):
        self.show_cache(node,node.e.call_cache,'call_cache')
.. @+node:ekr.20140526082700.18052: *7* ct.visitors
.. @+node:ekr.20140526082700.18053: *8* ct.ClassDef
# ClassDef(identifier name, expr* bases, stmt* body, expr* decorator_list)

def do_ClassDef(self,node):
    
    pad = ' '*2*self.level
    bases = ','.join([self.format(z) for z in node.bases])
    print('%sclass %s(%s)' % (pad,node.name,bases))
    
    self.level += 1
    try:
        self.visit_children(node)
    finally:
        self.level -= 1
.. @+node:ekr.20140526082700.18054: *8* ct.functionDef
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)

def do_FunctionDef (self,node):
    
    pad = ' '*2*self.level
    print('%sdef %s(%s)' % (pad,node.name,self.format(node.args)))
    
    self.level += 1
    try:
        self.visit_children(node)
    finally:
        self.level -= 1
.. @+node:ekr.20140526082700.18055: *6* class ChainPrinter (OpPatternFormatter)
class ChainPrinter: ### (OpPatternFormatter):
    
    def __init__ (self,fn):
    
        self.d = {}
        self.top_attribute = True
    
        ### OpPatternFormatter.__init__ (self)
            # Init the base class.

    @others
.. @+node:ekr.20140526082700.18056: *7* Attribute
# Attribute(expr value, identifier attr, expr_context ctx)

def do_Attribute(self,node):
    
    top = self.top_attribute
    try:
        self.top_attribute = False
        value = node.value
        attr  = node.attr
        s = '%s.%s' % (
            self.visit(value),
            self.visit(attr))
    finally:
        self.top_attribute = top
        
    if top:
        aList = s.split('.')
        if aList:
            name,rest = aList[0],aList[1:]
            if (
                name == 'self' and len(rest) > 1 or
                name != 'self' and len(rest) > 0
            ):
                aList2 = self.d.get(name,[])
                if rest not in aList2:
                    aList2.append(rest)
                    self.d[name] = aList2
                
    return s
.. @+node:ekr.20140526082700.18057: *7* showChains
def showChains(self):
    
    verbose = False
    result = []
    d,n1,n2 = self.d,0,0
    for key in sorted(d.keys()):
        aList = d.get(key)
        for chain in sorted(aList):
            s = '.'.join(chain)
            if s.find('(') > -1 or s.find('[') > -1 or s.find('{') > -1:
                # print('%s.%s' % (key,s))
                result.append('%s.%s' % (key,s))
                n2 += 1
            else:
                if verbose:
                    result.append('%s.%s' % (key,s))
                n1 += 1

    return n1,n2,'\n'.join(result)

.. @+node:ekr.20140526082700.18058: *6* class Context & subclasses
<< define class Context >>

@others
.. @+node:ekr.20140526082700.18059: *7* << define class Context >>
class Context:

    '''The base class of all Context objects.
    Contexts represent static scopes.'''

    @others
.. @+node:ekr.20140526082700.18060: *8*  cx ctor
def __init__(self,parent_context):

    self.format = u.format
    self.kind = '<Unknown context kind>' # All subclasses set this.
    self.name = '<Unknown context name>' # All subclasses set this.
    self.parent_context = parent_context
    self.st = SymbolTable(cx=self)
    self.stats = Stats()
    self.stats.n_contexts += 1

    # Public semantic data: accessed via getters.
    self.assignments_list = [] # All assignment statements.
    self.calls_list = [] # All call statements defined in this context.
    self.classes_list = [] # Classes defined in this context.
    self.defs_list = [] # Functions defined in this context.
    self.expressions_list = [] # Expr nodes in this context.
    self.definitions_of = [] # Assignments, imports and arguments that define this symbol.
    self.imported_symbols_list = [] # All imported symbols.
    self.methods_list = [] # # All methods of a class context.  Elements are DefContexts.
    self.returns_list = [] # List of all return statements in the context.
    self.statements_list = [] # List of *all* statements in the context.
    self.yields_list = [] # List of all yield statements in the context.

    # Private semantic data: no getters.
    self.n_lambdas = 0
        # Number of lambdas in this context:
        # Used to synthesize names of the form 'Lambda@@n'
    self.defining_context = self
    # self.global_names = set()
        # Names that appear in a global statement in this context.
    self.node = None
        # The AST tree representing this context.
.. @+node:ekr.20140526082700.18061: *8* cx.__getstate__
def __getstate__(self):
    
    '''Return the representation of the Context class for use by pickle.'''
    
    d = {
        'calls':        [repr(z) for z in self.calls_list],
        'classes':      [repr(z) for z in self.classes_list],
        'defs':         [repr(z) for z in self.defs_list],
        'statements':   [repr(z) for z in self.statements()],
    }

    return d
.. @+node:ekr.20140526082700.18062: *8* cx.__hash__
# Important: Define __hash__ only if __eq__ is also defined.

def __hash__ (self):
    return id(self)

# This is defined below...

# def __eq__ (self,other):
    # return id(self) == id(other)
.. @+node:ekr.20140526082700.18063: *8* cx.__repr__ & __str__
def __repr__ (self):

    return 'Cx:id(%s)' % id(self)
    
__str__ = __repr__
.. @+node:ekr.20140526082700.18064: *8* cx.__eq__ & __ne__(others return NotImplemented)
# Py3k wants __lt__ etc, and Py2k needs all of them defined.

# Use identity only for contexts!
def __lt__(self, other): return NotImplemented 
def __le__(self, other): return NotImplemented 
def __eq__(self, other): return id(self) == id(other)
def __ne__(self, other): return id(self) != id(other)
def __gt__(self, other): return NotImplemented 
def __ge__(self, other): return NotImplemented 

# if 1:
    # # Ignore case in comparisons.
    # def __lt__(self, other): return self.name.lower() <  other.name.lower()
    # def __le__(self, other): return self.name.lower() <= other.name.lower()
    # def __eq__(self, other): return self.name.lower() == other.name.lower()
    # def __ne__(self, other): return self.name.lower() != other.name.lower()
    # def __gt__(self, other): return self.name.lower() >  other.name.lower()
    # def __ge__(self, other): return self.name.lower() >= other.name.lower()
# else:
    # def __lt__(self, other): return self.name <  other.name
    # def __le__(self, other): return self.name <= other.name
    # def __eq__(self, other): return self.name == other.name
    # def __ne__(self, other): return self.name != other.name
    # def __gt__(self, other): return self.name >  other.name
    # def __ge__(self, other): return self.name >= other.name
.. @+node:ekr.20140526082700.18065: *8* cx.description & short_description
def description (self):
    
    '''Return a description of this context and all parent contexts.'''
    
    if self.parent_context:
        return  '%s:%s' % (
            self.parent_context.description(),repr(self))
    else:
        return repr(self)

def short_description(self):
    return repr(self)
.. @+node:ekr.20140526082700.18066: *8* cx.dump_statements
def dump_statements(self,var_filter=None):
    
    cx = self
    # aList = [node.dump(0,var_filter=var_filter) for node in cx.local_statements()]
    aList = [self.u.dump_ast(node) for node in cx.local_statements()]
    return '\n'.join([z for z in aList if z.strip()])
.. @+node:ekr.20140526082700.18067: *8* cx.full_name
def full_name (self):
    
    '''Return a context name for compatibility with HTMLReportTraverser.'''
    
    # A hack: must match the name generated in rt.report().
    
    return 'report_writer_test' if self.name == '<string>' else self.name
.. @+node:ekr.20140526082700.18068: *8* cx.generators & getters
# Unlike in leoInspect, most of these getters return lists of Statement objects.
.. @+node:ekr.20140526082700.18069: *9* cx.assignments
# This is really a helper for assignments_to/using.
def assignments(self):
    
    result = []
    for cx in self.contexts():
        result.extend(cx.assignments_list)
    return result
.. @+node:ekr.20140526082700.18070: *9* cx.assignments_to (rewritten)
def assignments_to (self,s):
    
    cx = self
    result = []
    for node in cx.assignments():
        statement = cx.u.format(node)
        kind = cx.u.kind(node)
        if kind == 'Assign':
            #  Assign(expr* targets, expr value)
            for target in node.targets:
                kind2 = cx.u.kind(target)
                if kind2 == 'Name':
                    if s == target.id:
                        result.append(statement)
                elif kind2 == 'Tuple':
                    # Tuple(expr* elts, expr_context ctx)
                    for item2 in target.elts:
                        if cx.u.kind(item2) == 'Name' and s == item2.id:
                            result.append(statement)
        elif kind == 'AugAssign':
            kind2 = cx.u.kind(node.target)
            if kind2 == 'Name':
                if s == node.target.id:
                    result.append(statement)
        elif kind == 'For':
            s2 = statement
            i = s2.find(' in ')
            assert s2.startswith('for ')
            assert i > -1
            s2 = s2[4:i].strip('()')
            aList = s2.split(',')
            if s in aList:
                i = statement.find(':\n')
                assert i > -1
                result.append(statement[:i+1])
        elif kind == 'ListComp':
            # node.generators is a comprehension.
            for item in node.generators:
                target = item.target
                kind2 = cx.u.kind(target)
                if kind2 == 'Name':
                    if s == target.id:
                        result.append(statement)
                elif kind2 == 'Tuple':
                    for item2 in target.elts:
                        if cx.u.kind(item2) == 'Name' and s == item2.id:
                            result.append(statement)
                            break
                else:
                    assert False,kind2
        else:
            assert False,kind
    return list(set(result))
.. @+node:ekr.20140526082700.18071: *9* cx.assignments_using
def assignments_using (self,s):
    
    result = []
    for node in self.assignments():
        assert node.kind in ('Assign','AugAssign'),node.kind
        val = node.value
        rhs = self.format(val)
        i = rhs.find(s,0)
        while -1 < i < len(rhs):
            if g.match_word(rhs,i,s):
                result.append(node)
                break
            else:
                i += len(s)

    return result
.. @+node:ekr.20140526082700.18072: *9* cx.call_args_of
def call_args_of (self,s):
    
    result = []
    for node in self.calls():
        assert node.kind == 'Call'
        func = self.format(node.func)
        if s == func:
            result.append(node) ### Should return only args.

    return result
.. @+node:ekr.20140526082700.18073: *9* cx.calls
# This is really a helper for calls_to/call_args_of.
def calls(self):
    
    result = []
    for cx in self.contexts():
        result.extend(cx.calls_list)
    return result
.. @+node:ekr.20140526082700.18074: *9* cx.calls_to
def calls_to (self,s):

    result = []
    for node in self.calls():
        assert node.kind == 'Call'
        func = self.format(node.func)
        if s == func:
            result.append(node)

    return result
.. @+node:ekr.20140526082700.18075: *9* cx.classes
def classes (self):
    
    result = []
    for cx in self.contexts():
        result.extend(cx.classes_list)
    return result
.. @+node:ekr.20140526082700.18076: *9* cx.contexts & getters
def contexts (self,name=None):
        
    '''An iterator returning all contexts.
    
    If name is given, return only contexts with the given name.'''
    
    cx = self
    
    if name is None or cx.name == name:
        yield cx
       
    for cx2 in self.classes_list:
        for z in cx2.contexts(name=name):
            if z != self:
                yield z

    for cx2 in self.defs_list:
        for z in cx2.contexts(name=name):
            if z != self:
                yield z
.. @+node:ekr.20140526082700.18077: *10* get_contexts and get_unique_context
# These getters are designed for unit testing.
def get_contexts(self,name):
    
    '''Return the list of symbol tables having the given name.
    If the list has exactly one element, return it.'''
    
    aList = list(self.contexts(name=name))
    return aList[0] if aList and len(aList) == 1 else aList
   
def get_unique_context (self,name):
    
    '''Return the unique symbol table having the given name.
    Raise AssertionError if the unexpected happens.'''
    
    aList = list(self.contexts(name=name))
    assert aList and len(aList) == 1,aList
    return aList[0]
.. @+node:ekr.20140526082700.18078: *9* cx.defs
def defs (self):
    
    result = []
    for cx in self.contexts():
        result.extend(cx.defs_list)
    return result
.. @+node:ekr.20140526082700.18079: *9* cx.parent_contexts
def parent_contexts (self):
    
    cx = self
    result = []

    while cx.parent_context:
        result.append(cx.parent_context)
        cx = cx.parent_context

    result.reverse()
    return result
.. @+node:ekr.20140526082700.18080: *9* cx.returns (dubious)
# Using cx.returns_list will almost always be correct.

if 0:
    
    def returns (self):
        
        '''Return all return statements in the present context and all descendant contexts.'''
        
        result = []
        for cx in self.contexts():
            result.extend(cx.returns_list)
        return result
.. @+node:ekr.20140526082700.18081: *9* cx.statements (new)
def statements (self):
    
    '''A generator yielding all statements in the receiver context, in the proper order.'''

    cx = self
    assert cx.kind in ('class','def','lambda','module')
    for node in cx.statements_list:
        yield node
.. @+node:ekr.20140526082700.18082: *9* cx.symbol_tables & getters
def symbol_tables (self,name=None):
    
    '''Return all symbol tables for all contexts.
    If name is given, return only symbol tables for contexts with the given name.'''
    
    cx = self

    if name:
        for cx2 in self.contexts():
            if name == cx2.name:
                yield cx2.st
    else:
        for cx2 in self.contexts():
            yield cx2.st

.. @+node:ekr.20140526082700.18083: *10* get_symbol_tables and get_unique_symbol_table
# These getters are designed for unit testing.
def get_symbol_tables (self,name):
    
    '''Return the list of symbol tables having the given name.
    If the list has exactly one element, return it.'''
    
    aList = list(self.symbol_tables(name=name))
    return aList[0] if aList and len(aList) == 1 else aList
   
def get_unique_symbol_table (self,name):
    
    '''Return the unique symbol table having the given name.
    Raise AssertionError if the unexpected happens.'''
    
    aList = list(self.symbol_tables(name=name))
    assert aList and len(aList) == 1,aList
    return aList[0]
.. @+node:ekr.20140526082700.18084: *9* cx.symbol_table_entries
def symbol_table_entries (self,name):
    
    '''Return all STE's for the given name.'''
    
    cx = self

    for cx2 in cx.contexts():
        d = cx2.st.d
        e = d.get(name)
        if e:
            yield d.get(name)
.. @+node:ekr.20140526082700.18085: *9* cx.local_statements
def local_statements(self):
    
    '''Return the top-level statements of a context.'''
    
    cx = self

    assert cx.kind in ('class','def','lambda','module')

    return cx.node.body
.. @+node:ekr.20140526082700.18086: *8* cx.line_number (not used)
# def line_number (self):
    
    # return self.tree_ptr.lineno
.. @+node:ekr.20140526082700.18087: *8* cx.token_range (TO DO) (Uses tree_ptr)
# def token_range (self):
    
    # tree = self.tree_ptr
    
    # # return (
        # # g.toUnicode(self.byte_array[:tree.col_offset]),
        # # g.toUnicode(self.byte_array[:tree_end_col_offset]),
    # # )
    
    # if getattr(tree,'col_offset',None):
        # return tree.lineno,tree.col_offset,tree.end_lineno,tree.end_col_offset
    # else:
        # return -1,-1
.. @+node:ekr.20140526082700.18088: *7* class ClassContext
class ClassContext (Context):

    '''A class to hold semantic data about a class.'''
    
    @others

.. @+node:ekr.20140526082700.18089: *8* ClassContext.__init__
def __init__(self,u,parent_context,name,node,bases):

    Context.__init__(self,u,parent_context)
        # Init the base class.

    self.ctor = None # Filled in when def __init__ seen.
    self.kind = 'class'
    self.bases = bases # A list of ast.Name nodes?
    self.name = name
    self.class_context  = self
    self.def_context = self.parent_context.def_context
    self.ivars_dict = {} # Keys are names, values are reaching sets.
    self.module_context = self.parent_context.module_context
    self.node = node
    u.stats.n_classes += 1
.. @+node:ekr.20140526082700.18090: *8* ClassContext.__repr__& __str__
def __repr__ (self):

    if self.bases:
        bases = [self.format(z) for z in self.bases]
        return 'Cx:class %s(%s)' % (self.name,','.join(bases))
    else:
        return 'Cx:class %s' % (self.name)

__str__ = __repr__        
.. @+node:ekr.20140526082700.18091: *8* ClassContext.short_description
def short_description(self):
    
    if self.bases:
        bases = [self.format(z) for z in self.bases]
        return 'class %s(%s):' % (self.name,','.join(bases))
    else:
        return 'class %s:' % (self.name)
.. @+node:ekr.20140526082700.18092: *7* class DefContext
class DefContext (Context):

    '''A class to hold semantic data about a function/method.'''
        
    @others

    
.. @+node:ekr.20140526082700.18093: *8* DefContext.__init__
def __init__(self,u,parent_context,name):
    
    Context.__init__(self,u,parent_context)
    self.kind = 'def'
    self.name = name
    self.args = None # Must be set later.
    self.class_context = self.parent_context.class_context
    self.def_context = self
    self.module_context = self.parent_context.module_context
    self.node = None
    u.stats.n_defs += 1
.. @+node:ekr.20140526082700.18094: *8* DefContext.__repr__ & __str__
def __repr__ (self):
    
    args = self.format(self.args) if self.args else  '<**no args yet**>'

    return 'Cx:def %s(%s)' % (self.name,args)

__str__ = __repr__        
.. @+node:ekr.20140526082700.18095: *8* DefContext.short_description
def short_description (self):
  
    args = self.format(self.args) if self.args else ''

    return 'def %s(%s):' % (self.name,args)
.. @+node:ekr.20140526082700.18096: *7* class LambdaContext
class LambdaContext (Context):

    '''A class to represent the range of a 'lambda' statement.'''

    def __init__(self,u,parent_context,name):
        Context.__init__(self,u,parent_context)
        self.kind = 'lambda'
        self.args = None # Patched in later.
        self.class_context  = self.parent_context.class_context
        self.def_context    = self.parent_context.def_context
        self.module_context = self.parent_context.module_context
        self.name = name # Set to 'Lambda@@n' by the caller.
        self.node = None
        u.stats.n_lambdas += 1

    def __repr__ (self):
        if self.args:
            args = ','.join([self.format(z) for z in self.args])
        else:
            args = 'None'
        return 'Cx:lambda %s:' % (args)

    __str__ = __repr__
.. @+node:ekr.20140526082700.18097: *7* class LIbraryModuleContext
class LibraryModuleContext (Context):

    '''A class to hold semantic data about a module.'''

    def __init__(self,u,fn):
        Context.__init__(self,u,parent_context=None)
        self.kind = 'module'
        self.class_context  = None
        self.def_context    = None
        self.fn = g.os_path_abspath(fn)
        self.module_context = self
        self.module_type = Module_Type(u,self,node=None)
            # The singleton *constant* type of this module.
        if fn.find('.') > -1:
            self.name = g.shortFileName(self.fn)[:-3]
        else:
            self.name = fn
        self.node = None
        u.stats.n_library_modules += 1

    def __repr__ (self):
        return 'Cx:module(%s)' % self.name

    __str__ = __repr__        
.. @+node:ekr.20140526082700.18098: *7* class ModuleContext
class ModuleContext (Context):

    '''A class to hold semantic data about a module.'''

    def __init__(self,u,fn,node):
        Context.__init__(self,u,parent_context=None)
        self.kind = 'module'
        self.class_context  = None
        self.def_context    = None
        self.fn = g.os_path_abspath(fn)
        self.module_context = self
        self.module_type = Module_Type(u,self,node)
            # The singleton *constant* type of this module.
        if fn.find('.') > -1:
            self.name = g.shortFileName(self.fn)[:-3]
        else:
            self.name = fn
        self.node = node
        u.stats.n_modules += 1

    def __repr__ (self):
        return 'Cx:module(%s)' % self.name

    __str__ = __repr__        
.. @+node:ekr.20140526082700.18290: *6* class ScopeBinder
# Running ScopeBinder on all Leo files:
# 1.25sec when this class is a subclass of AstTraverser
# 0.75sec when this class is a subclass of AstFullTraverser.

class ScopeBinder(AstFullTraverser):
    
    '''Resolve all symbols to the scope in which they are defined.
    
    This pass is invoked by P1; it must run after P1 has injected
    all fields into the trees and discovered all definitions.
    '''
    
    def __init__(self):
        AstFullTraverser.__init__(self)
        self.init_dicts()
        self.u = Utils()

    @others
.. @+node:ekr.20140526082700.18291: *7* sb.check & helper
def check(self,fn,root):
    trace = True and not g.app.runningAllUnitTests
    u = self.u
    for cx in u.contexts(root):
        assert hasattr(cx,'stc_context'),cx
        result = []
        self.check_context(cx,result)
        if trace and result:
            result=sorted(set(result))
            pad = ' '*u.compute_node_level(cx)
            result.insert(0,'%s%s' % (pad,u.format(cx)))
            if fn:
                result.insert(0,fn)
            for s in result:
                print(s)
.. @+node:ekr.20140526082700.18292: *8* check_context
def check_context(self,cx,result):
    
    trace = False
    u = self.u
    for statement in u.local_statements(cx):
        if trace:
            pad = ' '*u.compute_node_level(statement)
            print(pad+u.format(statement))
        for node in u.local_nodes(statement):
            # if trace:print(' %s%s: %s' % (pad,node.__class__.__name__,u.format(node)))
            if isinstance(node,ast.Name):
                key = node.id
                def_cx = getattr(node,'stc_scope')
                if def_cx:
                    d = def_cx.stc_symbol_table
                    aSet = d.get('*defined*')
                    if key not in aSet:
                        # UnboundLocalError: no definition in scope.
                        pad = ' '*u.compute_node_level(statement)
                        result.append(' %s*%s %s: %s' % (
                            pad,u.format(node.ctx),key,u.format(statement)))
                else:
                    d = self.lookup(cx,key)
                    if d:
                        assert d.has_key(key),repr(key)
                    else:
                        # No scope.
                        pad = ' '*u.compute_node_level(statement)
                        result.append(' %s+%s %s: %s' % (
                            pad,u.format(node.ctx),key,u.format(statement)))
.. @+node:ekr.20140526082700.18293: *7* sb.dump_symbol_table
def dump_symbol_table(self,node):
    
    if getattr(node,'stc_symbol_table',None):
        d = node.stc_symbol_table
        for key in sorted(d.keys()):
            name = d.get(key)
            print('%s:%s' % (self.format(name.ctx),name.id))
.. @+node:ekr.20140526082700.18294: *7* sb.init_dicts
def init_dicts(self):
    
    self.builtins_d = dict([(z,z) for z in __builtins__])

    table = (
        '__builtins__',
        '__file__',
        '__path__',
        '__repr__',
    )
    self.special_methods_d = dict([(z,z) for z in table])
.. @+node:ekr.20140526082700.18295: *7* sb.lookup
def lookup(self,cx,key):
    
    '''Return the symbol table for key, starting the search at node cx.'''
    
    trace = False and not g.app.runningAllUnitTests
    assert isinstance(cx,(ast.Module,ast.ClassDef,ast.FunctionDef,ast.Lambda)),cx
    cx2 = cx
    while cx2:
        st = cx.stc_symbol_table
        if key in st.d.keys():
            return st.d
        else:
            cx2 = cx2.stc_context
            assert isinstance(cx,(ast.Module,ast.ClassDef,ast.FunctionDef,ast.Lambda)),cx
    for d in (self.builtins_d,self.special_methods_d):
        if key in d.keys():
            return d
    else:
        if trace:
            g.trace('** (ScopeBinder) no definition for %20s in %s' % (
                key,self.u.format(cx)))
        return None
.. @+node:ekr.20140526082700.18296: *7* sb.run
def run (self,fn,root):

    self.fn = g.shortFileName(fn)
    self.n_resolved = 0
    self.n_visited = 0
    self.visit(root)
    if 0:
        self.check(fn,root)
        # g.trace('ScopeBinder visited %s nodes' % self.n_visited)
.. @+node:ekr.20140526082700.18297: *7* sb.visit & visitors
def visit(self,node):

    # assert isinstance(node,ast.AST),node.__class__.__name__
    method = getattr(self,'do_' + node.__class__.__name__)
    self.n_visited += 1
    return method(node)
.. @+node:ekr.20140526082700.18298: *8* sb.FunctionDef
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)

def do_FunctionDef (self,node):
    
    self.visit(node.args)
    for z in node.body:
        self.visit(z)
    for z in node.decorator_list:
        self.visit(z)
  
.. @+node:ekr.20140526082700.18299: *8* sb.Name
# Name(identifier id, expr_context ctx)

def do_Name(self,node):
    
    '''Set node.stc_scope for all references to names.'''
    
    trace = False and not g.app.runningAllUnitTests

    # if isinstance(node.ctx.__class__,ast.Param):# 
        # assert node.stc_scope is not None,node
            # P1 has defined the scope.
    # elif isinstance(node.ctx,ast.Store):
        # assert node.stc_scope is not None,node
        
    if node.stc_scope is None:
        # Search for the defining context.
        self.n_resolved += 1
        cx = node.stc_context
            # cx will be None if cx is an ast.Module.
            # In that case, self.lookup will search the builtins.
        d = self.lookup(cx,node.id)
        if d is None:
            # g.trace('(ScopeBinder) undefined symbol: %s' % node.id)
            if trace: print('%s undefined name: %s' % (self.fn,node.id))
.. @+node:ekr.20140526082700.18204: *6* class Pass1 (AstFullTraverser)
class Pass1 (AstTraverser):
    
    ''' Pass1 traverses an entire AST tree, creating symbol
    tables and context objects, injecting pointers to them
    in the tree. This pass also resolves Python names to
    their proper context, following the rules of section
    4.1, Naming and binding, of the Python langauge
    reference.
    
    Pass1 uses the tree-traversal code from the AstTraverser
    base class. As a result, not all AST nodes need to be
    visited explicitly.
    
    Pass 1 injects the following fields into ast.AST nodes::

    for N in cx: refs_list: N.e = e
    for N in (ast.Class, ast.FunctionDef and ast.Lambda): N.new_cx = new_cx
    For ast.Name nodes N: N.e = e ; N.cx = cx
    For all operator nodes N: N.op_name = <spelling of operator>

    For every context C, Pass 1 sets the following ivars of C:
        C.node                  <node defining C>
        C.ivars_dict            Dictionary of ivars.
                                Keys are names, values are reaching sets (set by SSA pass)
        C.assignments_list      All assignment statements in C
        C.calls_list            All call statements defined in C.
        C.classes_list          All classes defined in C.
        C.defs_list             All functions defined in C.
        C.expressions_list      All Expr nodes in C.
        C.returns_list          All return statements in C.
        C.yields_list           All yield statements in C.
    '''

    @others
.. @+node:ekr.20140526082700.18205: *7*  p1.ctor
def __init__(self):
    
    # Init the base class.
    AstTraverser.__init__(self)
    
    # Abbreviations.
    self.stats = Stats()
    self.u = Utils()
    self.format = u.format
    
    # self.gen_flag = False
        # True: enable code generation (in part of an AST).
        # We generate code only for assignments,
        # returns, yields and function calls.

    self.in_attr = False
        # True: traversing inner parts of an AST.Attribute tree.
.. @+node:ekr.20140526082700.18206: *7*  p1.run (entry point)
def run (self,root):

    self.visit(root)
.. @+node:ekr.20140526082700.18207: *7*  p1.visit
def visit(self,node):
    
    """Walk a tree of AST nodes, injecting _parent entries into the tree."""
    
    assert isinstance(node,ast.AST),node.__class__.__name__
    node._parent = self.parents[-1]
    if self.context_stack:
        node.cx = self.context_stack[-1]

    self.level += 1
    self.parents.append(node)

    method_name = 'do_' + node.__class__.__name__
    # stat_name = 'n_' + node.__class__.__name__ + '_nodes'
    method = getattr(self,method_name,None)
    if method:
        # method is responsible for traversing subtrees.
        val = method(node)
    else:
        # Traverse subtrees automatically.
        val = None
        for child in self.get_child_nodes(node):
            val = self.visit(child)
            
    self.level -= 1
    self.parents.pop()
    return val
.. @+node:ekr.20140526082700.18208: *7* p1.helpers
.. @+node:ekr.20140526082700.18209: *8* p1.bind_name
def bind_name(self,new_cx,old_cx,old_e,name):
    
    trace = False

    new_e = new_cx.st.d.get(name)
    if not new_e:
        # Not an error: name is not defined in new_cx.
        return

    assert old_e
    if old_e == new_e:
        return
        
    if trace and old_e.defs_list:
        g.trace('*****',old_e.defs_list)
        
    if trace:
        g.trace('%22s old_cx: %20s new_cx: %20s' % (name,old_cx,new_cx))

    assert old_cx.st.d.get(name) == old_e
    assert not old_e.defined
    self.stats.n_relinked_names += 1

    # Change all the references to old_e to references to new_e.
    for node in old_e.refs_list:
        kind = self.kind(node)
        assert kind in ('Builtin','Import','ImportFrom','Name'),kind
        setattr(node,'e',new_e)
        self.stats.n_relinked_pointers += 1

    # Merge the reference_lists.
    new_e.refs_list.extend(old_e.refs_list)

    # Relocate the old symbol table entry.
    old_cx.st.d[name] = new_e
.. @+node:ekr.20140526082700.18210: *8* p1.bind_unbound_name
def bind_unbound_name(self,name,cx):
    
    '''Name has just been bound in context cx.
    
    Bind all matching unbound names in descendant contexts.'''
    
    # Important: this method has little or no effect on overall speed.
    
    # g.trace('*** %10s %s' % (name,cx))
    for cx2 in cx.contexts():
        if cx2 != cx:
            e2 = cx2.st.d.get(name)
            if e2 and not e2.defined:
                self.bind_name(cx,cx2,e2,name)
.. @+node:ekr.20140526082700.18211: *8* p1.def_args_helper
# arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def def_args_helper (self,cx,def_e,node):
    
    assert self.kind(node) == 'arguments'
    self.visit_list(node.args)
    self.visit_list(node.defaults)
    for field in ('vararg','kwarg'): # node.field is a string.
        name = getattr(node,field,None)
        if name:
            e = cx.st.define_name(name)
            self.stats.n_param_names += 1
.. @+node:ekr.20140526082700.18212: *8* p1.get_import_names
def get_import_names (self,node):

    '''Return a list of the the full file names in the import statement.'''

    result = []

    for ast2 in node.names:

        if self.kind(ast2) == 'alias':
            data = ast2.name,ast2.asname
            result.append(data)
        else:
            g.trace('unsupported kind in Import.names list',self.kind(ast2))

    # g.trace(result)
    return result
.. @+node:ekr.20140526082700.18213: *8* p1.resolve_import_name
def resolve_import_name (self,spec):

    '''Return the full path name corresponding to the import spec.'''

    trace = False ; verbose = False

    if not spec:
        if trace: g.trace('no spec')
        return ''
    
    ### This may not work for leading dots.
    aList,path,paths = spec.split('.'),None,None

    for name in aList:
        try:
            f,path,description = imp.find_module(name,paths)
            if not path: break
            paths = [path]
            if f: f.close()
        except ImportError:
            # Important: imports can fail due to Python version.
            # Thus, such errors are not necessarily searious.
            if trace: g.trace('failed: %s paths: %s cx: %s' % (
                name,paths,self.get_context()))
            path = None
            break
            
    if trace and verbose: g.trace(name,path)
            
    if not path:
        if trace: g.trace('no path')
        return ''

    if path.endswith('.pyd'):
        if trace: g.trace('pyd: %s' % path)
        return ''
    else:
        if trace: g.trace('path: %s' % path)
        return path
.. @+node:ekr.20140526082700.18214: *7* p1.visitors
.. @+node:ekr.20140526082700.18215: *8* p1.Assign
def do_Assign(self,node):
    
    cx = self.get_context()
    self.stats.n_assignments += 1
    self.visit_children(node)
    cx.assignments_list.append(node)
    cx.statements_list.append(node)
.. @+node:ekr.20140526082700.18216: *8* p1.Attribute
# Attribute(expr value, identifier attr, expr_context ctx)

def do_Attribute(self,node):

    cx = self.get_context()
    self.stats.n_attributes += 1
    old_attr,self.in_attr = self.in_attr,True
    ctx = self.kind(node.ctx)
    self.visit_children(node)
    self.in_attr = old_attr
    if not self.in_attr:
        base_node = self.attribute_base(node)
        assert base_node
        kind = self.kind(base_node)
        if kind in ('Builtin','Name'):
            base_name = base_node.id
            assert base_node and base_name
            e = cx.st.add_name(base_name)
            e.refs_list.append(base_node)
            ### e.add_chain(base,node) ### ?
        elif kind in ('Dict','List','Num','Str','Tuple',):
            pass
        elif kind in ('BinOp','UnaryOp'):
            pass
        else:
            assert False,kind
.. @+node:ekr.20140526082700.18217: *8* p1.AugAssign
def do_AugAssign(self,node):
    
    self.stats.n_assignments += 1
    cx = self.get_context()
    
    self.visit_children(node)
    cx.assignments_list.append(node)
    cx.statements_list.append(node)
        
.. @+node:ekr.20140526082700.18218: *8* p1.Call (Stats only)
# Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs)

def do_Call(self,node):
    
    cx = self.get_context()
    self.stats.n_calls += 1
    cx.calls_list.append(node)

    n = len(node.args or []) + int(bool(node.starargs)) + int(bool(node.kwargs))
    d = self.stats.actual_args_dict
    d[n] = 1 + d.get(n,0)

    self.visit_children(node)
.. @+node:ekr.20140526082700.18219: *8* p1.ClassDef
# ClassDef(identifier name, expr* bases, stmt* body, expr* decorator_list)

def do_ClassDef (self,node):

    '''Create a context for a class, and
    define the class name in the present context.'''
    
    old_cx = self.get_context()
    name = node.name
    
    # Generate code for the base classes.
    # g.trace([self.format(z) for z in node.bases]) # A list of ast.Name nodes.
    ### bases = self.visit_list(node.bases)
    new_cx = ClassContext(old_cx,name,node,node.bases)
    setattr(node,'new_cx',new_cx) # Bug fix: 2013/01/27

    # Generate code for the class members.
    self.push_context(new_cx)
    self.visit_list(node.body)
    self.pop_context()

    # Define the name in the old context.
    e = old_cx.st.define_name(name)
    e.node = node # 2012/12/25
    node.e = e # 2012/12/25
    # g.trace(e,node)
    e.self_context = new_cx
    old_cx.classes_list.append(new_cx)
    
    # Bind all unbound matching names in inner contexts.
    self.bind_unbound_name(name,new_cx)

.. @+node:ekr.20140526082700.18220: *8* p1.Expr
# Expr(expr value)

def do_Expr(self,node):
    
    cx = self.get_context()
    self.visit_children(node)
    self.stats.n_expressions += 1
    cx.expressions_list.append(node)
    cx.statements_list.append(node)
.. @+node:ekr.20140526082700.18221: *8* p1.For
def do_For(self,node):
    
    cx = self.get_context()
    self.stats.n_fors += 1
    self.visit_children(node)
    cx.statements_list.append(node)
    cx.assignments_list.append(node)
.. @+node:ekr.20140526082700.18222: *8* p1.FunctionDef
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)

def do_FunctionDef (self,node):
    
    # Stats
    args = node.args.args
    n = len(args) if args else 0
    d = self.stats.formal_args_dict
    d[n] = 1 + d.get(n,0)

    # Switch to the new context.
    old_cx = self.get_context()
    
    # Define the function/method name in the old context.
    name = node.name
    e = old_cx.st.define_name(name)

    # Create the new context: args are known in the new context.
    new_cx = DefContext(old_cx,name)
    setattr(node,'new_cx',new_cx) # Bug fix.
    setattr(node,'e',e) # Bug fix: 2012/12/28.
    new_cx.node = node
    e.self_context = new_cx
    
    # If this is a method, remember it:
    if old_cx and old_cx.class_context:
        # If this is the ctor, remember it.
        if name == '__init__':
            old_cx.class_context.ctor = new_cx
        # 2013/01/28: Add the method to the ivars dict.
        d = old_cx.class_context.ivars_dict
        if name in d:
            # Not quite a correct error, but something unusual is happening.
            self.error('%20s method hides ivar' % name)
        else:
            aList = d.get(name,[])
            aList.append(node)
            d [name] = aList

    # Define the function arguments before visiting the body.
    # These arguments, including 'self', are known in the body.
    self.push_context(new_cx)
    self.def_args_helper(new_cx,e,node.args)
    self.pop_context()
    
    new_cx.args = node.args # was set by def_args_helper.
    old_cx.defs_list.append(new_cx)

    # Evaluate the body in the new context.
    self.push_context(new_cx)
    self.visit_list(node.body)
    new_cx.node = e.node = node
    self.pop_context()
    
    # Bind all unbound matching names in inner contexts.
    self.bind_unbound_name(name,new_cx)
.. @+node:ekr.20140526082700.18223: *8* p1.Global
def do_Global(self,node):

    '''Enter the names in a 'global' statement into the *module* symbol table.'''

    cx = self.get_context()
    cx.statements_list.append(node)
    self.stats.n_globals += 1

    for name in node.names:
        
        # Create a symbol table entry for the name in the *module* context.
        module_e = cx.module_context.st.add_name(name)
        
        # This does *not* define the symbol!
        module_e.defined = False
        
        # Both Python 2 and 3 generate SyntaxWarnings when a name
        # is used before the corresponding global declarations.
        # We can make the same assumpution here:
        # give an *error* if an STE appears in this context for the name.
        # The error indicates that scope resolution will give the wrong result.
        e = cx.st.d.get(name)
        if e:
            self.u.error('name \'%s\' used prior to global declaration' % (name))
            # Add the name to the global_names set in *this* context.
            # cx.global_names.add(name)
            
        # Regardless of error, bind the name in *this* context,
        # using the STE from the module context.
        cx.st.d[name] = module_e
.. @+node:ekr.20140526082700.18224: *8* p1.Import
@ From Guido:

import x            -->  x = __import__('x')
import x as y       -->  y = __import__('x')
import x.y.z        -->  x = __import__('x.y.z')
import x.y.z as p   -->  p = __import__('x.y.z').y.z
@c

def do_Import(self,node):

    '''Add the imported file to u.files_list if needed
    and create a context for the file.'''

    trace = False
    cx = self.get_context()
    cx.statements_list.append(node)
    e_list,names = [],[]
    for fn,asname in self.get_import_names(node):
        fn2 = self.resolve_import_name(fn)
        # Important: do *not* analyze modules not in the files list.
        if fn2:
            mname = self.u.module_name(fn2)
            if g.shortFileName(fn2) in self.u.files_list: 
                if mname not in self.u.module_names:
                    self.u.module_names.append(mname)
            # if trace: g.trace('%s as %s' % (mname,asname))
            def_name = asname or mname
            names.append(def_name)
            e = cx.st.define_name(def_name) # sets e.defined.
            cx.imported_symbols_list.append(def_name)
            if trace: g.trace('define: (Import) %10s in %s' % (def_name,cx))
            e_list.append(e)

            # Add the constant type to the list of types for the *variable*.
            mod_cx = self.u.modules_dict.get(fn2) or LibraryModuleContext(self.u,fn2)
            e.types_cache[''] = mod_cx.module_type
            self.u.stats.n_imports += 1
        else:
            if trace: g.trace('can not resolve %s in %s' % (fn,cx))

    for e in e_list:
        e.defs_list.append(node)
        e.refs_list.append(node)
.. @+node:ekr.20140526082700.18225: *8* p1.ImportFrom
@ From Guido:
    
from p.q import x       -->  x = __import__('p.q', fromlist=['x']).x
from p.q import x as y  -->  y = __import__('p.q', fromlist=['x']).x
from ..x.y import z     -->  z = __import('x.y', level=2, fromlist=['z']).z

All these equivalences are still somewhat approximate; __import__
isn't looked up the way other variables are looked up (it is taken
from the current builtins), and if the getattr operation in the "from"
versions raises AttributeError that is translated into ImportError.

There's also a subtlety where "import x.y" implies that y must be a
submodule/subpackage of x, whereas in "from x import y" it may be
either a submodule/subpackage or a plain attribute (e.g. a class,
function or some other variable).
@c

def do_ImportFrom(self,node):

    '''Add the imported file to u.files_list if needed
    and add the imported symbols to the *present* context.'''

    trace = False ; dump = False
    if trace and dump:
        self.u.dump_ast(node)
        
    u = self.u
    cx = self.get_context()
    cx.statements_list.append(node)
    m = self.resolve_import_name(node.module)
    
    if m and m not in self.u.files_list:
        if trace: g.trace('adding module',m)
        self.u.files_list.append(m)

    e_list,names = [],[]
    for fn,asname in self.get_import_names(node):
        fn2 = asname or fn
        if fn2 == '*':
            if trace: g.trace('From x import * not ready yet')
            return
        names.append(fn2)
        e = cx.st.add_name(fn2)
        cx.imported_symbols_list.append(fn2)
        e_list.append(e)
        if trace: g.trace('define: (ImportFrom) %s' % (fn2))
        # Get the ModuleContext corresponding to fn2.
        mod_cx = self.u.modules_dict.get(fn2)
        ###
        ### if not mod_cx:
        ###    self.u.modules_dict[fn2] = mod_cx = ModuleContext(fn2)
        if mod_cx:
            # module_type is the singleton *constant* type of the module.
            module_type = mod_cx.module_type
            # Add the constant type to the list of types for the *variable*.
            e.defined = True # Indicate there is at least one definition.
            e.types_cache[''] = mod_cx.module_type
            mname = u.module_name(fn2)
            ### if mname not in self.u.module_names:
            ###    self.u.module_names.append(mname)
            u.stats.n_imports += 1

    for e in e_list:
        e.defs_list.append(node)
        e.refs_list.append(node)
.. @+node:ekr.20140526082700.18226: *8* p1.Interactive
def do_Interactive(self,node):
    
    assert False,'Interactive context not supported'
.. @+node:ekr.20140526082700.18227: *8* p1.Lambda
def do_Lambda (self,node):
    
    old_cx = self.get_context()

    # Synthesize a lambda name in the old context.
    # This name must not conflict with split names of the form name@n.
    old_cx.n_lambdas += 1
    name = 'Lambda@@%s' % old_cx.n_lambdas
    e = old_cx.st.define_name(name)

    # Define a namespace for the 'lambda' variables.
    new_cx = LambdaContext(self.u,old_cx,name)
    setattr(node,'new_cx',new_cx)
    setattr(node,'e',e) # Bug fix: 2012/12/28.
    new_cx.node = node
    
    self.push_context(new_cx)
    def_e = None
    args = self.def_args_helper(new_cx,def_e,node.args)
    body = self.visit(node.body)
    self.pop_context()
.. @+node:ekr.20140526082700.18228: *8* p1.ListComp
def do_ListComp(self,node):
    
    self.stats.n_list_comps += 1
    self.visit_children(node)

    cx = self.get_context()
    cx.assignments_list.append(node)
.. @+node:ekr.20140526082700.18229: *8* p1.Module
def do_Module (self,node):

    # Get the module context from the global dict if possible.
    
    # Bug fix: treat all <string> files as separate modules.
    new_cx = None if self.fn == '<string>' else self.u.modules_dict.get(self.fn)

    if not new_cx:
        new_cx = ModuleContext(self.u,self.fn,node)
        self.u.modules_dict[self.fn] = new_cx
        
    new_cx.node = node

    self.push_context(new_cx)
    self.visit_list(node.body)
    self.pop_context()
    
    # Bind all unbound matching names in inner contexts.
    for name in sorted(new_cx.st.d.keys()):
        self.bind_unbound_name(name,new_cx)
.. @+node:ekr.20140526082700.18230: *8* p1.Name
def do_Name(self,node):

    trace = False
    cx  = self.get_context()
    ctx = self.kind(node.ctx)
    name = node.id
    
    # Create the symbol table entry, even for builtins.
    e = cx.st.add_name(name)
    setattr(node,'e',e)
    setattr(node,'cx',cx)
    
    def_flag,ref_flag=False,False
    
    if ctx in ('AugLoad','AugStore','Load'):
        # Note: AugStore does *not* define the symbol.
        e.referenced = ref_flag = True
        self.stats.n_load_names += 1
    elif ctx == 'Store':
        # if name not in cx.global_names:
        e.defined = def_flag = True
        if trace: g.trace('Store: %s in %s' % (name,cx))
        self.stats.n_store_names += 1
    elif ctx == 'Param':
        if trace: g.trace('Param: %s in %s' % (name,cx))
        e.defined = def_flag = True
        self.stats.n_param_refs += 1
    else:
        assert ctx == 'Del',ctx
        e.referenced = ref_flag = True
        self.stats.n_del_names += 1

    if isPython3:
        if name in self.u.module_names:
            return None
    else:
        if name in dir(__builtin__) or name in self.u.module_names:
            return None

    if not self.in_attr:
        if def_flag: e.defs_list.append(node)
        if ref_flag: e.refs_list.append(node)
.. @+node:ekr.20140526082700.18231: *8* p1.Return
def do_Return(self,node):
    
    self.stats.n_returns += 1
    cx = self.get_context()
    if getattr(node,'value'):
        self.visit(node.value)
    cx.returns_list.append(node)
    cx.statements_list.append(node)
    # g.trace('%s %s' % (cx.name,self.format(node)))
.. @+node:ekr.20140526082700.18232: *9* p1.Operators...
# operator = Add | BitAnd | BitOr | BitXor | Div
# FloorDiv | LShift | Mod | Mult | Pow | RShift | Sub | 

def do_Add(self,node):       setattr(node,'op_name','+')
def do_BitAnd(self,node):    setattr(node,'op_name','&')
def do_BitOr(self,node):     setattr(node,'op_name','|')
def do_BitXor(self,node):    setattr(node,'op_name','^')
def do_Div(self,node):       setattr(node,'op_name','/')
def do_FloorDiv(self,node):  setattr(node,'op_name','//')
def do_LShift(self,node):    setattr(node,'op_name','<<')
def do_Mod(self,node):       setattr(node,'op_name','%')
def do_Mult(self,node):      setattr(node,'op_name','*')
def do_Pow(self,node):       setattr(node,'op_name','**')
def do_RShift(self,node):    setattr(node,'op_name','>>')
def do_Sub(self,node):       setattr(node,'op_name','-')

# boolop = And | Or
def do_And(self,node):       setattr(node,'op_name',' and ')
def do_Or(self,node):        setattr(node,'op_name',' or ')

# cmpop = Eq | Gt | GtE | In |
# Is | IsNot | Lt | LtE | NotEq | NotIn
def do_Eq(self,node):        setattr(node,'op_name','==')
def do_Gt(self,node):        setattr(node,'op_name','>')
def do_GtE(self,node):       setattr(node,'op_name','>=')
def do_In(self,node):        setattr(node,'op_name',' in ')
def do_Is(self,node):        setattr(node,'op_name',' is ')
def do_IsNot(self,node):     setattr(node,'op_name',' is not ')
def do_Lt(self,node):        setattr(node,'op_name','<')
def do_LtE(self,node):       setattr(node,'op_name','<=')
def do_NotEq(self,node):     setattr(node,'op_name','!=')
def do_NotIn(self,node):     setattr(node,'op_name',' not in ')

# unaryop = Invert | Not | UAdd | USub
def do_Invert(self,node):   setattr(node,'op_name','~')
def do_Not(self,node):      setattr(node,'op_name',' not ')
def do_UAdd(self,node):     setattr(node,'op_name','+')
def do_USub(self,node):     setattr(node,'op_name','-')
.. @+node:ekr.20140526082700.18233: *8* p1.With
def do_With(self,node):
    
    cx = self.get_context()
    self.stats.n_withs += 1
    self.visit_children(node)
    cx.statements_list.append(node)
.. @+node:ekr.20140526082700.18234: *6* class Resolver (keep for now)
class Resolver:
    
    '''A class controlling the resolution pattern matchers.'''

    @others
.. @+node:ekr.20140526082700.18235: *7*  r.ctor & helper
def __init__(self):
    
    self.app = app
    self.format = app.format
    self.sd = app.sd

    # g.trace('(Resolver)',g.callers())
    
    # Singleton type objects.
    # self.num_type = Num_Type()
    self.string_type = String_Type()

    # Data created in Pass 1...
    self.constants_list = []
        # List of all constant ops.
        
    # Data created just after scope resolution...
    self.self_list = []
        # List of all instances of self within methods.
    
    # The main lists for the main algorithm.
    self.known_symbols_list = []
        # The list of symbols whose types are definitely known.
        # The main algorithm pops symbols off this list.
    self.mushy_ops_list = []
        # Ops with mushy type sets. Debugging only?
    self.mushy_ste_list = []
        # The lists of symbols that would have mushy type sets.
        # The hard part of resolution deals with such symbols.
   
    self.calls_d = {}
        # Keys are contexts, values are list of calls in the context.
    self.defs_d = {} # The global defs dict.
        # Keys are names; values are sets of Contexts
    self.refs_d = {} # The global refs dict.
        # The global dictionary.
        # Keys are names.  Values are sets of contexts.

    # Class info dicts: keys and values are contexts.
    self.class_supers_d = {} # All superclasses.
    self.class_sub_d = {}  # All subclasses.
    self.class_relatives_d = {}
        # All super and subclasses, as well as other related classes.
        
    # Create the dispatch dict.
    self.dispatch_dict = self.make_dispatch_dict()
.. @+node:ekr.20140526082700.18236: *7*  r.generators
.. @+node:ekr.20140526082700.18237: *8* r.classes
def classes (self):
    
    '''A generator yielding all class contexts in all modules.'''
    
    r = self
    for cx in r.contexts():
        if cx.kind == 'class':
            yield cx
.. @+node:ekr.20140526082700.18238: *8* r.contexts
def contexts (self):
    
    '''A generator yielding all contexts in all modules.'''
    
    r = self
    for m in r.modules():
        for cx in m.contexts():
            yield cx
.. @+node:ekr.20140526082700.18239: *8* r.modules
def modules (self):
    
    d = self.sd.modules_dict
    for fn in sorted(d.keys()):
        m = d.get(fn)
        yield m
.. @+node:ekr.20140526082700.18240: *8* r.statements
def statements(self):
    
    '''A generator yielding all statements in all modules, in the proper order.'''

    r = self
    
    for cx in r.modules():
        for op in cx.statements():
            yield op
.. @+node:ekr.20140526082700.18241: *8* r.unresolved_names (TEST)
def unresolved_names(self):
    
    r = self
    for cx in r.contexts():
        for e in cx.st.d.values():
            if not e.resolved:
                yield e
.. @+node:ekr.20140526082700.18242: *7* r.resolve & initers
def resolve (self):
    
    trace_time = False
    r = self
    
    if trace_time: t1 = time.time()
    
    # Init & do scope resolution.
    r.make_global_dicts()
    
    if trace_time:
        t2 = time.time()
        g.trace('make dicts & resolve scopes: %2.2f sec' % (t2-t1))
    
    # Add 'self', module names and class names to list of known symbols.
    r.init_self()
    
    if trace_time:
        t3 = time.time()
        g.trace('init_self: %2.2f sec' % (t3-t2))
        
    r.init_module_names()
    
    if trace_time:
        t4 = time.time()
        g.trace('init_module_names: %2.2f sec' % (t4-t3))
        
    r.init_class_names()
    
    if trace_time:
        t5 = time.time()
        g.trace('init_class_names: %2.2f sec' % (t5-t4))
    
    r.known_symbols_list.extend(r.self_list)
    r.known_symbols_list.extend(r.constants_list)
    
    # Run the main algorithm.
    r.main_algorithm()
    
    r.resolve_aliases()
    r.resolve_class_relationships()
    r.analyze_classes()
    r.resolve_ivars()
    
    # The table of type-resolution methods.
    table = (
    )

    # Do the main, iterative, peepholes.
    progress = True
    while progress:
        progress = False
        for f in table:
            progress = progress or f()
            
    # Do the final peepholes.
    
    if trace_time:
        t6 = time.time()
        g.trace('main algorithm: %2.2f sec' % (t6-t5))
.. @+node:ekr.20140526082700.18243: *8* r.init_class_names
def init_class_names(self):
    
    '''Mark all refereces to class names as known.'''
    
    trace = False
    r = self
    format = self.format
    
    # Step 1: Create a dict whose keys are class names and whose values are lists of STE's.
    # Using a dict instead of a list speeds up the code by a factor of more than 300.
    # For all the files of Leo: 30 sec. for the old way and 0.08 sec. the new way.
    e_dict = {}
    for cx in r.classes():
        cx.class_type = Class_Type(cx) # Do this after scope resolution.
        parent = cx.parent_context
        if parent:
            d = parent.st.d
            e = d.get(cx.name)
            if e:
                key = e.name
                aList = e_dict.get(key,[])
                if e not in aList:
                    aList.append(e)
                        # Use a list to disambiguate classes with the same name.
                    e_dict[key] = aList

    # Step 2: Mark all Name ops refering to class names as knowns.
    for cx in r.contexts():
        d = cx.st.d
        for e in d.values():
            for op in e.refs_list:
                kind = op.__class__.__name__
                if kind == 'Builtin':
                    pass ### Not ready yet.
                elif kind == 'Name':
                    e = op.e
                    if e.name in e_dict:
                        aList = e_dict.get(e.name)
                        assert aList
                        if e in aList:
                            if trace: g.trace('known Name',e,op,op._parent,cx)
                            r.known_symbols_list.append(op)
                elif kind == 'Import':
                    aList = op.e_list
                    for e in aList:
                        if e.name in e_dict:
                            aList = e_dict.get(e.name)
                            assert aList
                            if e in aList:
                                if trace: g.trace('known Import',e,op,op._parent,cx)
                                r.known_symbols_list.append(op)
                elif kind == 'ImportFrom':
                    if trace: g.trace('ImportFrom not ready yet: %s' % (
                        format(op)))
                else:
                    assert False,'Unexpected Op: %s' % kind
.. @+node:ekr.20140526082700.18244: *8* r.init_module_names
def init_module_names(self):
    
    trace = False
    r,sd = self,self.sd
    format = self.format
    
    # Step 1: Create a dict whose keys are module names and whose values are lists of STE's.
    e_dict = {}
    for fn in sd.modules_dict:
        m = sd.modules_dict.get(fn)
        if trace: g.trace(m)
    # module_names = self.u.module_names
    # e_dict = {}
    # for cx in r.classes():
        # d = cx.st.d
        # e = d.get(cx.name)
        # if e:
            # key = e.name
            # aList = e_dict.get(key,[])
            # if e not in aList:
                # aList.append(e)
                    # # Use a list to disambiguate classes with the same name.
                # e_dict[key] = aList
                
    if trace: g.trace(e_dict)

    # Step 2: Mark all Name ops refering to class names as knowns.
    for cx in r.contexts():
        d = cx.st.d
        for e in d.values():
            for op in e.refs_list:
                kind = op.__class__.__name__
                if kind in ('Builtin','Name'):
                    e = op.e
                    if e and e.name in e_dict:
                        aList = e_dict.get(e.name)
                        assert aList
                        if e in aList:
                            if trace: g.trace('known',e,op,op._parent,cx)
                elif kind == 'Import':
                    aList = op.e_list
                    for e in aList:
                        if e.name in e_dict:
                            aList2 = e_dict.get(e.name)
                            assert aList2
                            if e in aList2:
                                if trace: g.trace('known',e,op,op._parent,cx)
                elif kind == 'ImportFrom':
                    if trace: g.trace('ImportFrom not ready yet: %s' % (
                        format(op)))
                else:
                    assert False,'Unexpected Op: %s' % kind
.. @+node:ekr.20140526082700.18245: *8* r.init_self
def init_self (self):
    
    '''Add all instances of "self" to r.self.list.'''

    r = self
    for class_ in r.classes():
        for def_ in class_.defs():
            e = def_.st.d.get('self')
            if e:
                if len(e.defs_list) > 1:
                    g.trace('*** redefining self',e.defs_list)
                else:
                    r.self_list.extend(e.refs_list)
.. @+node:ekr.20140526082700.18246: *8* r.main_algorithm
def main_algorithm(self):
    
    r = self
    
    # g.trace('known symbols: %s' % (len(r.known_symbols_list)))
    
    while r.known_symbols_list:
        op = r.known_symbols_list.pop()
        r.make_known(op)
.. @+node:ekr.20140526082700.18247: *8* r.make_global_dicts
def make_global_dicts (self):
    
    contexts = 0
    r = self
    r.refs_dict = {}
    for m in r.modules():
        for cx in m.contexts():
            contexts += 1
            d = cx.st.d # Keys are names, values are STEs.
            for e in d.values():
                aSet = r.refs_dict.get(e.name,set())
                if cx not in aSet:
                    aSet.add(cx)
                    r.refs_dict[e.name] = aSet
                    
    # r.defs_dict contains entries only for defined names.
    r.defs_dict = {}
    for name in r.refs_dict.keys():
        aSet = r.refs_dict.get(name)
        defs = [cx for cx in aSet if cx.st.d.get(name).defined]
        r.defs_dict[name] = defs

    # g.trace('contexts: %s' % (contexts))
.. @+node:ekr.20140526082700.18248: *8* r.make_known & op handlers
def make_known(self,op):
    
    '''This is called from the main_algorithm.
    op is an Op representing a name or constant with a single, known type.
    '''

    r = self
    # g.trace('known: %s parent: %s' % (op,op._parent))
    
    if 0:
        g.trace('%10s %9s %-8s %8s %s' % (
            op,id(op),
            op.__class__.__name__,
            op._parent and op._parent.__class__.__name__,op._parent))

    return ###
    # if op._parent:
        # f = r.dispatch_dict.get(op.parent.kind)
        # if f:
            # f(op.parent)
        # else:
            # g.trace('bad op.parent.kind: %s' % op.parent.kind)
            # g.trace(op)
            # assert False
.. @+node:ekr.20140526082700.18249: *9* Do-nothings (not used at present)
if 0:
    @others
.. @+node:ekr.20140526082700.18250: *10* r.Arg
def do_Arg (self,op):
    
    # arg = op.arg
    pass
.. @+node:ekr.20140526082700.18251: *10* r.Arguments
def do_Arguments (self,op):
    
    # args     = [self.visit(z) for z in op.args]
    # defaults = [self.visit(z) for z in op.defaults]
    pass
.. @+node:ekr.20140526082700.18252: *10* r.AugAssign
def do_AugAssign(self,op):
    
    # This does not define any value!
    pass
.. @+node:ekr.20140526082700.18253: *10* r.Keyword
def do_Keyword(self,op):
    
    # arg   = op.arg
    # value = op.value
    pass
.. @+node:ekr.20140526082700.18254: *9* Known types
.. @+node:ekr.20140526082700.18255: *10* r.Bytes
def do_Bytes(self,op):

    value = op.value
    # g.trace(value)
.. @+node:ekr.20140526082700.18256: *10* r.Dict
def do_Dict(self,op):

    keys   = op.keys
    values = op.values
    # g.trace(keys,values)
.. @+node:ekr.20140526082700.18257: *10* r.List
def do_List(self,op):

    elts = op.elements
    # g.trace(elts)
.. @+node:ekr.20140526082700.18258: *10* r.Num
def do_Num(self,op):
    
    n = op.n
    # g.trace(n)
.. @+node:ekr.20140526082700.18259: *10* r.Str
def do_Str(self,op):
    
    '''This represents a string constant.'''

    s = op.s
    # g.trace(s)
    
.. @+node:ekr.20140526082700.18260: *10* r.Tuple
def do_Tuple (self,op):
    
    elts = op.elements
    # g.trace(elts)
.. @+node:ekr.20140526082700.18261: *9* Names & Builtins
.. @+node:ekr.20140526082700.18262: *10* r.Builtin
def do_Builtin(self,op):
    
    name = op.name
    # g.trace(name)
.. @+node:ekr.20140526082700.18263: *10* r.Name
def do_Name(self,op):
    
    name = op.name
    # g.trace(name)
.. @+node:ekr.20140526082700.18264: *9* Not ready yet
.. @+node:ekr.20140526082700.18265: *10* r.Comprehension
def do_Comprehension(self,op):

    result = []
    
    name  = op.name
    iter_ = op.it
    ifs   = op.ifs
    # g.trace(name,iter_,ifs)
.. @+node:ekr.20140526082700.18266: *10* r.GenExp
def do_GenExp (self,op):
    
    elt  = op.elt
    gens = op.generators
    # g.trace(elt,gens)
.. @+node:ekr.20140526082700.18267: *10* r.Index
def do_Index(self,op):
    
    index = op.index
    # g.trace(index)
.. @+node:ekr.20140526082700.18268: *10* r.ListComp
def do_ListComp(self,op):

    elt  = op.elt
    gens = op.generators
    # g.trace(elt,gens)
.. @+node:ekr.20140526082700.18269: *10* r.Slice
def do_Slice(self,op):
    
    upper = op.upper
    lower = op.lower
    step  = op.step
    # g.trace(upper,lower,step)
.. @+node:ekr.20140526082700.18270: *10* r.Subscript
def do_Subscript(self,op):

    value  = op.value
    slice_ = op.slice_
    # g.trace(value,slice_)
.. @+node:ekr.20140526082700.18271: *9* Operators
.. @+node:ekr.20140526082700.18272: *10* r.Attribute
def do_Attribute (self,op):
    
    value = op.value
    attr  = op.attr
    # g.trace(attr,value)
.. @+node:ekr.20140526082700.18273: *10* r.BinOp
def do_BinOp(self,op):
    
    trace = True
    r = self
    name = op.op_name
    lt   = op.lt
    rt   = op.rt
    assert lt.parent == op
    assert rt.parent == op
    assert op.n_unknowns > 0
    op.n_unknowns -= 1
    if op.n_unknowns > 0: return
    
    ### Testing only.
    if not lt.typ or not rt.typ:
        # if trace: g.trace('missing typ: %s' % op)
        return ###

    assert lt.typ,op
    assert rt.typ,op
    
    if len(lt.typ) == 1 and len(rt.typ):
        lt_type,rt_type = lt.typ[0],rt.typ[0]
        if lt_type == rt_type:
            op.typ = [lt_type]
        # elif lt_type == r.string_type and rt_type == r.num_type:
            # op.typ = [r.string_type]
        else:
            #### Unusual case.
            op.typ.extend(lt.typ)
            op.typ.extend(rt.typ)
    else:
        # Mushy cases.
        op.typ.extend(lt.typ)
        op.typ.extend(rt.typ)
        op.typ = list(set(op.typ))

    if trace and len(op.typ) > 1:
        g.trace('ambiguous: %s%s%s %s' % (lt,name,rt,op.typ))
    
    assert op.typ,'empty op.typ'
    
    if len(op.typ) == 1:
        r.make_known(op)
    else:
        # if trace:
            # g.trace('lt',lt.typ)
            # g.trace('rt',rt.typ)
        r.mushy_ops_list.append(op)
.. @+node:ekr.20140526082700.18274: *10* r.BoolOp
def do_BoolOp(self,op):
    
    name   = op.op_name
    values = op.values
    # g.trace(name,values)
.. @+node:ekr.20140526082700.18275: *10* r.Call
def do_Call (self,op):
    
    pass

    # args     = op.args    
    # func     = op.func
    # keyargs  = op.keywords
    # starargs = op.starargs
    # star2args = op.starstarargs
    
    ### We have to know the type of the return value to do anything useful.
    # g.trace(op)
    
    
    
   
.. @+node:ekr.20140526082700.18276: *10* r.CompareOp
def do_CompareOp(self,op):

    left  = op.left
    ops   = op.ops
    comps = op.comparators
    # g.trace(left,ops,comps)
.. @+node:ekr.20140526082700.18277: *10* r.TernaryOp
def do_TernaryOp(self,op):

    test   = op.test
    body   = op.body
    orelse = op.orelse
    # g.trace(test,body,orelse)
.. @+node:ekr.20140526082700.18278: *10* r.UnaryOp
def do_UnaryOp(self,op):
    
    name    = op.op_name
    operand = op.operand
    # g.trace(name,operand)
.. @+node:ekr.20140526082700.18279: *9* r.Assign
def do_Assign(self,op):
    
    trace = False
    r = self
    target = op.target
    value  = op.value
    assert target.parent == op
    assert value.parent == op
    assert repr(op) == '%s=%s' % (target,value)

    if target.kind == 'Name':
        e = target.e
        defs = e.defs_list
        e.defs_seen += 1

        # Append the new types to e.typ.
        changed = False
        for z in value.typ:
            if z not in e.typ:
                e.typ.append(z)
                changed = True
        if not changed:
            if trace: g.trace('unchanged: %s %s' % (e,e.typ))
            return
                
        # The symbol's type is unambiguously known if
        # a) all defs have been seen and 
        # b) e.type_list has exactly one symbol.
        val = value.typ[0]
        if e.defs_seen == len(defs) and len(value.typ) == 1:
            if trace:
                g.trace('known: %s=%s refs: %s' % (
                    target,val,[z.parent for z in e.refs_list]))
            assert target not in r.known_symbols_list
            # Push all the references to the newly-known symbol.
            r.known_symbols_list.extend(e.refs_list)
            # Add the new value to all Ops in e.refs_list.
            for op in e.refs_list:
                op.typ.append(val)
        else:
            if trace: g.trace('add: %s=%s' % (target,value.typ[0]))
            # Add the new value to all Ops in e.refs_list.
            for op in e.refs_list:
                op.typ.append(val)

        if len(e.typ) > 1:
            if trace: g.trace('mushy: %s=%s' % (target,e.typ))
            if e not in r.mushy_ste_list:
                r.mushy_ste_list.append(e)
                    ### This could be expensive.
                    ### It would be better to make this a per-context list.
    else:
        # assert False,'Unexpected target kind: %s' % target.kind
        if trace: g.trace('unexpected target kind: %s %s' % (target.kind,target))
.. @+node:ekr.20140526082700.18280: *9* r.do_nothing
def do_nothing(self,op):
    pass
    
    # g.trace(op)
.. @+node:ekr.20140526082700.18281: *7* The hard part
.. @+node:ekr.20140526082700.18282: *8* r.analyze_assignments (to do)
def analyze_assignments (self):
    
    r = self
    if 0: ### Old unit test...
        for m in r.modules():
            result = []
            for cx in m.contexts():
                n = len(cx.parent_contexts())
                pad,pad2 = ' '*n,' '*(n+1)
                result.append('%s%s' % (pad,cx))
                if 0:
                    result2 = []
                    for z in cx.assignments_list:
                        result2.append('%s%s' % (
                            pad2,
                            self.format(z.op).strip()))
                    result.extend(sorted(list(set(result2))))
                if 1:
                    result2 = []
                    for z in cx.returns_list:
                        result2.append('%s%s' % (
                            pad2,
                            self.format(z).strip()))
                    result.extend(sorted(list(set(result2))))
.. @+node:ekr.20140526082700.18283: *8* r.analyze_calls (to do)
def analyze_calls (self):
    
    pass
.. @+node:ekr.20140526082700.18284: *8* r.analyze_returns (To do)
def analyze_returns(self):
    
    r = self
    result = []
    # g.trace()
    for m in r.modules():
        for cx in m.defs():
            # print(cx.name)
            result.append(cx.name)
            for a in sorted(set(cx.assignments_list)):
                # print(' %s' % (a))
                result.append(' %s' % (a))
    # g.trace('end')
    
    return '\n'.join(result)
            
.. @+node:ekr.20140526082700.18285: *8* r.resolve_class_relationships
def resolve_class_relationships (self):
    
    r = self
    
    # Class info dicts: keys and values are contexts.
    r.class_supers_d = {} # All superclasses.
    r.class_sub_d = {}  # All sukbclasses.
    r.class_relatives_d = {}
        # All super and subclasses, as well as other related classes.

    excluded_names = ('object',)
    r_d = r.class_relatives_d
    
    return #### Rewrite

    # for m in r.modules():
        # for cx in m.contexts():
            # if cx.kind == 'class' and cx.name not in excluded_names:
                # hash1 = cx.name
                # aSet = r_d.get(hash1,set())
                # for cx2 in cx.bases:
                    # hash2 = repr(cx2)
                    # aSet2 = r_d.get(hash2,set())
                    # aSet2.add(cx)
                    # aSet.add(cx2)
                    # r_d[hash2] = aSet2
                # r_d[hash1] = aSet
.. @+node:ekr.20140526082700.18286: *8* r.analyze_classes & helpers
def analyze_classes(self,aList=None):
    
    trace = False
    r = self

    if aList:
        # Convert names to classes.
        aList = sorted([z for z in r.classes() if z.name in aList])
    else:
        aList = sorted([z for z in r.classes()])

    for cx1 in aList:
        if trace:
            print('%20s %s' % (cx1.name,cx1.bases))
        # for cx2 in aList:
            # r.analyze_class_pair(aList,cx1,cx2)
    
    # for cx in sorted(aList):
        # g.trace(cx.name)

    # g.trace(len(aList))
    
    return aList
.. @+node:ekr.20140526082700.18287: *9* r.analyze_class_pair
def analyze_class_pair(self,aLisst,cx1,cx2):
    
    r = self
    if cx1 == cx2:
        return
        
    print('  %s: %s' % (cx2.name,cx2.bases))
    # print('    subclass: %s' % (cx2.name in cx1.bases))
    
.. @+node:ekr.20140526082700.18288: *8* r.resolve_ivars
def resolve_ivars (self):
    
    r = self
    
    if 0: ###
    
        constants = ('Dict','Int','List','Num','Str','Tuple',)

        g.trace()
    
        trace = True
        
        for m in self.modules():
            g.trace(m)
            for class_ in m.classes():
                for def_ in class_.defs():
                    for op in def_.assignments_to('self'):
                        target = op.target
                        value  = op.value
                        kind = op.__class__.__name__
                        if trace:
                            g.trace(op)
                            g.trace(self.format(op))
                            
                        val = PatternFormatter().visit(value) ### g_pattern_formatter.visit(value)
                        if val in constants:
                            if trace: g.trace('found constant type: %s' % val)
                            if kind == 'Assign':
                                print('%s=%s\n' % (target,val))
                                    # To do: add constant type for the ste for target.
                            else:
                                assert kind=='AugAssign',kind
                                print('%s=%s\n' % (target,val))
.. @+node:ekr.20140526082700.18289: *8* r.resolve_aliases (will be removed)
def resolve_aliases (self):
    
    r = self
.. @+node:ekr.20140526082700.17394: *6* class TypeInferrer (AstFullTraverser)
class TypeInferrer (AstFullTraverser):
    
    '''A class to infer the types of objects.'''
    
    def __init__ (self):
        AstFullTraverser.__init__(self)

    def __call__(self,node):
        return self.run(node)
    
    @others
.. @+node:ekr.20140526082700.17395: *7* ti.clean (*revise*)
def clean (self,aList):
    
    '''Return sorted(aList) with all duplicates removed.'''
    
    if 1:
        return aList or []
    else:
        ti = self
        if 1:
            # Good for debugging and traces.
            result = []
            for z in aList:
                if z not in result:
                    result.append(z)
            
            # An excellent check.
            assert len(result) == len(list(set(aList))),aList
        else:
            result = list(set(aList))
       
        # Strip out inference errors if there are real results.
        result2 = ti.ignore_failures(result)
        if result2:
            ti.stats.n_clean_success += 1
            return sorted(result2)
        else:
            ti.stats.n_clean_fail += 1
            return sorted(result)
.. @+node:ekr.20140528102444.17989: *7* ti.has_children
def has_children(self,node):
    
    assert isinstance(node,ast.AST),node.__class__.__name__
    
    return any(self.get_child_nodes(node))
.. @+node:ekr.20140526082700.17396: *7* ti.format
def format(self,node):
    
    u = self.u
    return '%s%s' % (
        ' '*u.compute_node_level(node),
        u.first_line(u.format(node)))
.. @+node:ekr.20140526082700.17397: *7* ti.init
def init(self):

    self.stats = Stats()
    self.u = Utils()
    
    # Local stats
    self.n_nodes = 0
    
    # Detecting circular inferences
    self.call_stack = [] # Detects recursive calls
    self.assign_stack = [] # Detects circular assignments.

    # Create singleton instances of simple types.
    self.bool_type = Bool_Type()
    self.builtin_type = Builtin_Type()
    self.bytes_type = Bytes_Type()
    self.float_type = Float_Type()
    self.int_type = Int_Type()
    self.none_type = None_Type()
    self.string_type = String_Type()

    # Create the builtin type dict.
    self.builtin_type_dict = {
        'eval': [self.none_type],
        'id':   [self.int_type],
        'len':  [self.int_type],
        'ord':  [self.int_type],
        # list,tuple...
        # close,open,sort,sorted,super...
    }
.. @+node:ekr.20140526082700.17398: *7* ti.run (entry point)
def run (self,root):
    
    self.init()
    self.visit(root)
.. @+node:ekr.20140526082700.17399: *7* ti.type helpers
def has_failed(self,t1,t2=[],t3=[]):
    
    return any([isinstance(z,Inference_Failure) for z in t1+t2+t3])
    
def is_circular(self,t1,t2=[],t3=[]):
    
    return any([isinstance(z,Circular_Assignment) for z in t1+t2+t3])
    
def is_recursive(self,t1,t2=[],t3=[]):
    
    return any([isinstance(z,Recursive_Inference) for z in t1+t2+t3])
    
def ignore_failures(self,t1,t2=[],t3=[]):
    
    return [z for z in t1+t2+t3 if not isinstance(z,Inference_Failure)]
    
def ignore_unknowns(self,t1,t2=[],t3=[]):
    
    return [z for z in t1+t2+t3 if not isinstance(z,(Unknown_Type,Unknown_Arg_Type))]
    
def merge_failures(self,t1,t2=[],t3=[]):

    aList = [z for z in t1+t2+t3 if isinstance(z,Inference_Failure)]
    if len(aList) > 1:
        # Prefer the most specific reason for failure.
        aList = [z for z in aList if not isinstance(z,Unknown_Type)]
    return aList
.. @+node:ekr.20140526082700.17400: *7* ti.visit
def visit(self,node):

    '''Visit a single node.  Callers are responsible for visiting children.'''

    # This assert is redundant.
    # assert isinstance(node,ast.AST),node.__class__.__name__
    method = getattr(self,'do_' + node.__class__.__name__)
    self.n_nodes += 1
    return method(node)
.. @+node:ekr.20140526082700.17401: *7* ti.visitors
.. @+node:ekr.20140526082700.17402: *8* ti.expressions
.. @+node:ekr.20140526082700.17403: *9* ti.Attribute & check_attr (check super classes for attributes)
# Attribute(expr value, identifier attr, expr_context ctx)

def do_Attribute (self,node):

    ti = self
    trace = False and not g.app.runningAllUnitTests
    
    # g.trace(ti.format(node),node.value,node.attr)
    t = ti.visit(node.value) or [] ###
    t = ti.clean(t)
    t = ti.merge_failures(t)
    tag = '%s.%s' % (t,node.attr) # node.attr is always a string.
    if t:
        if len(t) == 1:
            ti.stats.n_not_fuzzy += 1
            t1 = t[0]
            if ti.kind(t1) == 'Class_Type':
                aList = t1.cx.ivars_dict.get(node.attr)
                aList = ti.clean(aList) if aList else []
                if aList:
                    t = []
                    for node2 in aList:
                        t.extend(ti.visit(node2))
                    t = ti.clean(t)
                    ti.set_cache(node,t,tag='ti.Attribute')
                    ti.stats.n_attr_success += 1
                    if trace and trace_found:
                        g.trace('ivar found: %s -> %s' % (tag,t))
                elif t1.cx.bases:
                    if trace_errors: g.trace('bases',
                        ti.format(node),ti.format(t1.cx.bases))
                    ### Must check super classes.
                    t = [Unknown_Type(node)]
                else:
                    u.error('%20s has no %s member' % (ti.format(node),t1.cx.name))
                    t = [Unknown_Type(node)]
            else:
                ti.stats.n_attr_fail += 1
                if trace and trace_errors:
                    g.trace('fail',t,ti.format(node))
                t = [Unknown_Type(node)]
        else:
            ti.stats.n_fuzzy += 1
            if trace and trace_fuzzy: g.trace('fuzzy',t,ti.format(node))
    else:
        if trace and trace_errors: g.trace('fail',t,ti.format(node))
        t = [Unknown_Type(node)]
    # ti.check_attr(node) # Does nothing
    return t
.. @+node:ekr.20140526082700.17404: *10* ti.check_attr
def check_attr(self,node):
    
    ti = self
    trace = False and not g.app.runningAllUnitTests
    
    return ### Now done in ti.Attribute

    # assert ti.kind(node) == 'Attribute'
    # value = node.value
    # # node.attr is always a string.
    
    # if ti.kind(value) == 'Name':
        # # The ssa pass has computed the ivars dict.
        # # There is no need to examine value.ctx.
        # name = value.id
        # name_e = value.e
        # name_cx = name_e.cx
        # name_class_cx = name_cx.class_context
        # if name == 'self':
            # if name_class_cx:
                # if node.attr in name_class_cx.ivars_dict:
                    # if trace: g.trace('OK: %s.%s' % (
                        # name_class_cx.name,node.attr))
                # else:
                    # ti.error('%s has no %s member' % (
                        # name_class_cx.name,node.attr))
            # else:
                # ti.error('%s is not a method of any class' % (
                    # name)) ####
        # else:
            # ### To do: handle any id whose inferred type is a class or instance.
            # if trace:
                # g.trace('** not checked: %s' % (name))
                # g.trace(ti.u.dump_ast(value))
.. @+node:ekr.20140526082700.17405: *9* ti.BinOp & helper
def do_BinOp (self,node):

    ti = self
    trace = True and not g.app.runningAllUnitTests
    trace_infer = False ; trace_fail = False
    lt = ti.visit(node.left) or []
    rt = ti.visit(node.right) or []
    lt = ti.clean(lt)
    rt = ti.clean(rt)
    op_kind = ti.kind(node.op)
    num_types = ([ti.float_type],[ti.int_type])
    list_type = [List_Type(None)]
    if rt in num_types and lt in num_types:
        if rt == [ti.float_type] or lt == [ti.float_type]:
            t = [ti.float_type]
        else:
            t = [ti.int_type]
    elif rt == list_type and lt == list_type and op_kind == 'Add':
        t = list_type
    elif op_kind == 'Add' and rt == [ti.string_type] and lt == [ti.string_type]:
        t = [ti.string_type]
    elif op_kind == 'Mult' and rt == [ti.string_type] and lt == [ti.string_type]:
        g.trace('*** User error: string mult')
        t = [Unknown_Type(node)]
    elif op_kind == 'Mult' and (
        (lt==[ti.string_type] and rt==[ti.int_type]) or
        (lt==[ti.int_type] and rt==[ti.string_type])
    ):
        t = [ti.string_type]
    elif op_kind == 'Mod' and lt == [ti.string_type]:
        t = [ti.string_type] # (string % anything) is a string.
    else:
        ti.stats.n_binop_fail += 1
        if trace and trace_fail:
            if 1:
                s = '%r %s %r' % (lt,op_kind,rt)
                g.trace('  fail: %30s %s' % (s,ti.format(node)))
            else:
                g.trace('  fail:',lt,op_kind,rt,ti.format(node))
        t = [Inference_Error(node)] ### Should merge types!
    if trace and trace_infer: g.trace(ti.format(node),'->',t)
    return t
.. @+node:ekr.20140526082700.17406: *9* ti.BoolOp
def do_BoolOp(self,node):

    ti = self    
    return [ti.bool_type]
.. @+node:ekr.20140526082700.17407: *9* ti.Call & helpers
# Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs)
#   Note: node.starargs and node.kwargs are given only if assigned explicitly.

def do_Call (self,node):
    '''
    Infer the value of a function called with a particular set of arguments.
    '''
    ti = self
    trace = False and not g.app.runningAllUnitTests
    trace_builtins = True
    trace_errors = True ; trace_returns = False

    kind = ti.kind(node)
    func_name = ti.find_function_call(node)
    
    if trace: g.trace('1:entry:',func_name) # ,before='\n',
    
    # Special case builtins.
    t = ti.builtin_type_dict.get(func_name,[])
    if t:
        if trace and trace_builtins: g.trace(func_name,t)
        return t
        
    # Find the def or ctor to be evaluated.
    e = ti.find_call_e(node.func)
    if not (e and e.node):
        # find_call_e has given the warning.
        t = [Unknown_Type(node)]
        s = '%s(**no e**)' % (func_name)
        if trace and trace_errors: g.trace('%17s -> %s' % (s,t))
        return t

    # Special case classes.  More work is needed.
    if ti.kind(e.node) == 'ClassDef':
        # Return a type representing an instance of the class
        # whose ctor is evaluated in the present context.
        args,t = ti.class_instance(e)
        if trace and trace_returns:
            s = '%s(%s)' % (func_name,args)
            g.trace('%17s -> %s' % (s,t))
        return t

    # Infer the specific arguments and gather them in args list.
    # Each element of the args list may have multiple types.
    assert ti.kind(e.node) == 'FunctionDef'
    args = ti.infer_actual_args(e,node)
        
    # Infer the function for the cross-product the args list.
    # In the cross product, each argument has exactly one type.
    ti.stats.n_ti_calls += 1
    recursive_args,t = [],[]
    t2 = ti.infer_def(node,rescan_flag=False) ### specific_args,e,node,)
    if ti.is_recursive(t2):
        recursive_args.append(t2)
    t.extend(t2)

    if True and recursive_args:
        if trace: g.trace('===== rerunning inference =====',t)
        for t2 in recursive_args:
            t3 = ti.infer_def(node,rescan_flag=True) ### specific_args,e,node,rescan_flag=True)
            t.extend(t3)
        
    if ti.has_failed(t):
        t = ti.merge_failures(t)
        # t = ti.ignore_failures(t)
    else:
        t = ti.clean(t)
    if trace and trace_returns:
        s = '3:return %s(%s)' % (func_name,args)
        g.trace('%17s -> %s' % (s,t))
    return t
.. @+node:ekr.20140526082700.17408: *10* ti.class_instance
def class_instance (self,e):
    
    '''
    Return a type representing an instance of the class
    whose ctor is evaluated in the present context.
    '''
    
    ti = self
    trace = True and not g.app.runningAllUnitTests
    cx = e.self_context
    
    # Step 1: find the ctor if it exists.
    d = cx.st.d
    ctor = d.get('__init__')

    # node2 = node.value
    # name = node2.id
    # attr = node.attr
    # e = getattr(node2,'e',None)
    # if trace: g.trace(kind,v_kind,name,attr)
    # # g.trace('e',e)
    # t = ti.get_cache(e)
    # # g.trace('cache',t)
    # if len(t) == 1:
        # t = t[0]
        # e_value = t.node.e
        # # g.trace('* e_value',e_value)
        # # g.trace('e_value.self_context',e_value.self_context)
        # e = e_value.self_context.st.d.get(node.attr)
        # if trace: g.trace('** e_value.self_context.st.d.get(%s)' % (attr),e)
        # # g.trace('e_value.self_context.st.d', e_value.self_context.st.d)
        # # g.trace('e.node',e.node)
        
    args = [] ### To do
    t = [Class_Type(cx)]
    # ti.set_cache(e,t,tag='class name')
    return args,t
.. @+node:ekr.20140526082700.17409: *10* ti.find_call_e
def find_call_e (self,node):
    
    '''Find the symbol table entry for node, an ast.Call node.'''
    
    ti = self
    trace = False and not g.app.runningAllUnitTests
    trace_errors = False; trace_fuzzy = True ; trace_return = False
    kind = ti.kind(node)
    e = None # Default.
    if kind == 'Name':
        # if trace: g.trace(kind,node.id)
        e = getattr(node,'e',None)
    else:
        t = ti.visit(node) or []
        if len(t) == 1:
            ti.stats.n_not_fuzzy += 1
            t = t[0]
            if ti.kind(t) == 'Class_Type':
                d = t.cx.st.d
                if ti.kind(node) == 'Attribute':
                    name = node.attr
                elif ti.kind(node) == 'Call':
                    name = node.func
                else:
                    name = None
                if name:
                    e = d.get(name)
                else:
                    e = None
            else:
                if trace and trace_errors:
                    g.trace('not a class type: %s %s' % (ti.kind(t),ti.format(node)))
        elif len(t) > 1:
            if trace and trace_fuzzy: g.trace('fuzzy',t,ti.format(node))
            ti.stats.n_fuzzy += 1
            e = None
        
    # elif kind == 'Attribute':
        # v_kind = ti.kind(node.value)
        # if v_kind == 'Name':
            # node2 = node.value
            # name = node2.id
            # attr = node.attr
            # e = getattr(node2,'e',None)
            # # if trace: g.trace(kind,v_kind,name,attr)
            # t = ti.get_cache(e)
            # if len(t) == 1:
                # t = t[0]
                # if ti.kind(t) == 'Class_Type':
                    # d = t.cx.st.d
                    # e = d.get(node.attr)
                # else:
                    # pass ### To do
            # elif t:
                # pass
            # else:
                # t = [Unknown_Type(node)]
        # elif v_kind == 'Attribute':
            # node2 = node.value
            # g.trace('*****',kind,v_kind,ti.format(node.value))
            # e = ti.find_call_e(node2)
        # else:
            # g.trace('not ready yet',kind,v_kind)
            # e = None
    # elif kind in ('Call','Subscript'):
        # g.trace(kind)
        # e = None
    # else:
        # g.trace('===== oops:',kind)
        # e = None
        
    # if e:
        # assert isinstance(e,SymbolTableEntry),ti.kind(e)
        # ti.stats.n_find_call_e_success += 1
    # else:
        # # Can happen with methods,Lambda.
        # ti.stats.n_find_call_e_fail += 1
        # if trace and trace_errors: g.trace('**** no e!',kind,ti.format(node),
            # before='\n')

    # if e and not e.node:
        # if trace and trace_errors: g.trace(
            # 'undefined e: %s' % (e),before='\n')

    # if trace and trace_return: g.trace(
        # kind,'e:',e,ti.format(node))
    # return e
.. @+node:ekr.20140526082700.17410: *10* ti.infer_actual_args
# Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs)
#   keyword = (identifier arg, expr value) # keyword arguments supplied to call

# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
#   arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def infer_actual_args (self,e,node):
    
    '''Return a list of types for all actual args, in the order defined in
    by the entire formal argument list.'''
    
    ti = self
    trace = False and not g.app.runningAllUnitTests
    trace_args = False
    assert ti.kind(node)=='Call'
    cx = e.self_context
    # Formals...
    formals  = cx.node.args or []
    defaults = cx.node.args.defaults or [] # A list of expressions
    vararg   = cx.node.args.vararg
    kwarg    = cx.node.args.kwarg
    # Actuals...
    actuals  = node.args or [] # A list of expressions.
    keywords = node.keywords or [] # A list of (identifier,expression) pairs.
    starargs = node.starargs
    kwargs   = node.kwargs
    assert ti.kind(formals)=='arguments'
    assert ti.kind(formals.args)=='list'
    
    formal_names = [z.id for z in formals.args]
        # The names of *all* the formal arguments, include those with defauls.
        # Doesw not include vararg and kwarg.
       
    # Append unnamed actual args.
    # These could be either non-keyword arguments or keyword arguments.
    args = [ti.visit(z) for z in actuals]
    bound_names = formal_names[:len(actuals)]
    
    if trace and trace_args:
        g.trace('formal names',formal_names)
        g.trace('   arg names',bound_names)
        g.trace('    starargs',starargs and ti.format(starargs))
        g.trace('    keywargs',kwargs   and ti.format(kwargs))
        # formal_defaults = [ti.visit(z) for z in defaults]
            # # The types of each default.
        # g.trace('formal default types',formal_defaults)
        # g.trace('unnamed actuals',ti.format(actuals))
    
    # Add keyword args in the call, in the order they appear in the formal list.
    # These could be either non-keyword arguments or keyword arguments.
    keywargs_d = {}
    keywords_d = {}
    for keyword in keywords:
        name = keyword.arg
        t = ti.visit(keyword.value)
        value = ti.format(keyword.value)
        keywords_d[name] = (value,t)

    for name in formal_names[len(actuals):]:
        data = keywords_d.get(name)
        if data:
            value,t = data
            if trace and trace_args: g.trace('set keyword',name,value,t)
            args.append(t)
            bound_names.append(name)
        # else: keywargs_d[name] = None ### ???

    # Finally, add any defaults from the formal args.
    n_plain = len(formal_names) - len(defaults)
    defaults_dict = {}
    for i,expr in enumerate(defaults):
        name = formal_names[n_plain+i]
        value = ti.format(expr)
        t = ti.visit(expr)
        defaults_dict[name] = (value,t)

    for name in formal_names:
        if name not in bound_names:
            data = defaults_dict.get(name)
            t = None # default
            if data:
                value,t = data
                if trace and trace_args: g.trace('set default',name,value,t)
            elif name == 'self':
                def_cx = e.self_context
                class_cx = def_cx and def_cx.class_context
                if class_cx:
                    t = [Class_Type(class_cx)]
            if t is None:
                t = [Unknown_Arg_Type(node)]
                ti.error('Unbound actual argument: %s' % (name))
            args.append(t)
            bound_names.append(name)
            
    ### Why should this be true???
    # assert sorted(formal_names) == sorted(bound_names)

    if None in args:
        g.trace('***** opps node.args: %s, args: %s' % (node.args,args))
        args = [z for z in args if z is not None]
        
    if trace: g.trace('result',args)
    return args
.. @+node:ekr.20140526082700.17411: *10* ti.infer_def & helpers (sets call cache)
def infer_def(self,node,rescan_flag):
    
    '''Infer everything possible from a def D called with specific args:
    
    1. Bind the specific args to the formal parameters in D.
    2. Infer all assignments in D.
    3. Infer all outer expression in D.
    4. Infer all return statements in D.
    '''
    
    ti = self
    trace = False and not g.app.runningAllUnitTests
    return ###

    # t0 = ti.get_call_cache(e,hash_) or []
    # if hash_ in ti.call_stack and not rescan_flag:
        # # A recursive call: always add an Recursive_Instance marker.
        # if trace:g.trace('A recursive','rescan',rescan_flag,hash_,'->',t0)
        # ti.stats.n_recursive_calls += 1
        # t = [Recursive_Inference(node)]
    # else:
        # if trace: g.trace('A',hash_,'->',t0)
        # ti.call_stack.append(hash_)
        # try:
            # cx = e.self_context
            # # data = ti.switch_context(e,hash_,node)
            # ti.bind_args(specific_args,cx,e,node)
            # ti.infer_assignments(cx,e)
            # ti.infer_outer_expressions(cx,node)
            # t = ti.infer_return_statements(cx,e)
            # ti.restore_context(data)
        # finally:
            # hash2 = ti.call_stack.pop()
            # assert hash2 == hash_
    # # Merge the result and reset the cache.
    # t.extend(t0)
    # t = ti.clean(t)
    # if trace: g.trace('B',hash_,'->',t)
    # return t
.. @+node:ekr.20140526082700.17412: *11* ti.bind_args (ti.infer_def helper) (To do: handle self)
# Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs)
#   keyword = (identifier arg, expr value) # keyword arguments supplied to call

# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
#   arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def bind_args (self,types,cx,e,node):
    
    ti = self
    trace = False and not g.app.runningAllUnitTests
    assert ti.kind(node)=='Call'
    assert isinstance(node.args,list),node
    formals = cx.node.args or []
    assert ti.kind(formals)=='arguments'
    assert ti.kind(formals.args)=='list'
    formal_names = [z.id for z in formals.args]
        # The names of *all* the formal arguments, include those with defauls.
        
    if len(formal_names) != len(types):
        # g.trace('**** oops: formal_names: %s types: %s' % (formal_names,types))
        return

    def_cx = e.self_context
    d = def_cx.st.d
    for i,name in enumerate(formal_names):
        pass ### 
        ### Handle self here.
        # t = types[i]
        # e2 = d.get(name)
        # if e2:
            # if trace: g.trace(e2,t) # g.trace(e2.name,t)
            # ti.set_cache(e2,[t],tag='bindargs:%s'%(name))
        # else:
            # g.trace('**** oops: no e2',name,d)
.. @+node:ekr.20140526082700.17413: *11* ti.infer_assignments
def infer_assignments(self,cx,e):
    
    '''Infer all the assignments in the function context.'''

    ti = self
    trace = False and not g.app.runningAllUnitTests
    for a in cx.assignments_list:
        if ti.kind(a) == 'Assign': # ignore AugAssign.
            pass ####

            # t2 = ti.get_cache(a)
            # if t2:
                # ti.stats.n_assign_hits += 1
                # if trace: g.trace('hit!',t2)
            # else:
                # t2 = ti.visit(a)
                # t3 = ti.ignore_failures(t2)
                # if t3:
                    # ti.stats.n_assign_misses += 1
                    # # g.trace('***** set cache',t2)
                    # ti.set_cache(a,t2,tag='infer_assns')
                    # if trace: g.trace('miss',t2)
                # else:
                    # ti.stats.n_assign_fails += 1
                    # if trace: g.trace('fail',t2)
               
                   
    return None # This value is never used.
.. @+node:ekr.20140526082700.17414: *11* ti.infer_outer_expressions
def infer_outer_expressions(self,cx,node):
    
    '''Infer all outer expressions in the function context.'''

    ti = self
    trace = False and not g.app.runningAllUnitTests
    for exp in cx.expressions_list:
        if trace: g.trace(ti.format(exp))
        ti.stats.n_outer_expr_misses += 1
        t = ti.visit(exp)

    return None # This value is never used.
.. @+node:ekr.20140526082700.17415: *11* ti.infer_return_statements
def infer_return_statements(self,cx,e):
    
    '''Infer all return_statements in the function context.'''
    
    ti = self
    trace = False and not g.app.runningAllUnitTests
    t = []
    for r in cx.returns_list:
        t2 = ti.visit(r)
        if trace: g.trace('miss',t2)
        t.extend(t2)
    if ti.has_failed(t):
        t = ti.merge_failures(t)
    else:
        t = ti.clean(t)
    return t
.. @+node:ekr.20140526082700.17416: *9* ti.Compare
# Compare(expr left, cmpop* ops, expr* comparators)

def do_Compare(self,node):
    
    ti = self
    ti.visit(node.left)
    for z in node.comparators:
        ti.visit(z)
    return [ti.bool_type]
.. @+node:ekr.20140526082700.17417: *9* ti.comprehension
def do_comprehension(self,node):

    ti = self
    ti.visit(node.target) # A name.
    ti.visit(node.iter) # An attribute.
    return [List_Type(node)]
.. @+node:ekr.20140526082700.17418: *9* ti.Expr
# Expr(expr value)

def do_Expr(self,node):
    
    ti = self
    t = ti.visit(node.value)
    return t
.. @+node:ekr.20140526082700.17419: *9* ti.GeneratorExp
def do_GeneratorExp (self,node):

    ti = self
    trace = False and not g.app.runningAllUnitTests
    junk = ti.visit(node.elt)
    t = []
    for node2 in node.generators:
        t2 = ti.visit(node2)
        t.extend(t2)
    if ti.has_failed(t):
        t = ti.merge_failures(t)
        if trace: g.trace('failed inference',ti.format(node),t)
    else:
        t = ti.clean(t)
    return t
.. @+node:ekr.20140526082700.17420: *9* ti.IfExp
# The ternary operator
# IfExp(expr test, expr body, expr orelse)

def do_IfExp(self,node):
    
    ti = self    
    junk = ti.visit(node.test)
    t = ti.visit(node.body)
    t.extend(ti.visit(node.orelse))
    if ti.has_failed(t):
        t = ti.merge_failures(t)
    else:
        t = ti.clean(t)
    return t
.. @+node:ekr.20140526082700.17421: *9* ti.Index
def do_Index(self,node):

    ti = self    
    return ti.visit(node.value)
.. @+node:ekr.20140526082700.17422: *9* ti.Lambda
def do_Lambda (self,node):
    
    ti = self
    return ti.visit(node.body)
.. @+node:ekr.20140526082700.17423: *9* ti.ListComp
def do_ListComp(self,node):
    
    ti = self
    # g.trace(node.elt,node.generators)
    junk = ti.visit(node.elt)
    t = []
    for node2 in node.generators:
        t.extend(ti.visit(node2))
    if ti.has_failed(t):
        t = ti.merge_failures(t)
    else:
        t = ti.clean(t)
    return t
.. @+node:ekr.20140526082700.17424: *9* ti.Name (**rewrite)
def do_Name(self,node):
    
    ti = self ; u = ti.u
    trace = True and not g.app.runningAllUnitTests
    trace_infer = False ; trace_fail = False
    trace_self = False
    ctx_kind = ti.kind(node.ctx)
    name = node.id
    trace = trace and name == 'i'
    
    # # Reaching sets are useful only for Load attributes.
    # if ctx_kind not in ('Load','Param'):
        # # if trace: g.trace('skipping %s' % ctx_kind)
        # return []

    # ### ast.Name nodes for class base names have no 'e' attr.
    # if not hasattr(node,'e'):
        # if trace: g.trace('no e',node)
        # return []

    if name == 'self':
        # reach = getattr(node,'reach',[])
        # if reach: g.trace('**** assignment to self')
        cx = node.stc_context ### should be class context.
        if cx:
            if trace and trace_self: g.trace('found self',cx)
            t = [Class_Type(cx)]
        else:
            g.trace('**** oops: no class context for self',ti.format(node))
            t = [Unknown_Type(node)]
    else:
        reach = getattr(node,'reach',[])
        t = []
        for node2 in reach:
            # The reaching sets are the RHS of assignments.
            t = [Unknown_Type(node)]
            t2 = ti.visit(node2)
            if isinstance(t2,(list,tuple)):
                t.extend(t2)
            else:
                g.trace('**oops:',t2,ti.format(node2))
        if ti.has_failed(t):
            t = ti.merge_failures(t)
        else:
            t = ti.clean(t)

    if trace and trace_infer and t:
        g.trace('infer',t,u.format(node))
    if trace and trace_fail and not t:
        g.trace('fail ',name,ctx_kind,'reach:',
            ['%s:%s' % (id(z),u.format(z)) for z in reach])
    return t
.. @+node:ekr.20140526082700.17425: *9* ti.Slice
def do_Slice(self,node):
    
    ti = self
    if node.upper: junk = ti.visit(node.upper)
    if node.lower: junk = ti.visit(node.lower)
    if node.step:  junk = ti.visit(node.step)
    return [ti.int_type] ### ???
.. @+node:ekr.20140526082700.17426: *9* ti.Subscript (to do)
def do_Subscript(self,node):

    ti = self
    trace = False and not g.app.runningAllUnitTests
    t1 = ti.visit(node.value)
    t2 = ti.visit(node.slice)
    if t1 and trace: g.trace(t1,t2,ti.format(node))
    return t1 ### ?
.. @+node:ekr.20140526082700.17427: *9* ti.UnaryOp
def do_UnaryOp(self,node):
    
    ti = self
    trace = True and not g.app.runningAllUnitTests
    t = ti.visit(node.operand) or []
    t = ti.clean(t)
    op_kind = ti.kind(node.op)
    if op_kind == 'Not':
        t = [self.bool_type]
    elif t == [self.int_type] or t == [self.float_type]:
        pass # All operators are valid.
    else:
        ti.stats.n_unop_fail += 1
        if trace: g.trace(' fail:',op_kind,t,ti.format(node))
        t = [Unknown_Type(node)]
    return t
.. @+node:ekr.20140526082700.17428: *8* ti.primitive Types
.. @+node:ekr.20140526082700.17429: *9* ti.Builtin
def do_Builtin(self,node):

    ti = self
    return [ti.builtin_type]
.. @+node:ekr.20140526082700.17430: *9* ti.Bytes
def do_Bytes(self,node):

    ti = self
    return [ti.bytes_type]
.. @+node:ekr.20140526082700.17431: *9* ti.Dict
# Dict(expr* keys, expr* values)

def do_Dict(self,node):
    
    ti = self
    for z in node.keys:
        ti.visit(z)
    for z in node.values:
        ti.visit(z)
    return [Dict_Type(node)]
        ### More specific type.
.. @+node:ekr.20140526082700.17432: *9* ti.List
# List(expr* elts, expr_context ctx) 

def do_List(self,node):
    
    ti = self
    for z in node.elts:
        ti.visit(z)
    # ti.visit(node.ctx)
    return [List_Type(node)]
.. @+node:ekr.20140526082700.17433: *9* ti.Num
def do_Num(self,node):
    
    ti = self
    t_num = Num_Type(node.n.__class__)
    # g.trace(ti.format(node),'->',t_num)
    return [t_num]
.. @+node:ekr.20140526082700.17434: *9* ti.Str
def do_Str(self,node):
    
    '''This represents a string constant.'''

    ti = self
    return [ti.string_type]
.. @+node:ekr.20140526082700.17435: *9* ti.Tuple
# Tuple(expr* elts, expr_context ctx)

def do_Tuple(self,node):
    
    ti = self
    for z in node.elts:
        ti.visit(z)
    # ti.visit(node.ctx)
    return [Tuple_Type(node)]
.. @+node:ekr.20140526082700.17436: *8* ti.statements
.. @+node:ekr.20140526082700.17437: *9* ti.arguments
# arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def do_arguments (self,node):
    
    '''Bind formal arguments to actual arguments.'''
    
    assert False # All the work is done in ti.Call and its helpers.
.. @+node:ekr.20140526082700.17438: *9* ti.Assign (**rewrite)
def do_Assign(self,node):

    ti = self
    trace = False and not g.app.runningAllUnitTests
    t_val = ti.visit(node.value)
    t = []
    for z in node.targets:
        t.append(ti.visit(z))
    t = ti.clean(t)
    return t

    # if data in ti.assign_stack:
        # t = [Circular_Assignment(node)]
        # ti.stats.n_circular_assignments += 1
    # else:
        # ti.assign_stack.append(data)
        # try:
            # t = ti.visit(node.value)
            # if trace: g.trace(t)
        # finally:
            # data2 = ti.assign_stack.pop()
            # assert data == data2
        
    # for target in node.targets:
        # kind = ti.kind(target)
        # if kind == 'Name':
            # t0 = ti.get_cache(target.e) or []
            # t.extend(t0)
            # ti.set_cache(target.e,t,tag='Name:target.e')
            # if trace: g.trace('infer: %10s -> %s' % (
                # ti.format(target),t),before='\n')
        # else:
            # ### What to do about this?
            # if trace: g.trace('(ti) not a Name: %s' % (
                # ti.format(target)),before='\n')
                
    # # Update the cache immediately.
    # t0 = ti.get_cache(node) or []
    # t.extend(t0)
    # t = ti.clean(t)
    # ti.set_cache(node,t,tag='ti.Assign')
    # return t
.. @+node:ekr.20140526082700.17439: *9* ti.ClassDef (could be default)
def do_ClassDef(self,node):
    
    ti = self
    for z in node.body:
        self.visit(z)
.. @+node:ekr.20140526082700.17440: *9* ti.For
# For(expr target, expr iter, stmt* body, stmt* orelse)

def do_For (self,tree):

    ti = self
    ### what if target conflicts with an assignment??
    ti.visit(tree.target)
    ti.visit(tree.iter)
    for z in tree.body:
        ti.visit(z)
    for z in tree.orelse:
        ti.visit(z)
.. @+node:ekr.20140526082700.17441: *9* ti.FunctionDef & helpers (**rewrite)
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)

def do_FunctionDef (self,node):
    
    '''Infer this function or method with 'unknown' as the value of all args.
    This gets inference going.
    '''
    
    ti = self
    trace = False and not g.app.runningAllUnitTests
    ti.infer_outer_def(node)
    
    # # Set up function call, with 'unknown' for all args.
    # e = node.e
    # specific_args = [Unknown_Arg_Type(node)] * ti.count_full_args(node)
    # hash_ = ti.cache_hash(specific_args,e)
    # t = ti.get_call_cache(e,hash_)
    # if trace:
        # g.trace('%s %12s -> %s' % ('miss' if t is None else 'hit!',
            # node.name,specific_args))
    # if t is None:
        # t = ti.infer_outer_def(specific_args,hash_,node)
    # return t
.. @+node:ekr.20140526082700.17442: *10* ti.count_full_args
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
#   arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def count_full_args (self,node):
    
    '''Return the number of arguments in a call to the function/def defined
    by node, an ast.FunctionDef node.'''
    
    ti = self
    trace = False and not g.app.runningAllUnitTests
    assert ti.kind(node)=='FunctionDef'    
    args = node.args
    if trace: g.trace('args: %s vararg: %s kwarg: %s' % (
        [z.id for z in args.args],args.vararg,args.kwarg))
    n = len(args.args)
    if args.vararg: n += 1
    if args.kwarg:  n += 1
    return n
.. @+node:ekr.20140526082700.17443: *10* ti.infer_outer_def & helper
def infer_outer_def(self,node):
    
    '''Infer everything possible from a def D called with specific args:
    
    1. Bind the args to the formal parameters in D.
    2. Infer all assignments in D.
    3. Infer all outer expression in D.
    4. Infer all return statements in D.
    '''
    
    return []

    # ti = self
    # # trace = True and not g.app.runningAllUnitTests
    # assert ti.kind(node)=='FunctionDef',node
    # e = node.e
    # assert hasattr(e,'call_cache')
    # cx = e.self_context
    # ### data = ti.switch_context(e,hash_,node)
    # ti.bind_outer_args(node)
    # ti.infer_assignments(cx,e)
    # ti.infer_outer_expressions(cx,node)
    # t = ti.infer_return_statements(cx,e)
    # ### ti.set_call_cache(e,hash_,t,tag='infer_def')
    # ### ti.restore_context(data)
    # return t
.. @+node:ekr.20140526082700.17444: *11* ti_bind_outer_args (ti.infer_outer_def helper)
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
#   arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)
def bind_outer_args (self,node):
    
    '''Bind all all actual arguments except 'self' to "Unknown_Arg_Type".'''
    
    ti = self
    trace = False and not g.app.runningAllUnitTests
    assert ti.kind(node)=='FunctionDef'
    e = node.e
    def_cx = e.self_context
    args = node.args or []
    assert ti.kind(args)=='arguments',args
    assert ti.kind(args.args)=='list',args.args
    formal_names = [z.id if hasattr(z,'id') else '<tuple arg>' for z in args.args]
    if args.vararg: formal_names.append(args.vararg)
    if args.kwarg:  formal_names.append(args.kwarg)
    # if trace: g.trace(formal_names)
    d = def_cx.st.d
    for name in formal_names:
        if name == 'self':
            if def_cx:
                t = [Class_Type(def_cx)]
            else:
                t = [Unknown_Arg_Type(node)]
            e2 = e
        else:
            t = [Unknown_Arg_Type(node)]
            e2 = d.get(name)
        # if e2:
            # ti.set_cache(e2,t,tag='bind_outer_args:%s'%(name))
            # if trace: g.trace(name,t)
        # else:
            # if trace: g.trace('**** oops: no e2',name,d)
.. @+node:ekr.20140526082700.17445: *9* ti.Import (not used)
# def do_Import(self,node):
    
    # pass
.. @+node:ekr.20140526082700.17446: *9* ti.ImportFrom (not used)
# def do_ImportFrom(self,node):
    
    # pass
.. @+node:ekr.20140526082700.17447: *9* ti.Return & ti.Yield & helper
def do_Return(self,node):
    return self.return_helper(node)
    
def do_Yield(self,node):
    return self.return_helper(node)
.. @+node:ekr.20140526082700.17448: *10* ti.return_helper
def return_helper(self,node):

    ti = self
    trace = False and not g.app.runningAllUnitTests
    e = ti.call_e
    assert e
    if node.value:
        t = ti.visit(node.value)
        if ti.has_failed(t):
            ti.stats.n_return_fail += 1
            t = ti.ignore_unknowns(t)
        if t:
            ti.stats.n_return_success += 1
        else:
            ti.stats.n_return_fail += 1
            t = [] # Do **not** propagate a failure here!
    else:
        t = [ti.none_type]
    if trace: g.trace(t,ti.format(node))
    return t
.. @+node:ekr.20140526082700.17449: *9* ti.With
def do_With (self,node):

    ti = self
    t = []
    for z in node.body:
        t.append(ti.visit(z))
    t = ti.clean(t)
    return t
.. @+node:ekr.20140526082700.18325: *6* class TypeInferer (AstTraverser)
class TypeInferer (AstTraverser):
    
    '''
    This class infers the types of objects.
    
    See the documentation for complete details.
    '''
    
    @others
.. @+node:ekr.20140526082700.18326: *7*  ti.ctor
def __init__ (self,enable_trace=True):
    
    AstTraverser.__init__(self)
    
    u = Utils()
    self.cache_traverser = CacheTraverser()
    self.dump_ast = u.dump_ast
    self.format = u.format
    self.kind = None
    self.stats = u.stats
    
    # Detecting circular inferences
    self.call_stack = [] # Detects recursive calls
    self.assign_stack = [] # Detects circular assignments.

    # Create singleton instances of simple types.
    self.bool_type = Bool_Type()
    self.builtin_type = Builtin_Type()
    self.bytes_type = Bytes_Type()
    self.float_type = Float_Type()
    self.int_type = Int_Type()
    self.none_type = None_Type()
    self.string_type = String_Type()
    
    # Create the builtin type dict.
    self.builtin_type_dict = {
        'eval': [self.none_type],
        'id':   [self.int_type],
        'len':  [self.int_type],
        'ord':  [self.int_type],
        # list,tuple...
        # close,open,sort,sorted,super...
    }
    
    # Context info.
    self.null_hash = 'hash:none'
    self.call_args = None # The list of argument types for the present call.
    self.call_e = None
    self.call_hash = self.null_hash
        # The hash associated with self.call_args.
        # All hashes must start with 'hash:'

    # Debugging.
    self.align = 15
    self.enable_trace = enable_trace and u.enable_trace
    self.level = 0 # Node nesting level.
    self.n_caches = 0
    self.trace_level = 0 # Trace nesting level.
    self.trace_context = False
    self.trace_context_level = 0
.. @+node:ekr.20140526082700.18327: *7*  ti.run (entry point)
def run (self,node):
    
    # pylint: disable=W0221
        # Arguments number differs from overridden method.
    
    ti = self
    t1 = time.time()
    ti.check_visitor_names()
    ti.visit(node)
    ti.u.stats.n_caches += ti.n_caches
    t2 = time.time()
    return t2-t1
.. @+node:ekr.20140526082700.18328: *7* ti.caches
# Note: the hash_ argument to ti.get_call_cache can't easily be removed.
.. @+node:ekr.20140526082700.18329: *8* ti.cache_hash
def cache_hash(self,args,e):
    
    ''' Return a hash for a list of type arg. This must be a perfect hash:
    collisions must not be possible.
    
    ti.set_cache asserts hash.startswith('hash:') This ensures that hashes
    can't be confused wiht tracing tags.'''

    return 'hash:%s([%s])' % (
        '%s@%s' % (e.name,id(e)),
        ','.join([repr(arg) for arg in args]))
.. @+node:ekr.20140526082700.18330: *8* ti.get_cache
def get_cache(self,obj):
    
    '''Return the value of object's cache for the present context, creating
    the cache as needed.'''
    
    ti = self
    if not hasattr(obj,'cache'):
        obj.cache = {}
        ti.n_caches += 1
    return obj.cache.get(ti.call_hash,None)
        # None is the signal for a cache miss.
.. @+node:ekr.20140526082700.18331: *8* ti.get_call_cache
def get_call_cache(self,obj,hash_):
    
    '''Return the value of object's cache for the present context, creating
    the cache as needed.'''
    
    ti = self
    if not hasattr(obj,'call_cache'):
        obj.call_cache = {}
        ti.n_caches += 1

    return obj.call_cache.get(hash_)
.. @+node:ekr.20140526082700.18332: *8* ti.method_hash
def method_hash(self,e,node):
    
    '''If this is a method call, return the hash for the inferred ctor's
    arguments. Otherwise, return the empty string.'''
    
    ti = self
    trace = False and ti.enable_trace
    
    if ti.kind(e.self_context) == 'ClassContext':
        class_cx = e.self_context
        class_name = class_cx.name
        ctor = e.self_context.ctor
        if ctor:
            args = [ti.visit(z) for z in ctor.node.args.args]
            for specific_args in ti.cross_product(args):
                hash_ = ti.cache_hash(specific_args,e)
            return 'hash:class:%s:%s' % (class_name,hash_)
        else:
            if trace: ti.trace(class_name,'no ctor')
    return ''
.. @+node:ekr.20140526082700.18333: *8* ti.set_cache
def set_cache(self,obj,t,tag=''):

    '''Set the object's cache for the present context to the given type
    list t, creating the cache as needed.'''

    ti = self
    trace = False and ti.enable_trace
    assert isinstance(t,list)
    hash_ = ti.call_hash
    assert hash_.startswith('hash:'),hash_
        # Don't confuse the hash_ and tag_ keywords!
    assert isinstance(t,list)
    if not hasattr(obj,'cache'):
        obj.cache = {}
        ti.n_caches += 1
    
    obj.cache [hash_] = t
    if trace: ti.trace('%s -> %s' % (hash_,t))
        # ti.show_cache(obj,obj.cache,tag)
       
    # Old 
    # aList = obj.cache.get(hash_,[])
    # aList.extend(t)
    # aList = ti.clean(aList)
    #obj.cache [hash_] = aList
.. @+node:ekr.20140526082700.18334: *8* ti.set_call_cache
def set_call_cache(self,obj,hash_,t,tag=''):
    
    ti=self
    trace = False and ti.enable_trace
    if not hasattr(obj,'call_cache'):
        obj.call_cache = {}
        ti.n_caches += 1

    # Update e.call_cache, not e.cache!
    assert isinstance(t,list)
    obj.call_cache [hash_] = t
    
    if trace: ti.trace('%s:%s -> %s' % (obj,hash_,t))
 
    ### Old
    # aList = obj.call_cache.get(hash_,[])
    # aList.extend(t)
    # aList = ti.clean(aList)
    # obj.call_cache [hash_] = aList
.. @+node:ekr.20140526082700.18335: *8* ti.show_cache
def show_cache(self,obj,cache,tag):
    
    ti = self
    d = cache
    # kind = ti.kind(obj)
    pad = ' '*2*ti.level
    s = ti.format(obj) if isinstance(obj,ast.AST) else repr(obj)
    if len(s) > 40: s = s[:40]+'...'
    g.trace('%2s %s %s' % (ti.level,tag,s))
    # pad2 = pad + ' '*44
    for key in sorted(d.keys()):
        aList = d.get(key)
        for item in aList:
            print('   %s => %s' % (key,item))
    print('')
.. @+node:ekr.20140528102444.17991: *7* ti.has_children
def has_children(self,node):
    
    assert isinstance(node,ast.AST),node.__class__.__name__
    
    return any(self.get_child_nodes(node))
.. @+node:ekr.20140526082700.18336: *7* ti.helpers
.. @+node:ekr.20140526082700.18337: *8* ti.clean
def clean (self,aList):
    
    '''Return sorted(aList) with all duplicates removed.'''
    
    ti = self
    if 1:
        # Good for debugging and traces.
        result = []
        for z in aList:
            if z not in result:
                result.append(z)
        
        # An excellent check.
        assert len(result) == len(list(set(aList))),aList
    else:
        result = list(set(aList))
   
    # Strip out inference errors if there are real results.
    result2 = ti.ignore_failures(result)
    if result2:
        ti.stats.n_clean_success += 1
        return sorted(result2)
    else:
        ti.stats.n_clean_fail += 1
        return sorted(result)
.. @+node:ekr.20140526082700.18338: *8* ti.cross_product
def cross_product(self,aList):
    
    '''Return generator yielding a list of lists representing the
    cross product of all elements in aList, a list of lists. Examples:
        
    cross_product([['a']])               -> [['a']]
    cross_product([['a'],['b']])         -> [['a'],['b']]
    cross_product([['a'],['b','c']])     -> [['a','b'],['a','c']]
    cross_product([['a','b'],['c']])     -> [['a','c'],['b','c']]
    cross_product([['a','b'],['c','d']]) -> [['a','c'],['a','d'],['b','c'],['b','d']]
    '''
    
    ti = self
    trace = False and ti.enable_trace
    
    # Return a real list so we can do stats on it.
    result = [z for z in itertools.product(*aList)]
    
    if 0:
        g.trace(len(aList),aList)
        for z in result:
            print(z)
    
    if 1: # Stats and traces.
        ambig = len(result) > 1
        if trace and ambig: g.trace('\n',aList,'->',result)
        ti.stats.n_cross_products += 1
        n = len(result)
        d = ti.stats.cross_product_dict
        d[n] = 1 + d.get(n,0)

    return result
.. @+node:ekr.20140526082700.18339: *8* ti.switch/restore_context
# These are called *only* from ti.infer_def.
 
def switch_context(self,e,hash_,node):
    ti = self
    ti.trace_context = False and ti.enable_trace
    data = ti.call_args,ti.call_e,ti.call_hash
    ti.call_args = e.call_cache.get(hash_)
    ti.call_e = e
    ti.call_hash = hash_
    if ti.trace_context:
        ti.trace(ti.call_hash,before='\n'+' '*2*ti.trace_context_level)
    ti.trace_context_level += 1
    return data
    
def restore_context(self,data):
    ti = self
    ti.call_args,ti.call_e,ti.call_hash = data
    ti.trace_context_level -= 1
    if self.trace_context:
        ti.trace(ti.call_hash,before=' '*2*ti.trace_context_level)
.. @+node:ekr.20140526082700.18340: *8* ti.type helpers
def has_failed(self,t1,t2=[],t3=[]):
    
    return any([isinstance(z,Inference_Failure) for z in t1+t2+t3])
    
def is_circular(self,t1,t2=[],t3=[]):
    
    return any([isinstance(z,Circular_Assignment) for z in t1+t2+t3])
    
def is_recursive(self,t1,t2=[],t3=[]):
    
    return any([isinstance(z,Recursive_Inference) for z in t1+t2+t3])
    
def ignore_failures(self,t1,t2=[],t3=[]):
    
    return [z for z in t1+t2+t3 if not isinstance(z,Inference_Failure)]
    
def ignore_unknowns(self,t1,t2=[],t3=[]):
    
    return [z for z in t1+t2+t3 if not isinstance(z,(Unknown_Type,Unknown_Arg_Type))]
    
def merge_failures(self,t1,t2=[],t3=[]):

    aList = [z for z in t1+t2+t3 if isinstance(z,Inference_Failure)]
    if len(aList) > 1:
        # Prefer the most specific reason for failure.
        aList = [z for z in aList if not isinstance(z,Unknown_Type)]
    return aList
.. @+node:ekr.20140526082700.18341: *7* ti.trace
def trace(self,*args,**keys):
    
    ti = self

    if 1: # No indentation at all.
        level = 0
    elif 1: # Show tree level.
        level = ti.level
    else: # Minimize trace level.
        if ti.trace_level < ti.level:
            ti.trace_level += 1
        elif ti.trace_level > ti.level:
            ti.trace_level -= 1
        level = ti.trace_level
        
    if keys.get('before') is None:
        before = '.'*level
    else:
        before = keys.get('before')
  
    keys['align'] = ti.align
    keys['before'] = before
    keys['caller_level'] = 2
    g.trace(*args,**keys)
.. @+node:ekr.20140526082700.18342: *7* ti.traversers
.. @+node:ekr.20140526082700.18343: *8*  ti.visit
def visit(self,node):
    
    '''Infer the types of all nodes in a tree of AST nodes.'''

    ti = self
    assert isinstance(node,ast.AST),node.__class__.__name__
    method_name = 'do_' + node.__class__.__name__
    method = getattr(self,method_name,None)
    val = None
    try:
        ti.level += 1
        if method:
            # The method is responsible for traversing subtrees.
            # Furthermore, somebody uses the returned value.
            val = method(node)
        else:
            # Traverse subtrees automatically.
            # *Nobody* uses the returned value.
            for child in ti.get_child_nodes(node):
                ti.visit(child)
    
            # Returning None is a good test.
            val = None
    finally:
        ti.level -= 1
    return val
.. @+node:ekr.20140526082700.18344: *8*  ti.visit_children
def visit_children(self,node):
    
    ti = self
    assert isinstance(node,ast.AST),node.__class__.__name__
    
    for child in ti.get_child_nodes(node):
        ti.visit(child)

    # Returning None is a good test.
    return None
.. @+node:ekr.20140526082700.18345: *8*  ti.visit_list
def visit_list (self,aList):

    ti = self
    assert type(aList) in (list,tuple),aList
    
    for node in aList:
        ti.visit(node)
        
    # Returning None is a good test.
    return None
.. @+node:ekr.20140526082700.18346: *7* ti.visitors
.. @+node:ekr.20140526082700.18347: *8* ti.arguments
# arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def do_arguments (self,node):
    
    '''Bind formal arguments to actual arguments.'''
    
    assert False # All the work is done in ti.Call and its helpers.
.. @+node:ekr.20140526082700.18348: *8* ti.Assign (sets cache)
def do_Assign(self,node):

    ti = self
    trace = False and ti.enable_trace
    junk = ti.visit_list(node.targets)
    hash_ = ti.call_hash
    data = hash_,node
    if data in ti.assign_stack:
        t = [Circular_Assignment(hash_,node)]
        ti.stats.n_circular_assignments += 1
    else:
        ti.assign_stack.append(data)
        try:
            t = ti.visit(node.value)
            if trace: ti.trace(t)
        finally:
            data2 = ti.assign_stack.pop()
            assert data == data2
        
    for target in node.targets:
        kind = ti.kind(target)
        if kind == 'Name':
            t0 = ti.get_cache(target.e) or []
            t.extend(t0)
            ti.set_cache(target.e,t,tag='Name:target.e')
            if trace: ti.trace('infer: %10s -> %s' % (
                ti.format(target),t),before='\n')
        else:
            ### What to do about this?
            if trace: ti.trace('(ti) not a Name: %s' % (
                ti.format(target)),before='\n')
                
    # Update the cache immediately.
    t0 = ti.get_cache(node) or []
    t.extend(t0)
    t = ti.clean(t)
    ti.set_cache(node,t,tag='ti.Assign')
    return t
.. @+node:ekr.20140526082700.18349: *8* ti.Attribute & check_attr (check super classes for attributes)
# Attribute(expr value, identifier attr, expr_context ctx)

def do_Attribute (self,node):

    ti = self
    trace = False and ti.enable_trace
    trace_errors = True ; trace_found = False ; trace_fuzzy = True
    # print('do_Attribute',ti.format(node),node.value,node.attr)
    
    t = ti.get_cache(node)
    if t is not None:
        # g.trace('hit',t)
        return t

    #### ti.set_cache(node,[Unknown_Type(ti.call_hash,node)],tag='ti.Attribute')
    t = ti.visit(node.value)
    t = ti.clean(t) ###
    t = ti.merge_failures(t)
    tag = '%s.%s' % (t,node.attr) # node.attr is always a string.
    if t:
        if len(t) == 1:
            ti.stats.n_not_fuzzy += 1
            t1 = t[0]
            if ti.kind(t1) == 'Class_Type':
                aList = t1.cx.ivars_dict.get(node.attr)
                aList = ti.clean(aList) if aList else []
                if aList:
                    t = []
                    for node2 in aList:
                        t.extend(ti.visit(node2))
                    t = ti.clean(t)
                    ti.set_cache(node,t,tag='ti.Attribute')
                    ti.stats.n_attr_success += 1
                    if trace and trace_found:
                        g.trace('ivar found: %s -> %s' % (tag,t))
                        # [ti.format(z) for z in aList],t))
                elif t1.cx.bases:
                    if trace_errors: g.trace('bases',
                        ti.format(node),[ti.format(z) for z in t1.cx.bases])
                    pass ### Must check super classes.
                    t = [Unknown_Type(ti.call_hash,node)] ###
                else:
                    ti.error('%20s has no %s member' % (ti.format(node),t1.cx.name))
                    t = [Unknown_Type(ti.call_hash,node)] ###
            else:
                ti.stats.n_attr_fail += 1
                if trace and trace_errors:
                    g.trace('fail',t,ti.format(node))
                t = [Unknown_Type(ti.call_hash,node)] ###
        else:
            ti.stats.n_fuzzy += 1
            if trace and trace_fuzzy: g.trace('fuzzy',t,ti.format(node))
    else:
        if trace and trace_errors: g.trace('fail',t,ti.format(node))
        t = [Unknown_Type(ti.call_hash,node)]

    # ti.check_attr(node) # Does nothing
    return t
.. @+node:ekr.20140526082700.18350: *9* ti.check_attr
def check_attr(self,node):
    
    ti = self
    trace = False and ti.enable_trace
    
    return ### Now done in ti.Attribute

    # assert ti.kind(node) == 'Attribute'
    # value = node.value
    # # node.attr is always a string.
    
    # if ti.kind(value) == 'Name':
        # # The ssa pass has computed the ivars dict.
        # # There is no need to examine value.ctx.
        # name = value.id
        # name_e = value.e
        # name_cx = name_e.cx
        # name_class_cx = name_cx.class_context
        # if name == 'self':
            # if name_class_cx:
                # if node.attr in name_class_cx.ivars_dict:
                    # if trace: g.trace('OK: %s.%s' % (
                        # name_class_cx.name,node.attr))
                # else:
                    # ti.error('%s has no %s member' % (
                        # name_class_cx.name,node.attr))
            # else:
                # ti.error('%s is not a method of any class' % (
                    # name)) ####
        # else:
            # ### To do: handle any id whose inferred type is a class or instance.
            # if trace:
                # g.trace('** not checked: %s' % (name))
                # g.trace(ti.dump_ast(value))
.. @+node:ekr.20140526082700.18351: *8* ti.Builtin
def do_Builtin(self,node):
    
    assert False,node
.. @+node:ekr.20140526082700.18352: *8* ti.Call & helpers
# Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs)
#   Note: node.starargs and node.kwargs are given only if assigned explicitly.

def do_Call (self,node):
    '''
    Infer the value of a function called with a particular set of arguments.
    '''
    ti = self
    trace = False and ti.enable_trace
    trace_builtins = True ; trace_hit = False
    trace_errors = True ; trace_returns = False

    kind = ti.kind(node)
    func_name = ti.find_function_call(node)
    
    if trace and trace_hit: ti.trace('1:entry:',func_name) # ,before='\n',
    
    # Special case builtins.
    t = ti.builtin_type_dict.get(func_name,[])
    if t:
        if trace and trace_builtins: ti.trace(func_name,t)
        return t
        
    # Find the def or ctor to be evaluated.
    e = ti.find_call_e(node.func)
    if not (e and e.node):
        # find_call_e has given the warning.
        t = [Unknown_Type(ti.call_hash,node)]
        s = '%s(**no e**)' % (func_name)
        if trace and trace_errors: ti.trace('%17s -> %s' % (s,t))
        return t

    # Special case classes.  More work is needed.
    if ti.kind(e.node) == 'ClassDef':
        # Return a type representing an instance of the class
        # whose ctor is evaluated in the present context.
        args,t = ti.class_instance(e)
        if trace and trace_returns:
            s = '%s(%s)' % (func_name,args)
            ti.trace('%17s -> %s' % (s,t))
        return t

    # Infer the specific arguments and gather them in args list.
    # Each element of the args list may have multiple types.
    assert ti.kind(e.node) == 'FunctionDef'
    args = ti.infer_actual_args(e,node)
        
    # Infer the function for the cross-product the args list.
    # In the cross product, each argument has exactly one type.
    ti.stats.n_ti_calls += 1
    recursive_args,t = [],[]
    for specific_args in ti.cross_product(args):
        # Add the specific arguments to the cache.
        hash_ = ti.cache_hash(specific_args,e)
        t2 = ti.get_call_cache(e,hash_)
        miss = t2 is None   
        # if trace and trace_hit:
            # ti.trace('%s %12s -> %s' % ('miss' if miss else 'hit!',
                # func_name,specific_args))
        if miss:
            ti.stats.n_call_misses += 1
            if trace and trace_hit: ti.trace('2:miss',hash_)
            t2 = ti.infer_def(specific_args,e,hash_,node,rescan_flag=False)
            if ti.is_recursive(t2):
                data = hash_,specific_args,t2
                recursive_args.append(data)
            # if trace and trace_returns: ti.trace(hash_,'->',t2)
        else:
            if trace and trace_hit: ti.trace('2:hit!',hash_)
            ti.stats.n_call_hits += 1
        t.extend(t2)

    if True and recursive_args:
        if trace: ti.trace('===== rerunning inference =====',t)
        for data in recursive_args:
            # Merge the types into the cache.
            hash_,specific_args,t2 = data
            t3  = ti.get_call_cache(e,hash_) or []
            t4 = ti.ignore_failures(t,t2,t3)
            # g.trace('t3',t3)
            # g.trace('t4',t4)
            ti.set_call_cache(e,hash_,t4,tag='ti.call:recursive')
            t5 = ti.infer_def(specific_args,e,hash_,node,rescan_flag=True)
            if trace: g.trace('t5',t5)
            t.extend(t5)
        
    if ti.has_failed(t):
        t = ti.merge_failures(t)
        # t = ti.ignore_failures(t)
    else:
        t = ti.clean(t)
    if trace and trace_returns:
        s = '3:return %s(%s)' % (func_name,args)
        ti.trace('%17s -> %s' % (s,t))
    return t
.. @+node:ekr.20140526082700.18353: *9* ti.class_instance
def class_instance (self,e):
    
    '''
    Return a type representing an instance of the class
    whose ctor is evaluated in the present context.
    '''
    
    ti = self
    trace = True and ti.enable_trace
    cx = e.self_context
    
    # Step 1: find the ctor if it exists.
    d = cx.st.d
    ctor = d.get('__init__')

    # node2 = node.value
    # name = node2.id
    # attr = node.attr
    # e = getattr(node2,'e',None)
    # if trace: ti.trace(kind,v_kind,name,attr)
    # # ti.trace('e',e)
    # t = ti.get_cache(e)
    # # ti.trace('cache',t)
    # if len(t) == 1:
        # t = t[0]
        # e_value = t.node.e
        # # ti.trace('* e_value',e_value)
        # # ti.trace('e_value.self_context',e_value.self_context)
        # e = e_value.self_context.st.d.get(node.attr)
        # if trace: ti.trace('** e_value.self_context.st.d.get(%s)' % (attr),e)
        # # ti.trace('e_value.self_context.st.d', e_value.self_context.st.d)
        # # ti.trace('e.node',e.node)
        
    args = [] ### To do
    t = [Class_Type(cx)]
    ti.set_cache(e,t,tag='class name')
    return args,t
.. @+node:ekr.20140526082700.18354: *9* ti.find_call_e
def find_call_e (self,node):
    
    '''Find the symbol table entry for node, an ast.Call node.'''
    
    ti = self
    trace = False and ti.enable_trace
    trace_errors = False; trace_fuzzy = True ; trace_return = False
    kind = ti.kind(node)
    e = None # Default.
    if kind == 'Name':
        # if trace: ti.trace(kind,node.id)
        e = getattr(node,'e',None)
    else:
        t = ti.visit(node)
        if len(t) == 1:
            ti.stats.n_not_fuzzy += 1
            t = t[0]
            if ti.kind(t) == 'Class_Type':
                d = t.cx.st.d
                if ti.kind(node) == 'Attribute':
                    name = node.attr
                elif ti.kind(node) == 'Call':
                    name = node.func
                else:
                    name = None
                if name:
                    e = d.get(name)
                else:
                    e = None
            else:
                if trace and trace_errors:
                    ti.trace('not a class type: %s %s' % (ti.kind(t),ti.format(node)))
        elif len(t) > 1:
            if trace and trace_fuzzy: ti.trace('fuzzy',t,ti.format(node))
            ti.stats.n_fuzzy += 1
            e = None
        
    # elif kind == 'Attribute':
        # v_kind = ti.kind(node.value)
        # if v_kind == 'Name':
            # node2 = node.value
            # name = node2.id
            # attr = node.attr
            # e = getattr(node2,'e',None)
            # # if trace: ti.trace(kind,v_kind,name,attr)
            # t = ti.get_cache(e)
            # if len(t) == 1:
                # t = t[0]
                # if ti.kind(t) == 'Class_Type':
                    # d = t.cx.st.d
                    # e = d.get(node.attr)
                # else:
                    # pass ### To do
            # elif t:
                # pass
            # else:
                # t = [Unknown_Type(ti.call_hash,node)]
        # elif v_kind == 'Attribute':
            # node2 = node.value
            # ti.trace('*****',kind,v_kind,ti.format(node.value))
            # e = ti.find_call_e(node2)
        # else:
            # ti.trace('not ready yet',kind,v_kind)
            # e = None
    # elif kind in ('Call','Subscript'):
        # ti.trace(kind)
        # e = None
    # else:
        # ti.trace('===== oops:',kind)
        # e = None
        
    if e:
        assert isinstance(e,SymbolTableEntry),ti.kind(e)
        ti.stats.n_find_call_e_success += 1
    else:
        # Can happen with methods,Lambda.
        ti.stats.n_find_call_e_fail += 1
        if trace and trace_errors: ti.trace('**** no e!',kind,ti.format(node),
            align=ti.align,before='\n')

    if e and not e.node:
        if trace and trace_errors: ti.trace(
            'undefined e: %s' % (e),before='\n')

    if trace and trace_return: ti.trace(
        kind,'e:',e,ti.format(node))
    return e
.. @+node:ekr.20140526082700.18355: *9* ti.infer_actual_args
# Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs)
#   keyword = (identifier arg, expr value) # keyword arguments supplied to call

# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
#   arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def infer_actual_args (self,e,node):
    
    '''Return a list of types for all actual args, in the order defined in
    by the entire formal argument list.'''
    
    ti = self
    trace = False and ti.enable_trace
    trace_args = False
    assert ti.kind(node)=='Call'
    cx = e.self_context
    # Formals...
    formals  = cx.node.args or []
    defaults = cx.node.args.defaults or [] # A list of expressions
    vararg   = cx.node.args.vararg
    kwarg    = cx.node.args.kwarg
    # Actuals...
    actuals  = node.args or [] # A list of expressions.
    keywords = node.keywords or [] # A list of (identifier,expression) pairs.
    starargs = node.starargs
    kwargs   = node.kwargs
    assert ti.kind(formals)=='arguments'
    assert ti.kind(formals.args)=='list'
    
    formal_names = [z.id for z in formals.args]
        # The names of *all* the formal arguments, include those with defauls.
        # Doesw not include vararg and kwarg.
       
    # Append unnamed actual args.
    # These could be either non-keyword arguments or keyword arguments.
    args = [ti.visit(z) for z in actuals]
    bound_names = formal_names[:len(actuals)]
    
    if trace and trace_args:
        ti.trace('formal names',formal_names)
        ti.trace('   arg names',bound_names)
        ti.trace('    starargs',starargs and ti.format(starargs))
        ti.trace('    keywargs',kwargs   and ti.format(kwargs))
        # formal_defaults = [ti.visit(z) for z in defaults]
            # # The types of each default.
        # ti.trace('formal default types',formal_defaults)
        # ti.trace('unnamed actuals',[ti.format(z) for z in actuals])
    
    # Add keyword args in the call, in the order they appear in the formal list.
    # These could be either non-keyword arguments or keyword arguments.
    keywargs_d = {}
    keywords_d = {}
    for keyword in keywords:
        name = keyword.arg
        t = ti.visit(keyword.value)
        value = ti.format(keyword.value)
        keywords_d[name] = (value,t)

    for name in formal_names[len(actuals):]:
        data = keywords_d.get(name)
        if data:
            value,t = data
            if trace and trace_args: ti.trace('set keyword',name,value,t)
            args.append(t)
            bound_names.append(name)
        # else: keywargs_d[name] = None ### ???

    # Finally, add any defaults from the formal args.
    n_plain = len(formal_names) - len(defaults)
    defaults_dict = {}
    for i,expr in enumerate(defaults):
        name = formal_names[n_plain+i]
        value = ti.format(expr)
        t = ti.visit(expr)
        defaults_dict[name] = (value,t)

    for name in formal_names:
        if name not in bound_names:
            data = defaults_dict.get(name)
            t = None # default
            if data:
                value,t = data
                if trace and trace_args: ti.trace('set default',name,value,t)
            elif name == 'self':
                def_cx = e.self_context
                class_cx = def_cx and def_cx.class_context
                if class_cx:
                    t = [Class_Type(class_cx)]
            if t is None:
                t = [Unknown_Arg_Type(ti.call_hash,node)]
                ti.error('Unbound actual argument: %s' % (name))
            args.append(t)
            bound_names.append(name)
            
    ### Why should this be true???
    # assert sorted(formal_names) == sorted(bound_names)

    if None in args:
        ti.trace('***** opps node.args: %s, args: %s' % (node.args,args))
        args = [z for z in args if z is not None]
        
    if trace: ti.trace('result',args)
    return args
.. @+node:ekr.20140526082700.18356: *9* ti.infer_def & helpers (sets call cache)
def infer_def(self,specific_args,e,hash_,node,rescan_flag):
    
    '''Infer everything possible from a def D called with specific args:
    
    1. Bind the specific args to the formal parameters in D.
    2. Infer all assignments in D.
    3. Infer all outer expression in D.
    4. Infer all return statements in D.
    '''

    ti = self
    trace = False and ti.enable_trace
    t0 = ti.get_call_cache(e,hash_) or []
    if hash_ in ti.call_stack and not rescan_flag:
        # A recursive call: always add an Recursive_Instance marker.
        if trace:ti.trace('A recursive','rescan',rescan_flag,hash_,'->',t0)
        ti.stats.n_recursive_calls += 1
        t = [Recursive_Inference(hash_,node)]
    else:
        if trace: ti.trace('A',hash_,'->',t0)
        ti.call_stack.append(hash_)
        try:
            cx = e.self_context
            data = ti.switch_context(e,hash_,node)
            ti.bind_args(specific_args,cx,e,node)
            ti.infer_assignments(cx,e)
            ti.infer_outer_expressions(cx,node)
            t = ti.infer_return_statements(cx,e)
            ti.restore_context(data)
        finally:
            hash2 = ti.call_stack.pop()
            assert hash2 == hash_
    # Merge the result and reset the cache.
    t.extend(t0)
    t = ti.clean(t)
    ti.set_call_cache(e,hash_,t,tag='infer_def')
        # Important: does *not* use ti.call_hash.
    if trace: ti.trace('B',hash_,'->',t)
    return t
.. @+node:ekr.20140526082700.18357: *10* ti.bind_args (ti.infer_def helper) (To do: handle self)
# Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs)
#   keyword = (identifier arg, expr value) # keyword arguments supplied to call

# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
#   arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def bind_args (self,types,cx,e,node):
    
    ti = self
    trace = False and ti.enable_trace
    assert ti.kind(node)=='Call'
    assert isinstance(node.args,list),node
    formals = cx.node.args or []
    assert ti.kind(formals)=='arguments'
    assert ti.kind(formals.args)=='list'
    formal_names = [z.id for z in formals.args]
        # The names of *all* the formal arguments, include those with defauls.
        
    if len(formal_names) != len(types):
        # ti.trace('**** oops: formal_names: %s types: %s' % (formal_names,types))
        return

    def_cx = e.self_context
    d = def_cx.st.d
    for i,name in enumerate(formal_names):
        ### Handle self here.
        t = types[i]
        e2 = d.get(name)
        if e2:
            if trace: ti.trace(e2,t) # ti.trace(e2.name,t)
            ti.set_cache(e2,[t],tag='bindargs:%s'%(name))
        else:
            ti.trace('**** oops: no e2',name,d)
.. @+node:ekr.20140526082700.18358: *10* ti.infer_assignments
def infer_assignments(self,cx,e):
    
    '''Infer all the assignments in the function context.'''

    ti = self
    trace = False and ti.enable_trace
    for a in cx.assignments_list:
        if ti.kind(a) == 'Assign': # ignore AugAssign.
            t2 = ti.get_cache(a)
            if t2:
                ti.stats.n_assign_hits += 1
                if trace: ti.trace('hit!',t2)
            else:
                t2 = ti.visit(a)
                t3 = ti.ignore_failures(t2)
                if t3:
                    ti.stats.n_assign_misses += 1
                    # ti.trace('***** set cache',t2)
                    ti.set_cache(a,t2,tag='infer_assns')
                    if trace: ti.trace('miss',t2)
                else:
                    ti.stats.n_assign_fails += 1
                    if trace: ti.trace('fail',t2)
               
                   
    return None # This value is never used.
.. @+node:ekr.20140526082700.18359: *10* ti.infer_outer_expressions
def infer_outer_expressions(self,cx,node):
    
    '''Infer all outer expressions in the function context.'''

    ti = self
    trace = False and ti.enable_trace
    for exp in cx.expressions_list:
        if trace: ti.trace(ti.call_hash,ti.format(exp))
        t2 = ti.get_cache(exp)
        if t2 is not None:
            ti.stats.n_outer_expr_hits += 1
            if trace: ti.trace('hit!',t2)
        else:
            ti.stats.n_outer_expr_misses += 1
            # ti.trace('miss',ti.call_hash)
            # Set the cache *before* calling ti.visit to terminate the recursion.
            t = [Unknown_Type(ti.call_hash,node)]
            ti.set_cache(exp,t,tag='ti.infer_outer_expressions')
            t = ti.visit(exp)
            ti.set_cache(exp,t,tag='ti.infer_outer_expressions')
            if trace: ti.trace('miss',t)

    return None # This value is never used.
.. @+node:ekr.20140526082700.18360: *10* ti.infer_return_statements
def infer_return_statements(self,cx,e):
    
    '''Infer all return_statements in the function context.'''
    
    ti = self
    trace = True and ti.enable_trace
    trace_hit = False
    t = []
    for r in cx.returns_list:
        assert r
        t2 = ti.get_cache(r)
        if t2:
            if trace and trace_hit: ti.trace('hit!',t2)
        else:
            t2 = ti.visit(r)
            if trace and trace_hit: ti.trace('miss',t2)
            t.extend(t2)
    if ti.has_failed(t):
        t = ti.merge_failures(t)
    else:
        t = ti.clean(t)
    return t
.. @+node:ekr.20140526082700.18361: *8* ti.ClassDef
def do_ClassDef(self,node):
    
    '''
    For lint-like operation: infer all methods with 'unknown' as the value of all args.
    For jit-like operation: do nothing.
    '''
    
    ti = self
    if lint_like:
        return ti.visit_children(node)
    else:
        return [] # This value should not be used.
.. @+node:ekr.20140526082700.18362: *8* ti.Expr (new)
# Expr(expr value)

# This isn't really needed: the default visitor would work.

def do_Expr(self,node):
    
    ti = self
    t = ti.visit(node.value)
    return t
.. @+node:ekr.20140526082700.18363: *8* ti.FunctionDef & helpers
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)

def do_FunctionDef (self,node):
    
    '''Infer this function or method with 'unknown' as the value of all args.
    This gets inference going.
    '''
    
    ti = self
    trace = False and not ti.enable_trace
    
    # Set up function call, with 'unknown' for all args.
    e = node.e
    specific_args = [Unknown_Arg_Type(ti.call_hash,node)] * ti.count_full_args(node)
    hash_ = ti.cache_hash(specific_args,e)
    t = ti.get_call_cache(e,hash_)
    if trace:
        ti.trace('%s %12s -> %s' % ('miss' if t is None else 'hit!',
            node.name,specific_args))
    if t is None:
        t = ti.infer_outer_def(specific_args,hash_,node)
    return t

.. @+node:ekr.20140526082700.18364: *9* ti.count_full_args
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
#   arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def count_full_args (self,node):
    
    '''Return the number of arguments in a call to the function/def defined
    by node, an ast.FunctionDef node.'''
    
    ti = self
    trace = False and ti.enable_trace
    assert ti.kind(node)=='FunctionDef'    
    args = node.args
    if trace: ti.trace('args: %s vararg: %s kwarg: %s' % (
        [z.id for z in args.args],args.vararg,args.kwarg))
    n = len(args.args)
    if args.vararg: n += 1
    if args.kwarg:  n += 1
    return n
.. @+node:ekr.20140526082700.18365: *9* ti.infer_outer_def & helper
def infer_outer_def(self,specific_args,hash_,node):
    
    '''Infer everything possible from a def D called with specific args:
    
    1. Bind the args to the formal parameters in D.
    2. Infer all assignments in D.
    3. Infer all outer expression in D.
    4. Infer all return statements in D.
    '''

    ti = self
    # trace = True and ti.enable_trace
    assert ti.kind(node)=='FunctionDef',node
    e = node.e
    assert hasattr(e,'call_cache')
    cx = e.self_context
    data = ti.switch_context(e,hash_,node)
    ti.bind_outer_args(hash_,node)
    ti.infer_assignments(cx,e)
    ti.infer_outer_expressions(cx,node)
    t = ti.infer_return_statements(cx,e)
    ti.set_call_cache(e,hash_,t,tag='infer_def')
    ti.restore_context(data)
    return t
.. @+node:ekr.20140526082700.18366: *10* ti_bind_outer_args (ti.infer_outer_def helper)
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)
#   arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)
def bind_outer_args (self,hash_,node):
    
    '''Bind all all actual arguments except 'self' to "Unknown_Arg_Type".'''
    
    ti = self
    trace = False and ti.enable_trace
    assert ti.kind(node)=='FunctionDef'
    e = node.e
    def_cx = e.self_context
    args = node.args or []
    assert ti.kind(args)=='arguments',args
    assert ti.kind(args.args)=='list',args.args
    formal_names = [z.id if hasattr(z,'id') else '<tuple arg>' for z in args.args]
    if args.vararg: formal_names.append(args.vararg)
    if args.kwarg:  formal_names.append(args.kwarg)
    # if trace: ti.trace(formal_names)
    d = def_cx.st.d
    for name in formal_names:
        if name == 'self':
            if def_cx:
                t = [Class_Type(def_cx)]
            else:
                t = [Unknown_Arg_Type(ti.call_hash,node)]
            e2 = e
        else:
            t = [Unknown_Arg_Type(ti.call_hash,node)]
            e2 = d.get(name)
        if e2:
            ti.set_cache(e2,t,tag='bind_outer_args:%s'%(name))
            if trace: ti.trace(name,t)
        else:
            if trace: ti.trace('**** oops: no e2',name,d)
.. @+node:ekr.20140526082700.18367: *8* ti.Lambda
def do_Lambda (self,node):
    
    ti = self
    return ti.visit(node.body)
.. @+node:ekr.20140526082700.18368: *8* ti.operators
.. @+node:ekr.20140526082700.18369: *9* ti.BinOp & helper
def do_BinOp (self,node):

    ti = self
    trace = True and ti.enable_trace
    trace_infer = False ; trace_fail = True
    lt = ti.visit(node.left)
    rt = ti.visit(node.right)
    lt = ti.clean(lt)
    rt = ti.clean(rt)
    op_kind = ti.kind(node.op)
    num_types = ([ti.float_type],[ti.int_type])
    list_type = [List_Type(None)]
    if rt in num_types and lt in num_types:
        if rt == [ti.float_type] or lt == [ti.float_type]:
            t = [ti.float_type]
        else:
            t = [ti.int_type]
    elif rt == list_type and lt == list_type and op_kind == 'Add':
        t = list_type
    elif op_kind == 'Add' and rt == [ti.string_type] and lt == [ti.string_type]:
        t = [ti.string_type]
    elif op_kind == 'Mult' and rt == [ti.string_type] and lt == [ti.string_type]:
        ti.trace('*** User error: string mult')
        t = [Unknown_Type(ti.call_hash,node)]
    elif op_kind == 'Mult' and (
        (lt==[ti.string_type] and rt==[ti.int_type]) or
        (lt==[ti.int_type] and rt==[ti.string_type])
    ):
        t = [ti.string_type]
    elif op_kind == 'Mod' and lt == [ti.string_type]:
        t = [ti.string_type] # (string % anything) is a string.
    else:
        ti.stats.n_binop_fail += 1
        if trace and trace_fail:
            if 1:
                s = '%r %s %r' % (lt,op_kind,rt)
                g.trace('  fail: %30s %s' % (s,ti.format(node)))
            else:
                g.trace('  fail:',lt,op_kind,rt,ti.format(node))
        t = [Inference_Error(ti.call_hash,node)] ### Should merge types!
    if trace and trace_infer: ti.trace(ti.format(node),'->',t)
    return t
.. @+node:ekr.20140526082700.18370: *9* ti.BoolOp
def do_BoolOp(self,node):

    ti = self    
    junk = ti.visit_children(node)
    return [ti.bool_type]
.. @+node:ekr.20140526082700.18371: *9* ti.Compare
def do_Compare(self,node):

    ti = self    
    junk = ti.visit_children(node)
    return [ti.bool_type]
.. @+node:ekr.20140526082700.18372: *9* ti.comprehension
def do_comprehension(self,node):

    ti = self    
    junk = ti.visit_children(node)

    # name = node.name
    # ti.visit(node.it)

    # for node2 in node.ifs:
        # ti.visit(node2)

    return [List_Type(node)]
.. @+node:ekr.20140526082700.18373: *9* ti.Expr (not used)
# def do_Expr (self,node):

    # ti = self    
    # return ti.visit(node.value)
.. @+node:ekr.20140526082700.18374: *9* ti.GeneratorExp
def do_GeneratorExp (self,node):

    ti = self
    trace = False and ti.enable_trace
    junk = ti.visit(node.elt)
    t = []
    for node2 in node.generators:
        t2 = ti.visit(node2)
        t.extend(t2)
    if ti.has_failed(t):
        t = ti.merge_failures(t)
        if trace: ti.trace('failed inference',ti.format(node),t)
    else:
        t = ti.clean(t)
    return t
.. @+node:ekr.20140526082700.18375: *9* ti.IfExp (Ternary operator)
# IfExp(expr test, expr body, expr orelse)

def do_IfExp(self,node):
    
    ti = self    
    junk = ti.visit(node.test)
    t = ti.visit(node.body)
    t.extend(ti.visit(node.orelse))
    if ti.has_failed(t):
        t = ti.merge_failures(t)
    else:
        t = ti.clean(t)
    return t
.. @+node:ekr.20140526082700.18376: *9* ti.Index (default, at present)
def do_Index(self,node):

    ti = self    
    return ti.visit(node.value)
.. @+node:ekr.20140526082700.18377: *9* ti.ListComp
def do_ListComp(self,node):
    
    ti = self
    # ti.trace(node.elt,node.generators)
    junk = ti.visit(node.elt)
    t = []
    for node2 in node.generators:
        t.extend(ti.visit(node2))
    if ti.has_failed(t):
        t = ti.merge_failures(t)
    else:
        t = ti.clean(t)
    return t
.. @+node:ekr.20140526082700.18378: *9* ti.Slice
def do_Slice(self,node):
    
    ti = self
    if node.upper: junk = ti.visit(node.upper)
    if node.lower: junk = ti.visit(node.lower)
    if node.step:  junk = ti.visit(node.step)
    return [ti.int_type] ### ???
.. @+node:ekr.20140526082700.18379: *9* ti.Subscript (*** to do)
def do_Subscript(self,node):

    ti = self
    trace = False and not ti.enable_trace
    t1 = ti.visit(node.value)
    t2 = ti.visit(node.slice)
    if t1 and trace: g.trace(t1,t2,ti.format(node))
    return t1 ### ?
.. @+node:ekr.20140526082700.18380: *9* ti.UnaryOp
def do_UnaryOp(self,node):
    
    ti = self
    trace = True and ti.enable_trace
    t = ti.visit(node.operand)
    t = ti.clean(t)
    op_kind = ti.kind(node.op)
    if op_kind == 'Not':
        t == [self.bool_type]
    elif t == [self.int_type] or t == [self.float_type]:
        pass # All operators are valid.
    else:
        ti.stats.n_unop_fail += 1
        if trace: g.trace(' fail:',op_kind,t,ti.format(node))
        t = [Unknown_Type(ti.call_hash,node)]
    return t
.. @+node:ekr.20140526082700.18381: *8* ti.primitive Types
.. @+node:ekr.20140526082700.18382: *9* ti.Builtin
def do_Builtin(self,node):

    ti = self
    assert not ti.has_children(node)
    return [ti.builtin_type]

.. @+node:ekr.20140526082700.18383: *9* ti.Bytes
def do_Bytes(self,node):

    ti = self
    assert not ti.has_children(node)    
    return [ti.bytes_type]
.. @+node:ekr.20140526082700.18384: *9* ti.Dict
def do_Dict(self,node):

    ti = self
    junk = ti.visit_children(node)
    return [Dict_Type(node)]
        ### More specific type.
.. @+node:ekr.20140526082700.18385: *9* ti.List
def do_List(self,node): 
            
    ti = self
    junk = ti.visit_children(node)
    return [List_Type(node)]
.. @+node:ekr.20140526082700.18386: *9* ti.Num
def do_Num(self,node):
    
    ti = self
    assert not ti.has_children(node)
    t_num = Num_Type(node.n.__class__)
    # ti.trace(ti.format(node),'->',t_num)
    return [t_num]
.. @+node:ekr.20140526082700.18387: *9* ti.Str
def do_Str(self,node):
    
    '''This represents a string constant.'''

    ti = self
    assert not ti.has_children(node)
    return [ti.string_type]
.. @+node:ekr.20140526082700.18388: *9* ti.Tuple
def do_Tuple (self,node):

    ti = self
    junk = ti.visit_children(node)
    return [Tuple_Type(node)]
.. @+node:ekr.20140526082700.18389: *8* ti.statements
.. @+node:ekr.20140526082700.18390: *9* ti.For
def do_For(self,node):
    
    ### what if target conflicts with an assignment??
    
    ti = self
    # ti.visit(node.iter)
    # ti.visit_list(node.body)
    # if node.orelse:
        # ti.visit_list(node.orelse)
        
    return ti.visit_children(node)
.. @+node:ekr.20140526082700.18391: *9* ti.Import (not used)
# def do_Import(self,node):
    
    # pass
.. @+node:ekr.20140526082700.18392: *9* ti.ImportFrom (not used)
# def do_ImportFrom(self,node):
    
    # pass
.. @+node:ekr.20140526082700.18393: *9* ti.Return & ti.Yield & helper
def do_Return(self,node):
    ti = self
    return ti.return_helper(node)
    
def do_Yield(self,node):
    ti = self
    return ti.return_helper(node)
    
.. @+node:ekr.20140526082700.18394: *10* ti.return_helper (sets cache)
def return_helper(self,node):

    ti = self
    trace = False and ti.enable_trace
    trace_hash = False
    assert node
    e,hash_ = ti.call_e,ti.call_hash
    assert e
    assert hash_
    if node.value:
        t = ti.visit(node.value)
        if ti.has_failed(t):
            ti.stats.n_return_fail += 1
            t = ti.ignore_unknowns(t)
        if t:
            # Don't set the cache unless we succeed!
            ti.set_cache(node,t,tag=ti.format(node))
            ti.stats.n_return_success += 1
        else:
            ti.stats.n_return_fail += 1
            t = [] # Do **not** propagate a failure here!
    else:
        t = [ti.none_type]
    # Set the cache.
    t0 = ti.get_call_cache(e,hash_) or []
    t.extend(t0)
    ti.set_call_cache(e,hash_,t,tag='ti.return')
    if trace:
        if trace_hash: ti.trace(t,hash_,ti.format(node))
        else:          ti.trace(t,ti.format(node))
    return t
.. @+node:ekr.20140526082700.18395: *9* ti.With
def do_With (self,node):

    ti = self
    t = ti.visit_list(node.body)
    # ti.trace(t)
    return t
.. @+node:ekr.20140526082700.18396: *8* ti.Name (***ivars don't work)
def do_Name(self,node):
    
    ti = self
    trace = True and ti.enable_trace
    trace_hit = False ; trace_infer = False
    trace_fail = True ; trace_self = False
    ctx_kind = ti.kind(node.ctx)
    name = node.id
    trace = trace and name == 'i'
    hash_ = ti.call_hash
    
    # Reaching sets are useful only for Load attributes.
    if ctx_kind not in ('Load','Param'):
        # if trace: ti.trace('skipping %s' % ctx_kind)
        return []

    ### ast.Name nodes for class base names have no 'e' attr.
    if not hasattr(node,'e'):
        if trace: ti.trace('no e',node)
        return []

    t = ti.get_cache(node.e) or []
    t = ti.clean(t)
    t = ti.ignore_failures(t)
    if t:
        if trace and trace_hit: ti.trace('**hit!',t,name)
    elif name == 'self':
        e = node.e
        reach = getattr(e,'reach',[])
        if reach: ti.trace('**** assignment to self')
        cx = e.cx.class_context
        if cx:
            d = cx.ivars_dict
            if trace and trace_self: ti.trace('found self',e.name)
                # ti.u.dump_ivars_dict(d)) # Very expensive
            t = [Class_Type(cx)]
        else:
            ti.trace('**** oops: no class context for self',ti.format(node))
            t = [Unknown_Type(ti.call_hash,node)]
    else:
        reach = getattr(node.e,'reach',[])
        t = []
        for node2 in reach:
            # The reaching sets are the RHS of assignments.
            t2 = ti.get_cache(node2)
            if t2 is None:
                # Set the cache *before* calling ti.visit to terminate the recursion.
                t = [Unknown_Type(ti.call_hash,node)]
                ti.set_cache(node2,t,tag='ti.Name')
                t2 = ti.visit(node2)
                ti.set_cache(node2,t2,tag='ti.Name')
            if isinstance(t2,(list,tuple)):
                t.extend(t2)
            else:
                ti.trace('**oops:',t2,ti.format(node2))
        if ti.has_failed(t):
            t = ti.merge_failures(t)
        else:
            t = ti.clean(t)

    if trace and trace_infer and t:
        ti.trace('infer',t,ti.format(node))
    if trace and trace_fail and not t:
        ti.trace('fail ',name,ctx_kind,'reach:',
            ['%s:%s' % (id(z),ti.format(z)) for z in reach])
    return t
.. @+node:ekr.20140527123213.17049: *5*  Traverser classes
.. @+node:ekr.20140526082700.18007: *6*   class AstTraverser
class AstTraverser:
    
    '''
    The base class for all traversers.
    
    See the documentation for *important* information about this class.
    '''

    @others
.. @+node:ekr.20140526082700.18008: *7*  a.Birth
def __init__(self):

    self.context_stack = []
    self.level = 0 # The indentation level (not the context level).
        # The number of parents a node has.
    self.parents = [None]
.. @+node:ekr.20140526082700.18009: *7* a.traversers
.. @+node:ekr.20140526082700.18010: *8* a.find_function_call
# Used by leoInspect code.

def find_function_call (self,node):

    '''
    Return the static name of the function being called.
    
    tree is the tree.func part of the Call node.'''
    
    trace = True and self.enable_trace
    kind = self.kind(node)
    assert kind not in ('str','Builtin')
    if kind == 'Name':
        s = node.id
    elif kind == 'Attribute':
        s = node.attr # node.attr is always a string.
    elif kind == 'Call':
        s = self.find_function_call(node.func)
    elif kind == 'Subscript':
        s = None
    else:
        s = None
        if trace:
            # This is not an error.  Example:  (g())()
            s = '****unknown kind: %s****: %s' % (kind,Utils().format(node))
            g.trace(s)

    return s or '<no function name>'
.. @+node:ekr.20140526082700.18011: *8* a.get/push/pop_context
def get_context (self):

    return self.context_stack[-1]

def push_context (self,context):

    assert context
    self.context_stack.append(context)

def pop_context (self):

    self.context_stack.pop()
.. @+node:ekr.20140526082700.18012: *8* a.get_child_nodes
def get_child_nodes(self,node):

    assert isinstance(node,ast.AST),node.__class__.__name__

    if node._fields is not None:
        for name in node._fields:
            child = getattr(node, name)
            if isinstance(child, list):
                for node2 in child:
                    if isinstance(node2, ast.AST):
                        yield node2    
            elif isinstance(child, ast.AST):
                yield child
.. @+node:ekr.20140526082700.18013: *8* a.has_children
def has_children(self,node):
    
    assert isinstance(node,ast.AST),node.__class__.__name__
    
    return any(self.get_child_nodes(node))
.. @+node:ekr.20140526082700.18014: *8* a.run (default entry)
def run (self,s):

    t1 = time.time()
    node = ast.parse(s,filename=self.fn,mode='exec')
    self.visit(node)
    t2 = time.time()
    return t2-t1
.. @+node:ekr.20140526082700.18015: *8* a.visit
def visit(self,node):
    
    """Walk a tree of AST nodes."""

    assert isinstance(node,ast.AST),node.__class__.__name__

    method_name = 'do_' + node.__class__.__name__
    method = getattr(self,method_name,None)
    if method:
        # method is responsible for traversing subtrees.
        return method(node)
    else:
        # Traverse subtrees automatically, without calling visit_children.
        for child in self.get_child_nodes(node):
            self.visit(child)
.. @+node:ekr.20140526082700.18016: *8* a.visit_children
# def visit_children(self,node):
    
    # assert isinstance(node,ast.AST),node.__class__.__name__

    # for child in self.get_child_nodes(node):
        # self.visit(child)
.. @+node:ekr.20140526082700.18017: *8* a.visit_list
def visit_list (self,aList):
    
    assert isinstance(aList,(list,tuple))
    
    for z in aList:
        self.visit(z)
.. @+node:ekr.20140526082700.18018: *7* a.utils
.. @+node:ekr.20140526082700.18019: *8* a.attribute_base
def attribute_base(self,node):
    
    '''Return the node representing the base of the chain.
    Only 'Name' and 'Builtin' nodes represent names.
    All other chains have a base that is a constant or nameless dict, list, etc.
    '''

    trace = False
    kind = self.kind(node)
    if kind in ('Name','Builtin','Str'):
        result = node # We have found the base.
    elif kind in ('Attribute','Subscript'):
        if trace: g.trace('value: %s'% node.value)
        result = self.attribute_base(node.value)
    elif kind == 'Call':
        result = self.attribute_base(node.func)
    else:
        # The chain is rooted in a constant or nameless dict, list, etc.
        # This is not an error.
        # g.trace('*** kind: %s node: %s' % (kind,node))
        result = node
        
    if trace:
        u = Utils()
        g.trace(u.format(node),'->',u.format(result))
    return result
.. @+node:ekr.20140526082700.18020: *8* a.attribute_target (To be deleted)
def attribute_target(self,node):
    
    '''Return the node representing the target of the chain.
    Only 'Name' and 'Builtin' Ops represent names.'''
    
    trace = True
    kind = self.kind(node)
    if kind in ('Name','Builtin','Str'):
        result = node # We have found the target.
    elif kind == 'Attribute':
        # result = self.attribute_target(node.attr) ### Always a string.
        result = node # node.attr is the target.
    elif kind == 'Call':
        result = self.attribute_target(node.func)
    elif kind == 'Subscript':
        result = self.attribute_target(node.value)
    else:
        g.trace('can not happen',node.__class__.__name__,repr(node))
        # Don't call u.format here.
        return None
    
    if trace:
        u = Utils()
        g.trace(u.format(node),'->',u.format(result))
    return result
.. @+node:ekr.20140526082700.18021: *8* a.check_visitor_names
def check_visitor_names(self):
    
    '''Check that there is an ast.AST node named x
    for all visitor methods do_x.'''
    
    << ast abstract grammar >>
    << define names >>

    # Inexpensive, because there are few entries in aList.
    aList = [z for z in dir(self) if z.startswith('do_')]
    for s in sorted(aList):
        name = s[3:]
        if name not in names:
            g.trace('***** oops',self.__class__.__name__,name)
            assert False,name
                # This is useful now that most errors have been caught.
.. @+node:ekr.20140526082700.18022: *9* << ast abstract grammar >>
@nocolor-node
@
Python 3 only:
    arguments = (arg* args, identifier? vararg, expr? varargannotation,
                     arg* kwonlyargs, identifier? kwarg,
                     expr? kwargannotation, expr* defaults,
                     expr* kw_defaults)
    arg = (identifier arg, expr? annotation)
mod:
    Expression(expr body)
    Interactive(stmt* body)
    Module(stmt* body)
    Suite(stmt* body) #  not an actual node,
stmt:
    Assert(expr test, expr? msg)
    Assign(expr* targets, expr value)
    AugAssign(expr target, operator op, expr value)
    Break
    ClassDef(identifier name, expr* bases, stmt* body, expr* decorator_list)
    Continue
    Delete(expr* targets)
    Exec(expr body, expr? globals, expr? locals)
    Expr(expr value)
    For(expr target, expr iter, stmt* body, stmt* orelse)
    FunctionDef(identifier name, arguments args,stmt* body, expr* decorator_list)
    Global(identifier* names)
    If(expr test, stmt* body, stmt* orelse)
    Import(alias* names)
    ImportFrom(identifier? module, alias* names, int? level)
    Pass
    Print(expr? dest, expr* values, bool nl)
    Raise(expr? type, expr? inst, expr? tback)
    Return(expr? value)
    TryExcept(stmt* body, excepthandler* handlers, stmt* orelse)
    TryFinally(stmt* body, stmt* finalbody)
    While(expr test, stmt* body, stmt* orelse)
    With(expr context_expr, expr? optional_vars, stmt* body)
expr:
    Attribute(expr value, identifier attr, expr_context ctx)
    BinOp(expr left, operator op, expr right)
    BoolOp(boolop op, expr* values)
    Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs)
    Compare(expr left, cmpop* ops, expr* comparators)
    Dict(expr* keys, expr* values)
    DictComp(expr key, expr value, comprehension* generators)
    GeneratorExp(expr elt, comprehension* generators)
    IfExp(expr test, expr body, expr orelse)
    Lambda(arguments args, expr body)
    List(expr* elts, expr_context ctx) 
    ListComp(expr elt, comprehension* generators)
    Name(identifier id, expr_context ctx)
    Num(object n) -- a number as a PyObject.
    Repr(expr value)
    Set(expr* elts)
    SetComp(expr elt, comprehension* generators)
    Str(string s) -- need to specify raw, unicode, etc?
    Subscript(expr value, slice slice, expr_context ctx)
    Tuple(expr* elts, expr_context ctx)
    UnaryOp(unaryop op, expr operand)
    Yield(expr? value)
expr_context:
    AugLoad
    AugStore
    Del
    Load
    Param
    Store
slice:
    Ellipsis
    Slice(expr? lower, expr? upper, expr? step) 
    ExtSlice(slice* dims) 
    Index(expr value) 
boolop:
    And | Or 
operator:
    Add | Sub | Mult | Div | Mod | Pow | LShift | RShift | BitOr | BitXor | BitAnd | FloorDiv
unaryop:
    Invert | Not | UAdd | USub
cmpop:
    Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn
excepthandler:
    ExceptHandler(expr? type, expr? name, stmt* body)
    
Lower case node names:
    alias (identifier name, identifier? asname)
    arguments (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)
    comprehension (expr target, expr iter, expr* ifs)
    keyword (identifier arg, expr value)
.. @+node:ekr.20140526082700.18023: *9* << define names >>
names = (
    'Add','And','Assert','Assign','Attribute','AugAssign','AugLoad','AugStore',
    'BinOp','BitAnd','BitOr','BitXor','BoolOp','Break',
    'Builtin', ### Python 3.x only???
    'Bytes', # Python 3.x only.
    'Call','ClassDef','Compare','Continue',
    'Del','Delete','Dict','DictComp','Div',
    'Ellipsis','Eq','ExceptHandler','Exec','Expr','Expression','ExtSlice',
    'FloorDiv','For','FunctionDef','GeneratorExp','Global','Gt','GtE',
    'If','IfExp','Import','ImportFrom','In','Index','Interactive',
    'Invert','Is','IsNot','LShift','Lambda',
    'List','ListComp','Load','Lt','LtE',
    'Mod','Module','Mult','Name','Not','NotEq','NotIn','Num',
    'Or','Param','Pass','Pow','Print',
    'RShift','Raise','Repr','Return',
    'Set','SetComp','Slice','Store','Str','Sub','Subscript','Suite',
    'TryExcept','TryFinally','Tuple','UAdd','USub','UnaryOp',
    'While','With','Yield',
    # Lower case names...
    'alias',         # A valid ast.AST node.
    'arguments',     # A valid ast.AST node.
    'comprehension', # A valid ast.AST node.
    'keyword',       # A valid ast.AST node(!)
        # 'keywords', # A valid field, but not a valid ast.AST node!
        # In ast.Call nodes, node.keywords points to a *list* of ast.keyword objects.
    # There is never any need to traverse these:
        # 'id','n','name','s','str'.
)
.. @+node:ekr.20140526082700.18024: *8* a.info
def info (self,node):
    
    return '%s: %9s' % (node.__class__.__name__,id(node))
.. @+node:ekr.20140526082700.18025: *8* a.kind
def kind(self,node):
    
    return node.__class__.__name__
.. @+node:ekr.20140526082700.18026: *8* a.op_name
def op_name (self,node):
    
    '''Return the print name of an operator node.'''
    
    d = {
    # Binary operators. 
    'Add':       '+',
    'BitAnd':    '&',
    'BitOr':     '|',
    'BitXor':    '^',
    'Div':       '/',
    'FloorDiv':  '//',
    'LShift':    '<<',
    'Mod':       '%',
    'Mult':      '*',
    'Pow':       '**',
    'RShift':    '>>',
    'Sub':       '-',
    # Boolean operators.
    'And':   ' and ',
    'Or':    ' or ',
    # Comparison operators
    'Eq':    '==',
    'Gt':    '>',
    'GtE':   '>=',
    'In':    ' in ',
    'Is':    ' is ',
    'IsNot': ' is not ',
    'Lt':    '<',
    'LtE':   '<=',
    'NotEq': '!=',
    'NotIn': ' not in ',
    # Context operators.
    'do_AugLoad':  '<AugLoad>',
    'do_AugStore': '<AugStore>',
    'do_Del':      '<Del>',
    'do_Load':     '<Load>',
    'do_Param':    '<Param>',
    'do_Store':    '<Store>',
    # Unary operators.
    'Invert':   '~',
    'Not':      ' not ',
    'UAdd':     '+',
    'USub':     '-',
    }
    name = d.get(self.kind(node),'<%s>' % node.__class__.__name__)
    assert name,self.kind(node)
    return name
.. @+node:ekr.20140526082700.18027: *6*   class StatementTraverser
class StatementTraverser(AstFullTraverser):
    
    def __init__ (self):

        AstFullTraverser.__init__(self)
            # Init the base class.
        self.root = None

    @others
.. @+node:ekr.20140526082700.18028: *7* stat.run
def run (self,root):

    self.root = root
    self.visit(root)
.. @+node:ekr.20140526082700.18029: *7* stat.visit & helpers
def default_visitor(self,node):
    pass
   
def visit(self,node):
    
    '''Visit a *single* ast node.  Visitors are responsible for visiting children!'''
    assert isinstance(node,ast.AST),node.__class__.__name__
    method_name = 'do_' + node.__class__.__name__
    method = getattr(self,method_name,self.default_visitor)
    return method(node)

def visit_children(self,node):
    assert False,'must visit children explicitly'
.. @+node:ekr.20140526082700.18030: *7* stat.Do nothings
if 0:
    @others
.. @+node:ekr.20140526082700.18031: *8* stat.Assert
# Assert(expr test, expr? msg)

def do_Assert(self,node):
    pass
.. @+node:ekr.20140526082700.18032: *8* stat.Assign
# Assign(expr* targets, expr value)

def do_Assign(self,node):
    pass
.. @+node:ekr.20140526082700.18033: *8* stat.AugAssign
# AugAssign(expr target, operator op, expr value)

def do_AugAssign(self,node):
    pass
.. @+node:ekr.20140526082700.18034: *8* stat.Break
def do_Break(self,node):
    pass

.. @+node:ekr.20140526082700.18035: *8* stat.Continue
def do_Continue(self,node):
    pass
.. @+node:ekr.20140526082700.18036: *8* stat.Delete
# Delete(expr* targets)

def do_Delete(self,node):
    pass
.. @+node:ekr.20140526082700.18037: *8* stat.Exec
# Python 2.x only
# Exec(expr body, expr? globals, expr? locals)

def do_Exec(self,node):
    pass
.. @+node:ekr.20140526082700.18038: *8* stat.Expr
# Expr(expr value)

def do_Expr(self,node):
    pass
.. @+node:ekr.20140526082700.18039: *8* stat.Global
# Global(identifier* names)

def do_Global(self,node):
    pass
.. @+node:ekr.20140526082700.18040: *8* stat.Import & ImportFrom
# Import(alias* names)

def do_Import(self,node):
    pass

# ImportFrom(identifier? module, alias* names, int? level)

def do_ImportFrom(self,node):
    pass
.. @+node:ekr.20140526082700.18041: *8* stat.Pass
def do_Pass(self,node):
    pass
.. @+node:ekr.20140526082700.18042: *8* stat.Print
# Python 2.x only
# Print(expr? dest, expr* values, bool nl)
def do_Print(self,node):
    pass
    
.. @+node:ekr.20140526082700.18043: *8* stat.Raise
# Raise(expr? type, expr? inst, expr? tback)

def do_Raise(self,node):
    pass
.. @+node:ekr.20140526082700.18044: *8* stat.Return
# Return(expr? value)

def do_Return(self,node):
    pass
.. @+node:ekr.20140526082700.18045: *8* stat.Yield
#  Yield(expr? value)

def do_Yield(self,node):
    pass
.. @+node:ekr.20140526082700.18199: *6* class IterativeAstTraverser
class IterativeAstTraverser:
    
    # def __init__(self):
        # pass
        
    @others
.. @+node:ekr.20140526082700.18200: *7* iterative.traversers
.. @+node:ekr.20140526082700.18201: *8* private_visit
def private_visit(self,node):
    
    '''Visit a node and all its descendants *without* using recursion.
    
    Visitor methods should *not* call visit, visit_children or visit_list:
    the visit method visits all nodes automatically.
    '''
    
    trace = False
    nodes=[]
    
    for node in self._iterative_postorder_nodes(node):
        kind = node.__class__.__name__
        if trace: nodes.append(kind)
        method = getattr(self,'do_'+kind,None)
        if method:
            if trace: g.trace(method,node)
            method(node)

    if trace: g.trace('\n'+' '.join(reversed(nodes)))
.. @+node:ekr.20140526082700.18202: *8* _iterative_postorder_nodes
def _iterative_postorder_nodes(self,node):

    '''Iteratively yield a node and its descendants in post order:
    that is, this yields all descendants of a node before yielding the node.
    
    Adapted from the iterativePostorder algorithm at:
    http://en.wikipedia.org/wiki/Tree_traversal#Postorder
    '''

    marked_nodes = {} # Do *not* alter the AST nodes!
    stack = [node]
    while stack:
        all_visited = True
        for child in self._children(stack[-1]):
            if not marked_nodes.has_key(id(child)):
                stack.append(child)
                all_visited = False
        if all_visited:
            node2 = stack.pop()
            marked_nodes[id(node2)]=True
            yield node2
.. @+node:ekr.20140526082700.18203: *8* _children
def _children(self,node):

    if isinstance(node, ast.Module):
        for node2 in node.body:
            yield node2

    elif isinstance(node,ast.AST) and node._fields is not None:
        for name in node._fields:
            child = getattr(node,name)
            if isinstance(child,list):
                for node2 in child:
                    if isinstance(node2, ast.AST):
                        yield node2
            elif isinstance(child, ast.AST):
                yield child
    else:
        raise StopIteration
.. @+node:ekr.20140526082700.18196: *6* class HybridAstTraverser
class HybridAstTraverser(AstTraverser):
    
    # def __init__(self):
        # AstTraverser.__init__(self)
        
    @others
.. @+node:ekr.20140526082700.18197: *7* visit
def visit(self,node,data):
    
    '''Visit a tree using a combination of iteration and recursion.'''
    
    # pylint: disable=W0221
        # Arguments number differs from overridden method.
    
    assert isinstance(node,ast.AST),node.__class__.__name__
    method = getattr(self,'do_'+node.__class__.__name__,self.visit_children)
    return method(node,data)
.. @+node:ekr.20140526082700.18198: *7* visit_children
def visit_children(self,node,data):
    
    # pylint: disable=W0221
        # Arguments number differs from overridden method.
    
    assert isinstance(node,ast.AST),node.__class__.__name__

    stack = list(self.get_child_nodes(node))
    while stack:
        node2 = stack.pop()
        kind = node2.__class__.__name__
        method = getattr(self,'do_'+kind,None)
        if method:
            # The method is responsible for visiting children.
            data = method(node2,data)
        else:
            # Just push the children.
            stack.extend(list(self.get_child_nodes(node2)))
    return data
.. @+node:ekr.20140526082700.18300: *6* class StringReportTraverser (AstFormatter)
class StringReportTraverser (AstFormatter):
    
    '''Create string reports from an AST tree.'''

    @others
.. @+node:ekr.20140526082700.18301: *7* srt.__init__
def __init__(self,fn):
    
    AstFormatter.__init__(self)
        # Init the base class.
    self.debug = True
    self.fn = fn
    self.visitor = self
.. @+node:ekr.20140526082700.18302: *8* define_html_header
def define_html_header(self):
    
    # Use string catenation to avoid using g.adjustTripleString.
    return (
        '<?xml version="1.0" encoding="iso-8859-15"?>\n'
        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n'
        '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n'
        '<html xmlns="http://www.w3.org/1999/xhtml">\n'
        '<head>\n'
        '  <title>%(title)s</title>\n'
        '  <link rel="stylesheet" type="text/css" href="%(css-fn)s" />\n'
        '</head>\n<body>'
    )
.. @+node:ekr.20140526082700.18303: *7* srt.report(entry_point)
def report(self,node):

    val = self.visit(node)
    s = val and val.strip()
    fn = ' for '+self.fn if self.fn else ''
    return '\nReport%s...\n\n' % (self.fn) + s
   
.. @+node:ekr.20140526082700.18304: *7* srt.show_all & helper
def show_all(self,node,tag):
    
    result = []
    s = self.show(node,tag)
    if s: result.append(s)
    for child in self.get_child_nodes(node):
        s = self.show_all(child,tag)
        if s: result.append(s)
    return '\n'.join(result)
.. @+node:ekr.20140526082700.18305: *7* srt.show
def show(self,node,tag):
    
    e = getattr(node,'e',None)
    table = (
        (node,'cache',tag),
        (e,'call_cache','e(%s)' % (e and e.name or '')),
        (node,'failures',''),
    )
    result = []
    for obj,ivar,tag2 in table:
        if obj and hasattr(obj,ivar):
            list_or_dict = getattr(obj,ivar)
            pad = ' '*2*(self.level+2)
            if hasattr(list_or_dict,'keys'):
                result.append('%s%s:%s...' % (pad,tag2,ivar))
                for key in sorted(list_or_dict.keys()):
                    aList = list_or_dict.get(key)
                    result.append('   %s%s => %s' % (pad,key,aList))
            else:
                result.append('%sfailures: %s...' % (pad,self.format(obj)))
                result.append('   %s%s' % (pad,list_or_dict))
    # Must end with a newline so the source is shown correctly.
    return '%s\n' % '\n'.join(result) if result else ''
.. @+node:ekr.20140526082700.18306: *7* srt.visit
def visit(self,node):
    
    """Walk a tree of AST nodes."""

    assert isinstance(node,ast.AST),node.__class__.__name__
    kind = node.__class__.__name__
    method = getattr(self,'do_' + kind,None)
    if method:
        # method is responsible for traversing subtrees.
        return method(node)
    else:
        # Traverse subtrees automatically, without calling visit_children.
        return self.show_all(node,kind)
.. @+node:ekr.20140526082700.18307: *7* srt.visitors
# Only these nodes may have caches.
.. @+node:ekr.20140526082700.18308: *8* srt.Assign
def do_Assign(self,node):

    value = self.visit(node.value)
    assns = ['%s=%s\n' % (self.visit(z),value) for z in node.targets]
    s =  ''.join([self.indent(z) for z in assns])
    return s + self.show_all(node,'Assign')
.. @+node:ekr.20140526082700.18309: *8* srt.Expr
def do_Expr(self,node):
    
    '''An outer expression: must be indented.'''
    
    s = self.indent('%s\n' % self.visit(node.value))
    return s + self.show_all(node,'Expr')
.. @+node:ekr.20140526082700.18310: *8* srt.Return
def do_Return(self,node):
     
    val = ' ' + self.visit(node.value) if node.value else ''
    s = self.indent('return%s\n' % val)
    return s + self.show_all(node,'Return')
.. @+node:ekr.20140526082700.18311: *8* str.Str
def do_Str (self,node):
    
    '''This represents a string constant.'''
    s = repr(node.s)
    return s if len(s) < 60 else s[:57]+'...%s' % (s[0])
.. @+node:ekr.20140526082700.18099: *5* class GeneralTest (StcTest)
class GeneralTest: ### (StcTest):
    
    '''A general test class.'''
    
    @others
.. @+node:ekr.20050920084036.207: *4* QueryReplaceCommandsClass (limited to single node)
class QueryReplaceCommandsClass (baseEditCommandsClass):

    '''A class to handle query replace commands.'''

    @others
.. @+node:ekr.20050920084036.208: *5*  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: *5*  getPublicCommands
def getPublicCommands (self):

    return {
        'query-replace':        self.queryReplace,
        'query-replace-regex':  self.queryReplaceRegex,
    }
.. @+node:ekr.20050920084036.210: *5* 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: *5* Helpers
.. @+node:ekr.20050920084036.212: *6* 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: *6* 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: *7* << 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: *7* << 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: *6* 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: *6* 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: *6* 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.20131122162143.16455: *4* Script: isSearchableWidget
g.cls()
# Determine whether the focus widget supports the high-level interface.
import leo.plugins.qtGui as qtGui
import leo.core.leoFrame as leoFrame
import PyQt4.QtGui as QtGui
if 0:
    c.logWantsFocusNow()
elif 1: # Edit a headline
    c.editHeadline(p)
    # c.redraw()
body_w = c.frame.body.bodyCtrl.widget
w = QtGui.QApplication.focusWidget()
print('Focus','isBodyCtrl',w == body_w,w)
tree = c.frame.tree
while w:
    # isText = g.app.gui.isTextWidget(w)
    if isinstance(w,QtGui.QLineEdit):
        wrapper = tree.getWrapper(w,item=None)
        if isinstance(wrapper,qtGui.leoQtBaseTextWidget):
            print('QLineEdit has wrapper',w,wrapper)
        else:
            print('QLineEdit: NO wrapper',w)
            # wrapper = tree.headlineWrapper(c,item=None,name='find-head-wrapper',widget=w)
            # print('QLineEdit NEW wrapper',w,wrapper)
        break
    elif isinstance(w,QtGui.QTextEdit):
        wrapper = getattr(w,'leo_wrapper',None)
        if wrapper:
            if isinstance(wrapper,qtGui.leoQtBaseTextWidget):
                print('QTextEdit has text wrapper',w,wrapper)
            elif isinstance(wrapper,qtGui.leoQtLog):
                logCtrl = wrapper.widget # same as wrapper.logCtrl
                print('QtTextEdit has log wrapper',w,logCtrl)
            else:
                print('unknown wrapper',wrapper)
        else:
            wrapper = qtGui.leoQTextEditWidget(w,'find-wrapper',c=c)
            print('QTextEdit NEW wrapper',w,wrapper)
        break
    print('Fail',w)
    wrapper = False
    if hasattr(w,'parent'):
        w = w.parent()
    else:
        print('no parent',w)
        break
if wrapper:
    print('is searchable (has wrapper)',w,wrapper)
    # Make sure wrapper supports the high-level interface.
    print('high level?',isinstance(wrapper,leoFrame.HighLevelInterface))
    table = (
        'insert',
        'getAllText',
        'setAllText',
        'setInsertPoint',
        'setSelectionRange',
    )
    for ivar in table:
        print(bool(getattr(wrapper,ivar,None)),ivar)
.. @+node:ekr.20141021083702.18356: *4* unused from leoPersistence.py
.. @+node:ekr.20140711111623.17859: *5* pd.find_gnx_node
if 0:
    ### No longer used
    # Replaced by pd.gnx_dict.
    def find_gnx_node(pd,gnx):
        '''Return the first position having the given gnx.'''
        # Newly-imported nodes never have the given gnx initially,
        # but their gnx's may be changed while reading.
        for p in pd.c.all_unique_positions():
            if p.v.gnx == gnx:
                return p
        return None
.. @+node:ekr.20140716021139.17767: *5* pd.recover_ua_for_gnx
def recover_ua_for_gnx(pd,gnx,root,unl):
    '''
    No gnx was found for unl. If an @ua:<gnx> node exists,
    copy that node as a child of the @recovery node.
    '''
    trace = False and not g.unitTesting
    at_uas = pd.has_at_uas_node(root)
    if at_uas:
        # Find the @ua:<gnx> node in root's @uas node.
        h = '@ua:'+gnx
        for at_ua in at_uas.children():
            if at_ua.h == h:
                break
        else:
            if trace: g.trace('no @ua node for gnx:',gnx)
            return
        # Create the @recovery node if necessary.
        at_recovery = pd.find_at_recovery_node(root)
        # Create the @ua node if it does not exist as a child of the @recovery node.
        for child in at_recovery.children():
            if (child.h,child.b) == (at_ua.h,at_ua.b):
                if trace: g.trace('found recovered node',child.h)
                break
        else:
            p = at_recovery.insertAsLastChild()
            p.h = at_ua.h
            p.b = at_ua.b
            if not g.unitTesting:
                g.trace('created recovered node',p.h)
    elif trace:
        g.trace('no @uas node for:',root.h)
.. @+node:ekr.20141021083702.18355: *5* from delete_at_data_children
        # This looks dubious.
        for child in at_data.children():
            if g.match_word(child.h,0,'@recovery'):
                # Move the node to the parent.
                parent = at_data.parent()
                child.moveToLastChildOf(parent)
                # Delete all the children.
                at_data.deleteAllChildren()
                # Move the node back.
                p = parent.firstChild()
                while p.hasNext():
                    p.moveToNext()
                p.moveToLastChildOf(at_data)
                break
        else:
            at_data.deleteAllChildren()
.. @+node:ekr.20140716021139.17772: *5* pd.find_at_recovery_node
def find_at_recovery_node(pd,root):
    '''
    Find the @recovery node for root, a foreign node.
    Create the @recovery node if it does not exist.
    '''
    h = '@recovery'
    at_data = pd.find_at_data_node(root)
    p = g.findNodeInTree(pd.c,at_data,h)
    if not p:
        p = at_data.insertAsLastChild()
        p.h = h
    return p
.. @+node:ekr.20140716021139.17770: *5* pd.has_at_recovery_node
def has_at_recovery_node(pd,root):
    '''
    Find the @recovery node for an @data node with the given unl.
    Return None if it does not exist.
    '''
    p = pd.has_at_data_node(root)
    return p and g.findNodeInTree(pd.c,p,'@recovery')
.. @+node:ekr.20131114124839.17399: *3* set_selection abbrevCommandsClass (no longer used)
# def set_selection(self,i,j):
    # '''Set the selection range, with the insert point at the end.'''
    # self.c.frame.body.wrapper.setSelectionRange(i,j,insert=j)
.. @-all
.. @-leo
