##// END OF EJS Templates
Complete reorganization of InteractiveShell....
Brian Granger -
Show More
@@ -0,0 +1,14 b''
1 class InputList(list):
2 """Class to store user input.
3
4 It's basically a list, but slices return a string instead of a list, thus
5 allowing things like (assuming 'In' is an instance):
6
7 exec In[4:7]
8
9 or
10
11 exec In[5:9] + In[14] + In[21:25]"""
12
13 def __getslice__(self,i,j):
14 return ''.join(list.__getslice__(self,i,j))
This diff has been collapsed as it changes many lines, (541 lines changed) Show them Hide them
@@ -0,0 +1,541 b''
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
3
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
12
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
16
17 import __builtin__
18 import bdb
19 from contextlib import nested
20 import os
21 import re
22 import sys
23
24 from IPython.core.error import TryNext
25 from IPython.core.usage import interactive_usage, default_banner
26 from IPython.core.inputlist import InputList
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
28 from IPython.lib.inputhook import enable_gui
29 from IPython.lib.pylabtools import pylab_activate
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn
33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool
35
36
37 #-----------------------------------------------------------------------------
38 # Utilities
39 #-----------------------------------------------------------------------------
40
41
42 def get_default_editor():
43 try:
44 ed = os.environ['EDITOR']
45 except KeyError:
46 if os.name == 'posix':
47 ed = 'vi' # the only one guaranteed to be there!
48 else:
49 ed = 'notepad' # same in Windows!
50 return ed
51
52
53 # store the builtin raw_input globally, and use this always, in case user code
54 # overwrites it (like wx.py.PyShell does)
55 raw_input_original = raw_input
56
57
58 class SeparateStr(Str):
59 """A Str subclass to validate separate_in, separate_out, etc.
60
61 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
62 """
63
64 def validate(self, obj, value):
65 if value == '0': value = ''
66 value = value.replace('\\n','\n')
67 return super(SeparateStr, self).validate(obj, value)
68
69
70 #-----------------------------------------------------------------------------
71 # Main class
72 #-----------------------------------------------------------------------------
73
74
75 class TerminalInteractiveShell(InteractiveShell):
76
77 autoedit_syntax = CBool(False, config=True)
78 autoindent = CBool(True, config=True)
79 banner = Str('')
80 banner1 = Str(default_banner, config=True)
81 banner2 = Str('', config=True)
82 confirm_exit = CBool(True, config=True)
83 # This display_banner only controls whether or not self.show_banner()
84 # is called when mainloop/interact are called. The default is False
85 # because for the terminal based application, the banner behavior
86 # is controlled by Global.display_banner, which IPythonApp looks at
87 # to determine if *it* should call show_banner() by hand or not.
88 display_banner = CBool(False) # This isn't configurable!
89 embedded = CBool(False)
90 embedded_active = CBool(False)
91 editor = Str(get_default_editor(), config=True)
92 exit_now = CBool(False)
93 pager = Str('less', config=True)
94
95 screen_length = Int(0, config=True)
96
97 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
98 separate_in = SeparateStr('\n', config=True)
99 separate_out = SeparateStr('', config=True)
100 separate_out2 = SeparateStr('', config=True)
101 term_title = CBool(False, config=True)
102
103 def __init__(self, config=None, ipython_dir=None, user_ns=None,
104 user_global_ns=None, custom_exceptions=((),None),
105 usage=None, banner1=None, banner2=None,
106 display_banner=None):
107
108 super(TerminalInteractiveShell, self).__init__(
109 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
110 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
111 )
112 self.init_term_title()
113 self.init_usage(usage)
114 self.init_banner(banner1, banner2, display_banner)
115
116 #-------------------------------------------------------------------------
117 # Things related to the terminal
118 #-------------------------------------------------------------------------
119
120 @property
121 def usable_screen_length(self):
122 if self.screen_length == 0:
123 return 0
124 else:
125 num_lines_bot = self.separate_in.count('\n')+1
126 return self.screen_length - num_lines_bot
127
128 def init_term_title(self):
129 # Enable or disable the terminal title.
130 if self.term_title:
131 toggle_set_term_title(True)
132 set_term_title('IPython: ' + abbrev_cwd())
133 else:
134 toggle_set_term_title(False)
135
136 #-------------------------------------------------------------------------
137 # Things related to the banner and usage
138 #-------------------------------------------------------------------------
139
140 def _banner1_changed(self):
141 self.compute_banner()
142
143 def _banner2_changed(self):
144 self.compute_banner()
145
146 def _term_title_changed(self, name, new_value):
147 self.init_term_title()
148
149 def init_banner(self, banner1, banner2, display_banner):
150 if banner1 is not None:
151 self.banner1 = banner1
152 if banner2 is not None:
153 self.banner2 = banner2
154 if display_banner is not None:
155 self.display_banner = display_banner
156 self.compute_banner()
157
158 def show_banner(self, banner=None):
159 if banner is None:
160 banner = self.banner
161 self.write(banner)
162
163 def compute_banner(self):
164 self.banner = self.banner1 + '\n'
165 if self.profile:
166 self.banner += '\nIPython profile: %s\n' % self.profile
167 if self.banner2:
168 self.banner += '\n' + self.banner2 + '\n'
169
170 def init_usage(self, usage=None):
171 if usage is None:
172 self.usage = interactive_usage
173 else:
174 self.usage = usage
175
176 #-------------------------------------------------------------------------
177 # Mainloop and code execution logic
178 #-------------------------------------------------------------------------
179
180 def mainloop(self, display_banner=None):
181 """Start the mainloop.
182
183 If an optional banner argument is given, it will override the
184 internally created default banner.
185 """
186
187 with nested(self.builtin_trap, self.display_trap):
188
189 # if you run stuff with -c <cmd>, raw hist is not updated
190 # ensure that it's in sync
191 if len(self.input_hist) != len (self.input_hist_raw):
192 self.input_hist_raw = InputList(self.input_hist)
193
194 while 1:
195 try:
196 self.interact(display_banner=display_banner)
197 #self.interact_with_readline()
198 # XXX for testing of a readline-decoupled repl loop, call
199 # interact_with_readline above
200 break
201 except KeyboardInterrupt:
202 # this should not be necessary, but KeyboardInterrupt
203 # handling seems rather unpredictable...
204 self.write("\nKeyboardInterrupt in interact()\n")
205
206 def interact(self, display_banner=None):
207 """Closely emulate the interactive Python console."""
208
209 # batch run -> do not interact
210 if self.exit_now:
211 return
212
213 if display_banner is None:
214 display_banner = self.display_banner
215 if display_banner:
216 self.show_banner()
217
218 more = 0
219
220 # Mark activity in the builtins
221 __builtin__.__dict__['__IPYTHON__active'] += 1
222
223 if self.has_readline:
224 self.readline_startup_hook(self.pre_readline)
225 # exit_now is set by a call to %Exit or %Quit, through the
226 # ask_exit callback.
227
228 while not self.exit_now:
229 self.hooks.pre_prompt_hook()
230 if more:
231 try:
232 prompt = self.hooks.generate_prompt(True)
233 except:
234 self.showtraceback()
235 if self.autoindent:
236 self.rl_do_indent = True
237
238 else:
239 try:
240 prompt = self.hooks.generate_prompt(False)
241 except:
242 self.showtraceback()
243 try:
244 line = self.raw_input(prompt, more)
245 if self.exit_now:
246 # quick exit on sys.std[in|out] close
247 break
248 if self.autoindent:
249 self.rl_do_indent = False
250
251 except KeyboardInterrupt:
252 #double-guard against keyboardinterrupts during kbdint handling
253 try:
254 self.write('\nKeyboardInterrupt\n')
255 self.resetbuffer()
256 # keep cache in sync with the prompt counter:
257 self.outputcache.prompt_count -= 1
258
259 if self.autoindent:
260 self.indent_current_nsp = 0
261 more = 0
262 except KeyboardInterrupt:
263 pass
264 except EOFError:
265 if self.autoindent:
266 self.rl_do_indent = False
267 if self.has_readline:
268 self.readline_startup_hook(None)
269 self.write('\n')
270 self.exit()
271 except bdb.BdbQuit:
272 warn('The Python debugger has exited with a BdbQuit exception.\n'
273 'Because of how pdb handles the stack, it is impossible\n'
274 'for IPython to properly format this particular exception.\n'
275 'IPython will resume normal operation.')
276 except:
277 # exceptions here are VERY RARE, but they can be triggered
278 # asynchronously by signal handlers, for example.
279 self.showtraceback()
280 else:
281 more = self.push_line(line)
282 if (self.SyntaxTB.last_syntax_error and
283 self.autoedit_syntax):
284 self.edit_syntax_error()
285
286 # We are off again...
287 __builtin__.__dict__['__IPYTHON__active'] -= 1
288
289 # Turn off the exit flag, so the mainloop can be restarted if desired
290 self.exit_now = False
291
292 def raw_input(self,prompt='',continue_prompt=False):
293 """Write a prompt and read a line.
294
295 The returned line does not include the trailing newline.
296 When the user enters the EOF key sequence, EOFError is raised.
297
298 Optional inputs:
299
300 - prompt(''): a string to be printed to prompt the user.
301
302 - continue_prompt(False): whether this line is the first one or a
303 continuation in a sequence of inputs.
304 """
305 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
306
307 # Code run by the user may have modified the readline completer state.
308 # We must ensure that our completer is back in place.
309
310 if self.has_readline:
311 self.set_completer()
312
313 try:
314 line = raw_input_original(prompt).decode(self.stdin_encoding)
315 except ValueError:
316 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
317 " or sys.stdout.close()!\nExiting IPython!")
318 self.ask_exit()
319 return ""
320
321 # Try to be reasonably smart about not re-indenting pasted input more
322 # than necessary. We do this by trimming out the auto-indent initial
323 # spaces, if the user's actual input started itself with whitespace.
324 #debugx('self.buffer[-1]')
325
326 if self.autoindent:
327 if num_ini_spaces(line) > self.indent_current_nsp:
328 line = line[self.indent_current_nsp:]
329 self.indent_current_nsp = 0
330
331 # store the unfiltered input before the user has any chance to modify
332 # it.
333 if line.strip():
334 if continue_prompt:
335 self.input_hist_raw[-1] += '%s\n' % line
336 if self.has_readline and self.readline_use:
337 try:
338 histlen = self.readline.get_current_history_length()
339 if histlen > 1:
340 newhist = self.input_hist_raw[-1].rstrip()
341 self.readline.remove_history_item(histlen-1)
342 self.readline.replace_history_item(histlen-2,
343 newhist.encode(self.stdin_encoding))
344 except AttributeError:
345 pass # re{move,place}_history_item are new in 2.4.
346 else:
347 self.input_hist_raw.append('%s\n' % line)
348 # only entries starting at first column go to shadow history
349 if line.lstrip() == line:
350 self.shadowhist.add(line.strip())
351 elif not continue_prompt:
352 self.input_hist_raw.append('\n')
353 try:
354 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
355 except:
356 # blanket except, in case a user-defined prefilter crashes, so it
357 # can't take all of ipython with it.
358 self.showtraceback()
359 return ''
360 else:
361 return lineout
362
363 # TODO: The following three methods are an early attempt to refactor
364 # the main code execution logic. We don't use them, but they may be
365 # helpful when we refactor the code execution logic further.
366 # def interact_prompt(self):
367 # """ Print the prompt (in read-eval-print loop)
368 #
369 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
370 # used in standard IPython flow.
371 # """
372 # if self.more:
373 # try:
374 # prompt = self.hooks.generate_prompt(True)
375 # except:
376 # self.showtraceback()
377 # if self.autoindent:
378 # self.rl_do_indent = True
379 #
380 # else:
381 # try:
382 # prompt = self.hooks.generate_prompt(False)
383 # except:
384 # self.showtraceback()
385 # self.write(prompt)
386 #
387 # def interact_handle_input(self,line):
388 # """ Handle the input line (in read-eval-print loop)
389 #
390 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
391 # used in standard IPython flow.
392 # """
393 # if line.lstrip() == line:
394 # self.shadowhist.add(line.strip())
395 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
396 #
397 # if line.strip():
398 # if self.more:
399 # self.input_hist_raw[-1] += '%s\n' % line
400 # else:
401 # self.input_hist_raw.append('%s\n' % line)
402 #
403 #
404 # self.more = self.push_line(lineout)
405 # if (self.SyntaxTB.last_syntax_error and
406 # self.autoedit_syntax):
407 # self.edit_syntax_error()
408 #
409 # def interact_with_readline(self):
410 # """ Demo of using interact_handle_input, interact_prompt
411 #
412 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
413 # it should work like this.
414 # """
415 # self.readline_startup_hook(self.pre_readline)
416 # while not self.exit_now:
417 # self.interact_prompt()
418 # if self.more:
419 # self.rl_do_indent = True
420 # else:
421 # self.rl_do_indent = False
422 # line = raw_input_original().decode(self.stdin_encoding)
423 # self.interact_handle_input(line)
424
425 #-------------------------------------------------------------------------
426 # Methods to support auto-editing of SyntaxErrors.
427 #-------------------------------------------------------------------------
428
429 def edit_syntax_error(self):
430 """The bottom half of the syntax error handler called in the main loop.
431
432 Loop until syntax error is fixed or user cancels.
433 """
434
435 while self.SyntaxTB.last_syntax_error:
436 # copy and clear last_syntax_error
437 err = self.SyntaxTB.clear_err_state()
438 if not self._should_recompile(err):
439 return
440 try:
441 # may set last_syntax_error again if a SyntaxError is raised
442 self.safe_execfile(err.filename,self.user_ns)
443 except:
444 self.showtraceback()
445 else:
446 try:
447 f = file(err.filename)
448 try:
449 # This should be inside a display_trap block and I
450 # think it is.
451 sys.displayhook(f.read())
452 finally:
453 f.close()
454 except:
455 self.showtraceback()
456
457 def _should_recompile(self,e):
458 """Utility routine for edit_syntax_error"""
459
460 if e.filename in ('<ipython console>','<input>','<string>',
461 '<console>','<BackgroundJob compilation>',
462 None):
463
464 return False
465 try:
466 if (self.autoedit_syntax and
467 not self.ask_yes_no('Return to editor to correct syntax error? '
468 '[Y/n] ','y')):
469 return False
470 except EOFError:
471 return False
472
473 def int0(x):
474 try:
475 return int(x)
476 except TypeError:
477 return 0
478 # always pass integer line and offset values to editor hook
479 try:
480 self.hooks.fix_error_editor(e.filename,
481 int0(e.lineno),int0(e.offset),e.msg)
482 except TryNext:
483 warn('Could not open editor')
484 return False
485 return True
486
487 #-------------------------------------------------------------------------
488 # Things related to GUI support and pylab
489 #-------------------------------------------------------------------------
490
491 def enable_pylab(self, gui=None):
492 """Activate pylab support at runtime.
493
494 This turns on support for matplotlib, preloads into the interactive
495 namespace all of numpy and pylab, and configures IPython to correcdtly
496 interact with the GUI event loop. The GUI backend to be used can be
497 optionally selected with the optional :param:`gui` argument.
498
499 Parameters
500 ----------
501 gui : optional, string
502
503 If given, dictates the choice of matplotlib GUI backend to use
504 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
505 'gtk'), otherwise we use the default chosen by matplotlib (as
506 dictated by the matplotlib build-time options plus the user's
507 matplotlibrc configuration file).
508 """
509 # We want to prevent the loading of pylab to pollute the user's
510 # namespace as shown by the %who* magics, so we execute the activation
511 # code in an empty namespace, and we update *both* user_ns and
512 # user_ns_hidden with this information.
513 ns = {}
514 gui = pylab_activate(ns, gui)
515 self.user_ns.update(ns)
516 self.user_ns_hidden.update(ns)
517 # Now we must activate the gui pylab wants to use, and fix %run to take
518 # plot updates into account
519 enable_gui(gui)
520 self.magic_run = self._pylab_magic_run
521
522 #-------------------------------------------------------------------------
523 # Things related to exiting
524 #-------------------------------------------------------------------------
525
526 def ask_exit(self):
527 """ Ask the shell to exit. Can be overiden and used as a callback. """
528 self.exit_now = True
529
530 def exit(self):
531 """Handle interactive exit.
532
533 This method calls the ask_exit callback."""
534 if self.confirm_exit:
535 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
536 self.ask_exit()
537 else:
538 self.ask_exit()
539
540
541 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -47,15 +47,15 b' c = get_config()'
47 47
48 48 # c.InteractiveShell.autocall = 1
49 49
50 # c.InteractiveShell.autoedit_syntax = False
50 # c.TerminalInteractiveShell.autoedit_syntax = False
51 51
52 # c.InteractiveShell.autoindent = True
52 # c.TerminalInteractiveShell.autoindent = True
53 53
54 54 # c.InteractiveShell.automagic = False
55 55
56 # c.InteractiveShell.banner1 = 'This if for overriding the default IPython banner'
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57 57
58 # c.InteractiveShell.banner2 = "This is for extra banner text"
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
59 59
60 60 # c.InteractiveShell.cache_size = 1000
61 61
@@ -63,11 +63,11 b' c = get_config()'
63 63
64 64 # c.InteractiveShell.color_info = True
65 65
66 # c.InteractiveShell.confirm_exit = True
66 # c.TerminalInteractiveShell.confirm_exit = True
67 67
68 68 # c.InteractiveShell.deep_reload = False
69 69
70 # c.InteractiveShell.editor = 'nano'
70 # c.TerminalInteractiveShell.editor = 'nano'
71 71
72 72 # c.InteractiveShell.logstart = True
73 73
@@ -77,7 +77,7 b' c = get_config()'
77 77
78 78 # c.InteractiveShell.object_info_string_level = 0
79 79
80 # c.InteractiveShell.pager = 'less'
80 # c.TerminalInteractiveShell.pager = 'less'
81 81
82 82 # c.InteractiveShell.pdb = False
83 83
@@ -114,17 +114,17 b' c = get_config()'
114 114 # c.InteractiveShell.readline_merge_completions = True
115 115 # c.InteractiveShell.readline_omit__names = 0
116 116
117 # c.InteractiveShell.screen_length = 0
117 # c.TerminalInteractiveShell.screen_length = 0
118 118
119 # c.InteractiveShell.separate_in = '\n'
120 # c.InteractiveShell.separate_out = ''
121 # c.InteractiveShell.separate_out2 = ''
119 # c.TerminalInteractiveShell.separate_in = '\n'
120 # c.TerminalInteractiveShell.separate_out = ''
121 # c.TerminalInteractiveShell.separate_out2 = ''
122 122
123 123 # c.InteractiveShell.system_header = "IPython system call: "
124 124
125 125 # c.InteractiveShell.system_verbose = True
126 126
127 # c.InteractiveShell.term_title = False
127 # c.TerminalInteractiveShell.term_title = False
128 128
129 129 # c.InteractiveShell.wildcards_case_sensitive = True
130 130
@@ -10,9 +10,9 b" c.InteractiveShell.prompt_out = '<\\#> '"
10 10
11 11 c.InteractiveShell.prompts_pad_left = True
12 12
13 c.InteractiveShell.separate_in = ''
14 c.InteractiveShell.separate_out = ''
15 c.InteractiveShell.separate_out2 = ''
13 c.TerminalInteractiveShell.separate_in = ''
14 c.TerminalInteractiveShell.separate_out = ''
15 c.TerminalInteractiveShell.separate_out2 = ''
16 16
17 17 c.PrefilterManager.multi_line_specials = True
18 18
This diff has been collapsed as it changes many lines, (637 lines changed) Show them Hide them
@@ -19,7 +19,6 b' from __future__ import absolute_import'
19 19
20 20 import __builtin__
21 21 import abc
22 import bdb
23 22 import codeop
24 23 import exceptions
25 24 import new
@@ -39,35 +38,27 b' from IPython.core.alias import AliasManager'
39 38 from IPython.core.builtin_trap import BuiltinTrap
40 39 from IPython.config.configurable import Configurable
41 40 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.error import TryNext, UsageError
41 from IPython.core.error import UsageError
43 42 from IPython.core.extensions import ExtensionManager
44 43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.inputlist import InputList
45 45 from IPython.core.logger import Logger
46 46 from IPython.core.magic import Magic
47 47 from IPython.core.plugin import PluginManager
48 48 from IPython.core.prefilter import PrefilterManager
49 49 from IPython.core.prompts import CachedOutput
50 from IPython.core.usage import interactive_usage, default_banner
51 50 import IPython.core.hooks
52 51 from IPython.external.Itpl import ItplNS
53 from IPython.lib.inputhook import enable_gui
54 from IPython.lib.backgroundjobs import BackgroundJobManager
55 from IPython.lib.pylabtools import pylab_activate
56 52 from IPython.utils import PyColorize
57 53 from IPython.utils import pickleshare
58 54 from IPython.utils.doctestreload import doctest_reload
59 55 from IPython.utils.ipstruct import Struct
60 56 from IPython.utils.io import Term, ask_yes_no
61 57 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.process import (
63 abbrev_cwd,
64 getoutput,
65 getoutputerror
66 )
67 # import IPython.utils.rlineimpl as readline
58 from IPython.utils.process import getoutput, getoutputerror
68 59 from IPython.utils.strdispatch import StrDispatch
69 60 from IPython.utils.syspathcontext import prepended_to_syspath
70 from IPython.utils.terminal import toggle_set_term_title, set_term_title
61 from IPython.utils.text import num_ini_spaces
71 62 from IPython.utils.warn import warn, error, fatal
72 63 from IPython.utils.traitlets import (
73 64 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
@@ -80,10 +71,6 b' from IPython.utils.traitlets import ('
80 71 # Globals
81 72 #-----------------------------------------------------------------------------
82 73
83 # store the builtin raw_input globally, and use this always, in case user code
84 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
86
87 74 # compiled regexps for autoindent management
88 75 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89 76
@@ -91,18 +78,9 b" dedent_re = re.compile(r'^\\s+raise|^\\s+return|^\\s+pass')"
91 78 # Utilities
92 79 #-----------------------------------------------------------------------------
93 80
94 ini_spaces_re = re.compile(r'^(\s+)')
95
96
97 def num_ini_spaces(strng):
98 """Return the number of initial spaces in a string"""
99
100 ini_spaces = ini_spaces_re.match(strng)
101 if ini_spaces:
102 return ini_spaces.end()
103 else:
104 return 0
105
81 # store the builtin raw_input globally, and use this always, in case user code
82 # overwrites it (like wx.py.PyShell does)
83 raw_input_original = raw_input
106 84
107 85 def softspace(file, newvalue):
108 86 """Copied from code.py, to remove the dependency"""
@@ -126,22 +104,6 b' class SpaceInInput(exceptions.Exception): pass'
126 104
127 105 class Bunch: pass
128 106
129 class InputList(list):
130 """Class to store user input.
131
132 It's basically a list, but slices return a string instead of a list, thus
133 allowing things like (assuming 'In' is an instance):
134
135 exec In[4:7]
136
137 or
138
139 exec In[5:9] + In[14] + In[21:25]"""
140
141 def __getslice__(self,i,j):
142 return ''.join(list.__getslice__(self,i,j))
143
144
145 107 class SyntaxTB(ultratb.ListTB):
146 108 """Extension which holds some state: the last exception value"""
147 109
@@ -160,17 +122,6 b' class SyntaxTB(ultratb.ListTB):'
160 122 return e
161 123
162 124
163 def get_default_editor():
164 try:
165 ed = os.environ['EDITOR']
166 except KeyError:
167 if os.name == 'posix':
168 ed = 'vi' # the only one guaranteed to be there!
169 else:
170 ed = 'notepad' # same in Windows!
171 return ed
172
173
174 125 def get_default_colors():
175 126 if sys.platform=='darwin':
176 127 return "LightBG"
@@ -180,18 +131,6 b' def get_default_colors():'
180 131 return 'Linux'
181 132
182 133
183 class SeparateStr(Str):
184 """A Str subclass to validate separate_in, separate_out, etc.
185
186 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
187 """
188
189 def validate(self, obj, value):
190 if value == '0': value = ''
191 value = value.replace('\\n','\n')
192 return super(SeparateStr, self).validate(obj, value)
193
194
195 134 #-----------------------------------------------------------------------------
196 135 # Main IPython class
197 136 #-----------------------------------------------------------------------------
@@ -201,28 +140,13 b' class InteractiveShell(Configurable, Magic):'
201 140 """An enhanced, interactive shell for Python."""
202 141
203 142 autocall = Enum((0,1,2), default_value=1, config=True)
204 autoedit_syntax = CBool(False, config=True)
205 autoindent = CBool(True, config=True)
206 143 automagic = CBool(True, config=True)
207 banner = Str('')
208 banner1 = Str(default_banner, config=True)
209 banner2 = Str('', config=True)
210 144 cache_size = Int(1000, config=True)
211 145 color_info = CBool(True, config=True)
212 146 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
213 147 default_value=get_default_colors(), config=True)
214 confirm_exit = CBool(True, config=True)
215 148 debug = CBool(False, config=True)
216 149 deep_reload = CBool(False, config=True)
217 # This display_banner only controls whether or not self.show_banner()
218 # is called when mainloop/interact are called. The default is False
219 # because for the terminal based application, the banner behavior
220 # is controlled by Global.display_banner, which IPythonApp looks at
221 # to determine if *it* should call show_banner() by hand or not.
222 display_banner = CBool(False) # This isn't configurable!
223 embedded = CBool(False)
224 embedded_active = CBool(False)
225 editor = Str(get_default_editor(), config=True)
226 150 filename = Str("<ipython console>")
227 151 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
228 152 logstart = CBool(False, config=True)
@@ -230,7 +154,6 b' class InteractiveShell(Configurable, Magic):'
230 154 logappend = Str('', config=True)
231 155 object_info_string_level = Enum((0,1,2), default_value=0,
232 156 config=True)
233 pager = Str('less', config=True)
234 157 pdb = CBool(False, config=True)
235 158 pprint = CBool(True, config=True)
236 159 profile = Str('', config=True)
@@ -240,6 +163,8 b' class InteractiveShell(Configurable, Magic):'
240 163 prompts_pad_left = CBool(True, config=True)
241 164 quiet = CBool(False, config=True)
242 165
166 # The readline stuff will eventually be moved to the terminal subclass
167 # but for now, we can't do that as readline is welded in everywhere.
243 168 readline_use = CBool(True, config=True)
244 169 readline_merge_completions = CBool(True, config=True)
245 170 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
@@ -262,26 +187,12 b' class InteractiveShell(Configurable, Magic):'
262 187 '"\C-u": unix-line-discard',
263 188 ], allow_none=False, config=True)
264 189
265 screen_length = Int(0, config=True)
266
267 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
268 separate_in = SeparateStr('\n', config=True)
269 separate_out = SeparateStr('', config=True)
270 separate_out2 = SeparateStr('', config=True)
271
272 190 system_header = Str('IPython system call: ', config=True)
273 191 system_verbose = CBool(False, config=True)
274 term_title = CBool(False, config=True)
275 192 wildcards_case_sensitive = CBool(True, config=True)
276 193 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
277 194 default_value='Context', config=True)
278 195
279 autoexec = List(allow_none=False)
280
281 # class attribute to indicate whether the class supports threads or not.
282 # Subclasses with thread support should override this as needed.
283 isthreaded = False
284
285 196 # Subcomponents of InteractiveShell
286 197 alias_manager = Instance('IPython.core.alias.AliasManager')
287 198 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
@@ -290,9 +201,8 b' class InteractiveShell(Configurable, Magic):'
290 201 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
291 202 plugin_manager = Instance('IPython.core.plugin.PluginManager')
292 203
293 def __init__(self, config=None, ipython_dir=None, usage=None,
204 def __init__(self, config=None, ipython_dir=None,
294 205 user_ns=None, user_global_ns=None,
295 banner1=None, banner2=None, display_banner=None,
296 206 custom_exceptions=((),None)):
297 207
298 208 # This is where traits with a config_key argument are updated
@@ -302,9 +212,6 b' class InteractiveShell(Configurable, Magic):'
302 212 # These are relatively independent and stateless
303 213 self.init_ipython_dir(ipython_dir)
304 214 self.init_instance_attrs()
305 self.init_term_title()
306 self.init_usage(usage)
307 self.init_banner(banner1, banner2, display_banner)
308 215
309 216 # Create namespaces (user_ns, user_global_ns, etc.)
310 217 self.init_create_namespaces(user_ns, user_global_ns)
@@ -366,27 +273,10 b' class InteractiveShell(Configurable, Magic):'
366 273 # Trait changed handlers
367 274 #-------------------------------------------------------------------------
368 275
369 def _banner1_changed(self):
370 self.compute_banner()
371
372 def _banner2_changed(self):
373 self.compute_banner()
374
375 276 def _ipython_dir_changed(self, name, new):
376 277 if not os.path.isdir(new):
377 278 os.makedirs(new, mode = 0777)
378 279
379 @property
380 def usable_screen_length(self):
381 if self.screen_length == 0:
382 return 0
383 else:
384 num_lines_bot = self.separate_in.count('\n')+1
385 return self.screen_length - num_lines_bot
386
387 def _term_title_changed(self, name, new_value):
388 self.init_term_title()
389
390 280 def set_autoindent(self,value=None):
391 281 """Set the autoindent flag, checking for readline support.
392 282
@@ -421,7 +311,6 b' class InteractiveShell(Configurable, Magic):'
421 311 self.config.Global.ipython_dir = self.ipython_dir
422 312
423 313 def init_instance_attrs(self):
424 self.jobs = BackgroundJobManager()
425 314 self.more = False
426 315
427 316 # command compiler
@@ -443,9 +332,6 b' class InteractiveShell(Configurable, Magic):'
443 332 # item which gets cleared once run.
444 333 self.code_to_run = None
445 334
446 # Flag to mark unconditional exit
447 self.exit_now = False
448
449 335 # Temporary files used for various purposes. Deleted at exit.
450 336 self.tempfiles = []
451 337
@@ -459,20 +345,6 b' class InteractiveShell(Configurable, Magic):'
459 345 # Indentation management
460 346 self.indent_current_nsp = 0
461 347
462 def init_term_title(self):
463 # Enable or disable the terminal title.
464 if self.term_title:
465 toggle_set_term_title(True)
466 set_term_title('IPython: ' + abbrev_cwd())
467 else:
468 toggle_set_term_title(False)
469
470 def init_usage(self, usage=None):
471 if usage is None:
472 self.usage = interactive_usage
473 else:
474 self.usage = usage
475
476 348 def init_encoding(self):
477 349 # Get system encoding at startup time. Certain terminals (like Emacs
478 350 # under Win32 have it set to None, and we need to have a known valid
@@ -550,31 +422,6 b' class InteractiveShell(Configurable, Magic):'
550 422 warn("doctest module does not exist.")
551 423
552 424 #-------------------------------------------------------------------------
553 # Things related to the banner
554 #-------------------------------------------------------------------------
555
556 def init_banner(self, banner1, banner2, display_banner):
557 if banner1 is not None:
558 self.banner1 = banner1
559 if banner2 is not None:
560 self.banner2 = banner2
561 if display_banner is not None:
562 self.display_banner = display_banner
563 self.compute_banner()
564
565 def show_banner(self, banner=None):
566 if banner is None:
567 banner = self.banner
568 self.write(banner)
569
570 def compute_banner(self):
571 self.banner = self.banner1 + '\n'
572 if self.profile:
573 self.banner += '\nIPython profile: %s\n' % self.profile
574 if self.banner2:
575 self.banner += '\n' + self.banner2 + '\n'
576
577 #-------------------------------------------------------------------------
578 425 # Things related to injections into the sys module
579 426 #-------------------------------------------------------------------------
580 427
@@ -762,11 +609,6 b' class InteractiveShell(Configurable, Magic):'
762 609
763 610 # notify the actual exception handlers
764 611 self.InteractiveTB.call_pdb = val
765 if self.isthreaded:
766 try:
767 self.sys_excepthook.call_pdb = val
768 except:
769 warn('Failed to activate pdb for threaded exception handler')
770 612
771 613 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
772 614 'Control auto-activation of pdb at exceptions')
@@ -1404,64 +1246,6 b' class InteractiveShell(Configurable, Magic):'
1404 1246 value = msg, (filename, lineno, offset, line)
1405 1247 self.SyntaxTB(etype,value,[])
1406 1248
1407 def edit_syntax_error(self):
1408 """The bottom half of the syntax error handler called in the main loop.
1409
1410 Loop until syntax error is fixed or user cancels.
1411 """
1412
1413 while self.SyntaxTB.last_syntax_error:
1414 # copy and clear last_syntax_error
1415 err = self.SyntaxTB.clear_err_state()
1416 if not self._should_recompile(err):
1417 return
1418 try:
1419 # may set last_syntax_error again if a SyntaxError is raised
1420 self.safe_execfile(err.filename,self.user_ns)
1421 except:
1422 self.showtraceback()
1423 else:
1424 try:
1425 f = file(err.filename)
1426 try:
1427 # This should be inside a display_trap block and I
1428 # think it is.
1429 sys.displayhook(f.read())
1430 finally:
1431 f.close()
1432 except:
1433 self.showtraceback()
1434
1435 def _should_recompile(self,e):
1436 """Utility routine for edit_syntax_error"""
1437
1438 if e.filename in ('<ipython console>','<input>','<string>',
1439 '<console>','<BackgroundJob compilation>',
1440 None):
1441
1442 return False
1443 try:
1444 if (self.autoedit_syntax and
1445 not self.ask_yes_no('Return to editor to correct syntax error? '
1446 '[Y/n] ','y')):
1447 return False
1448 except EOFError:
1449 return False
1450
1451 def int0(x):
1452 try:
1453 return int(x)
1454 except TypeError:
1455 return 0
1456 # always pass integer line and offset values to editor hook
1457 try:
1458 self.hooks.fix_error_editor(e.filename,
1459 int0(e.lineno),int0(e.offset),e.msg)
1460 except TryNext:
1461 warn('Could not open editor')
1462 return False
1463 return True
1464
1465 1249 #-------------------------------------------------------------------------
1466 1250 # Things related to tab completion
1467 1251 #-------------------------------------------------------------------------
@@ -1641,13 +1425,12 b' class InteractiveShell(Configurable, Magic):'
1641 1425
1642 1426 self.rl_next_input = s
1643 1427
1428 # Maybe move this to the terminal subclass?
1644 1429 def pre_readline(self):
1645 1430 """readline hook to be used at the start of each line.
1646 1431
1647 1432 Currently it handles auto-indent only."""
1648 1433
1649 #debugx('self.indent_current_nsp','pre_readline:')
1650
1651 1434 if self.rl_do_indent:
1652 1435 self.readline.insert_text(self._indent_current_str())
1653 1436 if self.rl_next_input is not None:
@@ -1773,6 +1556,17 b' class InteractiveShell(Configurable, Magic):'
1773 1556 self.plugin_manager = PluginManager(config=self.config)
1774 1557
1775 1558 #-------------------------------------------------------------------------
1559 # Things related to the prefilter
1560 #-------------------------------------------------------------------------
1561
1562 def init_prefilter(self):
1563 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1564 # Ultimately this will be refactored in the new interpreter code, but
1565 # for now, we should expose the main prefilter method (there's legacy
1566 # code out there that may rely on this).
1567 self.prefilter = self.prefilter_manager.prefilter_lines
1568
1569 #-------------------------------------------------------------------------
1776 1570 # Things related to the running of code
1777 1571 #-------------------------------------------------------------------------
1778 1572
@@ -1789,177 +1583,6 b' class InteractiveShell(Configurable, Magic):'
1789 1583 with nested(self.builtin_trap,):
1790 1584 return eval(expr, self.user_global_ns, self.user_ns)
1791 1585
1792 def mainloop(self, display_banner=None):
1793 """Start the mainloop.
1794
1795 If an optional banner argument is given, it will override the
1796 internally created default banner.
1797 """
1798
1799 with nested(self.builtin_trap, self.display_trap):
1800
1801 # if you run stuff with -c <cmd>, raw hist is not updated
1802 # ensure that it's in sync
1803 if len(self.input_hist) != len (self.input_hist_raw):
1804 self.input_hist_raw = InputList(self.input_hist)
1805
1806 while 1:
1807 try:
1808 self.interact(display_banner=display_banner)
1809 #self.interact_with_readline()
1810 # XXX for testing of a readline-decoupled repl loop, call
1811 # interact_with_readline above
1812 break
1813 except KeyboardInterrupt:
1814 # this should not be necessary, but KeyboardInterrupt
1815 # handling seems rather unpredictable...
1816 self.write("\nKeyboardInterrupt in interact()\n")
1817
1818 def interact_prompt(self):
1819 """ Print the prompt (in read-eval-print loop)
1820
1821 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1822 used in standard IPython flow.
1823 """
1824 if self.more:
1825 try:
1826 prompt = self.hooks.generate_prompt(True)
1827 except:
1828 self.showtraceback()
1829 if self.autoindent:
1830 self.rl_do_indent = True
1831
1832 else:
1833 try:
1834 prompt = self.hooks.generate_prompt(False)
1835 except:
1836 self.showtraceback()
1837 self.write(prompt)
1838
1839 def interact_handle_input(self,line):
1840 """ Handle the input line (in read-eval-print loop)
1841
1842 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1843 used in standard IPython flow.
1844 """
1845 if line.lstrip() == line:
1846 self.shadowhist.add(line.strip())
1847 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1848
1849 if line.strip():
1850 if self.more:
1851 self.input_hist_raw[-1] += '%s\n' % line
1852 else:
1853 self.input_hist_raw.append('%s\n' % line)
1854
1855
1856 self.more = self.push_line(lineout)
1857 if (self.SyntaxTB.last_syntax_error and
1858 self.autoedit_syntax):
1859 self.edit_syntax_error()
1860
1861 def interact_with_readline(self):
1862 """ Demo of using interact_handle_input, interact_prompt
1863
1864 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1865 it should work like this.
1866 """
1867 self.readline_startup_hook(self.pre_readline)
1868 while not self.exit_now:
1869 self.interact_prompt()
1870 if self.more:
1871 self.rl_do_indent = True
1872 else:
1873 self.rl_do_indent = False
1874 line = raw_input_original().decode(self.stdin_encoding)
1875 self.interact_handle_input(line)
1876
1877 def interact(self, display_banner=None):
1878 """Closely emulate the interactive Python console."""
1879
1880 # batch run -> do not interact
1881 if self.exit_now:
1882 return
1883
1884 if display_banner is None:
1885 display_banner = self.display_banner
1886 if display_banner:
1887 self.show_banner()
1888
1889 more = 0
1890
1891 # Mark activity in the builtins
1892 __builtin__.__dict__['__IPYTHON__active'] += 1
1893
1894 if self.has_readline:
1895 self.readline_startup_hook(self.pre_readline)
1896 # exit_now is set by a call to %Exit or %Quit, through the
1897 # ask_exit callback.
1898
1899 while not self.exit_now:
1900 self.hooks.pre_prompt_hook()
1901 if more:
1902 try:
1903 prompt = self.hooks.generate_prompt(True)
1904 except:
1905 self.showtraceback()
1906 if self.autoindent:
1907 self.rl_do_indent = True
1908
1909 else:
1910 try:
1911 prompt = self.hooks.generate_prompt(False)
1912 except:
1913 self.showtraceback()
1914 try:
1915 line = self.raw_input(prompt, more)
1916 if self.exit_now:
1917 # quick exit on sys.std[in|out] close
1918 break
1919 if self.autoindent:
1920 self.rl_do_indent = False
1921
1922 except KeyboardInterrupt:
1923 #double-guard against keyboardinterrupts during kbdint handling
1924 try:
1925 self.write('\nKeyboardInterrupt\n')
1926 self.resetbuffer()
1927 # keep cache in sync with the prompt counter:
1928 self.outputcache.prompt_count -= 1
1929
1930 if self.autoindent:
1931 self.indent_current_nsp = 0
1932 more = 0
1933 except KeyboardInterrupt:
1934 pass
1935 except EOFError:
1936 if self.autoindent:
1937 self.rl_do_indent = False
1938 if self.has_readline:
1939 self.readline_startup_hook(None)
1940 self.write('\n')
1941 self.exit()
1942 except bdb.BdbQuit:
1943 warn('The Python debugger has exited with a BdbQuit exception.\n'
1944 'Because of how pdb handles the stack, it is impossible\n'
1945 'for IPython to properly format this particular exception.\n'
1946 'IPython will resume normal operation.')
1947 except:
1948 # exceptions here are VERY RARE, but they can be triggered
1949 # asynchronously by signal handlers, for example.
1950 self.showtraceback()
1951 else:
1952 more = self.push_line(line)
1953 if (self.SyntaxTB.last_syntax_error and
1954 self.autoedit_syntax):
1955 self.edit_syntax_error()
1956
1957 # We are off again...
1958 __builtin__.__dict__['__IPYTHON__active'] -= 1
1959
1960 # Turn off the exit flag, so the mainloop can be restarted if desired
1961 self.exit_now = False
1962
1963 1586 def safe_execfile(self, fname, *where, **kw):
1964 1587 """A safe version of the builtin execfile().
1965 1588
@@ -2057,43 +1680,6 b' class InteractiveShell(Configurable, Magic):'
2057 1680 except:
2058 1681 self.showtraceback()
2059 1682 warn('Unknown failure executing file: <%s>' % fname)
2060
2061 def _is_secondary_block_start(self, s):
2062 if not s.endswith(':'):
2063 return False
2064 if (s.startswith('elif') or
2065 s.startswith('else') or
2066 s.startswith('except') or
2067 s.startswith('finally')):
2068 return True
2069
2070 def cleanup_ipy_script(self, script):
2071 """Make a script safe for self.runlines()
2072
2073 Currently, IPython is lines based, with blocks being detected by
2074 empty lines. This is a problem for block based scripts that may
2075 not have empty lines after blocks. This script adds those empty
2076 lines to make scripts safe for running in the current line based
2077 IPython.
2078 """
2079 res = []
2080 lines = script.splitlines()
2081 level = 0
2082
2083 for l in lines:
2084 lstripped = l.lstrip()
2085 stripped = l.strip()
2086 if not stripped:
2087 continue
2088 newlevel = len(l) - len(lstripped)
2089 if level > 0 and newlevel == 0 and \
2090 not self._is_secondary_block_start(stripped):
2091 # add empty line
2092 res.append('')
2093 res.append(l)
2094 level = newlevel
2095
2096 return '\n'.join(res) + '\n'
2097 1683
2098 1684 def runlines(self, lines, clean=False):
2099 1685 """Run a string of one or more lines of source.
@@ -2108,7 +1694,7 b' class InteractiveShell(Configurable, Magic):'
2108 1694 lines = '\n'.join(lines)
2109 1695
2110 1696 if clean:
2111 lines = self.cleanup_ipy_script(lines)
1697 lines = self._cleanup_ipy_script(lines)
2112 1698
2113 1699 # We must start with a clean buffer, in case this is run from an
2114 1700 # interactive IPython session (via a magic, for example).
@@ -2272,6 +1858,47 b' class InteractiveShell(Configurable, Magic):'
2272 1858 self.resetbuffer()
2273 1859 return more
2274 1860
1861 def resetbuffer(self):
1862 """Reset the input buffer."""
1863 self.buffer[:] = []
1864
1865 def _is_secondary_block_start(self, s):
1866 if not s.endswith(':'):
1867 return False
1868 if (s.startswith('elif') or
1869 s.startswith('else') or
1870 s.startswith('except') or
1871 s.startswith('finally')):
1872 return True
1873
1874 def _cleanup_ipy_script(self, script):
1875 """Make a script safe for self.runlines()
1876
1877 Currently, IPython is lines based, with blocks being detected by
1878 empty lines. This is a problem for block based scripts that may
1879 not have empty lines after blocks. This script adds those empty
1880 lines to make scripts safe for running in the current line based
1881 IPython.
1882 """
1883 res = []
1884 lines = script.splitlines()
1885 level = 0
1886
1887 for l in lines:
1888 lstripped = l.lstrip()
1889 stripped = l.strip()
1890 if not stripped:
1891 continue
1892 newlevel = len(l) - len(lstripped)
1893 if level > 0 and newlevel == 0 and \
1894 not self._is_secondary_block_start(stripped):
1895 # add empty line
1896 res.append('')
1897 res.append(l)
1898 level = newlevel
1899
1900 return '\n'.join(res) + '\n'
1901
2275 1902 def _autoindent_update(self,line):
2276 1903 """Keep track of the indent level."""
2277 1904
@@ -2290,91 +1917,12 b' class InteractiveShell(Configurable, Magic):'
2290 1917 else:
2291 1918 self.indent_current_nsp = 0
2292 1919
2293 def resetbuffer(self):
2294 """Reset the input buffer."""
2295 self.buffer[:] = []
2296
2297 def raw_input(self,prompt='',continue_prompt=False):
2298 """Write a prompt and read a line.
2299
2300 The returned line does not include the trailing newline.
2301 When the user enters the EOF key sequence, EOFError is raised.
2302
2303 Optional inputs:
2304
2305 - prompt(''): a string to be printed to prompt the user.
2306
2307 - continue_prompt(False): whether this line is the first one or a
2308 continuation in a sequence of inputs.
2309 """
2310 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2311
2312 # Code run by the user may have modified the readline completer state.
2313 # We must ensure that our completer is back in place.
2314
2315 if self.has_readline:
2316 self.set_completer()
2317
2318 try:
2319 line = raw_input_original(prompt).decode(self.stdin_encoding)
2320 except ValueError:
2321 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2322 " or sys.stdout.close()!\nExiting IPython!")
2323 self.ask_exit()
2324 return ""
2325
2326 # Try to be reasonably smart about not re-indenting pasted input more
2327 # than necessary. We do this by trimming out the auto-indent initial
2328 # spaces, if the user's actual input started itself with whitespace.
2329 #debugx('self.buffer[-1]')
2330
2331 if self.autoindent:
2332 if num_ini_spaces(line) > self.indent_current_nsp:
2333 line = line[self.indent_current_nsp:]
2334 self.indent_current_nsp = 0
2335
2336 # store the unfiltered input before the user has any chance to modify
2337 # it.
2338 if line.strip():
2339 if continue_prompt:
2340 self.input_hist_raw[-1] += '%s\n' % line
2341 if self.has_readline and self.readline_use:
2342 try:
2343 histlen = self.readline.get_current_history_length()
2344 if histlen > 1:
2345 newhist = self.input_hist_raw[-1].rstrip()
2346 self.readline.remove_history_item(histlen-1)
2347 self.readline.replace_history_item(histlen-2,
2348 newhist.encode(self.stdin_encoding))
2349 except AttributeError:
2350 pass # re{move,place}_history_item are new in 2.4.
2351 else:
2352 self.input_hist_raw.append('%s\n' % line)
2353 # only entries starting at first column go to shadow history
2354 if line.lstrip() == line:
2355 self.shadowhist.add(line.strip())
2356 elif not continue_prompt:
2357 self.input_hist_raw.append('\n')
2358 try:
2359 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2360 except:
2361 # blanket except, in case a user-defined prefilter crashes, so it
2362 # can't take all of ipython with it.
2363 self.showtraceback()
2364 return ''
2365 else:
2366 return lineout
2367
2368 1920 #-------------------------------------------------------------------------
2369 # Things related to the prefilter
1921 # Things related to GUI support and pylab
2370 1922 #-------------------------------------------------------------------------
2371 1923
2372 def init_prefilter(self):
2373 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2374 # Ultimately this will be refactored in the new interpreter code, but
2375 # for now, we should expose the main prefilter method (there's legacy
2376 # code out there that may rely on this).
2377 self.prefilter = self.prefilter_manager.prefilter_lines
1924 def enable_pylab(self, gui=None):
1925 raise NotImplementedError('Implement enable_pylab in a subclass')
2378 1926
2379 1927 #-------------------------------------------------------------------------
2380 1928 # Utilities
@@ -2426,10 +1974,12 b' class InteractiveShell(Configurable, Magic):'
2426 1974 tmp_file.close()
2427 1975 return filename
2428 1976
1977 # TODO: This should be removed when Term is refactored.
2429 1978 def write(self,data):
2430 1979 """Write a string to the default output"""
2431 1980 Term.cout.write(data)
2432 1981
1982 # TODO: This should be removed when Term is refactored.
2433 1983 def write_err(self,data):
2434 1984 """Write a string to the default error output"""
2435 1985 Term.cerr.write(data)
@@ -2440,58 +1990,9 b' class InteractiveShell(Configurable, Magic):'
2440 1990 return ask_yes_no(prompt,default)
2441 1991
2442 1992 #-------------------------------------------------------------------------
2443 # Things related to GUI support and pylab
2444 #-------------------------------------------------------------------------
2445
2446 def enable_pylab(self, gui=None):
2447 """Activate pylab support at runtime.
2448
2449 This turns on support for matplotlib, preloads into the interactive
2450 namespace all of numpy and pylab, and configures IPython to correcdtly
2451 interact with the GUI event loop. The GUI backend to be used can be
2452 optionally selected with the optional :param:`gui` argument.
2453
2454 Parameters
2455 ----------
2456 gui : optional, string
2457
2458 If given, dictates the choice of matplotlib GUI backend to use
2459 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2460 'gtk'), otherwise we use the default chosen by matplotlib (as
2461 dictated by the matplotlib build-time options plus the user's
2462 matplotlibrc configuration file).
2463 """
2464 # We want to prevent the loading of pylab to pollute the user's
2465 # namespace as shown by the %who* magics, so we execute the activation
2466 # code in an empty namespace, and we update *both* user_ns and
2467 # user_ns_hidden with this information.
2468 ns = {}
2469 gui = pylab_activate(ns, gui)
2470 self.user_ns.update(ns)
2471 self.user_ns_hidden.update(ns)
2472 # Now we must activate the gui pylab wants to use, and fix %run to take
2473 # plot updates into account
2474 enable_gui(gui)
2475 self.magic_run = self._pylab_magic_run
2476
2477 #-------------------------------------------------------------------------
2478 1993 # Things related to IPython exiting
2479 1994 #-------------------------------------------------------------------------
2480 1995
2481 def ask_exit(self):
2482 """ Ask the shell to exit. Can be overiden and used as a callback. """
2483 self.exit_now = True
2484
2485 def exit(self):
2486 """Handle interactive exit.
2487
2488 This method calls the ask_exit callback."""
2489 if self.confirm_exit:
2490 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2491 self.ask_exit()
2492 else:
2493 self.ask_exit()
2494
2495 1996 def atexit_operations(self):
2496 1997 """This will be executed at the time of exit.
2497 1998
@@ -25,6 +25,6 b' has been made into a component, this module will be sent to deathrow.'
25 25
26 26 def get():
27 27 """Get the global InteractiveShell instance."""
28 from IPython.core.interactiveshell import InteractiveShell
29 return InteractiveShell.instance()
28 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
29 return TerminalInteractiveShell.instance()
30 30
@@ -2524,13 +2524,6 b' Currently the magic system has the following functions:\\n"""'
2524 2524 except:
2525 2525 xmode_switch_err('user')
2526 2526
2527 # threaded shells use a special handler in sys.excepthook
2528 if shell.isthreaded:
2529 try:
2530 shell.sys_excepthook.set_mode(mode=new_mode)
2531 except:
2532 xmode_switch_err('threaded')
2533
2534 2527 def magic_colors(self,parameter_s = ''):
2535 2528 """Switch color scheme for prompts, info system and exception handlers.
2536 2529
@@ -2585,13 +2578,6 b' Defaulting color scheme to \'NoColor\'"""'
2585 2578 except:
2586 2579 color_switch_err('exception')
2587 2580
2588 # threaded shells use a verbose traceback in sys.excepthook
2589 if shell.isthreaded:
2590 try:
2591 shell.sys_excepthook.set_colors(scheme=new_scheme)
2592 except:
2593 color_switch_err('system exception handler')
2594
2595 2581 # Set info (for 'object?') colors
2596 2582 if shell.color_info:
2597 2583 try:
@@ -3160,49 +3146,6 b' Defaulting color scheme to \'NoColor\'"""'
3160 3146 print >> Term.cerr,err
3161 3147 return SList(out.split('\n'))
3162 3148
3163 def magic_bg(self, parameter_s=''):
3164 """Run a job in the background, in a separate thread.
3165
3166 For example,
3167
3168 %bg myfunc(x,y,z=1)
3169
3170 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3171 execution starts, a message will be printed indicating the job
3172 number. If your job number is 5, you can use
3173
3174 myvar = jobs.result(5) or myvar = jobs[5].result
3175
3176 to assign this result to variable 'myvar'.
3177
3178 IPython has a job manager, accessible via the 'jobs' object. You can
3179 type jobs? to get more information about it, and use jobs.<TAB> to see
3180 its attributes. All attributes not starting with an underscore are
3181 meant for public use.
3182
3183 In particular, look at the jobs.new() method, which is used to create
3184 new jobs. This magic %bg function is just a convenience wrapper
3185 around jobs.new(), for expression-based jobs. If you want to create a
3186 new job with an explicit function object and arguments, you must call
3187 jobs.new() directly.
3188
3189 The jobs.new docstring also describes in detail several important
3190 caveats associated with a thread-based model for background job
3191 execution. Type jobs.new? for details.
3192
3193 You can check the status of all jobs with jobs.status().
3194
3195 The jobs variable is set by IPython into the Python builtin namespace.
3196 If you ever declare a variable named 'jobs', you will shadow this
3197 name. You can either delete your global jobs variable to regain
3198 access to the job manager, or make a new name and assign it manually
3199 to the manager (stored in IPython's namespace). For example, to
3200 assign the job manager to the Jobs name, use:
3201
3202 Jobs = __builtins__.jobs"""
3203
3204 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3205
3206 3149 def magic_r(self, parameter_s=''):
3207 3150 """Repeat previous input.
3208 3151
@@ -40,9 +40,6 b' def test_import_magic():'
40 40 def test_import_oinspect():
41 41 from IPython.core import oinspect
42 42
43 def test_import_outputtrap():
44 from IPython.core import outputtrap
45
46 43 def test_import_prefilter():
47 44 from IPython.core import prefilter
48 45
1 NO CONTENT: file renamed from IPython/core/outputtrap.py to IPython/deathrow/outputtrap.py
@@ -30,7 +30,7 b' import sys'
30 30 from contextlib import nested
31 31
32 32 from IPython.core import ultratb
33 from IPython.core.interactiveshell import InteractiveShell
33 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
34 34 from IPython.frontend.terminal.ipapp import load_default_config
35 35
36 36 from IPython.utils.traitlets import Bool, Str, CBool
@@ -59,7 +59,7 b" def kill_embedded(self,parameter_s=''):"
59 59 print "This embedded IPython will not reactivate anymore once you exit."
60 60
61 61
62 class InteractiveShellEmbed(InteractiveShell):
62 class InteractiveShellEmbed(TerminalInteractiveShell):
63 63
64 64 dummy_mode = Bool(False)
65 65 exit_msg = Str('')
@@ -69,18 +69,19 b' class InteractiveShellEmbed(InteractiveShell):'
69 69 # is True by default.
70 70 display_banner = CBool(True)
71 71
72 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
73 user_ns=None, user_global_ns=None,
74 banner1=None, banner2=None, display_banner=None,
75 custom_exceptions=((),None), exit_msg=''):
72 def __init__(self, config=None, ipython_dir=None, user_ns=None,
73 user_global_ns=None, custom_exceptions=((),None),
74 usage=None, banner1=None, banner2=None,
75 display_banner=None, exit_msg=u''):
76 76
77 77 self.save_sys_ipcompleter()
78 78
79 79 super(InteractiveShellEmbed,self).__init__(
80 parent=parent, config=config, ipython_dir=ipython_dir, usage=usage,
81 user_ns=user_ns, user_global_ns=user_global_ns,
82 banner1=banner1, banner2=banner2, display_banner=display_banner,
83 custom_exceptions=custom_exceptions)
80 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
81 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions,
82 usage=usage, banner1=banner1, banner2=banner2,
83 display_banner=display_banner
84 )
84 85
85 86 self.exit_msg = exit_msg
86 87 self.define_magic("kill_embedded", kill_embedded)
@@ -240,8 +241,7 b' class InteractiveShellEmbed(InteractiveShell):'
240 241 _embedded_shell = None
241 242
242 243
243 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
244 display_banner=True, exit_msg=''):
244 def embed(**kwargs):
245 245 """Call this to embed IPython at the current point in your program.
246 246
247 247 The first invocation of this will create an :class:`InteractiveShellEmbed`
@@ -261,15 +261,12 b" def embed(header='', config=None, usage=None, banner1=None, banner2=None,"
261 261 Full customization can be done by passing a :class:`Struct` in as the
262 262 config argument.
263 263 """
264 config = kwargs.get('config')
265 header = kwargs.pop('header', u'')
264 266 if config is None:
265 267 config = load_default_config()
266 config.InteractiveShellEmbed = config.InteractiveShell
268 config.InteractiveShellEmbed = config.TerminalInteractiveShell
267 269 global _embedded_shell
268 270 if _embedded_shell is None:
269 _embedded_shell = InteractiveShellEmbed(
270 config=config, usage=usage,
271 banner1=banner1, banner2=banner2,
272 display_banner=display_banner, exit_msg=exit_msg
273 )
271 _embedded_shell = InteractiveShellEmbed(**kwargs)
274 272 _embedded_shell(header=header, stack_depth=2)
275
@@ -31,7 +31,7 b' import sys'
31 31 from IPython.core import release
32 32 from IPython.core.crashhandler import CrashHandler
33 33 from IPython.core.application import Application, BaseAppConfigLoader
34 from IPython.core.interactiveshell import InteractiveShell
34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
35 35 from IPython.config.loader import (
36 36 Config,
37 37 PyFileConfigLoader
@@ -85,10 +85,10 b' class IPAppConfigLoader(BaseAppConfigLoader):'
85 85 The default is '1'.""",
86 86 metavar='InteractiveShell.autocall')
87 87 paa('--autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
88 action='store_true', dest='TerminalInteractiveShell.autoindent',
89 89 help='Turn on autoindenting.')
90 90 paa('--no-autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
91 action='store_false', dest='TerminalInteractiveShell.autoindent',
92 92 help='Turn off autoindenting.')
93 93 paa('--automagic',
94 94 action='store_true', dest='InteractiveShell.automagic',
@@ -99,10 +99,10 b' class IPAppConfigLoader(BaseAppConfigLoader):'
99 99 action='store_false', dest='InteractiveShell.automagic',
100 100 help='Turn off the auto calling of magic commands.')
101 101 paa('--autoedit-syntax',
102 action='store_true', dest='InteractiveShell.autoedit_syntax',
102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
103 103 help='Turn on auto editing of files with syntax errors.')
104 104 paa('--no-autoedit-syntax',
105 action='store_false', dest='InteractiveShell.autoedit_syntax',
105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
106 106 help='Turn off auto editing of files with syntax errors.')
107 107 paa('--banner',
108 108 action='store_true', dest='Global.display_banner',
@@ -143,13 +143,13 b' class IPAppConfigLoader(BaseAppConfigLoader):'
143 143 action='store_false', dest='InteractiveShell.color_info',
144 144 help="Disable using colors for info related things.")
145 145 paa('--confirm-exit',
146 action='store_true', dest='InteractiveShell.confirm_exit',
146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
147 147 help=
148 148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 150 '%%Exit', you can force a direct exit without any confirmation.""")
151 151 paa('--no-confirm-exit',
152 action='store_false', dest='InteractiveShell.confirm_exit',
152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
153 153 help="Don't prompt the user when exiting.")
154 154 paa('--deep-reload',
155 155 action='store_true', dest='InteractiveShell.deep_reload',
@@ -167,9 +167,9 b' class IPAppConfigLoader(BaseAppConfigLoader):'
167 167 action='store_false', dest='InteractiveShell.deep_reload',
168 168 help="Disable deep (recursive) reloading by default.")
169 169 paa('--editor',
170 type=str, dest='InteractiveShell.editor',
170 type=str, dest='TerminalInteractiveShell.editor',
171 171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 metavar='InteractiveShell.editor')
172 metavar='TerminalInteractiveShell.editor')
173 173 paa('--log','-l',
174 174 action='store_true', dest='InteractiveShell.logstart',
175 175 help="Start logging to the default log file (./ipython_log.py).")
@@ -228,7 +228,7 b' class IPAppConfigLoader(BaseAppConfigLoader):'
228 228 action='store_false', dest='InteractiveShell.readline_use',
229 229 help="Disable readline for command line usage.")
230 230 paa('--screen-length','-sl',
231 type=int, dest='InteractiveShell.screen_length',
231 type=int, dest='TerminalInteractiveShell.screen_length',
232 232 help=
233 233 """Number of lines of your screen, used to control printing of very
234 234 long strings. Strings longer than this number of lines will be sent
@@ -239,27 +239,27 b' class IPAppConfigLoader(BaseAppConfigLoader):'
239 239 internally). If for some reason this isn't working well (it needs
240 240 curses support), specify it yourself. Otherwise don't change the
241 241 default.""",
242 metavar='InteractiveShell.screen_length')
242 metavar='TerminalInteractiveShell.screen_length')
243 243 paa('--separate-in','-si',
244 type=str, dest='InteractiveShell.separate_in',
244 type=str, dest='TerminalInteractiveShell.separate_in',
245 245 help="Separator before input prompts. Default '\\n'.",
246 metavar='InteractiveShell.separate_in')
246 metavar='TerminalInteractiveShell.separate_in')
247 247 paa('--separate-out','-so',
248 type=str, dest='InteractiveShell.separate_out',
248 type=str, dest='TerminalInteractiveShell.separate_out',
249 249 help="Separator before output prompts. Default 0 (nothing).",
250 metavar='InteractiveShell.separate_out')
250 metavar='TerminalInteractiveShell.separate_out')
251 251 paa('--separate-out2','-so2',
252 type=str, dest='InteractiveShell.separate_out2',
252 type=str, dest='TerminalInteractiveShell.separate_out2',
253 253 help="Separator after output prompts. Default 0 (nonight).",
254 metavar='InteractiveShell.separate_out2')
254 metavar='TerminalInteractiveShell.separate_out2')
255 255 paa('--no-sep',
256 256 action='store_true', dest='Global.nosep',
257 257 help="Eliminate all spacing between prompts.")
258 258 paa('--term-title',
259 action='store_true', dest='InteractiveShell.term_title',
259 action='store_true', dest='TerminalInteractiveShell.term_title',
260 260 help="Enable auto setting the terminal title.")
261 261 paa('--no-term-title',
262 action='store_false', dest='InteractiveShell.term_title',
262 action='store_false', dest='TerminalInteractiveShell.term_title',
263 263 help="Disable auto setting the terminal title.")
264 264 paa('--xmode',
265 265 type=str, dest='InteractiveShell.xmode',
@@ -448,17 +448,17 b' class IPythonApp(Application):'
448 448 config.InteractiveShell.prompt_in1 = '>>> '
449 449 config.InteractiveShell.prompt_in2 = '... '
450 450 config.InteractiveShell.prompt_out = ''
451 config.InteractiveShell.separate_in = \
452 config.InteractiveShell.separate_out = \
453 config.InteractiveShell.separate_out2 = ''
451 config.TerminalInteractiveShell.separate_in = \
452 config.TerminalInteractiveShell.separate_out = \
453 config.TerminalInteractiveShell.separate_out2 = ''
454 454 config.InteractiveShell.colors = 'NoColor'
455 455 config.InteractiveShell.xmode = 'Plain'
456 456
457 457 if hasattr(config.Global, 'nosep'):
458 458 if config.Global.nosep:
459 config.InteractiveShell.separate_in = \
460 config.InteractiveShell.separate_out = \
461 config.InteractiveShell.separate_out2 = ''
459 config.TerminalInteractiveShell.separate_in = \
460 config.TerminalInteractiveShell.separate_out = \
461 config.TerminalInteractiveShell.separate_out2 = ''
462 462
463 463 # if there is code of files to run from the cmd line, don't interact
464 464 # unless the -i flag (Global.force_interact) is true.
@@ -476,7 +476,7 b' class IPythonApp(Application):'
476 476 sys.path.insert(0, '')
477 477
478 478 # Create an InteractiveShell instance.
479 self.shell = InteractiveShell.instance(config=self.master_config)
479 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
480 480
481 481 def post_construct(self):
482 482 """Do actions after construct, but before starting the app."""
@@ -114,8 +114,7 b' def start_ipython():'
114 114 return
115 115 start_ipython.already_called = True
116 116
117 # Ok, first time we're called, go ahead
118 from IPython.core import interactiveshell
117 from IPython.frontend.terminal import interactiveshell
119 118
120 119 def xsys(cmd):
121 120 """Execute a command and print its output.
@@ -136,7 +135,7 b' def start_ipython():'
136 135 config = tools.default_config()
137 136
138 137 # Create and initialize our test-friendly IPython instance.
139 shell = interactiveshell.InteractiveShell.instance(
138 shell = interactiveshell.TerminalInteractiveShell.instance(
140 139 config=config,
141 140 user_ns=ipnsdict(), user_global_ns={}
142 141 )
@@ -164,9 +164,9 b' def default_argv():'
164 164 def default_config():
165 165 """Return a config object with good defaults for testing."""
166 166 config = Config()
167 config.InteractiveShell.colors = 'NoColor'
168 config.InteractiveShell.term_title = False,
169 config.InteractiveShell.autocall = 0
167 config.TerminalInteractiveShell.colors = 'NoColor'
168 config.TerminalTerminalInteractiveShell.term_title = False,
169 config.TerminalInteractiveShell.autocall = 0
170 170 return config
171 171
172 172
@@ -471,3 +471,14 b" def marquee(txt='',width=78,mark='*'):"
471 471 return '%s %s %s' % (marks,txt,marks)
472 472
473 473
474 ini_spaces_re = re.compile(r'^(\s+)')
475
476 def num_ini_spaces(strng):
477 """Return the number of initial spaces in a string"""
478
479 ini_spaces = ini_spaces_re.match(strng)
480 if ini_spaces:
481 return ini_spaces.end()
482 else:
483 return 0
484
General Comments 0
You need to be logged in to leave comments. Login now