##// END OF EJS Templates
Complete reorganization of InteractiveShell....
Brian Granger -
r2761:7b6e19f0
parent child
Show More
@@ -0,0 +1,14
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
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 c = get_config()
47
47
48 # c.InteractiveShell.autocall = 1
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 # c.InteractiveShell.automagic = False
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 # c.InteractiveShell.cache_size = 1000
60 # c.InteractiveShell.cache_size = 1000
61
61
@@ -63,11 +63,11 c = get_config()
63
63
64 # c.InteractiveShell.color_info = True
64 # c.InteractiveShell.color_info = True
65
65
66 # c.InteractiveShell.confirm_exit = True
66 # c.TerminalInteractiveShell.confirm_exit = True
67
67
68 # c.InteractiveShell.deep_reload = False
68 # c.InteractiveShell.deep_reload = False
69
69
70 # c.InteractiveShell.editor = 'nano'
70 # c.TerminalInteractiveShell.editor = 'nano'
71
71
72 # c.InteractiveShell.logstart = True
72 # c.InteractiveShell.logstart = True
73
73
@@ -77,7 +77,7 c = get_config()
77
77
78 # c.InteractiveShell.object_info_string_level = 0
78 # c.InteractiveShell.object_info_string_level = 0
79
79
80 # c.InteractiveShell.pager = 'less'
80 # c.TerminalInteractiveShell.pager = 'less'
81
81
82 # c.InteractiveShell.pdb = False
82 # c.InteractiveShell.pdb = False
83
83
@@ -114,17 +114,17 c = get_config()
114 # c.InteractiveShell.readline_merge_completions = True
114 # c.InteractiveShell.readline_merge_completions = True
115 # c.InteractiveShell.readline_omit__names = 0
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'
119 # c.TerminalInteractiveShell.separate_in = '\n'
120 # c.InteractiveShell.separate_out = ''
120 # c.TerminalInteractiveShell.separate_out = ''
121 # c.InteractiveShell.separate_out2 = ''
121 # c.TerminalInteractiveShell.separate_out2 = ''
122
122
123 # c.InteractiveShell.system_header = "IPython system call: "
123 # c.InteractiveShell.system_header = "IPython system call: "
124
124
125 # c.InteractiveShell.system_verbose = True
125 # c.InteractiveShell.system_verbose = True
126
126
127 # c.InteractiveShell.term_title = False
127 # c.TerminalInteractiveShell.term_title = False
128
128
129 # c.InteractiveShell.wildcards_case_sensitive = True
129 # c.InteractiveShell.wildcards_case_sensitive = True
130
130
@@ -10,9 +10,9 c.InteractiveShell.prompt_out = '<\#> '
10
10
11 c.InteractiveShell.prompts_pad_left = True
11 c.InteractiveShell.prompts_pad_left = True
12
12
13 c.InteractiveShell.separate_in = ''
13 c.TerminalInteractiveShell.separate_in = ''
14 c.InteractiveShell.separate_out = ''
14 c.TerminalInteractiveShell.separate_out = ''
15 c.InteractiveShell.separate_out2 = ''
15 c.TerminalInteractiveShell.separate_out2 = ''
16
16
17 c.PrefilterManager.multi_line_specials = True
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 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import abc
21 import abc
22 import bdb
23 import codeop
22 import codeop
24 import exceptions
23 import exceptions
25 import new
24 import new
@@ -39,35 +38,27 from IPython.core.alias import AliasManager
39 from IPython.core.builtin_trap import BuiltinTrap
38 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.config.configurable import Configurable
39 from IPython.config.configurable import Configurable
41 from IPython.core.display_trap import DisplayTrap
40 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.error import TryNext, UsageError
41 from IPython.core.error import UsageError
43 from IPython.core.extensions import ExtensionManager
42 from IPython.core.extensions import ExtensionManager
44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.inputlist import InputList
45 from IPython.core.logger import Logger
45 from IPython.core.logger import Logger
46 from IPython.core.magic import Magic
46 from IPython.core.magic import Magic
47 from IPython.core.plugin import PluginManager
47 from IPython.core.plugin import PluginManager
48 from IPython.core.prefilter import PrefilterManager
48 from IPython.core.prefilter import PrefilterManager
49 from IPython.core.prompts import CachedOutput
49 from IPython.core.prompts import CachedOutput
50 from IPython.core.usage import interactive_usage, default_banner
51 import IPython.core.hooks
50 import IPython.core.hooks
52 from IPython.external.Itpl import ItplNS
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 from IPython.utils import PyColorize
52 from IPython.utils import PyColorize
57 from IPython.utils import pickleshare
53 from IPython.utils import pickleshare
58 from IPython.utils.doctestreload import doctest_reload
54 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.ipstruct import Struct
55 from IPython.utils.ipstruct import Struct
60 from IPython.utils.io import Term, ask_yes_no
56 from IPython.utils.io import Term, ask_yes_no
61 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
57 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.process import (
58 from IPython.utils.process import getoutput, getoutputerror
63 abbrev_cwd,
64 getoutput,
65 getoutputerror
66 )
67 # import IPython.utils.rlineimpl as readline
68 from IPython.utils.strdispatch import StrDispatch
59 from IPython.utils.strdispatch import StrDispatch
69 from IPython.utils.syspathcontext import prepended_to_syspath
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 from IPython.utils.warn import warn, error, fatal
62 from IPython.utils.warn import warn, error, fatal
72 from IPython.utils.traitlets import (
63 from IPython.utils.traitlets import (
73 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
64 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
@@ -80,10 +71,6 from IPython.utils.traitlets import (
80 # Globals
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 # compiled regexps for autoindent management
74 # compiled regexps for autoindent management
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
75 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89
76
@@ -91,18 +78,9 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
91 # Utilities
78 # Utilities
92 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
93
80
94 ini_spaces_re = re.compile(r'^(\s+)')
81 # store the builtin raw_input globally, and use this always, in case user code
95
82 # overwrites it (like wx.py.PyShell does)
96
83 raw_input_original = raw_input
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
106
84
107 def softspace(file, newvalue):
85 def softspace(file, newvalue):
108 """Copied from code.py, to remove the dependency"""
86 """Copied from code.py, to remove the dependency"""
@@ -126,22 +104,6 class SpaceInInput(exceptions.Exception): pass
126
104
127 class Bunch: pass
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 class SyntaxTB(ultratb.ListTB):
107 class SyntaxTB(ultratb.ListTB):
146 """Extension which holds some state: the last exception value"""
108 """Extension which holds some state: the last exception value"""
147
109
@@ -160,17 +122,6 class SyntaxTB(ultratb.ListTB):
160 return e
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 def get_default_colors():
125 def get_default_colors():
175 if sys.platform=='darwin':
126 if sys.platform=='darwin':
176 return "LightBG"
127 return "LightBG"
@@ -180,18 +131,6 def get_default_colors():
180 return 'Linux'
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 # Main IPython class
135 # Main IPython class
197 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
@@ -201,28 +140,13 class InteractiveShell(Configurable, Magic):
201 """An enhanced, interactive shell for Python."""
140 """An enhanced, interactive shell for Python."""
202
141
203 autocall = Enum((0,1,2), default_value=1, config=True)
142 autocall = Enum<