.. @+leo-ver=5-thin
.. @+node:ekr.20031218072017.329: * @file ../doc/leoNotes.txt
.. @@language rest
.. @@killbeautify
.. @+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.20150520135110.1: *3* autopep8 notes
.. @+node:ekr.20150520111038.1: *4* autopep8
@language rest
@wrap

https://github.com/hhatto/autopep8#usage

Suppress these:

E301 - Add missing blank line.
E302 - Add missing 2 blank lines.

Create local config file, wherever that is!
.. @+node:ekr.20150520065100.1: *4* About settings
Existing settings:
    @bool tidy_add_blank_lines_around_comments = False ###
    @bool tidy_double_quoted_strings = False
    @bool tidy_java_style_list_dedent = True
        ### Essential for continued def args.
    @bool tidy_keep_blank_lines = True ###
    @bool tidy_left_adjust_docstrings = False
    @int  tidy_lines_before_split_lit = 2
    @int  tidy_max_seps_func_def = 3

New settings:
    @bool tidy_blank_line_after_docstring = False 
    @bool tidy_blank_line_after_func_def = True
    @bool tidy_leo_call_continuation = False
    @bool tidy_spaces_after_docstring = False
    @int tidy_col_limit = 75
    @int tidy_max_seps_func_def = 20
.. @+node:ekr.20150520085848.1: *4* 2to3 log
@language rest
@wrap

c:\leo.repo\leo-editor\leo\external>c:\python27\python.exe c:\Python27\Tools\Scripts\2to3.py -w PythonTidy.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored PythonTidy.py
--- PythonTidy.py       (original)
+++ PythonTidy.py       (refactored)
@@ -119,7 +119,7 @@

 '''
 #@-<< docstring >>
-from __future__ import division
+
 VERSION = '1.23.1'
     # EKR: based on version 1.23, 2012 May 23
     # http://lacusveris.com/PythonTidy/PythonTidy-1.23.python
@@ -875,7 +875,7 @@
         self.end = len(self.lines) - 1
         return self
     #@+node:ekr.20141010141310.18651: *4* next
-    def next(self):
+    def __next__(self):

         if self.ndx > self.end:
             raise StopIteration
@@ -893,7 +893,7 @@
     def readline(self):

         try:
-            result = self.next()
+            result = next(self)
         except StopIteration:
             result = ''
         return result
@@ -1219,14 +1219,14 @@
             """
             try:
                 while True:
-                    prev_item = lines.next()
+                    prev_item = next(lines)
                     yield prev_item
                     prev_token_type, prev_token_string, prev_start, prev_end, \
                         prev_line = prev_item
                     if prev_token_type in [tokenize.STRING]:
                         on1 = True
                         while True:
-                            next_item = lines.next()
+                            next_item = next(lines)
                             yield next_item
                             next_token_type, next_token_string, next_start, \
                                 next_end, next_line = next_item
@@ -1254,8 +1254,8 @@
         lines = merge_concatenated_strings(lines)
         for token_type, token_string, start, end, line in lines:
             if False and DEBUG:
-                print (token.tok_name[token_type], token_string, start, end,
-                       line)
+                print((token.tok_name[token_type], token_string, start, end,
+                       line))
             self.max_lineno, scol = start
             erow, ecol = end
             if token_type in [tokenize.COMMENT, tokenize.NL]:
@@ -1826,7 +1826,7 @@
             self.str = g.toEncodedString(str_)
         else:
             self.str = str_
-            if isinstance(self.str, unicode):
+            if isinstance(self.str, str):
                 pass
             elif not RECODE_STRINGS:
                 pass
@@ -5846,7 +5846,7 @@
         result = NodeWith(indent, lineno, node.expr, node.vars, node.body)
     elif isinstance_(node, 'Yield'):
         result = NodeYield(indent, lineno, node.value)
-    elif isinstance(node, basestring):
+    elif isinstance(node, str):
         result = NodeStr(indent, lineno, node)
     elif isinstance(node, int):
         result = NodeInt(indent, lineno, node)
RefactoringTool: Files that were modified:
RefactoringTool: PythonTidy.py
RefactoringTool: Warnings/messages while refactoring:
RefactoringTool: ### In file PythonTidy.py ###
RefactoringTool: Line 3415: cannot convert map(None, ...) with multiple arguments because map() now truncates to the sho
rtest sequence
RefactoringTool: Line 3415: cannot convert map(None, ...) with multiple arguments because map() now truncates to the sho
rtest sequence

.. @+node:ekr.20150520135211.1: *4* Unused code in ppp.python_tidy
    # refs = []
    # for line in g.splitLines(s1):
        # i = line.find('<<')
        # j = line.find('>>')
        # if -1 < i < j:
            # ref = line[i:j]
            # refs.append(ref)
            # ref2 = ref.replace('<<','# < <')
            # s1 = s1.replace(ref,ref2)
.. @+node:ekr.20031218072017.365: *3* How to...
.. @+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.20060331094112: *4* 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.20100904134301.8336: *4* How to generate pdf on Linux
El 01/05/09 15:12, Ville M. Vainio escribió:

- make latex
- cd _build/latex
- make all-pdf
.. @+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.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.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.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.20141125112845.5: *3* Leo code notes
.. @+node:ekr.20131011050613.16839: *4* About autocompletion
.. @+node:ekr.20131011050613.16840: *5* 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: *5* 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: *5* 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: *4* 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: *5* 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: *5* Handling key events
.. @+node:ekr.20131011050613.16851: *6* 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: *6* 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: *5* 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: *5* 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: *5* 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.20130807203905.16683: *4* 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.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.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.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.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.20110527084258.18374: *4* 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.20140212062130.16585: *4* Theory of operation for @auto-view
@language rest


.. @+node:ekr.20140212062130.16586: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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.20091218120633.6300: *3* Other notes
.. @+node:ekr.20141125112845.6: *4* jyLeo stuff
.. @+node:ekr.20051203084725.1: *5* 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: *5* 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: *6* 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: *6* 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: *5* 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: *6* @url http://www.jython.org/install.html
.. @+node:ekr.20060111112513.1: *5* 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.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.20130814140750.17191: *4* IPython notes
.. @+node:ekr.20130814140750.17192: *5* 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: *5* 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.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.20131001045038.19027: *4* Quotes from "Why Leo isn't more popular"
@language rest
.. @+node:ekr.20131001045038.19028: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* 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: *5* derwish
To me, it's to directed acyclic graphs what MS Excel is to tables. 
.. @+node:ekr.20131012060912.16765: *5* 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.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.20150527092711.1: ** Backups
@language python
@ignore
.. @+node:ekr.20150530203147.1: *3* @@button TEST PTB
r'''The script to test AddTokensToTree class.'''
g.cls()
if c.isChanged():
    c.save()
project = None # 'leo'
<< imports >>
if project:
    # 17.1 sec. --> 17.4 --> 17.3
    # The format time is about twice the tokenize time.
    aList = leoBeautify.ProjectUtils().project_files(project)
    aList = ['@file %s' % (g.shortFileName(z).rstrip()) for z in aList]
    settings_d = {
        # 'output_string': True,
        # 'stats': True,
    }
else:
    aList = [
        'unit test: leoBeautify.py',
        # '@file leoColorizer.py',
        # '@file leoBeautify.py',
        # '@file leoCommands.py',
    ]
    small = aList[0].startswith('unit test:')
    settings_d = {
        'tidy-keep-blank-lines': True,
        'input_string': small,
        # 'input_lines':  True,
        # 'input_tokens': small,
        'output_tokens': small,
        'output_string': small,
        'stats': not small # and len(aList) == 1,
    }
assert aList,'no input in %s' % (p.h)
<< init total stats >>
t1 = time.clock()
for h in aList:
    p2 = g.findNodeAnywhere(c,h)
    if p2:
        try:
            b = leoBeautify.test_beautifier(c,h,p2,settings_d)
            << update total stats >>
        except Exception:
            g.es_exception()
if len(aList) > 1:
    << print total stats >>
tot_time = time.clock()-t1
if len(aList) > 1:
    print('done: %4.2f sec. = %4.2f sec./file' % (tot_time,tot_time/float(tot_files)))
else:
    print('done: %4.2f sec.' % (tot_time))
.. @+node:ekr.20150530203147.2: *4* << imports >>
import leo.core.leoBeautify as leoBeautify
import imp
import time
imp.reload(leoBeautify)
.. @+node:ekr.20150530203147.3: *4* << init total stats >>
tot_beautify_time = 0.0
tot_changed_nodes = 0
tot_check_time = 0.0
tot_files = 0
tot_input_tokens = 0
tot_output_tokens = 0
tot_parse_time = 0.0
tot_strings = 0
tot_tokenize_time = 0.0
tot_total_time = 0.0
.. @+node:ekr.20150530203147.4: *4* << update total stats >>
tot_beautify_time += b.beautify_time
tot_changed_nodes += b.n_changed_nodes
tot_check_time += b.check_time
tot_files += 1
tot_input_tokens += b.n_input_tokens
tot_output_tokens += b.n_output_tokens
tot_parse_time += b.parse_time
tot_strings += b.n_strings
tot_tokenize_time += b.tokenize_time
tot_total_time += b.total_time
.. @+node:ekr.20150530203147.5: *4* << print total stats >>
print('========== totals ==========')
print('files          %s' % tot_files)
print('changed nodes  %s' % tot_changed_nodes)
print('tokens         %s' % tot_input_tokens)
print('len(code_list) %s' % tot_output_tokens)
print('len(s)         %s' % tot_strings)
print('parse          %4.2f sec.' % tot_parse_time)
print('tokenize       %4.2f sec.' % tot_tokenize_time)
print('format         %4.2f sec.' % tot_beautify_time)
print('check          %4.2f sec.' % tot_check_time)
print('total          %4.2f sec.' % tot_total_time)
.. @+node:ekr.20150704140210.1: *3* test leoCheck.py
g.cls()
import imp
import leo.core.leoCheck as leoCheck
imp.reload(leoCheck)
files = (
    [
        r'c:\leo.repo\leo-editor\leo\core\leoNodes.py',
        # r'c:\leo.repo\leo-editor\leo\core\leoApp.py',
        # r'c:\leo.repo\leo-editor\leo\core\leoFileCommands.py',
    ] or
    leoCheck.ProjectUtils().project_files('leo')
)
leoCheck.test(files)
.. @+node:ekr.20150527092615.1: ** Unused code: do not delete
@language python
@ignore
.. @+node:ekr.20150601161120.1: *3* Beautifier stuff
.. @+node:ekr.20150521132404.1: *4* class AddTokensToTree (AstFullTraverser)
class AddTokensToTree(leoAst.AstFullTraverser):
    '''
    A class that injects token-based data into Ast trees.
    
    This class could be folded into the LeoTidy class, but doing so would
    save negligible time.
    '''
        
    @others
.. @+node:ekr.20150525074945.1: *5* add.ctor
def __init__(self,c,settings,tokens):
    
    leoAst.AstFullTraverser.__init__(self)
        # Init the base class.
    # Copy args...
    self.c = c
    self.settings = settings
    self.tokens = tokens
    # Other ivars...
    self.n_visits = 0
        # Number of calls to visit.
    self.n_set_tokens = 0
        # Number of calls to set_tokens
    self.prev_statement = None
        # The previous statement node.
    self.statements_d = {}
        # Set below.  Keys are statement kinds, values ignored.
    self.strings_list = []
        # A global list of tuples (n,s), for all string tokens.
    self.tokens_d = {}
        # (Debugging only) Keys are line numbers. Values are token5tuples.
    self.trailing_tokens_list = []
        # A list of tuples (n,kind,list_of_tokens)
    self.trailing_tokens_list_offset = 0
        # The number of trailing tokens already seen.
    # Compute data.
    self.make_statements_d()
    self.make_tokens_data(tokens)
        # Make strings_list, trailing_tokens_list.
        # Also makes tokens_d, used only for debugging.
.. @+node:ekr.20150525105228.1: *5* add.dump_tokens_d
def dump_tokens_d(self):
    '''Print tokens_d'''
    print('-' * 20)
    print('AddTokensToTree: tokens_d...')
    for n in sorted(self.tokens_d.keys()):
        aList = self.tokens_d.get(n)
        if aList:
            pad = 6 * ' '
            pad2 = '\n' + 7 * ' '
            nl = '' if len(aList) == 1 else '\n'+pad
            result = []
            for n2,name,lws,s in aList:
                assert n == n2, (n,n2)
                lws = self.show_lws(lws)
                if name in ('newline','nl'):
                    s = repr(str(s))
                result.append('%10s lws: %-2s %s' % (name,lws,s))
            print('%4s: [%s%s]' % (n,pad2.join(result),nl))
.. @+node:ekr.20150526094135.1: *5* add.dump_strings_list
def dump_strings_list(self):
    '''Dump the strings list.'''
    print('-' * 20)
    print('AddTokensToTree: strings_list...')
    for data in self.strings_list:
        n,name,lws,s = data
        lws = self.show_lws(lws)
        assert name == 'string',name
        print('%3s lws: %-2s %s' % (n,lws,s))
.. @+node:ekr.20150526094136.1: *5* add.dump_trailing_list
def dump_trailing_list(self):
    '''Dump the trailing tokens list.'''
    print('-' * 20)
    print('AddTokensToTree: trailing_tokens_list...')
    for data in self.trailing_tokens_list:
        n,name,lws,s = data
        lws = self.show_lws(lws)
        if name in ('newline','nl'):
            s = repr(str(s))
        print('%4s: %8s lws: %-2s %s' % (n,name,lws,s))
.. @+node:ekr.20150522110017.1: *5* add.make_statements_d
def make_statements_d(self):
    '''
    Return a dictionary of statements that should call set_tokens.
    
    In essence, these entries replace visitors.
    '''
    aList = [
        'Assert','Assign','AugAssign',
        'Break','Call','ClassDef','Continue','Delete',
        'ExceptHandler','Exec','Expr',
        'For','FunctionDef','Global',
        'If','Import','ImportFrom','Lambda', # Module
        'Pass','Print','Raise','Return',
        'Try','TryExcept','TryFinally',
        'While','With','Yield',
    ]
    self.statements_d = {}
    for z in aList:
        self.statements_d[z] = 0
.. @+node:ekr.20150525083523.1: *5* add.make_tokens_data
def make_tokens_data(self,tokens):
    '''Make tokens_d, strings_list and trailing_tokens_list.'''
    self.strings_list = []
    self.tokens_d = {}
    self.trailing_tokens_list = []
    n = 1 # The line number (one-based)
    aList = [] # The list of tokens with line number n (one-based)
    lws = '' # The leading whitespace of the current line.
    for t1,t2,t3,t4,t5 in tokens:
        name = token.tok_name[t1].lower()
        s = g.toUnicode(t2)
        srow,scol = t3
        erow,ecol = t4
        raw_s = g.toUnicode(t5) # Contains leading whitespace!
        if n != srow:
            # g.pr("----- line",srow,erow,repr(line))
            self.tokens_d[n] = aList
            aList,n = [],srow
            for i,ch in enumerate(raw_s):
                if ch not in ' \t':
                    lws = raw_s[:i]
                    break
            else:
                lws = ''
        data = n,name,lws,s  
        if name == 'nl' and not aList:
            self.trailing_tokens_list.append(data)
        elif name == 'comment':
            self.trailing_tokens_list.append(data)
        elif name == 'string':
            g.trace(n,'raw_s',raw_s.rstrip())
            self.strings_list.append(data)
        else:
            pass
        # Put all tokens in self.tokens_d
        aList.append(data)
        # g.trace('%10s %r %r' % (name,lws,t2))
    # Finish the last line.
    self.tokens_d[n] = aList
    for setting, func in (
        ('ast_tokens_d',        self.dump_tokens_d),
        ('ast_strings_list',    self.dump_strings_list),
        ('ast_trailing_list',   self.dump_trailing_list),
    ):
        if self.settings.get(setting):
            func()
.. @+node:ekr.20150521174358.1: *5* add.run
def run(self,node):
    '''The main line for the AddTokensToTree class.'''
    self.prev_statement = node
    self.visit(node)
    return self.n_visits
.. @+node:ekr.20150521174136.1: *5* add.set_tokens & helper
def set_tokens(self,node):
    '''
    Compute the set of tokens associated with this node.
    node.lineno: the line number of source text: the first line is line 1.
    node.col_offset: the UTF-8 byte offset of the first token that generated the node.
    '''
    # n = node.lineno
    # col = node.col_offset
    self.inject_trailing_tokens()
    self.n_set_tokens += 1
    self.prev_statement = node
.. @+node:ekr.20150525101059.1: *6* add.inject_trailing_tokens
def inject_trailing_tokens(self):
    '''Inject all previous comment tokens into self.prev_statement.'''
    trace = False
    prev = self.prev_statement
    prev_n = prev.lineno if hasattr(prev,'lineno') else 1
    n = 0
    offset = self.trailing_tokens_list_offset
    for data in self.trailing_tokens_list[offset:]:
        n2,name,kind,s = data
        if n2 < prev_n:
            n += 1
        else:
            break
    if n > 0:
        # Inject the comment_tokens into the previous statement.
        tokens = self.trailing_tokens_list[offset : offset+n]
        prev.trailing_tokens = tokens
        self.trailing_tokens_list_offset += n
        if trace:
            print('inject trailing tokens %3s %12s %s' % (
                n,self.kind(prev),tokens))
.. @+node:ekr.20150526093911.1: *5* add.show_lws
def show_lws(self,s):
    '''Show leading whitespace in a convenient format.'''
    return repr(s) if s.strip(' ') else len(s)
.. @+node:ekr.20150521174401.1: *5* add.visit
def visit(self,node):
    '''AddTokentsToTree.visit.'''
    self.n_visits += 1
    name = node.__class__.__name__
    if name in self.statements_d:
        self.set_tokens(node)
    method = getattr(self,'do_' + name)
    method(node)
.. @+node:ekr.20150525171444.1: *5* add.Str
def do_Str (self,node):
    '''Associate a token with a ast.Str node.'''
    data = self.strings_list.pop(0)
    n,name,lws,s = data
    assert name == 'string'
    node.str_spelling = s
    # if not s.strip('"').strip("'").endswith(node.s):
        # g.trace('=======================',repr(node.s),repr(s))
.. @+node:ekr.20150520173107.1: *4* class LeoTidy (Uses PythonTidy)
class LeoTidy:
    '''A class to beautify source code from an AST'''
    
    def __init__(self,c,options_d=None):
        '''Ctor for the LeoTidy class.'''
        self.c = c
        self.code_list = []
        self.in_arg_list = False
        self.indent = ' ' * 4
        self.level = 0
        self.tab_width = 4
    
    @others
.. @+node:ekr.20150527171440.1: *5* class OutputToken
class OutputToken:
    '''A class representing items on the code list.'''
    
    def __init__(self,kind,lws,value):
        self.kind = kind
        self.lws = lws
        self.value = value
        
    def __repr__(self):
        return '%15s %-2s %s' % (self.kind,show_lws(self.lws),repr(self.value))
   
    __str__ = __repr__

    def to_string(self):
        '''Convert an output token to a string.'''
        return self.value if g.isString(self.value) else ''
.. @+node:ekr.20150523083023.1: *5* lt.Code Generators
.. @+node:ekr.20150523131619.1: *6* lt.add_token
def add_token(self,kind,value=''):
    '''Add a token to the code list.'''
    tok = self.OutputToken(kind,self.level,value)
    self.code_list.append(tok)
.. @+node:ekr.20150526052853.1: *6* lt.arg_start & arg_end
def arg_end(self):
    '''Add a token indicating the end of an argument list.'''
    self.add_token('arg-end','')
    
def arg_start(self):
    '''Add a token indicating the start of an argument list.'''
    self.add_token('arg-start','')
.. @+node:ekr.20150523083639.1: *6* lt.blank
def blank(self):
    '''Add a blank request on the code list.'''
    prev = self.code_list[-1]
    if prev.kind not in (
        'blank','blank-lines',
            # Suppress duplicates.
        'file-start','line-start','line-end',
            # These tokens implicitly suppress blanks.
        'arg-start','lit-no-blanks','lt',
            # These tokens explicity suppress blanks.
    ):
        self.add_token('blank',' ')
.. @+node:ekr.20150523084306.1: *6* lt.blank_lines
def blank_lines(self,n):
    '''
    Add a request for n blank lines to the code list.
    Multiple blank-lines request yield at least the maximum of all requests.
    '''
    # Count the number of 'consecutive' end-line tokens, ignoring blank-lines tokens.
    prev_lines = 0
    i = len(self.code_list)-1 # start-file token guarantees i >= 0
    while True:
        kind = self.code_list[i].kind
        if kind == 'file-start':
            prev_lines = n ; break
        elif kind == 'blank-lines':
            i -= 1
        elif kind == 'line-end':
            i -= 1 ; prev_lines += 1
        else: break
    # g.trace('i: %3s n: %s prev: %s' % (len(self.code_list),n,prev_lines))
    while prev_lines <= n:
        self.line_end()
        prev_lines += 1
    # Retain the intention for debugging.
    self.add_token('blank-lines',n)
.. @+node:ekr.20150524075023.1: *6* clean
def clean(self,kind):
    '''Remove the last item of token list if it has the given kind.'''
    prev = self.code_list[-1]
    if prev.kind == kind:
        self.code_list.pop()
.. @+node:ekr.20150523085208.1: *6* lt.conditional_line_start
def conditional_line_start(self):
    '''Add a conditional line start to the code list.'''
    prev = self.code_list[-1]
    if prev.kind != 'start-line':
        self.add_token('start-line')
.. @+node:ekr.20150523131526.1: *6* lt.file_start & file_end
def file_end(self):
    '''
    Add a file-end token to the code list.
    Retain exactly one line-end token.
    '''
    while True:
        prev = self.code_list[-1]
        if prev.kind in ('blank-lines','line-end'):
            self.code_list.pop()
        else:
            break
    self.add_token('line-end')
    self.add_token('file-end')

def file_start(self):
    '''Add a file-start token to the code list.'''
    self.add_token('file-start')
.. @+node:ekr.20150523084222.1: *6* lt.line_start & line_end
def line_end(self):
    '''Add a line-end request to the code list.'''
    prev = self.code_list[-1]
    if prev.kind != 'file-start':
        self.add_token('line-end','\n')

def line_start(self):
    '''Add a line-start request to the code list.'''
    prev = self.code_list[-1]
    if prev.kind != 'line-start':
        self.add_token('line-start',self.indent*self.level)
.. @+node:ekr.20150523083627.1: *6* lt.lit*
def lit(self,s):
    '''Add a request for a literal to the code list.'''
    assert s and g.isString(s),repr(s)
    # g.trace(repr(s),g.callers())
    self.add_token('lit',s)
    
def lit_blank(self,s):
    '''Add request for a liter (no previous blank) followed by a blank.'''
    self.clean('blank')
    self.lit(s)
    self.blank()

def lit_no_blanks(self,s):
    '''Add a request for a literal *not* surrounded by blanks.'''
    self.clean('blank')
    self.add_token('lit-no-blanks',s)
.. @+node:ekr.20150523083651.1: *6* lt.lt & rt
def lt(self,s):
    '''Add a left paren request to the code list.'''
    assert s in '([{',repr(s)
    self.add_token('lt',s)
    
def rt(self,s):
    '''Add a right paren request to the code list.'''
    assert s in ')]}',repr(s)
    prev = self.code_list[-1]
    if prev.kind == 'arg-end':
        # Remove a blank token preceding the arg-end token.
        prev = self.code_list.pop()
        self.clean('blank')
        self.code_list.append(prev)   
    else:
        self.clean('blank')
    self.add_token('rt',s)
.. @+node:ekr.20150522212520.1: *6* lt.op
def op(self,s):
    '''Add an operator request to the code list.'''
    assert s and g.isString(s),repr(s)
    self.blank()
    self.lit(s)
    self.blank()
.. @+node:ekr.20150523083952.1: *6* lt.word
def word(self,s):
    '''Add a word request to the code list.'''
    assert s and g.isString(s),repr(s)
    self.blank()
    self.add_token('word',s)
    self.blank()
.. @+node:ekr.20150520173107.2: *5* lt.Entries
.. @+node:ekr.20150520173107.4: *6* lt.format
def format (self,node):
    '''Format the node (or list of nodes) and its descendants.'''
    self.level = 0
    self.file_start()
    val = self.visit(node)
    self.file_end()
    return ''.join([z.to_string() for z in self.code_list])
.. @+node:ekr.20150520173107.5: *6* lt.visit
def visit(self,node):
    '''Return the formatted version of an Ast node, or list of Ast nodes.'''
    trace = False and not g.unitTesting
    assert isinstance(node,ast.AST),node.__class__.__name__
    method_name = 'do_' + node.__class__.__name__
    method = getattr(self,method_name)
    if trace: g.trace(method_name)
    method(node)
.. @+node:ekr.20150520173107.69: *5* lt.Utils
.. @+node:ekr.20150520173107.70: *6* lt.kind
def kind(self,node):
    '''Return the name of node's class.'''
    return node.__class__.__name__
