##// END OF EJS Templates
ipy_leo: @ev node support, have _p (LeoNode for current pos) in user_ns on normal ipython script execution
Ville M. Vainio -
Show More
@@ -1,474 +1,486 b''
1 """ ILeo - Leo plugin for IPython
1 """ ILeo - Leo plugin for IPython
2
2
3
3
4 """
4 """
5 import IPython.ipapi
5 import IPython.ipapi
6 import IPython.genutils
6 import IPython.genutils
7 import IPython.generics
7 import IPython.generics
8 from IPython.hooks import CommandChainDispatcher
8 from IPython.hooks import CommandChainDispatcher
9 import re
9 import re
10 import UserDict
10 import UserDict
11 from IPython.ipapi import TryNext
11 from IPython.ipapi import TryNext
12
12
13
13
14 def init_ipython(ipy):
14 def init_ipython(ipy):
15 """ This will be run by _ip.load('ipy_leo')
15 """ This will be run by _ip.load('ipy_leo')
16
16
17 Leo still needs to run update_commander() after this.
17 Leo still needs to run update_commander() after this.
18
18
19 """
19 """
20 global ip
20 global ip
21 ip = ipy
21 ip = ipy
22 ip.set_hook('complete_command', mb_completer, str_key = 'mb')
22 ip.set_hook('complete_command', mb_completer, str_key = 'mb')
23 ip.expose_magic('mb',mb_f)
23 ip.expose_magic('mb',mb_f)
24 ip.expose_magic('leo',leo_f)
24 ip.expose_magic('leo',leo_f)
25 ip.expose_magic('leoref',leoref_f)
25 ip.expose_magic('leoref',leoref_f)
26 expose_ileo_push(push_cl_node,100)
26 expose_ileo_push(push_cl_node,100)
27 # this should be the LAST one that will be executed, and it will never raise TryNext
27 # this should be the LAST one that will be executed, and it will never raise TryNext
28 expose_ileo_push(push_ipython_script, 1000)
28 expose_ileo_push(push_ipython_script, 1000)
29 expose_ileo_push(push_plain_python, 100)
29 expose_ileo_push(push_plain_python, 100)
30 expose_ileo_push(push_ev_node, 100)
30 ip.user_ns['wb'] = LeoWorkbook()
31 ip.user_ns['wb'] = LeoWorkbook()
31
32
32 show_welcome()
33 show_welcome()
33
34
34
35
35 def update_commander(new_leox):
36 def update_commander(new_leox):
36 """ Set the Leo commander to use
37 """ Set the Leo commander to use
37
38
38 This will be run every time Leo does ipython-launch; basically,
39 This will be run every time Leo does ipython-launch; basically,
39 when the user switches the document he is focusing on, he should do
40 when the user switches the document he is focusing on, he should do
40 ipython-launch to tell ILeo what document the commands apply to.
41 ipython-launch to tell ILeo what document the commands apply to.
41
42
42 """
43 """
43
44
44 global c,g
45 global c,g
45 c,g = new_leox.c, new_leox.g
46 c,g = new_leox.c, new_leox.g
46 print "Set Leo Commander:",c.frame.getTitle()
47 print "Set Leo Commander:",c.frame.getTitle()
47
48
48 # will probably be overwritten by user, but handy for experimentation early on
49 # will probably be overwritten by user, but handy for experimentation early on
49 ip.user_ns['c'] = c
50 ip.user_ns['c'] = c
50 ip.user_ns['g'] = g
51 ip.user_ns['g'] = g
51 ip.user_ns['_leo'] = new_leox
52 ip.user_ns['_leo'] = new_leox
52
53
53 new_leox.push = push_position_from_leo
54 new_leox.push = push_position_from_leo
54 run_leo_startup_node()
55 run_leo_startup_node()
55
56
56 from IPython.external.simplegeneric import generic
57 from IPython.external.simplegeneric import generic
57 import pprint
58 import pprint
58
59
59 def es(s):
60 def es(s):
60 g.es(s, tabName = 'IPython')
61 g.es(s, tabName = 'IPython')
61 pass
62 pass
62
63
63 @generic
64 @generic
64 def format_for_leo(obj):
65 def format_for_leo(obj):
65 """ Convert obj to string representiation (for editing in Leo)"""
66 """ Convert obj to string representiation (for editing in Leo)"""
66 return pprint.pformat(obj)
67 return pprint.pformat(obj)
67
68
68 @format_for_leo.when_type(list)
69 @format_for_leo.when_type(list)
69 def format_list(obj):
70 def format_list(obj):
70 return "\n".join(str(s) for s in obj)
71 return "\n".join(str(s) for s in obj)
71
72
72 attribute_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
73 attribute_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
73 def valid_attribute(s):
74 def valid_attribute(s):
74 return attribute_re.match(s)
75 return attribute_re.match(s)
75
76
76 def all_cells():
77 def all_cells():
77 d = {}
78 d = {}
78 for p in c.allNodes_iter():
79 for p in c.allNodes_iter():
79 h = p.headString()
80 h = p.headString()
80 if h.startswith('@a '):
81 if h.startswith('@a '):
81 d[h.lstrip('@a ').strip()] = p.parent().copy()
82 d[h.lstrip('@a ').strip()] = p.parent().copy()
82 elif not valid_attribute(h):
83 elif not valid_attribute(h):
83 continue
84 continue
84 d[h] = p.copy()
85 d[h] = p.copy()
85 return d
86 return d
86
87
87 def eval_node(n):
88 def eval_node(n):
88 body = n.b
89 body = n.b
89 if not body.startswith('@cl'):
90 if not body.startswith('@cl'):
90 # plain python repr node, just eval it
91 # plain python repr node, just eval it
91 return ip.ev(n.b)
92 return ip.ev(n.b)
92 # @cl nodes deserve special treatment - first eval the first line (minus cl), then use it to call the rest of body
93 # @cl nodes deserve special treatment - first eval the first line (minus cl), then use it to call the rest of body
93 first, rest = body.split('\n',1)
94 first, rest = body.split('\n',1)
94 tup = first.split(None, 1)
95 tup = first.split(None, 1)
95 # @cl alone SPECIAL USE-> dump var to user_ns
96 # @cl alone SPECIAL USE-> dump var to user_ns
96 if len(tup) == 1:
97 if len(tup) == 1:
97 val = ip.ev(rest)
98 val = ip.ev(rest)
98 ip.user_ns[n.h] = val
99 ip.user_ns[n.h] = val
99 es("%s = %s" % (n.h, repr(val)[:20] ))
100 es("%s = %s" % (n.h, repr(val)[:20] ))
100 return val
101 return val
101
102
102 cl, hd = tup
103 cl, hd = tup
103
104
104 xformer = ip.ev(hd.strip())
105 xformer = ip.ev(hd.strip())
105 es('Transform w/ %s' % repr(xformer))
106 es('Transform w/ %s' % repr(xformer))
106 return xformer(rest, n)
107 return xformer(rest, n)
107
108
108 class LeoNode(object, UserDict.DictMixin):
109 class LeoNode(object, UserDict.DictMixin):
109 """ Node in Leo outline
110 """ Node in Leo outline
110
111
111 Most important attributes (getters/setters available:
112 Most important attributes (getters/setters available:
112 .v - evaluate node, can also be alligned
113 .v - evaluate node, can also be alligned
113 .b, .h - body string, headline string
114 .b, .h - body string, headline string
114 .l - value as string list
115 .l - value as string list
115
116
116 Also supports iteration,
117 Also supports iteration,
117
118
118 setitem / getitem (indexing):
119 setitem / getitem (indexing):
119 wb.foo['key'] = 12
120 wb.foo['key'] = 12
120 assert wb.foo['key'].v == 12
121 assert wb.foo['key'].v == 12
121
122
122 Note the asymmetry on setitem and getitem! Also other
123 Note the asymmetry on setitem and getitem! Also other
123 dict methods are available.
124 dict methods are available.
124
125
125 .ipush() - run push-to-ipython
126 .ipush() - run push-to-ipython
126
127
127 Minibuffer command access (tab completion works):
128 Minibuffer command access (tab completion works):
128
129
129 mb save-to-file
130 mb save-to-file
130
131
131 """
132 """
132 def __init__(self,p):
133 def __init__(self,p):
133 self.p = p.copy()
134 self.p = p.copy()
134
135
135 def __str__(self):
136 def __str__(self):
136 return "<LeoNode %s>" % str(self.p)
137 return "<LeoNode %s>" % str(self.p)
137
138
138 __repr__ = __str__
139 __repr__ = __str__
139
140
140 def __get_h(self): return self.p.headString()
141 def __get_h(self): return self.p.headString()
141 def __set_h(self,val):
142 def __set_h(self,val):
142 print "set head",val
143 print "set head",val
143 c.beginUpdate()
144 c.beginUpdate()
144 try:
145 try:
145 c.setHeadString(self.p,val)
146 c.setHeadString(self.p,val)
146 finally:
147 finally:
147 c.endUpdate()
148 c.endUpdate()
148
149
149 h = property( __get_h, __set_h, doc = "Node headline string")
150 h = property( __get_h, __set_h, doc = "Node headline string")
150
151
151 def __get_b(self): return self.p.bodyString()
152 def __get_b(self): return self.p.bodyString()
152 def __set_b(self,val):
153 def __set_b(self,val):
153 print "set body",val
154 print "set body",val
154 c.beginUpdate()
155 c.beginUpdate()
155 try:
156 try:
156 c.setBodyString(self.p, val)
157 c.setBodyString(self.p, val)
157 finally:
158 finally:
158 c.endUpdate()
159 c.endUpdate()
159
160
160 b = property(__get_b, __set_b, doc = "Nody body string")
161 b = property(__get_b, __set_b, doc = "Nody body string")
161
162
162 def __set_val(self, val):
163 def __set_val(self, val):
163 self.b = format_for_leo(val)
164 self.b = format_for_leo(val)
164
165
165 v = property(lambda self: eval_node(self), __set_val, doc = "Node evaluated value")
166 v = property(lambda self: eval_node(self), __set_val, doc = "Node evaluated value")
166
167
167 def __set_l(self,val):
168 def __set_l(self,val):
168 self.b = '\n'.join(val )
169 self.b = '\n'.join(val )
169 l = property(lambda self : IPython.genutils.SList(self.b.splitlines()),
170 l = property(lambda self : IPython.genutils.SList(self.b.splitlines()),
170 __set_l, doc = "Node value as string list")
171 __set_l, doc = "Node value as string list")
171
172
172 def __iter__(self):
173 def __iter__(self):
173 """ Iterate through nodes direct children """
174 """ Iterate through nodes direct children """
174
175
175 return (LeoNode(p) for p in self.p.children_iter())
176 return (LeoNode(p) for p in self.p.children_iter())
176
177
177 def __children(self):
178 def __children(self):
178 d = {}
179 d = {}
179 for child in self:
180 for child in self:
180 head = child.h
181 head = child.h
181 tup = head.split(None,1)
182 tup = head.split(None,1)
182 if len(tup) > 1 and tup[0] == '@k':
183 if len(tup) > 1 and tup[0] == '@k':
183 d[tup[1]] = child
184 d[tup[1]] = child
184 continue
185 continue
185
186
186 if not valid_attribute(head):
187 if not valid_attribute(head):
187 d[head] = child
188 d[head] = child
188 continue
189 continue
189 return d
190 return d
190 def keys(self):
191 def keys(self):
191 d = self.__children()
192 d = self.__children()
192 return d.keys()
193 return d.keys()
193 def __getitem__(self, key):
194 def __getitem__(self, key):
194 """ wb.foo['Some stuff'] Return a child node with headline 'Some stuff'
195 """ wb.foo['Some stuff'] Return a child node with headline 'Some stuff'
195
196
196 If key is a valid python name (e.g. 'foo'), look for headline '@k foo' as well
197 If key is a valid python name (e.g. 'foo'), look for headline '@k foo' as well
197 """
198 """
198 key = str(key)
199 key = str(key)
199 d = self.__children()
200 d = self.__children()
200 return d[key]
201 return d[key]
201 def __setitem__(self, key, val):
202 def __setitem__(self, key, val):
202 """ You can do wb.foo['My Stuff'] = 12 to create children
203 """ You can do wb.foo['My Stuff'] = 12 to create children
203
204
204 This will create 'My Stuff' as a child of foo (if it does not exist), and
205 This will create 'My Stuff' as a child of foo (if it does not exist), and
205 do .v = 12 assignment.
206 do .v = 12 assignment.
206
207
207 Exception:
208 Exception:
208
209
209 wb.foo['bar'] = 12
210 wb.foo['bar'] = 12
210
211
211 will create a child with headline '@k bar', because bar is a valid python name
212 will create a child with headline '@k bar', because bar is a valid python name
212 and we don't want to crowd the WorkBook namespace with (possibly numerous) entries
213 and we don't want to crowd the WorkBook namespace with (possibly numerous) entries
213 """
214 """
214 key = str(key)
215 key = str(key)
215 d = self.__children()
216 d = self.__children()
216 if key in d:
217 if key in d:
217 d[key].v = val
218 d[key].v = val
218 return
219 return
219
220
220 if not valid_attribute(key):
221 if not valid_attribute(key):
221 head = key
222 head = key
222 else:
223 else:
223 head = '@k ' + key
224 head = '@k ' + key
224 p = c.createLastChildNode(self.p, head, '')
225 p = c.createLastChildNode(self.p, head, '')
225 LeoNode(p).v = val
226 LeoNode(p).v = val
226
227
227 def ipush(self):
228 def ipush(self):
228 """ Does push-to-ipython on the node """
229 """ Does push-to-ipython on the node """
229 push_from_leo(self)
230 push_from_leo(self)
230
231
231 def go(self):
232 def go(self):
232 """ Set node as current node (to quickly see it in Outline) """
233 """ Set node as current node (to quickly see it in Outline) """
233 c.beginUpdate()
234 c.beginUpdate()
234 try:
235 try:
235 c.setCurrentPosition(self.p)
236 c.setCurrentPosition(self.p)
236 finally:
237 finally:
237 c.endUpdate()
238 c.endUpdate()
238
239
239 def script(self):
240 def script(self):
240 """ Method to get the 'tangled' contents of the node
241 """ Method to get the 'tangled' contents of the node
241
242
242 (parse @others, << section >> references etc.)
243 (parse @others, << section >> references etc.)
243 """
244 """
244 return g.getScript(c,self.p,useSelectedText=False,useSentinels=False)
245 return g.getScript(c,self.p,useSelectedText=False,useSentinels=False)
245
246
246 def __get_uA(self):
247 def __get_uA(self):
247 p = self.p
248 p = self.p
248 # Create the uA if necessary.
249 # Create the uA if necessary.
249 if not hasattr(p.v.t,'unknownAttributes'):
250 if not hasattr(p.v.t,'unknownAttributes'):
250 p.v.t.unknownAttributes = {}
251 p.v.t.unknownAttributes = {}
251
252
252 d = p.v.t.unknownAttributes.setdefault('ipython', {})
253 d = p.v.t.unknownAttributes.setdefault('ipython', {})
253 return d
254 return d
254
255
255 uA = property(__get_uA, doc = "Access persistent unknownAttributes of node")
256 uA = property(__get_uA, doc = "Access persistent unknownAttributes of node")
256
257
257
258
258 class LeoWorkbook:
259 class LeoWorkbook:
259 """ class for 'advanced' node access
260 """ class for 'advanced' node access
260
261
261 Has attributes for all "discoverable" nodes. Node is discoverable if it
262 Has attributes for all "discoverable" nodes. Node is discoverable if it
262 either
263 either
263
264
264 - has a valid python name (Foo, bar_12)
265 - has a valid python name (Foo, bar_12)
265 - is a parent of an anchor node (if it has a child '@a foo', it is visible as foo)
266 - is a parent of an anchor node (if it has a child '@a foo', it is visible as foo)
266
267
267 """
268 """
268 def __getattr__(self, key):
269 def __getattr__(self, key):
269 if key.startswith('_') or key == 'trait_names' or not valid_attribute(key):
270 if key.startswith('_') or key == 'trait_names' or not valid_attribute(key):
270 raise AttributeError
271 raise AttributeError
271 cells = all_cells()
272 cells = all_cells()
272 p = cells.get(key, None)
273 p = cells.get(key, None)
273 if p is None:
274 if p is None:
274 p = add_var(key)
275 p = add_var(key)
275
276
276 return LeoNode(p)
277 return LeoNode(p)
277
278
278 def __str__(self):
279 def __str__(self):
279 return "<LeoWorkbook>"
280 return "<LeoWorkbook>"
280 def __setattr__(self,key, val):
281 def __setattr__(self,key, val):
281 raise AttributeError("Direct assignment to workbook denied, try wb.%s.v = %s" % (key,val))
282 raise AttributeError("Direct assignment to workbook denied, try wb.%s.v = %s" % (key,val))
282
283
283 __repr__ = __str__
284 __repr__ = __str__
284
285
285 def __iter__(self):
286 def __iter__(self):
286 """ Iterate all (even non-exposed) nodes """
287 """ Iterate all (even non-exposed) nodes """
287 cells = all_cells()
288 cells = all_cells()
288 return (LeoNode(p) for p in c.allNodes_iter())
289 return (LeoNode(p) for p in c.allNodes_iter())
289
290
290 current = property(lambda self: LeoNode(c.currentPosition()), doc = "Currently selected node")
291 current = property(lambda self: LeoNode(c.currentPosition()), doc = "Currently selected node")
291
292
292 def match_h(self, regex):
293 def match_h(self, regex):
293 cmp = re.compile(regex)
294 cmp = re.compile(regex)
294 for node in self:
295 for node in self:
295 if re.match(cmp, node.h, re.IGNORECASE):
296 if re.match(cmp, node.h, re.IGNORECASE):
296 yield node
297 yield node
297 return
298 return
298
299
299 @IPython.generics.complete_object.when_type(LeoWorkbook)
300 @IPython.generics.complete_object.when_type(LeoWorkbook)
300 def workbook_complete(obj, prev):
301 def workbook_complete(obj, prev):
301 return all_cells().keys() + [s for s in prev if not s.startswith('_')]
302 return all_cells().keys() + [s for s in prev if not s.startswith('_')]
302
303
303
304
304 def add_var(varname):
305 def add_var(varname):
305 c.beginUpdate()
306 c.beginUpdate()
306 try:
307 try:
307 p2 = g.findNodeAnywhere(c,varname)
308 p2 = g.findNodeAnywhere(c,varname)
308 if p2:
309 if p2:
309 return
310 return
310
311
311 rootpos = g.findNodeAnywhere(c,'@ipy-results')
312 rootpos = g.findNodeAnywhere(c,'@ipy-results')
312 if not rootpos:
313 if not rootpos:
313 rootpos = c.currentPosition()
314 rootpos = c.currentPosition()
314 p2 = rootpos.insertAsLastChild()
315 p2 = rootpos.insertAsLastChild()
315 c.setHeadString(p2,varname)
316 c.setHeadString(p2,varname)
316 return p2
317 return p2
317 finally:
318 finally:
318 c.endUpdate()
319 c.endUpdate()
319
320
320 def add_file(self,fname):
321 def add_file(self,fname):
321 p2 = c.currentPosition().insertAfter()
322 p2 = c.currentPosition().insertAfter()
322
323
323 push_from_leo = CommandChainDispatcher()
324 push_from_leo = CommandChainDispatcher()
324
325
325 def expose_ileo_push(f, prio = 0):
326 def expose_ileo_push(f, prio = 0):
326 push_from_leo.add(f, prio)
327 push_from_leo.add(f, prio)
327
328
328 def push_ipython_script(node):
329 def push_ipython_script(node):
329 """ Execute the node body in IPython, as if it was entered in interactive prompt """
330 """ Execute the node body in IPython, as if it was entered in interactive prompt """
330 c.beginUpdate()
331 c.beginUpdate()
331 try:
332 try:
332 ohist = ip.IP.output_hist
333 ohist = ip.IP.output_hist
333 hstart = len(ip.IP.input_hist)
334 hstart = len(ip.IP.input_hist)
334 script = node.script()
335 script = node.script()
335
336
336 script = g.splitLines(script + '\n')
337 script = g.splitLines(script + '\n')
337
338 ip.user_ns['_p'] = node
338 ip.runlines(script)
339 ip.runlines(script)
340 del ip.user_ns['_p']
339
341
340 has_output = False
342 has_output = False
341 for idx in range(hstart,len(ip.IP.input_hist)):
343 for idx in range(hstart,len(ip.IP.input_hist)):
342 val = ohist.get(idx,None)
344 val = ohist.get(idx,None)
343 if val is None:
345 if val is None:
344 continue
346 continue
345 has_output = True
347 has_output = True
346 inp = ip.IP.input_hist[idx]
348 inp = ip.IP.input_hist[idx]
347 if inp.strip():
349 if inp.strip():
348 es('In: %s' % (inp[:40], ))
350 es('In: %s' % (inp[:40], ))
349
351
350 es('<%d> %s' % (idx, pprint.pformat(ohist[idx],width = 40)))
352 es('<%d> %s' % (idx, pprint.pformat(ohist[idx],width = 40)))
351
353
352 if not has_output:
354 if not has_output:
353 es('ipy run: %s (%d LL)' %( node.h,len(script)))
355 es('ipy run: %s (%d LL)' %( node.h,len(script)))
354 finally:
356 finally:
355 c.endUpdate()
357 c.endUpdate()
356
358
357
359
358 def eval_body(body):
360 def eval_body(body):
359 try:
361 try:
360 val = ip.ev(body)
362 val = ip.ev(body)
361 except:
363 except:
362 # just use stringlist if it's not completely legal python expression
364 # just use stringlist if it's not completely legal python expression
363 val = IPython.genutils.SList(body.splitlines())
365 val = IPython.genutils.SList(body.splitlines())
364 return val
366 return val
365
367
366 def push_plain_python(node):
368 def push_plain_python(node):
367 if not node.h.endswith('P'):
369 if not node.h.endswith('P'):
368 raise TryNext
370 raise TryNext
369 script = node.script()
371 script = node.script()
370 lines = script.count('\n')
372 lines = script.count('\n')
371 try:
373 try:
372 exec script in ip.user_ns
374 exec script in ip.user_ns
373 except:
375 except:
374 print " -- Exception in script:\n"+script + "\n --"
376 print " -- Exception in script:\n"+script + "\n --"
375 raise
377 raise
376 es('ipy plain: %s (%d LL)' % (node.h,lines))
378 es('ipy plain: %s (%d LL)' % (node.h,lines))
377
379
378
380
379 def push_cl_node(node):
381 def push_cl_node(node):
380 """ If node starts with @cl, eval it
382 """ If node starts with @cl, eval it
381
383
382 The result is put to root @ipy-results node
384 The result is put to root @ipy-results node
383 """
385 """
384 if not node.b.startswith('@cl'):
386 if not node.b.startswith('@cl'):
385 raise TryNext
387 raise TryNext
386
388
387 p2 = g.findNodeAnywhere(c,'@ipy-results')
389 p2 = g.findNodeAnywhere(c,'@ipy-results')
388 val = node.v
390 val = node.v
389 if p2:
391 if p2:
390 es("=> @ipy-results")
392 es("=> @ipy-results")
391 LeoNode(p2).v = val
393 LeoNode(p2).v = val
392 es(val)
394 es(val)
393
395
396 def push_ev_node(node):
397 """ If headline starts with @ev, eval it and put result in body """
398 if not node.h.startswith('@ev '):
399 raise TryNext
400 expr = node.h.lstrip('@ev ')
401 es('ipy eval ' + expr)
402 res = ip.ev(expr)
403 node.v = res
404
405
394
406
395
407
396 def push_position_from_leo(p):
408 def push_position_from_leo(p):
397 push_from_leo(LeoNode(p))
409 push_from_leo(LeoNode(p))
398
410
399 def leo_f(self,s):
411 def leo_f(self,s):
400 """ open file(s) in Leo
412 """ open file(s) in Leo
401
413
402 Takes an mglob pattern, e.g. '%leo *.cpp' or %leo 'rec:*.cpp'
414 Takes an mglob pattern, e.g. '%leo *.cpp' or %leo 'rec:*.cpp'
403 """
415 """
404 import os
416 import os
405 from IPython.external import mglob
417 from IPython.external import mglob
406
418
407 files = mglob.expand(s)
419 files = mglob.expand(s)
408 c.beginUpdate()
420 c.beginUpdate()
409 try:
421 try:
410 for fname in files:
422 for fname in files:
411 p = g.findNodeAnywhere(c,'@auto ' + fname)
423 p = g.findNodeAnywhere(c,'@auto ' + fname)
412 if not p:
424 if not p:
413 p = c.currentPosition().insertAfter()
425 p = c.currentPosition().insertAfter()
414
426
415 p.setHeadString('@auto ' + fname)
427 p.setHeadString('@auto ' + fname)
416 if os.path.isfile(fname):
428 if os.path.isfile(fname):
417 c.setBodyString(p,open(fname).read())
429 c.setBodyString(p,open(fname).read())
418 c.selectPosition(p)
430 c.selectPosition(p)
419 finally:
431 finally:
420 c.endUpdate()
432 c.endUpdate()
421
433
422
434
423
435
424 def leoref_f(self,s):
436 def leoref_f(self,s):
425 """ Quick reference for ILeo """
437 """ Quick reference for ILeo """
426 import textwrap
438 import textwrap
427 print textwrap.dedent("""\
439 print textwrap.dedent("""\
428 %leo file - open file in leo
440 %leo file - open file in leo
429 wb.foo.v - eval node foo (i.e. headstring is 'foo' or '@ipy foo')
441 wb.foo.v - eval node foo (i.e. headstring is 'foo' or '@ipy foo')
430 wb.foo.v = 12 - assign to body of node foo
442 wb.foo.v = 12 - assign to body of node foo
431 wb.foo.b - read or write the body of node foo
443 wb.foo.b - read or write the body of node foo
432 wb.foo.l - body of node foo as string list
444 wb.foo.l - body of node foo as string list
433
445
434 for el in wb.foo:
446 for el in wb.foo:
435 print el.v
447 print el.v
436
448
437 """
449 """
438 )
450 )
439
451
440
452
441
453
442 def mb_f(self, arg):
454 def mb_f(self, arg):
443 """ Execute leo minibuffer commands
455 """ Execute leo minibuffer commands
444
456
445 Example:
457 Example:
446 mb save-to-file
458 mb save-to-file
447 """
459 """
448 c.executeMinibufferCommand(arg)
460 c.executeMinibufferCommand(arg)
449
461
450 def mb_completer(self,event):
462 def mb_completer(self,event):
451 """ Custom completer for minibuffer """
463 """ Custom completer for minibuffer """
452 cmd_param = event.line.split()
464 cmd_param = event.line.split()
453 if event.line.endswith(' '):
465 if event.line.endswith(' '):
454 cmd_param.append('')
466 cmd_param.append('')
455 if len(cmd_param) > 2:
467 if len(cmd_param) > 2:
456 return ip.IP.Completer.file_matches(event.symbol)
468 return ip.IP.Completer.file_matches(event.symbol)
457 cmds = c.commandsDict.keys()
469 cmds = c.commandsDict.keys()
458 cmds.sort()
470 cmds.sort()
459 return cmds
471 return cmds
460
472
461 def show_welcome():
473 def show_welcome():
462 print "------------------"
474 print "------------------"
463 print "Welcome to Leo-enabled IPython session!"
475 print "Welcome to Leo-enabled IPython session!"
464 print "Try %leoref for quick reference."
476 print "Try %leoref for quick reference."
465 import IPython.platutils
477 import IPython.platutils
466 IPython.platutils.set_term_title('ILeo')
478 IPython.platutils.set_term_title('ILeo')
467 IPython.platutils.freeze_term_title()
479 IPython.platutils.freeze_term_title()
468
480
469 def run_leo_startup_node():
481 def run_leo_startup_node():
470 p = g.findNodeAnywhere(c,'@ipy-startup')
482 p = g.findNodeAnywhere(c,'@ipy-startup')
471 if p:
483 if p:
472 print "Running @ipy-startup nodes"
484 print "Running @ipy-startup nodes"
473 for n in LeoNode(p):
485 for n in LeoNode(p):
474 push_from_leo(n)
486 push_from_leo(n)
General Comments 0
You need to be logged in to leave comments. Login now