##// END OF EJS Templates
Reorganization of readline and completion dependent code....
Fernando Perez -
Show More
@@ -1,789 +1,784 b''
1 1 """Word completion for IPython.
2 2
3 3 This module is a fork of the rlcompleter module in the Python standard
4 4 library. The original enhancements made to rlcompleter have been sent
5 5 upstream and were accepted as of Python 2.3, but we need a lot more
6 6 functionality specific to IPython, so this module will continue to live as an
7 7 IPython-specific utility.
8 8
9 9 Original rlcompleter documentation:
10 10
11 11 This requires the latest extension to the readline module (the
12 12 completes keywords, built-ins and globals in __main__; when completing
13 13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 14 completes its attributes.
15 15
16 16 It's very cool to do "import string" type "string.", hit the
17 17 completion key (twice), and see the list of names defined by the
18 18 string module!
19 19
20 20 Tip: to use the tab key as the completion key, call
21 21
22 22 readline.parse_and_bind("tab: complete")
23 23
24 24 Notes:
25 25
26 26 - Exceptions raised by the completer function are *ignored* (and
27 27 generally cause the completion to fail). This is a feature -- since
28 28 readline sets the tty device in raw (or cbreak) mode, printing a
29 29 traceback wouldn't work well without some complicated hoopla to save,
30 30 reset and restore the tty state.
31 31
32 32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 33 application defined code to be executed if an object with a
34 34 __getattr__ hook is found. Since it is the responsibility of the
35 35 application (or the user) to enable this feature, I consider this an
36 36 acceptable risk. More complicated expressions (e.g. function calls or
37 37 indexing operations) are *not* evaluated.
38 38
39 39 - GNU readline is also used by the built-in functions input() and
40 40 raw_input(), and thus these also benefit/suffer from the completer
41 41 features. Clearly an interactive application can benefit by
42 42 specifying its own completer function and using raw_input() for all
43 43 its input.
44 44
45 45 - When the original stdin is not a tty device, GNU readline is never
46 46 used, and this module (and the readline module) are silently inactive.
47 47 """
48 48
49 49 #*****************************************************************************
50 50 #
51 51 # Since this file is essentially a minimally modified copy of the rlcompleter
52 52 # module which is part of the standard Python distribution, I assume that the
53 53 # proper procedure is to maintain its copyright as belonging to the Python
54 54 # Software Foundation (in addition to my own, for all new code).
55 55 #
56 56 # Copyright (C) 2008-2010 IPython Development Team
57 57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
58 58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 59 #
60 60 # Distributed under the terms of the BSD License. The full license is in
61 61 # the file COPYING, distributed as part of this software.
62 62 #
63 63 #*****************************************************************************
64 64 from __future__ import print_function
65 65
66 66 #-----------------------------------------------------------------------------
67 67 # Imports
68 68 #-----------------------------------------------------------------------------
69 69
70 70 import __builtin__
71 71 import __main__
72 72 import glob
73 73 import inspect
74 74 import itertools
75 75 import keyword
76 76 import os
77 77 import re
78 78 import shlex
79 79 import sys
80 80
81 81 from IPython.core.error import TryNext
82 82 from IPython.core.prefilter import ESC_MAGIC
83 83 from IPython.utils import generics, io
84 84 from IPython.utils.frame import debugx
85 85 from IPython.utils.dir2 import dir2
86 86
87 87 #-----------------------------------------------------------------------------
88 88 # Globals
89 89 #-----------------------------------------------------------------------------
90 90
91 91 # Public API
92 92 __all__ = ['Completer','IPCompleter']
93 93
94 94 if sys.platform == 'win32':
95 95 PROTECTABLES = ' '
96 96 else:
97 97 PROTECTABLES = ' ()'
98 98
99 99 #-----------------------------------------------------------------------------
100 100 # Main functions and classes
101 101 #-----------------------------------------------------------------------------
102 102
103 103 def protect_filename(s):
104 104 """Escape a string to protect certain characters."""
105 105
106 106 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
107 107 for ch in s])
108 108
109 109
110 110 def mark_dirs(matches):
111 111 """Mark directories in input list by appending '/' to their names."""
112 112 out = []
113 113 isdir = os.path.isdir
114 114 for x in matches:
115 115 if isdir(x):
116 116 out.append(x+'/')
117 117 else:
118 118 out.append(x)
119 119 return out
120 120
121 121
122 122 def single_dir_expand(matches):
123 123 "Recursively expand match lists containing a single dir."
124 124
125 125 if len(matches) == 1 and os.path.isdir(matches[0]):
126 126 # Takes care of links to directories also. Use '/'
127 127 # explicitly, even under Windows, so that name completions
128 128 # don't end up escaped.
129 129 d = matches[0]
130 130 if d[-1] in ['/','\\']:
131 131 d = d[:-1]
132 132
133 133 subdirs = os.listdir(d)
134 134 if subdirs:
135 135 matches = [ (d + '/' + p) for p in subdirs]
136 136 return single_dir_expand(matches)
137 137 else:
138 138 return matches
139 139 else:
140 140 return matches
141 141
142 142
143 143 class Bunch(object): pass
144 144
145 145
146 146 class CompletionSplitter(object):
147 147 """An object to split an input line in a manner similar to readline.
148 148
149 149 By having our own implementation, we can expose readline-like completion in
150 150 a uniform manner to all frontends. This object only needs to be given the
151 151 line of text to be split and the cursor position on said line, and it
152 152 returns the 'word' to be completed on at the cursor after splitting the
153 153 entire line.
154 154
155 155 What characters are used as splitting delimiters can be controlled by
156 156 setting the `delims` attribute (this is a property that internally
157 157 automatically builds the necessary """
158 158
159 159 # Private interface
160 160
161 161 # A string of delimiter characters. The default value makes sense for
162 162 # IPython's most typical usage patterns.
163 163 _delims = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
164 164
165 165 # The expression (a normal string) to be compiled into a regular expression
166 166 # for actual splitting. We store it as an attribute mostly for ease of
167 167 # debugging, since this type of code can be so tricky to debug.
168 168 _delim_expr = None
169 169
170 170 # The regular expression that does the actual splitting
171 171 _delim_re = None
172 172
173 173 def __init__(self, delims=None):
174 174 delims = CompletionSplitter._delims if delims is None else delims
175 175 self.set_delims(delims)
176 176
177 177 def set_delims(self, delims):
178 178 """Set the delimiters for line splitting."""
179 179 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
180 180 self._delim_re = re.compile(expr)
181 181 self._delims = delims
182 182 self._delim_expr = expr
183 183
184 184 def get_delims(self):
185 185 """Return the string of delimiter characters."""
186 186 return self._delims
187 187
188 188 def split_line(self, line, cursor_pos=None):
189 189 """Split a line of text with a cursor at the given position.
190 190 """
191 191 l = line if cursor_pos is None else line[:cursor_pos]
192 192 return self._delim_re.split(l)[-1]
193 193
194 194
195 195 class Completer(object):
196 196 def __init__(self, namespace=None, global_namespace=None):
197 197 """Create a new completer for the command line.
198 198
199 199 Completer([namespace,global_namespace]) -> completer instance.
200 200
201 201 If unspecified, the default namespace where completions are performed
202 202 is __main__ (technically, __main__.__dict__). Namespaces should be
203 203 given as dictionaries.
204 204
205 205 An optional second namespace can be given. This allows the completer
206 206 to handle cases where both the local and global scopes need to be
207 207 distinguished.
208 208
209 209 Completer instances should be used as the completion mechanism of
210 210 readline via the set_completer() call:
211 211
212 212 readline.set_completer(Completer(my_namespace).complete)
213 213 """
214 214
215 215 # Don't bind to namespace quite yet, but flag whether the user wants a
216 216 # specific namespace or to use __main__.__dict__. This will allow us
217 217 # to bind to __main__.__dict__ at completion time, not now.
218 218 if namespace is None:
219 219 self.use_main_ns = 1
220 220 else:
221 221 self.use_main_ns = 0
222 222 self.namespace = namespace
223 223
224 224 # The global namespace, if given, can be bound directly
225 225 if global_namespace is None:
226 226 self.global_namespace = {}
227 227 else:
228 228 self.global_namespace = global_namespace
229 229
230 230 def complete(self, text, state):
231 231 """Return the next possible completion for 'text'.
232 232
233 233 This is called successively with state == 0, 1, 2, ... until it
234 234 returns None. The completion should begin with 'text'.
235 235
236 236 """
237 237 if self.use_main_ns:
238 238 self.namespace = __main__.__dict__
239 239
240 240 if state == 0:
241 241 if "." in text:
242 242 self.matches = self.attr_matches(text)
243 243 else:
244 244 self.matches = self.global_matches(text)
245 245 try:
246 246 return self.matches[state]
247 247 except IndexError:
248 248 return None
249 249
250 250 def global_matches(self, text):
251 251 """Compute matches when text is a simple name.
252 252
253 253 Return a list of all keywords, built-in functions and names currently
254 254 defined in self.namespace or self.global_namespace that match.
255 255
256 256 """
257 257 #print 'Completer->global_matches, txt=%r' % text # dbg
258 258 matches = []
259 259 match_append = matches.append
260 260 n = len(text)
261 261 for lst in [keyword.kwlist,
262 262 __builtin__.__dict__.keys(),
263 263 self.namespace.keys(),
264 264 self.global_namespace.keys()]:
265 265 for word in lst:
266 266 if word[:n] == text and word != "__builtins__":
267 267 match_append(word)
268 268 return matches
269 269
270 270 def attr_matches(self, text):
271 271 """Compute matches when text contains a dot.
272 272
273 273 Assuming the text is of the form NAME.NAME....[NAME], and is
274 274 evaluatable in self.namespace or self.global_namespace, it will be
275 275 evaluated and its attributes (as revealed by dir()) are used as
276 276 possible completions. (For class instances, class members are are
277 277 also considered.)
278 278
279 279 WARNING: this can still invoke arbitrary C code, if an object
280 280 with a __getattr__ hook is evaluated.
281 281
282 282 """
283 283
284 284 #print 'Completer->attr_matches, txt=%r' % text # dbg
285 285 # Another option, seems to work great. Catches things like ''.<tab>
286 286 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
287 287
288 288 if not m:
289 289 return []
290 290
291 291 expr, attr = m.group(1, 3)
292 292 try:
293 293 obj = eval(expr, self.namespace)
294 294 except:
295 295 try:
296 296 obj = eval(expr, self.global_namespace)
297 297 except:
298 298 return []
299 299
300 300 words = dir2(obj)
301 301
302 302 try:
303 303 words = generics.complete_object(obj, words)
304 304 except TryNext:
305 305 pass
306 306 # Build match list to return
307 307 n = len(attr)
308 308 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
309 309 return res
310 310
311 311
312 312 class IPCompleter(Completer):
313 313 """Extension of the completer class with IPython-specific features"""
314 314
315 315 def __init__(self, shell, namespace=None, global_namespace=None,
316 316 omit__names=0, alias_table=None, use_readline=True):
317 317 """IPCompleter() -> completer
318 318
319 319 Return a completer object suitable for use by the readline library
320 320 via readline.set_completer().
321 321
322 322 Inputs:
323 323
324 324 - shell: a pointer to the ipython shell itself. This is needed
325 325 because this completer knows about magic functions, and those can
326 326 only be accessed via the ipython instance.
327 327
328 328 - namespace: an optional dict where completions are performed.
329 329
330 330 - global_namespace: secondary optional dict for completions, to
331 331 handle cases (such as IPython embedded inside functions) where
332 332 both Python scopes are visible.
333 333
334 334 - The optional omit__names parameter sets the completer to omit the
335 335 'magic' names (__magicname__) for python objects unless the text
336 336 to be completed explicitly starts with one or more underscores.
337 337
338 338 - If alias_table is supplied, it should be a dictionary of aliases
339 339 to complete.
340 340
341 341 use_readline : bool, optional
342 342 If true, use the readline library. This completer can still function
343 343 without readline, though in that case callers must provide some extra
344 344 information on each call about the current line."""
345 345
346 346 Completer.__init__(self, namespace, global_namespace)
347 347
348 348 self.magic_escape = ESC_MAGIC
349
350 349 self.splitter = CompletionSplitter()
351 350
352 # Readline-dependent code
353 self.use_readline = use_readline
351 # Readline configuration, only used by the rlcompleter method.
354 352 if use_readline:
353 # We store the right version of readline so that later code
355 354 import IPython.utils.rlineimpl as readline
356 355 self.readline = readline
357 delims = self.readline.get_completer_delims()
358 delims = delims.replace(self.magic_escape,'')
359 self.readline.set_completer_delims(delims)
360 self.get_line_buffer = self.readline.get_line_buffer
361 self.get_endidx = self.readline.get_endidx
362 # /end readline-dependent code
356 else:
357 self.readline = None
363 358
364 359 # List where completion matches will be stored
365 360 self.matches = []
366 361 self.omit__names = omit__names
367 362 self.merge_completions = shell.readline_merge_completions
368 363 self.shell = shell.shell
369 364 if alias_table is None:
370 365 alias_table = {}
371 366 self.alias_table = alias_table
372 367 # Regexp to split filenames with spaces in them
373 368 self.space_name_re = re.compile(r'([^\\] )')
374 369 # Hold a local ref. to glob.glob for speed
375 370 self.glob = glob.glob
376 371
377 372 # Determine if we are running on 'dumb' terminals, like (X)Emacs
378 373 # buffers, to avoid completion problems.
379 374 term = os.environ.get('TERM','xterm')
380 375 self.dumb_terminal = term in ['dumb','emacs']
381 376
382 377 # Special handling of backslashes needed in win32 platforms
383 378 if sys.platform == "win32":
384 379 self.clean_glob = self._clean_glob_win32
385 380 else:
386 381 self.clean_glob = self._clean_glob
387 382
388 383 # All active matcher routines for completion
389 384 self.matchers = [self.python_matches,
390 385 self.file_matches,
391 386 self.magic_matches,
392 387 self.alias_matches,
393 388 self.python_func_kw_matches,
394 389 ]
395 390
396 391 # Code contributed by Alex Schmolck, for ipython/emacs integration
397 392 def all_completions(self, text):
398 393 """Return all possible completions for the benefit of emacs."""
399 394
400 395 completions = []
401 396 comp_append = completions.append
402 397 try:
403 398 for i in xrange(sys.maxint):
404 399 res = self.complete(text, i, text)
405 400 if not res:
406 401 break
407 402 comp_append(res)
408 403 #XXX workaround for ``notDefined.<tab>``
409 404 except NameError:
410 405 pass
411 406 return completions
412 407 # /end Alex Schmolck code.
413 408
414 409 def _clean_glob(self,text):
415 410 return self.glob("%s*" % text)
416 411
417 412 def _clean_glob_win32(self,text):
418 413 return [f.replace("\\","/")
419 414 for f in self.glob("%s*" % text)]
420 415
421 416 def file_matches(self, text):
422 417 """Match filenames, expanding ~USER type strings.
423 418
424 419 Most of the seemingly convoluted logic in this completer is an
425 420 attempt to handle filenames with spaces in them. And yet it's not
426 421 quite perfect, because Python's readline doesn't expose all of the
427 422 GNU readline details needed for this to be done correctly.
428 423
429 424 For a filename with a space in it, the printed completions will be
430 425 only the parts after what's already been typed (instead of the
431 426 full completions, as is normally done). I don't think with the
432 427 current (as of Python 2.3) Python readline it's possible to do
433 428 better."""
434 429
435 430 #io.rprint('Completer->file_matches: <%s>' % text) # dbg
436 431
437 432 # chars that require escaping with backslash - i.e. chars
438 433 # that readline treats incorrectly as delimiters, but we
439 434 # don't want to treat as delimiters in filename matching
440 435 # when escaped with backslash
441 436 if text.startswith('!'):
442 437 text = text[1:]
443 438 text_prefix = '!'
444 439 else:
445 440 text_prefix = ''
446 441
447 lbuf = self.lbuf
442 text_until_cursor = self.text_until_cursor
448 443 open_quotes = 0 # track strings with open quotes
449 444 try:
450 lsplit = shlex.split(lbuf)[-1]
445 lsplit = shlex.split(text_until_cursor)[-1]
451 446 except ValueError:
452 447 # typically an unmatched ", or backslash without escaped char.
453 if lbuf.count('"')==1:
448 if text_until_cursor.count('"')==1:
454 449 open_quotes = 1
455 lsplit = lbuf.split('"')[-1]
456 elif lbuf.count("'")==1:
450 lsplit = text_until_cursor.split('"')[-1]
451 elif text_until_cursor.count("'")==1:
457 452 open_quotes = 1
458 lsplit = lbuf.split("'")[-1]
453 lsplit = text_until_cursor.split("'")[-1]
459 454 else:
460 455 return []
461 456 except IndexError:
462 457 # tab pressed on empty line
463 458 lsplit = ""
464 459
465 460 if not open_quotes and lsplit != protect_filename(lsplit):
466 461 # if protectables are found, do matching on the whole escaped
467 462 # name
468 463 has_protectables = 1
469 464 text0,text = text,lsplit
470 465 else:
471 466 has_protectables = 0
472 467 text = os.path.expanduser(text)
473 468
474 469 if text == "":
475 470 return [text_prefix + protect_filename(f) for f in self.glob("*")]
476 471
477 472 m0 = self.clean_glob(text.replace('\\',''))
478 473 if has_protectables:
479 474 # If we had protectables, we need to revert our changes to the
480 475 # beginning of filename so that we don't double-write the part
481 476 # of the filename we have so far
482 477 len_lsplit = len(lsplit)
483 478 matches = [text_prefix + text0 +
484 479 protect_filename(f[len_lsplit:]) for f in m0]
485 480 else:
486 481 if open_quotes:
487 482 # if we have a string with an open quote, we don't need to
488 483 # protect the names at all (and we _shouldn't_, as it
489 484 # would cause bugs when the filesystem call is made).
490 485 matches = m0
491 486 else:
492 487 matches = [text_prefix +
493 488 protect_filename(f) for f in m0]
494 489
495 490 #io.rprint('mm', matches) # dbg
496 491 return mark_dirs(matches)
497 492
498 493 def magic_matches(self, text):
499 494 """Match magics"""
500 #print 'Completer->magic_matches:',text,'lb',self.lbuf # dbg
495 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
501 496 # Get all shell magics now rather than statically, so magics loaded at
502 497 # runtime show up too
503 498 magics = self.shell.lsmagic()
504 499 pre = self.magic_escape
505 500 baretext = text.lstrip(pre)
506 501 return [ pre+m for m in magics if m.startswith(baretext)]
507 502
508 503 def alias_matches(self, text):
509 504 """Match internal system aliases"""
510 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
511
512 # if we are not in the first 'item', alias matching
505 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
506
507 # if we are not in the first 'item', alias matching
513 508 # doesn't make sense - unless we are starting with 'sudo' command.
514 if ' ' in self.lbuf.lstrip() and \
515 not self.lbuf.lstrip().startswith('sudo'):
509 main_text = self.text_until_cursor.lstrip()
510 if ' ' in main_text and not main_text.startswith('sudo'):
516 511 return []
517 512 text = os.path.expanduser(text)
518 513 aliases = self.alias_table.keys()
519 if text == "":
514 if text == '':
520 515 return aliases
521 516 else:
522 return [alias for alias in aliases if alias.startswith(text)]
517 return [a for a in aliases if a.startswith(text)]
523 518
524 519 def python_matches(self,text):
525 520 """Match attributes or global python names"""
526 521
527 522 #print 'Completer->python_matches, txt=%r' % text # dbg
528 523 if "." in text:
529 524 try:
530 525 matches = self.attr_matches(text)
531 526 if text.endswith('.') and self.omit__names:
532 527 if self.omit__names == 1:
533 528 # true if txt is _not_ a __ name, false otherwise:
534 529 no__name = (lambda txt:
535 530 re.match(r'.*\.__.*?__',txt) is None)
536 531 else:
537 532 # true if txt is _not_ a _ name, false otherwise:
538 533 no__name = (lambda txt:
539 534 re.match(r'.*\._.*?',txt) is None)
540 535 matches = filter(no__name, matches)
541 536 except NameError:
542 537 # catches <undefined attributes>.<tab>
543 538 matches = []
544 539 else:
545 540 matches = self.global_matches(text)
546 541
547 542 return matches
548 543
549 544 def _default_arguments(self, obj):
550 545 """Return the list of default arguments of obj if it is callable,
551 546 or empty list otherwise."""
552 547
553 548 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
554 549 # for classes, check for __init__,__new__
555 550 if inspect.isclass(obj):
556 551 obj = (getattr(obj,'__init__',None) or
557 552 getattr(obj,'__new__',None))
558 553 # for all others, check if they are __call__able
559 554 elif hasattr(obj, '__call__'):
560 555 obj = obj.__call__
561 556 # XXX: is there a way to handle the builtins ?
562 557 try:
563 558 args,_,_1,defaults = inspect.getargspec(obj)
564 559 if defaults:
565 560 return args[-len(defaults):]
566 561 except TypeError: pass
567 562 return []
568 563
569 564 def python_func_kw_matches(self,text):
570 565 """Match named parameters (kwargs) of the last open function"""
571 566
572 567 if "." in text: # a parameter cannot be dotted
573 568 return []
574 569 try: regexp = self.__funcParamsRegex
575 570 except AttributeError:
576 571 regexp = self.__funcParamsRegex = re.compile(r'''
577 572 '.*?' | # single quoted strings or
578 573 ".*?" | # double quoted strings or
579 574 \w+ | # identifier
580 575 \S # other characters
581 576 ''', re.VERBOSE | re.DOTALL)
582 577 # 1. find the nearest identifier that comes before an unclosed
583 578 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
584 tokens = regexp.findall(self.get_line_buffer())
579 tokens = regexp.findall(self.line_buffer)
585 580 tokens.reverse()
586 581 iterTokens = iter(tokens); openPar = 0
587 582 for token in iterTokens:
588 583 if token == ')':
589 584 openPar -= 1
590 585 elif token == '(':
591 586 openPar += 1
592 587 if openPar > 0:
593 588 # found the last unclosed parenthesis
594 589 break
595 590 else:
596 591 return []
597 592 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
598 593 ids = []
599 594 isId = re.compile(r'\w+$').match
600 595 while True:
601 596 try:
602 597 ids.append(iterTokens.next())
603 598 if not isId(ids[-1]):
604 599 ids.pop(); break
605 600 if not iterTokens.next() == '.':
606 601 break
607 602 except StopIteration:
608 603 break
609 604 # lookup the candidate callable matches either using global_matches
610 605 # or attr_matches for dotted names
611 606 if len(ids) == 1:
612 607 callableMatches = self.global_matches(ids[0])
613 608 else:
614 609 callableMatches = self.attr_matches('.'.join(ids[::-1]))
615 610 argMatches = []
616 611 for callableMatch in callableMatches:
617 612 try:
618 613 namedArgs = self._default_arguments(eval(callableMatch,
619 614 self.namespace))
620 615 except:
621 616 continue
622 617 for namedArg in namedArgs:
623 618 if namedArg.startswith(text):
624 619 argMatches.append("%s=" %namedArg)
625 620 return argMatches
626 621
627 622 def dispatch_custom_completer(self,text):
628 623 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
629 line = self.full_lbuf
624 line = self.line_buffer
630 625 if not line.strip():
631 626 return None
632 627
633 628 event = Bunch()
634 629 event.line = line
635 630 event.symbol = text
636 631 cmd = line.split(None,1)[0]
637 632 event.command = cmd
638 633 #print "\ncustom:{%s]\n" % event # dbg
639 634
640 635 # for foo etc, try also to find completer for %foo
641 636 if not cmd.startswith(self.magic_escape):
642 637 try_magic = self.custom_completers.s_matches(
643 self.magic_escape + cmd)
638 self.magic_escape + cmd)
644 639 else:
645 640 try_magic = []
646 641
647 642 for c in itertools.chain(self.custom_completers.s_matches(cmd),
648 try_magic,
649 self.custom_completers.flat_matches(self.lbuf)):
643 try_magic,
644 self.custom_completers.flat_matches(self.text_until_cursor)):
650 645 #print "try",c # dbg
651 646 try:
652 647 res = c(event)
653 648 # first, try case sensitive match
654 649 withcase = [r for r in res if r.startswith(text)]
655 650 if withcase:
656 651 return withcase
657 652 # if none, then case insensitive ones are ok too
658 653 text_low = text.lower()
659 654 return [r for r in res if r.lower().startswith(text_low)]
660 655 except TryNext:
661 656 pass
662 657
663 658 return None
664 659
665 660 def complete(self, text=None, line_buffer=None, cursor_pos=None):
666 661 """Return the state-th possible completion for 'text'.
667 662
668 663 This is called successively with state == 0, 1, 2, ... until it
669 664 returns None. The completion should begin with 'text'.
670 665
671 666 Note that both the text and the line_buffer are optional, but at least
672 667 one of them must be given.
673 668
674 669 Parameters
675 670 ----------
676 671 text : string, optional
677 672 Text to perform the completion on. If not given, the line buffer
678 673 is split using the instance's CompletionSplitter object.
679 674
680 675 line_buffer : string, optional
681 676 If not given, the completer attempts to obtain the current line
682 677 buffer via readline. This keyword allows clients which are
683 678 requesting for text completions in non-readline contexts to inform
684 679 the completer of the entire text.
685 680
686 681 cursor_pos : int, optional
687 682 Index of the cursor in the full line buffer. Should be provided by
688 683 remote frontends where kernel has no access to frontend state.
689 684 """
690 685 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
691 686
692 687 # if the cursor position isn't given, the only sane assumption we can
693 688 # make is that it's at the end of the line (the common case)
694 689 if cursor_pos is None:
695 690 cursor_pos = len(line_buffer) if text is None else len(text)
696 691
697 692 # if text is either None or an empty string, rely on the line buffer
698 693 if not text:
699 694 text = self.splitter.split_line(line_buffer, cursor_pos)
700 695
701 696 # If no line buffer is given, assume the input text is all there was
702 697 if line_buffer is None:
703 698 line_buffer = text
704 699
705 700 magic_escape = self.magic_escape
706 self.full_lbuf = line_buffer
707 self.lbuf = self.full_lbuf[:cursor_pos]
701 self.line_buffer = line_buffer
702 self.text_until_cursor = self.line_buffer[:cursor_pos]
708 703 #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
709 704
710 705 # Start with a clean slate of completions
711 706 self.matches[:] = []
712 707 custom_res = self.dispatch_custom_completer(text)
713 708 if custom_res is not None:
714 709 # did custom completers produce something?
715 710 self.matches = custom_res
716 711 else:
717 712 # Extend the list of completions with the results of each
718 713 # matcher, so we return results to the user from all
719 714 # namespaces.
720 715 if self.merge_completions:
721 716 self.matches = []
722 717 for matcher in self.matchers:
723 718 self.matches.extend(matcher(text))
724 719 else:
725 720 for matcher in self.matchers:
726 721 self.matches = matcher(text)
727 722 if self.matches:
728 723 break
729 724 # FIXME: we should extend our api to return a dict with completions for
730 725 # different types of objects. The rlcomplete() method could then
731 726 # simply collapse the dict into a list for readline, but we'd have
732 727 # richer completion semantics in other evironments.
733 728 self.matches = sorted(set(self.matches))
734 729 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
735 730 return text, self.matches
736 731
737 732 def rlcomplete(self, text, state):
738 733 """Return the state-th possible completion for 'text'.
739 734
740 735 This is called successively with state == 0, 1, 2, ... until it
741 736 returns None. The completion should begin with 'text'.
742 737
743 738 Parameters
744 739 ----------
745 740 text : string
746 741 Text to perform the completion on.
747 742
748 743 state : int
749 744 Counter used by readline.
750 745 """
751 746 if state==0:
752 747
753 self.full_lbuf = line_buffer = self.get_line_buffer()
754 cursor_pos = self.get_endidx()
748 self.line_buffer = line_buffer = self.readline.get_line_buffer()
749 cursor_pos = self.readline.get_endidx()
755 750
756 751 #io.rprint("\nRLCOMPLETE: %r %r %r" %
757 752 # (text, line_buffer, cursor_pos) ) # dbg
758 753
759 754 # if there is only a tab on a line with only whitespace, instead of
760 755 # the mostly useless 'do you want to see all million completions'
761 756 # message, just do the right thing and give the user his tab!
762 757 # Incidentally, this enables pasting of tabbed text from an editor
763 758 # (as long as autoindent is off).
764 759
765 760 # It should be noted that at least pyreadline still shows file
766 761 # completions - is there a way around it?
767 762
768 763 # don't apply this on 'dumb' terminals, such as emacs buffers, so
769 764 # we don't interfere with their own tab-completion mechanism.
770 765 if not (self.dumb_terminal or line_buffer.strip()):
771 766 self.readline.insert_text('\t')
772 767 sys.stdout.flush()
773 768 return None
774 769
775 770 # This method computes the self.matches array
776 771 self.complete(text, line_buffer, cursor_pos)
777 772
778 773 # Debug version, since readline silences all exceptions making it
779 774 # impossible to debug any problem in the above code
780 775
781 776 ## try:
782 777 ## self.complete(text, line_buffer, cursor_pos)
783 778 ## except:
784 779 ## import traceback; traceback.print_exc()
785 780
786 781 try:
787 782 return self.matches[state]
788 783 except IndexError:
789 784 return None
@@ -1,2374 +1,2390 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import atexit
24 24 import codeop
25 25 import exceptions
26 26 import new
27 27 import os
28 28 import re
29 29 import string
30 30 import sys
31 31 import tempfile
32 32 from contextlib import nested
33 33
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager
42 42 from IPython.core.builtin_trap import BuiltinTrap
43 43 from IPython.core.display_trap import DisplayTrap
44 44 from IPython.core.displayhook import DisplayHook
45 45 from IPython.core.error import TryNext, UsageError
46 46 from IPython.core.extensions import ExtensionManager
47 47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 48 from IPython.core.inputlist import InputList
49 49 from IPython.core.logger import Logger
50 50 from IPython.core.magic import Magic
51 51 from IPython.core.payload import PayloadManager
52 52 from IPython.core.plugin import PluginManager
53 53 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 54 from IPython.external.Itpl import ItplNS
55 55 from IPython.utils import PyColorize
56 56 from IPython.utils import io
57 57 from IPython.utils import pickleshare
58 58 from IPython.utils.doctestreload import doctest_reload
59 59 from IPython.utils.io import ask_yes_no, rprint
60 60 from IPython.utils.ipstruct import Struct
61 61 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 62 from IPython.utils.process import system, getoutput
63 63 from IPython.utils.strdispatch import StrDispatch
64 64 from IPython.utils.syspathcontext import prepended_to_syspath
65 65 from IPython.utils.text import num_ini_spaces, format_screen
66 66 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 67 List, Unicode, Instance, Type)
68 68 from IPython.utils.warn import warn, error, fatal
69 69 import IPython.core.hooks
70 70
71 71 #-----------------------------------------------------------------------------
72 72 # Globals
73 73 #-----------------------------------------------------------------------------
74 74
75 75 # compiled regexps for autoindent management
76 76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 77
78 78 #-----------------------------------------------------------------------------
79 79 # Utilities
80 80 #-----------------------------------------------------------------------------
81 81
82 82 # store the builtin raw_input globally, and use this always, in case user code
83 83 # overwrites it (like wx.py.PyShell does)
84 84 raw_input_original = raw_input
85 85
86 86 def softspace(file, newvalue):
87 87 """Copied from code.py, to remove the dependency"""
88 88
89 89 oldvalue = 0
90 90 try:
91 91 oldvalue = file.softspace
92 92 except AttributeError:
93 93 pass
94 94 try:
95 95 file.softspace = newvalue
96 96 except (AttributeError, TypeError):
97 97 # "attribute-less object" or "read-only attributes"
98 98 pass
99 99 return oldvalue
100 100
101 101
102 102 def no_op(*a, **kw): pass
103 103
104 104 class SpaceInInput(exceptions.Exception): pass
105 105
106 106 class Bunch: pass
107 107
108 108
109 109 def get_default_colors():
110 110 if sys.platform=='darwin':
111 111 return "LightBG"
112 112 elif os.name=='nt':
113 113 return 'Linux'
114 114 else:
115 115 return 'Linux'
116 116
117 117
118 118 class SeparateStr(Str):
119 119 """A Str subclass to validate separate_in, separate_out, etc.
120 120
121 121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 122 """
123 123
124 124 def validate(self, obj, value):
125 125 if value == '0': value = ''
126 126 value = value.replace('\\n','\n')
127 127 return super(SeparateStr, self).validate(obj, value)
128 128
129 129 class MultipleInstanceError(Exception):
130 130 pass
131 131
132 132
133 133 #-----------------------------------------------------------------------------
134 134 # Main IPython class
135 135 #-----------------------------------------------------------------------------
136 136
137 137
138 138 class InteractiveShell(Configurable, Magic):
139 139 """An enhanced, interactive shell for Python."""
140 140
141 141 _instance = None
142 142 autocall = Enum((0,1,2), default_value=1, config=True)
143 143 # TODO: remove all autoindent logic and put into frontends.
144 144 # We can't do this yet because even runlines uses the autoindent.
145 145 autoindent = CBool(True, config=True)
146 146 automagic = CBool(True, config=True)
147 147 cache_size = Int(1000, config=True)
148 148 color_info = CBool(True, config=True)
149 149 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 150 default_value=get_default_colors(), config=True)
151 151 debug = CBool(False, config=True)
152 152 deep_reload = CBool(False, config=True)
153 153 displayhook_class = Type(DisplayHook)
154 154 exit_now = CBool(False)
155 155 filename = Str("<ipython console>")
156 156 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
157 157 logstart = CBool(False, config=True)
158 158 logfile = Str('', config=True)
159 159 logappend = Str('', config=True)
160 160 object_info_string_level = Enum((0,1,2), default_value=0,
161 161 config=True)
162 162 pdb = CBool(False, config=True)
163 163 pprint = CBool(True, config=True)
164 164 profile = Str('', config=True)
165 165 prompt_in1 = Str('In [\\#]: ', config=True)
166 166 prompt_in2 = Str(' .\\D.: ', config=True)
167 167 prompt_out = Str('Out[\\#]: ', config=True)
168 168 prompts_pad_left = CBool(True, config=True)
169 169 quiet = CBool(False, config=True)
170 170
171 171 # The readline stuff will eventually be moved to the terminal subclass
172 172 # but for now, we can't do that as readline is welded in everywhere.
173 173 readline_use = CBool(True, config=True)
174 174 readline_merge_completions = CBool(True, config=True)
175 175 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
176 176 readline_remove_delims = Str('-/~', config=True)
177 177 readline_parse_and_bind = List([
178 178 'tab: complete',
179 179 '"\C-l": clear-screen',
180 180 'set show-all-if-ambiguous on',
181 181 '"\C-o": tab-insert',
182 182 '"\M-i": " "',
183 183 '"\M-o": "\d\d\d\d"',
184 184 '"\M-I": "\d\d\d\d"',
185 185 '"\C-r": reverse-search-history',
186 186 '"\C-s": forward-search-history',
187 187 '"\C-p": history-search-backward',
188 188 '"\C-n": history-search-forward',
189 189 '"\e[A": history-search-backward',
190 190 '"\e[B": history-search-forward',
191 191 '"\C-k": kill-line',
192 192 '"\C-u": unix-line-discard',
193 193 ], allow_none=False, config=True)
194 194
195 195 # TODO: this part of prompt management should be moved to the frontends.
196 196 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
197 197 separate_in = SeparateStr('\n', config=True)
198 198 separate_out = SeparateStr('', config=True)
199 199 separate_out2 = SeparateStr('', config=True)
200 200 wildcards_case_sensitive = CBool(True, config=True)
201 201 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
202 202 default_value='Context', config=True)
203 203
204 204 # Subcomponents of InteractiveShell
205 205 alias_manager = Instance('IPython.core.alias.AliasManager')
206 206 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
207 207 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
208 208 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
209 209 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
210 210 plugin_manager = Instance('IPython.core.plugin.PluginManager')
211 211 payload_manager = Instance('IPython.core.payload.PayloadManager')
212 212
213 213 def __init__(self, config=None, ipython_dir=None,
214 214 user_ns=None, user_global_ns=None,
215 215 custom_exceptions=((),None)):
216 216
217 217 # This is where traits with a config_key argument are updated
218 218 # from the values on config.
219 219 super(InteractiveShell, self).__init__(config=config)
220 220
221 221 # These are relatively independent and stateless
222 222 self.init_ipython_dir(ipython_dir)
223 223 self.init_instance_attrs()
224 224
225 225 # Create namespaces (user_ns, user_global_ns, etc.)
226 226 self.init_create_namespaces(user_ns, user_global_ns)
227 227 # This has to be done after init_create_namespaces because it uses
228 228 # something in self.user_ns, but before init_sys_modules, which
229 229 # is the first thing to modify sys.
230 230 # TODO: When we override sys.stdout and sys.stderr before this class
231 231 # is created, we are saving the overridden ones here. Not sure if this
232 232 # is what we want to do.
233 233 self.save_sys_module_state()
234 234 self.init_sys_modules()
235 235
236 236 self.init_history()
237 237 self.init_encoding()
238 238 self.init_prefilter()
239 239
240 240 Magic.__init__(self, self)
241 241
242 242 self.init_syntax_highlighting()
243 243 self.init_hooks()
244 244 self.init_pushd_popd_magic()
245 245 # self.init_traceback_handlers use to be here, but we moved it below
246 246 # because it and init_io have to come after init_readline.
247 247 self.init_user_ns()
248 248 self.init_logger()
249 249 self.init_alias()
250 250 self.init_builtins()
251 251
252 252 # pre_config_initialization
253 253 self.init_shadow_hist()
254 254
255 255 # The next section should contain averything that was in ipmaker.
256 256 self.init_logstart()
257 257
258 258 # The following was in post_config_initialization
259 259 self.init_inspector()
260 260 # init_readline() must come before init_io(), because init_io uses
261 261 # readline related things.
262 262 self.init_readline()
263 # init_completer must come after init_readline, because it needs to
264 # know whether readline is present or not system-wide to configure the
265 # completers, since the completion machinery can now operate
266 # independently of readline (e.g. over the network)
267 self.init_completer()
263 268 # TODO: init_io() needs to happen before init_traceback handlers
264 269 # because the traceback handlers hardcode the stdout/stderr streams.
265 270 # This logic in in debugger.Pdb and should eventually be changed.
266 271 self.init_io()
267 272 self.init_traceback_handlers(custom_exceptions)
268 273 self.init_prompts()
269 274 self.init_displayhook()
270 275 self.init_reload_doctest()
271 276 self.init_magics()
272 277 self.init_pdb()
273 278 self.init_extension_manager()
274 279 self.init_plugin_manager()
275 280 self.init_payload()
276 281 self.hooks.late_startup_hook()
277 282 atexit.register(self.atexit_operations)
278 283
279 284 @classmethod
280 285 def instance(cls, *args, **kwargs):
281 286 """Returns a global InteractiveShell instance."""
282 287 if cls._instance is None:
283 288 inst = cls(*args, **kwargs)
284 289 # Now make sure that the instance will also be returned by
285 290 # the subclasses instance attribute.
286 291 for subclass in cls.mro():
287 292 if issubclass(cls, subclass) and \
288 293 issubclass(subclass, InteractiveShell):
289 294 subclass._instance = inst
290 295 else:
291 296 break
292 297 if isinstance(cls._instance, cls):
293 298 return cls._instance
294 299 else:
295 300 raise MultipleInstanceError(
296 301 'Multiple incompatible subclass instances of '
297 302 'InteractiveShell are being created.'
298 303 )
299 304
300 305 @classmethod
301 306 def initialized(cls):
302 307 return hasattr(cls, "_instance")
303 308
304 309 def get_ipython(self):
305 310 """Return the currently running IPython instance."""
306 311 return self
307 312
308 313 #-------------------------------------------------------------------------
309 314 # Trait changed handlers
310 315 #-------------------------------------------------------------------------
311 316
312 317 def _ipython_dir_changed(self, name, new):
313 318 if not os.path.isdir(new):
314 319 os.makedirs(new, mode = 0777)
315 320
316 321 def set_autoindent(self,value=None):
317 322 """Set the autoindent flag, checking for readline support.
318 323
319 324 If called with no arguments, it acts as a toggle."""
320 325
321 326 if not self.has_readline:
322 327 if os.name == 'posix':
323 328 warn("The auto-indent feature requires the readline library")
324 329 self.autoindent = 0
325 330 return
326 331 if value is None:
327 332 self.autoindent = not self.autoindent
328 333 else:
329 334 self.autoindent = value
330 335
331 336 #-------------------------------------------------------------------------
332 337 # init_* methods called by __init__
333 338 #-------------------------------------------------------------------------
334 339
335 340 def init_ipython_dir(self, ipython_dir):
336 341 if ipython_dir is not None:
337 342 self.ipython_dir = ipython_dir
338 343 self.config.Global.ipython_dir = self.ipython_dir
339 344 return
340 345
341 346 if hasattr(self.config.Global, 'ipython_dir'):
342 347 self.ipython_dir = self.config.Global.ipython_dir
343 348 else:
344 349 self.ipython_dir = get_ipython_dir()
345 350
346 351 # All children can just read this
347 352 self.config.Global.ipython_dir = self.ipython_dir
348 353
349 354 def init_instance_attrs(self):
350 355 self.more = False
351 356
352 357 # command compiler
353 358 self.compile = codeop.CommandCompiler()
354 359
355 360 # User input buffer
356 361 self.buffer = []
357 362
358 363 # Make an empty namespace, which extension writers can rely on both
359 364 # existing and NEVER being used by ipython itself. This gives them a
360 365 # convenient location for storing additional information and state
361 366 # their extensions may require, without fear of collisions with other
362 367 # ipython names that may develop later.
363 368 self.meta = Struct()
364 369
365 370 # Object variable to store code object waiting execution. This is
366 371 # used mainly by the multithreaded shells, but it can come in handy in
367 372 # other situations. No need to use a Queue here, since it's a single
368 373 # item which gets cleared once run.
369 374 self.code_to_run = None
370 375
371 376 # Temporary files used for various purposes. Deleted at exit.
372 377 self.tempfiles = []
373 378
374 379 # Keep track of readline usage (later set by init_readline)
375 380 self.has_readline = False
376 381
377 382 # keep track of where we started running (mainly for crash post-mortem)
378 383 # This is not being used anywhere currently.
379 384 self.starting_dir = os.getcwd()
380 385
381 386 # Indentation management
382 387 self.indent_current_nsp = 0
383 388
384 389 def init_encoding(self):
385 390 # Get system encoding at startup time. Certain terminals (like Emacs
386 391 # under Win32 have it set to None, and we need to have a known valid
387 392 # encoding to use in the raw_input() method
388 393 try:
389 394 self.stdin_encoding = sys.stdin.encoding or 'ascii'
390 395 except AttributeError:
391 396 self.stdin_encoding = 'ascii'
392 397
393 398 def init_syntax_highlighting(self):
394 399 # Python source parser/formatter for syntax highlighting
395 400 pyformat = PyColorize.Parser().format
396 401 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
397 402
398 403 def init_pushd_popd_magic(self):
399 404 # for pushd/popd management
400 405 try:
401 406 self.home_dir = get_home_dir()
402 407 except HomeDirError, msg:
403 408 fatal(msg)
404 409
405 410 self.dir_stack = []
406 411
407 412 def init_logger(self):
408 413 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
409 414 # local shortcut, this is used a LOT
410 415 self.log = self.logger.log
411 416
412 417 def init_logstart(self):
413 418 if self.logappend:
414 419 self.magic_logstart(self.logappend + ' append')
415 420 elif self.logfile:
416 421 self.magic_logstart(self.logfile)
417 422 elif self.logstart:
418 423 self.magic_logstart()
419 424
420 425 def init_builtins(self):
421 426 self.builtin_trap = BuiltinTrap(shell=self)
422 427
423 428 def init_inspector(self):
424 429 # Object inspector
425 430 self.inspector = oinspect.Inspector(oinspect.InspectColors,
426 431 PyColorize.ANSICodeColors,
427 432 'NoColor',
428 433 self.object_info_string_level)
429 434
430 435 def init_io(self):
431 436 import IPython.utils.io
432 437 if sys.platform == 'win32' and self.has_readline:
433 438 Term = io.IOTerm(
434 439 cout=self.readline._outputfile,cerr=self.readline._outputfile
435 440 )
436 441 else:
437 442 Term = io.IOTerm()
438 443 io.Term = Term
439 444
440 445 def init_prompts(self):
441 446 # TODO: This is a pass for now because the prompts are managed inside
442 447 # the DisplayHook. Once there is a separate prompt manager, this
443 448 # will initialize that object and all prompt related information.
444 449 pass
445 450
446 451 def init_displayhook(self):
447 452 # Initialize displayhook, set in/out prompts and printing system
448 453 self.displayhook = self.displayhook_class(
449 454 shell=self,
450 455 cache_size=self.cache_size,
451 456 input_sep = self.separate_in,
452 457 output_sep = self.separate_out,
453 458 output_sep2 = self.separate_out2,
454 459 ps1 = self.prompt_in1,
455 460 ps2 = self.prompt_in2,
456 461 ps_out = self.prompt_out,
457 462 pad_left = self.prompts_pad_left
458 463 )
459 464 # This is a context manager that installs/revmoes the displayhook at
460 465 # the appropriate time.
461 466 self.display_trap = DisplayTrap(hook=self.displayhook)
462 467
463 468 def init_reload_doctest(self):
464 469 # Do a proper resetting of doctest, including the necessary displayhook
465 470 # monkeypatching
466 471 try:
467 472 doctest_reload()
468 473 except ImportError:
469 474 warn("doctest module does not exist.")
470 475
471 476 #-------------------------------------------------------------------------
472 477 # Things related to injections into the sys module
473 478 #-------------------------------------------------------------------------
474 479
475 480 def save_sys_module_state(self):
476 481 """Save the state of hooks in the sys module.
477 482
478 483 This has to be called after self.user_ns is created.
479 484 """
480 485 self._orig_sys_module_state = {}
481 486 self._orig_sys_module_state['stdin'] = sys.stdin
482 487 self._orig_sys_module_state['stdout'] = sys.stdout
483 488 self._orig_sys_module_state['stderr'] = sys.stderr
484 489 self._orig_sys_module_state['excepthook'] = sys.excepthook
485 490 try:
486 491 self._orig_sys_modules_main_name = self.user_ns['__name__']
487 492 except KeyError:
488 493 pass
489 494
490 495 def restore_sys_module_state(self):
491 496 """Restore the state of the sys module."""
492 497 try:
493 498 for k, v in self._orig_sys_module_state.items():
494 499 setattr(sys, k, v)
495 500 except AttributeError:
496 501 pass
497 502 # Reset what what done in self.init_sys_modules
498 503 try:
499 504 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
500 505 except (AttributeError, KeyError):
501 506 pass
502 507
503 508 #-------------------------------------------------------------------------
504 509 # Things related to hooks
505 510 #-------------------------------------------------------------------------
506 511
507 512 def init_hooks(self):
508 513 # hooks holds pointers used for user-side customizations
509 514 self.hooks = Struct()
510 515
511 516 self.strdispatchers = {}
512 517
513 518 # Set all default hooks, defined in the IPython.hooks module.
514 519 hooks = IPython.core.hooks
515 520 for hook_name in hooks.__all__:
516 521 # default hooks have priority 100, i.e. low; user hooks should have
517 522 # 0-100 priority
518 523 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
519 524
520 525 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
521 526 """set_hook(name,hook) -> sets an internal IPython hook.
522 527
523 528 IPython exposes some of its internal API as user-modifiable hooks. By
524 529 adding your function to one of these hooks, you can modify IPython's
525 530 behavior to call at runtime your own routines."""
526 531
527 532 # At some point in the future, this should validate the hook before it
528 533 # accepts it. Probably at least check that the hook takes the number
529 534 # of args it's supposed to.
530 535
531 536 f = new.instancemethod(hook,self,self.__class__)
532 537
533 538 # check if the hook is for strdispatcher first
534 539 if str_key is not None:
535 540 sdp = self.strdispatchers.get(name, StrDispatch())
536 541 sdp.add_s(str_key, f, priority )
537 542 self.strdispatchers[name] = sdp
538 543 return
539 544 if re_key is not None:
540 545 sdp = self.strdispatchers.get(name, StrDispatch())
541 546 sdp.add_re(re.compile(re_key), f, priority )
542 547 self.strdispatchers[name] = sdp
543 548 return
544 549
545 550 dp = getattr(self.hooks, name, None)
546 551 if name not in IPython.core.hooks.__all__:
547 552 print "Warning! Hook '%s' is not one of %s" % \
548 553 (name, IPython.core.hooks.__all__ )
549 554 if not dp:
550 555 dp = IPython.core.hooks.CommandChainDispatcher()
551 556
552 557 try:
553 558 dp.add(f,priority)
554 559 except AttributeError:
555 560 # it was not commandchain, plain old func - replace
556 561 dp = f
557 562
558 563 setattr(self.hooks,name, dp)
559 564
560 565 #-------------------------------------------------------------------------
561 566 # Things related to the "main" module
562 567 #-------------------------------------------------------------------------
563 568
564 569 def new_main_mod(self,ns=None):
565 570 """Return a new 'main' module object for user code execution.
566 571 """
567 572 main_mod = self._user_main_module
568 573 init_fakemod_dict(main_mod,ns)
569 574 return main_mod
570 575
571 576 def cache_main_mod(self,ns,fname):
572 577 """Cache a main module's namespace.
573 578
574 579 When scripts are executed via %run, we must keep a reference to the
575 580 namespace of their __main__ module (a FakeModule instance) around so
576 581 that Python doesn't clear it, rendering objects defined therein
577 582 useless.
578 583
579 584 This method keeps said reference in a private dict, keyed by the
580 585 absolute path of the module object (which corresponds to the script
581 586 path). This way, for multiple executions of the same script we only
582 587 keep one copy of the namespace (the last one), thus preventing memory
583 588 leaks from old references while allowing the objects from the last
584 589 execution to be accessible.
585 590
586 591 Note: we can not allow the actual FakeModule instances to be deleted,
587 592 because of how Python tears down modules (it hard-sets all their
588 593 references to None without regard for reference counts). This method
589 594 must therefore make a *copy* of the given namespace, to allow the
590 595 original module's __dict__ to be cleared and reused.
591 596
592 597
593 598 Parameters
594 599 ----------
595 600 ns : a namespace (a dict, typically)
596 601
597 602 fname : str
598 603 Filename associated with the namespace.
599 604
600 605 Examples
601 606 --------
602 607
603 608 In [10]: import IPython
604 609
605 610 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
606 611
607 612 In [12]: IPython.__file__ in _ip._main_ns_cache
608 613 Out[12]: True
609 614 """
610 615 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
611 616
612 617 def clear_main_mod_cache(self):
613 618 """Clear the cache of main modules.
614 619
615 620 Mainly for use by utilities like %reset.
616 621
617 622 Examples
618 623 --------
619 624
620 625 In [15]: import IPython
621 626
622 627 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
623 628
624 629 In [17]: len(_ip._main_ns_cache) > 0
625 630 Out[17]: True
626 631
627 632 In [18]: _ip.clear_main_mod_cache()
628 633
629 634 In [19]: len(_ip._main_ns_cache) == 0
630 635 Out[19]: True
631 636 """
632 637 self._main_ns_cache.clear()
633 638
634 639 #-------------------------------------------------------------------------
635 640 # Things related to debugging
636 641 #-------------------------------------------------------------------------
637 642
638 643 def init_pdb(self):
639 644 # Set calling of pdb on exceptions
640 645 # self.call_pdb is a property
641 646 self.call_pdb = self.pdb
642 647
643 648 def _get_call_pdb(self):
644 649 return self._call_pdb
645 650
646 651 def _set_call_pdb(self,val):
647 652
648 653 if val not in (0,1,False,True):
649 654 raise ValueError,'new call_pdb value must be boolean'
650 655
651 656 # store value in instance
652 657 self._call_pdb = val
653 658
654 659 # notify the actual exception handlers
655 660 self.InteractiveTB.call_pdb = val
656 661
657 662 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
658 663 'Control auto-activation of pdb at exceptions')
659 664
660 665 def debugger(self,force=False):
661 666 """Call the pydb/pdb debugger.
662 667
663 668 Keywords:
664 669
665 670 - force(False): by default, this routine checks the instance call_pdb
666 671 flag and does not actually invoke the debugger if the flag is false.
667 672 The 'force' option forces the debugger to activate even if the flag
668 673 is false.
669 674 """
670 675
671 676 if not (force or self.call_pdb):
672 677 return
673 678
674 679 if not hasattr(sys,'last_traceback'):
675 680 error('No traceback has been produced, nothing to debug.')
676 681 return
677 682
678 683 # use pydb if available
679 684 if debugger.has_pydb:
680 685 from pydb import pm
681 686 else:
682 687 # fallback to our internal debugger
683 688 pm = lambda : self.InteractiveTB.debugger(force=True)
684 689 self.history_saving_wrapper(pm)()
685 690
686 691 #-------------------------------------------------------------------------
687 692 # Things related to IPython's various namespaces
688 693 #-------------------------------------------------------------------------
689 694
690 695 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
691 696 # Create the namespace where the user will operate. user_ns is
692 697 # normally the only one used, and it is passed to the exec calls as
693 698 # the locals argument. But we do carry a user_global_ns namespace
694 699 # given as the exec 'globals' argument, This is useful in embedding
695 700 # situations where the ipython shell opens in a context where the
696 701 # distinction between locals and globals is meaningful. For
697 702 # non-embedded contexts, it is just the same object as the user_ns dict.
698 703
699 704 # FIXME. For some strange reason, __builtins__ is showing up at user
700 705 # level as a dict instead of a module. This is a manual fix, but I
701 706 # should really track down where the problem is coming from. Alex
702 707 # Schmolck reported this problem first.
703 708
704 709 # A useful post by Alex Martelli on this topic:
705 710 # Re: inconsistent value from __builtins__
706 711 # Von: Alex Martelli <aleaxit@yahoo.com>
707 712 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
708 713 # Gruppen: comp.lang.python
709 714
710 715 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
711 716 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
712 717 # > <type 'dict'>
713 718 # > >>> print type(__builtins__)
714 719 # > <type 'module'>
715 720 # > Is this difference in return value intentional?
716 721
717 722 # Well, it's documented that '__builtins__' can be either a dictionary
718 723 # or a module, and it's been that way for a long time. Whether it's
719 724 # intentional (or sensible), I don't know. In any case, the idea is
720 725 # that if you need to access the built-in namespace directly, you
721 726 # should start with "import __builtin__" (note, no 's') which will
722 727 # definitely give you a module. Yeah, it's somewhat confusing:-(.
723 728
724 729 # These routines return properly built dicts as needed by the rest of
725 730 # the code, and can also be used by extension writers to generate
726 731 # properly initialized namespaces.
727 732 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
728 733 user_global_ns)
729 734
730 735 # Assign namespaces
731 736 # This is the namespace where all normal user variables live
732 737 self.user_ns = user_ns
733 738 self.user_global_ns = user_global_ns
734 739
735 740 # An auxiliary namespace that checks what parts of the user_ns were
736 741 # loaded at startup, so we can list later only variables defined in
737 742 # actual interactive use. Since it is always a subset of user_ns, it
738 743 # doesn't need to be separately tracked in the ns_table.
739 744 self.user_ns_hidden = {}
740 745
741 746 # A namespace to keep track of internal data structures to prevent
742 747 # them from cluttering user-visible stuff. Will be updated later
743 748 self.internal_ns = {}
744 749
745 750 # Now that FakeModule produces a real module, we've run into a nasty
746 751 # problem: after script execution (via %run), the module where the user
747 752 # code ran is deleted. Now that this object is a true module (needed
748 753 # so docetst and other tools work correctly), the Python module
749 754 # teardown mechanism runs over it, and sets to None every variable
750 755 # present in that module. Top-level references to objects from the
751 756 # script survive, because the user_ns is updated with them. However,
752 757 # calling functions defined in the script that use other things from
753 758 # the script will fail, because the function's closure had references
754 759 # to the original objects, which are now all None. So we must protect
755 760 # these modules from deletion by keeping a cache.
756 761 #
757 762 # To avoid keeping stale modules around (we only need the one from the
758 763 # last run), we use a dict keyed with the full path to the script, so
759 764 # only the last version of the module is held in the cache. Note,
760 765 # however, that we must cache the module *namespace contents* (their
761 766 # __dict__). Because if we try to cache the actual modules, old ones
762 767 # (uncached) could be destroyed while still holding references (such as
763 768 # those held by GUI objects that tend to be long-lived)>
764 769 #
765 770 # The %reset command will flush this cache. See the cache_main_mod()
766 771 # and clear_main_mod_cache() methods for details on use.
767 772
768 773 # This is the cache used for 'main' namespaces
769 774 self._main_ns_cache = {}
770 775 # And this is the single instance of FakeModule whose __dict__ we keep
771 776 # copying and clearing for reuse on each %run
772 777 self._user_main_module = FakeModule()
773 778
774 779 # A table holding all the namespaces IPython deals with, so that
775 780 # introspection facilities can search easily.
776 781 self.ns_table = {'user':user_ns,
777 782 'user_global':user_global_ns,
778 783 'internal':self.internal_ns,
779 784 'builtin':__builtin__.__dict__
780 785 }
781 786
782 787 # Similarly, track all namespaces where references can be held and that
783 788 # we can safely clear (so it can NOT include builtin). This one can be
784 789 # a simple list.
785 790 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
786 791 self.internal_ns, self._main_ns_cache ]
787 792
788 793 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
789 794 """Return a valid local and global user interactive namespaces.
790 795
791 796 This builds a dict with the minimal information needed to operate as a
792 797 valid IPython user namespace, which you can pass to the various
793 798 embedding classes in ipython. The default implementation returns the
794 799 same dict for both the locals and the globals to allow functions to
795 800 refer to variables in the namespace. Customized implementations can
796 801 return different dicts. The locals dictionary can actually be anything
797 802 following the basic mapping protocol of a dict, but the globals dict
798 803 must be a true dict, not even a subclass. It is recommended that any
799 804 custom object for the locals namespace synchronize with the globals
800 805 dict somehow.
801 806
802 807 Raises TypeError if the provided globals namespace is not a true dict.
803 808
804 809 Parameters
805 810 ----------
806 811 user_ns : dict-like, optional
807 812 The current user namespace. The items in this namespace should
808 813 be included in the output. If None, an appropriate blank
809 814 namespace should be created.
810 815 user_global_ns : dict, optional
811 816 The current user global namespace. The items in this namespace
812 817 should be included in the output. If None, an appropriate
813 818 blank namespace should be created.
814 819
815 820 Returns
816 821 -------
817 822 A pair of dictionary-like object to be used as the local namespace
818 823 of the interpreter and a dict to be used as the global namespace.
819 824 """
820 825
821 826
822 827 # We must ensure that __builtin__ (without the final 's') is always
823 828 # available and pointing to the __builtin__ *module*. For more details:
824 829 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
825 830
826 831 if user_ns is None:
827 832 # Set __name__ to __main__ to better match the behavior of the
828 833 # normal interpreter.
829 834 user_ns = {'__name__' :'__main__',
830 835 '__builtin__' : __builtin__,
831 836 '__builtins__' : __builtin__,
832 837 }
833 838 else:
834 839 user_ns.setdefault('__name__','__main__')
835 840 user_ns.setdefault('__builtin__',__builtin__)
836 841 user_ns.setdefault('__builtins__',__builtin__)
837 842
838 843 if user_global_ns is None:
839 844 user_global_ns = user_ns
840 845 if type(user_global_ns) is not dict:
841 846 raise TypeError("user_global_ns must be a true dict; got %r"
842 847 % type(user_global_ns))
843 848
844 849 return user_ns, user_global_ns
845 850
846 851 def init_sys_modules(self):
847 852 # We need to insert into sys.modules something that looks like a
848 853 # module but which accesses the IPython namespace, for shelve and
849 854 # pickle to work interactively. Normally they rely on getting
850 855 # everything out of __main__, but for embedding purposes each IPython
851 856 # instance has its own private namespace, so we can't go shoving
852 857 # everything into __main__.
853 858
854 859 # note, however, that we should only do this for non-embedded
855 860 # ipythons, which really mimic the __main__.__dict__ with their own
856 861 # namespace. Embedded instances, on the other hand, should not do
857 862 # this because they need to manage the user local/global namespaces
858 863 # only, but they live within a 'normal' __main__ (meaning, they
859 864 # shouldn't overtake the execution environment of the script they're
860 865 # embedded in).
861 866
862 867 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
863 868
864 869 try:
865 870 main_name = self.user_ns['__name__']
866 871 except KeyError:
867 872 raise KeyError('user_ns dictionary MUST have a "__name__" key')
868 873 else:
869 874 sys.modules[main_name] = FakeModule(self.user_ns)
870 875
871 876 def init_user_ns(self):
872 877 """Initialize all user-visible namespaces to their minimum defaults.
873 878
874 879 Certain history lists are also initialized here, as they effectively
875 880 act as user namespaces.
876 881
877 882 Notes
878 883 -----
879 884 All data structures here are only filled in, they are NOT reset by this
880 885 method. If they were not empty before, data will simply be added to
881 886 therm.
882 887 """
883 888 # This function works in two parts: first we put a few things in
884 889 # user_ns, and we sync that contents into user_ns_hidden so that these
885 890 # initial variables aren't shown by %who. After the sync, we add the
886 891 # rest of what we *do* want the user to see with %who even on a new
887 892 # session (probably nothing, so theye really only see their own stuff)
888 893
889 894 # The user dict must *always* have a __builtin__ reference to the
890 895 # Python standard __builtin__ namespace, which must be imported.
891 896 # This is so that certain operations in prompt evaluation can be
892 897 # reliably executed with builtins. Note that we can NOT use
893 898 # __builtins__ (note the 's'), because that can either be a dict or a
894 899 # module, and can even mutate at runtime, depending on the context
895 900 # (Python makes no guarantees on it). In contrast, __builtin__ is
896 901 # always a module object, though it must be explicitly imported.
897 902
898 903 # For more details:
899 904 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
900 905 ns = dict(__builtin__ = __builtin__)
901 906
902 907 # Put 'help' in the user namespace
903 908 try:
904 909 from site import _Helper
905 910 ns['help'] = _Helper()
906 911 except ImportError:
907 912 warn('help() not available - check site.py')
908 913
909 914 # make global variables for user access to the histories
910 915 ns['_ih'] = self.input_hist
911 916 ns['_oh'] = self.output_hist
912 917 ns['_dh'] = self.dir_hist
913 918
914 919 ns['_sh'] = shadowns
915 920
916 921 # user aliases to input and output histories. These shouldn't show up
917 922 # in %who, as they can have very large reprs.
918 923 ns['In'] = self.input_hist
919 924 ns['Out'] = self.output_hist
920 925
921 926 # Store myself as the public api!!!
922 927 ns['get_ipython'] = self.get_ipython
923 928
924 929 # Sync what we've added so far to user_ns_hidden so these aren't seen
925 930 # by %who
926 931 self.user_ns_hidden.update(ns)
927 932
928 933 # Anything put into ns now would show up in %who. Think twice before
929 934 # putting anything here, as we really want %who to show the user their
930 935 # stuff, not our variables.
931 936
932 937 # Finally, update the real user's namespace
933 938 self.user_ns.update(ns)
934 939
935 940
936 941 def reset(self):
937 942 """Clear all internal namespaces.
938 943
939 944 Note that this is much more aggressive than %reset, since it clears
940 945 fully all namespaces, as well as all input/output lists.
941 946 """
942 947 for ns in self.ns_refs_table:
943 948 ns.clear()
944 949
945 950 self.alias_manager.clear_aliases()
946 951
947 952 # Clear input and output histories
948 953 self.input_hist[:] = []
949 954 self.input_hist_raw[:] = []
950 955 self.output_hist.clear()
951 956
952 957 # Restore the user namespaces to minimal usability
953 958 self.init_user_ns()
954 959
955 960 # Restore the default and user aliases
956 961 self.alias_manager.init_aliases()
957 962
958 963 def reset_selective(self, regex=None):
959 964 """Clear selective variables from internal namespaces based on a
960 965 specified regular expression.
961 966
962 967 Parameters
963 968 ----------
964 969 regex : string or compiled pattern, optional
965 970 A regular expression pattern that will be used in searching
966 971 variable names in the users namespaces.
967 972 """
968 973 if regex is not None:
969 974 try:
970 975 m = re.compile(regex)
971 976 except TypeError:
972 977 raise TypeError('regex must be a string or compiled pattern')
973 978 # Search for keys in each namespace that match the given regex
974 979 # If a match is found, delete the key/value pair.
975 980 for ns in self.ns_refs_table:
976 981 for var in ns:
977 982 if m.search(var):
978 983 del ns[var]
979 984
980 985 def push(self, variables, interactive=True):
981 986 """Inject a group of variables into the IPython user namespace.
982 987
983 988 Parameters
984 989 ----------
985 990 variables : dict, str or list/tuple of str
986 991 The variables to inject into the user's namespace. If a dict, a
987 992 simple update is done. If a str, the string is assumed to have
988 993 variable names separated by spaces. A list/tuple of str can also
989 994 be used to give the variable names. If just the variable names are
990 995 give (list/tuple/str) then the variable values looked up in the
991 996 callers frame.
992 997 interactive : bool
993 998 If True (default), the variables will be listed with the ``who``
994 999 magic.
995 1000 """
996 1001 vdict = None
997 1002
998 1003 # We need a dict of name/value pairs to do namespace updates.
999 1004 if isinstance(variables, dict):
1000 1005 vdict = variables
1001 1006 elif isinstance(variables, (basestring, list, tuple)):
1002 1007 if isinstance(variables, basestring):
1003 1008 vlist = variables.split()
1004 1009 else:
1005 1010 vlist = variables
1006 1011 vdict = {}
1007 1012 cf = sys._getframe(1)
1008 1013 for name in vlist:
1009 1014 try:
1010 1015 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1011 1016 except:
1012 1017 print ('Could not get variable %s from %s' %
1013 1018 (name,cf.f_code.co_name))
1014 1019 else:
1015 1020 raise ValueError('variables must be a dict/str/list/tuple')
1016 1021
1017 1022 # Propagate variables to user namespace
1018 1023 self.user_ns.update(vdict)
1019 1024
1020 1025 # And configure interactive visibility
1021 1026 config_ns = self.user_ns_hidden
1022 1027 if interactive:
1023 1028 for name, val in vdict.iteritems():
1024 1029 config_ns.pop(name, None)
1025 1030 else:
1026 1031 for name,val in vdict.iteritems():
1027 1032 config_ns[name] = val
1028 1033
1029 1034 #-------------------------------------------------------------------------
1030 1035 # Things related to object introspection
1031 1036 #-------------------------------------------------------------------------
1032 1037 def _ofind(self, oname, namespaces=None):
1033 1038 """Find an object in the available namespaces.
1034 1039
1035 1040 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1036 1041
1037 1042 Has special code to detect magic functions.
1038 1043 """
1039 1044 #oname = oname.strip()
1040 1045 #print '1- oname: <%r>' % oname # dbg
1041 1046 try:
1042 1047 oname = oname.strip().encode('ascii')
1043 1048 #print '2- oname: <%r>' % oname # dbg
1044 1049 except UnicodeEncodeError:
1045 1050 print 'Python identifiers can only contain ascii characters.'
1046 1051 return dict(found=False)
1047 1052
1048 1053 alias_ns = None
1049 1054 if namespaces is None:
1050 1055 # Namespaces to search in:
1051 1056 # Put them in a list. The order is important so that we
1052 1057 # find things in the same order that Python finds them.
1053 1058 namespaces = [ ('Interactive', self.user_ns),
1054 1059 ('IPython internal', self.internal_ns),
1055 1060 ('Python builtin', __builtin__.__dict__),
1056 1061 ('Alias', self.alias_manager.alias_table),
1057 1062 ]
1058 1063 alias_ns = self.alias_manager.alias_table
1059 1064
1060 1065 # initialize results to 'null'
1061 1066 found = False; obj = None; ospace = None; ds = None;
1062 1067 ismagic = False; isalias = False; parent = None
1063 1068
1064 1069 # We need to special-case 'print', which as of python2.6 registers as a
1065 1070 # function but should only be treated as one if print_function was
1066 1071 # loaded with a future import. In this case, just bail.
1067 1072 if (oname == 'print' and not (self.compile.compiler.flags &
1068 1073 __future__.CO_FUTURE_PRINT_FUNCTION)):
1069 1074 return {'found':found, 'obj':obj, 'namespace':ospace,
1070 1075 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1071 1076
1072 1077 # Look for the given name by splitting it in parts. If the head is
1073 1078 # found, then we look for all the remaining parts as members, and only
1074 1079 # declare success if we can find them all.
1075 1080 oname_parts = oname.split('.')
1076 1081 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1077 1082 for nsname,ns in namespaces:
1078 1083 try:
1079 1084 obj = ns[oname_head]
1080 1085 except KeyError:
1081 1086 continue
1082 1087 else:
1083 1088 #print 'oname_rest:', oname_rest # dbg
1084 1089 for part in oname_rest:
1085 1090 try:
1086 1091 parent = obj
1087 1092 obj = getattr(obj,part)
1088 1093 except:
1089 1094 # Blanket except b/c some badly implemented objects
1090 1095 # allow __getattr__ to raise exceptions other than
1091 1096 # AttributeError, which then crashes IPython.
1092 1097 break
1093 1098 else:
1094 1099 # If we finish the for loop (no break), we got all members
1095 1100 found = True
1096 1101 ospace = nsname
1097 1102 if ns == alias_ns:
1098 1103 isalias = True
1099 1104 break # namespace loop
1100 1105
1101 1106 # Try to see if it's magic
1102 1107 if not found:
1103 1108 if oname.startswith(ESC_MAGIC):
1104 1109 oname = oname[1:]
1105 1110 obj = getattr(self,'magic_'+oname,None)
1106 1111 if obj is not None:
1107 1112 found = True
1108 1113 ospace = 'IPython internal'
1109 1114 ismagic = True
1110 1115
1111 1116 # Last try: special-case some literals like '', [], {}, etc:
1112 1117 if not found and oname_head in ["''",'""','[]','{}','()']:
1113 1118 obj = eval(oname_head)
1114 1119 found = True
1115 1120 ospace = 'Interactive'
1116 1121
1117 1122 return {'found':found, 'obj':obj, 'namespace':ospace,
1118 1123 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1119 1124
1120 1125 def _ofind_property(self, oname, info):
1121 1126 """Second part of object finding, to look for property details."""
1122 1127 if info.found:
1123 1128 # Get the docstring of the class property if it exists.
1124 1129 path = oname.split('.')
1125 1130 root = '.'.join(path[:-1])
1126 1131 if info.parent is not None:
1127 1132 try:
1128 1133 target = getattr(info.parent, '__class__')
1129 1134 # The object belongs to a class instance.
1130 1135 try:
1131 1136 target = getattr(target, path[-1])
1132 1137 # The class defines the object.
1133 1138 if isinstance(target, property):
1134 1139 oname = root + '.__class__.' + path[-1]
1135 1140 info = Struct(self._ofind(oname))
1136 1141 except AttributeError: pass
1137 1142 except AttributeError: pass
1138 1143
1139 1144 # We return either the new info or the unmodified input if the object
1140 1145 # hadn't been found
1141 1146 return info
1142 1147
1143 1148 def _object_find(self, oname, namespaces=None):
1144 1149 """Find an object and return a struct with info about it."""
1145 1150 inf = Struct(self._ofind(oname, namespaces))
1146 1151 return Struct(self._ofind_property(oname, inf))
1147 1152
1148 1153 def _inspect(self, meth, oname, namespaces=None, **kw):
1149 1154 """Generic interface to the inspector system.
1150 1155
1151 1156 This function is meant to be called by pdef, pdoc & friends."""
1152 1157 info = self._object_find(oname)
1153 1158 if info.found:
1154 1159 pmethod = getattr(self.inspector, meth)
1155 1160 formatter = format_screen if info.ismagic else None
1156 1161 if meth == 'pdoc':
1157 1162 pmethod(info.obj, oname, formatter)
1158 1163 elif meth == 'pinfo':
1159 1164 pmethod(info.obj, oname, formatter, info, **kw)
1160 1165 else:
1161 1166 pmethod(info.obj, oname)
1162 1167 else:
1163 1168 print 'Object `%s` not found.' % oname
1164 1169 return 'not found' # so callers can take other action
1165 1170
1166 1171 def object_inspect(self, oname):
1167 1172 info = self._object_find(oname)
1168 1173 if info.found:
1169 1174 return self.inspector.info(info.obj, info=info)
1170 1175 else:
1171 1176 return oinspect.mk_object_info({'found' : False})
1172 1177
1173 1178 #-------------------------------------------------------------------------
1174 1179 # Things related to history management
1175 1180 #-------------------------------------------------------------------------
1176 1181
1177 1182 def init_history(self):
1178 1183 # List of input with multi-line handling.
1179 1184 self.input_hist = InputList()
1180 1185 # This one will hold the 'raw' input history, without any
1181 1186 # pre-processing. This will allow users to retrieve the input just as
1182 1187 # it was exactly typed in by the user, with %hist -r.
1183 1188 self.input_hist_raw = InputList()
1184 1189
1185 1190 # list of visited directories
1186 1191 try:
1187 1192 self.dir_hist = [os.getcwd()]
1188 1193 except OSError:
1189 1194 self.dir_hist = []
1190 1195
1191 1196 # dict of output history
1192 1197 self.output_hist = {}
1193 1198
1194 1199 # Now the history file
1195 1200 if self.profile:
1196 1201 histfname = 'history-%s' % self.profile
1197 1202 else:
1198 1203 histfname = 'history'
1199 1204 self.histfile = os.path.join(self.ipython_dir, histfname)
1200 1205
1201 1206 # Fill the history zero entry, user counter starts at 1
1202 1207 self.input_hist.append('\n')
1203 1208 self.input_hist_raw.append('\n')
1204 1209
1205 1210 def init_shadow_hist(self):
1206 1211 try:
1207 1212 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1208 1213 except exceptions.UnicodeDecodeError:
1209 1214 print "Your ipython_dir can't be decoded to unicode!"
1210 1215 print "Please set HOME environment variable to something that"
1211 1216 print r"only has ASCII characters, e.g. c:\home"
1212 1217 print "Now it is", self.ipython_dir
1213 1218 sys.exit()
1214 1219 self.shadowhist = ipcorehist.ShadowHist(self.db)
1215 1220
1216 1221 def savehist(self):
1217 1222 """Save input history to a file (via readline library)."""
1218 1223
1219 1224 try:
1220 1225 self.readline.write_history_file(self.histfile)
1221 1226 except:
1222 1227 print 'Unable to save IPython command history to file: ' + \
1223 1228 `self.histfile`
1224 1229
1225 1230 def reloadhist(self):
1226 1231 """Reload the input history from disk file."""
1227 1232
1228 1233 try:
1229 1234 self.readline.clear_history()
1230 1235 self.readline.read_history_file(self.shell.histfile)
1231 1236 except AttributeError:
1232 1237 pass
1233 1238
1234 1239 def history_saving_wrapper(self, func):
1235 1240 """ Wrap func for readline history saving
1236 1241
1237 1242 Convert func into callable that saves & restores
1238 1243 history around the call """
1239 1244
1240 1245 if self.has_readline:
1241 1246 from IPython.utils import rlineimpl as readline
1242 1247 else:
1243 1248 return func
1244 1249
1245 1250 def wrapper():
1246 1251 self.savehist()
1247 1252 try:
1248 1253 func()
1249 1254 finally:
1250 1255 readline.read_history_file(self.histfile)
1251 1256 return wrapper
1252 1257
1253 1258 def get_history(self, index=None, raw=False, output=True):
1254 1259 """Get the history list.
1255 1260
1256 1261 Get the input and output history.
1257 1262
1258 1263 Parameters
1259 1264 ----------
1260 1265 index : n or (n1, n2) or None
1261 1266 If n, then the last entries. If a tuple, then all in
1262 1267 range(n1, n2). If None, then all entries. Raises IndexError if
1263 1268 the format of index is incorrect.
1264 1269 raw : bool
1265 1270 If True, return the raw input.
1266 1271 output : bool
1267 1272 If True, then return the output as well.
1268 1273
1269 1274 Returns
1270 1275 -------
1271 1276 If output is True, then return a dict of tuples, keyed by the prompt
1272 1277 numbers and with values of (input, output). If output is False, then
1273 1278 a dict, keyed by the prompt number with the values of input. Raises
1274 1279 IndexError if no history is found.
1275 1280 """
1276 1281 if raw:
1277 1282 input_hist = self.input_hist_raw
1278 1283 else:
1279 1284 input_hist = self.input_hist
1280 1285 if output:
1281 1286 output_hist = self.user_ns['Out']
1282 1287 n = len(input_hist)
1283 1288 if index is None:
1284 1289 start=0; stop=n
1285 1290 elif isinstance(index, int):
1286 1291 start=n-index; stop=n
1287 1292 elif isinstance(index, tuple) and len(index) == 2:
1288 1293 start=index[0]; stop=index[1]
1289 1294 else:
1290 1295 raise IndexError('Not a valid index for the input history: %r'
1291 1296 % index)
1292 1297 hist = {}
1293 1298 for i in range(start, stop):
1294 1299 if output:
1295 1300 hist[i] = (input_hist[i], output_hist.get(i))
1296 1301 else:
1297 1302 hist[i] = input_hist[i]
1298 1303 if len(hist)==0:
1299 1304 raise IndexError('No history for range of indices: %r' % index)
1300 1305 return hist
1301 1306
1302 1307 #-------------------------------------------------------------------------
1303 1308 # Things related to exception handling and tracebacks (not debugging)
1304 1309 #-------------------------------------------------------------------------
1305 1310
1306 1311 def init_traceback_handlers(self, custom_exceptions):
1307 1312 # Syntax error handler.
1308 1313 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1309 1314
1310 1315 # The interactive one is initialized with an offset, meaning we always
1311 1316 # want to remove the topmost item in the traceback, which is our own
1312 1317 # internal code. Valid modes: ['Plain','Context','Verbose']
1313 1318 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1314 1319 color_scheme='NoColor',
1315 1320 tb_offset = 1)
1316 1321
1317 1322 # The instance will store a pointer to the system-wide exception hook,
1318 1323 # so that runtime code (such as magics) can access it. This is because
1319 1324 # during the read-eval loop, it may get temporarily overwritten.
1320 1325 self.sys_excepthook = sys.excepthook
1321 1326
1322 1327 # and add any custom exception handlers the user may have specified
1323 1328 self.set_custom_exc(*custom_exceptions)
1324 1329
1325 1330 # Set the exception mode
1326 1331 self.InteractiveTB.set_mode(mode=self.xmode)
1327 1332
1328 1333 def set_custom_exc(self, exc_tuple, handler):
1329 1334 """set_custom_exc(exc_tuple,handler)
1330 1335
1331 1336 Set a custom exception handler, which will be called if any of the
1332 1337 exceptions in exc_tuple occur in the mainloop (specifically, in the
1333 1338 runcode() method.
1334 1339
1335 1340 Inputs:
1336 1341
1337 1342 - exc_tuple: a *tuple* of valid exceptions to call the defined
1338 1343 handler for. It is very important that you use a tuple, and NOT A
1339 1344 LIST here, because of the way Python's except statement works. If
1340 1345 you only want to trap a single exception, use a singleton tuple:
1341 1346
1342 1347 exc_tuple == (MyCustomException,)
1343 1348
1344 1349 - handler: this must be defined as a function with the following
1345 1350 basic interface::
1346 1351
1347 1352 def my_handler(self, etype, value, tb, tb_offset=None)
1348 1353 ...
1349 1354 # The return value must be
1350 1355 return structured_traceback
1351 1356
1352 1357 This will be made into an instance method (via new.instancemethod)
1353 1358 of IPython itself, and it will be called if any of the exceptions
1354 1359 listed in the exc_tuple are caught. If the handler is None, an
1355 1360 internal basic one is used, which just prints basic info.
1356 1361
1357 1362 WARNING: by putting in your own exception handler into IPython's main
1358 1363 execution loop, you run a very good chance of nasty crashes. This
1359 1364 facility should only be used if you really know what you are doing."""
1360 1365
1361 1366 assert type(exc_tuple)==type(()) , \
1362 1367 "The custom exceptions must be given AS A TUPLE."
1363 1368
1364 1369 def dummy_handler(self,etype,value,tb):
1365 1370 print '*** Simple custom exception handler ***'
1366 1371 print 'Exception type :',etype
1367 1372 print 'Exception value:',value
1368 1373 print 'Traceback :',tb
1369 1374 print 'Source code :','\n'.join(self.buffer)
1370 1375
1371 1376 if handler is None: handler = dummy_handler
1372 1377
1373 1378 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1374 1379 self.custom_exceptions = exc_tuple
1375 1380
1376 1381 def excepthook(self, etype, value, tb):
1377 1382 """One more defense for GUI apps that call sys.excepthook.
1378 1383
1379 1384 GUI frameworks like wxPython trap exceptions and call
1380 1385 sys.excepthook themselves. I guess this is a feature that
1381 1386 enables them to keep running after exceptions that would
1382 1387 otherwise kill their mainloop. This is a bother for IPython
1383 1388 which excepts to catch all of the program exceptions with a try:
1384 1389 except: statement.
1385 1390
1386 1391 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1387 1392 any app directly invokes sys.excepthook, it will look to the user like
1388 1393 IPython crashed. In order to work around this, we can disable the
1389 1394 CrashHandler and replace it with this excepthook instead, which prints a
1390 1395 regular traceback using our InteractiveTB. In this fashion, apps which
1391 1396 call sys.excepthook will generate a regular-looking exception from
1392 1397 IPython, and the CrashHandler will only be triggered by real IPython
1393 1398 crashes.
1394 1399
1395 1400 This hook should be used sparingly, only in places which are not likely
1396 1401 to be true IPython errors.
1397 1402 """
1398 1403 self.showtraceback((etype,value,tb),tb_offset=0)
1399 1404
1400 1405 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1401 1406 exception_only=False):
1402 1407 """Display the exception that just occurred.
1403 1408
1404 1409 If nothing is known about the exception, this is the method which
1405 1410 should be used throughout the code for presenting user tracebacks,
1406 1411 rather than directly invoking the InteractiveTB object.
1407 1412
1408 1413 A specific showsyntaxerror() also exists, but this method can take
1409 1414 care of calling it if needed, so unless you are explicitly catching a
1410 1415 SyntaxError exception, don't try to analyze the stack manually and
1411 1416 simply call this method."""
1412 1417
1413 1418 try:
1414 1419 if exc_tuple is None:
1415 1420 etype, value, tb = sys.exc_info()
1416 1421 else:
1417 1422 etype, value, tb = exc_tuple
1418 1423
1419 1424 if etype is None:
1420 1425 if hasattr(sys, 'last_type'):
1421 1426 etype, value, tb = sys.last_type, sys.last_value, \
1422 1427 sys.last_traceback
1423 1428 else:
1424 1429 self.write_err('No traceback available to show.\n')
1425 1430 return
1426 1431
1427 1432 if etype is SyntaxError:
1428 1433 # Though this won't be called by syntax errors in the input
1429 1434 # line, there may be SyntaxError cases whith imported code.
1430 1435 self.showsyntaxerror(filename)
1431 1436 elif etype is UsageError:
1432 1437 print "UsageError:", value
1433 1438 else:
1434 1439 # WARNING: these variables are somewhat deprecated and not
1435 1440 # necessarily safe to use in a threaded environment, but tools
1436 1441 # like pdb depend on their existence, so let's set them. If we
1437 1442 # find problems in the field, we'll need to revisit their use.
1438 1443 sys.last_type = etype
1439 1444 sys.last_value = value
1440 1445 sys.last_traceback = tb
1441 1446
1442 1447 if etype in self.custom_exceptions:
1443 1448 # FIXME: Old custom traceback objects may just return a
1444 1449 # string, in that case we just put it into a list
1445 1450 stb = self.CustomTB(etype, value, tb, tb_offset)
1446 1451 if isinstance(ctb, basestring):
1447 1452 stb = [stb]
1448 1453 else:
1449 1454 if exception_only:
1450 1455 stb = ['An exception has occurred, use %tb to see '
1451 1456 'the full traceback.\n']
1452 1457 stb.extend(self.InteractiveTB.get_exception_only(etype,
1453 1458 value))
1454 1459 else:
1455 1460 stb = self.InteractiveTB.structured_traceback(etype,
1456 1461 value, tb, tb_offset=tb_offset)
1457 1462 # FIXME: the pdb calling should be done by us, not by
1458 1463 # the code computing the traceback.
1459 1464 if self.InteractiveTB.call_pdb:
1460 1465 # pdb mucks up readline, fix it back
1461 1466 self.set_readline_completer()
1462 1467
1463 1468 # Actually show the traceback
1464 1469 self._showtraceback(etype, value, stb)
1465 1470
1466 1471 except KeyboardInterrupt:
1467 1472 self.write_err("\nKeyboardInterrupt\n")
1468 1473
1469 1474 def _showtraceback(self, etype, evalue, stb):
1470 1475 """Actually show a traceback.
1471 1476
1472 1477 Subclasses may override this method to put the traceback on a different
1473 1478 place, like a side channel.
1474 1479 """
1475 1480 # FIXME: this should use the proper write channels, but our test suite
1476 1481 # relies on it coming out of stdout...
1477 1482 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1478 1483
1479 1484 def showsyntaxerror(self, filename=None):
1480 1485 """Display the syntax error that just occurred.
1481 1486
1482 1487 This doesn't display a stack trace because there isn't one.
1483 1488
1484 1489 If a filename is given, it is stuffed in the exception instead
1485 1490 of what was there before (because Python's parser always uses
1486 1491 "<string>" when reading from a string).
1487 1492 """
1488 1493 etype, value, last_traceback = sys.exc_info()
1489 1494
1490 1495 # See note about these variables in showtraceback() above
1491 1496 sys.last_type = etype
1492 1497 sys.last_value = value
1493 1498 sys.last_traceback = last_traceback
1494 1499
1495 1500 if filename and etype is SyntaxError:
1496 1501 # Work hard to stuff the correct filename in the exception
1497 1502 try:
1498 1503 msg, (dummy_filename, lineno, offset, line) = value
1499 1504 except:
1500 1505 # Not the format we expect; leave it alone
1501 1506 pass
1502 1507 else:
1503 1508 # Stuff in the right filename
1504 1509 try:
1505 1510 # Assume SyntaxError is a class exception
1506 1511 value = SyntaxError(msg, (filename, lineno, offset, line))
1507 1512 except:
1508 1513 # If that failed, assume SyntaxError is a string
1509 1514 value = msg, (filename, lineno, offset, line)
1510 1515 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1511 1516 self._showtraceback(etype, value, stb)
1512 1517
1513 1518 #-------------------------------------------------------------------------
1514 # Things related to tab completion
1515 #-------------------------------------------------------------------------
1516
1517 def complete(self, text, line=None, cursor_pos=None):
1518 """Return the completed text and a list of completions.
1519
1520 Parameters
1521 ----------
1522
1523 text : string
1524 A string of text to be completed on. It can be given as empty and
1525 instead a line/position pair are given. In this case, the
1526 completer itself will split the line like readline does.
1527
1528 line : string, optional
1529 The complete line that text is part of.
1530
1531 cursor_pos : int, optional
1532 The position of the cursor on the input line.
1533
1534 Returns
1535 -------
1536 text : string
1537 The actual text that was completed.
1538
1539 matches : list
1540 A sorted list with all possible completions.
1541
1542 The optional arguments allow the completion to take more context into
1543 account, and are part of the low-level completion API.
1544
1545 This is a wrapper around the completion mechanism, similar to what
1546 readline does at the command line when the TAB key is hit. By
1547 exposing it as a method, it can be used by other non-readline
1548 environments (such as GUIs) for text completion.
1549
1550 Simple usage example:
1551
1552 In [1]: x = 'hello'
1553
1554 In [2]: _ip.complete('x.l')
1555 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1556 """
1557
1558 # Inject names into __builtin__ so we can complete on the added names.
1559 with self.builtin_trap:
1560 return self.Completer.complete(text, line, cursor_pos)
1561
1562 def set_custom_completer(self, completer, pos=0):
1563 """Adds a new custom completer function.
1564
1565 The position argument (defaults to 0) is the index in the completers
1566 list where you want the completer to be inserted."""
1567
1568 newcomp = new.instancemethod(completer,self.Completer,
1569 self.Completer.__class__)
1570 self.Completer.matchers.insert(pos,newcomp)
1571
1572 def set_readline_completer(self):
1573 """Reset readline's completer to be our own."""
1574 self.readline.set_completer(self.Completer.rlcomplete)
1575
1576 def set_completer_frame(self, frame=None):
1577 """Set the frame of the completer."""
1578 if frame:
1579 self.Completer.namespace = frame.f_locals
1580 self.Completer.global_namespace = frame.f_globals
1581 else:
1582 self.Completer.namespace = self.user_ns
1583 self.Completer.global_namespace = self.user_global_ns
1584
1585 #-------------------------------------------------------------------------
1586 1519 # Things related to readline
1587 1520 #-------------------------------------------------------------------------
1588 1521
1589 1522 def init_readline(self):
1590 1523 """Command history completion/saving/reloading."""
1591 1524
1592 1525 if self.readline_use:
1593 1526 import IPython.utils.rlineimpl as readline
1594 1527
1595 1528 self.rl_next_input = None
1596 1529 self.rl_do_indent = False
1597 1530
1598 1531 if not self.readline_use or not readline.have_readline:
1599 1532 self.has_readline = False
1600 1533 self.readline = None
1601 1534 # Set a number of methods that depend on readline to be no-op
1602 1535 self.savehist = no_op
1603 1536 self.reloadhist = no_op
1604 1537 self.set_readline_completer = no_op
1605 1538 self.set_custom_completer = no_op
1606 1539 self.set_completer_frame = no_op
1607 1540 warn('Readline services not available or not loaded.')
1608 1541 else:
1609 1542 self.has_readline = True
1610 1543 self.readline = readline
1611 1544 sys.modules['readline'] = readline
1612 1545
1613 from IPython.core.completer import IPCompleter
1614 self.Completer = IPCompleter(self,
1615 self.user_ns,
1616 self.user_global_ns,
1617 self.readline_omit__names,
1618 self.alias_manager.alias_table)
1619 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1620 self.strdispatchers['complete_command'] = sdisp
1621 self.Completer.custom_completers = sdisp
1622
1623 1546 # Platform-specific configuration
1624 1547 if os.name == 'nt':
1625 1548 # FIXME - check with Frederick to see if we can harmonize
1626 1549 # naming conventions with pyreadline to avoid this
1627 1550 # platform-dependent check
1628 1551 self.readline_startup_hook = readline.set_pre_input_hook
1629 1552 else:
1630 1553 self.readline_startup_hook = readline.set_startup_hook
1631 1554
1632 1555 # Load user's initrc file (readline config)
1633 1556 # Or if libedit is used, load editrc.
1634 1557 inputrc_name = os.environ.get('INPUTRC')
1635 1558 if inputrc_name is None:
1636 1559 home_dir = get_home_dir()
1637 1560 if home_dir is not None:
1638 1561 inputrc_name = '.inputrc'
1639 1562 if readline.uses_libedit:
1640 1563 inputrc_name = '.editrc'
1641 1564 inputrc_name = os.path.join(home_dir, inputrc_name)
1642 1565 if os.path.isfile(inputrc_name):
1643 1566 try:
1644 1567 readline.read_init_file(inputrc_name)
1645 1568 except:
1646 1569 warn('Problems reading readline initialization file <%s>'
1647 1570 % inputrc_name)
1648 1571
1649 self.set_readline_completer()
1650
1651 1572 # Configure readline according to user's prefs
1652 1573 # This is only done if GNU readline is being used. If libedit
1653 1574 # is being used (as on Leopard) the readline config is
1654 1575 # not run as the syntax for libedit is different.
1655 1576 if not readline.uses_libedit:
1656 1577 for rlcommand in self.readline_parse_and_bind:
1657 1578 #print "loading rl:",rlcommand # dbg
1658 1579 readline.parse_and_bind(rlcommand)
1659 1580
1660 1581 # Remove some chars from the delimiters list. If we encounter
1661 1582 # unicode chars, discard them.
1662 1583 delims = readline.get_completer_delims().encode("ascii", "ignore")
1663 1584 delims = delims.translate(string._idmap,
1664 1585 self.readline_remove_delims)
1586 delims = delims.replace(ESC_MAGIC, '')
1665 1587 readline.set_completer_delims(delims)
1666 1588 # otherwise we end up with a monster history after a while:
1667 1589 readline.set_history_length(1000)
1668 1590 try:
1669 1591 #print '*** Reading readline history' # dbg
1670 1592 readline.read_history_file(self.histfile)
1671 1593 except IOError:
1672 1594 pass # It doesn't exist yet.
1673 1595
1674 1596 # If we have readline, we want our history saved upon ipython
1675 1597 # exiting.
1676 1598 atexit.register(self.savehist)
1677 1599
1678 1600 # Configure auto-indent for all platforms
1679 1601 self.set_autoindent(self.autoindent)
1680 1602
1681 1603 def set_next_input(self, s):
1682 1604 """ Sets the 'default' input string for the next command line.
1683 1605
1684 1606 Requires readline.
1685 1607
1686 1608 Example:
1687 1609
1688 1610 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1689 1611 [D:\ipython]|2> Hello Word_ # cursor is here
1690 1612 """
1691 1613
1692 1614 self.rl_next_input = s
1693 1615
1694 1616 # Maybe move this to the terminal subclass?
1695 1617 def pre_readline(self):
1696 1618 """readline hook to be used at the start of each line.
1697 1619
1698 1620 Currently it handles auto-indent only."""
1699 1621
1700 1622 if self.rl_do_indent:
1701 1623 self.readline.insert_text(self._indent_current_str())
1702 1624 if self.rl_next_input is not None:
1703 1625 self.readline.insert_text(self.rl_next_input)
1704 1626 self.rl_next_input = None
1705 1627
1706 1628 def _indent_current_str(self):
1707 1629 """return the current level of indentation as a string"""
1708 1630 return self.indent_current_nsp * ' '
1709 1631
1710 1632 #-------------------------------------------------------------------------
1633 # Things related to text completion
1634 #-------------------------------------------------------------------------
1635
1636 def init_completer(self):
1637 """Initialize the completion machinery.
1638
1639 This creates completion machinery that can be used by client code,
1640 either interactively in-process (typically triggered by the readline
1641 library), programatically (such as in test suites) or out-of-prcess
1642 (typically over the network by remote frontends).
1643 """
1644 from IPython.core.completer import IPCompleter
1645 self.Completer = IPCompleter(self,
1646 self.user_ns,
1647 self.user_global_ns,
1648 self.readline_omit__names,
1649 self.alias_manager.alias_table,
1650 self.has_readline)
1651 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1652 self.strdispatchers['complete_command'] = sdisp
1653 self.Completer.custom_completers = sdisp
1654
1655 if self.has_readline:
1656 self.set_readline_completer()
1657
1658 def complete(self, text, line=None, cursor_pos=None):
1659 """Return the completed text and a list of completions.
1660
1661 Parameters
1662 ----------
1663
1664 text : string
1665 A string of text to be completed on. It can be given as empty and
1666 instead a line/position pair are given. In this case, the
1667 completer itself will split the line like readline does.
1668
1669 line : string, optional
1670 The complete line that text is part of.
1671
1672 cursor_pos : int, optional
1673 The position of the cursor on the input line.
1674
1675 Returns
1676 -------
1677 text : string
1678 The actual text that was completed.
1679
1680 matches : list
1681 A sorted list with all possible completions.
1682
1683 The optional arguments allow the completion to take more context into
1684 account, and are part of the low-level completion API.
1685
1686 This is a wrapper around the completion mechanism, similar to what
1687 readline does at the command line when the TAB key is hit. By
1688 exposing it as a method, it can be used by other non-readline
1689 environments (such as GUIs) for text completion.
1690
1691 Simple usage example:
1692
1693 In [1]: x = 'hello'
1694
1695 In [2]: _ip.complete('x.l')
1696 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1697 """
1698
1699 # Inject names into __builtin__ so we can complete on the added names.
1700 with self.builtin_trap:
1701 return self.Completer.complete(text, line, cursor_pos)
1702
1703 def set_custom_completer(self, completer, pos=0):
1704 """Adds a new custom completer function.
1705
1706 The position argument (defaults to 0) is the index in the completers
1707 list where you want the completer to be inserted."""
1708
1709 newcomp = new.instancemethod(completer,self.Completer,
1710 self.Completer.__class__)
1711 self.Completer.matchers.insert(pos,newcomp)
1712
1713 def set_readline_completer(self):
1714 """Reset readline's completer to be our own."""
1715 self.readline.set_completer(self.Completer.rlcomplete)
1716
1717 def set_completer_frame(self, frame=None):
1718 """Set the frame of the completer."""
1719 if frame:
1720 self.Completer.namespace = frame.f_locals
1721 self.Completer.global_namespace = frame.f_globals
1722 else:
1723 self.Completer.namespace = self.user_ns
1724 self.Completer.global_namespace = self.user_global_ns
1725
1726 #-------------------------------------------------------------------------
1711 1727 # Things related to magics
1712 1728 #-------------------------------------------------------------------------
1713 1729
1714 1730 def init_magics(self):
1715 1731 # FIXME: Move the color initialization to the DisplayHook, which
1716 1732 # should be split into a prompt manager and displayhook. We probably
1717 1733 # even need a centralize colors management object.
1718 1734 self.magic_colors(self.colors)
1719 1735 # History was moved to a separate module
1720 1736 from . import history
1721 1737 history.init_ipython(self)
1722 1738
1723 1739 def magic(self,arg_s):
1724 1740 """Call a magic function by name.
1725 1741
1726 1742 Input: a string containing the name of the magic function to call and
1727 1743 any additional arguments to be passed to the magic.
1728 1744
1729 1745 magic('name -opt foo bar') is equivalent to typing at the ipython
1730 1746 prompt:
1731 1747
1732 1748 In[1]: %name -opt foo bar
1733 1749
1734 1750 To call a magic without arguments, simply use magic('name').
1735 1751
1736 1752 This provides a proper Python function to call IPython's magics in any
1737 1753 valid Python code you can type at the interpreter, including loops and
1738 1754 compound statements.
1739 1755 """
1740 1756 args = arg_s.split(' ',1)
1741 1757 magic_name = args[0]
1742 1758 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1743 1759
1744 1760 try:
1745 1761 magic_args = args[1]
1746 1762 except IndexError:
1747 1763 magic_args = ''
1748 1764 fn = getattr(self,'magic_'+magic_name,None)
1749 1765 if fn is None:
1750 1766 error("Magic function `%s` not found." % magic_name)
1751 1767 else:
1752 1768 magic_args = self.var_expand(magic_args,1)
1753 1769 with nested(self.builtin_trap,):
1754 1770 result = fn(magic_args)
1755 1771 return result
1756 1772
1757 1773 def define_magic(self, magicname, func):
1758 1774 """Expose own function as magic function for ipython
1759 1775
1760 1776 def foo_impl(self,parameter_s=''):
1761 1777 'My very own magic!. (Use docstrings, IPython reads them).'
1762 1778 print 'Magic function. Passed parameter is between < >:'
1763 1779 print '<%s>' % parameter_s
1764 1780 print 'The self object is:',self
1765 1781
1766 1782 self.define_magic('foo',foo_impl)
1767 1783 """
1768 1784
1769 1785 import new
1770 1786 im = new.instancemethod(func,self, self.__class__)
1771 1787 old = getattr(self, "magic_" + magicname, None)
1772 1788 setattr(self, "magic_" + magicname, im)
1773 1789 return old
1774 1790
1775 1791 #-------------------------------------------------------------------------
1776 1792 # Things related to macros
1777 1793 #-------------------------------------------------------------------------
1778 1794
1779 1795 def define_macro(self, name, themacro):
1780 1796 """Define a new macro
1781 1797
1782 1798 Parameters
1783 1799 ----------
1784 1800 name : str
1785 1801 The name of the macro.
1786 1802 themacro : str or Macro
1787 1803 The action to do upon invoking the macro. If a string, a new
1788 1804 Macro object is created by passing the string to it.
1789 1805 """
1790 1806
1791 1807 from IPython.core import macro
1792 1808
1793 1809 if isinstance(themacro, basestring):
1794 1810 themacro = macro.Macro(themacro)
1795 1811 if not isinstance(themacro, macro.Macro):
1796 1812 raise ValueError('A macro must be a string or a Macro instance.')
1797 1813 self.user_ns[name] = themacro
1798 1814
1799 1815 #-------------------------------------------------------------------------
1800 1816 # Things related to the running of system commands
1801 1817 #-------------------------------------------------------------------------
1802 1818
1803 1819 def system(self, cmd):
1804 1820 """Call the given cmd in a subprocess."""
1805 1821 # We do not support backgrounding processes because we either use
1806 1822 # pexpect or pipes to read from. Users can always just call
1807 1823 # os.system() if they really want a background process.
1808 1824 if cmd.endswith('&'):
1809 1825 raise OSError("Background processes not supported.")
1810 1826
1811 1827 return system(self.var_expand(cmd, depth=2))
1812 1828
1813 1829 def getoutput(self, cmd):
1814 1830 """Get output (possibly including stderr) from a subprocess."""
1815 1831 if cmd.endswith('&'):
1816 1832 raise OSError("Background processes not supported.")
1817 1833 return getoutput(self.var_expand(cmd, depth=2))
1818 1834
1819 1835 #-------------------------------------------------------------------------
1820 1836 # Things related to aliases
1821 1837 #-------------------------------------------------------------------------
1822 1838
1823 1839 def init_alias(self):
1824 1840 self.alias_manager = AliasManager(shell=self, config=self.config)
1825 1841 self.ns_table['alias'] = self.alias_manager.alias_table,
1826 1842
1827 1843 #-------------------------------------------------------------------------
1828 1844 # Things related to extensions and plugins
1829 1845 #-------------------------------------------------------------------------
1830 1846
1831 1847 def init_extension_manager(self):
1832 1848 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1833 1849
1834 1850 def init_plugin_manager(self):
1835 1851 self.plugin_manager = PluginManager(config=self.config)
1836 1852
1837 1853 #-------------------------------------------------------------------------
1838 1854 # Things related to payloads
1839 1855 #-------------------------------------------------------------------------
1840 1856
1841 1857 def init_payload(self):
1842 1858 self.payload_manager = PayloadManager(config=self.config)
1843 1859
1844 1860 #-------------------------------------------------------------------------
1845 1861 # Things related to the prefilter
1846 1862 #-------------------------------------------------------------------------
1847 1863
1848 1864 def init_prefilter(self):
1849 1865 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1850 1866 # Ultimately this will be refactored in the new interpreter code, but
1851 1867 # for now, we should expose the main prefilter method (there's legacy
1852 1868 # code out there that may rely on this).
1853 1869 self.prefilter = self.prefilter_manager.prefilter_lines
1854 1870
1855 1871
1856 1872 def auto_rewrite_input(self, cmd):
1857 1873 """Print to the screen the rewritten form of the user's command.
1858 1874
1859 1875 This shows visual feedback by rewriting input lines that cause
1860 1876 automatic calling to kick in, like::
1861 1877
1862 1878 /f x
1863 1879
1864 1880 into::
1865 1881
1866 1882 ------> f(x)
1867 1883
1868 1884 after the user's input prompt. This helps the user understand that the
1869 1885 input line was transformed automatically by IPython.
1870 1886 """
1871 1887 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1872 1888
1873 1889 try:
1874 1890 # plain ascii works better w/ pyreadline, on some machines, so
1875 1891 # we use it and only print uncolored rewrite if we have unicode
1876 1892 rw = str(rw)
1877 1893 print >> IPython.utils.io.Term.cout, rw
1878 1894 except UnicodeEncodeError:
1879 1895 print "------> " + cmd
1880 1896
1881 1897 #-------------------------------------------------------------------------
1882 1898 # Things related to extracting values/expressions from kernel and user_ns
1883 1899 #-------------------------------------------------------------------------
1884 1900
1885 1901 def _simple_error(self):
1886 1902 etype, value = sys.exc_info()[:2]
1887 1903 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1888 1904
1889 1905 def get_user_variables(self, names):
1890 1906 """Get a list of variable names from the user's namespace.
1891 1907
1892 1908 The return value is a dict with the repr() of each value.
1893 1909 """
1894 1910 out = {}
1895 1911 user_ns = self.user_ns
1896 1912 for varname in names:
1897 1913 try:
1898 1914 value = repr(user_ns[varname])
1899 1915 except:
1900 1916 value = self._simple_error()
1901 1917 out[varname] = value
1902 1918 return out
1903 1919
1904 1920 def eval_expressions(self, expressions):
1905 1921 """Evaluate a dict of expressions in the user's namespace.
1906 1922
1907 1923 The return value is a dict with the repr() of each value.
1908 1924 """
1909 1925 out = {}
1910 1926 user_ns = self.user_ns
1911 1927 global_ns = self.user_global_ns
1912 1928 for key, expr in expressions.iteritems():
1913 1929 try:
1914 1930 value = repr(eval(expr, global_ns, user_ns))
1915 1931 except:
1916 1932 value = self._simple_error()
1917 1933 out[key] = value
1918 1934 return out
1919 1935
1920 1936 #-------------------------------------------------------------------------
1921 1937 # Things related to the running of code
1922 1938 #-------------------------------------------------------------------------
1923 1939
1924 1940 def ex(self, cmd):
1925 1941 """Execute a normal python statement in user namespace."""
1926 1942 with nested(self.builtin_trap,):
1927 1943 exec cmd in self.user_global_ns, self.user_ns
1928 1944
1929 1945 def ev(self, expr):
1930 1946 """Evaluate python expression expr in user namespace.
1931 1947
1932 1948 Returns the result of evaluation
1933 1949 """
1934 1950 with nested(self.builtin_trap,):
1935 1951 return eval(expr, self.user_global_ns, self.user_ns)
1936 1952
1937 1953 def safe_execfile(self, fname, *where, **kw):
1938 1954 """A safe version of the builtin execfile().
1939 1955
1940 1956 This version will never throw an exception, but instead print
1941 1957 helpful error messages to the screen. This only works on pure
1942 1958 Python files with the .py extension.
1943 1959
1944 1960 Parameters
1945 1961 ----------
1946 1962 fname : string
1947 1963 The name of the file to be executed.
1948 1964 where : tuple
1949 1965 One or two namespaces, passed to execfile() as (globals,locals).
1950 1966 If only one is given, it is passed as both.
1951 1967 exit_ignore : bool (False)
1952 1968 If True, then silence SystemExit for non-zero status (it is always
1953 1969 silenced for zero status, as it is so common).
1954 1970 """
1955 1971 kw.setdefault('exit_ignore', False)
1956 1972
1957 1973 fname = os.path.abspath(os.path.expanduser(fname))
1958 1974
1959 1975 # Make sure we have a .py file
1960 1976 if not fname.endswith('.py'):
1961 1977 warn('File must end with .py to be run using execfile: <%s>' % fname)
1962 1978
1963 1979 # Make sure we can open the file
1964 1980 try:
1965 1981 with open(fname) as thefile:
1966 1982 pass
1967 1983 except:
1968 1984 warn('Could not open file <%s> for safe execution.' % fname)
1969 1985 return
1970 1986
1971 1987 # Find things also in current directory. This is needed to mimic the
1972 1988 # behavior of running a script from the system command line, where
1973 1989 # Python inserts the script's directory into sys.path
1974 1990 dname = os.path.dirname(fname)
1975 1991
1976 1992 with prepended_to_syspath(dname):
1977 1993 try:
1978 1994 execfile(fname,*where)
1979 1995 except SystemExit, status:
1980 1996 # If the call was made with 0 or None exit status (sys.exit(0)
1981 1997 # or sys.exit() ), don't bother showing a traceback, as both of
1982 1998 # these are considered normal by the OS:
1983 1999 # > python -c'import sys;sys.exit(0)'; echo $?
1984 2000 # 0
1985 2001 # > python -c'import sys;sys.exit()'; echo $?
1986 2002 # 0
1987 2003 # For other exit status, we show the exception unless
1988 2004 # explicitly silenced, but only in short form.
1989 2005 if status.code not in (0, None) and not kw['exit_ignore']:
1990 2006 self.showtraceback(exception_only=True)
1991 2007 except:
1992 2008 self.showtraceback()
1993 2009
1994 2010 def safe_execfile_ipy(self, fname):
1995 2011 """Like safe_execfile, but for .ipy files with IPython syntax.
1996 2012
1997 2013 Parameters
1998 2014 ----------
1999 2015 fname : str
2000 2016 The name of the file to execute. The filename must have a
2001 2017 .ipy extension.
2002 2018 """
2003 2019 fname = os.path.abspath(os.path.expanduser(fname))
2004 2020
2005 2021 # Make sure we have a .py file
2006 2022 if not fname.endswith('.ipy'):
2007 2023 warn('File must end with .py to be run using execfile: <%s>' % fname)
2008 2024
2009 2025 # Make sure we can open the file
2010 2026 try:
2011 2027 with open(fname) as thefile:
2012 2028 pass
2013 2029 except:
2014 2030 warn('Could not open file <%s> for safe execution.' % fname)
2015 2031 return
2016 2032
2017 2033 # Find things also in current directory. This is needed to mimic the
2018 2034 # behavior of running a script from the system command line, where
2019 2035 # Python inserts the script's directory into sys.path
2020 2036 dname = os.path.dirname(fname)
2021 2037
2022 2038 with prepended_to_syspath(dname):
2023 2039 try:
2024 2040 with open(fname) as thefile:
2025 2041 script = thefile.read()
2026 2042 # self.runlines currently captures all exceptions
2027 2043 # raise in user code. It would be nice if there were
2028 2044 # versions of runlines, execfile that did raise, so
2029 2045 # we could catch the errors.
2030 2046 self.runlines(script, clean=True)
2031 2047 except:
2032 2048 self.showtraceback()
2033 2049 warn('Unknown failure executing file: <%s>' % fname)
2034 2050
2035 2051 def runlines(self, lines, clean=False):
2036 2052 """Run a string of one or more lines of source.
2037 2053
2038 2054 This method is capable of running a string containing multiple source
2039 2055 lines, as if they had been entered at the IPython prompt. Since it
2040 2056 exposes IPython's processing machinery, the given strings can contain
2041 2057 magic calls (%magic), special shell access (!cmd), etc.
2042 2058 """
2043 2059
2044 2060 if isinstance(lines, (list, tuple)):
2045 2061 lines = '\n'.join(lines)
2046 2062
2047 2063 if clean:
2048 2064 lines = self._cleanup_ipy_script(lines)
2049 2065
2050 2066 # We must start with a clean buffer, in case this is run from an
2051 2067 # interactive IPython session (via a magic, for example).
2052 2068 self.resetbuffer()
2053 2069 lines = lines.splitlines()
2054 2070 more = 0
2055 2071 with nested(self.builtin_trap, self.display_trap):
2056 2072 for line in lines:
2057 2073 # skip blank lines so we don't mess up the prompt counter, but
2058 2074 # do NOT skip even a blank line if we are in a code block (more
2059 2075 # is true)
2060 2076
2061 2077 if line or more:
2062 2078 # push to raw history, so hist line numbers stay in sync
2063 2079 self.input_hist_raw.append(line + '\n')
2064 2080 prefiltered = self.prefilter_manager.prefilter_lines(line,
2065 2081 more)
2066 2082 more = self.push_line(prefiltered)
2067 2083 # IPython's runsource returns None if there was an error
2068 2084 # compiling the code. This allows us to stop processing
2069 2085 # right away, so the user gets the error message at the
2070 2086 # right place.
2071 2087 if more is None:
2072 2088 break
2073 2089 else:
2074 2090 self.input_hist_raw.append("\n")
2075 2091 # final newline in case the input didn't have it, so that the code
2076 2092 # actually does get executed
2077 2093 if more:
2078 2094 self.push_line('\n')
2079 2095
2080 2096 def runsource(self, source, filename='<input>', symbol='single'):
2081 2097 """Compile and run some source in the interpreter.
2082 2098
2083 2099 Arguments are as for compile_command().
2084 2100
2085 2101 One several things can happen:
2086 2102
2087 2103 1) The input is incorrect; compile_command() raised an
2088 2104 exception (SyntaxError or OverflowError). A syntax traceback
2089 2105 will be printed by calling the showsyntaxerror() method.
2090 2106
2091 2107 2) The input is incomplete, and more input is required;
2092 2108 compile_command() returned None. Nothing happens.
2093 2109
2094 2110 3) The input is complete; compile_command() returned a code
2095 2111 object. The code is executed by calling self.runcode() (which
2096 2112 also handles run-time exceptions, except for SystemExit).
2097 2113
2098 2114 The return value is:
2099 2115
2100 2116 - True in case 2
2101 2117
2102 2118 - False in the other cases, unless an exception is raised, where
2103 2119 None is returned instead. This can be used by external callers to
2104 2120 know whether to continue feeding input or not.
2105 2121
2106 2122 The return value can be used to decide whether to use sys.ps1 or
2107 2123 sys.ps2 to prompt the next line."""
2108 2124
2109 2125 # if the source code has leading blanks, add 'if 1:\n' to it
2110 2126 # this allows execution of indented pasted code. It is tempting
2111 2127 # to add '\n' at the end of source to run commands like ' a=1'
2112 2128 # directly, but this fails for more complicated scenarios
2113 2129 source=source.encode(self.stdin_encoding)
2114 2130 if source[:1] in [' ', '\t']:
2115 2131 source = 'if 1:\n%s' % source
2116 2132
2117 2133 try:
2118 2134 code = self.compile(source,filename,symbol)
2119 2135 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2120 2136 # Case 1
2121 2137 self.showsyntaxerror(filename)
2122 2138 return None
2123 2139
2124 2140 if code is None:
2125 2141 # Case 2
2126 2142 return True
2127 2143
2128 2144 # Case 3
2129 2145 # We store the code object so that threaded shells and
2130 2146 # custom exception handlers can access all this info if needed.
2131 2147 # The source corresponding to this can be obtained from the
2132 2148 # buffer attribute as '\n'.join(self.buffer).
2133 2149 self.code_to_run = code
2134 2150 # now actually execute the code object
2135 2151 if self.runcode(code) == 0:
2136 2152 return False
2137 2153 else:
2138 2154 return None
2139 2155
2140 2156 def runcode(self,code_obj):
2141 2157 """Execute a code object.
2142 2158
2143 2159 When an exception occurs, self.showtraceback() is called to display a
2144 2160 traceback.
2145 2161
2146 2162 Return value: a flag indicating whether the code to be run completed
2147 2163 successfully:
2148 2164
2149 2165 - 0: successful execution.
2150 2166 - 1: an error occurred.
2151 2167 """
2152 2168
2153 2169 # Set our own excepthook in case the user code tries to call it
2154 2170 # directly, so that the IPython crash handler doesn't get triggered
2155 2171 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2156 2172
2157 2173 # we save the original sys.excepthook in the instance, in case config
2158 2174 # code (such as magics) needs access to it.
2159 2175 self.sys_excepthook = old_excepthook
2160 2176 outflag = 1 # happens in more places, so it's easier as default
2161 2177 try:
2162 2178 try:
2163 2179 self.hooks.pre_runcode_hook()
2164 2180 #rprint('Running code') # dbg
2165 2181 exec code_obj in self.user_global_ns, self.user_ns
2166 2182 finally:
2167 2183 # Reset our crash handler in place
2168 2184 sys.excepthook = old_excepthook
2169 2185 except SystemExit:
2170 2186 self.resetbuffer()
2171 2187 self.showtraceback(exception_only=True)
2172 2188 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2173 2189 except self.custom_exceptions:
2174 2190 etype,value,tb = sys.exc_info()
2175 2191 self.CustomTB(etype,value,tb)
2176 2192 except:
2177 2193 self.showtraceback()
2178 2194 else:
2179 2195 outflag = 0
2180 2196 if softspace(sys.stdout, 0):
2181 2197 print
2182 2198 # Flush out code object which has been run (and source)
2183 2199 self.code_to_run = None
2184 2200 return outflag
2185 2201
2186 2202 def push_line(self, line):
2187 2203 """Push a line to the interpreter.
2188 2204
2189 2205 The line should not have a trailing newline; it may have
2190 2206 internal newlines. The line is appended to a buffer and the
2191 2207 interpreter's runsource() method is called with the
2192 2208 concatenated contents of the buffer as source. If this
2193 2209 indicates that the command was executed or invalid, the buffer
2194 2210 is reset; otherwise, the command is incomplete, and the buffer
2195 2211 is left as it was after the line was appended. The return
2196 2212 value is 1 if more input is required, 0 if the line was dealt
2197 2213 with in some way (this is the same as runsource()).
2198 2214 """
2199 2215
2200 2216 # autoindent management should be done here, and not in the
2201 2217 # interactive loop, since that one is only seen by keyboard input. We
2202 2218 # need this done correctly even for code run via runlines (which uses
2203 2219 # push).
2204 2220
2205 2221 #print 'push line: <%s>' % line # dbg
2206 2222 for subline in line.splitlines():
2207 2223 self._autoindent_update(subline)
2208 2224 self.buffer.append(line)
2209 2225 more = self.runsource('\n'.join(self.buffer), self.filename)
2210 2226 if not more:
2211 2227 self.resetbuffer()
2212 2228 return more
2213 2229
2214 2230 def resetbuffer(self):
2215 2231 """Reset the input buffer."""
2216 2232 self.buffer[:] = []
2217 2233
2218 2234 def _is_secondary_block_start(self, s):
2219 2235 if not s.endswith(':'):
2220 2236 return False
2221 2237 if (s.startswith('elif') or
2222 2238 s.startswith('else') or
2223 2239 s.startswith('except') or
2224 2240 s.startswith('finally')):
2225 2241 return True
2226 2242
2227 2243 def _cleanup_ipy_script(self, script):
2228 2244 """Make a script safe for self.runlines()
2229 2245
2230 2246 Currently, IPython is lines based, with blocks being detected by
2231 2247 empty lines. This is a problem for block based scripts that may
2232 2248 not have empty lines after blocks. This script adds those empty
2233 2249 lines to make scripts safe for running in the current line based
2234 2250 IPython.
2235 2251 """
2236 2252 res = []
2237 2253 lines = script.splitlines()
2238 2254 level = 0
2239 2255
2240 2256 for l in lines:
2241 2257 lstripped = l.lstrip()
2242 2258 stripped = l.strip()
2243 2259 if not stripped:
2244 2260 continue
2245 2261 newlevel = len(l) - len(lstripped)
2246 2262 if level > 0 and newlevel == 0 and \
2247 2263 not self._is_secondary_block_start(stripped):
2248 2264 # add empty line
2249 2265 res.append('')
2250 2266 res.append(l)
2251 2267 level = newlevel
2252 2268
2253 2269 return '\n'.join(res) + '\n'
2254 2270
2255 2271 def _autoindent_update(self,line):
2256 2272 """Keep track of the indent level."""
2257 2273
2258 2274 #debugx('line')
2259 2275 #debugx('self.indent_current_nsp')
2260 2276 if self.autoindent:
2261 2277 if line:
2262 2278 inisp = num_ini_spaces(line)
2263 2279 if inisp < self.indent_current_nsp:
2264 2280 self.indent_current_nsp = inisp
2265 2281
2266 2282 if line[-1] == ':':
2267 2283 self.indent_current_nsp += 4
2268 2284 elif dedent_re.match(line):
2269 2285 self.indent_current_nsp -= 4
2270 2286 else:
2271 2287 self.indent_current_nsp = 0
2272 2288
2273 2289 #-------------------------------------------------------------------------
2274 2290 # Things related to GUI support and pylab
2275 2291 #-------------------------------------------------------------------------
2276 2292
2277 2293 def enable_pylab(self, gui=None):
2278 2294 raise NotImplementedError('Implement enable_pylab in a subclass')
2279 2295
2280 2296 #-------------------------------------------------------------------------
2281 2297 # Utilities
2282 2298 #-------------------------------------------------------------------------
2283 2299
2284 2300 def var_expand(self,cmd,depth=0):
2285 2301 """Expand python variables in a string.
2286 2302
2287 2303 The depth argument indicates how many frames above the caller should
2288 2304 be walked to look for the local namespace where to expand variables.
2289 2305
2290 2306 The global namespace for expansion is always the user's interactive
2291 2307 namespace.
2292 2308 """
2293 2309
2294 2310 return str(ItplNS(cmd,
2295 2311 self.user_ns, # globals
2296 2312 # Skip our own frame in searching for locals:
2297 2313 sys._getframe(depth+1).f_locals # locals
2298 2314 ))
2299 2315
2300 2316 def mktempfile(self,data=None):
2301 2317 """Make a new tempfile and return its filename.
2302 2318
2303 2319 This makes a call to tempfile.mktemp, but it registers the created
2304 2320 filename internally so ipython cleans it up at exit time.
2305 2321
2306 2322 Optional inputs:
2307 2323
2308 2324 - data(None): if data is given, it gets written out to the temp file
2309 2325 immediately, and the file is closed again."""
2310 2326
2311 2327 filename = tempfile.mktemp('.py','ipython_edit_')
2312 2328 self.tempfiles.append(filename)
2313 2329
2314 2330 if data:
2315 2331 tmp_file = open(filename,'w')
2316 2332 tmp_file.write(data)
2317 2333 tmp_file.close()
2318 2334 return filename
2319 2335
2320 2336 # TODO: This should be removed when Term is refactored.
2321 2337 def write(self,data):
2322 2338 """Write a string to the default output"""
2323 2339 io.Term.cout.write(data)
2324 2340
2325 2341 # TODO: This should be removed when Term is refactored.
2326 2342 def write_err(self,data):
2327 2343 """Write a string to the default error output"""
2328 2344 io.Term.cerr.write(data)
2329 2345
2330 2346 def ask_yes_no(self,prompt,default=True):
2331 2347 if self.quiet:
2332 2348 return True
2333 2349 return ask_yes_no(prompt,default)
2334 2350
2335 2351 def show_usage(self):
2336 2352 """Show a usage message"""
2337 2353 page.page(IPython.core.usage.interactive_usage)
2338 2354
2339 2355 #-------------------------------------------------------------------------
2340 2356 # Things related to IPython exiting
2341 2357 #-------------------------------------------------------------------------
2342 2358 def atexit_operations(self):
2343 2359 """This will be executed at the time of exit.
2344 2360
2345 2361 Cleanup operations and saving of persistent data that is done
2346 2362 unconditionally by IPython should be performed here.
2347 2363
2348 2364 For things that may depend on startup flags or platform specifics (such
2349 2365 as having readline or not), register a separate atexit function in the
2350 2366 code that has the appropriate information, rather than trying to
2351 2367 clutter
2352 2368 """
2353 2369 # Cleanup all tempfiles left around
2354 2370 for tfile in self.tempfiles:
2355 2371 try:
2356 2372 os.unlink(tfile)
2357 2373 except OSError:
2358 2374 pass
2359 2375
2360 2376 # Clear all user namespaces to release all references cleanly.
2361 2377 self.reset()
2362 2378
2363 2379 # Run user hooks
2364 2380 self.hooks.shutdown_hook()
2365 2381
2366 2382 def cleanup(self):
2367 2383 self.restore_sys_module_state()
2368 2384
2369 2385
2370 2386 class InteractiveShellABC(object):
2371 2387 """An abstract base class for InteractiveShell."""
2372 2388 __metaclass__ = abc.ABCMeta
2373 2389
2374 2390 InteractiveShellABC.register(InteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now