.. @+node:ekr.20150520173107.72: *6* lt.op_name
def op_name (self,node,strict=True):
    '''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.
    'AugLoad':  '<AugLoad>',
    'AugStore': '<AugStore>',
    'Del':      '<Del>',
    'Load':     '<Load>',
    'Param':    '<Param>',
    'Store':    '<Store>',
    # Unary operators.
    'Invert':   '~',
    'Not':      'not',
    'UAdd':     '+',
    'USub':     '-',
    }
    name = d.get(self.kind(node),'<%s>' % node.__class__.__name__)
    if strict: assert name,self.kind(node)
    return name
.. @+node:ekr.20150523083043.1: *5* lt.Visitors
.. @+node:ekr.20150520173107.12: *6* lt.Expressions
.. @+node:ekr.20150520173107.13: *7* lt.Expr
def do_Expr(self,node):
    '''An outer expression: must be indented.'''
    self.line_start()
    self.visit(node.value)
    self.line_end()
.. @+node:ekr.20150520173107.14: *7* lt.Expression
def do_Expression(self,node):
    '''An inner expression: do not indent.'''
    self.visit(node.body)
    self.line_end()
.. @+node:ekr.20150520173107.15: *7* lt.GeneratorExp
# GeneratorExp(expr elt, comprehension* generators)

def do_GeneratorExp(self,node):
    
    self.lt('(')
    self.visit(node.elt)
    self.word('for')
    if node.generators:
        for z in node.generators:
            self.visit(z)
    self.rt(')')
.. @+node:ekr.20150520173107.17: *6* lt.Operands
.. @+node:ekr.20150520173107.18: *7* lt.arguments
# arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults)

def do_arguments(self,node):
    '''Format the arguments node.'''
    assert self.kind(node) == 'arguments',node
    self.in_arg_list = True
    n_plain = len(node.args) - len(node.defaults)
    n_args = len(node.args)
    self.arg_start()
    for i in range(n_args):
        if i < n_plain:
            self.visit(node.args[i])
        else:
            self.visit(node.args[i])
            self.op('=')
            self.visit(node.defaults[i-n_plain])
        if i + 1 < n_args:
            self.lit_blank(',')
    if getattr(node,'vararg',None):
        if node.args:
            self.lit_blank(',')
        self.lit('*')
        name = getattr(node,'vararg')
        self.word(name.arg if g.isPython3 else name)
    if getattr(node,'kwarg',None):
        if node.args or getattr(node,'vararg',None):
            self.lit_blank(',')
        self.lit('**')
        name = getattr(node,'kwarg')
        self.word(name.arg if g.isPython3 else name)
    self.arg_end()
    self.in_arg_list = False
.. @+node:ekr.20150520173107.19: *7* lt.arg (Python3 only)
# Python 3:
# arg = (identifier arg, expr? annotation)

def do_arg(self,node):
    '''Return the name of the argument.'''
    self.word(node.arg)
.. @+node:ekr.20150520173107.20: *7* lt.Attribute
# Attribute(expr value, identifier attr, expr_context ctx)

def do_Attribute(self,node):
    
    self.visit(node.value)
    self.lit_no_blanks('.')
    self.word(node.attr)
.. @+node:ekr.20150520173107.21: *7* lt.Bytes
def do_Bytes(self,node): # Python 3.x only.
    assert g.isPython3
    self.lit(node.s)
.. @+node:ekr.20150520173107.22: *7* lt.Call & lt.keyword
# Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs)

def do_Call(self,node):

    self.visit(node.func)
    self.lit_no_blanks('(')
    for i,z in enumerate(node.args):
        self.visit(z)
        if i + 1 < len(node.args):
            self.lit_blank(',')
    if node.args and node.keywords:
        self.lit_blank(',')
    for i,z in enumerate(node.keywords):
        self.visit(z) # Calls f.do_keyword.
        if i + 1 < len(node.keywords):
            self.lit_blank(',')
    if getattr(node,'starargs',None):
        if node.args or node.keywords:
            self.lit_blank(',')
        self.lit('*')
        self.visit(node.starargs)
    if getattr(node,'kwargs',None):
        if node.args or node.keywords or getattr(node,'starargs',None):
            self.lit_blank(',')
        self.lit('**')
        self.visit(node.kwargs)
    self.rt(')')
.. @+node:ekr.20150520173107.23: *8* lt.keyword
# keyword = (identifier arg, expr value)

def do_keyword(self,node):
    
    self.lit(node.arg)
        # node.arg is a string.
    self.lit('=')
    self.visit(node.value)
        # This is a keyword *arg*, not a Python keyword!
.. @+node:ekr.20150520173107.24: *7* lt.comprehension
# comprehension (expr target, expr iter, expr* ifs)

def do_comprehension(self,node):
    
    self.visit(node.target)
    self.op('in')
    self.visit(node.iter)
    if node.ifs:
        for i,z in enumerate(node.ifs):
            self.word('if')
            self.visit(z)
.. @+node:ekr.20150520173107.25: *7* lt.Dict
def do_Dict(self,node):
    
    self.lt('{')
    if node.keys:
        if len(node.keys) == len(node.values):
            # g.trace([(z.s,z.str_spelling) for z in node.keys])
            # g.trace([(z.s,z.str_spelling) for z in node.values])
            self.level += 1
            for i in range(len(node.keys)):
                self.visit(node.keys[i])
                self.lit(':')
                self.blank()
                self.visit(node.values[i])
                self.lit_blank(',')
                if i + 1 < len(node.keys):
                    self.line_start()
            self.level -= 1
        else:
            print('Error: f.Dict: len(keys) != len(values)\nkeys: %r\nvals: %r' % (
                node.keys,node.values))
    self.rt('}')
.. @+node:ekr.20150520173107.26: *7* lt.Ellipsis
def do_Ellipsis(self,node):
    
    self.lit('...')
.. @+node:ekr.20150520173107.27: *7* lt.ExtSlice
def do_ExtSlice (self,node):
    
    for i,z in enumerate(node.dims):
        self.visit(z)
        if i + 1 < len(node.dims):
            self.op(':')
.. @+node:ekr.20150520173107.28: *7* lt.Index
def do_Index (self,node):
    
    self.visit(node.value)
.. @+node:ekr.20150520173107.29: *7* lt.List
def do_List(self,node):

    # Not used: list context.
    # self.visit(node.ctx)
    self.lt('[')
    if node.elts:
        for i,z in enumerate(node.elts):
            self.visit(z)
            if i + 1 < len(node.elts):
                self.lit_blank(',')
    self.rt(']')
    
.. @+node:ekr.20150520173107.30: *7* lt.ListComp
def do_ListComp(self,node):
    
    self.lt('[')
    self.visit(node.elt)
    self.word('for')
    for i,z in enumerate(node.generators):
        self.visit(z)
        ### ?
    self.rt(']')
.. @+node:ekr.20150520173107.31: *7* lt.Name
def do_Name(self,node):

    self.word(node.id)
.. @+node:ekr.20150520182346.1: *7* lt.NameConstant
# Python 3 only.

def do_NameConstant(self,node):
    
    self.lit(str(node.value))
.. @+node:ekr.20150520173107.32: *7* lt.Num
def do_Num(self,node):
    
    self.lit(repr(node.n))
.. @+node:ekr.20150520173107.33: *7* lt.Repr
# Python 2.x only
def do_Repr(self,node):
    
    self.word('repr')
    self.lt('(')
    self.visit(node.value)
    self.rt(')')
.. @+node:ekr.20150520173107.34: *7* lt.Slice
def do_Slice (self,node):
    
    # g.trace(repr(node.lower),repr(node.upper),repr(node.step))
    if node.lower:
        self.visit(node.lower)
    self.op(':')
    if node.upper:
        self.visit(node.upper)
    if node.step:
        self.op(':')
        if hasattr(node.step,'id') and node.step.id == 'None':
            pass
        else:
            self.visit(node.step) 

    # if getattr(node,'lower',None) is not None:
        # self.visit(node.lower)
    # self.op(':')
    # if getattr(node,'upper',None) is not None:
        # self.visit(node.upper)
    # if getattr(node,'step',None) is not None:
        # if hasattr(node.step,'id'):
            # g.trace(node.step.id)
        # self.op(':')
        # g.trace(node.step)
        # self.visit(node.step) 
.. @+node:ekr.20150520173107.35: *7* lt.Str
def do_Str (self,node):
    '''This represents a string constant.'''
    self.lit(node.str_spelling)
.. @+node:ekr.20150520173107.36: *7* lt.Subscript
# Subscript(expr value, slice slice, expr_context ctx)

def do_Subscript(self,node):
    
    self.visit(node.value)
    self.lt('[')
    self.visit(node.slice)
    self.rt(']')
.. @+node:ekr.20150520173107.37: *7* lt.Tuple
def do_Tuple(self,node):
    
    self.lt('(')
    for i,z in enumerate(node.elts):
        self.visit(z)
        if i + 1 < len(node.elts):
            self.lit_blank(',')
    self.rt(')')
.. @+node:ekr.20150520173107.38: *6* lt.Operators
.. @+node:ekr.20150520173107.39: *7* lt.BinOp
def do_BinOp (self,node):

    self.lt('(')
    self.visit(node.left)
    self.op(self.op_name(node.op))
    self.visit(node.right)
    self.rt(')')
    
.. @+node:ekr.20150526141653.1: *7* lt.Compare ops
# Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn
 
def do_Eq   (self,node): self.op('==')
def do_Gt   (self,node): self.op('>')
def do_GtE  (self,node): self.op('>=')
def do_In   (self,node): self.word('in')
def do_Is   (self,node): self.word('is')
def do_IsNot(self,node): self.word('is not')
def do_Lt   (self,node): self.op('<')
def do_LtE  (self,node): self.op('<=')
def do_NotEq(self,node): self.op('!=')
def do_NotIn(self,node): self.word('not in')
.. @+node:ekr.20150520173107.40: *7* lt.BoolOp
# BoolOp(boolop op, expr* values)

def do_BoolOp (self,node):
    
    op_name = self.op_name(node.op)
    self.lt('(')
    for i,z in enumerate(node.values):
        self.visit(z)
        if i + 1 < len(node.values):
            self.op(op_name)
    self.rt(')')
.. @+node:ekr.20150520173107.41: *7* lt.Compare
# Compare(expr left, cmpop* ops, expr* comparators)

def do_Compare(self,node):
    
    self.lt('(')
    self.visit(node.left)
    assert len(node.ops) == len(node.comparators)
    for i in range(len(node.ops)):
        self.visit(node.ops[i])
        self.visit(node.comparators[i])
    self.rt(')')
.. @+node:ekr.20150520173107.42: *7* lt.UnaryOp
# UnaryOp(unaryop op, expr operand)

def do_UnaryOp (self,node):
    
    name = self.op_name(node.op)
    self.lt('(')
    if name.isalpha():
        self.word(name)
    else:
        self.lit(name)
    self.visit(node.operand)
    self.rt(')')
    
.. @+node:ekr.20150520173107.43: *7* lt.ifExp (ternary operator)
def do_IfExp (self,node):
    
    self.visit(node.body)
    self.word('if')
    self.visit(node.test)
    self.blank()
    self.word('else')
    self.visit(node.orelse)
    self.blank()
.. @+node:ekr.20150520173107.44: *6* lt.Statements
.. @+node:ekr.20150520173107.45: *7* lt.Assert
def do_Assert(self,node):

    self.line_start()
    self.word('assert')
    self.visit(node.test)
    if getattr(node,'msg',None):
        self.lit_blank(',')
        self.visit(node.msg)
    self.line_end()
.. @+node:ekr.20150520173107.46: *7* lt.Assign
def do_Assign(self,node):

    self.line_start()
    for z in node.targets:
        self.visit(z)
        self.op('=')
    self.visit(node.value)
    self.line_end()
    
.. @+node:ekr.20150520173107.47: *7* lt.AugAssign
def do_AugAssign(self,node):
    
    self.line_start()
    self.visit(node.target)
    self.op(self.op_name(node.op)+'=')
    self.visit(node.value)
    self.line_end()
.. @+node:ekr.20150520173107.48: *7* lt.Break
def do_Break(self,node):

    self.line_start()
    self.word('break')
    self.line_end()
.. @+node:ekr.20150520173107.7: *7* lt.ClassDef
# ClassDef(identifier name, expr* bases, stmt* body, expr* decorator_list)

def do_ClassDef (self,node):

    self.blank_lines(2)
    decorators = node.decorator_list
    if decorators:
        for i,z in enumerate(decorators):
            self.line_start()
            self.visit(z)
            self.line_end()
    self.line_start()
    self.word('class')
    self.word(node.name)
    if node.bases:
        self.lt('(')
        for i,z in enumerate(node.bases):
            self.visit(z)
            if i + 1 < len(node.bases):
                self.lit_blank(',')
        self.rt(')')
    self.lit_no_blanks(':')
    self.line_end()
    for z in node.body:
        self.level += 1
        self.visit(z)
        self.level -= 1
    self.blank_lines(2)
.. @+node:ekr.20150520173107.49: *7* lt.Continue
def do_Continue(self,node):
    
    self.line_start()
    self.word('continue')
    self.line_end()
    
.. @+node:ekr.20150520173107.50: *7* lt.Delete
def do_Delete(self,node):

    self.line_start()
    self.word('del')
    if node.targets:
        for i, z in enumerate(node.targets):
            self.visit(z)
            if i + 1 < len(node.targets):
                self.lit_blank(',')
    self.line_end()
.. @+node:ekr.20150520173107.51: *7* lt.ExceptHandler
def do_ExceptHandler(self,node):
    
    # g.trace(node)
    self.line_start()
    self.word('except')
    if getattr(node,'type',None):
        self.blank()
        self.visit(node.type)
    if getattr(node,'name',None):
        self.word('as')
        if isinstance(node.name,ast.AST):
            self.visit(node.name)
        else:
            self.word(node.name) # Python 3.x.
    self.lit_no_blanks(':')
    self.line_end()
    for z in node.body:
        self.level += 1
        self.visit(z)
        self.level -= 1
.. @+node:ekr.20150520173107.52: *7* lt.Exec
# Exec(expr body, expr? globals, expr? locals)

# Python 2.x only
def do_Exec(self,node):
    
    globals_ = getattr(node,'globals',None)
    locals_ = getattr(node,'locals',None)
    self.line_start()
    self.word('exec')
    self.visit(node.body)
    if globals_ or locals_:
        self.word('in')
    if globals_:
        self.visit(node.globals)
    if locals_:
        if globals_:
            self.lit_blank(',')
        self.visit(node.locals)
    self.line_end()
.. @+node:ekr.20150520173107.53: *7* lt.For
def do_For (self,node):
    
    self.line_start()
    self.word('for')
    self.visit(node.target)
    self.op('in')
    self.visit(node.iter)
    self.lit_no_blanks(':')
    self.line_end()
    for z in node.body:
        self.level += 1
        self.visit(z)
        self.level -= 1
    if node.orelse:
        self.line_start()
        self.word('else')
        self.lit_no_blanks(':')
        self.line_end()
        for z in node.orelse:
            self.level += 1
            self.visit(z)
            self.level -= 1
.. @+node:ekr.20150520173107.8: *7* lt.FunctionDef
# FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list)

def do_FunctionDef (self,node):
    '''Format a FunctionDef node.'''
    self.blank_lines(1)
    if node.decorator_list:
        for z in node.decorator_list:
            self.line_start()
            self.op('@')
            self.visit(z)
            self.line_end()
    self.line_start()
    self.word('def')
    self.word(node.name)
    self.lt('(')
    if node.args:
        self.visit(node.args)
    self.rt(')')
    self.lit_no_blanks(':')
    self.line_end()
    for z in node.body:
        self.level += 1
        self.visit(z)
        self.level -= 1
    self.blank_lines(1)
.. @+node:ekr.20150520173107.54: *7* lt.Global
def do_Global(self,node):
    
    self.line_start()
    self.word('global')
    for i,z in enumerate(node.names):
        self.word(z)
        if i + 1 < len(node.names):
            self.lit_blank(',')
    self.line_end()
.. @+node:ekr.20150520173107.55: *7* lt.If
def do_If (self,node):
    
    self.line_start()
    self.word('if')
    self.visit(node.test)
    self.lit_no_blanks(':')
    self.line_end()
    for z in node.body:
        self.level += 1
        self.visit(z)
        self.level -= 1
    if node.orelse:
        self.line_start()
        self.word('else')
        self.lit_no_blanks(':')
        self.line_end()
        for z in node.orelse:
            self.level += 1
            self.visit(z)
            self.level -= 1
.. @+node:ekr.20150520173107.56: *7* lt.Import & helper
def do_Import(self,node):
    
    self.line_start()
    self.word('import')
    aList = self.get_import_names(node)
    for i,data in enumerate(aList):
        fn,asname = data
        self.word(fn)
        if asname:
            self.op('as')
            self.word(asname)
        if i + 1 < len(aList):
            self.lit_blank(',')
    self.line_end()
.. @+node:ekr.20150520173107.57: *8* lt.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))
    return result
.. @+node:ekr.20150520173107.58: *7* lt.ImportFrom
def do_ImportFrom(self,node):
    
    self.line_start()
    self.word('from')
    self.word(node.module)
    self.word('import')
    aList = self.get_import_names(node)
    for i, data in enumerate(aList):
        fn, asname = data
        self.word(fn)
        if asname:
            self.word('as')
            self.word(asname)
        if i + 1 < len(aList):
            self.lit_blank(',')
    self.line_end()
.. @+node:ekr.20150520173107.11: *7* lt.Lambda
def do_Lambda (self,node):
    
    ### self.conditional_line_start()
    self.word('lambda')
    if node.args:
        self.visit(node.args)
    self.lit_no_blanks(':')
    self.visit(node.body)
    self.line_end()
.. @+node:ekr.20150520173107.10: *7* lt.Module
def do_Module (self,node):
    
    for z in node.body:
        self.visit(z)
.. @+node:ekr.20150520173107.59: *7* lt.Pass
def do_Pass(self,node):

    self.line_start()
    self.word('pass')
    self.line_end()
.. @+node:ekr.20150520173107.60: *7* lt.Print (Still a problem)
# Python 2.x only
# Print(expr? dest, expr* values, bool nl)
def do_Print(self,node):

    self.line_start()
    self.word('print')
    self.lt('(')
    for i,z in enumerate(node.values):
        if isinstance(z,ast.Tuple):
            for z2 in z.elts:
                self.visit(z2)
                if i + 1 < len(z.elts):
                    self.lit_blank(',')
        else:
            self.visit(z)
        if i + 1 < len(node.values):
            self.lit_blank(',')
    # if getattr(node,'dest',None):
        # vals.append('dest=%s' % self.visit(node.dest))
    # if getattr(node,'nl',None):
        # vals.append('nl=%s' % node.nl)
    self.rt(')')
    self.line_end()
.. @+node:ekr.20150520173107.61: *7* lt.Raise
def do_Raise(self,node):
    
    has_arg = False
    self.line_start()
    self.word('raise')
    for attr in ('type','inst','tback'):
        if getattr(node,attr,None) is not None:
            if has_arg:
                self.lit_blank(',')
            self.visit(getattr(node,attr))
            has_arg = True
    self.line_end()
.. @+node:ekr.20150520173107.62: *7* lt.Return
def do_Return(self,node):
    
    self.line_start()
    self.word('return')
    if node.value:
        self.blank()
        self.visit(node.value)
    self.line_end()
.. @+node:ekr.20150520202136.1: *7* lt.Try
# Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)

def do_Try(self,node):

    self.line_start()
    self.word('try')
    self.lit_no_blanks(':')
    self.line_end()
    for z in node.body:
        self.level += 1
        self.visit(z)
        self.level -= 1
    if node.handlers:
        for z in node.handlers:
            self.visit(z)
    if node.orelse:
        self.line_start()
        self.word('else')
        self.lit_no_blanks(':')
        self.line_end()
        for z in node.orelse:
            self.level += 1
            self.visit(z)
            self.level -= 1 
    if node.finalbody:
        self.line_start()
        self.word('finally')
        self.lit_no_blanks(':')
        self.line_end()
        for z in node.finalbody:
            self.level += 1
            self.visit(z)
            self.level -= 1
.. @+node:ekr.20150520173107.64: *7* lt.TryExcept (Python 2)
# TryExcept(stmt* body, excepthandler* handlers, stmt* orelse)
# TryFinally(stmt* body, stmt* finalbody)

def do_TryExcept(self,node):

    # g.trace(node)
    self.line_start()
    self.word('try:')
    self.line_end()
    for z in node.body:
        self.level += 1
        self.visit(z)
        self.level -= 1
    if node.handlers:
        for z in node.handlers:
            self.visit(z)
    if node.orelse:
        self.line_start()
        self.word('else:')
        self.line_end()
        for z in node.orelse:
            self.level += 1
            self.visit(z)
            self.level -= 1
    self.line_end()
.. @+node:ekr.20150520173107.65: *7* lt.TryFinally (Python 2)
# TryExcept(stmt* body, excepthandler* handlers, stmt* orelse)
# TryFinally(stmt* body, stmt* finalbody)

def do_TryFinally(self,node):
    
    # g.trace(node)
    self.line_start()
    self.word('try:')
    self.line_end()
    for z in node.body:
        self.level += 1
        self.visit(z)
        self.level -= 1
    self.line_start()
    self.word('finally:')
    self.line_end()
    for z in node.finalbody:
        self.level += 1
        self.visit(z)
        self.level -= 1
    
.. @+node:ekr.20150520173107.66: *7* lt.While
def do_While (self,node):
    
    self.line_start()
    self.word('while')
    self.visit(node.test)
    self.lit_no_blanks(':')
    self.line_end()
    for z in node.body:
        self.level += 1
        self.visit(z)
        self.level -= 1
    if node.orelse:
        self.line_start()
        self.word('else')
        self.lit_no_blanks(':')
        self.line_end()
        for z in node.orelse:
            self.level += 1
            self.visit(z)
            self.level -= 1
.. @+node:ekr.20150520173107.67: *7* lt.With
# With(expr context_expr, expr? optional_vars, stmt* body)

def do_With (self,node):
    
    self.line_start()
    self.word('with')
    if hasattr(node,'context_expression'):
        self.visit(node.context_expresssion)
    vars_list = []
    if hasattr(node,'optional_vars'):
        try:
            for i,z in enumerate(node.optional_vars):
                self.visit(z)
                if i + 1 < len(node.optional_vars):
                    self.lit_blank(',')
        except TypeError: # Not iterable.
            self.visit(node.optional_vars) 
    self.lit_no_blanks(':')
    self.line_end()
    self.level += 1
    for z in node.body:
        self.visit(z)
    self.level -= 1
    self.line_end()
.. @+node:ekr.20150520173107.68: *7* lt.Yield
# Yield(expr? value)

def do_Yield(self,node):
    
    self.line_start()
    self.word('yield')
    if hasattr(node,'value'):
        self.blank()
        self.visit(node.value)
    self.line_end()
.. @+node:ekr.20150528131012.2: *4* beautify-all-python
@g.command('beautify-all-python')
@g.command('pretty-print-all-python')
def prettyPrintAllPythonCode(event):
    '''Beautify all Python code in the entire outline.'''
    c = event.get('c')
    if not c: return
    t1 = time.clock()
    pp = PythonTokenBeautifier(c)
    prev_changed = 0
    for p in c.all_unique_positions():
        if g.scanForAtLanguage(c, p) == "python":
            if p.isAnyAtFileNode():
                # Report changed nodes in previous @<file> node.
                if pp.n_changed_nodes != prev_changed:
                    g.es_print('changed %s nodes' % (pp.n_changed_nodes - prev_changed))
                prev_changed = pp.n_changed_nodes
                g.es_print(p.h)
            pp.prettyPrintNode(p)
    # Report any nodes in the last @<file> tree.
    if pp.n_changed_nodes != prev_changed:
        g.es_print('changed %s nodes' % (pp.n_changed_nodes - prev_changed))
    pp.end_undo()
    t2 = time.clock()
    # pp.print_stats()
    g.es_print('changed %s nodes in %4.2f sec.' % (pp.n_changed_nodes, t2 - t1))
.. @+node:ekr.20160121163900.1: *3* class g.MatchBrackets (new & slow)
class MatchBrackets:
        
    @others
    
.. @+node:ekr.20160121163900.2: *4* mb.ctor
def __init__(self, c, p, language):
    '''Ctor for MatchBrackets class.'''
    self.c = c
    self.p = p.copy()
    self.language = language
    self.s = None # set by find_matching_bracket.
    # Constants...
    self.close_brackets = ")]}"
    self.open_brackets = "([{"
    self.brackets = self.open_brackets + self.close_brackets
    ### self.matching_brackets = self.close_brackets + self.open_brackets
    # Language dependent.
    d1, d2, d3 = g.set_delims_from_language(language)
    self.single_comment, self.start_comment, self.end_comment = d1, d2, d3
    # g.trace(repr(d1), repr(d2), repr(d3))
    # Data structures for scanning...
    self.brackets_dict = {}
        # Keys are indices into self.s.
        # Values are (ch1, ch2, i, j)
        # s[i] == ch. s[j] == ch2 if j is not None.
    self.comments_and_strings_list = []
        # Values are (start_index, end_index)
.. @+node:ekr.20160121163900.3: *4* mb.find_matching_bracket
def find_matching_bracket(self, ch1, s, i):
    '''Find the bracket matching s[i] for self.language.'''
    self.s = s
    if ch1 not in self.brackets:
        return None
    self.forward = forward = ch1 in self.open_brackets
    d = {
        '{':'}', '[':']', '(':')',
        '}':'{', ']':'[', ')':'(',
    }
    target = d.get(ch1)
    if not target:
        return None
    # # Find the character matching the initial bracket.
    # for n in range(len(self.brackets)):
        # if ch1 == self.brackets[n]:
            # target = self.matching_brackets[n]
            # break
    # else:
        # return None
    if self.forward:
        self.prescan(ch1, s, target)
    else:
        self.prescan(target, s, ch1)
    return self.lookup_matching_bracket(ch1, target, i)
.. @+node:ekr.20160121163900.4: *4* mb.oops
def oops(self, s):
    '''Report an error in the match-brackets command.'''
    g.es_print(s, color='red')
.. @+node:ekr.20160121163900.5: *4* mb.run
def run(self):
    '''The driver for the MatchBrackets class.'''
    # A partial fix for bug 127: Bracket matching is buggy.
    w = self.c.frame.body.wrapper
    brackets = "()[]{}<>"
    s = w.getAllText()
    ins = w.getInsertPoint()
    ch1 = 0 <= ins - 1 < len(s) and s[ins - 1] or ''
    ch2 = 0 <= ins < len(s) and s[ins] or ''
    # g.trace(repr(ch1),repr(ch2),ins)
    # Prefer to match the character to the left of the cursor.
    if ch1 and ch1 in self.brackets:
        ch = ch1; index = max(0, ins - 1)
    elif ch2 and ch2 in self.brackets:
        ch = ch2; index = ins
    else:
        return
    index2 = self.find_matching_bracket(ch, s, index)
    # g.trace('index,index2',index,index2)
    if index2 is not None:
        if index2 < index:
            w.setSelectionRange(index2, index + 1, insert=index2)
            # w.setSelectionRange(index + 1, index2, insert=index2)
            # g.trace('case 1',s[index2:index+1])
        else:
            w.setSelectionRange(index, index2 + 1, insert=min(len(s), index2 + 1))
            # g.trace('case2',s[index:index2+1])
        w.see(index2)
    else:
        g.es("unmatched", repr(ch))
.. @+node:ekr.20160121163900.6: *4* mb.prescan & helpers
def prescan(self, ch1, s, target):
    
    d = self.brackets_dict
    i, level = 0, 0
    stack = [] # Stack of indices of open brackets.
    while i < len(s):
        progress = i
        ch = s[i]
        # g.trace(repr(ch),'i',i)
        if ch in '"\'':
            # Scan to the end of the string.
            i1 = i
            i = self.scan_string(s, i)
            self.comments_and_strings_list.append((i1,i),)
        elif self.starts_comment(s, i):
            i1 = i
            i = self.scan_comment(s, i)
            self.comments_and_strings_list.append((i1,i),)
        elif ch == '/' and self.is_regex(s, i):
            i = self.scan_regex(s, i)
                # Searching within a regex is pointless.
        elif ch == ch1:
            # An opening bracket.
            level += 1
            stack.append(i)
            d [i] = (ch1, target, i, None)
            i += 1
        elif ch == target:
            # A closing bracket.
            level -= 1
            if stack:
                # Update the matching dict entry.
                prev_i = stack.pop()
                data = d.get(prev_i)
                ch2, target2, junk_i2, junk_j2 = data
                assert ch2 == ch1, (ch1, ch2)
                assert target2 == target, (target, target2)
                assert junk_i2 == prev_i, (prev_i, junk_i2)
                assert junk_j2 is None, (junk_j2)
                # Create two entries in the brackets dict.
                d [prev_i] = (ch2, target2, prev_i, i)
                d [i] = (target, ch1, i, prev_i)
            else:
                self.oops('unmatched brackets: %s %s' % (ch1, target))
                d [i] = (target, ch1, i, None)
            i += 1
        else:
            # Any ordinary character.
            i += 1
        assert i > progress
    if stack:
        self.oops('unclosed brackets')
.. @+node:ekr.20160121163900.7: *5* mb.is_regex
def is_regex(self, s, i):
    '''Return true if there is another slash on the line.'''
    assert s[i] == '/'
    i1 = i
    i += 1
    while i < len(s) and s[i] != '\n':
        if s[i] == '/':
           return True
        i += 1
    return False
.. @+node:ekr.20160121163900.8: *5* mb.scan_comment
def scan_comment(self, s, i):
    '''Return the index of the character after a comment.'''
    i1 = i
    if g.match(s, i, self.start_comment):
        i += 1
        while i < len(s):
            if g.match(s, i, self.end_comment):
                i += len(self.end_comment)
                # g.trace('multi-line',s[i1:i])
                return i
            i += 1
        self.oops('unmatched multiline comment')
        return i
    else:
        # Scan to the newline.
        target = '\n'
        while i < len(s):
            if s[i] == '\n':
                i += 1
                # g.trace('single-line',s[i1,i].rstrip())
                return i
            i += 1
        return i
.. @+node:ekr.20160121163900.9: *5* mb.scan_regex
def scan_regex(self, s, i):
    '''Scan a regex, including perl substitutions.'''
    assert s[i] == '/'
    i1 = i
    i += 1
    found = None
    while 0 <= i < len(s) and s[i] != '\n':
        ch = s[i]
        i2 = i - 1 # in case we have to look behind.
        i += 1
        if ch == '/':
            # Count the preceding backslashes.
            n = 0
            while 0 <= i2 < len(s) and s[i2] == '\\':
                n += 1
                i2 -= 1
            if (n % 2) == 0:
                # g.trace(i, s[i1:i9].strip())
                if self.language == 'perl':
                    # Allow either two or three slashes, but not more.
                    if found is None:
                        found = i
                    else:
                        found = i
                        break
                else:
                    # The second slash terminates the regex.
                    found = i
                    break
    if found is None:
        self.oops('unmatched regex delim')
        return i
    else:
        return found
.. @+node:ekr.20160121163900.10: *5* mb.scan_string
def scan_string(self, s, i):
    '''
    Scan the string starting at s[i].
    Return the index of the next character.
    '''
    i1 = i
    delim = s[i]
    assert delim in "'\"", repr(delim)
    i += 1
    while i < len(s):
        ch = s[i]
        i2 = i - 1 # in case we have to look behind.
        i += 1
        if ch == delim:
            # Count the preceding backslashes.
            n = 0
            while 0 <= i2 < len(s) and s[i2] == '\\':
                n += 1
                i2 -= 1
            if (n % 2) == 0:
                # g.trace(i, s[i1: i].strip())
                return i
    # Annoying when matching brackets on the fly.
    # self.oops('unmatched string')
    return i + 1
.. @+node:ekr.20160121163900.11: *5* mb.starts_comment
def starts_comment(self, s, i):
    '''Return True if s[i] starts a comment.'''
    return (
        self.single_comment and g.match(s, i, self.single_comment)
        or
        self.start_comment and self.end_comment and 
        g.match(s, i, self.start_comment))
.. @+node:ekr.20160121163900.12: *4* mb.lookup_matching_bracket
def lookup_matching_bracket (self, ch1, target, index):
    '''Return the character matching ch1 at the given index into self.s'''
    assert self.s[index] == ch1, (ch1, self.s[index])
    data = self.brackets_dict.get(index)
    if data is None:
        # To do: scan comments/strings.
        g.trace('can not happen: not brackets_dict entry', index)
        return None
    else:
        ch2, target2, i, j = data
        g.trace(ch2, target2, i, j)
        assert ch2 in (ch1, target), (ch2, ch1, target)
        if i is not None:
            assert self.s[i] in (ch1, target), self.s[i]
        if j is not None:
            assert self.s[j] in (ch1, target), self.s[j]
        return j

.. @+node:ekr.20150312225028.6: *3* class LogManager (not used yet)
class LogManager:

    '''A class to handle the global log, and especially
    switching the log from commander to commander.'''

    def __init__ (self):

        trace = (False or g.trace_startup) and not g.unitTesting
        if trace: g.es_debug('(LogManager)')

        self.log = None             # The LeoFrame containing the present log.
        self.logInited = False      # False: all log message go to logWaiting list.
        self.logIsLocked = False    # True: no changes to log are allowed.
        self.logWaiting = []        # List of messages waiting to go to a log.
        self.printWaiting = []      # Queue of messages to be sent to the printer.
        self.signon_printed = False # True: the global signon has been printed.

    @others
.. @+node:ekr.20150312225028.7: *4* LogM.setLog, lockLog, unlocklog
def setLog (self,log):

    """set the frame to which log messages will go"""

    # print("app.setLog:",log,g.callers())
    if not self.logIsLocked:
        self.log = log

def lockLog(self):
    """Disable changes to the log"""
    self.logIsLocked = True

def unlockLog(self):
    """Enable changes to the log"""
    self.logIsLocked = False
.. @+node:ekr.20150312225028.8: *4* LogM.writeWaitingLog
def writeWaitingLog (self,c):
    '''Write all waiting lines to the log.'''
    trace = True
    lm = self
    if trace:
        # Do not call g.es, g.es_print, g.pr or g.trace here!
        print('** writeWaitingLog','silent',g.app.silentMode,c.shortFileName())
        # print('writeWaitingLog',g.callers())
        # import sys ; print('writeWaitingLog: argv',sys.argv)
    if not c or not c.exists:
        return
    if g.unitTesting:
        lm.printWaiting = []
        lm.logWaiting = []
        g.app.setLog(None) # Prepare to requeue for other commanders.
        return
    table = [
        ('Leo Log Window','red'),
        (g.app.signon,'black'),
        (g.app.signon2,'black'),
    ]
    table.reverse()
    c.setLog()
    lm.logInited = True # Prevent recursive call.
    if not lm.signon_printed:
        lm.signon_printed = True
        if not g.app.silentMode:
            print('')
            print('** isPython3: %s' % g.isPython3)
            if not g.enableDB:
                print('** caching disabled')
            print(g.app.signon)
            print(g.app.signon2)
    if not g.app.silentMode:
        for s in lm.printWaiting:
            print(s)
    lm.printWaiting = []
    if not g.app.silentMode:
        for s,color in table:
            lm.logWaiting.insert(0,(s+'\n',color),)
        for s,color in lm.logWaiting:
            g.es('',s,color=color,newline=0)
                # The caller must write the newlines.
    lm.logWaiting = []
    # Essential when opening multiple files...
    lm.setLog(None)
.. @+node:ekr.20150312225028.9: *3* Existing autocompleter (keep)
.. @+node:ekr.20150312225028.10: *4* completeSelf (not used yet)
def completeSelf (self):

    g.trace(g.callers(4))

    # This scan will be fast if an instant object already exists.
    className,obj,p,s = self.classScanner.scan()
    # g.trace(className,obj,p,s and len(s))

    # First, look up the className.
    if not obj and className:
        obj = self.allClassesDict.get(className)
        # if obj: g.trace('found in allClassesDict: %s = %s' % (className,obj))

    # Second, create the object from class definition.
    if not obj and s:
        theClass = self.computeClassObjectFromString(className,s)
        if theClass:
            obj = self.createProxyObjectFromClass(className,theClass)
            if obj:
                self.selfObjectsDict [className] = obj
                # This prevents future rescanning, even if the node moves.
                self.selfVnodesDict [p.v] = obj
    if obj:
        self.selfClassName = className
        self.push(self.theObject)
        self.theObject = obj
        self.membersList = self.getMembersList(obj=obj)
    else:
        # No further action possible or desirable.
        self.selfClassName = None
        self.theObject = None
        self.clear()
        self.membersList = []
.. @+node:ekr.20150312225028.11: *4* class ForgivingParserClass (not used)
class ForgivingParserClass:

    '''A class to create a valid class instances from
    a class definition that may contain syntax errors.'''

    @others
.. @+node:ekr.20150312225028.12: *5* ctor (ForgivingParserClass)
def __init__ (self,c):

    self.c = c
    self.excludedTnodesList = []
    self.old_putBody = None # Set in parse for communication with newPutBody.
.. @+node:ekr.20150312225028.13: *5* parse
def parse (self,p):

    '''The top-level parser method.

    It patches c.atFileCommands.putBody, calls the forgiving parser and finally
    restores c.atFileCommands.putBody.'''

    c = self.c

    # Create an ivar for communication with newPutBody.
    self.old_putBody = c.atFileCommands.putBody

    # Override atFile.putBody.
    c.atFileCommands.putBody = self.newPutBody

    try:
        s = None
        s = self.forgivingParser(p)
    finally:
        c.atFileCommands.putBody = self.old_putBody

    return s # Don't put a return in a finally clause.


.. @+node:ekr.20150312225028.14: *5* forgivingParser (leoKeys)
def forgivingParser (self,p,suppress=False):

    c = self.c ; root = p.copy()
    self.excludedTnodesList = []
    s = g.getScript(c,root,useSelectedText=False)
    while s:
        try:
            if not g.isPython3:
                s = g.toEncodedString(s)
            compile(s+'\n','<string>','exec')
            break
        except SyntaxError:
            fileName, n = g.getLastTracebackFileAndLineNumber()
            p = self.computeErrorNode(c,root,n,lines=g.splitLines(s))
            if not p or p == root:
                if not suppress:
                    g.es_print('syntax error in class node: can not continue')
                s = None ; break
            else:
                # g.es_print('syntax error: deleting',p.h)
                self.excludedTnodesList.append(p.v)
                s = g.getScript(c,root,useSelectedText=False)
        except Exception:
            g.trace('unexpected exception')
            g.es_exception()
            break
    return s or ''
.. @+node:ekr.20150312225028.15: *5* computeErrorNode (leoKeys)
def computeErrorNode (self,c,root,n,lines):

    '''The from c.goToLineNumber that applies to scripts.
    Unlike c.gotoLineNumberOpen, this function returns a position.'''

    if n == 1 or n >= len(lines):
        return root

    # vnodeName, junk, junk, junk, junk = c.convertLineToVnodeNameIndexLine(
        # lines, n, root, scriptFind = True)

    goto = goToLineNumber(c)
    vnodeName,junk,junk,junk = goto.findVnode(
        root,lines,n,ignoreSentinels)

    if vnodeName:
        for p in root.self_and_subtree():
            if p.matchHeadline(vnodeName):
                return p

    return None
.. @+node:ekr.20150312225028.16: *5* newPutBody
def newPutBody (self,p,oneNodeOnly=False,fromString=''):

    if p.v in self.excludedTnodesList:
        pass
        # g.trace('ignoring',p.h)
    else:
        self.old_putBody(p,oneNodeOnly,fromString)
.. @+node:ekr.20150312225028.17: *4* class ClassScannerClass (not used)
# Called by completeSelf, which is not used.

class ClassScannerClass:

    '''A class to find class definitions in a node or its parents.'''

    @others
.. @+node:ekr.20150312225028.18: *5* ctor (classScannerClass)
def __init__ (self,c):

    self.c = c

    # Ignore @root for now:
    # self.start_in_doc = c.config.getBool('at_root_bodies_start_in_doc_mode')

    self.start_in_doc = False
.. @+node:ekr.20150312225028.19: *5* scan
def scan (self):

    c = self.c

    className,obj,p = self.findParentClass(c.p)
    # g.trace(className,obj,p)

    if p and not obj:
        parser = c.k.autoCompleter.forgivingParser
        s = parser.parse(p)
    else:
        s = None

    return className,obj,p,s
.. @+node:ekr.20150312225028.20: *5* findParentClass
def findParentClass (self,root):

    autoCompleter = self.c.k.autoCompleter

    # First, see if any parent has already been scanned.
    for p in root.self_and_parents():
        obj = autoCompleter.selfVnodesDict.get(p.v)
        if obj:
            # g.trace('found',obj,'in',p.h)
            return None,obj,p

    # Next, do a much slower scan.
    # g.trace('slow scanning...')
    for p in root.self_and_parents():
        className = self.findClass(p)
        if className:
            # g.trace('found',className,'in',p.h)
            return className,None,p

    return None,None,None
.. @+node:ekr.20150312225028.21: *5* findClass & helpers
def findClass (self,p):

    lines = g.splitLines(p.b)
    inDoc = self.start_in_doc
    # g.trace(p.h)
    for s in lines:
        if inDoc:
            if self.endsDoc(s):
                inDoc = False
        else:
            if self.startsDoc(s):
                inDoc = True
            else:
                # Not a perfect scan: a triple-string could start with 'class',
                # but perfection is not important.
                className = self.startsClass(s)
                if className: return className
    else:
        return None
.. @+node:ekr.20150312225028.22: *6* endsDoc
def endsDoc (self,s):

    return s.startswith('@c')
.. @+node:ekr.20150312225028.23: *6* startsClass
def startsClass (self,s):

    if s.startswith('class'):
        i = 5
        i = g.skip_ws(s,i)
        j = g.skip_id(s,i)
        word = s[i:j]
        # g.trace(word)
        return word
    else:
        return None
.. @+node:ekr.20150312225028.24: *6* startsDoc
def startsDoc (self,s):

    for s2 in ('@doc','@ ','@\n', '@r', '@\t'):
        if s.startswith(s2):
            return True
    else:
        return False
.. @+node:ekr.20150312225028.25: *4* Proxy classes and objects
.. @+node:ekr.20150312225028.26: *5* createProxyObjectFromClass
def createProxyObjectFromClass (self,className,theClass):

    '''Create a dummy instance object by instantiating theClass with a dummy ctor.'''

    if 0: # Calling the real ctor is way too dangerous.
        # Set args to the list of required arguments.
        args = inspect.getargs(theClass.__init__.im_func.func_code)
        args = args[0] ; n = len(args)-1
        args = [None for z in range(n)]

    def dummyCtor (self):
        pass

    try:
        obj = None
        old_init = hasattr(theClass,'__init__') and theClass.__init__
        theClass.__init__ = dummyCtor
        obj = theClass()
    finally:
        if old_init:
            theClass.__init__ = old_init
        else:
            delattr(theClass,'__init__')

    g.trace(type(theClass),obj)

    # Verify that it has all the proper attributes.
    # g.trace(g.listToString(dir(obj)))
    return obj
.. @+node:ekr.20150312225028.27: *5* createClassObjectFromString
def computeClassObjectFromString (self,className,s):

    try:
        # Add the the class definition to the present environment.
        exec(s) # Security violation!

        # Get the newly created object from the locals dict.
        theClass = locals().get(className)
        return theClass

    except Exception:
        if 1: # Could be a weird kind of user error.
            g.es_print('unexpected exception in',computeProxyObject)
            g.es_exception()
        return None
.. @+node:ekr.20150312225028.28: *4* getExternalCompletions
def getExternalCompletions (self,s,p=None,language='python'):

    '''Return the completions possible at the end of string 's'.
       Return (theObject,completions):
    - theObject is None unless the last character is 's' is a period.
    - completions is the list of valid completions.'''

    c = self.c ; k = c.k
    if not p: p = c.p

    # Use a separate widget containing just s.
    self.widget = w = leoFrame.stringTextWidget(c,'compute-completions-widget')
    w.setAllText(s)

    # Scan back for the first period.
    i = len(s)-1
    # while i > 0 and s[i] != '.':
    while i > 0 and g.isWordChar(s[i]):
        i -= 1
    if s[i] == '.': i += 1
    prefix = s[i:].strip()

    # Remember the prefix, but put the insert before the period.
    w.setSelectionRange(i, len(s)-1, insert=i)

    # Init the ivars...
    self.language = p and g.scanForAtLanguage(c,p) or language
    self.tabName = ''
    old_enable = c.k.enable_autocompleter

    # Get the completions.
    try:
        c.k.enable_autocompleter = True
        self.useTabs = False
        self.start(prefix=prefix)
    finally:
        c.k.enable_autocompleter = old_enable
        self.useTabs = True

    theObject,tabList = self.theObject,self.tabList
    self.exit() # Not called from the autocompleter itself.
    return theObject,tabList
.. @+node:ekr.20150312225028.127: *3* 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.20150312225028.29: *3* leoViews stuff (keep)
This was a major project, now abandoned.
.. @+node:ekr.20150312225028.31: *4* 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.20150312225028.32: *4* class ViewController
class ViewController:
    << docstring >>
    @others
.. @+node:ekr.20150312225028.33: *5*  << 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.20150312225028.34: *5*  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.20150312225028.35: *5* vc.Entry points
.. @+node:ekr.20150312225028.36: *6* 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.20150312225028.37: *7* 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.20150312225028.38: *8* 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.20150312225028.39: *8* 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.20150312225028.40: *8* 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.20150312225028.41: *8* 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.20150312225028.42: *8* 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.20150312225028.43: *6* 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.20150312225028.44: *7* 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.20150312225028.45: *6* 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.20150312225028.46: *6* 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.20150312225028.47: *7* 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.20150312225028.48: *7* 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.20150312225028.49: *6* 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.20150312225028.50: *7* 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.20150312225028.51: *7* 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.20150312225028.52: *7* 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.20150312225028.53: *7* 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.20150312225028.54: *7* 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.20150312225028.55: *5* vc.Main Lines
.. @+node:ekr.20150312225028.56: *6* 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.20150312225028.57: *7* 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.20150312225028.58: *7* 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.20150312225028.59: *8* 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.20150312225028.60: *8* 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.20150312225028.61: *8* 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.20150312225028.62: *7* 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.20150312225028.63: *7* 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.20150312225028.64: *8* 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.20150312225028.65: *7* 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.20150312225028.66: *7* 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.20150312225028.67: *6* 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.20150312225028.68: *7* 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.20150312225028.69: *7* 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.20150312225028.70: *7* 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.20150312225028.71: *7* 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.20150312225028.72: *7* 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.20150312225028.73: *7* 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.20150312225028.74: *7* 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.20150312225028.75: *7* 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.20150312225028.76: *7* 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.20150312225028.77: *7* 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.20150312225028.78: *7* 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.20150312225028.79: *7* 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.20150312225028.80: *6* 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.20150312225028.81: *7* 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.20150312225028.82: *7* 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.20150312225028.83: *7* 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.20150312225028.84: *5* vc.Helpers
.. @+node:ekr.20150312225028.85: *6* 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.20150312225028.86: *6* 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.20150312225028.87: *6* vc.comments...
.. @+node:ekr.20150312225028.88: *7* 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.20150312225028.89: *7* 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.20150312225028.90: *7* 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.20150312225028.91: *7* 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.20150312225028.92: *7* 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.20150312225028.93: *7* 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.20150312225028.94: *6* vc.find...
# The find commands create the node if not found.
.. @+node:ekr.20150312225028.95: *7* 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.20150312225028.96: *7* 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.20150312225028.97: *7* 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.20150312225028.98: *7* 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.20150312225028.99: *7* 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.20150312225028.100: *7* 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.20150312225028.101: *7* 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.20150312225028.102: *7* 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.20150312225028.103: *7* 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.20150312225028.104: *6* vc.has...
# The has commands return None if the node does not exist.
.. @+node:ekr.20150312225028.105: *7* 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.20150312225028.106: *7* 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.20150312225028.107: *7* 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.20150312225028.108: *7* 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.20150312225028.109: *7* 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.20150312225028.110: *6* vc.is...
.. @+node:ekr.20150312225028.111: *7* 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.20150312225028.112: *7* 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.20150312225028.113: *7* 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.20150312225028.114: *6* vc.testing...
.. @+node:ekr.20150312225028.115: *7* 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.20150312225028.116: *7* 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.20150312225028.117: *7* 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.20150312225028.118: *7* 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.20150312225028.119: *6* vc.unls...
.. @+node:ekr.20150312225028.120: *7* 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.20150312225028.121: *7* 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.20150312225028.122: *7* 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.20150312225028.123: *7* 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.20150312225028.124: *7* 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.20150312225028.125: *7* vc.unl_tail
def unl_tail(self,unl):
    '''Return the last part of a unl.'''
    return unl.split('-->')[:-1][0]
.. @+node:ekr.20150312225028.126: *4* 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.20150312225028.512: *3* QueryReplaceCommandsClass (limited to single node)
class QueryReplaceCommandsClass (baseEditCommandsClass):

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

    @others
.. @+node:ekr.20150312225028.513: *4*  ctor & init (QueryReplaceCommandsClass)
def __init__ (self,c):

    baseEditCommandsClass.__init__(self,c) # init the base class.
    self.regexp = False # True: do query-replace-regexp.  Set in stateHandler.

def init (self):

    self.qQ = None
    self.qR = None
    self.replaced = 0 # The number of replacements.
.. @+node:ekr.20150312225028.514: *4*  getPublicCommands
def getPublicCommands (self):

    return {
        'query-replace':        self.queryReplace,
        'query-replace-regex':  self.queryReplaceRegex,
    }
.. @+node:ekr.20150312225028.515: *4* Entry points
def queryReplace (self,event):

    '''Interactively find and replace text.
    This is not recommended: Leo's other find and change commands are more capable.'''
    self.regexp = False
    self.stateHandler(event)

