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