ipy_leo.py
332 lines
| 8.7 KiB
| text/x-python
|
PythonLexer
Ville M. Vainio
|
r996 | """ ILeo - Leo plugin for IPython | ||
ville
|
r988 | |||
""" | ||||
import IPython.ipapi | ||||
import IPython.genutils | ||||
import IPython.generics | ||||
import re | ||||
Ville M. Vainio
|
r996 | import UserDict | ||
ville
|
r988 | |||
ip = IPython.ipapi.get() | ||||
leo = ip.user_ns['leox'] | ||||
c,g = leo.c, leo.g | ||||
# will probably be overwritten by user, but handy for experimentation early on | ||||
ip.user_ns['c'] = c | ||||
ip.user_ns['g'] = g | ||||
from IPython.external.simplegeneric import generic | ||||
import pprint | ||||
Ville M. Vainio
|
r994 | def es(s): | ||
g.es(s, tabName = 'IPython') | ||||
pass | ||||
ville
|
r988 | @generic | ||
def format_for_leo(obj): | ||||
""" Convert obj to string representiation (for editing in Leo)""" | ||||
return pprint.pformat(obj) | ||||
@format_for_leo.when_type(list) | ||||
def format_list(obj): | ||||
return "\n".join(str(s) for s in obj) | ||||
Ville M. Vainio
|
r996 | attribute_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$') | ||
def valid_attribute(s): | ||||
return attribute_re.match(s) | ||||
ville
|
r988 | |||
def all_cells(): | ||||
d = {} | ||||
for p in c.allNodes_iter(): | ||||
h = p.headString() | ||||
Ville M. Vainio
|
r996 | if not valid_attribute(h): | ||
continue | ||||
d[h] = p.copy() | ||||
ville
|
r988 | return d | ||
Ville M. Vainio
|
r994 | def eval_node(n): | ||
body = n.b | ||||
if not body.startswith('@cl'): | ||||
# plain python repr node, just eval it | ||||
return ip.ev(n.b) | ||||
# @cl nodes deserve special treatment - first eval the first line (minus cl), then use it to call the rest of body | ||||
first, rest = body.split('\n',1) | ||||
Ville M. Vainio
|
r996 | tup = first.split(None, 1) | ||
# @cl alone SPECIAL USE-> dump var to user_ns | ||||
if len(tup) == 1: | ||||
val = ip.ev(rest) | ||||
ip.user_ns[n.h] = val | ||||
es("%s = %s" % (n.h, repr(val)[:20] )) | ||||
return val | ||||
cl, hd = tup | ||||
Ville M. Vainio
|
r994 | xformer = ip.ev(hd.strip()) | ||
es('Transform w/ %s' % repr(xformer)) | ||||
return xformer(rest) | ||||
ville
|
r988 | |||
Ville M. Vainio
|
r996 | class LeoNode(object, UserDict.DictMixin): | ||
ville
|
r988 | def __init__(self,p): | ||
self.p = p.copy() | ||||
def get_h(self): return self.p.headString() | ||||
def set_h(self,val): | ||||
ville
|
r990 | print "set head",val | ||
c.beginUpdate() | ||||
try: | ||||
c.setHeadString(self.p,val) | ||||
finally: | ||||
c.endUpdate() | ||||
ville
|
r988 | |||
h = property( get_h, set_h) | ||||
def get_b(self): return self.p.bodyString() | ||||
def set_b(self,val): | ||||
ville
|
r990 | print "set body",val | ||
c.beginUpdate() | ||||
try: | ||||
c.setBodyString(self.p, val) | ||||
finally: | ||||
c.endUpdate() | ||||
ville
|
r988 | |||
b = property(get_b, set_b) | ||||
Ville M. Vainio
|
r997 | def set_val(self, val): | ||
self.b = format_for_leo(val) | ||||
ville
|
r988 | |||
Ville M. Vainio
|
r994 | v = property(lambda self: eval_node(self), set_val) | ||
ville
|
r988 | |||
def set_l(self,val): | ||||
self.b = '\n'.join(val ) | ||||
l = property(lambda self : IPython.genutils.SList(self.b.splitlines()), | ||||
set_l) | ||||
def __iter__(self): | ||||
return (LeoNode(p) for p in self.p.children_iter()) | ||||
Ville M. Vainio
|
r996 | |||
def _children(self): | ||||
d = {} | ||||
for child in self: | ||||
head = child.h | ||||
tup = head.split(None,1) | ||||
if len(tup) > 1 and tup[0] == '@k': | ||||
d[tup[1]] = child | ||||
continue | ||||
if not valid_attribute(head): | ||||
d[head] = child | ||||
continue | ||||
return d | ||||
def keys(self): | ||||
d = self._children() | ||||
return d.keys() | ||||
def __getitem__(self, key): | ||||
key = str(key) | ||||
d = self._children() | ||||
return d[key] | ||||
def __setitem__(self, key, val): | ||||
key = str(key) | ||||
d = self._children() | ||||
if key in d: | ||||
d[key].v = val | ||||
return | ||||
if not valid_attribute(key): | ||||
head = key | ||||
else: | ||||
head = '@k ' + key | ||||
p = c.createLastChildNode(self.p, head, '') | ||||
LeoNode(p).v = val | ||||
def __delitem__(self,key): | ||||
pass | ||||
ville
|
r988 | |||
class LeoWorkbook: | ||||
""" class for 'advanced' node access """ | ||||
def __getattr__(self, key): | ||||
Ville M. Vainio
|
r996 | if key.startswith('_') or key == 'trait_names' or not valid_attribute(key): | ||
ville
|
r988 | raise AttributeError | ||
cells = all_cells() | ||||
p = cells.get(key, None) | ||||
if p is None: | ||||
p = add_var(key,None) | ||||
return LeoNode(p) | ||||
def __str__(self): | ||||
return "<LeoWorkbook>" | ||||
Ville M. Vainio
|
r996 | def __setattr__(self,key, val): | ||
raise AttributeError("Direct assignment to workbook denied, try wb.%s.v = %s" % (key,val)) | ||||
ville
|
r988 | __repr__ = __str__ | ||
ip.user_ns['wb'] = LeoWorkbook() | ||||
_dummyval = object() | ||||
@IPython.generics.complete_object.when_type(LeoWorkbook) | ||||
def workbook_complete(obj, prev): | ||||
return all_cells().keys() | ||||
def add_var(varname, value = _dummyval): | ||||
ville
|
r990 | c.beginUpdate() | ||
try: | ||||
Ville M. Vainio
|
r997 | p2 = g.findNodeAnywhere(c,varname) | ||
ville
|
r990 | if not c.positionExists(p2): | ||
p2 = c.currentPosition().insertAfter() | ||||
Ville M. Vainio
|
r997 | c.setHeadString(p2,varname) | ||
ville
|
r990 | |||
c.setCurrentPosition(p2) | ||||
if value is _dummyval: | ||||
val = ip.user_ns[varname] | ||||
else: | ||||
val = value | ||||
if val is not None: | ||||
formatted = format_for_leo(val) | ||||
c.setBodyString(p2,formatted) | ||||
return p2 | ||||
finally: | ||||
c.endUpdate() | ||||
ville
|
r988 | |||
def add_file(self,fname): | ||||
p2 = c.currentPosition().insertAfter() | ||||
def push_script(p): | ||||
ville
|
r990 | c.beginUpdate() | ||
try: | ||||
ohist = ip.IP.output_hist | ||||
hstart = len(ip.IP.input_hist) | ||||
script = g.getScript(c,p,useSelectedText=False,forcePythonSentinels=False,useSentinels=False) | ||||
script = g.splitLines(script + '\n') | ||||
script = ''.join(z for z in script if z.strip()) | ||||
ip.runlines(script) | ||||
has_output = False | ||||
for idx in range(hstart,len(ip.IP.input_hist)): | ||||
val = ohist.get(idx,None) | ||||
if val is None: | ||||
continue | ||||
has_output = True | ||||
inp = ip.IP.input_hist[idx] | ||||
if inp.strip(): | ||||
Ville M. Vainio
|
r994 | es('In: %s' % (inp[:40], )) | ||
ville
|
r990 | |||
Ville M. Vainio
|
r994 | es('<%d> %s' % (idx, pprint.pformat(ohist[idx],width = 40))) | ||
ville
|
r990 | |||
if not has_output: | ||||
Ville M. Vainio
|
r994 | es('ipy run: %s' %( p.headString(),)) | ||
ville
|
r990 | finally: | ||
c.endUpdate() | ||||
ville
|
r988 | |||
def eval_body(body): | ||||
try: | ||||
val = ip.ev(body) | ||||
except: | ||||
# just use stringlist if it's not completely legal python expression | ||||
val = IPython.genutils.SList(body.splitlines()) | ||||
return val | ||||
Ville M. Vainio
|
r995 | def push_variable(p,varname): | ||
try: | ||||
val = eval_node(LeoNode(p)) | ||||
except: | ||||
body = p.bodyString() | ||||
val = IPython.genutils.SList(body.splitlines()) | ||||
ville
|
r988 | ip.user_ns[varname] = val | ||
Ville M. Vainio
|
r994 | es('ipy var: %s' % (varname,)) | ||
Ville M. Vainio
|
r991 | |||
def push_plain_python(p): | ||||
script = g.getScript(c,p,useSelectedText=False,forcePythonSentinels=False,useSentinels=False) | ||||
exec script in ip.user_ns | ||||
Ville M. Vainio
|
r994 | es('ipy plain: %s' % (p.headString(),)) | ||
ville
|
r988 | |||
Ville M. Vainio
|
r991 | def push_from_leo(p): | ||
Ville M. Vainio
|
r994 | nod = LeoNode(p) | ||
Ville M. Vainio
|
r991 | h = p.headString() | ||
tup = h.split(None,1) | ||||
ville
|
r988 | # @ipy foo is variable foo | ||
if len(tup) == 2 and tup[0] == '@ipy': | ||||
varname = tup[1] | ||||
push_variable(p,varname) | ||||
return | ||||
Ville M. Vainio
|
r991 | if h.endswith('P'): | ||
push_plain_python(p) | ||||
return | ||||
Ville M. Vainio
|
r994 | if nod.b.startswith('@cl'): | ||
es(nod.v) | ||||
return | ||||
ville
|
r990 | push_script(p) | ||
return | ||||
ville
|
r988 | |||
ip.user_ns['leox'].push = push_from_leo | ||||
def leo_f(self,s): | ||||
ville
|
r990 | """ open file(s) in Leo | ||
Takes an mglob pattern, e.g. '%leo *.cpp' or %leo 'rec:*.cpp' | ||||
""" | ||||
import os | ||||
from IPython.external import mglob | ||||
files = mglob.expand(s) | ||||
c.beginUpdate() | ||||
try: | ||||
for fname in files: | ||||
p = g.findNodeAnywhere(c,'@auto ' + fname) | ||||
if not p: | ||||
p = c.currentPosition().insertAfter() | ||||
p.setHeadString('@auto ' + fname) | ||||
if os.path.isfile(fname): | ||||
c.setBodyString(p,open(fname).read()) | ||||
c.selectPosition(p) | ||||
finally: | ||||
c.endUpdate() | ||||
ville
|
r988 | |||
ip.expose_magic('leo',leo_f) | ||||
Ville M. Vainio
|
r992 | |||
def leoref_f(self,s): | ||||
import textwrap | ||||
print textwrap.dedent("""\ | ||||
%leo file - open file in leo | ||||
wb.foo.v - eval node foo (i.e. headstring is 'foo' or '@ipy foo') | ||||
wb.foo.v = 12 - assign to body of node foo | ||||
wb.foo.b - read or write the body of node foo | ||||
wb.foo.l - body of node foo as string list | ||||
for el in wb.foo: | ||||
print el.v | ||||
Ville M. Vainio
|
r993 | |||
Ville M. Vainio
|
r992 | """ | ||
) | ||||
ip.expose_magic('leoref',leoref_f) | ||||
def show_welcome(): | ||||
print "------------------" | ||||
print "Welcome to Leo-enabled IPython session!" | ||||
print "Try %leoref for quick reference." | ||||
import IPython.platutils | ||||
Ville M. Vainio
|
r994 | IPython.platutils.set_term_title('ILeo') | ||
Ville M. Vainio
|
r992 | IPython.platutils.freeze_term_title() | ||
Ville M. Vainio
|
r993 | |||
def run_leo_startup_node(): | ||||
p = g.findNodeAnywhere(c,'@ipy-startup') | ||||
if p: | ||||
print "Running @ipy-startup" | ||||
push_script(p) | ||||
run_leo_startup_node() | ||||
Ville M. Vainio
|
r992 | show_welcome() | ||
Ville M. Vainio
|
r993 | |||