def queryReplaceRegex (self,event):
    '''Interactively find and replace text using regular expressions.
    This is not recommended: Leo's other find and change commands are more capable.'''
    self.regexp = True
    self.stateHandler(event)
.. @+node:ekr.20150312225028.516: *4* Helpers
.. @+node:ekr.20150312225028.517: *5* doOneReplace
def doOneReplace (self,event):

    w = self.editWidget(event)
    if not w: return

    i = w.tag_ranges('qR')
    w.delete(i[0],i[1])
    ins = w.getInsertPoint()
    w.insert(ins,self.qR)
    self.replaced += 1
.. @+node:ekr.20150312225028.518: *5* findNextMatch (query-replace)
def findNextMatch (self,event):

    '''Find the next match and select it.
    Return True if a match was found.
    Otherwise, call quitSearch and return False.'''

    k = self.k
    w = self.editWidget(event)
    if not w: return

    if g.app.gui.guiName() != 'tkinter':
        return g.es('command not ready yet',color='blue')

    w.tag_delete('qR')
    if self.regexp:
        << handle regexp >>
    else:
        << handle plain search >>
.. @+node:ekr.20150312225028.519: *6* << handle regexp >>
try:
    regex = re.compile(self.qQ)
except Exception:
    self.quitSearch(event,'Illegal regular expression')
    return False

