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