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