i = w.getInsertPoint()
txt = w.get(i,'end')
match = regex.search(txt)

if match:
    start = match.start()
    end = match.end()
    length = end - start
    i = w.getInsertPoint()
    w.setInsertPoint(i+start)
    w.tag_add('qR','insert','insert +%sc' % length)
    w.tag_config('qR',background='lightblue')
    i = w.getInsertPoint()
    txt = w.get(i,i+length)
    return True
else:
    self.quitSearch(event)
    return False
.. @+node:ekr.20150312225028.520: *6* << handle plain search >> (tag_add & tag_config) LATER
i = w.search(self.qQ,'insert',stopindex='end')

if i:
    w.setInsertPoint(i)
    w.tag_add('qR','insert','insert +%sc' % len(self.qQ))
    w.tag_config('qR',background='lightblue')
    return True
else:
    self.quitSearch(event)
    return False
.. @+node:ekr.20150312225028.521: *5* getUserResponse
def getUserResponse (self,event):

    w = self.editWidget(event)
    char = event and event.char or ''
    
    if not w or not char return

    if char in ('Y','y'):
        self.doOneReplace(event)
        if not self.findNextMatch(event):
            self.quitSearch(event)
    elif char in ('Q','q','\n','Return'):
        self.quitSearch(event)
    elif char == '!':
        while self.findNextMatch(event):
            self.doOneReplace(event)
    elif char in ('N','n','Delete'):
        # Skip over the present match.
        i = w.getInsertPoint()
        w.setInsertPoint(i + len(self.qQ))
        if not self.findNextMatch(event):
            self.quitSearch(event)

    w.seeInsertPoint()
.. @+node:ekr.20150312225028.522: *5* quitSearch
def quitSearch (self,event,message=None):

    k = self.k
    w = self.editWidget(event)
    if not w: return

    w.tag_delete('qR')
    k.clearState()
    if message is None:
        message = 'Replaced %d occurences' % self.replaced
    k.setLabelGrey(message)
.. @+node:ekr.20150312225028.523: *5* stateHandler
def stateHandler (self,event):

    k = self.k ; state = k.getState('query-replace')

    prompt = g.choose(self.regexp,'Query replace regexp','Query replace')

    if state == 0: # Get the first arg.
        self.init()
        k.setLabelBlue(prompt + ': ',protect=True)
        k.getArg(event,'query-replace',1,self.stateHandler)
    elif state == 1: # Get the second arg.
        self.qQ = k.arg
        if len(k.arg) > 0:
            prompt = '%s %s with: ' % (prompt,k.arg)
            k.setLabelBlue(prompt)
            k.getArg(event,'query-replace',2,self.stateHandler)
        else:
            k.resetLabel()
            k.clearState()
    elif state == 2: # Set the prompt and find the first match.
        self.qR = k.arg # Null replacement arg is ok.
        k.setLabelBlue('Query replacing %s with %s\n' % (self.qQ,self.qR) +
            'y: replace, (n or Delete): skip, !: replace all, (q or Return): quit',
            protect=True)
        k.setState('query-replace',3,self.stateHandler)
        self.findNextMatch(event)
    elif state == 3:
        self.getUserResponse(event)
.. @+node:ekr.20150312225028.128: *3* STC stuff (keep)
.. @+node:ekr.20150312225028.129: *4*  Deduction stuff
.. @+node:ekr.20150312225028.130: *5* 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.20150312225028.131: *6*  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.20150312225028.132: *6*  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.20150312225028.133: *6* dt.Contexts
.. @+node:ekr.20150312225028.134: *7* 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.20150312225028.135: *7* 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.20150312225028.136: *7* dt.Module
def do_Module (self,tree):

    for z in tree.body:
        self.visit(z)
.. @+node:ekr.20150312225028.137: *6* dt.Operands
.. @+node:ekr.20150312225028.138: *7* 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.20150312225028.139: *7* dt.bool
# Python 2.x only.
def do_bool(self,tree):
    pass
    
.. @+node:ekr.20150312225028.140: *7* dt.Bytes
# Python 3.x only.
def do_Bytes(self,tree):
    pass

.. @+node:ekr.20150312225028.141: *7* 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.20150312225028.142: *7* 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.20150312225028.143: *7* 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.20150312225028.144: *7* dt.Ellipsis
def do_Ellipsis(self,tree):
    pass

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

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

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

    self.visit(tree.value)

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

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

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

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

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

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

    self.visit(tree.elt)

    for z in tree.generators:
        self.visit(z)
        
.. @+node:ekr.20150312225028.151: *7* 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.20150312225028.152: *7* dt.Num
def do_Num(self,tree):
    pass

.. @+node:ekr.20150312225028.153: *7* 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.20150312225028.154: *7* dt.Str
def do_Str (self,tree):
    '''This represents a string constant.'''
    pass
.. @+node:ekr.20150312225028.155: *7* dt.Subscript
def do_Subscript(self,tree):

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

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

    for z in tree.elts:
        self.visit(z)
    self.visit(tree.ctx)
.. @+node:ekr.20150312225028.157: *6* dt.Statements
.. @+node:ekr.20150312225028.158: *7* 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.20150312225028.159: *7* 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.20150312225028.160: *7* 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.20150312225028.161: *7* 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.20150312225028.162: *7* dt.Global
def do_Global(self,tree):

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

    pass
.. @+node:ekr.20150312225028.164: *7* dt.ImportFrom
def do_ImportFrom(self,tree):
    
    pass
.. @+node:ekr.20150312225028.165: *7* 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.20150312225028.166: *7* 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.20150312225028.167: *7* 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.20150312225028.168: *5* 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.20150312225028.169: *5* 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.20150312225028.170: *5* e.is_known
def is_known (self):
    
    '''return True if this is a known symbol.'''
    
    return len(self.vals) == 1
.. @+node:ekr.20150312225028.171: *4*  Inference-related classes
.. @+node:ekr.20150312225028.172: *5* 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.20150312225028.173: *6* 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.20150312225028.174: *6* 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.20150312225028.175: *6* ct.traversers
.. @+node:ekr.20150312225028.176: *7* 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.20150312225028.177: *7* 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.20150312225028.178: *6* ct.visitors
.. @+node:ekr.20150312225028.179: *7* 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.20150312225028.180: *7* 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.20150312225028.181: *5* 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.20150312225028.182: *6* 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.20150312225028.183: *6* 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.20150312225028.184: *5* class Context & subclasses
<< define class Context >>

@others
.. @+node:ekr.20150312225028.185: *6* << define class Context >>
class Context:

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

    @others
.. @+node:ekr.20150312225028.186: *7*  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.20150312225028.187: *7* 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.20150312225028.188: *7* 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.20150312225028.189: *7* cx.__repr__ & __str__
def __repr__ (self):

    return 'Cx:id(%s)' % id(self)
    
__str__ = __repr__
.. @+node:ekr.20150312225028.190: *7* 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.20150312225028.191: *7* 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.20150312225028.192: *7* 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.20150312225028.193: *7* 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.20150312225028.194: *7* cx.generators & getters
# Unlike in leoInspect, most of these getters return lists of Statement objects.
.. @+node:ekr.20150312225028.195: *8* 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.20150312225028.196: *8* 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.20150312225028.197: *8* 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.20150312225028.198: *8* 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.20150312225028.199: *8* 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.20150312225028.200: *8* 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.20150312225028.201: *8* cx.classes
def classes (self):
    
    result = []
    for cx in self.contexts():
        result.extend(cx.classes_list)
    return result
.. @+node:ekr.20150312225028.202: *8* 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.20150312225028.203: *9* 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.20150312225028.204: *8* cx.defs
def defs (self):
    
    result = []
    for cx in self.contexts():
        result.extend(cx.defs_list)
    return result
.. @+node:ekr.20150312225028.205: *8* 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.20150312225028.206: *8* 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.20150312225028.207: *8* 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.20150312225028.208: *8* 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.20150312225028.209: *9* 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.20150312225028.210: *8* 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.20150312225028.211: *8* 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.20150312225028.212: *7* cx.line_number (not used)
# def line_number (self):
    
    # return self.tree_ptr.lineno
.. @+node:ekr.20150312225028.213: *7* 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.20150312225028.214: *6* class ClassContext
class ClassContext (Context):

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

.. @+node:ekr.20150312225028.215: *7* 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.20150312225028.216: *7* 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.20150312225028.217: *7* 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.20150312225028.218: *6* class DefContext
class DefContext (Context):

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

    
.. @+node:ekr.20150312225028.219: *7* 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.20150312225028.220: *7* 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.20150312225028.221: *7* 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.20150312225028.222: *6* 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.20150312225028.223: *6* 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.20150312225028.224: *6* 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.20150312225028.225: *5* 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.20150312225028.226: *6* 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.20150312225028.227: *7* 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.20150312225028.228: *6* 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.20150312225028.229: *6* 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.20150312225028.230: *6* 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.20150312225028.231: *6* 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.20150312225028.232: *6* 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.20150312225028.233: *7* 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.20150312225028.234: *7* 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.20150312225028.235: *5* class Pass1 (AstFullTraverser)
class Pass1 (AstFullTraverser):
    
    ''' 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.20150312225028.236: *6*  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.20150312225028.237: *6*  p1.run (entry point)
def run (self,root):

    self.visit(root)
.. @+node:ekr.20150312225028.238: *6*  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.20150312225028.239: *6* p1.helpers
.. @+node:ekr.20150312225028.240: *7* 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.20150312225028.241: *7* 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.20150312225028.242: *7* 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.20150312225028.243: *7* 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.20150312225028.244: *7* 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.20150312225028.245: *6* p1.visitors
.. @+node:ekr.20150312225028.246: *7* 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.20150312225028.247: *7* 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.20150312225028.248: *7* 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.20150312225028.249: *7* 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.20150312225028.250: *7* 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.20150312225028.251: *7* 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.20150312225028.252: *7* 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.20150312225028.253: *7* 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.20150312225028.254: *7* 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.20150312225028.255: *7* 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.20150312225028.256: *7* 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.20150312225028.257: *7* p1.Interactive
def do_Interactive(self,node):
    
    assert False,'Interactive context not supported'
.. @+node:ekr.20150312225028.258: *7* 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.20150312225028.259: *7* 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.20150312225028.260: *7* 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.20150312225028.261: *7* 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.20150312225028.262: *7* 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.20150312225028.263: *8* 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.20150312225028.264: *7* 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.20150312225028.265: *5* class Resolver (keep for now)
class Resolver:
    
    '''A class controlling the resolution pattern matchers.'''

    @others
.. @+node:ekr.20150312225028.266: *6*  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.20150312225028.267: *6*  r.generators
.. @+node:ekr.20150312225028.268: *7* 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.20150312225028.269: *7* 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.20150312225028.270: *7* r.modules
def modules (self):
    
    d = self.sd.modules_dict
    for fn in sorted(d.keys()):
        m = d.get(fn)
        yield m
.. @+node:ekr.20150312225028.271: *7* 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.20150312225028.272: *7* 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.20150312225028.273: *6* 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.20150312225028.274: *7* 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.20150312225028.275: *7* 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.20150312225028.276: *7* 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.20150312225028.277: *7* 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.20150312225028.278: *7* 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.20150312225028.279: *7* 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.20150312225028.280: *8* Do-nothings (not used at present)
if 0:
    @others
.. @+node:ekr.20150312225028.281: *9* r.Arg
def do_Arg (self,op):
    
    # arg = op.arg
    pass
.. @+node:ekr.20150312225028.282: *9* 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.20150312225028.283: *9* r.AugAssign
def do_AugAssign(self,op):
    
    # This does not define any value!
    pass
.. @+node:ekr.20150312225028.284: *9* r.Keyword
def do_Keyword(self,op):
    
    # arg   = op.arg
    # value = op.value
    pass
.. @+node:ekr.20150312225028.285: *8* Known types
.. @+node:ekr.20150312225028.286: *9* r.Bytes
def do_Bytes(self,op):

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

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

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

    s = op.s
    # g.trace(s)
    
.. @+node:ekr.20150312225028.291: *9* r.Tuple
def do_Tuple (self,op):
    
    elts = op.elements
    # g.trace(elts)
.. @+node:ekr.20150312225028.292: *8* Names & Builtins
.. @+node:ekr.20150312225028.293: *9* r.Builtin
def do_Builtin(self,op):
    
    name = op.name
    # g.trace(name)
.. @+node:ekr.20150312225028.294: *9* r.Name
def do_Name(self,op):
    
    name = op.name
    # g.trace(name)
.. @+node:ekr.20150312225028.295: *8* Not ready yet
.. @+node:ekr.20150312225028.296: *9* r.Comprehension
def do_Comprehension(self,op):

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

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

    value  = op.value
    slice_ = op.slice_
    # g.trace(value,slice_)
.. @+node:ekr.20150312225028.302: *8* Operators
.. @+node:ekr.20150312225028.303: *9* r.Attribute
def do_Attribute (self,op):
    
    value = op.value
    attr  = op.attr
    # g.trace(attr,value)
.. @+node:ekr.20150312225028.304: *9* 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.20150312225028.305: *9* r.BoolOp
def do_BoolOp(self,op):
    
    name   = op.op_name
    values = op.values
    # g.trace(name,values)
.. @+node:ekr.20150312225028.306: *9* 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.20150312225028.307: *9* r.CompareOp
def do_CompareOp(self,op):

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

    test   = op.test
    body   = op.body
    orelse = op.orelse
    # g.trace(test,body,orelse)
.. @+node:ekr.20150312225028.309: *9* r.UnaryOp
def do_UnaryOp(self,op):
    
    name    = op.op_name
    operand = op.operand
    # g.trace(name,operand)
.. @+node:ekr.20150312225028.310: *8* 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.20150312225028.311: *8* r.do_nothing
def do_nothing(self,op):
    pass
    
    # g.trace(op)
.. @+node:ekr.20150312225028.312: *6* The hard part
.. @+node:ekr.20150312225028.313: *7* 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.20150312225028.314: *7* r.analyze_calls (to do)
def analyze_calls (self):
    
    pass
.. @+node:ekr.20150312225028.315: *7* 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.20150312225028.316: *7* 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.20150312225028.317: *7* 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.20150312225028.318: *8* 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.20150312225028.319: *7* 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.20150312225028.320: *7* r.resolve_aliases (will be removed)
def resolve_aliases (self):
    
    r = self
.. @+node:ekr.20150312225028.321: *5* 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.20150312225028.322: *6* 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.20150312225028.323: *6* 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.20150312225028.324: *6* 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.20150312225028.325: *6* 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.20150312225028.326: *6* ti.run (entry point)
def run (self,root):
    
    self.init()
    self.visit(root)
.. @+node:ekr.20150312225028.327: *6* 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.20150312225028.328: *6* 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.20150312225028.329: *6* ti.visitors
.. @+node:ekr.20150312225028.330: *7* ti.expressions
.. @+node:ekr.20150312225028.331: *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 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.20150312225028.332: *9* 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.20150312225028.333: *8* 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.20150312225028.334: *8* ti.BoolOp
def do_BoolOp(self,node):

    ti = self    
    return [ti.bool_type]
.. @+node:ekr.20150312225028.335: *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 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.20150312225028.336: *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 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.20150312225028.337: *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 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.20150312225028.338: *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 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.20150312225028.339: *9* 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.20150312225028.340: *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 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.20150312225028.341: *10* 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.20150312225028.342: *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 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.20150312225028.343: *10* 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.20150312225028.344: *8* 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.20150312225028.345: *8* 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.20150312225028.346: *8* ti.Expr
# Expr(expr value)

def do_Expr(self,node):
    
    ti = self
    t = ti.visit(node.value)
    return t
.. @+node:ekr.20150312225028.347: *8* 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.20150312225028.348: *8* 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.20150312225028.349: *8* ti.Index
def do_Index(self,node):

    ti = self    
    return ti.visit(node.value)
.. @+node:ekr.20150312225028.350: *8* ti.Lambda
def do_Lambda (self,node):
    
    ti = self
    return ti.visit(node.body)
.. @+node:ekr.20150312225028.351: *8* 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.20150312225028.352: *8* 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.20150312225028.353: *8* 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.20150312225028.354: *8* 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.20150312225028.355: *8* 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.20150312225028.356: *7* ti.primitive Types
.. @+node:ekr.20150312225028.357: *8* ti.Builtin
def do_Builtin(self,node):

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

    ti = self
    return [ti.bytes_type]
.. @+node:ekr.20150312225028.359: *8* 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.20150312225028.360: *8* 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.20150312225028.361: *8* 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.20150312225028.362: *8* ti.Str
def do_Str(self,node):
    
    '''This represents a string constant.'''

    ti = self
    return [ti.string_type]
.. @+node:ekr.20150312225028.363: *8* 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.20150312225028.364: *7* ti.statements
.. @+node:ekr.20150312225028.365: *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.20150312225028.366: *8* 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.20150312225028.367: *8* ti.ClassDef (could be default)
def do_ClassDef(self,node):
    
    ti = self
    for z in node.body:
        self.visit(z)
.. @+node:ekr.20150312225028.368: *8* 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.20150312225028.369: *8* 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.20150312225028.370: *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 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.20150312225028.371: *9* 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.20150312225028.372: *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,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.20150312225028.373: *8* ti.Import (not used)
# def do_Import(self,node):
    
    # pass
.. @+node:ekr.20150312225028.374: *8* ti.ImportFrom (not used)
# def do_ImportFrom(self,node):
    
    # pass
.. @+node:ekr.20150312225028.375: *8* 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.20150312225028.376: *9* 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.20150312225028.377: *8* 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.20150312225028.378: *5* class TypeInferer (AstTraverser)
class TypeInferer (AstTraverser):
    
    '''
    This class infers the types of objects.
    
    See the documentation for complete details.
    '''
    
    @others
.. @+node:ekr.20150312225028.379: *6*  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.20150312225028.380: *6*  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.20150312225028.381: *6* ti.caches
# Note: the hash_ argument to ti.get_call_cache can't easily be removed.
.. @+node:ekr.20150312225028.382: *7* 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.20150312225028.383: *7* 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.20150312225028.384: *7* 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.20150312225028.385: *7* 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.20150312225028.386: *7* 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.20150312225028.387: *7* 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.20150312225028.388: *7* 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.20150312225028.389: *6* 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.20150312225028.390: *6* ti.helpers
.. @+node:ekr.20150312225028.391: *7* 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.20150312225028.392: *7* 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.20150312225028.393: *7* 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.20150312225028.394: *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.20150312225028.395: *6* 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.20150312225028.396: *6* ti.traversers
.. @+node:ekr.20150312225028.397: *7*  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.20150312225028.398: *7*  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.20150312225028.399: *7*  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.20150312225028.400: *6* ti.visitors
.. @+node:ekr.20150312225028.401: *7* 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.20150312225028.402: *7* 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.20150312225028.403: *7* 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.20150312225028.404: *8* 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.20150312225028.405: *7* ti.Builtin
def do_Builtin(self,node):
    
    assert False,node
.. @+node:ekr.20150312225028.406: *7* 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.20150312225028.407: *8* 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.20150312225028.408: *8* 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.20150312225028.409: *8* 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.20150312225028.410: *8* 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.20150312225028.411: *9* 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.20150312225028.412: *9* 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.20150312225028.413: *9* 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.20150312225028.414: *9* 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.20150312225028.415: *7* 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.20150312225028.416: *7* 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.20150312225028.417: *7* 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.20150312225028.418: *8* 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.20150312225028.419: *8* 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.20150312225028.420: *9* 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.20150312225028.421: *7* ti.Lambda
def do_Lambda (self,node):
    
    ti = self
    return ti.visit(node.body)
.. @+node:ekr.20150312225028.422: *7* ti.operators
.. @+node:ekr.20150312225028.423: *8* 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.20150312225028.424: *8* ti.BoolOp
def do_BoolOp(self,node):

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

    ti = self    
    junk = ti.visit_children(node)
    return [ti.bool_type]
.. @+node:ekr.20150312225028.426: *8* 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.20150312225028.427: *8* ti.Expr (not used)
# def do_Expr (self,node):

    # ti = self    
    # return ti.visit(node.value)
.. @+node:ekr.20150312225028.428: *8* 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.20150312225028.429: *8* 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.20150312225028.430: *8* ti.Index (default, at present)
def do_Index(self,node):

    ti = self    
    return ti.visit(node.value)
.. @+node:ekr.20150312225028.431: *8* 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.20150312225028.432: *8* 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.20150312225028.433: *8* 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.20150312225028.434: *8* 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.20150312225028.435: *7* ti.primitive Types
.. @+node:ekr.20150312225028.436: *8* ti.Builtin
def do_Builtin(self,node):

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

.. @+node:ekr.20150312225028.437: *8* ti.Bytes
def do_Bytes(self,node):

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

    ti = self
    junk = ti.visit_children(node)
    return [Dict_Type(node)]
        ### More specific type.
.. @+node:ekr.20150312225028.439: *8* ti.List
def do_List(self,node): 
            
    ti = self
    junk = ti.visit_children(node)
    return [List_Type(node)]
.. @+node:ekr.20150312225028.440: *8* 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.20150312225028.441: *8* 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.20150312225028.442: *8* ti.Tuple
def do_Tuple (self,node):

    ti = self
    junk = ti.visit_children(node)
    return [Tuple_Type(node)]
.. @+node:ekr.20150312225028.443: *7* ti.statements
.. @+node:ekr.20150312225028.444: *8* 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.20150312225028.445: *8* ti.Import (not used)
# def do_Import(self,node):
    
    # pass
.. @+node:ekr.20150312225028.446: *8* ti.ImportFrom (not used)
# def do_ImportFrom(self,node):
    
    # pass
.. @+node:ekr.20150312225028.447: *8* 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.20150312225028.448: *9* 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.20150312225028.449: *8* ti.With
def do_With (self,node):

    ti = self
    t = ti.visit_list(node.body)
    # ti.trace(t)
    return t
.. @+node:ekr.20150312225028.450: *7* 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.20150524200357.1: *3* testing beautifier code
.. @+node:ekr.20150521113831.1: *4* @button TEST PTB
r'''The script to test AddTokensToTree class.'''
g.cls()
if c.isChanged():
    c.save()
project = None # 'leo'
<< imports >>
if project:
    # 17.1 sec. --> 17.4 --> 17.3
    # The format time is about twice the tokenize time.
    aList = leoBeautify.ProjectUtils().project_files(project)
    aList = ['@file %s' % (g.shortFileName(z).rstrip()) for z in aList]
    settings_d = {
        # 'output_string': True,
        # 'stats': True,
    }
else:
    aList = [
        'unit test: leoBeautify.py',
        # '@file leoColorizer.py',
        # '@file leoBeautify.py',
        # '@file leoCommands.py',
    ]
    small = aList[0].startswith('unit test:')
    settings_d = {
        'tidy-keep-blank-lines': True,
        'input_string': small,
        # 'input_lines':  True,
        # 'input_tokens': small,
        # 'output_tokens': small,
        'output_string': small,
        'stats': not small # and len(aList) == 1,
    }
assert aList,'no input in %s' % (p.h)
<< init total stats >>
t1 = time.clock()
for h in aList:
    p2 = g.findNodeAnywhere(c,h)
    if p2:
        try:
            b = leoBeautify.test_beautifier(c,h,p2,settings_d)
            << update total stats >>
        except Exception:
            g.es_exception()
if len(aList) > 1:
    << print total stats >>
tot_time = time.clock()-t1
if len(aList) > 1:
    print('done: %4.2f sec. = %4.2f sec./file' % (tot_time,tot_time/float(tot_files)))
else:
    print('done: %4.2f sec.' % (tot_time))
.. @+node:ekr.20150525073117.1: *5* << imports >>
import leo.core.leoBeautify as leoBeautify
import imp
import time
imp.reload(leoBeautify)
.. @+node:ekr.20150530073856.1: *5* << init total stats >>
tot_beautify_time = 0.0
tot_changed_nodes = 0
tot_check_time = 0.0
tot_files = 0
tot_input_tokens = 0
tot_output_tokens = 0
tot_parse_time = 0.0
tot_strings = 0
tot_tokenize_time = 0.0
tot_total_time = 0.0
.. @+node:ekr.20150530073906.1: *5* << update total stats >>
tot_beautify_time += b.beautify_time
tot_changed_nodes += b.n_changed_nodes
tot_check_time += b.check_time
tot_files += 1
tot_input_tokens += b.n_input_tokens
tot_output_tokens += b.n_output_tokens
tot_parse_time += b.parse_time
tot_strings += b.n_strings
tot_tokenize_time += b.tokenize_time
tot_total_time += b.total_time
.. @+node:ekr.20150530074429.1: *5* << print total stats >>
print('========== totals ==========')
print('files          %s' % tot_files)
print('changed nodes  %s' % tot_changed_nodes)
print('tokens         %s' % tot_input_tokens)
print('len(code_list) %s' % tot_output_tokens)
print('len(s)         %s' % tot_strings)
print('parse          %4.2f sec.' % tot_parse_time)
print('tokenize       %4.2f sec.' % tot_tokenize_time)
print('format         %4.2f sec.' % tot_beautify_time)
print('check          %4.2f sec.' % tot_check_time)
print('total          %4.2f sec.' % tot_total_time)
.. @+node:ekr.20150524071341.1: *4* unit test: leoBeautify.py
# Extraneous backslash causes problems.
function1("NOTE: embedded layout in @settings/@data free-layout-layout" \
          "overrides saved layout " + name)
function2(a,
          b)
function3(a, \
          b)
# Weird case: comments ends in backslash\\
# Next comment

def test():
    legend = '''\
legend:
'''
    c = self.c
.. @+node:ekr.20150601042305.1: *5* new op problems
def spam():
    pass

a = b[25]
return {}
.. @+node:ekr.20150601015905.1: *5* return test
def return_test():
    if 1: return
    while True:
        if 2: return
    if 3:
        return
.. @+node:ekr.20150531104223.1: *5* class Command
class Command:
    '''
    A global decorator for functions outside of any class.
    
    g can *not* be used anywhere in this class!
    '''

    def __init__(self, name, **kwargs):
        '''Ctor for command decorator class.'''
        self.name = name

    def __call__(self, func):
        '''Register command for all future commanders.'''
        global_commands_dict[self.name] = func
        if app:
            for c in app.commanders():
                c.k.registerCommand(self.name, shortcut=None, func=func)
        # Inject ivars for plugins_menu.py.
        func.is_command = True
        func.command_name = self.name
        return func

command = Command
.. @+node:ekr.20150531060949.1: *5* comments
# Comments before class

class aClass:
    pass

pass # trailing comment.
    # indented comment.
# Comments before def.

def spam():
    pass
.. @+node:ekr.20150531054341.1: *5* * and ** args
def spam(a, *args, **keys):
    pass

a = (2 ** 3)
b = (4 * 5)
.. @+node:ekr.20150531052201.1: *5* indented arg lists
foo(a,
     b=2)
foo(a,
    b=2)

def spam(
    c=2,
    d=3,
):
    pass
.. @+node:ekr.20150529183213.1: *5* continued args
foo(a,
     b=2 # foo 1
     # foo 2
  )

def spam(a=2,
    b=3, # spam 1
):
    pass
.. @+node:ekr.20150530182531.1: *5* comments after inner def
def spam(a=2,
    b=3, # spam 1
):

    def inner():
        pass
    # spam 2:

    pass # spam 3.
    # The dedent happens after spam3, so spam2 is over-indented.
.. @+node:ekr.20150530084744.1: *5* doc parts
def f():
    pass
@ The following could be added to the 'else' clause::
    # Accumulate everything else.
.. @+node:ekr.20150528113231.1: *5* indent after inner class
# Indent after inner class.
if QtGui:

    class aClass:
        pass

if Qsci:
    pass
.. @+node:ekr.20150528095649.1: *5* multiple dedent tokens
def get_rc_file(self):
    while True:
        if False:
            return
    foo('oops')
    return
.. @+node:ekr.20150528092108.1: *5* blank lines between classes and defs
class aClass:

    def outer(a=2, b=3):
        a = 2

        def inner():
            b = 2

        c = 3

    class innerClass:
        pass
.. @+node:ekr.20150528093928.1: *5* decorators
class aClass:

    @decr('a')
    def outer():

        @decr('b')
        def inner():
            pass

        pass

    @decr('c')
    class innerClass:
        pass
.. @+node:ekr.20150528060217.1: *5* Inner defs
def outer():
    a = 2

    def inner():
        b = 2

    c = 3
.. @+node:ekr.20150527184101.1: *5* comments
def f1():
    # Comment1, flush.
    line1 = 1
        # Comment2, hanging.
    line2 = 2
    line3 = 3 # Trailing comment.
        # Final hanging comment.
.. @+node:ekr.20150526122041.1: *5* operators
a = -b
c = -(d + e)
b = not (a and b)
c = e or f
.. @+node:ekr.20150527201950.1: *5* strings
s = 'abc \
xyz'
s2 = 'part1' 'part2'
s3 = 'a' + 'b'
.. @+node:ekr.20150527182228.1: *5* Removing blank lines
def f1():
    line1 = 1
    line2 = 2
    line3 = 3

class aClass():
    line4 = 4
    line5 = 5
.. @+node:ekr.20160119213532.1: *3* Unused bracket matching code
.. @+node:ekr.20031218072017.3189: *4* g.skip_matching_python_delims
def skip_matching_python_delims(s, i, delim1, delim2, reverse=False):
    '''
    Skip from the opening delim to the matching delim2.
    Return the index of the matching ')', or -1
    Deprecated.  Use g.MatchBrackets class instead.
    '''
    level = 0; n = len(s)
    # g.trace('delim1/2',repr(delim1),repr(delim2),'i',i,'s[i]',repr(s[i]),'s',repr(s[i-5:i+5]))
    assert(g.match(s, i, delim1))
    if reverse:
        while i >= 0:
            ch = s[i]
            if ch == delim1:
                level += 1; i -= 1
            elif ch == delim2:
                level -= 1
                if level <= 0: return i
                i -= 1
            # Doesn't handle strings and comments properly...
            else: i -= 1
    else:
        while i < n:
            progress = i
            ch = s[i]
            if ch == delim1:
                level += 1; i += 1
            elif ch == delim2:
                level -= 1
                if level <= 0: return i
                i += 1
            elif ch == '\'' or ch == '"': i = g.skip_string(s, i, verbose=False)
            elif g.match(s, i, '#'): i = g.skip_to_end_of_line(s, i)
            else: i += 1
            if i == progress: return -1
    return -1
.. @+node:ekr.20110916215321.6712: *4* g.skip_matching_c_delims
def skip_matching_c_delims(s, i, delim1, delim2, reverse=False):
    '''Skip from the opening delim to the matching delim2.

    Return the index of the matching ')', or -1
    '''
    level = 0
    assert(g.match(s, i, delim1))
    if reverse:
        # Reverse scanning is tricky.
        # This doesn't handle single-line comments properly.
        while i >= 0:
            progress = i
            ch = s[i]
            if ch == delim1:
                level += 1; i -= 1
            elif ch == delim2:
                level -= 1
                if level <= 0: return i - 1
                i -= 1
            elif ch in ('\'', '"'):
                i -= 1
                while i >= 0:
                    if s[i] == ch and not s[i - 1] == '\\':
                        i -= 1; break
                    else:
                        i -= 1
            elif g.match(s, i, '*/'):
                i += 2
                while i >= 0:
                    if g.match(s, i, '/*'):
                        i -= 2
                        break
                    else:
                        i -= 1
            else: i -= 1
            if i == progress:
                g.trace('oops: reverse')
                return -1
    else:
        while i < len(s):
            progress = i
            ch = s[i]
            # g.trace(i,repr(ch))
            if ch == delim1:
                level += 1; i += 1
            elif ch == delim2:
                level -= 1; i += 1
                if level <= 0: return i
            elif ch in ('\'', '"'):
                i += 1
                while i < len(s):
                    if s[i] == ch and not s[i - 1] == '\\':
                        i += 1; break
                    else:
                        i += 1
            elif g.match(s, i, '//'):
                i = g.skip_to_end_of_line(s, i + 2)
            elif g.match(s, i, '/*'):
                i += 2
                while i < len(s):
                    if g.match(s, i, '*/'):
                        i += 2
                        break
                    else:
                        i += 1
            else: i += 1
            if i == progress:
                g.trace('oops')
                return -1
    g.trace('not found')
    return -1
.. @+node:ekr.20150514063305.120: *4* selectToMatchingBracket (leoEditCommands) (no longer used)
# No longer used: use c.findMatchingBracket instead.
@cmd('select-to-matching-bracket')
def selectToMatchingBracket(self, event):
    '''Select text that matches the bracket near the cursor.'''
    c = self.c
    w = self.editWidget(event)
    if not w: return
    i = w.getInsertPoint()
    s = w.getAllText()
    allBrackets = self.openBracketsList + self.closeBracketsList
    if i < len(s) and s[i] in allBrackets:
        ch = s[i]
    elif i > 0 and s[i - 1] in allBrackets:
        i -= 1
        ch = s[i]
    else:
        g.es('no bracket selected')
        return
    d = {}
    if ch in self.openBracketsList:
        for z in range(len(self.openBracketsList)):
            d[self.openBracketsList[z]] = self.closeBracketsList[z]
        reverse = False # Search forward
    else:
        for z in range(len(self.openBracketsList)):
            d[self.closeBracketsList[z]] = self.openBracketsList[z]
        reverse = True # Search backward
    delim2 = d.get(ch)
    # This should be generalized...
    language = g.findLanguageDirectives(c, c.p)
    if language in ('c', 'cpp', 'csharp'):
        j = g.skip_matching_c_delims(s, i, ch, delim2, reverse=reverse)
    else:
        j = g.skip_matching_python_delims(s, i, ch, delim2, reverse=reverse)
    # g.trace(i,j,ch,delim2,reverse,language)
    if j not in (-1, i):
        if reverse:
            i += 1
            j += 1
        w.setSelectionRange(i, j, insert=j)
            # 2011/11/21: Bug fix: was ins=j.
        w.see(j)
.. @+node:ekr.20060627080947: *4* skip_matching_python_parens (no longer used)
def skip_matching_python_parens(s, i):
    '''Skip from the opening ( to the matching ).

    Return the index of the matching ')', or -1
    '''
    # Deprecated: No longer used in Leo's core.
    return skip_matching_python_delims(s, i, '(', ')')
.. @+node:ekr.20110605121601.18020: *3* lqtb.event handlers (not used)
.. @+node:ekr.20110605121601.18021: *4* lqtb.mousePress/ReleaseEvent
# def mousePressEvent (self,event):
    # QtWidgets.QTextBrowser.mousePressEvent(self,event)

def mouseReleaseEvent(self, *args, **keys):
    '''Handle a mouse release event in a LeoQTextBrowser.'''
    g.trace('LeoQTextBrowser', args, keys)
    if len(args) == 1:
        event = args[0]
        self.onMouseUp(event)
        QtWidgets.QTextBrowser.mouseReleaseEvent(self, event)
    elif len(args) == 2:
        event = args[1]
        QtWidgets.QTextBrowser.mouseReleaseEvent(self, *args)
    else:
        g.trace('can not happen')
        return
.. @+node:ekr.20110605121601.18022: *4* lqtb.onMouseUp
def onMouseUp(self, event=None):
    # Open the url on a control-click.
    g.trace('(LeoQTextBrowser)', event)
    if QtCore.Qt.ControlModifier & event.modifiers():
        event = {'c': self.leo_c}
        g.openUrlOnClick(event)
.. @+node:ekr.20100701112151.5959: *3* getDiff
def getDiff(self, s1, s2):
    lines1 = g.splitLines(s1)
    lines2 = g.splitLines(s2)
    diffLines = difflib.Differ().compare(lines1, lines2)
    return diffLines
.. @+node:ekr.20160328145029.1: *3* ileo.show_result (no longer used)
def show_result(self, result):
    '''Show the result, an IPython.core.interactiveshell.ExecutionResult.'''
    # sys.stderr writes to Qt console.
    # g.es_print writes to console window, if any.
    
    ############ All we had to do was sys.stdout.flush() ###########
    
    def put(s):
        # g.trace(s.__class__.__name__, isinstance(s, Exception))
        sys.stderr.write(repr(s).rstrip()+'\n')
            # This seems to be the best that can be done.
        sys.stderr.flush()

    if result.error_before_exec:
        put(result.error_before_exec)
    elif result.error_in_exec:
        put(result.error_in_exec)
    elif result.result:
        put('Result: %s' % result.result)
.. @+node:ekr.20120208064440.10148: *3* class ModeController
class ModeController:

    def __init__(self, c):
        self.c = c
        self.d = {} # Keys are command names, values are modes.
        self.k = c.k
        g.trace(self)

    def __repr__(self):
        return '<ModeController %s>' % self.c.shortFileName()

    __str__ = __repr__
    @others
.. @+node:ekr.20120208064440.10161: *4* addModeCommands (ModeController)
def addModeCommands(self):
    g.trace(self, self.d)
    for mode in self.d.values():
        mode.createModeCommand()
.. @+node:ekr.20120208064440.10163: *4* getMode (ModeController)
def getMode(self, modeName):
    g.trace(self)
    mode = self.d.get(modeName)
    g.trace(modeName, mode)
    return mode
.. @+node:ekr.20120208064440.10164: *4* makeMode (ModeController)
def makeMode(self, name, aList):
    mode = ModeInfo(self.c, name, aList)
    g.trace(self, mode.name, mode)
    self.d[mode.name] = mode
.. @+node:ekr.20160424035115.1: *3* << old get_splitter* >> (FreeLayoutController)
### OLD CODE
def get_secondary_splitter(self):
    '''Return the secondary splitter".'''
    return self.get_splitter_by_name('secondary_splitter')
    
def get_main_splitter(self):
    '''Return main splitter".'''
    return self.get_splitter_by_name('main_splitter')

def get_splitter_by_name(self, name):
    '''Return the splitter with the given objectName().'''
    top = self.get_top_splitter()
    return top and top.get_splitter_by_name(name)
.. @+node:ekr.20140913054442.17863: *3* dw.onSplitter1/2Moved & helper
if g.new_splitters:
    pass
else:

    def onMainSplitterMoved(self, pos, index):
        '''Handle a moved event in the main splitter.'''
        c = self.leo_c
        w = c.free_layout.get_main_splitter()
        if w:
            c.frame.ratio = self.splitterFrac(w, pos, index)

    def onSecondarySplitterMoved(self, pos, index):
        '''Handle a moved event in the secondary splitter.'''
        c = self.leo_c
        w = c.free_layout.get_secondary_splitter()
        if w:
             c.frame.secondary_ratio = self.splitterFrac(w, pos, index)
.. @+node:ekr.20140913054442.17865: *4* dw.splitterFrac
def splitterFrac(self, splitter, pos, index):
    '''Return the ratio of pos to the total.'''
    i, j = splitter.getRange(index)
    return float(pos) / float(j - i)
.. @-all
.. @@nosearch
.. @-leo
