##// END OF EJS Templates
Continue refactoring input handling across clients....
Fernando Perez -
Show More
@@ -1,297 +1,293 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
2 """Displayhook for IPython.
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 __builtin__
22 import __builtin__
23 from pprint import PrettyPrinter
23 from pprint import PrettyPrinter
24 pformat = PrettyPrinter().pformat
24 pformat = PrettyPrinter().pformat
25
25
26 from IPython.config.configurable import Configurable
26 from IPython.config.configurable import Configurable
27 from IPython.core import prompts
27 from IPython.core import prompts
28 import IPython.utils.generics
28 import IPython.utils.generics
29 import IPython.utils.io
29 import IPython.utils.io
30 from IPython.utils.traitlets import Instance, Int
30 from IPython.utils.traitlets import Instance, Int
31 from IPython.utils.warn import warn
31 from IPython.utils.warn import warn
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Main displayhook class
34 # Main displayhook class
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37 # TODO: The DisplayHook class should be split into two classes, one that
37 # TODO: The DisplayHook class should be split into two classes, one that
38 # manages the prompts and their synchronization and another that just does the
38 # manages the prompts and their synchronization and another that just does the
39 # displayhook logic and calls into the prompt manager.
39 # displayhook logic and calls into the prompt manager.
40
40
41 # TODO: Move the various attributes (cache_size, colors, input_sep,
41 # TODO: Move the various attributes (cache_size, colors, input_sep,
42 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
42 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
43 # attributes of InteractiveShell. They should be on ONE object only and the
43 # attributes of InteractiveShell. They should be on ONE object only and the
44 # other objects should ask that one object for their values.
44 # other objects should ask that one object for their values.
45
45
46 class DisplayHook(Configurable):
46 class DisplayHook(Configurable):
47 """The custom IPython displayhook to replace sys.displayhook.
47 """The custom IPython displayhook to replace sys.displayhook.
48
48
49 This class does many things, but the basic idea is that it is a callable
49 This class does many things, but the basic idea is that it is a callable
50 that gets called anytime user code returns a value.
50 that gets called anytime user code returns a value.
51
51
52 Currently this class does more than just the displayhook logic and that
52 Currently this class does more than just the displayhook logic and that
53 extra logic should eventually be moved out of here.
53 extra logic should eventually be moved out of here.
54 """
54 """
55
55
56 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
56 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
57
57
58 # Each call to the In[] prompt raises it by 1, even the first.
58 # Each call to the In[] prompt raises it by 1, even the first.
59 #prompt_count = Int(0)
59 #prompt_count = Int(0)
60
60
61 def __init__(self, shell=None, cache_size=1000,
61 def __init__(self, shell=None, cache_size=1000,
62 colors='NoColor', input_sep='\n',
62 colors='NoColor', input_sep='\n',
63 output_sep='\n', output_sep2='',
63 output_sep='\n', output_sep2='',
64 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
64 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
65 config=None):
65 config=None):
66 super(DisplayHook, self).__init__(shell=shell, config=config)
66 super(DisplayHook, self).__init__(shell=shell, config=config)
67
67
68 cache_size_min = 3
68 cache_size_min = 3
69 if cache_size <= 0:
69 if cache_size <= 0:
70 self.do_full_cache = 0
70 self.do_full_cache = 0
71 cache_size = 0
71 cache_size = 0
72 elif cache_size < cache_size_min:
72 elif cache_size < cache_size_min:
73 self.do_full_cache = 0
73 self.do_full_cache = 0
74 cache_size = 0
74 cache_size = 0
75 warn('caching was disabled (min value for cache size is %s).' %
75 warn('caching was disabled (min value for cache size is %s).' %
76 cache_size_min,level=3)
76 cache_size_min,level=3)
77 else:
77 else:
78 self.do_full_cache = 1
78 self.do_full_cache = 1
79
79
80 self.cache_size = cache_size
80 self.cache_size = cache_size
81 self.input_sep = input_sep
81 self.input_sep = input_sep
82
82
83 # we need a reference to the user-level namespace
83 # we need a reference to the user-level namespace
84 self.shell = shell
84 self.shell = shell
85
85
86 # Set input prompt strings and colors
86 # Set input prompt strings and colors
87 if cache_size == 0:
87 if cache_size == 0:
88 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
88 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
89 or ps1.find(r'\N') > -1:
89 or ps1.find(r'\N') > -1:
90 ps1 = '>>> '
90 ps1 = '>>> '
91 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
91 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
92 or ps2.find(r'\N') > -1:
92 or ps2.find(r'\N') > -1:
93 ps2 = '... '
93 ps2 = '... '
94 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
94 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
95 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
95 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
96 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
96 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
97
97
98 self.color_table = prompts.PromptColors
98 self.color_table = prompts.PromptColors
99 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
99 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
100 pad_left=pad_left)
100 pad_left=pad_left)
101 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
101 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
102 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
102 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
103 pad_left=pad_left)
103 pad_left=pad_left)
104 self.set_colors(colors)
104 self.set_colors(colors)
105
105
106 # Store the last prompt string each time, we need it for aligning
106 # Store the last prompt string each time, we need it for aligning
107 # continuation and auto-rewrite prompts
107 # continuation and auto-rewrite prompts
108 self.last_prompt = ''
108 self.last_prompt = ''
109 self.output_sep = output_sep
109 self.output_sep = output_sep
110 self.output_sep2 = output_sep2
110 self.output_sep2 = output_sep2
111 self._,self.__,self.___ = '','',''
111 self._,self.__,self.___ = '','',''
112 self.pprint_types = map(type,[(),[],{}])
112 self.pprint_types = map(type,[(),[],{}])
113
113
114 # these are deliberately global:
114 # these are deliberately global:
115 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
115 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
116 self.shell.user_ns.update(to_user_ns)
116 self.shell.user_ns.update(to_user_ns)
117
117
118 @property
118 @property
119 def prompt_count(self):
119 def prompt_count(self):
120 return self.shell.execution_count
120 return self.shell.execution_count
121
121
122 @prompt_count.setter
123 def _set_prompt_count(self, val):
124 raise ValueError('prompt count is read only')
125
126 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
122 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
127 if p_str is None:
123 if p_str is None:
128 if self.do_full_cache:
124 if self.do_full_cache:
129 return cache_def
125 return cache_def
130 else:
126 else:
131 return no_cache_def
127 return no_cache_def
132 else:
128 else:
133 return p_str
129 return p_str
134
130
135 def set_colors(self, colors):
131 def set_colors(self, colors):
136 """Set the active color scheme and configure colors for the three
132 """Set the active color scheme and configure colors for the three
137 prompt subsystems."""
133 prompt subsystems."""
138
134
139 # FIXME: This modifying of the global prompts.prompt_specials needs
135 # FIXME: This modifying of the global prompts.prompt_specials needs
140 # to be fixed. We need to refactor all of the prompts stuff to use
136 # to be fixed. We need to refactor all of the prompts stuff to use
141 # proper configuration and traits notifications.
137 # proper configuration and traits notifications.
142 if colors.lower()=='nocolor':
138 if colors.lower()=='nocolor':
143 prompts.prompt_specials = prompts.prompt_specials_nocolor
139 prompts.prompt_specials = prompts.prompt_specials_nocolor
144 else:
140 else:
145 prompts.prompt_specials = prompts.prompt_specials_color
141 prompts.prompt_specials = prompts.prompt_specials_color
146
142
147 self.color_table.set_active_scheme(colors)
143 self.color_table.set_active_scheme(colors)
148 self.prompt1.set_colors()
144 self.prompt1.set_colors()
149 self.prompt2.set_colors()
145 self.prompt2.set_colors()
150 self.prompt_out.set_colors()
146 self.prompt_out.set_colors()
151
147
152 #-------------------------------------------------------------------------
148 #-------------------------------------------------------------------------
153 # Methods used in __call__. Override these methods to modify the behavior
149 # Methods used in __call__. Override these methods to modify the behavior
154 # of the displayhook.
150 # of the displayhook.
155 #-------------------------------------------------------------------------
151 #-------------------------------------------------------------------------
156
152
157 def check_for_underscore(self):
153 def check_for_underscore(self):
158 """Check if the user has set the '_' variable by hand."""
154 """Check if the user has set the '_' variable by hand."""
159 # If something injected a '_' variable in __builtin__, delete
155 # If something injected a '_' variable in __builtin__, delete
160 # ipython's automatic one so we don't clobber that. gettext() in
156 # ipython's automatic one so we don't clobber that. gettext() in
161 # particular uses _, so we need to stay away from it.
157 # particular uses _, so we need to stay away from it.
162 if '_' in __builtin__.__dict__:
158 if '_' in __builtin__.__dict__:
163 try:
159 try:
164 del self.shell.user_ns['_']
160 del self.shell.user_ns['_']
165 except KeyError:
161 except KeyError:
166 pass
162 pass
167
163
168 def quiet(self):
164 def quiet(self):
169 """Should we silence the display hook because of ';'?"""
165 """Should we silence the display hook because of ';'?"""
170 # do not print output if input ends in ';'
166 # do not print output if input ends in ';'
171 try:
167 try:
172 if self.shell.input_hist[self.prompt_count].endswith(';\n'):
168 if self.shell.input_hist[self.prompt_count].endswith(';\n'):
173 return True
169 return True
174 except IndexError:
170 except IndexError:
175 # some uses of ipshellembed may fail here
171 # some uses of ipshellembed may fail here
176 pass
172 pass
177 return False
173 return False
178
174
179 def start_displayhook(self):
175 def start_displayhook(self):
180 """Start the displayhook, initializing resources."""
176 """Start the displayhook, initializing resources."""
181 pass
177 pass
182
178
183 def write_output_prompt(self):
179 def write_output_prompt(self):
184 """Write the output prompt."""
180 """Write the output prompt."""
185 # Use write, not print which adds an extra space.
181 # Use write, not print which adds an extra space.
186 IPython.utils.io.Term.cout.write(self.output_sep)
182 IPython.utils.io.Term.cout.write(self.output_sep)
187 outprompt = str(self.prompt_out)
183 outprompt = str(self.prompt_out)
188 if self.do_full_cache:
184 if self.do_full_cache:
189 IPython.utils.io.Term.cout.write(outprompt)
185 IPython.utils.io.Term.cout.write(outprompt)
190
186
191 # TODO: Make this method an extension point. The previous implementation
187 # TODO: Make this method an extension point. The previous implementation
192 # has both a result_display hook as well as a result_display generic
188 # has both a result_display hook as well as a result_display generic
193 # function to customize the repr on a per class basis. We need to rethink
189 # function to customize the repr on a per class basis. We need to rethink
194 # the hooks mechanism before doing this though.
190 # the hooks mechanism before doing this though.
195 def compute_result_repr(self, result):
191 def compute_result_repr(self, result):
196 """Compute and return the repr of the object to be displayed.
192 """Compute and return the repr of the object to be displayed.
197
193
198 This method only compute the string form of the repr and should NOT
194 This method only compute the string form of the repr and should NOT
199 actual print or write that to a stream. This method may also transform
195 actual print or write that to a stream. This method may also transform
200 the result itself, but the default implementation passes the original
196 the result itself, but the default implementation passes the original
201 through.
197 through.
202 """
198 """
203 try:
199 try:
204 if self.shell.pprint:
200 if self.shell.pprint:
205 result_repr = pformat(result)
201 result_repr = pformat(result)
206 if '\n' in result_repr:
202 if '\n' in result_repr:
207 # So that multi-line strings line up with the left column of
203 # So that multi-line strings line up with the left column of
208 # the screen, instead of having the output prompt mess up
204 # the screen, instead of having the output prompt mess up
209 # their first line.
205 # their first line.
210 result_repr = '\n' + result_repr
206 result_repr = '\n' + result_repr
211 else:
207 else:
212 result_repr = repr(result)
208 result_repr = repr(result)
213 except TypeError:
209 except TypeError:
214 # This happens when result.__repr__ doesn't return a string,
210 # This happens when result.__repr__ doesn't return a string,
215 # such as when it returns None.
211 # such as when it returns None.
216 result_repr = '\n'
212 result_repr = '\n'
217 return result, result_repr
213 return result, result_repr
218
214
219 def write_result_repr(self, result_repr):
215 def write_result_repr(self, result_repr):
220 # We want to print because we want to always make sure we have a
216 # We want to print because we want to always make sure we have a
221 # newline, even if all the prompt separators are ''. This is the
217 # newline, even if all the prompt separators are ''. This is the
222 # standard IPython behavior.
218 # standard IPython behavior.
223 print >>IPython.utils.io.Term.cout, result_repr
219 print >>IPython.utils.io.Term.cout, result_repr
224
220
225 def update_user_ns(self, result):
221 def update_user_ns(self, result):
226 """Update user_ns with various things like _, __, _1, etc."""
222 """Update user_ns with various things like _, __, _1, etc."""
227
223
228 # Avoid recursive reference when displaying _oh/Out
224 # Avoid recursive reference when displaying _oh/Out
229 if result is not self.shell.user_ns['_oh']:
225 if result is not self.shell.user_ns['_oh']:
230 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
226 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
231 warn('Output cache limit (currently '+
227 warn('Output cache limit (currently '+
232 `self.cache_size`+' entries) hit.\n'
228 `self.cache_size`+' entries) hit.\n'
233 'Flushing cache and resetting history counter...\n'
229 'Flushing cache and resetting history counter...\n'
234 'The only history variables available will be _,__,___ and _1\n'
230 'The only history variables available will be _,__,___ and _1\n'
235 'with the current result.')
231 'with the current result.')
236
232
237 self.flush()
233 self.flush()
238 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
234 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
239 # we cause buggy behavior for things like gettext).
235 # we cause buggy behavior for things like gettext).
240 if '_' not in __builtin__.__dict__:
236 if '_' not in __builtin__.__dict__:
241 self.___ = self.__
237 self.___ = self.__
242 self.__ = self._
238 self.__ = self._
243 self._ = result
239 self._ = result
244 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
240 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
245
241
246 # hackish access to top-level namespace to create _1,_2... dynamically
242 # hackish access to top-level namespace to create _1,_2... dynamically
247 to_main = {}
243 to_main = {}
248 if self.do_full_cache:
244 if self.do_full_cache:
249 new_result = '_'+`self.prompt_count`
245 new_result = '_'+`self.prompt_count`
250 to_main[new_result] = result
246 to_main[new_result] = result
251 self.shell.user_ns.update(to_main)
247 self.shell.user_ns.update(to_main)
252 self.shell.user_ns['_oh'][self.prompt_count] = result
248 self.shell.user_ns['_oh'][self.prompt_count] = result
253
249
254 def log_output(self, result):
250 def log_output(self, result):
255 """Log the output."""
251 """Log the output."""
256 if self.shell.logger.log_output:
252 if self.shell.logger.log_output:
257 self.shell.logger.log_write(repr(result),'output')
253 self.shell.logger.log_write(repr(result),'output')
258
254
259 def finish_displayhook(self):
255 def finish_displayhook(self):
260 """Finish up all displayhook activities."""
256 """Finish up all displayhook activities."""
261 IPython.utils.io.Term.cout.write(self.output_sep2)
257 IPython.utils.io.Term.cout.write(self.output_sep2)
262 IPython.utils.io.Term.cout.flush()
258 IPython.utils.io.Term.cout.flush()
263
259
264 def __call__(self, result=None):
260 def __call__(self, result=None):
265 """Printing with history cache management.
261 """Printing with history cache management.
266
262
267 This is invoked everytime the interpreter needs to print, and is
263 This is invoked everytime the interpreter needs to print, and is
268 activated by setting the variable sys.displayhook to it.
264 activated by setting the variable sys.displayhook to it.
269 """
265 """
270 self.check_for_underscore()
266 self.check_for_underscore()
271 if result is not None and not self.quiet():
267 if result is not None and not self.quiet():
272 self.start_displayhook()
268 self.start_displayhook()
273 self.write_output_prompt()
269 self.write_output_prompt()
274 result, result_repr = self.compute_result_repr(result)
270 result, result_repr = self.compute_result_repr(result)
275 self.write_result_repr(result_repr)
271 self.write_result_repr(result_repr)
276 self.update_user_ns(result)
272 self.update_user_ns(result)
277 self.log_output(result)
273 self.log_output(result)
278 self.finish_displayhook()
274 self.finish_displayhook()
279
275
280 def flush(self):
276 def flush(self):
281 if not self.do_full_cache:
277 if not self.do_full_cache:
282 raise ValueError,"You shouldn't have reached the cache flush "\
278 raise ValueError,"You shouldn't have reached the cache flush "\
283 "if full caching is not enabled!"
279 "if full caching is not enabled!"
284 # delete auto-generated vars from global namespace
280 # delete auto-generated vars from global namespace
285
281
286 for n in range(1,self.prompt_count + 1):
282 for n in range(1,self.prompt_count + 1):
287 key = '_'+`n`
283 key = '_'+`n`
288 try:
284 try:
289 del self.shell.user_ns[key]
285 del self.shell.user_ns[key]
290 except: pass
286 except: pass
291 self.shell.user_ns['_oh'].clear()
287 self.shell.user_ns['_oh'].clear()
292
288
293 if '_' not in __builtin__.__dict__:
289 if '_' not in __builtin__.__dict__:
294 self.shell.user_ns.update({'_':None,'__':None, '___':None})
290 self.shell.user_ns.update({'_':None,'__':None, '___':None})
295 import gc
291 import gc
296 gc.collect() # xxx needed?
292 gc.collect() # xxx needed?
297
293
@@ -1,462 +1,461 b''
1 """ History related magics and functionality """
1 """ History related magics and functionality """
2 #-----------------------------------------------------------------------------
2 #-----------------------------------------------------------------------------
3 # Copyright (C) 2010 The IPython Development Team.
3 # Copyright (C) 2010 The IPython Development Team.
4 #
4 #
5 # Distributed under the terms of the BSD License.
5 # Distributed under the terms of the BSD License.
6 #
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
7 # The full license is in the file COPYING.txt, distributed with this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 from __future__ import print_function
13 from __future__ import print_function
14
14
15 # Stdlib imports
15 # Stdlib imports
16 import fnmatch
16 import fnmatch
17 import os
17 import os
18 import sys
18 import sys
19
19
20 # Our own packages
20 # Our own packages
21 import IPython.utils.io
21 import IPython.utils.io
22
22
23 from IPython.core import ipapi
23 from IPython.core import ipapi
24 from IPython.core.inputlist import InputList
24 from IPython.core.inputlist import InputList
25 from IPython.utils.pickleshare import PickleShareDB
25 from IPython.utils.pickleshare import PickleShareDB
26 from IPython.utils.io import ask_yes_no
26 from IPython.utils.io import ask_yes_no
27 from IPython.utils.warn import warn
27 from IPython.utils.warn import warn
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Classes and functions
30 # Classes and functions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 class HistoryManager(object):
33 class HistoryManager(object):
34 """A class to organize all history-related functionality in one place.
34 """A class to organize all history-related functionality in one place.
35 """
35 """
36 def __init__(self, shell):
36 def __init__(self, shell):
37 """Create a new history manager associated with a shell instance.
37 """Create a new history manager associated with a shell instance.
38 """
38 """
39 self.shell = shell
39 self.shell = shell
40
40
41 # List of input with multi-line handling.
41 # List of input with multi-line handling.
42 self.input_hist = InputList()
42 self.input_hist = InputList()
43 # This one will hold the 'raw' input history, without any
43 # This one will hold the 'raw' input history, without any
44 # pre-processing. This will allow users to retrieve the input just as
44 # pre-processing. This will allow users to retrieve the input just as
45 # it was exactly typed in by the user, with %hist -r.
45 # it was exactly typed in by the user, with %hist -r.
46 self.input_hist_raw = InputList()
46 self.input_hist_raw = InputList()
47
47
48 # list of visited directories
48 # list of visited directories
49 try:
49 try:
50 self.dir_hist = [os.getcwd()]
50 self.dir_hist = [os.getcwd()]
51 except OSError:
51 except OSError:
52 self.dir_hist = []
52 self.dir_hist = []
53
53
54 # dict of output history
54 # dict of output history
55 self.output_hist = {}
55 self.output_hist = {}
56
56
57 # Now the history file
57 # Now the history file
58 if shell.profile:
58 if shell.profile:
59 histfname = 'history-%s' % shell.profile
59 histfname = 'history-%s' % shell.profile
60 else:
60 else:
61 histfname = 'history'
61 histfname = 'history'
62 self.hist_file = os.path.join(shell.ipython_dir, histfname)
62 self.hist_file = os.path.join(shell.ipython_dir, histfname)
63
63
64 # Objects related to shadow history management
64 # Objects related to shadow history management
65 self._init_shadow_hist()
65 self._init_shadow_hist()
66
66
67 # Fill the history zero entry, user counter starts at 1
67 # Fill the history zero entry, user counter starts at 1
68 self.store_inputs('\n', '\n')
68 self.store_inputs('\n', '\n')
69
69
70 # For backwards compatibility, we must put these back in the shell
70 # For backwards compatibility, we must put these back in the shell
71 # object, until we've removed all direct uses of the history objects in
71 # object, until we've removed all direct uses of the history objects in
72 # the shell itself.
72 # the shell itself.
73 shell.input_hist = self.input_hist
73 shell.input_hist = self.input_hist
74 shell.input_hist_raw = self.input_hist_raw
74 shell.input_hist_raw = self.input_hist_raw
75 shell.output_hist = self.output_hist
75 shell.output_hist = self.output_hist
76 shell.dir_hist = self.dir_hist
76 shell.dir_hist = self.dir_hist
77 shell.histfile = self.hist_file
77 shell.histfile = self.hist_file
78 shell.shadowhist = self.shadow_hist
78 shell.shadowhist = self.shadow_hist
79 shell.db = self.shadow_db
79 shell.db = self.shadow_db
80
80
81 def _init_shadow_hist(self):
81 def _init_shadow_hist(self):
82 try:
82 try:
83 self.shadow_db = PickleShareDB(os.path.join(
83 self.shadow_db = PickleShareDB(os.path.join(
84 self.shell.ipython_dir, 'db'))
84 self.shell.ipython_dir, 'db'))
85 except UnicodeDecodeError:
85 except UnicodeDecodeError:
86 print("Your ipython_dir can't be decoded to unicode!")
86 print("Your ipython_dir can't be decoded to unicode!")
87 print("Please set HOME environment variable to something that")
87 print("Please set HOME environment variable to something that")
88 print(r"only has ASCII characters, e.g. c:\home")
88 print(r"only has ASCII characters, e.g. c:\home")
89 print("Now it is", self.ipython_dir)
89 print("Now it is", self.ipython_dir)
90 sys.exit()
90 sys.exit()
91 self.shadow_hist = ShadowHist(self.shadow_db)
91 self.shadow_hist = ShadowHist(self.shadow_db)
92
92
93 def save_hist(self):
93 def save_hist(self):
94 """Save input history to a file (via readline library)."""
94 """Save input history to a file (via readline library)."""
95
95
96 try:
96 try:
97 self.shell.readline.write_history_file(self.hist_file)
97 self.shell.readline.write_history_file(self.hist_file)
98 except:
98 except:
99 print('Unable to save IPython command history to file: ' +
99 print('Unable to save IPython command history to file: ' +
100 `self.hist_file`)
100 `self.hist_file`)
101
101
102 def reload_hist(self):
102 def reload_hist(self):
103 """Reload the input history from disk file."""
103 """Reload the input history from disk file."""
104
104
105 try:
105 try:
106 self.shell.readline.clear_history()
106 self.shell.readline.clear_history()
107 self.shell.readline.read_history_file(self.hist_file)
107 self.shell.readline.read_history_file(self.hist_file)
108 except AttributeError:
108 except AttributeError:
109 pass
109 pass
110
110
111 def get_history(self, index=None, raw=False, output=True):
111 def get_history(self, index=None, raw=False, output=True):
112 """Get the history list.
112 """Get the history list.
113
113
114 Get the input and output history.
114 Get the input and output history.
115
115
116 Parameters
116 Parameters
117 ----------
117 ----------
118 index : n or (n1, n2) or None
118 index : n or (n1, n2) or None
119 If n, then the last entries. If a tuple, then all in
119 If n, then the last entries. If a tuple, then all in
120 range(n1, n2). If None, then all entries. Raises IndexError if
120 range(n1, n2). If None, then all entries. Raises IndexError if
121 the format of index is incorrect.
121 the format of index is incorrect.
122 raw : bool
122 raw : bool
123 If True, return the raw input.
123 If True, return the raw input.
124 output : bool
124 output : bool
125 If True, then return the output as well.
125 If True, then return the output as well.
126
126
127 Returns
127 Returns
128 -------
128 -------
129 If output is True, then return a dict of tuples, keyed by the prompt
129 If output is True, then return a dict of tuples, keyed by the prompt
130 numbers and with values of (input, output). If output is False, then
130 numbers and with values of (input, output). If output is False, then
131 a dict, keyed by the prompt number with the values of input. Raises
131 a dict, keyed by the prompt number with the values of input. Raises
132 IndexError if no history is found.
132 IndexError if no history is found.
133 """
133 """
134 if raw:
134 if raw:
135 input_hist = self.input_hist_raw
135 input_hist = self.input_hist_raw
136 else:
136 else:
137 input_hist = self.input_hist
137 input_hist = self.input_hist
138 if output:
138 if output:
139 output_hist = self.output_hist
139 output_hist = self.output_hist
140 n = len(input_hist)
140 n = len(input_hist)
141 if index is None:
141 if index is None:
142 start=0; stop=n
142 start=0; stop=n
143 elif isinstance(index, int):
143 elif isinstance(index, int):
144 start=n-index; stop=n
144 start=n-index; stop=n
145 elif isinstance(index, tuple) and len(index) == 2:
145 elif isinstance(index, tuple) and len(index) == 2:
146 start=index[0]; stop=index[1]
146 start=index[0]; stop=index[1]
147 else:
147 else:
148 raise IndexError('Not a valid index for the input history: %r'
148 raise IndexError('Not a valid index for the input history: %r'
149 % index)
149 % index)
150 hist = {}
150 hist = {}
151 for i in range(start, stop):
151 for i in range(start, stop):
152 if output:
152 if output:
153 hist[i] = (input_hist[i], output_hist.get(i))
153 hist[i] = (input_hist[i], output_hist.get(i))
154 else:
154 else:
155 hist[i] = input_hist[i]
155 hist[i] = input_hist[i]
156 if not hist:
156 if not hist:
157 raise IndexError('No history for range of indices: %r' % index)
157 raise IndexError('No history for range of indices: %r' % index)
158 return hist
158 return hist
159
159
160 def store_inputs(self, source, source_raw=None):
160 def store_inputs(self, source, source_raw=None):
161 """Store source and raw input in history.
161 """Store source and raw input in history.
162
162
163 Parameters
163 Parameters
164 ----------
164 ----------
165 source : str
165 source : str
166 Python input.
166 Python input.
167
167
168 source_raw : str, optional
168 source_raw : str, optional
169 If given, this is the raw input without any IPython transformations
169 If given, this is the raw input without any IPython transformations
170 applied to it. If not given, ``source`` is used.
170 applied to it. If not given, ``source`` is used.
171 """
171 """
172 if source_raw is None:
172 if source_raw is None:
173 source_raw = source
173 source_raw = source
174 self.input_hist.append(source)
174 self.input_hist.append(source)
175 self.input_hist_raw.append(source_raw)
175 self.input_hist_raw.append(source_raw)
176 self.shadow_hist.add(source)
176 self.shadow_hist.add(source)
177
177
178 def sync_inputs(self):
178 def sync_inputs(self):
179 """Ensure raw and translated histories have same length."""
179 """Ensure raw and translated histories have same length."""
180 if len(self.input_hist) != len (self.input_hist_raw):
180 if len(self.input_hist) != len (self.input_hist_raw):
181 self.input_hist_raw = InputList(self.input_hist)
181 self.input_hist_raw = InputList(self.input_hist)
182
182
183
184 def reset(self):
183 def reset(self):
185 """Clear all histories managed by this object."""
184 """Clear all histories managed by this object."""
186 self.input_hist[:] = []
185 self.input_hist[:] = []
187 self.input_hist_raw[:] = []
186 self.input_hist_raw[:] = []
188 self.output_hist.clear()
187 self.output_hist.clear()
189 # The directory history can't be completely empty
188 # The directory history can't be completely empty
190 self.dir_hist[:] = [os.getcwd()]
189 self.dir_hist[:] = [os.getcwd()]
191
190
192
191
193 def magic_history(self, parameter_s = ''):
192 def magic_history(self, parameter_s = ''):
194 """Print input history (_i<n> variables), with most recent last.
193 """Print input history (_i<n> variables), with most recent last.
195
194
196 %history -> print at most 40 inputs (some may be multi-line)\\
195 %history -> print at most 40 inputs (some may be multi-line)\\
197 %history n -> print at most n inputs\\
196 %history n -> print at most n inputs\\
198 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
197 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
199
198
200 By default, input history is printed without line numbers so it can be
199 By default, input history is printed without line numbers so it can be
201 directly pasted into an editor.
200 directly pasted into an editor.
202
201
203 With -n, each input's number <n> is shown, and is accessible as the
202 With -n, each input's number <n> is shown, and is accessible as the
204 automatically generated variable _i<n> as well as In[<n>]. Multi-line
203 automatically generated variable _i<n> as well as In[<n>]. Multi-line
205 statements are printed starting at a new line for easy copy/paste.
204 statements are printed starting at a new line for easy copy/paste.
206
205
207 Options:
206 Options:
208
207
209 -n: print line numbers for each input.
208 -n: print line numbers for each input.
210 This feature is only available if numbered prompts are in use.
209 This feature is only available if numbered prompts are in use.
211
210
212 -o: also print outputs for each input.
211 -o: also print outputs for each input.
213
212
214 -p: print classic '>>>' python prompts before each input. This is useful
213 -p: print classic '>>>' python prompts before each input. This is useful
215 for making documentation, and in conjunction with -o, for producing
214 for making documentation, and in conjunction with -o, for producing
216 doctest-ready output.
215 doctest-ready output.
217
216
218 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
217 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
219
218
220 -t: print the 'translated' history, as IPython understands it. IPython
219 -t: print the 'translated' history, as IPython understands it. IPython
221 filters your input and converts it all into valid Python source before
220 filters your input and converts it all into valid Python source before
222 executing it (things like magics or aliases are turned into function
221 executing it (things like magics or aliases are turned into function
223 calls, for example). With this option, you'll see the native history
222 calls, for example). With this option, you'll see the native history
224 instead of the user-entered version: '%cd /' will be seen as
223 instead of the user-entered version: '%cd /' will be seen as
225 'get_ipython().magic("%cd /")' instead of '%cd /'.
224 'get_ipython().magic("%cd /")' instead of '%cd /'.
226
225
227 -g: treat the arg as a pattern to grep for in (full) history.
226 -g: treat the arg as a pattern to grep for in (full) history.
228 This includes the "shadow history" (almost all commands ever written).
227 This includes the "shadow history" (almost all commands ever written).
229 Use '%hist -g' to show full shadow history (may be very long).
228 Use '%hist -g' to show full shadow history (may be very long).
230 In shadow history, every index nuwber starts with 0.
229 In shadow history, every index nuwber starts with 0.
231
230
232 -f FILENAME: instead of printing the output to the screen, redirect it to
231 -f FILENAME: instead of printing the output to the screen, redirect it to
233 the given file. The file is always overwritten, though IPython asks for
232 the given file. The file is always overwritten, though IPython asks for
234 confirmation first if it already exists.
233 confirmation first if it already exists.
235 """
234 """
236
235
237 if not self.shell.displayhook.do_full_cache:
236 if not self.shell.displayhook.do_full_cache:
238 print('This feature is only available if numbered prompts are in use.')
237 print('This feature is only available if numbered prompts are in use.')
239 return
238 return
240 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
239 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
241
240
242 # Check if output to specific file was requested.
241 # Check if output to specific file was requested.
243 try:
242 try:
244 outfname = opts['f']
243 outfname = opts['f']
245 except KeyError:
244 except KeyError:
246 outfile = IPython.utils.io.Term.cout # default
245 outfile = IPython.utils.io.Term.cout # default
247 # We don't want to close stdout at the end!
246 # We don't want to close stdout at the end!
248 close_at_end = False
247 close_at_end = False
249 else:
248 else:
250 if os.path.exists(outfname):
249 if os.path.exists(outfname):
251 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
250 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
252 print('Aborting.')
251 print('Aborting.')
253 return
252 return
254
253
255 outfile = open(outfname,'w')
254 outfile = open(outfname,'w')
256 close_at_end = True
255 close_at_end = True
257
256
258 if 't' in opts:
257 if 't' in opts:
259 input_hist = self.shell.input_hist
258 input_hist = self.shell.input_hist
260 elif 'r' in opts:
259 elif 'r' in opts:
261 input_hist = self.shell.input_hist_raw
260 input_hist = self.shell.input_hist_raw
262 else:
261 else:
263 # Raw history is the default
262 # Raw history is the default
264 input_hist = self.shell.input_hist_raw
263 input_hist = self.shell.input_hist_raw
265
264
266 default_length = 40
265 default_length = 40
267 pattern = None
266 pattern = None
268 if 'g' in opts:
267 if 'g' in opts:
269 init = 1
268 init = 1
270 final = len(input_hist)
269 final = len(input_hist)
271 parts = parameter_s.split(None, 1)
270 parts = parameter_s.split(None, 1)
272 if len(parts) == 1:
271 if len(parts) == 1:
273 parts += '*'
272 parts += '*'
274 head, pattern = parts
273 head, pattern = parts
275 pattern = "*" + pattern + "*"
274 pattern = "*" + pattern + "*"
276 elif len(args) == 0:
275 elif len(args) == 0:
277 final = len(input_hist)-1
276 final = len(input_hist)-1
278 init = max(1,final-default_length)
277 init = max(1,final-default_length)
279 elif len(args) == 1:
278 elif len(args) == 1:
280 final = len(input_hist)
279 final = len(input_hist)
281 init = max(1, final-int(args[0]))
280 init = max(1, final-int(args[0]))
282 elif len(args) == 2:
281 elif len(args) == 2:
283 init, final = map(int, args)
282 init, final = map(int, args)
284 else:
283 else:
285 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
284 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
286 print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout)
285 print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout)
287 return
286 return
288
287
289 width = len(str(final))
288 width = len(str(final))
290 line_sep = ['','\n']
289 line_sep = ['','\n']
291 print_nums = 'n' in opts
290 print_nums = 'n' in opts
292 print_outputs = 'o' in opts
291 print_outputs = 'o' in opts
293 pyprompts = 'p' in opts
292 pyprompts = 'p' in opts
294
293
295 found = False
294 found = False
296 if pattern is not None:
295 if pattern is not None:
297 sh = self.shell.shadowhist.all()
296 sh = self.shell.shadowhist.all()
298 for idx, s in sh:
297 for idx, s in sh:
299 if fnmatch.fnmatch(s, pattern):
298 if fnmatch.fnmatch(s, pattern):
300 print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
299 print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
301 found = True
300 found = True
302
301
303 if found:
302 if found:
304 print("===", file=outfile)
303 print("===", file=outfile)
305 print("shadow history ends, fetch by %rep <number> (must start with 0)",
304 print("shadow history ends, fetch by %rep <number> (must start with 0)",
306 file=outfile)
305 file=outfile)
307 print("=== start of normal history ===", file=outfile)
306 print("=== start of normal history ===", file=outfile)
308
307
309 for in_num in range(init, final):
308 for in_num in range(init, final):
310 # Print user history with tabs expanded to 4 spaces. The GUI clients
309 # Print user history with tabs expanded to 4 spaces. The GUI clients
311 # use hard tabs for easier usability in auto-indented code, but we want
310 # use hard tabs for easier usability in auto-indented code, but we want
312 # to produce PEP-8 compliant history for safe pasting into an editor.
311 # to produce PEP-8 compliant history for safe pasting into an editor.
313 inline = input_hist[in_num].expandtabs(4)
312 inline = input_hist[in_num].expandtabs(4)
314
313
315 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
314 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
316 continue
315 continue
317
316
318 multiline = int(inline.count('\n') > 1)
317 multiline = int(inline.count('\n') > 1)
319 if print_nums:
318 if print_nums:
320 print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
319 print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
321 file=outfile)
320 file=outfile)
322 if pyprompts:
321 if pyprompts:
323 print('>>>', file=outfile)
322 print('>>>', file=outfile)
324 if multiline:
323 if multiline:
325 lines = inline.splitlines()
324 lines = inline.splitlines()
326 print('\n... '.join(lines), file=outfile)
325 print('\n... '.join(lines), file=outfile)
327 print('... ', file=outfile)
326 print('... ', file=outfile)
328 else:
327 else:
329 print(inline, end='', file=outfile)
328 print(inline, end='', file=outfile)
330 else:
329 else:
331 print(inline,end='', file=outfile)
330 print(inline,end='', file=outfile)
332 if print_outputs:
331 if print_outputs:
333 output = self.shell.output_hist.get(in_num)
332 output = self.shell.output_hist.get(in_num)
334 if output is not None:
333 if output is not None:
335 print(repr(output), file=outfile)
334 print(repr(output), file=outfile)
336
335
337 if close_at_end:
336 if close_at_end:
338 outfile.close()
337 outfile.close()
339
338
340
339
341 def magic_hist(self, parameter_s=''):
340 def magic_hist(self, parameter_s=''):
342 """Alternate name for %history."""
341 """Alternate name for %history."""
343 return self.magic_history(parameter_s)
342 return self.magic_history(parameter_s)
344
343
345
344
346 def rep_f(self, arg):
345 def rep_f(self, arg):
347 r""" Repeat a command, or get command to input line for editing
346 r""" Repeat a command, or get command to input line for editing
348
347
349 - %rep (no arguments):
348 - %rep (no arguments):
350
349
351 Place a string version of last computation result (stored in the special '_'
350 Place a string version of last computation result (stored in the special '_'
352 variable) to the next input prompt. Allows you to create elaborate command
351 variable) to the next input prompt. Allows you to create elaborate command
353 lines without using copy-paste::
352 lines without using copy-paste::
354
353
355 $ l = ["hei", "vaan"]
354 $ l = ["hei", "vaan"]
356 $ "".join(l)
355 $ "".join(l)
357 ==> heivaan
356 ==> heivaan
358 $ %rep
357 $ %rep
359 $ heivaan_ <== cursor blinking
358 $ heivaan_ <== cursor blinking
360
359
361 %rep 45
360 %rep 45
362
361
363 Place history line 45 to next input prompt. Use %hist to find out the
362 Place history line 45 to next input prompt. Use %hist to find out the
364 number.
363 number.
365
364
366 %rep 1-4 6-7 3
365 %rep 1-4 6-7 3
367
366
368 Repeat the specified lines immediately. Input slice syntax is the same as
367 Repeat the specified lines immediately. Input slice syntax is the same as
369 in %macro and %save.
368 in %macro and %save.
370
369
371 %rep foo
370 %rep foo
372
371
373 Place the most recent line that has the substring "foo" to next input.
372 Place the most recent line that has the substring "foo" to next input.
374 (e.g. 'svn ci -m foobar').
373 (e.g. 'svn ci -m foobar').
375 """
374 """
376
375
377 opts,args = self.parse_options(arg,'',mode='list')
376 opts,args = self.parse_options(arg,'',mode='list')
378 if not args:
377 if not args:
379 self.set_next_input(str(self.shell.user_ns["_"]))
378 self.set_next_input(str(self.shell.user_ns["_"]))
380 return
379 return
381
380
382 if len(args) == 1 and not '-' in args[0]:
381 if len(args) == 1 and not '-' in args[0]:
383 arg = args[0]
382 arg = args[0]
384 if len(arg) > 1 and arg.startswith('0'):
383 if len(arg) > 1 and arg.startswith('0'):
385 # get from shadow hist
384 # get from shadow hist
386 num = int(arg[1:])
385 num = int(arg[1:])
387 line = self.shell.shadowhist.get(num)
386 line = self.shell.shadowhist.get(num)
388 self.set_next_input(str(line))
387 self.set_next_input(str(line))
389 return
388 return
390 try:
389 try:
391 num = int(args[0])
390 num = int(args[0])
392 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
391 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
393 return
392 return
394 except ValueError:
393 except ValueError:
395 pass
394 pass
396
395
397 for h in reversed(self.shell.input_hist_raw):
396 for h in reversed(self.shell.input_hist_raw):
398 if 'rep' in h:
397 if 'rep' in h:
399 continue
398 continue
400 if fnmatch.fnmatch(h,'*' + arg + '*'):
399 if fnmatch.fnmatch(h,'*' + arg + '*'):
401 self.set_next_input(str(h).rstrip())
400 self.set_next_input(str(h).rstrip())
402 return
401 return
403
402
404 try:
403 try:
405 lines = self.extract_input_slices(args, True)
404 lines = self.extract_input_slices(args, True)
406 print("lines", lines)
405 print("lines", lines)
407 self.runlines(lines)
406 self.runlines(lines)
408 except ValueError:
407 except ValueError:
409 print("Not found in recent history:", args)
408 print("Not found in recent history:", args)
410
409
411
410
412 _sentinel = object()
411 _sentinel = object()
413
412
414 class ShadowHist(object):
413 class ShadowHist(object):
415 def __init__(self, db):
414 def __init__(self, db):
416 # cmd => idx mapping
415 # cmd => idx mapping
417 self.curidx = 0
416 self.curidx = 0
418 self.db = db
417 self.db = db
419 self.disabled = False
418 self.disabled = False
420
419
421 def inc_idx(self):
420 def inc_idx(self):
422 idx = self.db.get('shadowhist_idx', 1)
421 idx = self.db.get('shadowhist_idx', 1)
423 self.db['shadowhist_idx'] = idx + 1
422 self.db['shadowhist_idx'] = idx + 1
424 return idx
423 return idx
425
424
426 def add(self, ent):
425 def add(self, ent):
427 if self.disabled:
426 if self.disabled:
428 return
427 return
429 try:
428 try:
430 old = self.db.hget('shadowhist', ent, _sentinel)
429 old = self.db.hget('shadowhist', ent, _sentinel)
431 if old is not _sentinel:
430 if old is not _sentinel:
432 return
431 return
433 newidx = self.inc_idx()
432 newidx = self.inc_idx()
434 #print("new", newidx) # dbg
433 #print("new", newidx) # dbg
435 self.db.hset('shadowhist',ent, newidx)
434 self.db.hset('shadowhist',ent, newidx)
436 except:
435 except:
437 ipapi.get().showtraceback()
436 ipapi.get().showtraceback()
438 print("WARNING: disabling shadow history")
437 print("WARNING: disabling shadow history")
439 self.disabled = True
438 self.disabled = True
440
439
441 def all(self):
440 def all(self):
442 d = self.db.hdict('shadowhist')
441 d = self.db.hdict('shadowhist')
443 items = [(i,s) for (s,i) in d.items()]
442 items = [(i,s) for (s,i) in d.items()]
444 items.sort()
443 items.sort()
445 return items
444 return items
446
445
447 def get(self, idx):
446 def get(self, idx):
448 all = self.all()
447 all = self.all()
449
448
450 for k, v in all:
449 for k, v in all:
451 if k == idx:
450 if k == idx:
452 return v
451 return v
453
452
454
453
455 def init_ipython(ip):
454 def init_ipython(ip):
456 ip.define_magic("rep",rep_f)
455 ip.define_magic("rep",rep_f)
457 ip.define_magic("hist",magic_hist)
456 ip.define_magic("hist",magic_hist)
458 ip.define_magic("history",magic_history)
457 ip.define_magic("history",magic_history)
459
458
460 # XXX - ipy_completers are in quarantine, need to be updated to new apis
459 # XXX - ipy_completers are in quarantine, need to be updated to new apis
461 #import ipy_completers
460 #import ipy_completers
462 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
461 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,1020 +1,1011 b''
1 """Analysis of text input into executable blocks.
1 """Analysis of text input into executable blocks.
2
2
3 The main class in this module, :class:`InputSplitter`, is designed to break
3 The main class in this module, :class:`InputSplitter`, is designed to break
4 input from either interactive, line-by-line environments or block-based ones,
4 input from either interactive, line-by-line environments or block-based ones,
5 into standalone blocks that can be executed by Python as 'single' statements
5 into standalone blocks that can be executed by Python as 'single' statements
6 (thus triggering sys.displayhook).
6 (thus triggering sys.displayhook).
7
7
8 A companion, :class:`IPythonInputSplitter`, provides the same functionality but
8 A companion, :class:`IPythonInputSplitter`, provides the same functionality but
9 with full support for the extended IPython syntax (magics, system calls, etc).
9 with full support for the extended IPython syntax (magics, system calls, etc).
10
10
11 For more details, see the class docstring below.
11 For more details, see the class docstring below.
12
12
13 Syntax Transformations
13 Syntax Transformations
14 ----------------------
14 ----------------------
15
15
16 One of the main jobs of the code in this file is to apply all syntax
16 One of the main jobs of the code in this file is to apply all syntax
17 transformations that make up 'the IPython language', i.e. magics, shell
17 transformations that make up 'the IPython language', i.e. magics, shell
18 escapes, etc. All transformations should be implemented as *fully stateless*
18 escapes, etc. All transformations should be implemented as *fully stateless*
19 entities, that simply take one line as their input and return a line.
19 entities, that simply take one line as their input and return a line.
20 Internally for implementation purposes they may be a normal function or a
20 Internally for implementation purposes they may be a normal function or a
21 callable object, but the only input they receive will be a single line and they
21 callable object, but the only input they receive will be a single line and they
22 should only return a line, without holding any data-dependent state between
22 should only return a line, without holding any data-dependent state between
23 calls.
23 calls.
24
24
25 As an example, the EscapedTransformer is a class so we can more clearly group
25 As an example, the EscapedTransformer is a class so we can more clearly group
26 together the functionality of dispatching to individual functions based on the
26 together the functionality of dispatching to individual functions based on the
27 starting escape character, but the only method for public use is its call
27 starting escape character, but the only method for public use is its call
28 method.
28 method.
29
29
30
30
31 ToDo
31 ToDo
32 ----
32 ----
33
33
34 - Should we make push() actually raise an exception once push_accepts_more()
34 - Should we make push() actually raise an exception once push_accepts_more()
35 returns False?
35 returns False?
36
36
37 - Naming cleanups. The tr_* names aren't the most elegant, though now they are
37 - Naming cleanups. The tr_* names aren't the most elegant, though now they are
38 at least just attributes of a class so not really very exposed.
38 at least just attributes of a class so not really very exposed.
39
39
40 - Think about the best way to support dynamic things: automagic, autocall,
40 - Think about the best way to support dynamic things: automagic, autocall,
41 macros, etc.
41 macros, etc.
42
42
43 - Think of a better heuristic for the application of the transforms in
43 - Think of a better heuristic for the application of the transforms in
44 IPythonInputSplitter.push() than looking at the buffer ending in ':'. Idea:
44 IPythonInputSplitter.push() than looking at the buffer ending in ':'. Idea:
45 track indentation change events (indent, dedent, nothing) and apply them only
45 track indentation change events (indent, dedent, nothing) and apply them only
46 if the indentation went up, but not otherwise.
46 if the indentation went up, but not otherwise.
47
47
48 - Think of the cleanest way for supporting user-specified transformations (the
48 - Think of the cleanest way for supporting user-specified transformations (the
49 user prefilters we had before).
49 user prefilters we had before).
50
50
51 Authors
51 Authors
52 -------
52 -------
53
53
54 * Fernando Perez
54 * Fernando Perez
55 * Brian Granger
55 * Brian Granger
56 """
56 """
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58 # Copyright (C) 2010 The IPython Development Team
58 # Copyright (C) 2010 The IPython Development Team
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63 from __future__ import print_function
63 from __future__ import print_function
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Imports
66 # Imports
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68 # stdlib
68 # stdlib
69 import codeop
69 import codeop
70 import re
70 import re
71 import sys
71 import sys
72
72
73 # IPython modules
73 # IPython modules
74 from IPython.utils.text import make_quoted_expr
74 from IPython.utils.text import make_quoted_expr
75
75
76 #-----------------------------------------------------------------------------
76 #-----------------------------------------------------------------------------
77 # Globals
77 # Globals
78 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
79
79
80 # The escape sequences that define the syntax transformations IPython will
80 # The escape sequences that define the syntax transformations IPython will
81 # apply to user input. These can NOT be just changed here: many regular
81 # apply to user input. These can NOT be just changed here: many regular
82 # expressions and other parts of the code may use their hardcoded values, and
82 # expressions and other parts of the code may use their hardcoded values, and
83 # for all intents and purposes they constitute the 'IPython syntax', so they
83 # for all intents and purposes they constitute the 'IPython syntax', so they
84 # should be considered fixed.
84 # should be considered fixed.
85
85
86 ESC_SHELL = '!' # Send line to underlying system shell
86 ESC_SHELL = '!' # Send line to underlying system shell
87 ESC_SH_CAP = '!!' # Send line to system shell and capture output
87 ESC_SH_CAP = '!!' # Send line to system shell and capture output
88 ESC_HELP = '?' # Find information about object
88 ESC_HELP = '?' # Find information about object
89 ESC_HELP2 = '??' # Find extra-detailed information about object
89 ESC_HELP2 = '??' # Find extra-detailed information about object
90 ESC_MAGIC = '%' # Call magic function
90 ESC_MAGIC = '%' # Call magic function
91 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
91 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
92 ESC_QUOTE2 = ';' # Quote all args as a single string, call
92 ESC_QUOTE2 = ';' # Quote all args as a single string, call
93 ESC_PAREN = '/' # Call first argument with rest of line as arguments
93 ESC_PAREN = '/' # Call first argument with rest of line as arguments
94
94
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96 # Utilities
96 # Utilities
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98
98
99 # FIXME: These are general-purpose utilities that later can be moved to the
99 # FIXME: These are general-purpose utilities that later can be moved to the
100 # general ward. Kept here for now because we're being very strict about test
100 # general ward. Kept here for now because we're being very strict about test
101 # coverage with this code, and this lets us ensure that we keep 100% coverage
101 # coverage with this code, and this lets us ensure that we keep 100% coverage
102 # while developing.
102 # while developing.
103
103
104 # compiled regexps for autoindent management
104 # compiled regexps for autoindent management
105 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
105 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
106 ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
106 ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
107
107
108 # regexp to match pure comment lines so we don't accidentally insert 'if 1:'
108 # regexp to match pure comment lines so we don't accidentally insert 'if 1:'
109 # before pure comments
109 # before pure comments
110 comment_line_re = re.compile('^\s*\#')
110 comment_line_re = re.compile('^\s*\#')
111
111
112
112
113 def num_ini_spaces(s):
113 def num_ini_spaces(s):
114 """Return the number of initial spaces in a string.
114 """Return the number of initial spaces in a string.
115
115
116 Note that tabs are counted as a single space. For now, we do *not* support
116 Note that tabs are counted as a single space. For now, we do *not* support
117 mixing of tabs and spaces in the user's input.
117 mixing of tabs and spaces in the user's input.
118
118
119 Parameters
119 Parameters
120 ----------
120 ----------
121 s : string
121 s : string
122
122
123 Returns
123 Returns
124 -------
124 -------
125 n : int
125 n : int
126 """
126 """
127
127
128 ini_spaces = ini_spaces_re.match(s)
128 ini_spaces = ini_spaces_re.match(s)
129 if ini_spaces:
129 if ini_spaces:
130 return ini_spaces.end()
130 return ini_spaces.end()
131 else:
131 else:
132 return 0
132 return 0
133
133
134
134
135 def remove_comments(src):
135 def remove_comments(src):
136 """Remove all comments from input source.
136 """Remove all comments from input source.
137
137
138 Note: comments are NOT recognized inside of strings!
138 Note: comments are NOT recognized inside of strings!
139
139
140 Parameters
140 Parameters
141 ----------
141 ----------
142 src : string
142 src : string
143 A single or multiline input string.
143 A single or multiline input string.
144
144
145 Returns
145 Returns
146 -------
146 -------
147 String with all Python comments removed.
147 String with all Python comments removed.
148 """
148 """
149
149
150 return re.sub('#.*', '', src)
150 return re.sub('#.*', '', src)
151
151
152
152
153 def get_input_encoding():
153 def get_input_encoding():
154 """Return the default standard input encoding.
154 """Return the default standard input encoding.
155
155
156 If sys.stdin has no encoding, 'ascii' is returned."""
156 If sys.stdin has no encoding, 'ascii' is returned."""
157 # There are strange environments for which sys.stdin.encoding is None. We
157 # There are strange environments for which sys.stdin.encoding is None. We
158 # ensure that a valid encoding is returned.
158 # ensure that a valid encoding is returned.
159 encoding = getattr(sys.stdin, 'encoding', None)
159 encoding = getattr(sys.stdin, 'encoding', None)
160 if encoding is None:
160 if encoding is None:
161 encoding = 'ascii'
161 encoding = 'ascii'
162 return encoding
162 return encoding
163
163
164 #-----------------------------------------------------------------------------
164 #-----------------------------------------------------------------------------
165 # Classes and functions for normal Python syntax handling
165 # Classes and functions for normal Python syntax handling
166 #-----------------------------------------------------------------------------
166 #-----------------------------------------------------------------------------
167
167
168 # HACK! This implementation, written by Robert K a while ago using the
168 # HACK! This implementation, written by Robert K a while ago using the
169 # compiler module, is more robust than the other one below, but it expects its
169 # compiler module, is more robust than the other one below, but it expects its
170 # input to be pure python (no ipython syntax). For now we're using it as a
170 # input to be pure python (no ipython syntax). For now we're using it as a
171 # second-pass splitter after the first pass transforms the input to pure
171 # second-pass splitter after the first pass transforms the input to pure
172 # python.
172 # python.
173
173
174 def split_blocks(python):
174 def split_blocks(python):
175 """ Split multiple lines of code into discrete commands that can be
175 """ Split multiple lines of code into discrete commands that can be
176 executed singly.
176 executed singly.
177
177
178 Parameters
178 Parameters
179 ----------
179 ----------
180 python : str
180 python : str
181 Pure, exec'able Python code.
181 Pure, exec'able Python code.
182
182
183 Returns
183 Returns
184 -------
184 -------
185 commands : list of str
185 commands : list of str
186 Separate commands that can be exec'ed independently.
186 Separate commands that can be exec'ed independently.
187 """
187 """
188
188
189 import compiler
189 import compiler
190
190
191 # compiler.parse treats trailing spaces after a newline as a
191 # compiler.parse treats trailing spaces after a newline as a
192 # SyntaxError. This is different than codeop.CommandCompiler, which
192 # SyntaxError. This is different than codeop.CommandCompiler, which
193 # will compile the trailng spaces just fine. We simply strip any
193 # will compile the trailng spaces just fine. We simply strip any
194 # trailing whitespace off. Passing a string with trailing whitespace
194 # trailing whitespace off. Passing a string with trailing whitespace
195 # to exec will fail however. There seems to be some inconsistency in
195 # to exec will fail however. There seems to be some inconsistency in
196 # how trailing whitespace is handled, but this seems to work.
196 # how trailing whitespace is handled, but this seems to work.
197 python_ori = python # save original in case we bail on error
197 python_ori = python # save original in case we bail on error
198 python = python.strip()
198 python = python.strip()
199
199
200 # The compiler module does not like unicode. We need to convert
200 # The compiler module does not like unicode. We need to convert
201 # it encode it:
201 # it encode it:
202 if isinstance(python, unicode):
202 if isinstance(python, unicode):
203 # Use the utf-8-sig BOM so the compiler detects this a UTF-8
203 # Use the utf-8-sig BOM so the compiler detects this a UTF-8
204 # encode string.
204 # encode string.
205 python = '\xef\xbb\xbf' + python.encode('utf-8')
205 python = '\xef\xbb\xbf' + python.encode('utf-8')
206
206
207 # The compiler module will parse the code into an abstract syntax tree.
207 # The compiler module will parse the code into an abstract syntax tree.
208 # This has a bug with str("a\nb"), but not str("""a\nb""")!!!
208 # This has a bug with str("a\nb"), but not str("""a\nb""")!!!
209 try:
209 try:
210 ast = compiler.parse(python)
210 ast = compiler.parse(python)
211 except:
211 except:
212 return [python_ori]
212 return [python_ori]
213
213
214 # Uncomment to help debug the ast tree
214 # Uncomment to help debug the ast tree
215 # for n in ast.node:
215 # for n in ast.node:
216 # print n.lineno,'->',n
216 # print n.lineno,'->',n
217
217
218 # Each separate command is available by iterating over ast.node. The
218 # Each separate command is available by iterating over ast.node. The
219 # lineno attribute is the line number (1-indexed) beginning the commands
219 # lineno attribute is the line number (1-indexed) beginning the commands
220 # suite.
220 # suite.
221 # lines ending with ";" yield a Discard Node that doesn't have a lineno
221 # lines ending with ";" yield a Discard Node that doesn't have a lineno
222 # attribute. These nodes can and should be discarded. But there are
222 # attribute. These nodes can and should be discarded. But there are
223 # other situations that cause Discard nodes that shouldn't be discarded.
223 # other situations that cause Discard nodes that shouldn't be discarded.
224 # We might eventually discover other cases where lineno is None and have
224 # We might eventually discover other cases where lineno is None and have
225 # to put in a more sophisticated test.
225 # to put in a more sophisticated test.
226 linenos = [x.lineno-1 for x in ast.node if x.lineno is not None]
226 linenos = [x.lineno-1 for x in ast.node if x.lineno is not None]
227
227
228 # When we finally get the slices, we will need to slice all the way to
228 # When we finally get the slices, we will need to slice all the way to
229 # the end even though we don't have a line number for it. Fortunately,
229 # the end even though we don't have a line number for it. Fortunately,
230 # None does the job nicely.
230 # None does the job nicely.
231 linenos.append(None)
231 linenos.append(None)
232
232
233 # Same problem at the other end: sometimes the ast tree has its
233 # Same problem at the other end: sometimes the ast tree has its
234 # first complete statement not starting on line 0. In this case
234 # first complete statement not starting on line 0. In this case
235 # we might miss part of it. This fixes ticket 266993. Thanks Gael!
235 # we might miss part of it. This fixes ticket 266993. Thanks Gael!
236 linenos[0] = 0
236 linenos[0] = 0
237
237
238 lines = python.splitlines()
238 lines = python.splitlines()
239
239
240 # Create a list of atomic commands.
240 # Create a list of atomic commands.
241 cmds = []
241 cmds = []
242 for i, j in zip(linenos[:-1], linenos[1:]):
242 for i, j in zip(linenos[:-1], linenos[1:]):
243 cmd = lines[i:j]
243 cmd = lines[i:j]
244 if cmd:
244 if cmd:
245 cmds.append('\n'.join(cmd)+'\n')
245 cmds.append('\n'.join(cmd)+'\n')
246
246
247 return cmds
247 return cmds
248
248
249
249
250 class InputSplitter(object):
250 class InputSplitter(object):
251 """An object that can split Python source input in executable blocks.
251 """An object that can split Python source input in executable blocks.
252
252
253 This object is designed to be used in one of two basic modes:
253 This object is designed to be used in one of two basic modes:
254
254
255 1. By feeding it python source line-by-line, using :meth:`push`. In this
255 1. By feeding it python source line-by-line, using :meth:`push`. In this
256 mode, it will return on each push whether the currently pushed code
256 mode, it will return on each push whether the currently pushed code
257 could be executed already. In addition, it provides a method called
257 could be executed already. In addition, it provides a method called
258 :meth:`push_accepts_more` that can be used to query whether more input
258 :meth:`push_accepts_more` that can be used to query whether more input
259 can be pushed into a single interactive block.
259 can be pushed into a single interactive block.
260
260
261 2. By calling :meth:`split_blocks` with a single, multiline Python string,
261 2. By calling :meth:`split_blocks` with a single, multiline Python string,
262 that is then split into blocks each of which can be executed
262 that is then split into blocks each of which can be executed
263 interactively as a single statement.
263 interactively as a single statement.
264
264
265 This is a simple example of how an interactive terminal-based client can use
265 This is a simple example of how an interactive terminal-based client can use
266 this tool::
266 this tool::
267
267
268 isp = InputSplitter()
268 isp = InputSplitter()
269 while isp.push_accepts_more():
269 while isp.push_accepts_more():
270 indent = ' '*isp.indent_spaces
270 indent = ' '*isp.indent_spaces
271 prompt = '>>> ' + indent
271 prompt = '>>> ' + indent
272 line = indent + raw_input(prompt)
272 line = indent + raw_input(prompt)
273 isp.push(line)
273 isp.push(line)
274 print 'Input source was:\n', isp.source_reset(),
274 print 'Input source was:\n', isp.source_reset(),
275 """
275 """
276 # Number of spaces of indentation computed from input that has been pushed
276 # Number of spaces of indentation computed from input that has been pushed
277 # so far. This is the attributes callers should query to get the current
277 # so far. This is the attributes callers should query to get the current
278 # indentation level, in order to provide auto-indent facilities.
278 # indentation level, in order to provide auto-indent facilities.
279 indent_spaces = 0
279 indent_spaces = 0
280 # String, indicating the default input encoding. It is computed by default
280 # String, indicating the default input encoding. It is computed by default
281 # at initialization time via get_input_encoding(), but it can be reset by a
281 # at initialization time via get_input_encoding(), but it can be reset by a
282 # client with specific knowledge of the encoding.
282 # client with specific knowledge of the encoding.
283 encoding = ''
283 encoding = ''
284 # String where the current full source input is stored, properly encoded.
284 # String where the current full source input is stored, properly encoded.
285 # Reading this attribute is the normal way of querying the currently pushed
285 # Reading this attribute is the normal way of querying the currently pushed
286 # source code, that has been properly encoded.
286 # source code, that has been properly encoded.
287 source = ''
287 source = ''
288 # Code object corresponding to the current source. It is automatically
288 # Code object corresponding to the current source. It is automatically
289 # synced to the source, so it can be queried at any time to obtain the code
289 # synced to the source, so it can be queried at any time to obtain the code
290 # object; it will be None if the source doesn't compile to valid Python.
290 # object; it will be None if the source doesn't compile to valid Python.
291 code = None
291 code = None
292 # Input mode
292 # Input mode
293 input_mode = 'line'
293 input_mode = 'line'
294
294
295 # Private attributes
295 # Private attributes
296
296
297 # List with lines of input accumulated so far
297 # List with lines of input accumulated so far
298 _buffer = None
298 _buffer = None
299 # Command compiler
299 # Command compiler
300 _compile = None
300 _compile = None
301 # Mark when input has changed indentation all the way back to flush-left
301 # Mark when input has changed indentation all the way back to flush-left
302 _full_dedent = False
302 _full_dedent = False
303 # Boolean indicating whether the current block is complete
303 # Boolean indicating whether the current block is complete
304 _is_complete = None
304 _is_complete = None
305
305
306 def __init__(self, input_mode=None):
306 def __init__(self, input_mode=None):
307 """Create a new InputSplitter instance.
307 """Create a new InputSplitter instance.
308
308
309 Parameters
309 Parameters
310 ----------
310 ----------
311 input_mode : str
311 input_mode : str
312
312
313 One of ['line', 'cell']; default is 'line'.
313 One of ['line', 'cell']; default is 'line'.
314
314
315 The input_mode parameter controls how new inputs are used when fed via
315 The input_mode parameter controls how new inputs are used when fed via
316 the :meth:`push` method:
316 the :meth:`push` method:
317
317
318 - 'line': meant for line-oriented clients, inputs are appended one at a
318 - 'line': meant for line-oriented clients, inputs are appended one at a
319 time to the internal buffer and the whole buffer is compiled.
319 time to the internal buffer and the whole buffer is compiled.
320
320
321 - 'cell': meant for clients that can edit multi-line 'cells' of text at
321 - 'cell': meant for clients that can edit multi-line 'cells' of text at
322 a time. A cell can contain one or more blocks that can be compile in
322 a time. A cell can contain one or more blocks that can be compile in
323 'single' mode by Python. In this mode, each new input new input
323 'single' mode by Python. In this mode, each new input new input
324 completely replaces all prior inputs. Cell mode is thus equivalent
324 completely replaces all prior inputs. Cell mode is thus equivalent
325 to prepending a full reset() to every push() call.
325 to prepending a full reset() to every push() call.
326 """
326 """
327 self._buffer = []
327 self._buffer = []
328 self._compile = codeop.CommandCompiler()
328 self._compile = codeop.CommandCompiler()
329 self.encoding = get_input_encoding()
329 self.encoding = get_input_encoding()
330 self.input_mode = InputSplitter.input_mode if input_mode is None \
330 self.input_mode = InputSplitter.input_mode if input_mode is None \
331 else input_mode
331 else input_mode
332
332
333 def reset(self):
333 def reset(self):
334 """Reset the input buffer and associated state."""
334 """Reset the input buffer and associated state."""
335 self.indent_spaces = 0
335 self.indent_spaces = 0
336 self._buffer[:] = []
336 self._buffer[:] = []
337 self.source = ''
337 self.source = ''
338 self.code = None
338 self.code = None
339 self._is_complete = False
339 self._is_complete = False
340 self._full_dedent = False
340 self._full_dedent = False
341
341
342 def source_reset(self):
342 def source_reset(self):
343 """Return the input source and perform a full reset.
343 """Return the input source and perform a full reset.
344 """
344 """
345 out = self.source
345 out = self.source
346 self.reset()
346 self.reset()
347 return out
347 return out
348
348
349 def push(self, lines):
349 def push(self, lines):
350 """Push one ore more lines of input.
350 """Push one ore more lines of input.
351
351
352 This stores the given lines and returns a status code indicating
352 This stores the given lines and returns a status code indicating
353 whether the code forms a complete Python block or not.
353 whether the code forms a complete Python block or not.
354
354
355 Any exceptions generated in compilation are swallowed, but if an
355 Any exceptions generated in compilation are swallowed, but if an
356 exception was produced, the method returns True.
356 exception was produced, the method returns True.
357
357
358 Parameters
358 Parameters
359 ----------
359 ----------
360 lines : string
360 lines : string
361 One or more lines of Python input.
361 One or more lines of Python input.
362
362
363 Returns
363 Returns
364 -------
364 -------
365 is_complete : boolean
365 is_complete : boolean
366 True if the current input source (the result of the current input
366 True if the current input source (the result of the current input
367 plus prior inputs) forms a complete Python execution block. Note that
367 plus prior inputs) forms a complete Python execution block. Note that
368 this value is also stored as a private attribute (_is_complete), so it
368 this value is also stored as a private attribute (_is_complete), so it
369 can be queried at any time.
369 can be queried at any time.
370 """
370 """
371 if self.input_mode == 'cell':
371 if self.input_mode == 'cell':
372 self.reset()
372 self.reset()
373
373
374 # If the source code has leading blanks, add 'if 1:\n' to it
375 # this allows execution of indented pasted code. It is tempting
376 # to add '\n' at the end of source to run commands like ' a=1'
377 # directly, but this fails for more complicated scenarios
378
379 if not self._buffer and lines[:1] in [' ', '\t'] and \
380 not comment_line_re.match(lines):
381 lines = 'if 1:\n%s' % lines
382
383 self._store(lines)
374 self._store(lines)
384 source = self.source
375 source = self.source
385
376
386 # Before calling _compile(), reset the code object to None so that if an
377 # Before calling _compile(), reset the code object to None so that if an
387 # exception is raised in compilation, we don't mislead by having
378 # exception is raised in compilation, we don't mislead by having
388 # inconsistent code/source attributes.
379 # inconsistent code/source attributes.
389 self.code, self._is_complete = None, None
380 self.code, self._is_complete = None, None
390
381
391 # Honor termination lines properly
382 # Honor termination lines properly
392 if source.rstrip().endswith('\\'):
383 if source.rstrip().endswith('\\'):
393 return False
384 return False
394
385
395 self._update_indent(lines)
386 self._update_indent(lines)
396 try:
387 try:
397 self.code = self._compile(source)
388 self.code = self._compile(source)
398 # Invalid syntax can produce any of a number of different errors from
389 # Invalid syntax can produce any of a number of different errors from
399 # inside the compiler, so we have to catch them all. Syntax errors
390 # inside the compiler, so we have to catch them all. Syntax errors
400 # immediately produce a 'ready' block, so the invalid Python can be
391 # immediately produce a 'ready' block, so the invalid Python can be
401 # sent to the kernel for evaluation with possible ipython
392 # sent to the kernel for evaluation with possible ipython
402 # special-syntax conversion.
393 # special-syntax conversion.
403 except (SyntaxError, OverflowError, ValueError, TypeError,
394 except (SyntaxError, OverflowError, ValueError, TypeError,
404 MemoryError):
395 MemoryError):
405 self._is_complete = True
396 self._is_complete = True
406 else:
397 else:
407 # Compilation didn't produce any exceptions (though it may not have
398 # Compilation didn't produce any exceptions (though it may not have
408 # given a complete code object)
399 # given a complete code object)
409 self._is_complete = self.code is not None
400 self._is_complete = self.code is not None
410
401
411 return self._is_complete
402 return self._is_complete
412
403
413 def push_accepts_more(self):
404 def push_accepts_more(self):
414 """Return whether a block of interactive input can accept more input.
405 """Return whether a block of interactive input can accept more input.
415
406
416 This method is meant to be used by line-oriented frontends, who need to
407 This method is meant to be used by line-oriented frontends, who need to
417 guess whether a block is complete or not based solely on prior and
408 guess whether a block is complete or not based solely on prior and
418 current input lines. The InputSplitter considers it has a complete
409 current input lines. The InputSplitter considers it has a complete
419 interactive block and will not accept more input only when either a
410 interactive block and will not accept more input only when either a
420 SyntaxError is raised, or *all* of the following are true:
411 SyntaxError is raised, or *all* of the following are true:
421
412
422 1. The input compiles to a complete statement.
413 1. The input compiles to a complete statement.
423
414
424 2. The indentation level is flush-left (because if we are indented,
415 2. The indentation level is flush-left (because if we are indented,
425 like inside a function definition or for loop, we need to keep
416 like inside a function definition or for loop, we need to keep
426 reading new input).
417 reading new input).
427
418
428 3. There is one extra line consisting only of whitespace.
419 3. There is one extra line consisting only of whitespace.
429
420
430 Because of condition #3, this method should be used only by
421 Because of condition #3, this method should be used only by
431 *line-oriented* frontends, since it means that intermediate blank lines
422 *line-oriented* frontends, since it means that intermediate blank lines
432 are not allowed in function definitions (or any other indented block).
423 are not allowed in function definitions (or any other indented block).
433
424
434 Block-oriented frontends that have a separate keyboard event to
425 Block-oriented frontends that have a separate keyboard event to
435 indicate execution should use the :meth:`split_blocks` method instead.
426 indicate execution should use the :meth:`split_blocks` method instead.
436
427
437 If the current input produces a syntax error, this method immediately
428 If the current input produces a syntax error, this method immediately
438 returns False but does *not* raise the syntax error exception, as
429 returns False but does *not* raise the syntax error exception, as
439 typically clients will want to send invalid syntax to an execution
430 typically clients will want to send invalid syntax to an execution
440 backend which might convert the invalid syntax into valid Python via
431 backend which might convert the invalid syntax into valid Python via
441 one of the dynamic IPython mechanisms.
432 one of the dynamic IPython mechanisms.
442 """
433 """
443
434
444 # With incomplete input, unconditionally accept more
435 # With incomplete input, unconditionally accept more
445 if not self._is_complete:
436 if not self._is_complete:
446 return True
437 return True
447
438
448 # If we already have complete input and we're flush left, the answer
439 # If we already have complete input and we're flush left, the answer
449 # depends. In line mode, we're done. But in cell mode, we need to
440 # depends. In line mode, we're done. But in cell mode, we need to
450 # check how many blocks the input so far compiles into, because if
441 # check how many blocks the input so far compiles into, because if
451 # there's already more than one full independent block of input, then
442 # there's already more than one full independent block of input, then
452 # the client has entered full 'cell' mode and is feeding lines that
443 # the client has entered full 'cell' mode and is feeding lines that
453 # each is complete. In this case we should then keep accepting.
444 # each is complete. In this case we should then keep accepting.
454 # The Qt terminal-like console does precisely this, to provide the
445 # The Qt terminal-like console does precisely this, to provide the
455 # convenience of terminal-like input of single expressions, but
446 # convenience of terminal-like input of single expressions, but
456 # allowing the user (with a separate keystroke) to switch to 'cell'
447 # allowing the user (with a separate keystroke) to switch to 'cell'
457 # mode and type multiple expressions in one shot.
448 # mode and type multiple expressions in one shot.
458 if self.indent_spaces==0:
449 if self.indent_spaces==0:
459 if self.input_mode=='line':
450 if self.input_mode=='line':
460 return False
451 return False
461 else:
452 else:
462 nblocks = len(split_blocks(''.join(self._buffer)))
453 nblocks = len(split_blocks(''.join(self._buffer)))
463 if nblocks==1:
454 if nblocks==1:
464 return False
455 return False
465
456
466 # When input is complete, then termination is marked by an extra blank
457 # When input is complete, then termination is marked by an extra blank
467 # line at the end.
458 # line at the end.
468 last_line = self.source.splitlines()[-1]
459 last_line = self.source.splitlines()[-1]
469 return bool(last_line and not last_line.isspace())
460 return bool(last_line and not last_line.isspace())
470
461
471 def split_blocks(self, lines):
462 def split_blocks(self, lines):
472 """Split a multiline string into multiple input blocks.
463 """Split a multiline string into multiple input blocks.
473
464
474 Note: this method starts by performing a full reset().
465 Note: this method starts by performing a full reset().
475
466
476 Parameters
467 Parameters
477 ----------
468 ----------
478 lines : str
469 lines : str
479 A possibly multiline string.
470 A possibly multiline string.
480
471
481 Returns
472 Returns
482 -------
473 -------
483 blocks : list
474 blocks : list
484 A list of strings, each possibly multiline. Each string corresponds
475 A list of strings, each possibly multiline. Each string corresponds
485 to a single block that can be compiled in 'single' mode (unless it
476 to a single block that can be compiled in 'single' mode (unless it
486 has a syntax error)."""
477 has a syntax error)."""
487
478
488 # This code is fairly delicate. If you make any changes here, make
479 # This code is fairly delicate. If you make any changes here, make
489 # absolutely sure that you do run the full test suite and ALL tests
480 # absolutely sure that you do run the full test suite and ALL tests
490 # pass.
481 # pass.
491
482
492 self.reset()
483 self.reset()
493 blocks = []
484 blocks = []
494
485
495 # Reversed copy so we can use pop() efficiently and consume the input
486 # Reversed copy so we can use pop() efficiently and consume the input
496 # as a stack
487 # as a stack
497 lines = lines.splitlines()[::-1]
488 lines = lines.splitlines()[::-1]
498 # Outer loop over all input
489 # Outer loop over all input
499 while lines:
490 while lines:
500 #print 'Current lines:', lines # dbg
491 #print 'Current lines:', lines # dbg
501 # Inner loop to build each block
492 # Inner loop to build each block
502 while True:
493 while True:
503 # Safety exit from inner loop
494 # Safety exit from inner loop
504 if not lines:
495 if not lines:
505 break
496 break
506 # Grab next line but don't push it yet
497 # Grab next line but don't push it yet
507 next_line = lines.pop()
498 next_line = lines.pop()
508 # Blank/empty lines are pushed as-is
499 # Blank/empty lines are pushed as-is
509 if not next_line or next_line.isspace():
500 if not next_line or next_line.isspace():
510 self.push(next_line)
501 self.push(next_line)
511 continue
502 continue
512
503
513 # Check indentation changes caused by the *next* line
504 # Check indentation changes caused by the *next* line
514 indent_spaces, _full_dedent = self._find_indent(next_line)
505 indent_spaces, _full_dedent = self._find_indent(next_line)
515
506
516 # If the next line causes a dedent, it can be for two differnt
507 # If the next line causes a dedent, it can be for two differnt
517 # reasons: either an explicit de-dent by the user or a
508 # reasons: either an explicit de-dent by the user or a
518 # return/raise/pass statement. These MUST be handled
509 # return/raise/pass statement. These MUST be handled
519 # separately:
510 # separately:
520 #
511 #
521 # 1. the first case is only detected when the actual explicit
512 # 1. the first case is only detected when the actual explicit
522 # dedent happens, and that would be the *first* line of a *new*
513 # dedent happens, and that would be the *first* line of a *new*
523 # block. Thus, we must put the line back into the input buffer
514 # block. Thus, we must put the line back into the input buffer
524 # so that it starts a new block on the next pass.
515 # so that it starts a new block on the next pass.
525 #
516 #
526 # 2. the second case is detected in the line before the actual
517 # 2. the second case is detected in the line before the actual
527 # dedent happens, so , we consume the line and we can break out
518 # dedent happens, so , we consume the line and we can break out
528 # to start a new block.
519 # to start a new block.
529
520
530 # Case 1, explicit dedent causes a break.
521 # Case 1, explicit dedent causes a break.
531 # Note: check that we weren't on the very last line, else we'll
522 # Note: check that we weren't on the very last line, else we'll
532 # enter an infinite loop adding/removing the last line.
523 # enter an infinite loop adding/removing the last line.
533 if _full_dedent and lines and not next_line.startswith(' '):
524 if _full_dedent and lines and not next_line.startswith(' '):
534 lines.append(next_line)
525 lines.append(next_line)
535 break
526 break
536
527
537 # Otherwise any line is pushed
528 # Otherwise any line is pushed
538 self.push(next_line)
529 self.push(next_line)
539
530
540 # Case 2, full dedent with full block ready:
531 # Case 2, full dedent with full block ready:
541 if _full_dedent or \
532 if _full_dedent or \
542 self.indent_spaces==0 and not self.push_accepts_more():
533 self.indent_spaces==0 and not self.push_accepts_more():
543 break
534 break
544 # Form the new block with the current source input
535 # Form the new block with the current source input
545 blocks.append(self.source_reset())
536 blocks.append(self.source_reset())
546
537
547 #return blocks
538 #return blocks
548 # HACK!!! Now that our input is in blocks but guaranteed to be pure
539 # HACK!!! Now that our input is in blocks but guaranteed to be pure
549 # python syntax, feed it back a second time through the AST-based
540 # python syntax, feed it back a second time through the AST-based
550 # splitter, which is more accurate than ours.
541 # splitter, which is more accurate than ours.
551 return split_blocks(''.join(blocks))
542 return split_blocks(''.join(blocks))
552
543
553 #------------------------------------------------------------------------
544 #------------------------------------------------------------------------
554 # Private interface
545 # Private interface
555 #------------------------------------------------------------------------
546 #------------------------------------------------------------------------
556
547
557 def _find_indent(self, line):
548 def _find_indent(self, line):
558 """Compute the new indentation level for a single line.
549 """Compute the new indentation level for a single line.
559
550
560 Parameters
551 Parameters
561 ----------
552 ----------
562 line : str
553 line : str
563 A single new line of non-whitespace, non-comment Python input.
554 A single new line of non-whitespace, non-comment Python input.
564
555
565 Returns
556 Returns
566 -------
557 -------
567 indent_spaces : int
558 indent_spaces : int
568 New value for the indent level (it may be equal to self.indent_spaces
559 New value for the indent level (it may be equal to self.indent_spaces
569 if indentation doesn't change.
560 if indentation doesn't change.
570
561
571 full_dedent : boolean
562 full_dedent : boolean
572 Whether the new line causes a full flush-left dedent.
563 Whether the new line causes a full flush-left dedent.
573 """
564 """
574 indent_spaces = self.indent_spaces
565 indent_spaces = self.indent_spaces
575 full_dedent = self._full_dedent
566 full_dedent = self._full_dedent
576
567
577 inisp = num_ini_spaces(line)
568 inisp = num_ini_spaces(line)
578 if inisp < indent_spaces:
569 if inisp < indent_spaces:
579 indent_spaces = inisp
570 indent_spaces = inisp
580 if indent_spaces <= 0:
571 if indent_spaces <= 0:
581 #print 'Full dedent in text',self.source # dbg
572 #print 'Full dedent in text',self.source # dbg
582 full_dedent = True
573 full_dedent = True
583
574
584 if line[-1] == ':':
575 if line[-1] == ':':
585 indent_spaces += 4
576 indent_spaces += 4
586 elif dedent_re.match(line):
577 elif dedent_re.match(line):
587 indent_spaces -= 4
578 indent_spaces -= 4
588 if indent_spaces <= 0:
579 if indent_spaces <= 0:
589 full_dedent = True
580 full_dedent = True
590
581
591 # Safety
582 # Safety
592 if indent_spaces < 0:
583 if indent_spaces < 0:
593 indent_spaces = 0
584 indent_spaces = 0
594 #print 'safety' # dbg
585 #print 'safety' # dbg
595
586
596 return indent_spaces, full_dedent
587 return indent_spaces, full_dedent
597
588
598 def _update_indent(self, lines):
589 def _update_indent(self, lines):
599 for line in remove_comments(lines).splitlines():
590 for line in remove_comments(lines).splitlines():
600 if line and not line.isspace():
591 if line and not line.isspace():
601 self.indent_spaces, self._full_dedent = self._find_indent(line)
592 self.indent_spaces, self._full_dedent = self._find_indent(line)
602
593
603 def _store(self, lines, buffer=None, store='source'):
594 def _store(self, lines, buffer=None, store='source'):
604 """Store one or more lines of input.
595 """Store one or more lines of input.
605
596
606 If input lines are not newline-terminated, a newline is automatically
597 If input lines are not newline-terminated, a newline is automatically
607 appended."""
598 appended."""
608
599
609 if buffer is None:
600 if buffer is None:
610 buffer = self._buffer
601 buffer = self._buffer
611
602
612 if lines.endswith('\n'):
603 if lines.endswith('\n'):
613 buffer.append(lines)
604 buffer.append(lines)
614 else:
605 else:
615 buffer.append(lines+'\n')
606 buffer.append(lines+'\n')
616 setattr(self, store, self._set_source(buffer))
607 setattr(self, store, self._set_source(buffer))
617
608
618 def _set_source(self, buffer):
609 def _set_source(self, buffer):
619 return ''.join(buffer).encode(self.encoding)
610 return ''.join(buffer).encode(self.encoding)
620
611
621
612
622 #-----------------------------------------------------------------------------
613 #-----------------------------------------------------------------------------
623 # Functions and classes for IPython-specific syntactic support
614 # Functions and classes for IPython-specific syntactic support
624 #-----------------------------------------------------------------------------
615 #-----------------------------------------------------------------------------
625
616
626 # RegExp for splitting line contents into pre-char//first word-method//rest.
617 # RegExp for splitting line contents into pre-char//first word-method//rest.
627 # For clarity, each group in on one line.
618 # For clarity, each group in on one line.
628
619
629 line_split = re.compile("""
620 line_split = re.compile("""
630 ^(\s*) # any leading space
621 ^(\s*) # any leading space
631 ([,;/%]|!!?|\?\??) # escape character or characters
622 ([,;/%]|!!?|\?\??) # escape character or characters
632 \s*(%?[\w\.\*]*) # function/method, possibly with leading %
623 \s*(%?[\w\.\*]*) # function/method, possibly with leading %
633 # to correctly treat things like '?%magic'
624 # to correctly treat things like '?%magic'
634 (\s+.*$|$) # rest of line
625 (\s+.*$|$) # rest of line
635 """, re.VERBOSE)
626 """, re.VERBOSE)
636
627
637
628
638 def split_user_input(line):
629 def split_user_input(line):
639 """Split user input into early whitespace, esc-char, function part and rest.
630 """Split user input into early whitespace, esc-char, function part and rest.
640
631
641 This is currently handles lines with '=' in them in a very inconsistent
632 This is currently handles lines with '=' in them in a very inconsistent
642 manner.
633 manner.
643
634
644 Examples
635 Examples
645 ========
636 ========
646 >>> split_user_input('x=1')
637 >>> split_user_input('x=1')
647 ('', '', 'x=1', '')
638 ('', '', 'x=1', '')
648 >>> split_user_input('?')
639 >>> split_user_input('?')
649 ('', '?', '', '')
640 ('', '?', '', '')
650 >>> split_user_input('??')
641 >>> split_user_input('??')
651 ('', '??', '', '')
642 ('', '??', '', '')
652 >>> split_user_input(' ?')
643 >>> split_user_input(' ?')
653 (' ', '?', '', '')
644 (' ', '?', '', '')
654 >>> split_user_input(' ??')
645 >>> split_user_input(' ??')
655 (' ', '??', '', '')
646 (' ', '??', '', '')
656 >>> split_user_input('??x')
647 >>> split_user_input('??x')
657 ('', '??', 'x', '')
648 ('', '??', 'x', '')
658 >>> split_user_input('?x=1')
649 >>> split_user_input('?x=1')
659 ('', '', '?x=1', '')
650 ('', '', '?x=1', '')
660 >>> split_user_input('!ls')
651 >>> split_user_input('!ls')
661 ('', '!', 'ls', '')
652 ('', '!', 'ls', '')
662 >>> split_user_input(' !ls')
653 >>> split_user_input(' !ls')
663 (' ', '!', 'ls', '')
654 (' ', '!', 'ls', '')
664 >>> split_user_input('!!ls')
655 >>> split_user_input('!!ls')
665 ('', '!!', 'ls', '')
656 ('', '!!', 'ls', '')
666 >>> split_user_input(' !!ls')
657 >>> split_user_input(' !!ls')
667 (' ', '!!', 'ls', '')
658 (' ', '!!', 'ls', '')
668 >>> split_user_input(',ls')
659 >>> split_user_input(',ls')
669 ('', ',', 'ls', '')
660 ('', ',', 'ls', '')
670 >>> split_user_input(';ls')
661 >>> split_user_input(';ls')
671 ('', ';', 'ls', '')
662 ('', ';', 'ls', '')
672 >>> split_user_input(' ;ls')
663 >>> split_user_input(' ;ls')
673 (' ', ';', 'ls', '')
664 (' ', ';', 'ls', '')
674 >>> split_user_input('f.g(x)')
665 >>> split_user_input('f.g(x)')
675 ('', '', 'f.g(x)', '')
666 ('', '', 'f.g(x)', '')
676 >>> split_user_input('f.g (x)')
667 >>> split_user_input('f.g (x)')
677 ('', '', 'f.g', '(x)')
668 ('', '', 'f.g', '(x)')
678 >>> split_user_input('?%hist')
669 >>> split_user_input('?%hist')
679 ('', '?', '%hist', '')
670 ('', '?', '%hist', '')
680 >>> split_user_input('?x*')
671 >>> split_user_input('?x*')
681 ('', '?', 'x*', '')
672 ('', '?', 'x*', '')
682 """
673 """
683 match = line_split.match(line)
674 match = line_split.match(line)
684 if match:
675 if match:
685 lspace, esc, fpart, rest = match.groups()
676 lspace, esc, fpart, rest = match.groups()
686 else:
677 else:
687 # print "match failed for line '%s'" % line
678 # print "match failed for line '%s'" % line
688 try:
679 try:
689 fpart, rest = line.split(None, 1)
680 fpart, rest = line.split(None, 1)
690 except ValueError:
681 except ValueError:
691 # print "split failed for line '%s'" % line
682 # print "split failed for line '%s'" % line
692 fpart, rest = line,''
683 fpart, rest = line,''
693 lspace = re.match('^(\s*)(.*)', line).groups()[0]
684 lspace = re.match('^(\s*)(.*)', line).groups()[0]
694 esc = ''
685 esc = ''
695
686
696 # fpart has to be a valid python identifier, so it better be only pure
687 # fpart has to be a valid python identifier, so it better be only pure
697 # ascii, no unicode:
688 # ascii, no unicode:
698 try:
689 try:
699 fpart = fpart.encode('ascii')
690 fpart = fpart.encode('ascii')
700 except UnicodeEncodeError:
691 except UnicodeEncodeError:
701 lspace = unicode(lspace)
692 lspace = unicode(lspace)
702 rest = fpart + u' ' + rest
693 rest = fpart + u' ' + rest
703 fpart = u''
694 fpart = u''
704
695
705 #print 'line:<%s>' % line # dbg
696 #print 'line:<%s>' % line # dbg
706 #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg
697 #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg
707 return lspace, esc, fpart.strip(), rest.lstrip()
698 return lspace, esc, fpart.strip(), rest.lstrip()
708
699
709
700
710 # The escaped translators ALL receive a line where their own escape has been
701 # The escaped translators ALL receive a line where their own escape has been
711 # stripped. Only '?' is valid at the end of the line, all others can only be
702 # stripped. Only '?' is valid at the end of the line, all others can only be
712 # placed at the start.
703 # placed at the start.
713
704
714 class LineInfo(object):
705 class LineInfo(object):
715 """A single line of input and associated info.
706 """A single line of input and associated info.
716
707
717 This is a utility class that mostly wraps the output of
708 This is a utility class that mostly wraps the output of
718 :func:`split_user_input` into a convenient object to be passed around
709 :func:`split_user_input` into a convenient object to be passed around
719 during input transformations.
710 during input transformations.
720
711
721 Includes the following as properties:
712 Includes the following as properties:
722
713
723 line
714 line
724 The original, raw line
715 The original, raw line
725
716
726 lspace
717 lspace
727 Any early whitespace before actual text starts.
718 Any early whitespace before actual text starts.
728
719
729 esc
720 esc
730 The initial esc character (or characters, for double-char escapes like
721 The initial esc character (or characters, for double-char escapes like
731 '??' or '!!').
722 '??' or '!!').
732
723
733 fpart
724 fpart
734 The 'function part', which is basically the maximal initial sequence
725 The 'function part', which is basically the maximal initial sequence
735 of valid python identifiers and the '.' character. This is what is
726 of valid python identifiers and the '.' character. This is what is
736 checked for alias and magic transformations, used for auto-calling,
727 checked for alias and magic transformations, used for auto-calling,
737 etc.
728 etc.
738
729
739 rest
730 rest
740 Everything else on the line.
731 Everything else on the line.
741 """
732 """
742 def __init__(self, line):
733 def __init__(self, line):
743 self.line = line
734 self.line = line
744 self.lspace, self.esc, self.fpart, self.rest = \
735 self.lspace, self.esc, self.fpart, self.rest = \
745 split_user_input(line)
736 split_user_input(line)
746
737
747 def __str__(self):
738 def __str__(self):
748 return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc,
739 return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc,
749 self.fpart, self.rest)
740 self.fpart, self.rest)
750
741
751
742
752 # Transformations of the special syntaxes that don't rely on an explicit escape
743 # Transformations of the special syntaxes that don't rely on an explicit escape
753 # character but instead on patterns on the input line
744 # character but instead on patterns on the input line
754
745
755 # The core transformations are implemented as standalone functions that can be
746 # The core transformations are implemented as standalone functions that can be
756 # tested and validated in isolation. Each of these uses a regexp, we
747 # tested and validated in isolation. Each of these uses a regexp, we
757 # pre-compile these and keep them close to each function definition for clarity
748 # pre-compile these and keep them close to each function definition for clarity
758
749
759 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
750 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
760 r'\s*=\s*!\s*(?P<cmd>.*)')
751 r'\s*=\s*!\s*(?P<cmd>.*)')
761
752
762 def transform_assign_system(line):
753 def transform_assign_system(line):
763 """Handle the `files = !ls` syntax."""
754 """Handle the `files = !ls` syntax."""
764 m = _assign_system_re.match(line)
755 m = _assign_system_re.match(line)
765 if m is not None:
756 if m is not None:
766 cmd = m.group('cmd')
757 cmd = m.group('cmd')
767 lhs = m.group('lhs')
758 lhs = m.group('lhs')
768 expr = make_quoted_expr(cmd)
759 expr = make_quoted_expr(cmd)
769 new_line = '%s = get_ipython().getoutput(%s)' % (lhs, expr)
760 new_line = '%s = get_ipython().getoutput(%s)' % (lhs, expr)
770 return new_line
761 return new_line
771 return line
762 return line
772
763
773
764
774 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
765 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
775 r'\s*=\s*%\s*(?P<cmd>.*)')
766 r'\s*=\s*%\s*(?P<cmd>.*)')
776
767
777 def transform_assign_magic(line):
768 def transform_assign_magic(line):
778 """Handle the `a = %who` syntax."""
769 """Handle the `a = %who` syntax."""
779 m = _assign_magic_re.match(line)
770 m = _assign_magic_re.match(line)
780 if m is not None:
771 if m is not None:
781 cmd = m.group('cmd')
772 cmd = m.group('cmd')
782 lhs = m.group('lhs')
773 lhs = m.group('lhs')
783 expr = make_quoted_expr(cmd)
774 expr = make_quoted_expr(cmd)
784 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
775 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
785 return new_line
776 return new_line
786 return line
777 return line
787
778
788
779
789 _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')
780 _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')
790
781
791 def transform_classic_prompt(line):
782 def transform_classic_prompt(line):
792 """Handle inputs that start with '>>> ' syntax."""
783 """Handle inputs that start with '>>> ' syntax."""
793
784
794 if not line or line.isspace():
785 if not line or line.isspace():
795 return line
786 return line
796 m = _classic_prompt_re.match(line)
787 m = _classic_prompt_re.match(line)
797 if m:
788 if m:
798 return line[len(m.group(0)):]
789 return line[len(m.group(0)):]
799 else:
790 else:
800 return line
791 return line
801
792
802
793
803 _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
794 _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
804
795
805 def transform_ipy_prompt(line):
796 def transform_ipy_prompt(line):
806 """Handle inputs that start classic IPython prompt syntax."""
797 """Handle inputs that start classic IPython prompt syntax."""
807
798
808 if not line or line.isspace():
799 if not line or line.isspace():
809 return line
800 return line
810 #print 'LINE: %r' % line # dbg
801 #print 'LINE: %r' % line # dbg
811 m = _ipy_prompt_re.match(line)
802 m = _ipy_prompt_re.match(line)
812 if m:
803 if m:
813 #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
804 #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
814 return line[len(m.group(0)):]
805 return line[len(m.group(0)):]
815 else:
806 else:
816 return line
807 return line
817
808
818
809
819 class EscapedTransformer(object):
810 class EscapedTransformer(object):
820 """Class to transform lines that are explicitly escaped out."""
811 """Class to transform lines that are explicitly escaped out."""
821
812
822 def __init__(self):
813 def __init__(self):
823 tr = { ESC_SHELL : self._tr_system,
814 tr = { ESC_SHELL : self._tr_system,
824 ESC_SH_CAP : self._tr_system2,
815 ESC_SH_CAP : self._tr_system2,
825 ESC_HELP : self._tr_help,
816 ESC_HELP : self._tr_help,
826 ESC_HELP2 : self._tr_help,
817 ESC_HELP2 : self._tr_help,
827 ESC_MAGIC : self._tr_magic,
818 ESC_MAGIC : self._tr_magic,
828 ESC_QUOTE : self._tr_quote,
819 ESC_QUOTE : self._tr_quote,
829 ESC_QUOTE2 : self._tr_quote2,
820 ESC_QUOTE2 : self._tr_quote2,
830 ESC_PAREN : self._tr_paren }
821 ESC_PAREN : self._tr_paren }
831 self.tr = tr
822 self.tr = tr
832
823
833 # Support for syntax transformations that use explicit escapes typed by the
824 # Support for syntax transformations that use explicit escapes typed by the
834 # user at the beginning of a line
825 # user at the beginning of a line
835 @staticmethod
826 @staticmethod
836 def _tr_system(line_info):
827 def _tr_system(line_info):
837 "Translate lines escaped with: !"
828 "Translate lines escaped with: !"
838 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
829 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
839 return '%sget_ipython().system(%s)' % (line_info.lspace,
830 return '%sget_ipython().system(%s)' % (line_info.lspace,
840 make_quoted_expr(cmd))
831 make_quoted_expr(cmd))
841
832
842 @staticmethod
833 @staticmethod
843 def _tr_system2(line_info):
834 def _tr_system2(line_info):
844 "Translate lines escaped with: !!"
835 "Translate lines escaped with: !!"
845 cmd = line_info.line.lstrip()[2:]
836 cmd = line_info.line.lstrip()[2:]
846 return '%sget_ipython().getoutput(%s)' % (line_info.lspace,
837 return '%sget_ipython().getoutput(%s)' % (line_info.lspace,
847 make_quoted_expr(cmd))
838 make_quoted_expr(cmd))
848
839
849 @staticmethod
840 @staticmethod
850 def _tr_help(line_info):
841 def _tr_help(line_info):
851 "Translate lines escaped with: ?/??"
842 "Translate lines escaped with: ?/??"
852 # A naked help line should just fire the intro help screen
843 # A naked help line should just fire the intro help screen
853 if not line_info.line[1:]:
844 if not line_info.line[1:]:
854 return 'get_ipython().show_usage()'
845 return 'get_ipython().show_usage()'
855
846
856 # There may be one or two '?' at the end, move them to the front so that
847 # There may be one or two '?' at the end, move them to the front so that
857 # the rest of the logic can assume escapes are at the start
848 # the rest of the logic can assume escapes are at the start
858 l_ori = line_info
849 l_ori = line_info
859 line = line_info.line
850 line = line_info.line
860 if line.endswith('?'):
851 if line.endswith('?'):
861 line = line[-1] + line[:-1]
852 line = line[-1] + line[:-1]
862 if line.endswith('?'):
853 if line.endswith('?'):
863 line = line[-1] + line[:-1]
854 line = line[-1] + line[:-1]
864 line_info = LineInfo(line)
855 line_info = LineInfo(line)
865
856
866 # From here on, simply choose which level of detail to get, and
857 # From here on, simply choose which level of detail to get, and
867 # special-case the psearch syntax
858 # special-case the psearch syntax
868 if '*' in line_info.line:
859 if '*' in line_info.line:
869 pinfo = 'psearch'
860 pinfo = 'psearch'
870 elif line_info.esc == '?':
861 elif line_info.esc == '?':
871 pinfo = 'pinfo'
862 pinfo = 'pinfo'
872 elif line_info.esc == '??':
863 elif line_info.esc == '??':
873 pinfo = 'pinfo2'
864 pinfo = 'pinfo2'
874
865
875 tpl = '%sget_ipython().magic("%s %s")'
866 tpl = '%sget_ipython().magic("%s %s")'
876 return tpl % (line_info.lspace, pinfo,
867 return tpl % (line_info.lspace, pinfo,
877 ' '.join([line_info.fpart, line_info.rest]).strip())
868 ' '.join([line_info.fpart, line_info.rest]).strip())
878
869
879 @staticmethod
870 @staticmethod
880 def _tr_magic(line_info):
871 def _tr_magic(line_info):
881 "Translate lines escaped with: %"
872 "Translate lines escaped with: %"
882 tpl = '%sget_ipython().magic(%s)'
873 tpl = '%sget_ipython().magic(%s)'
883 cmd = make_quoted_expr(' '.join([line_info.fpart,
874 cmd = make_quoted_expr(' '.join([line_info.fpart,
884 line_info.rest]).strip())
875 line_info.rest]).strip())
885 return tpl % (line_info.lspace, cmd)
876 return tpl % (line_info.lspace, cmd)
886
877
887 @staticmethod
878 @staticmethod
888 def _tr_quote(line_info):
879 def _tr_quote(line_info):
889 "Translate lines escaped with: ,"
880 "Translate lines escaped with: ,"
890 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
881 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
891 '", "'.join(line_info.rest.split()) )
882 '", "'.join(line_info.rest.split()) )
892
883
893 @staticmethod
884 @staticmethod
894 def _tr_quote2(line_info):
885 def _tr_quote2(line_info):
895 "Translate lines escaped with: ;"
886 "Translate lines escaped with: ;"
896 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
887 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
897 line_info.rest)
888 line_info.rest)
898
889
899 @staticmethod
890 @staticmethod
900 def _tr_paren(line_info):
891 def _tr_paren(line_info):
901 "Translate lines escaped with: /"
892 "Translate lines escaped with: /"
902 return '%s%s(%s)' % (line_info.lspace, line_info.fpart,
893 return '%s%s(%s)' % (line_info.lspace, line_info.fpart,
903 ", ".join(line_info.rest.split()))
894 ", ".join(line_info.rest.split()))
904
895
905 def __call__(self, line):
896 def __call__(self, line):
906 """Class to transform lines that are explicitly escaped out.
897 """Class to transform lines that are explicitly escaped out.
907
898
908 This calls the above _tr_* static methods for the actual line
899 This calls the above _tr_* static methods for the actual line
909 translations."""
900 translations."""
910
901
911 # Empty lines just get returned unmodified
902 # Empty lines just get returned unmodified
912 if not line or line.isspace():
903 if not line or line.isspace():
913 return line
904 return line
914
905
915 # Get line endpoints, where the escapes can be
906 # Get line endpoints, where the escapes can be
916 line_info = LineInfo(line)
907 line_info = LineInfo(line)
917
908
918 # If the escape is not at the start, only '?' needs to be special-cased.
909 # If the escape is not at the start, only '?' needs to be special-cased.
919 # All other escapes are only valid at the start
910 # All other escapes are only valid at the start
920 if not line_info.esc in self.tr:
911 if not line_info.esc in self.tr:
921 if line.endswith(ESC_HELP):
912 if line.endswith(ESC_HELP):
922 return self._tr_help(line_info)
913 return self._tr_help(line_info)
923 else:
914 else:
924 # If we don't recognize the escape, don't modify the line
915 # If we don't recognize the escape, don't modify the line
925 return line
916 return line
926
917
927 return self.tr[line_info.esc](line_info)
918 return self.tr[line_info.esc](line_info)
928
919
929
920
930 # A function-looking object to be used by the rest of the code. The purpose of
921 # A function-looking object to be used by the rest of the code. The purpose of
931 # the class in this case is to organize related functionality, more than to
922 # the class in this case is to organize related functionality, more than to
932 # manage state.
923 # manage state.
933 transform_escaped = EscapedTransformer()
924 transform_escaped = EscapedTransformer()
934
925
935
926
936 class IPythonInputSplitter(InputSplitter):
927 class IPythonInputSplitter(InputSplitter):
937 """An input splitter that recognizes all of IPython's special syntax."""
928 """An input splitter that recognizes all of IPython's special syntax."""
938
929
939 # String with raw, untransformed input.
930 # String with raw, untransformed input.
940 source_raw = ''
931 source_raw = ''
941
932
942 # Private attributes
933 # Private attributes
943
934
944 # List with lines of raw input accumulated so far.
935 # List with lines of raw input accumulated so far.
945 _buffer_raw = None
936 _buffer_raw = None
946
937
947 def __init__(self, input_mode=None):
938 def __init__(self, input_mode=None):
948 InputSplitter.__init__(self, input_mode)
939 InputSplitter.__init__(self, input_mode)
949 self._buffer_raw = []
940 self._buffer_raw = []
950
941
951 def reset(self):
942 def reset(self):
952 """Reset the input buffer and associated state."""
943 """Reset the input buffer and associated state."""
953 InputSplitter.reset(self)
944 InputSplitter.reset(self)
954 self._buffer_raw[:] = []
945 self._buffer_raw[:] = []
955 self.source_raw = ''
946 self.source_raw = ''
956
947
957 def source_raw_reset(self):
948 def source_raw_reset(self):
958 """Return input and raw source and perform a full reset.
949 """Return input and raw source and perform a full reset.
959 """
950 """
960 out = self.source
951 out = self.source
961 out_r = self.source_raw
952 out_r = self.source_raw
962 self.reset()
953 self.reset()
963 return out, out_r
954 return out, out_r
964
955
965 def push(self, lines):
956 def push(self, lines):
966 """Push one or more lines of IPython input.
957 """Push one or more lines of IPython input.
967 """
958 """
968 if not lines:
959 if not lines:
969 return super(IPythonInputSplitter, self).push(lines)
960 return super(IPythonInputSplitter, self).push(lines)
970
961
971 lines_list = lines.splitlines()
962 lines_list = lines.splitlines()
972
963
973 transforms = [transform_escaped, transform_assign_system,
964 transforms = [transform_escaped, transform_assign_system,
974 transform_assign_magic, transform_ipy_prompt,
965 transform_assign_magic, transform_ipy_prompt,
975 transform_classic_prompt]
966 transform_classic_prompt]
976
967
977 # Transform logic
968 # Transform logic
978 #
969 #
979 # We only apply the line transformers to the input if we have either no
970 # We only apply the line transformers to the input if we have either no
980 # input yet, or complete input, or if the last line of the buffer ends
971 # input yet, or complete input, or if the last line of the buffer ends
981 # with ':' (opening an indented block). This prevents the accidental
972 # with ':' (opening an indented block). This prevents the accidental
982 # transformation of escapes inside multiline expressions like
973 # transformation of escapes inside multiline expressions like
983 # triple-quoted strings or parenthesized expressions.
974 # triple-quoted strings or parenthesized expressions.
984 #
975 #
985 # The last heuristic, while ugly, ensures that the first line of an
976 # The last heuristic, while ugly, ensures that the first line of an
986 # indented block is correctly transformed.
977 # indented block is correctly transformed.
987 #
978 #
988 # FIXME: try to find a cleaner approach for this last bit.
979 # FIXME: try to find a cleaner approach for this last bit.
989
980
990 # If we were in 'block' mode, since we're going to pump the parent
981 # If we were in 'block' mode, since we're going to pump the parent
991 # class by hand line by line, we need to temporarily switch out to
982 # class by hand line by line, we need to temporarily switch out to
992 # 'line' mode, do a single manual reset and then feed the lines one
983 # 'line' mode, do a single manual reset and then feed the lines one
993 # by one. Note that this only matters if the input has more than one
984 # by one. Note that this only matters if the input has more than one
994 # line.
985 # line.
995 changed_input_mode = False
986 changed_input_mode = False
996
987
997 if self.input_mode == 'cell':
988 if self.input_mode == 'cell':
998 self.reset()
989 self.reset()
999 changed_input_mode = True
990 changed_input_mode = True
1000 saved_input_mode = 'cell'
991 saved_input_mode = 'cell'
1001 self.input_mode = 'line'
992 self.input_mode = 'line'
1002
993
1003 # Store raw source before applying any transformations to it. Note
994 # Store raw source before applying any transformations to it. Note
1004 # that this must be done *after* the reset() call that would otherwise
995 # that this must be done *after* the reset() call that would otherwise
1005 # flush the buffer.
996 # flush the buffer.
1006 self._store(lines, self._buffer_raw, 'source_raw')
997 self._store(lines, self._buffer_raw, 'source_raw')
1007
998
1008 try:
999 try:
1009 push = super(IPythonInputSplitter, self).push
1000 push = super(IPythonInputSplitter, self).push
1010 for line in lines_list:
1001 for line in lines_list:
1011 if self._is_complete or not self._buffer or \
1002 if self._is_complete or not self._buffer or \
1012 (self._buffer and self._buffer[-1].rstrip().endswith(':')):
1003 (self._buffer and self._buffer[-1].rstrip().endswith(':')):
1013 for f in transforms:
1004 for f in transforms:
1014 line = f(line)
1005 line = f(line)
1015
1006
1016 out = push(line)
1007 out = push(line)
1017 finally:
1008 finally:
1018 if changed_input_mode:
1009 if changed_input_mode:
1019 self.input_mode = saved_input_mode
1010 self.input_mode = saved_input_mode
1020 return out
1011 return out
@@ -1,2537 +1,2516 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 atexit
23 import atexit
24 import codeop
24 import codeop
25 import exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager
41 from IPython.core.alias import AliasManager
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.display_trap import DisplayTrap
44 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displayhook import DisplayHook
45 from IPython.core.error import TryNext, UsageError
45 from IPython.core.error import TryNext, UsageError
46 from IPython.core.extensions import ExtensionManager
46 from IPython.core.extensions import ExtensionManager
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 from IPython.core.history import HistoryManager
48 from IPython.core.history import HistoryManager
49 from IPython.core.inputlist import InputList
49 from IPython.core.inputlist import InputList
50 from IPython.core.inputsplitter import IPythonInputSplitter
50 from IPython.core.inputsplitter import IPythonInputSplitter
51 from IPython.core.logger import Logger
51 from IPython.core.logger import Logger
52 from IPython.core.magic import Magic
52 from IPython.core.magic import Magic
53 from IPython.core.payload import PayloadManager
53 from IPython.core.payload import PayloadManager
54 from IPython.core.plugin import PluginManager
54 from IPython.core.plugin import PluginManager
55 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
55 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
56 from IPython.external.Itpl import ItplNS
56 from IPython.external.Itpl import ItplNS
57 from IPython.utils import PyColorize
57 from IPython.utils import PyColorize
58 from IPython.utils import io
58 from IPython.utils import io
59 from IPython.utils import pickleshare
59 from IPython.utils import pickleshare
60 from IPython.utils.doctestreload import doctest_reload
60 from IPython.utils.doctestreload import doctest_reload
61 from IPython.utils.io import ask_yes_no, rprint
61 from IPython.utils.io import ask_yes_no, rprint
62 from IPython.utils.ipstruct import Struct
62 from IPython.utils.ipstruct import Struct
63 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
63 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
64 from IPython.utils.process import system, getoutput
64 from IPython.utils.process import system, getoutput
65 from IPython.utils.strdispatch import StrDispatch
65 from IPython.utils.strdispatch import StrDispatch
66 from IPython.utils.syspathcontext import prepended_to_syspath
66 from IPython.utils.syspathcontext import prepended_to_syspath
67 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
67 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
68 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
68 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
69 List, Unicode, Instance, Type)
69 List, Unicode, Instance, Type)
70 from IPython.utils.warn import warn, error, fatal
70 from IPython.utils.warn import warn, error, fatal
71 import IPython.core.hooks
71 import IPython.core.hooks
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
159
160 # Input splitter, to split entire cells of input into either individual
160 # Input splitter, to split entire cells of input into either individual
161 # interactive statements or whole blocks.
161 # interactive statements or whole blocks.
162 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
163 (), {})
163 (), {})
164 logstart = CBool(False, config=True)
164 logstart = CBool(False, config=True)
165 logfile = Str('', config=True)
165 logfile = Str('', config=True)
166 logappend = Str('', config=True)
166 logappend = Str('', config=True)
167 object_info_string_level = Enum((0,1,2), default_value=0,
167 object_info_string_level = Enum((0,1,2), default_value=0,
168 config=True)
168 config=True)
169 pdb = CBool(False, config=True)
169 pdb = CBool(False, config=True)
170
170
171 pprint = CBool(True, config=True)
171 pprint = CBool(True, config=True)
172 profile = Str('', config=True)
172 profile = Str('', config=True)
173 prompt_in1 = Str('In [\\#]: ', config=True)
173 prompt_in1 = Str('In [\\#]: ', config=True)
174 prompt_in2 = Str(' .\\D.: ', config=True)
174 prompt_in2 = Str(' .\\D.: ', config=True)
175 prompt_out = Str('Out[\\#]: ', config=True)
175 prompt_out = Str('Out[\\#]: ', config=True)
176 prompts_pad_left = CBool(True, config=True)
176 prompts_pad_left = CBool(True, config=True)
177 quiet = CBool(False, config=True)
177 quiet = CBool(False, config=True)
178
178
179 # The readline stuff will eventually be moved to the terminal subclass
179 # The readline stuff will eventually be moved to the terminal subclass
180 # but for now, we can't do that as readline is welded in everywhere.
180 # but for now, we can't do that as readline is welded in everywhere.
181 readline_use = CBool(True, config=True)
181 readline_use = CBool(True, config=True)
182 readline_merge_completions = CBool(True, config=True)
182 readline_merge_completions = CBool(True, config=True)
183 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
183 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
184 readline_remove_delims = Str('-/~', config=True)
184 readline_remove_delims = Str('-/~', config=True)
185 readline_parse_and_bind = List([
185 readline_parse_and_bind = List([
186 'tab: complete',
186 'tab: complete',
187 '"\C-l": clear-screen',
187 '"\C-l": clear-screen',
188 'set show-all-if-ambiguous on',
188 'set show-all-if-ambiguous on',
189 '"\C-o": tab-insert',
189 '"\C-o": tab-insert',
190 '"\M-i": " "',
190 '"\M-i": " "',
191 '"\M-o": "\d\d\d\d"',
191 '"\M-o": "\d\d\d\d"',
192 '"\M-I": "\d\d\d\d"',
192 '"\M-I": "\d\d\d\d"',
193 '"\C-r": reverse-search-history',
193 '"\C-r": reverse-search-history',
194 '"\C-s": forward-search-history',
194 '"\C-s": forward-search-history',
195 '"\C-p": history-search-backward',
195 '"\C-p": history-search-backward',
196 '"\C-n": history-search-forward',
196 '"\C-n": history-search-forward',
197 '"\e[A": history-search-backward',
197 '"\e[A": history-search-backward',
198 '"\e[B": history-search-forward',
198 '"\e[B": history-search-forward',
199 '"\C-k": kill-line',
199 '"\C-k": kill-line',
200 '"\C-u": unix-line-discard',
200 '"\C-u": unix-line-discard',
201 ], allow_none=False, config=True)
201 ], allow_none=False, config=True)
202
202
203 # TODO: this part of prompt management should be moved to the frontends.
203 # TODO: this part of prompt management should be moved to the frontends.
204 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
204 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
205 separate_in = SeparateStr('\n', config=True)
205 separate_in = SeparateStr('\n', config=True)
206 separate_out = SeparateStr('', config=True)
206 separate_out = SeparateStr('', config=True)
207 separate_out2 = SeparateStr('', config=True)
207 separate_out2 = SeparateStr('', config=True)
208 wildcards_case_sensitive = CBool(True, config=True)
208 wildcards_case_sensitive = CBool(True, config=True)
209 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
209 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
210 default_value='Context', config=True)
210 default_value='Context', config=True)
211
211
212 # Subcomponents of InteractiveShell
212 # Subcomponents of InteractiveShell
213 alias_manager = Instance('IPython.core.alias.AliasManager')
213 alias_manager = Instance('IPython.core.alias.AliasManager')
214 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
214 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
215 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
215 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
216 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
216 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
217 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
217 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
218 plugin_manager = Instance('IPython.core.plugin.PluginManager')
218 plugin_manager = Instance('IPython.core.plugin.PluginManager')
219 payload_manager = Instance('IPython.core.payload.PayloadManager')
219 payload_manager = Instance('IPython.core.payload.PayloadManager')
220 history_manager = Instance('IPython.core.history.HistoryManager')
220 history_manager = Instance('IPython.core.history.HistoryManager')
221
221
222 # Private interface
222 # Private interface
223 _post_execute = set()
223 _post_execute = set()
224
224
225 def __init__(self, config=None, ipython_dir=None,
225 def __init__(self, config=None, ipython_dir=None,
226 user_ns=None, user_global_ns=None,
226 user_ns=None, user_global_ns=None,
227 custom_exceptions=((), None)):
227 custom_exceptions=((), None)):
228
228
229 # This is where traits with a config_key argument are updated
229 # This is where traits with a config_key argument are updated
230 # from the values on config.
230 # from the values on config.
231 super(InteractiveShell, self).__init__(config=config)
231 super(InteractiveShell, self).__init__(config=config)
232
232
233 # These are relatively independent and stateless
233 # These are relatively independent and stateless
234 self.init_ipython_dir(ipython_dir)
234 self.init_ipython_dir(ipython_dir)
235 self.init_instance_attrs()
235 self.init_instance_attrs()
236 self.init_environment()
236 self.init_environment()
237
237
238 # Create namespaces (user_ns, user_global_ns, etc.)
238 # Create namespaces (user_ns, user_global_ns, etc.)
239 self.init_create_namespaces(user_ns, user_global_ns)
239 self.init_create_namespaces(user_ns, user_global_ns)
240 # This has to be done after init_create_namespaces because it uses
240 # This has to be done after init_create_namespaces because it uses
241 # something in self.user_ns, but before init_sys_modules, which
241 # something in self.user_ns, but before init_sys_modules, which
242 # is the first thing to modify sys.
242 # is the first thing to modify sys.
243 # TODO: When we override sys.stdout and sys.stderr before this class
243 # TODO: When we override sys.stdout and sys.stderr before this class
244 # is created, we are saving the overridden ones here. Not sure if this
244 # is created, we are saving the overridden ones here. Not sure if this
245 # is what we want to do.
245 # is what we want to do.
246 self.save_sys_module_state()
246 self.save_sys_module_state()
247 self.init_sys_modules()
247 self.init_sys_modules()
248
248
249 self.init_history()
249 self.init_history()
250 self.init_encoding()
250 self.init_encoding()
251 self.init_prefilter()
251 self.init_prefilter()
252
252
253 Magic.__init__(self, self)
253 Magic.__init__(self, self)
254
254
255 self.init_syntax_highlighting()
255 self.init_syntax_highlighting()
256 self.init_hooks()
256 self.init_hooks()
257 self.init_pushd_popd_magic()
257 self.init_pushd_popd_magic()
258 # self.init_traceback_handlers use to be here, but we moved it below
258 # self.init_traceback_handlers use to be here, but we moved it below
259 # because it and init_io have to come after init_readline.
259 # because it and init_io have to come after init_readline.
260 self.init_user_ns()
260 self.init_user_ns()
261 self.init_logger()
261 self.init_logger()
262 self.init_alias()
262 self.init_alias()
263 self.init_builtins()
263 self.init_builtins()
264
264
265 # pre_config_initialization
265 # pre_config_initialization
266
266
267 # The next section should contain everything that was in ipmaker.
267 # The next section should contain everything that was in ipmaker.
268 self.init_logstart()
268 self.init_logstart()
269
269
270 # The following was in post_config_initialization
270 # The following was in post_config_initialization
271 self.init_inspector()
271 self.init_inspector()
272 # init_readline() must come before init_io(), because init_io uses
272 # init_readline() must come before init_io(), because init_io uses
273 # readline related things.
273 # readline related things.
274 self.init_readline()
274 self.init_readline()
275 # init_completer must come after init_readline, because it needs to
275 # init_completer must come after init_readline, because it needs to
276 # know whether readline is present or not system-wide to configure the
276 # know whether readline is present or not system-wide to configure the
277 # completers, since the completion machinery can now operate
277 # completers, since the completion machinery can now operate
278 # independently of readline (e.g. over the network)
278 # independently of readline (e.g. over the network)
279 self.init_completer()
279 self.init_completer()
280 # TODO: init_io() needs to happen before init_traceback handlers
280 # TODO: init_io() needs to happen before init_traceback handlers
281 # because the traceback handlers hardcode the stdout/stderr streams.
281 # because the traceback handlers hardcode the stdout/stderr streams.
282 # This logic in in debugger.Pdb and should eventually be changed.
282 # This logic in in debugger.Pdb and should eventually be changed.
283 self.init_io()
283 self.init_io()
284 self.init_traceback_handlers(custom_exceptions)
284 self.init_traceback_handlers(custom_exceptions)
285 self.init_prompts()
285 self.init_prompts()
286 self.init_displayhook()
286 self.init_displayhook()
287 self.init_reload_doctest()
287 self.init_reload_doctest()
288 self.init_magics()
288 self.init_magics()
289 self.init_pdb()
289 self.init_pdb()
290 self.init_extension_manager()
290 self.init_extension_manager()
291 self.init_plugin_manager()
291 self.init_plugin_manager()
292 self.init_payload()
292 self.init_payload()
293 self.hooks.late_startup_hook()
293 self.hooks.late_startup_hook()
294 atexit.register(self.atexit_operations)
294 atexit.register(self.atexit_operations)
295
295
296 @classmethod
296 @classmethod
297 def instance(cls, *args, **kwargs):
297 def instance(cls, *args, **kwargs):
298 """Returns a global InteractiveShell instance."""
298 """Returns a global InteractiveShell instance."""
299 if cls._instance is None:
299 if cls._instance is None:
300 inst = cls(*args, **kwargs)
300 inst = cls(*args, **kwargs)
301 # Now make sure that the instance will also be returned by
301 # Now make sure that the instance will also be returned by
302 # the subclasses instance attribute.
302 # the subclasses instance attribute.
303 for subclass in cls.mro():
303 for subclass in cls.mro():
304 if issubclass(cls, subclass) and \
304 if issubclass(cls, subclass) and \
305 issubclass(subclass, InteractiveShell):
305 issubclass(subclass, InteractiveShell):
306 subclass._instance = inst
306 subclass._instance = inst
307 else:
307 else:
308 break
308 break
309 if isinstance(cls._instance, cls):
309 if isinstance(cls._instance, cls):
310 return cls._instance
310 return cls._instance
311 else:
311 else:
312 raise MultipleInstanceError(
312 raise MultipleInstanceError(
313 'Multiple incompatible subclass instances of '
313 'Multiple incompatible subclass instances of '
314 'InteractiveShell are being created.'
314 'InteractiveShell are being created.'
315 )
315 )
316
316
317 @classmethod
317 @classmethod
318 def initialized(cls):
318 def initialized(cls):
319 return hasattr(cls, "_instance")
319 return hasattr(cls, "_instance")
320
320
321 def get_ipython(self):
321 def get_ipython(self):
322 """Return the currently running IPython instance."""
322 """Return the currently running IPython instance."""
323 return self
323 return self
324
324
325 #-------------------------------------------------------------------------
325 #-------------------------------------------------------------------------
326 # Trait changed handlers
326 # Trait changed handlers
327 #-------------------------------------------------------------------------
327 #-------------------------------------------------------------------------
328
328
329 def _ipython_dir_changed(self, name, new):
329 def _ipython_dir_changed(self, name, new):
330 if not os.path.isdir(new):
330 if not os.path.isdir(new):
331 os.makedirs(new, mode = 0777)
331 os.makedirs(new, mode = 0777)
332
332
333 def set_autoindent(self,value=None):
333 def set_autoindent(self,value=None):
334 """Set the autoindent flag, checking for readline support.
334 """Set the autoindent flag, checking for readline support.
335
335
336 If called with no arguments, it acts as a toggle."""
336 If called with no arguments, it acts as a toggle."""
337
337
338 if not self.has_readline:
338 if not self.has_readline:
339 if os.name == 'posix':
339 if os.name == 'posix':
340 warn("The auto-indent feature requires the readline library")
340 warn("The auto-indent feature requires the readline library")
341 self.autoindent = 0
341 self.autoindent = 0
342 return
342 return
343 if value is None:
343 if value is None:
344 self.autoindent = not self.autoindent
344 self.autoindent = not self.autoindent
345 else:
345 else:
346 self.autoindent = value
346 self.autoindent = value
347
347
348 #-------------------------------------------------------------------------
348 #-------------------------------------------------------------------------
349 # init_* methods called by __init__
349 # init_* methods called by __init__
350 #-------------------------------------------------------------------------
350 #-------------------------------------------------------------------------
351
351
352 def init_ipython_dir(self, ipython_dir):
352 def init_ipython_dir(self, ipython_dir):
353 if ipython_dir is not None:
353 if ipython_dir is not None:
354 self.ipython_dir = ipython_dir
354 self.ipython_dir = ipython_dir
355 self.config.Global.ipython_dir = self.ipython_dir
355 self.config.Global.ipython_dir = self.ipython_dir
356 return
356 return
357
357
358 if hasattr(self.config.Global, 'ipython_dir'):
358 if hasattr(self.config.Global, 'ipython_dir'):
359 self.ipython_dir = self.config.Global.ipython_dir
359 self.ipython_dir = self.config.Global.ipython_dir
360 else:
360 else:
361 self.ipython_dir = get_ipython_dir()
361 self.ipython_dir = get_ipython_dir()
362
362
363 # All children can just read this
363 # All children can just read this
364 self.config.Global.ipython_dir = self.ipython_dir
364 self.config.Global.ipython_dir = self.ipython_dir
365
365
366 def init_instance_attrs(self):
366 def init_instance_attrs(self):
367 self.more = False
367 self.more = False
368
368
369 # command compiler
369 # command compiler
370 self.compile = codeop.CommandCompiler()
370 self.compile = codeop.CommandCompiler()
371
371
372 # User input buffers
372 # User input buffers
373 self.buffer = []
373 self.buffer = []
374 self.buffer_raw = []
374 self.buffer_raw = []
375
375
376 # Make an empty namespace, which extension writers can rely on both
376 # Make an empty namespace, which extension writers can rely on both
377 # existing and NEVER being used by ipython itself. This gives them a
377 # existing and NEVER being used by ipython itself. This gives them a
378 # convenient location for storing additional information and state
378 # convenient location for storing additional information and state
379 # their extensions may require, without fear of collisions with other
379 # their extensions may require, without fear of collisions with other
380 # ipython names that may develop later.
380 # ipython names that may develop later.
381 self.meta = Struct()
381 self.meta = Struct()
382
382
383 # Object variable to store code object waiting execution. This is
383 # Object variable to store code object waiting execution. This is
384 # used mainly by the multithreaded shells, but it can come in handy in
384 # used mainly by the multithreaded shells, but it can come in handy in
385 # other situations. No need to use a Queue here, since it's a single
385 # other situations. No need to use a Queue here, since it's a single
386 # item which gets cleared once run.
386 # item which gets cleared once run.
387 self.code_to_run = None
387 self.code_to_run = None
388
388
389 # Temporary files used for various purposes. Deleted at exit.
389 # Temporary files used for various purposes. Deleted at exit.
390 self.tempfiles = []
390 self.tempfiles = []
391
391
392 # Keep track of readline usage (later set by init_readline)
392 # Keep track of readline usage (later set by init_readline)
393 self.has_readline = False
393 self.has_readline = False
394
394
395 # keep track of where we started running (mainly for crash post-mortem)
395 # keep track of where we started running (mainly for crash post-mortem)
396 # This is not being used anywhere currently.
396 # This is not being used anywhere currently.
397 self.starting_dir = os.getcwd()
397 self.starting_dir = os.getcwd()
398
398
399 # Indentation management
399 # Indentation management
400 self.indent_current_nsp = 0
400 self.indent_current_nsp = 0
401
401
402 # Increasing execution counter
402 # Increasing execution counter
403 self.execution_count = 0
403 self.execution_count = 1
404
404
405 def init_environment(self):
405 def init_environment(self):
406 """Any changes we need to make to the user's environment."""
406 """Any changes we need to make to the user's environment."""
407 pass
407 pass
408
408
409 def init_encoding(self):
409 def init_encoding(self):
410 # Get system encoding at startup time. Certain terminals (like Emacs
410 # Get system encoding at startup time. Certain terminals (like Emacs
411 # under Win32 have it set to None, and we need to have a known valid
411 # under Win32 have it set to None, and we need to have a known valid
412 # encoding to use in the raw_input() method
412 # encoding to use in the raw_input() method
413 try:
413 try:
414 self.stdin_encoding = sys.stdin.encoding or 'ascii'
414 self.stdin_encoding = sys.stdin.encoding or 'ascii'
415 except AttributeError:
415 except AttributeError:
416 self.stdin_encoding = 'ascii'
416 self.stdin_encoding = 'ascii'
417
417
418 def init_syntax_highlighting(self):
418 def init_syntax_highlighting(self):
419 # Python source parser/formatter for syntax highlighting
419 # Python source parser/formatter for syntax highlighting
420 pyformat = PyColorize.Parser().format
420 pyformat = PyColorize.Parser().format
421 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
421 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
422
422
423 def init_pushd_popd_magic(self):
423 def init_pushd_popd_magic(self):
424 # for pushd/popd management
424 # for pushd/popd management
425 try:
425 try:
426 self.home_dir = get_home_dir()
426 self.home_dir = get_home_dir()
427 except HomeDirError, msg:
427 except HomeDirError, msg:
428 fatal(msg)
428 fatal(msg)
429
429
430 self.dir_stack = []
430 self.dir_stack = []
431
431
432 def init_logger(self):
432 def init_logger(self):
433 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
433 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
434 # local shortcut, this is used a LOT
434 # local shortcut, this is used a LOT
435 self.log = self.logger.log
435 self.log = self.logger.log
436
436
437 def init_logstart(self):
437 def init_logstart(self):
438 if self.logappend:
438 if self.logappend:
439 self.magic_logstart(self.logappend + ' append')
439 self.magic_logstart(self.logappend + ' append')
440 elif self.logfile:
440 elif self.logfile:
441 self.magic_logstart(self.logfile)
441 self.magic_logstart(self.logfile)
442 elif self.logstart:
442 elif self.logstart:
443 self.magic_logstart()
443 self.magic_logstart()
444
444
445 def init_builtins(self):
445 def init_builtins(self):
446 self.builtin_trap = BuiltinTrap(shell=self)
446 self.builtin_trap = BuiltinTrap(shell=self)
447
447
448 def init_inspector(self):
448 def init_inspector(self):
449 # Object inspector
449 # Object inspector
450 self.inspector = oinspect.Inspector(oinspect.InspectColors,
450 self.inspector = oinspect.Inspector(oinspect.InspectColors,
451 PyColorize.ANSICodeColors,
451 PyColorize.ANSICodeColors,
452 'NoColor',
452 'NoColor',
453 self.object_info_string_level)
453 self.object_info_string_level)
454
454
455 def init_io(self):
455 def init_io(self):
456 # This will just use sys.stdout and sys.stderr. If you want to
456 # This will just use sys.stdout and sys.stderr. If you want to
457 # override sys.stdout and sys.stderr themselves, you need to do that
457 # override sys.stdout and sys.stderr themselves, you need to do that
458 # *before* instantiating this class, because Term holds onto
458 # *before* instantiating this class, because Term holds onto
459 # references to the underlying streams.
459 # references to the underlying streams.
460 if sys.platform == 'win32' and self.has_readline:
460 if sys.platform == 'win32' and self.has_readline:
461 Term = io.IOTerm(cout=self.readline._outputfile,
461 Term = io.IOTerm(cout=self.readline._outputfile,
462 cerr=self.readline._outputfile)
462 cerr=self.readline._outputfile)
463 else:
463 else:
464 Term = io.IOTerm()
464 Term = io.IOTerm()
465 io.Term = Term
465 io.Term = Term
466
466
467 def init_prompts(self):
467 def init_prompts(self):
468 # TODO: This is a pass for now because the prompts are managed inside
468 # TODO: This is a pass for now because the prompts are managed inside
469 # the DisplayHook. Once there is a separate prompt manager, this
469 # the DisplayHook. Once there is a separate prompt manager, this
470 # will initialize that object and all prompt related information.
470 # will initialize that object and all prompt related information.
471 pass
471 pass
472
472
473 def init_displayhook(self):
473 def init_displayhook(self):
474 # Initialize displayhook, set in/out prompts and printing system
474 # Initialize displayhook, set in/out prompts and printing system
475 self.displayhook = self.displayhook_class(
475 self.displayhook = self.displayhook_class(
476 shell=self,
476 shell=self,
477 cache_size=self.cache_size,
477 cache_size=self.cache_size,
478 input_sep = self.separate_in,
478 input_sep = self.separate_in,
479 output_sep = self.separate_out,
479 output_sep = self.separate_out,
480 output_sep2 = self.separate_out2,
480 output_sep2 = self.separate_out2,
481 ps1 = self.prompt_in1,
481 ps1 = self.prompt_in1,
482 ps2 = self.prompt_in2,
482 ps2 = self.prompt_in2,
483 ps_out = self.prompt_out,
483 ps_out = self.prompt_out,
484 pad_left = self.prompts_pad_left
484 pad_left = self.prompts_pad_left
485 )
485 )
486 # This is a context manager that installs/revmoes the displayhook at
486 # This is a context manager that installs/revmoes the displayhook at
487 # the appropriate time.
487 # the appropriate time.
488 self.display_trap = DisplayTrap(hook=self.displayhook)
488 self.display_trap = DisplayTrap(hook=self.displayhook)
489
489
490 def init_reload_doctest(self):
490 def init_reload_doctest(self):
491 # Do a proper resetting of doctest, including the necessary displayhook
491 # Do a proper resetting of doctest, including the necessary displayhook
492 # monkeypatching
492 # monkeypatching
493 try:
493 try:
494 doctest_reload()
494 doctest_reload()
495 except ImportError:
495 except ImportError:
496 warn("doctest module does not exist.")
496 warn("doctest module does not exist.")
497
497
498 #-------------------------------------------------------------------------
498 #-------------------------------------------------------------------------
499 # Things related to injections into the sys module
499 # Things related to injections into the sys module
500 #-------------------------------------------------------------------------
500 #-------------------------------------------------------------------------
501
501
502 def save_sys_module_state(self):
502 def save_sys_module_state(self):
503 """Save the state of hooks in the sys module.
503 """Save the state of hooks in the sys module.
504
504
505 This has to be called after self.user_ns is created.
505 This has to be called after self.user_ns is created.
506 """
506 """
507 self._orig_sys_module_state = {}
507 self._orig_sys_module_state = {}
508 self._orig_sys_module_state['stdin'] = sys.stdin
508 self._orig_sys_module_state['stdin'] = sys.stdin
509 self._orig_sys_module_state['stdout'] = sys.stdout
509 self._orig_sys_module_state['stdout'] = sys.stdout
510 self._orig_sys_module_state['stderr'] = sys.stderr
510 self._orig_sys_module_state['stderr'] = sys.stderr
511 self._orig_sys_module_state['excepthook'] = sys.excepthook
511 self._orig_sys_module_state['excepthook'] = sys.excepthook
512 try:
512 try:
513 self._orig_sys_modules_main_name = self.user_ns['__name__']
513 self._orig_sys_modules_main_name = self.user_ns['__name__']
514 except KeyError:
514 except KeyError:
515 pass
515 pass
516
516
517 def restore_sys_module_state(self):
517 def restore_sys_module_state(self):
518 """Restore the state of the sys module."""
518 """Restore the state of the sys module."""
519 try:
519 try:
520 for k, v in self._orig_sys_module_state.items():
520 for k, v in self._orig_sys_module_state.items():
521 setattr(sys, k, v)
521 setattr(sys, k, v)
522 except AttributeError:
522 except AttributeError:
523 pass
523 pass
524 # Reset what what done in self.init_sys_modules
524 # Reset what what done in self.init_sys_modules
525 try:
525 try:
526 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
526 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
527 except (AttributeError, KeyError):
527 except (AttributeError, KeyError):
528 pass
528 pass
529
529
530 #-------------------------------------------------------------------------
530 #-------------------------------------------------------------------------
531 # Things related to hooks
531 # Things related to hooks
532 #-------------------------------------------------------------------------
532 #-------------------------------------------------------------------------
533
533
534 def init_hooks(self):
534 def init_hooks(self):
535 # hooks holds pointers used for user-side customizations
535 # hooks holds pointers used for user-side customizations
536 self.hooks = Struct()
536 self.hooks = Struct()
537
537
538 self.strdispatchers = {}
538 self.strdispatchers = {}
539
539
540 # Set all default hooks, defined in the IPython.hooks module.
540 # Set all default hooks, defined in the IPython.hooks module.
541 hooks = IPython.core.hooks
541 hooks = IPython.core.hooks
542 for hook_name in hooks.__all__:
542 for hook_name in hooks.__all__:
543 # default hooks have priority 100, i.e. low; user hooks should have
543 # default hooks have priority 100, i.e. low; user hooks should have
544 # 0-100 priority
544 # 0-100 priority
545 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
545 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
546
546
547 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
547 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
548 """set_hook(name,hook) -> sets an internal IPython hook.
548 """set_hook(name,hook) -> sets an internal IPython hook.
549
549
550 IPython exposes some of its internal API as user-modifiable hooks. By
550 IPython exposes some of its internal API as user-modifiable hooks. By
551 adding your function to one of these hooks, you can modify IPython's
551 adding your function to one of these hooks, you can modify IPython's
552 behavior to call at runtime your own routines."""
552 behavior to call at runtime your own routines."""
553
553
554 # At some point in the future, this should validate the hook before it
554 # At some point in the future, this should validate the hook before it
555 # accepts it. Probably at least check that the hook takes the number
555 # accepts it. Probably at least check that the hook takes the number
556 # of args it's supposed to.
556 # of args it's supposed to.
557
557
558 f = new.instancemethod(hook,self,self.__class__)
558 f = new.instancemethod(hook,self,self.__class__)
559
559
560 # check if the hook is for strdispatcher first
560 # check if the hook is for strdispatcher first
561 if str_key is not None:
561 if str_key is not None:
562 sdp = self.strdispatchers.get(name, StrDispatch())
562 sdp = self.strdispatchers.get(name, StrDispatch())
563 sdp.add_s(str_key, f, priority )
563 sdp.add_s(str_key, f, priority )
564 self.strdispatchers[name] = sdp
564 self.strdispatchers[name] = sdp
565 return
565 return
566 if re_key is not None:
566 if re_key is not None:
567 sdp = self.strdispatchers.get(name, StrDispatch())
567 sdp = self.strdispatchers.get(name, StrDispatch())
568 sdp.add_re(re.compile(re_key), f, priority )
568 sdp.add_re(re.compile(re_key), f, priority )
569 self.strdispatchers[name] = sdp
569 self.strdispatchers[name] = sdp
570 return
570 return
571
571
572 dp = getattr(self.hooks, name, None)
572 dp = getattr(self.hooks, name, None)
573 if name not in IPython.core.hooks.__all__:
573 if name not in IPython.core.hooks.__all__:
574 print "Warning! Hook '%s' is not one of %s" % \
574 print "Warning! Hook '%s' is not one of %s" % \
575 (name, IPython.core.hooks.__all__ )
575 (name, IPython.core.hooks.__all__ )
576 if not dp:
576 if not dp:
577 dp = IPython.core.hooks.CommandChainDispatcher()
577 dp = IPython.core.hooks.CommandChainDispatcher()
578
578
579 try:
579 try:
580 dp.add(f,priority)
580 dp.add(f,priority)
581 except AttributeError:
581 except AttributeError:
582 # it was not commandchain, plain old func - replace
582 # it was not commandchain, plain old func - replace
583 dp = f
583 dp = f
584
584
585 setattr(self.hooks,name, dp)
585 setattr(self.hooks,name, dp)
586
586
587 def register_post_execute(self, func):
587 def register_post_execute(self, func):
588 """Register a function for calling after code execution.
588 """Register a function for calling after code execution.
589 """
589 """
590 if not callable(func):
590 if not callable(func):
591 raise ValueError('argument %s must be callable' % func)
591 raise ValueError('argument %s must be callable' % func)
592 self._post_execute.add(func)
592 self._post_execute.add(func)
593
593
594 #-------------------------------------------------------------------------
594 #-------------------------------------------------------------------------
595 # Things related to the "main" module
595 # Things related to the "main" module
596 #-------------------------------------------------------------------------
596 #-------------------------------------------------------------------------
597
597
598 def new_main_mod(self,ns=None):
598 def new_main_mod(self,ns=None):
599 """Return a new 'main' module object for user code execution.
599 """Return a new 'main' module object for user code execution.
600 """
600 """
601 main_mod = self._user_main_module
601 main_mod = self._user_main_module
602 init_fakemod_dict(main_mod,ns)
602 init_fakemod_dict(main_mod,ns)
603 return main_mod
603 return main_mod
604
604
605 def cache_main_mod(self,ns,fname):
605 def cache_main_mod(self,ns,fname):
606 """Cache a main module's namespace.
606 """Cache a main module's namespace.
607
607
608 When scripts are executed via %run, we must keep a reference to the
608 When scripts are executed via %run, we must keep a reference to the
609 namespace of their __main__ module (a FakeModule instance) around so
609 namespace of their __main__ module (a FakeModule instance) around so
610 that Python doesn't clear it, rendering objects defined therein
610 that Python doesn't clear it, rendering objects defined therein
611 useless.
611 useless.
612
612
613 This method keeps said reference in a private dict, keyed by the
613 This method keeps said reference in a private dict, keyed by the
614 absolute path of the module object (which corresponds to the script
614 absolute path of the module object (which corresponds to the script
615 path). This way, for multiple executions of the same script we only
615 path). This way, for multiple executions of the same script we only
616 keep one copy of the namespace (the last one), thus preventing memory
616 keep one copy of the namespace (the last one), thus preventing memory
617 leaks from old references while allowing the objects from the last
617 leaks from old references while allowing the objects from the last
618 execution to be accessible.
618 execution to be accessible.
619
619
620 Note: we can not allow the actual FakeModule instances to be deleted,
620 Note: we can not allow the actual FakeModule instances to be deleted,
621 because of how Python tears down modules (it hard-sets all their
621 because of how Python tears down modules (it hard-sets all their
622 references to None without regard for reference counts). This method
622 references to None without regard for reference counts). This method
623 must therefore make a *copy* of the given namespace, to allow the
623 must therefore make a *copy* of the given namespace, to allow the
624 original module's __dict__ to be cleared and reused.
624 original module's __dict__ to be cleared and reused.
625
625
626
626
627 Parameters
627 Parameters
628 ----------
628 ----------
629 ns : a namespace (a dict, typically)
629 ns : a namespace (a dict, typically)
630
630
631 fname : str
631 fname : str
632 Filename associated with the namespace.
632 Filename associated with the namespace.
633
633
634 Examples
634 Examples
635 --------
635 --------
636
636
637 In [10]: import IPython
637 In [10]: import IPython
638
638
639 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
639 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
640
640
641 In [12]: IPython.__file__ in _ip._main_ns_cache
641 In [12]: IPython.__file__ in _ip._main_ns_cache
642 Out[12]: True
642 Out[12]: True
643 """
643 """
644 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
644 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
645
645
646 def clear_main_mod_cache(self):
646 def clear_main_mod_cache(self):
647 """Clear the cache of main modules.
647 """Clear the cache of main modules.
648
648
649 Mainly for use by utilities like %reset.
649 Mainly for use by utilities like %reset.
650
650
651 Examples
651 Examples
652 --------
652 --------
653
653
654 In [15]: import IPython
654 In [15]: import IPython
655
655
656 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
656 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
657
657
658 In [17]: len(_ip._main_ns_cache) > 0
658 In [17]: len(_ip._main_ns_cache) > 0
659 Out[17]: True
659 Out[17]: True
660
660
661 In [18]: _ip.clear_main_mod_cache()
661 In [18]: _ip.clear_main_mod_cache()
662
662
663 In [19]: len(_ip._main_ns_cache) == 0
663 In [19]: len(_ip._main_ns_cache) == 0
664 Out[19]: True
664 Out[19]: True
665 """
665 """
666 self._main_ns_cache.clear()
666 self._main_ns_cache.clear()
667
667
668 #-------------------------------------------------------------------------
668 #-------------------------------------------------------------------------
669 # Things related to debugging
669 # Things related to debugging
670 #-------------------------------------------------------------------------
670 #-------------------------------------------------------------------------
671
671
672 def init_pdb(self):
672 def init_pdb(self):
673 # Set calling of pdb on exceptions
673 # Set calling of pdb on exceptions
674 # self.call_pdb is a property
674 # self.call_pdb is a property
675 self.call_pdb = self.pdb
675 self.call_pdb = self.pdb
676
676
677 def _get_call_pdb(self):
677 def _get_call_pdb(self):
678 return self._call_pdb
678 return self._call_pdb
679
679
680 def _set_call_pdb(self,val):
680 def _set_call_pdb(self,val):
681
681
682 if val not in (0,1,False,True):
682 if val not in (0,1,False,True):
683 raise ValueError,'new call_pdb value must be boolean'
683 raise ValueError,'new call_pdb value must be boolean'
684
684
685 # store value in instance
685 # store value in instance
686 self._call_pdb = val
686 self._call_pdb = val
687
687
688 # notify the actual exception handlers
688 # notify the actual exception handlers
689 self.InteractiveTB.call_pdb = val
689 self.InteractiveTB.call_pdb = val
690
690
691 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
691 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
692 'Control auto-activation of pdb at exceptions')
692 'Control auto-activation of pdb at exceptions')
693
693
694 def debugger(self,force=False):
694 def debugger(self,force=False):
695 """Call the pydb/pdb debugger.
695 """Call the pydb/pdb debugger.
696
696
697 Keywords:
697 Keywords:
698
698
699 - force(False): by default, this routine checks the instance call_pdb
699 - force(False): by default, this routine checks the instance call_pdb
700 flag and does not actually invoke the debugger if the flag is false.
700 flag and does not actually invoke the debugger if the flag is false.
701 The 'force' option forces the debugger to activate even if the flag
701 The 'force' option forces the debugger to activate even if the flag
702 is false.
702 is false.
703 """
703 """
704
704
705 if not (force or self.call_pdb):
705 if not (force or self.call_pdb):
706 return
706 return
707
707
708 if not hasattr(sys,'last_traceback'):
708 if not hasattr(sys,'last_traceback'):
709 error('No traceback has been produced, nothing to debug.')
709 error('No traceback has been produced, nothing to debug.')
710 return
710 return
711
711
712 # use pydb if available
712 # use pydb if available
713 if debugger.has_pydb:
713 if debugger.has_pydb:
714 from pydb import pm
714 from pydb import pm
715 else:
715 else:
716 # fallback to our internal debugger
716 # fallback to our internal debugger
717 pm = lambda : self.InteractiveTB.debugger(force=True)
717 pm = lambda : self.InteractiveTB.debugger(force=True)
718 self.history_saving_wrapper(pm)()
718 self.history_saving_wrapper(pm)()
719
719
720 #-------------------------------------------------------------------------
720 #-------------------------------------------------------------------------
721 # Things related to IPython's various namespaces
721 # Things related to IPython's various namespaces
722 #-------------------------------------------------------------------------
722 #-------------------------------------------------------------------------
723
723
724 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
724 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
725 # Create the namespace where the user will operate. user_ns is
725 # Create the namespace where the user will operate. user_ns is
726 # normally the only one used, and it is passed to the exec calls as
726 # normally the only one used, and it is passed to the exec calls as
727 # the locals argument. But we do carry a user_global_ns namespace
727 # the locals argument. But we do carry a user_global_ns namespace
728 # given as the exec 'globals' argument, This is useful in embedding
728 # given as the exec 'globals' argument, This is useful in embedding
729 # situations where the ipython shell opens in a context where the
729 # situations where the ipython shell opens in a context where the
730 # distinction between locals and globals is meaningful. For
730 # distinction between locals and globals is meaningful. For
731 # non-embedded contexts, it is just the same object as the user_ns dict.
731 # non-embedded contexts, it is just the same object as the user_ns dict.
732
732
733 # FIXME. For some strange reason, __builtins__ is showing up at user
733 # FIXME. For some strange reason, __builtins__ is showing up at user
734 # level as a dict instead of a module. This is a manual fix, but I
734 # level as a dict instead of a module. This is a manual fix, but I
735 # should really track down where the problem is coming from. Alex
735 # should really track down where the problem is coming from. Alex
736 # Schmolck reported this problem first.
736 # Schmolck reported this problem first.
737
737
738 # A useful post by Alex Martelli on this topic:
738 # A useful post by Alex Martelli on this topic:
739 # Re: inconsistent value from __builtins__
739 # Re: inconsistent value from __builtins__
740 # Von: Alex Martelli <aleaxit@yahoo.com>
740 # Von: Alex Martelli <aleaxit@yahoo.com>
741 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
741 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
742 # Gruppen: comp.lang.python
742 # Gruppen: comp.lang.python
743
743
744 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
744 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
745 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
745 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
746 # > <type 'dict'>
746 # > <type 'dict'>
747 # > >>> print type(__builtins__)
747 # > >>> print type(__builtins__)
748 # > <type 'module'>
748 # > <type 'module'>
749 # > Is this difference in return value intentional?
749 # > Is this difference in return value intentional?
750
750
751 # Well, it's documented that '__builtins__' can be either a dictionary
751 # Well, it's documented that '__builtins__' can be either a dictionary
752 # or a module, and it's been that way for a long time. Whether it's
752 # or a module, and it's been that way for a long time. Whether it's
753 # intentional (or sensible), I don't know. In any case, the idea is
753 # intentional (or sensible), I don't know. In any case, the idea is
754 # that if you need to access the built-in namespace directly, you
754 # that if you need to access the built-in namespace directly, you
755 # should start with "import __builtin__" (note, no 's') which will
755 # should start with "import __builtin__" (note, no 's') which will
756 # definitely give you a module. Yeah, it's somewhat confusing:-(.
756 # definitely give you a module. Yeah, it's somewhat confusing:-(.
757
757
758 # These routines return properly built dicts as needed by the rest of
758 # These routines return properly built dicts as needed by the rest of
759 # the code, and can also be used by extension writers to generate
759 # the code, and can also be used by extension writers to generate
760 # properly initialized namespaces.
760 # properly initialized namespaces.
761 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
761 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
762 user_global_ns)
762 user_global_ns)
763
763
764 # Assign namespaces
764 # Assign namespaces
765 # This is the namespace where all normal user variables live
765 # This is the namespace where all normal user variables live
766 self.user_ns = user_ns
766 self.user_ns = user_ns
767 self.user_global_ns = user_global_ns
767 self.user_global_ns = user_global_ns
768
768
769 # An auxiliary namespace that checks what parts of the user_ns were
769 # An auxiliary namespace that checks what parts of the user_ns were
770 # loaded at startup, so we can list later only variables defined in
770 # loaded at startup, so we can list later only variables defined in
771 # actual interactive use. Since it is always a subset of user_ns, it
771 # actual interactive use. Since it is always a subset of user_ns, it
772 # doesn't need to be separately tracked in the ns_table.
772 # doesn't need to be separately tracked in the ns_table.
773 self.user_ns_hidden = {}
773 self.user_ns_hidden = {}
774
774
775 # A namespace to keep track of internal data structures to prevent
775 # A namespace to keep track of internal data structures to prevent
776 # them from cluttering user-visible stuff. Will be updated later
776 # them from cluttering user-visible stuff. Will be updated later
777 self.internal_ns = {}
777 self.internal_ns = {}
778
778
779 # Now that FakeModule produces a real module, we've run into a nasty
779 # Now that FakeModule produces a real module, we've run into a nasty
780 # problem: after script execution (via %run), the module where the user
780 # problem: after script execution (via %run), the module where the user
781 # code ran is deleted. Now that this object is a true module (needed
781 # code ran is deleted. Now that this object is a true module (needed
782 # so docetst and other tools work correctly), the Python module
782 # so docetst and other tools work correctly), the Python module
783 # teardown mechanism runs over it, and sets to None every variable
783 # teardown mechanism runs over it, and sets to None every variable
784 # present in that module. Top-level references to objects from the
784 # present in that module. Top-level references to objects from the
785 # script survive, because the user_ns is updated with them. However,
785 # script survive, because the user_ns is updated with them. However,
786 # calling functions defined in the script that use other things from
786 # calling functions defined in the script that use other things from
787 # the script will fail, because the function's closure had references
787 # the script will fail, because the function's closure had references
788 # to the original objects, which are now all None. So we must protect
788 # to the original objects, which are now all None. So we must protect
789 # these modules from deletion by keeping a cache.
789 # these modules from deletion by keeping a cache.
790 #
790 #
791 # To avoid keeping stale modules around (we only need the one from the
791 # To avoid keeping stale modules around (we only need the one from the
792 # last run), we use a dict keyed with the full path to the script, so
792 # last run), we use a dict keyed with the full path to the script, so
793 # only the last version of the module is held in the cache. Note,
793 # only the last version of the module is held in the cache. Note,
794 # however, that we must cache the module *namespace contents* (their
794 # however, that we must cache the module *namespace contents* (their
795 # __dict__). Because if we try to cache the actual modules, old ones
795 # __dict__). Because if we try to cache the actual modules, old ones
796 # (uncached) could be destroyed while still holding references (such as
796 # (uncached) could be destroyed while still holding references (such as
797 # those held by GUI objects that tend to be long-lived)>
797 # those held by GUI objects that tend to be long-lived)>
798 #
798 #
799 # The %reset command will flush this cache. See the cache_main_mod()
799 # The %reset command will flush this cache. See the cache_main_mod()
800 # and clear_main_mod_cache() methods for details on use.
800 # and clear_main_mod_cache() methods for details on use.
801
801
802 # This is the cache used for 'main' namespaces
802 # This is the cache used for 'main' namespaces
803 self._main_ns_cache = {}
803 self._main_ns_cache = {}
804 # And this is the single instance of FakeModule whose __dict__ we keep
804 # And this is the single instance of FakeModule whose __dict__ we keep
805 # copying and clearing for reuse on each %run
805 # copying and clearing for reuse on each %run
806 self._user_main_module = FakeModule()
806 self._user_main_module = FakeModule()
807
807
808 # A table holding all the namespaces IPython deals with, so that
808 # A table holding all the namespaces IPython deals with, so that
809 # introspection facilities can search easily.
809 # introspection facilities can search easily.
810 self.ns_table = {'user':user_ns,
810 self.ns_table = {'user':user_ns,
811 'user_global':user_global_ns,
811 'user_global':user_global_ns,
812 'internal':self.internal_ns,
812 'internal':self.internal_ns,
813 'builtin':__builtin__.__dict__
813 'builtin':__builtin__.__dict__
814 }
814 }
815
815
816 # Similarly, track all namespaces where references can be held and that
816 # Similarly, track all namespaces where references can be held and that
817 # we can safely clear (so it can NOT include builtin). This one can be
817 # we can safely clear (so it can NOT include builtin). This one can be
818 # a simple list.
818 # a simple list.
819 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
819 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
820 self.internal_ns, self._main_ns_cache ]
820 self.internal_ns, self._main_ns_cache ]
821
821
822 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
822 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
823 """Return a valid local and global user interactive namespaces.
823 """Return a valid local and global user interactive namespaces.
824
824
825 This builds a dict with the minimal information needed to operate as a
825 This builds a dict with the minimal information needed to operate as a
826 valid IPython user namespace, which you can pass to the various
826 valid IPython user namespace, which you can pass to the various
827 embedding classes in ipython. The default implementation returns the
827 embedding classes in ipython. The default implementation returns the
828 same dict for both the locals and the globals to allow functions to
828 same dict for both the locals and the globals to allow functions to
829 refer to variables in the namespace. Customized implementations can
829 refer to variables in the namespace. Customized implementations can
830 return different dicts. The locals dictionary can actually be anything
830 return different dicts. The locals dictionary can actually be anything
831 following the basic mapping protocol of a dict, but the globals dict
831 following the basic mapping protocol of a dict, but the globals dict
832 must be a true dict, not even a subclass. It is recommended that any
832 must be a true dict, not even a subclass. It is recommended that any
833 custom object for the locals namespace synchronize with the globals
833 custom object for the locals namespace synchronize with the globals
834 dict somehow.
834 dict somehow.
835
835
836 Raises TypeError if the provided globals namespace is not a true dict.
836 Raises TypeError if the provided globals namespace is not a true dict.
837
837
838 Parameters
838 Parameters
839 ----------
839 ----------
840 user_ns : dict-like, optional
840 user_ns : dict-like, optional
841 The current user namespace. The items in this namespace should
841 The current user namespace. The items in this namespace should
842 be included in the output. If None, an appropriate blank
842 be included in the output. If None, an appropriate blank
843 namespace should be created.
843 namespace should be created.
844 user_global_ns : dict, optional
844 user_global_ns : dict, optional
845 The current user global namespace. The items in this namespace
845 The current user global namespace. The items in this namespace
846 should be included in the output. If None, an appropriate
846 should be included in the output. If None, an appropriate
847 blank namespace should be created.
847 blank namespace should be created.
848
848
849 Returns
849 Returns
850 -------
850 -------
851 A pair of dictionary-like object to be used as the local namespace
851 A pair of dictionary-like object to be used as the local namespace
852 of the interpreter and a dict to be used as the global namespace.
852 of the interpreter and a dict to be used as the global namespace.
853 """
853 """
854
854
855
855
856 # We must ensure that __builtin__ (without the final 's') is always
856 # We must ensure that __builtin__ (without the final 's') is always
857 # available and pointing to the __builtin__ *module*. For more details:
857 # available and pointing to the __builtin__ *module*. For more details:
858 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
858 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
859
859
860 if user_ns is None:
860 if user_ns is None:
861 # Set __name__ to __main__ to better match the behavior of the
861 # Set __name__ to __main__ to better match the behavior of the
862 # normal interpreter.
862 # normal interpreter.
863 user_ns = {'__name__' :'__main__',
863 user_ns = {'__name__' :'__main__',
864 '__builtin__' : __builtin__,
864 '__builtin__' : __builtin__,
865 '__builtins__' : __builtin__,
865 '__builtins__' : __builtin__,
866 }
866 }
867 else:
867 else:
868 user_ns.setdefault('__name__','__main__')
868 user_ns.setdefault('__name__','__main__')
869 user_ns.setdefault('__builtin__',__builtin__)
869 user_ns.setdefault('__builtin__',__builtin__)
870 user_ns.setdefault('__builtins__',__builtin__)
870 user_ns.setdefault('__builtins__',__builtin__)
871
871
872 if user_global_ns is None:
872 if user_global_ns is None:
873 user_global_ns = user_ns
873 user_global_ns = user_ns
874 if type(user_global_ns) is not dict:
874 if type(user_global_ns) is not dict:
875 raise TypeError("user_global_ns must be a true dict; got %r"
875 raise TypeError("user_global_ns must be a true dict; got %r"
876 % type(user_global_ns))
876 % type(user_global_ns))
877
877
878 return user_ns, user_global_ns
878 return user_ns, user_global_ns
879
879
880 def init_sys_modules(self):
880 def init_sys_modules(self):
881 # We need to insert into sys.modules something that looks like a
881 # We need to insert into sys.modules something that looks like a
882 # module but which accesses the IPython namespace, for shelve and
882 # module but which accesses the IPython namespace, for shelve and
883 # pickle to work interactively. Normally they rely on getting
883 # pickle to work interactively. Normally they rely on getting
884 # everything out of __main__, but for embedding purposes each IPython
884 # everything out of __main__, but for embedding purposes each IPython
885 # instance has its own private namespace, so we can't go shoving
885 # instance has its own private namespace, so we can't go shoving
886 # everything into __main__.
886 # everything into __main__.
887
887
888 # note, however, that we should only do this for non-embedded
888 # note, however, that we should only do this for non-embedded
889 # ipythons, which really mimic the __main__.__dict__ with their own
889 # ipythons, which really mimic the __main__.__dict__ with their own
890 # namespace. Embedded instances, on the other hand, should not do
890 # namespace. Embedded instances, on the other hand, should not do
891 # this because they need to manage the user local/global namespaces
891 # this because they need to manage the user local/global namespaces
892 # only, but they live within a 'normal' __main__ (meaning, they
892 # only, but they live within a 'normal' __main__ (meaning, they
893 # shouldn't overtake the execution environment of the script they're
893 # shouldn't overtake the execution environment of the script they're
894 # embedded in).
894 # embedded in).
895
895
896 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
896 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
897
897
898 try:
898 try:
899 main_name = self.user_ns['__name__']
899 main_name = self.user_ns['__name__']
900 except KeyError:
900 except KeyError:
901 raise KeyError('user_ns dictionary MUST have a "__name__" key')
901 raise KeyError('user_ns dictionary MUST have a "__name__" key')
902 else:
902 else:
903 sys.modules[main_name] = FakeModule(self.user_ns)
903 sys.modules[main_name] = FakeModule(self.user_ns)
904
904
905 def init_user_ns(self):
905 def init_user_ns(self):
906 """Initialize all user-visible namespaces to their minimum defaults.
906 """Initialize all user-visible namespaces to their minimum defaults.
907
907
908 Certain history lists are also initialized here, as they effectively
908 Certain history lists are also initialized here, as they effectively
909 act as user namespaces.
909 act as user namespaces.
910
910
911 Notes
911 Notes
912 -----
912 -----
913 All data structures here are only filled in, they are NOT reset by this
913 All data structures here are only filled in, they are NOT reset by this
914 method. If they were not empty before, data will simply be added to
914 method. If they were not empty before, data will simply be added to
915 therm.
915 therm.
916 """
916 """
917 # This function works in two parts: first we put a few things in
917 # This function works in two parts: first we put a few things in
918 # user_ns, and we sync that contents into user_ns_hidden so that these
918 # user_ns, and we sync that contents into user_ns_hidden so that these
919 # initial variables aren't shown by %who. After the sync, we add the
919 # initial variables aren't shown by %who. After the sync, we add the
920 # rest of what we *do* want the user to see with %who even on a new
920 # rest of what we *do* want the user to see with %who even on a new
921 # session (probably nothing, so theye really only see their own stuff)
921 # session (probably nothing, so theye really only see their own stuff)
922
922
923 # The user dict must *always* have a __builtin__ reference to the
923 # The user dict must *always* have a __builtin__ reference to the
924 # Python standard __builtin__ namespace, which must be imported.
924 # Python standard __builtin__ namespace, which must be imported.
925 # This is so that certain operations in prompt evaluation can be
925 # This is so that certain operations in prompt evaluation can be
926 # reliably executed with builtins. Note that we can NOT use
926 # reliably executed with builtins. Note that we can NOT use
927 # __builtins__ (note the 's'), because that can either be a dict or a
927 # __builtins__ (note the 's'), because that can either be a dict or a
928 # module, and can even mutate at runtime, depending on the context
928 # module, and can even mutate at runtime, depending on the context
929 # (Python makes no guarantees on it). In contrast, __builtin__ is
929 # (Python makes no guarantees on it). In contrast, __builtin__ is
930 # always a module object, though it must be explicitly imported.
930 # always a module object, though it must be explicitly imported.
931
931
932 # For more details:
932 # For more details:
933 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
933 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
934 ns = dict(__builtin__ = __builtin__)
934 ns = dict(__builtin__ = __builtin__)
935
935
936 # Put 'help' in the user namespace
936 # Put 'help' in the user namespace
937 try:
937 try:
938 from site import _Helper
938 from site import _Helper
939 ns['help'] = _Helper()
939 ns['help'] = _Helper()
940 except ImportError:
940 except ImportError:
941 warn('help() not available - check site.py')
941 warn('help() not available - check site.py')
942
942
943 # make global variables for user access to the histories
943 # make global variables for user access to the histories
944 ns['_ih'] = self.input_hist
944 ns['_ih'] = self.input_hist
945 ns['_oh'] = self.output_hist
945 ns['_oh'] = self.output_hist
946 ns['_dh'] = self.dir_hist
946 ns['_dh'] = self.dir_hist
947
947
948 ns['_sh'] = shadowns
948 ns['_sh'] = shadowns
949
949
950 # user aliases to input and output histories. These shouldn't show up
950 # user aliases to input and output histories. These shouldn't show up
951 # in %who, as they can have very large reprs.
951 # in %who, as they can have very large reprs.
952 ns['In'] = self.input_hist
952 ns['In'] = self.input_hist
953 ns['Out'] = self.output_hist
953 ns['Out'] = self.output_hist
954
954
955 # Store myself as the public api!!!
955 # Store myself as the public api!!!
956 ns['get_ipython'] = self.get_ipython
956 ns['get_ipython'] = self.get_ipython
957
957
958 # Sync what we've added so far to user_ns_hidden so these aren't seen
958 # Sync what we've added so far to user_ns_hidden so these aren't seen
959 # by %who
959 # by %who
960 self.user_ns_hidden.update(ns)
960 self.user_ns_hidden.update(ns)
961
961
962 # Anything put into ns now would show up in %who. Think twice before
962 # Anything put into ns now would show up in %who. Think twice before
963 # putting anything here, as we really want %who to show the user their
963 # putting anything here, as we really want %who to show the user their
964 # stuff, not our variables.
964 # stuff, not our variables.
965
965
966 # Finally, update the real user's namespace
966 # Finally, update the real user's namespace
967 self.user_ns.update(ns)
967 self.user_ns.update(ns)
968
968
969 def reset(self):
969 def reset(self):
970 """Clear all internal namespaces.
970 """Clear all internal namespaces.
971
971
972 Note that this is much more aggressive than %reset, since it clears
972 Note that this is much more aggressive than %reset, since it clears
973 fully all namespaces, as well as all input/output lists.
973 fully all namespaces, as well as all input/output lists.
974 """
974 """
975 # Clear histories
975 # Clear histories
976 self.history_manager.reset()
976 self.history_manager.reset()
977
977
978 # Reset counter used to index all histories
978 # Reset counter used to index all histories
979 self.execution_count = 0
979 self.execution_count = 0
980
980
981 # Restore the user namespaces to minimal usability
981 # Restore the user namespaces to minimal usability
982 for ns in self.ns_refs_table:
982 for ns in self.ns_refs_table:
983 ns.clear()
983 ns.clear()
984 self.init_user_ns()
984 self.init_user_ns()
985
985
986 # Restore the default and user aliases
986 # Restore the default and user aliases
987 self.alias_manager.clear_aliases()
987 self.alias_manager.clear_aliases()
988 self.alias_manager.init_aliases()
988 self.alias_manager.init_aliases()
989
989
990 def reset_selective(self, regex=None):
990 def reset_selective(self, regex=None):
991 """Clear selective variables from internal namespaces based on a
991 """Clear selective variables from internal namespaces based on a
992 specified regular expression.
992 specified regular expression.
993
993
994 Parameters
994 Parameters
995 ----------
995 ----------
996 regex : string or compiled pattern, optional
996 regex : string or compiled pattern, optional
997 A regular expression pattern that will be used in searching
997 A regular expression pattern that will be used in searching
998 variable names in the users namespaces.
998 variable names in the users namespaces.
999 """
999 """
1000 if regex is not None:
1000 if regex is not None:
1001 try:
1001 try:
1002 m = re.compile(regex)
1002 m = re.compile(regex)
1003 except TypeError:
1003 except TypeError:
1004 raise TypeError('regex must be a string or compiled pattern')
1004 raise TypeError('regex must be a string or compiled pattern')
1005 # Search for keys in each namespace that match the given regex
1005 # Search for keys in each namespace that match the given regex
1006 # If a match is found, delete the key/value pair.
1006 # If a match is found, delete the key/value pair.
1007 for ns in self.ns_refs_table:
1007 for ns in self.ns_refs_table:
1008 for var in ns:
1008 for var in ns:
1009 if m.search(var):
1009 if m.search(var):
1010 del ns[var]
1010 del ns[var]
1011
1011
1012 def push(self, variables, interactive=True):
1012 def push(self, variables, interactive=True):
1013 """Inject a group of variables into the IPython user namespace.
1013 """Inject a group of variables into the IPython user namespace.
1014
1014
1015 Parameters
1015 Parameters
1016 ----------
1016 ----------
1017 variables : dict, str or list/tuple of str
1017 variables : dict, str or list/tuple of str
1018 The variables to inject into the user's namespace. If a dict, a
1018 The variables to inject into the user's namespace. If a dict, a
1019 simple update is done. If a str, the string is assumed to have
1019 simple update is done. If a str, the string is assumed to have
1020 variable names separated by spaces. A list/tuple of str can also
1020 variable names separated by spaces. A list/tuple of str can also
1021 be used to give the variable names. If just the variable names are
1021 be used to give the variable names. If just the variable names are
1022 give (list/tuple/str) then the variable values looked up in the
1022 give (list/tuple/str) then the variable values looked up in the
1023 callers frame.
1023 callers frame.
1024 interactive : bool
1024 interactive : bool
1025 If True (default), the variables will be listed with the ``who``
1025 If True (default), the variables will be listed with the ``who``
1026 magic.
1026 magic.
1027 """
1027 """
1028 vdict = None
1028 vdict = None
1029
1029
1030 # We need a dict of name/value pairs to do namespace updates.
1030 # We need a dict of name/value pairs to do namespace updates.
1031 if isinstance(variables, dict):
1031 if isinstance(variables, dict):
1032 vdict = variables
1032 vdict = variables
1033 elif isinstance(variables, (basestring, list, tuple)):
1033 elif isinstance(variables, (basestring, list, tuple)):
1034 if isinstance(variables, basestring):
1034 if isinstance(variables, basestring):
1035 vlist = variables.split()
1035 vlist = variables.split()
1036 else:
1036 else:
1037 vlist = variables
1037 vlist = variables
1038 vdict = {}
1038 vdict = {}
1039 cf = sys._getframe(1)
1039 cf = sys._getframe(1)
1040 for name in vlist:
1040 for name in vlist:
1041 try:
1041 try:
1042 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1042 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1043 except:
1043 except:
1044 print ('Could not get variable %s from %s' %
1044 print ('Could not get variable %s from %s' %
1045 (name,cf.f_code.co_name))
1045 (name,cf.f_code.co_name))
1046 else:
1046 else:
1047 raise ValueError('variables must be a dict/str/list/tuple')
1047 raise ValueError('variables must be a dict/str/list/tuple')
1048
1048
1049 # Propagate variables to user namespace
1049 # Propagate variables to user namespace
1050 self.user_ns.update(vdict)
1050 self.user_ns.update(vdict)
1051
1051
1052 # And configure interactive visibility
1052 # And configure interactive visibility
1053 config_ns = self.user_ns_hidden
1053 config_ns = self.user_ns_hidden
1054 if interactive:
1054 if interactive:
1055 for name, val in vdict.iteritems():
1055 for name, val in vdict.iteritems():
1056 config_ns.pop(name, None)
1056 config_ns.pop(name, None)
1057 else:
1057 else:
1058 for name,val in vdict.iteritems():
1058 for name,val in vdict.iteritems():
1059 config_ns[name] = val
1059 config_ns[name] = val
1060
1060
1061 #-------------------------------------------------------------------------
1061 #-------------------------------------------------------------------------
1062 # Things related to object introspection
1062 # Things related to object introspection
1063 #-------------------------------------------------------------------------
1063 #-------------------------------------------------------------------------
1064
1064
1065 def _ofind(self, oname, namespaces=None):
1065 def _ofind(self, oname, namespaces=None):
1066 """Find an object in the available namespaces.
1066 """Find an object in the available namespaces.
1067
1067
1068 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1068 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1069
1069
1070 Has special code to detect magic functions.
1070 Has special code to detect magic functions.
1071 """
1071 """
1072 #oname = oname.strip()
1072 #oname = oname.strip()
1073 #print '1- oname: <%r>' % oname # dbg
1073 #print '1- oname: <%r>' % oname # dbg
1074 try:
1074 try:
1075 oname = oname.strip().encode('ascii')
1075 oname = oname.strip().encode('ascii')
1076 #print '2- oname: <%r>' % oname # dbg
1076 #print '2- oname: <%r>' % oname # dbg
1077 except UnicodeEncodeError:
1077 except UnicodeEncodeError:
1078 print 'Python identifiers can only contain ascii characters.'
1078 print 'Python identifiers can only contain ascii characters.'
1079 return dict(found=False)
1079 return dict(found=False)
1080
1080
1081 alias_ns = None
1081 alias_ns = None
1082 if namespaces is None:
1082 if namespaces is None:
1083 # Namespaces to search in:
1083 # Namespaces to search in:
1084 # Put them in a list. The order is important so that we
1084 # Put them in a list. The order is important so that we
1085 # find things in the same order that Python finds them.
1085 # find things in the same order that Python finds them.
1086 namespaces = [ ('Interactive', self.user_ns),
1086 namespaces = [ ('Interactive', self.user_ns),
1087 ('IPython internal', self.internal_ns),
1087 ('IPython internal', self.internal_ns),
1088 ('Python builtin', __builtin__.__dict__),
1088 ('Python builtin', __builtin__.__dict__),
1089 ('Alias', self.alias_manager.alias_table),
1089 ('Alias', self.alias_manager.alias_table),
1090 ]
1090 ]
1091 alias_ns = self.alias_manager.alias_table
1091 alias_ns = self.alias_manager.alias_table
1092
1092
1093 # initialize results to 'null'
1093 # initialize results to 'null'
1094 found = False; obj = None; ospace = None; ds = None;
1094 found = False; obj = None; ospace = None; ds = None;
1095 ismagic = False; isalias = False; parent = None
1095 ismagic = False; isalias = False; parent = None
1096
1096
1097 # We need to special-case 'print', which as of python2.6 registers as a
1097 # We need to special-case 'print', which as of python2.6 registers as a
1098 # function but should only be treated as one if print_function was
1098 # function but should only be treated as one if print_function was
1099 # loaded with a future import. In this case, just bail.
1099 # loaded with a future import. In this case, just bail.
1100 if (oname == 'print' and not (self.compile.compiler.flags &
1100 if (oname == 'print' and not (self.compile.compiler.flags &
1101 __future__.CO_FUTURE_PRINT_FUNCTION)):
1101 __future__.CO_FUTURE_PRINT_FUNCTION)):
1102 return {'found':found, 'obj':obj, 'namespace':ospace,
1102 return {'found':found, 'obj':obj, 'namespace':ospace,
1103 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1103 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1104
1104
1105 # Look for the given name by splitting it in parts. If the head is
1105 # Look for the given name by splitting it in parts. If the head is
1106 # found, then we look for all the remaining parts as members, and only
1106 # found, then we look for all the remaining parts as members, and only
1107 # declare success if we can find them all.
1107 # declare success if we can find them all.
1108 oname_parts = oname.split('.')
1108 oname_parts = oname.split('.')
1109 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1109 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1110 for nsname,ns in namespaces:
1110 for nsname,ns in namespaces:
1111 try:
1111 try:
1112 obj = ns[oname_head]
1112 obj = ns[oname_head]
1113 except KeyError:
1113 except KeyError:
1114 continue
1114 continue
1115 else:
1115 else:
1116 #print 'oname_rest:', oname_rest # dbg
1116 #print 'oname_rest:', oname_rest # dbg
1117 for part in oname_rest:
1117 for part in oname_rest:
1118 try:
1118 try:
1119 parent = obj
1119 parent = obj
1120 obj = getattr(obj,part)
1120 obj = getattr(obj,part)
1121 except:
1121 except:
1122 # Blanket except b/c some badly implemented objects
1122 # Blanket except b/c some badly implemented objects
1123 # allow __getattr__ to raise exceptions other than
1123 # allow __getattr__ to raise exceptions other than
1124 # AttributeError, which then crashes IPython.
1124 # AttributeError, which then crashes IPython.
1125 break
1125 break
1126 else:
1126 else:
1127 # If we finish the for loop (no break), we got all members
1127 # If we finish the for loop (no break), we got all members
1128 found = True
1128 found = True
1129 ospace = nsname
1129 ospace = nsname
1130 if ns == alias_ns:
1130 if ns == alias_ns:
1131 isalias = True
1131 isalias = True
1132 break # namespace loop
1132 break # namespace loop
1133
1133
1134 # Try to see if it's magic
1134 # Try to see if it's magic
1135 if not found:
1135 if not found:
1136 if oname.startswith(ESC_MAGIC):
1136 if oname.startswith(ESC_MAGIC):
1137 oname = oname[1:]
1137 oname = oname[1:]
1138 obj = getattr(self,'magic_'+oname,None)
1138 obj = getattr(self,'magic_'+oname,None)
1139 if obj is not None:
1139 if obj is not None:
1140 found = True
1140 found = True
1141 ospace = 'IPython internal'
1141 ospace = 'IPython internal'
1142 ismagic = True
1142 ismagic = True
1143
1143
1144 # Last try: special-case some literals like '', [], {}, etc:
1144 # Last try: special-case some literals like '', [], {}, etc:
1145 if not found and oname_head in ["''",'""','[]','{}','()']:
1145 if not found and oname_head in ["''",'""','[]','{}','()']:
1146 obj = eval(oname_head)
1146 obj = eval(oname_head)
1147 found = True
1147 found = True
1148 ospace = 'Interactive'
1148 ospace = 'Interactive'
1149
1149
1150 return {'found':found, 'obj':obj, 'namespace':ospace,
1150 return {'found':found, 'obj':obj, 'namespace':ospace,
1151 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1151 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1152
1152
1153 def _ofind_property(self, oname, info):
1153 def _ofind_property(self, oname, info):
1154 """Second part of object finding, to look for property details."""
1154 """Second part of object finding, to look for property details."""
1155 if info.found:
1155 if info.found:
1156 # Get the docstring of the class property if it exists.
1156 # Get the docstring of the class property if it exists.
1157 path = oname.split('.')
1157 path = oname.split('.')
1158 root = '.'.join(path[:-1])
1158 root = '.'.join(path[:-1])
1159 if info.parent is not None:
1159 if info.parent is not None:
1160 try:
1160 try:
1161 target = getattr(info.parent, '__class__')
1161 target = getattr(info.parent, '__class__')
1162 # The object belongs to a class instance.
1162 # The object belongs to a class instance.
1163 try:
1163 try:
1164 target = getattr(target, path[-1])
1164 target = getattr(target, path[-1])
1165 # The class defines the object.
1165 # The class defines the object.
1166 if isinstance(target, property):
1166 if isinstance(target, property):
1167 oname = root + '.__class__.' + path[-1]
1167 oname = root + '.__class__.' + path[-1]
1168 info = Struct(self._ofind(oname))
1168 info = Struct(self._ofind(oname))
1169 except AttributeError: pass
1169 except AttributeError: pass
1170 except AttributeError: pass
1170 except AttributeError: pass
1171
1171
1172 # We return either the new info or the unmodified input if the object
1172 # We return either the new info or the unmodified input if the object
1173 # hadn't been found
1173 # hadn't been found
1174 return info
1174 return info
1175
1175
1176 def _object_find(self, oname, namespaces=None):
1176 def _object_find(self, oname, namespaces=None):
1177 """Find an object and return a struct with info about it."""
1177 """Find an object and return a struct with info about it."""
1178 inf = Struct(self._ofind(oname, namespaces))
1178 inf = Struct(self._ofind(oname, namespaces))
1179 return Struct(self._ofind_property(oname, inf))
1179 return Struct(self._ofind_property(oname, inf))
1180
1180
1181 def _inspect(self, meth, oname, namespaces=None, **kw):
1181 def _inspect(self, meth, oname, namespaces=None, **kw):
1182 """Generic interface to the inspector system.
1182 """Generic interface to the inspector system.
1183
1183
1184 This function is meant to be called by pdef, pdoc & friends."""
1184 This function is meant to be called by pdef, pdoc & friends."""
1185 info = self._object_find(oname)
1185 info = self._object_find(oname)
1186 if info.found:
1186 if info.found:
1187 pmethod = getattr(self.inspector, meth)
1187 pmethod = getattr(self.inspector, meth)
1188 formatter = format_screen if info.ismagic else None
1188 formatter = format_screen if info.ismagic else None
1189 if meth == 'pdoc':
1189 if meth == 'pdoc':
1190 pmethod(info.obj, oname, formatter)
1190 pmethod(info.obj, oname, formatter)
1191 elif meth == 'pinfo':
1191 elif meth == 'pinfo':
1192 pmethod(info.obj, oname, formatter, info, **kw)
1192 pmethod(info.obj, oname, formatter, info, **kw)
1193 else:
1193 else:
1194 pmethod(info.obj, oname)
1194 pmethod(info.obj, oname)
1195 else:
1195 else:
1196 print 'Object `%s` not found.' % oname
1196 print 'Object `%s` not found.' % oname
1197 return 'not found' # so callers can take other action
1197 return 'not found' # so callers can take other action
1198
1198
1199 def object_inspect(self, oname):
1199 def object_inspect(self, oname):
1200 info = self._object_find(oname)
1200 info = self._object_find(oname)
1201 if info.found:
1201 if info.found:
1202 return self.inspector.info(info.obj, oname, info=info)
1202 return self.inspector.info(info.obj, oname, info=info)
1203 else:
1203 else:
1204 return oinspect.object_info(name=oname, found=False)
1204 return oinspect.object_info(name=oname, found=False)
1205
1205
1206 #-------------------------------------------------------------------------
1206 #-------------------------------------------------------------------------
1207 # Things related to history management
1207 # Things related to history management
1208 #-------------------------------------------------------------------------
1208 #-------------------------------------------------------------------------
1209
1209
1210 def init_history(self):
1210 def init_history(self):
1211 self.history_manager = HistoryManager(shell=self)
1211 self.history_manager = HistoryManager(shell=self)
1212
1212
1213 def savehist(self):
1213 def savehist(self):
1214 """Save input history to a file (via readline library)."""
1214 """Save input history to a file (via readline library)."""
1215 self.history_manager.save_hist()
1215 self.history_manager.save_hist()
1216
1216
1217 def reloadhist(self):
1217 def reloadhist(self):
1218 """Reload the input history from disk file."""
1218 """Reload the input history from disk file."""
1219 self.history_manager.reload_hist()
1219 self.history_manager.reload_hist()
1220
1220
1221 def history_saving_wrapper(self, func):
1221 def history_saving_wrapper(self, func):
1222 """ Wrap func for readline history saving
1222 """ Wrap func for readline history saving
1223
1223
1224 Convert func into callable that saves & restores
1224 Convert func into callable that saves & restores
1225 history around the call """
1225 history around the call """
1226
1226
1227 if self.has_readline:
1227 if self.has_readline:
1228 from IPython.utils import rlineimpl as readline
1228 from IPython.utils import rlineimpl as readline
1229 else:
1229 else:
1230 return func
1230 return func
1231
1231
1232 def wrapper():
1232 def wrapper():
1233 self.savehist()
1233 self.savehist()
1234 try:
1234 try:
1235 func()
1235 func()
1236 finally:
1236 finally:
1237 readline.read_history_file(self.histfile)
1237 readline.read_history_file(self.histfile)
1238 return wrapper
1238 return wrapper
1239
1239
1240 #-------------------------------------------------------------------------
1240 #-------------------------------------------------------------------------
1241 # Things related to exception handling and tracebacks (not debugging)
1241 # Things related to exception handling and tracebacks (not debugging)
1242 #-------------------------------------------------------------------------
1242 #-------------------------------------------------------------------------
1243
1243
1244 def init_traceback_handlers(self, custom_exceptions):
1244 def init_traceback_handlers(self, custom_exceptions):
1245 # Syntax error handler.
1245 # Syntax error handler.
1246 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1246 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1247
1247
1248 # The interactive one is initialized with an offset, meaning we always
1248 # The interactive one is initialized with an offset, meaning we always
1249 # want to remove the topmost item in the traceback, which is our own
1249 # want to remove the topmost item in the traceback, which is our own
1250 # internal code. Valid modes: ['Plain','Context','Verbose']
1250 # internal code. Valid modes: ['Plain','Context','Verbose']
1251 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1251 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1252 color_scheme='NoColor',
1252 color_scheme='NoColor',
1253 tb_offset = 1)
1253 tb_offset = 1)
1254
1254
1255 # The instance will store a pointer to the system-wide exception hook,
1255 # The instance will store a pointer to the system-wide exception hook,
1256 # so that runtime code (such as magics) can access it. This is because
1256 # so that runtime code (such as magics) can access it. This is because
1257 # during the read-eval loop, it may get temporarily overwritten.
1257 # during the read-eval loop, it may get temporarily overwritten.
1258 self.sys_excepthook = sys.excepthook
1258 self.sys_excepthook = sys.excepthook
1259
1259
1260 # and add any custom exception handlers the user may have specified
1260 # and add any custom exception handlers the user may have specified
1261 self.set_custom_exc(*custom_exceptions)
1261 self.set_custom_exc(*custom_exceptions)
1262
1262
1263 # Set the exception mode
1263 # Set the exception mode
1264 self.InteractiveTB.set_mode(mode=self.xmode)
1264 self.InteractiveTB.set_mode(mode=self.xmode)
1265
1265
1266 def set_custom_exc(self, exc_tuple, handler):
1266 def set_custom_exc(self, exc_tuple, handler):
1267 """set_custom_exc(exc_tuple,handler)
1267 """set_custom_exc(exc_tuple,handler)
1268
1268
1269 Set a custom exception handler, which will be called if any of the
1269 Set a custom exception handler, which will be called if any of the
1270 exceptions in exc_tuple occur in the mainloop (specifically, in the
1270 exceptions in exc_tuple occur in the mainloop (specifically, in the
1271 runcode() method.
1271 runcode() method.
1272
1272
1273 Inputs:
1273 Inputs:
1274
1274
1275 - exc_tuple: a *tuple* of valid exceptions to call the defined
1275 - exc_tuple: a *tuple* of valid exceptions to call the defined
1276 handler for. It is very important that you use a tuple, and NOT A
1276 handler for. It is very important that you use a tuple, and NOT A
1277 LIST here, because of the way Python's except statement works. If
1277 LIST here, because of the way Python's except statement works. If
1278 you only want to trap a single exception, use a singleton tuple:
1278 you only want to trap a single exception, use a singleton tuple:
1279
1279
1280 exc_tuple == (MyCustomException,)
1280 exc_tuple == (MyCustomException,)
1281
1281
1282 - handler: this must be defined as a function with the following
1282 - handler: this must be defined as a function with the following
1283 basic interface::
1283 basic interface::
1284
1284
1285 def my_handler(self, etype, value, tb, tb_offset=None)
1285 def my_handler(self, etype, value, tb, tb_offset=None)
1286 ...
1286 ...
1287 # The return value must be
1287 # The return value must be
1288 return structured_traceback
1288 return structured_traceback
1289
1289
1290 This will be made into an instance method (via new.instancemethod)
1290 This will be made into an instance method (via new.instancemethod)
1291 of IPython itself, and it will be called if any of the exceptions
1291 of IPython itself, and it will be called if any of the exceptions
1292 listed in the exc_tuple are caught. If the handler is None, an
1292 listed in the exc_tuple are caught. If the handler is None, an
1293 internal basic one is used, which just prints basic info.
1293 internal basic one is used, which just prints basic info.
1294
1294
1295 WARNING: by putting in your own exception handler into IPython's main
1295 WARNING: by putting in your own exception handler into IPython's main
1296 execution loop, you run a very good chance of nasty crashes. This
1296 execution loop, you run a very good chance of nasty crashes. This
1297 facility should only be used if you really know what you are doing."""
1297 facility should only be used if you really know what you are doing."""
1298
1298
1299 assert type(exc_tuple)==type(()) , \
1299 assert type(exc_tuple)==type(()) , \
1300 "The custom exceptions must be given AS A TUPLE."
1300 "The custom exceptions must be given AS A TUPLE."
1301
1301
1302 def dummy_handler(self,etype,value,tb):
1302 def dummy_handler(self,etype,value,tb):
1303 print '*** Simple custom exception handler ***'
1303 print '*** Simple custom exception handler ***'
1304 print 'Exception type :',etype
1304 print 'Exception type :',etype
1305 print 'Exception value:',value
1305 print 'Exception value:',value
1306 print 'Traceback :',tb
1306 print 'Traceback :',tb
1307 print 'Source code :','\n'.join(self.buffer)
1307 print 'Source code :','\n'.join(self.buffer)
1308
1308
1309 if handler is None: handler = dummy_handler
1309 if handler is None: handler = dummy_handler
1310
1310
1311 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1311 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1312 self.custom_exceptions = exc_tuple
1312 self.custom_exceptions = exc_tuple
1313
1313
1314 def excepthook(self, etype, value, tb):
1314 def excepthook(self, etype, value, tb):
1315 """One more defense for GUI apps that call sys.excepthook.
1315 """One more defense for GUI apps that call sys.excepthook.
1316
1316
1317 GUI frameworks like wxPython trap exceptions and call
1317 GUI frameworks like wxPython trap exceptions and call
1318 sys.excepthook themselves. I guess this is a feature that
1318 sys.excepthook themselves. I guess this is a feature that
1319 enables them to keep running after exceptions that would
1319 enables them to keep running after exceptions that would
1320 otherwise kill their mainloop. This is a bother for IPython
1320 otherwise kill their mainloop. This is a bother for IPython
1321 which excepts to catch all of the program exceptions with a try:
1321 which excepts to catch all of the program exceptions with a try:
1322 except: statement.
1322 except: statement.
1323
1323
1324 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1324 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1325 any app directly invokes sys.excepthook, it will look to the user like
1325 any app directly invokes sys.excepthook, it will look to the user like
1326 IPython crashed. In order to work around this, we can disable the
1326 IPython crashed. In order to work around this, we can disable the
1327 CrashHandler and replace it with this excepthook instead, which prints a
1327 CrashHandler and replace it with this excepthook instead, which prints a
1328 regular traceback using our InteractiveTB. In this fashion, apps which
1328 regular traceback using our InteractiveTB. In this fashion, apps which
1329 call sys.excepthook will generate a regular-looking exception from
1329 call sys.excepthook will generate a regular-looking exception from
1330 IPython, and the CrashHandler will only be triggered by real IPython
1330 IPython, and the CrashHandler will only be triggered by real IPython
1331 crashes.
1331 crashes.
1332
1332
1333 This hook should be used sparingly, only in places which are not likely
1333 This hook should be used sparingly, only in places which are not likely
1334 to be true IPython errors.
1334 to be true IPython errors.
1335 """
1335 """
1336 self.showtraceback((etype,value,tb),tb_offset=0)
1336 self.showtraceback((etype,value,tb),tb_offset=0)
1337
1337
1338 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1338 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1339 exception_only=False):
1339 exception_only=False):
1340 """Display the exception that just occurred.
1340 """Display the exception that just occurred.
1341
1341
1342 If nothing is known about the exception, this is the method which
1342 If nothing is known about the exception, this is the method which
1343 should be used throughout the code for presenting user tracebacks,
1343 should be used throughout the code for presenting user tracebacks,
1344 rather than directly invoking the InteractiveTB object.
1344 rather than directly invoking the InteractiveTB object.
1345
1345
1346 A specific showsyntaxerror() also exists, but this method can take
1346 A specific showsyntaxerror() also exists, but this method can take
1347 care of calling it if needed, so unless you are explicitly catching a
1347 care of calling it if needed, so unless you are explicitly catching a
1348 SyntaxError exception, don't try to analyze the stack manually and
1348 SyntaxError exception, don't try to analyze the stack manually and
1349 simply call this method."""
1349 simply call this method."""
1350
1350
1351 try:
1351 try:
1352 if exc_tuple is None:
1352 if exc_tuple is None:
1353 etype, value, tb = sys.exc_info()
1353 etype, value, tb = sys.exc_info()
1354 else:
1354 else:
1355 etype, value, tb = exc_tuple
1355 etype, value, tb = exc_tuple
1356
1356
1357 if etype is None:
1357 if etype is None:
1358 if hasattr(sys, 'last_type'):
1358 if hasattr(sys, 'last_type'):
1359 etype, value, tb = sys.last_type, sys.last_value, \
1359 etype, value, tb = sys.last_type, sys.last_value, \
1360 sys.last_traceback
1360 sys.last_traceback
1361 else:
1361 else:
1362 self.write_err('No traceback available to show.\n')
1362 self.write_err('No traceback available to show.\n')
1363 return
1363 return
1364
1364
1365 if etype is SyntaxError:
1365 if etype is SyntaxError:
1366 # Though this won't be called by syntax errors in the input
1366 # Though this won't be called by syntax errors in the input
1367 # line, there may be SyntaxError cases whith imported code.
1367 # line, there may be SyntaxError cases whith imported code.
1368 self.showsyntaxerror(filename)
1368 self.showsyntaxerror(filename)
1369 elif etype is UsageError:
1369 elif etype is UsageError:
1370 print "UsageError:", value
1370 print "UsageError:", value
1371 else:
1371 else:
1372 # WARNING: these variables are somewhat deprecated and not
1372 # WARNING: these variables are somewhat deprecated and not
1373 # necessarily safe to use in a threaded environment, but tools
1373 # necessarily safe to use in a threaded environment, but tools
1374 # like pdb depend on their existence, so let's set them. If we
1374 # like pdb depend on their existence, so let's set them. If we
1375 # find problems in the field, we'll need to revisit their use.
1375 # find problems in the field, we'll need to revisit their use.
1376 sys.last_type = etype
1376 sys.last_type = etype
1377 sys.last_value = value
1377 sys.last_value = value
1378 sys.last_traceback = tb
1378 sys.last_traceback = tb
1379
1379
1380 if etype in self.custom_exceptions:
1380 if etype in self.custom_exceptions:
1381 # FIXME: Old custom traceback objects may just return a
1381 # FIXME: Old custom traceback objects may just return a
1382 # string, in that case we just put it into a list
1382 # string, in that case we just put it into a list
1383 stb = self.CustomTB(etype, value, tb, tb_offset)
1383 stb = self.CustomTB(etype, value, tb, tb_offset)
1384 if isinstance(ctb, basestring):
1384 if isinstance(ctb, basestring):
1385 stb = [stb]
1385 stb = [stb]
1386 else:
1386 else:
1387 if exception_only:
1387 if exception_only:
1388 stb = ['An exception has occurred, use %tb to see '
1388 stb = ['An exception has occurred, use %tb to see '
1389 'the full traceback.\n']
1389 'the full traceback.\n']
1390 stb.extend(self.InteractiveTB.get_exception_only(etype,
1390 stb.extend(self.InteractiveTB.get_exception_only(etype,
1391 value))
1391 value))
1392 else:
1392 else:
1393 stb = self.InteractiveTB.structured_traceback(etype,
1393 stb = self.InteractiveTB.structured_traceback(etype,
1394 value, tb, tb_offset=tb_offset)
1394 value, tb, tb_offset=tb_offset)
1395 # FIXME: the pdb calling should be done by us, not by
1395 # FIXME: the pdb calling should be done by us, not by
1396 # the code computing the traceback.
1396 # the code computing the traceback.
1397 if self.InteractiveTB.call_pdb:
1397 if self.InteractiveTB.call_pdb:
1398 # pdb mucks up readline, fix it back
1398 # pdb mucks up readline, fix it back
1399 self.set_readline_completer()
1399 self.set_readline_completer()
1400
1400
1401 # Actually show the traceback
1401 # Actually show the traceback
1402 self._showtraceback(etype, value, stb)
1402 self._showtraceback(etype, value, stb)
1403
1403
1404 except KeyboardInterrupt:
1404 except KeyboardInterrupt:
1405 self.write_err("\nKeyboardInterrupt\n")
1405 self.write_err("\nKeyboardInterrupt\n")
1406
1406
1407 def _showtraceback(self, etype, evalue, stb):
1407 def _showtraceback(self, etype, evalue, stb):
1408 """Actually show a traceback.
1408 """Actually show a traceback.
1409
1409
1410 Subclasses may override this method to put the traceback on a different
1410 Subclasses may override this method to put the traceback on a different
1411 place, like a side channel.
1411 place, like a side channel.
1412 """
1412 """
1413 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1413 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1414
1414
1415 def showsyntaxerror(self, filename=None):
1415 def showsyntaxerror(self, filename=None):
1416 """Display the syntax error that just occurred.
1416 """Display the syntax error that just occurred.
1417
1417
1418 This doesn't display a stack trace because there isn't one.
1418 This doesn't display a stack trace because there isn't one.
1419
1419
1420 If a filename is given, it is stuffed in the exception instead
1420 If a filename is given, it is stuffed in the exception instead
1421 of what was there before (because Python's parser always uses
1421 of what was there before (because Python's parser always uses
1422 "<string>" when reading from a string).
1422 "<string>" when reading from a string).
1423 """
1423 """
1424 etype, value, last_traceback = sys.exc_info()
1424 etype, value, last_traceback = sys.exc_info()
1425
1425
1426 # See note about these variables in showtraceback() above
1426 # See note about these variables in showtraceback() above
1427 sys.last_type = etype
1427 sys.last_type = etype
1428 sys.last_value = value
1428 sys.last_value = value
1429 sys.last_traceback = last_traceback
1429 sys.last_traceback = last_traceback
1430
1430
1431 if filename and etype is SyntaxError:
1431 if filename and etype is SyntaxError:
1432 # Work hard to stuff the correct filename in the exception
1432 # Work hard to stuff the correct filename in the exception
1433 try:
1433 try:
1434 msg, (dummy_filename, lineno, offset, line) = value
1434 msg, (dummy_filename, lineno, offset, line) = value
1435 except:
1435 except:
1436 # Not the format we expect; leave it alone
1436 # Not the format we expect; leave it alone
1437 pass
1437 pass
1438 else:
1438 else:
1439 # Stuff in the right filename
1439 # Stuff in the right filename
1440 try:
1440 try:
1441 # Assume SyntaxError is a class exception
1441 # Assume SyntaxError is a class exception
1442 value = SyntaxError(msg, (filename, lineno, offset, line))
1442 value = SyntaxError(msg, (filename, lineno, offset, line))
1443 except:
1443 except:
1444 # If that failed, assume SyntaxError is a string
1444 # If that failed, assume SyntaxError is a string
1445 value = msg, (filename, lineno, offset, line)
1445 value = msg, (filename, lineno, offset, line)
1446 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1446 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1447 self._showtraceback(etype, value, stb)
1447 self._showtraceback(etype, value, stb)
1448
1448
1449 #-------------------------------------------------------------------------
1449 #-------------------------------------------------------------------------
1450 # Things related to readline
1450 # Things related to readline
1451 #-------------------------------------------------------------------------
1451 #-------------------------------------------------------------------------
1452
1452
1453 def init_readline(self):
1453 def init_readline(self):
1454 """Command history completion/saving/reloading."""
1454 """Command history completion/saving/reloading."""
1455
1455
1456 if self.readline_use:
1456 if self.readline_use:
1457 import IPython.utils.rlineimpl as readline
1457 import IPython.utils.rlineimpl as readline
1458
1458
1459 self.rl_next_input = None
1459 self.rl_next_input = None
1460 self.rl_do_indent = False
1460 self.rl_do_indent = False
1461
1461
1462 if not self.readline_use or not readline.have_readline:
1462 if not self.readline_use or not readline.have_readline:
1463 self.has_readline = False
1463 self.has_readline = False
1464 self.readline = None
1464 self.readline = None
1465 # Set a number of methods that depend on readline to be no-op
1465 # Set a number of methods that depend on readline to be no-op
1466 self.savehist = no_op
1466 self.savehist = no_op
1467 self.reloadhist = no_op
1467 self.reloadhist = no_op
1468 self.set_readline_completer = no_op
1468 self.set_readline_completer = no_op
1469 self.set_custom_completer = no_op
1469 self.set_custom_completer = no_op
1470 self.set_completer_frame = no_op
1470 self.set_completer_frame = no_op
1471 warn('Readline services not available or not loaded.')
1471 warn('Readline services not available or not loaded.')
1472 else:
1472 else:
1473 self.has_readline = True
1473 self.has_readline = True
1474 self.readline = readline
1474 self.readline = readline
1475 sys.modules['readline'] = readline
1475 sys.modules['readline'] = readline
1476
1476
1477 # Platform-specific configuration
1477 # Platform-specific configuration
1478 if os.name == 'nt':
1478 if os.name == 'nt':
1479 # FIXME - check with Frederick to see if we can harmonize
1479 # FIXME - check with Frederick to see if we can harmonize
1480 # naming conventions with pyreadline to avoid this
1480 # naming conventions with pyreadline to avoid this
1481 # platform-dependent check
1481 # platform-dependent check
1482 self.readline_startup_hook = readline.set_pre_input_hook
1482 self.readline_startup_hook = readline.set_pre_input_hook
1483 else:
1483 else:
1484 self.readline_startup_hook = readline.set_startup_hook
1484 self.readline_startup_hook = readline.set_startup_hook
1485
1485
1486 # Load user's initrc file (readline config)
1486 # Load user's initrc file (readline config)
1487 # Or if libedit is used, load editrc.
1487 # Or if libedit is used, load editrc.
1488 inputrc_name = os.environ.get('INPUTRC')
1488 inputrc_name = os.environ.get('INPUTRC')
1489 if inputrc_name is None:
1489 if inputrc_name is None:
1490 home_dir = get_home_dir()
1490 home_dir = get_home_dir()
1491 if home_dir is not None:
1491 if home_dir is not None:
1492 inputrc_name = '.inputrc'
1492 inputrc_name = '.inputrc'
1493 if readline.uses_libedit:
1493 if readline.uses_libedit:
1494 inputrc_name = '.editrc'
1494 inputrc_name = '.editrc'
1495 inputrc_name = os.path.join(home_dir, inputrc_name)
1495 inputrc_name = os.path.join(home_dir, inputrc_name)
1496 if os.path.isfile(inputrc_name):
1496 if os.path.isfile(inputrc_name):
1497 try:
1497 try:
1498 readline.read_init_file(inputrc_name)
1498 readline.read_init_file(inputrc_name)
1499 except:
1499 except:
1500 warn('Problems reading readline initialization file <%s>'
1500 warn('Problems reading readline initialization file <%s>'
1501 % inputrc_name)
1501 % inputrc_name)
1502
1502
1503 # Configure readline according to user's prefs
1503 # Configure readline according to user's prefs
1504 # This is only done if GNU readline is being used. If libedit
1504 # This is only done if GNU readline is being used. If libedit
1505 # is being used (as on Leopard) the readline config is
1505 # is being used (as on Leopard) the readline config is
1506 # not run as the syntax for libedit is different.
1506 # not run as the syntax for libedit is different.
1507 if not readline.uses_libedit:
1507 if not readline.uses_libedit:
1508 for rlcommand in self.readline_parse_and_bind:
1508 for rlcommand in self.readline_parse_and_bind:
1509 #print "loading rl:",rlcommand # dbg
1509 #print "loading rl:",rlcommand # dbg
1510 readline.parse_and_bind(rlcommand)
1510 readline.parse_and_bind(rlcommand)
1511
1511
1512 # Remove some chars from the delimiters list. If we encounter
1512 # Remove some chars from the delimiters list. If we encounter
1513 # unicode chars, discard them.
1513 # unicode chars, discard them.
1514 delims = readline.get_completer_delims().encode("ascii", "ignore")
1514 delims = readline.get_completer_delims().encode("ascii", "ignore")
1515 delims = delims.translate(string._idmap,
1515 delims = delims.translate(string._idmap,
1516 self.readline_remove_delims)
1516 self.readline_remove_delims)
1517 delims = delims.replace(ESC_MAGIC, '')
1517 delims = delims.replace(ESC_MAGIC, '')
1518 readline.set_completer_delims(delims)
1518 readline.set_completer_delims(delims)
1519 # otherwise we end up with a monster history after a while:
1519 # otherwise we end up with a monster history after a while:
1520 readline.set_history_length(1000)
1520 readline.set_history_length(1000)
1521 try:
1521 try:
1522 #print '*** Reading readline history' # dbg
1522 #print '*** Reading readline history' # dbg
1523 readline.read_history_file(self.histfile)
1523 readline.read_history_file(self.histfile)
1524 except IOError:
1524 except IOError:
1525 pass # It doesn't exist yet.
1525 pass # It doesn't exist yet.
1526
1526
1527 # If we have readline, we want our history saved upon ipython
1527 # If we have readline, we want our history saved upon ipython
1528 # exiting.
1528 # exiting.
1529 atexit.register(self.savehist)
1529 atexit.register(self.savehist)
1530
1530
1531 # Configure auto-indent for all platforms
1531 # Configure auto-indent for all platforms
1532 self.set_autoindent(self.autoindent)
1532 self.set_autoindent(self.autoindent)
1533
1533
1534 def set_next_input(self, s):
1534 def set_next_input(self, s):
1535 """ Sets the 'default' input string for the next command line.
1535 """ Sets the 'default' input string for the next command line.
1536
1536
1537 Requires readline.
1537 Requires readline.
1538
1538
1539 Example:
1539 Example:
1540
1540
1541 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1541 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1542 [D:\ipython]|2> Hello Word_ # cursor is here
1542 [D:\ipython]|2> Hello Word_ # cursor is here
1543 """
1543 """
1544
1544
1545 self.rl_next_input = s
1545 self.rl_next_input = s
1546
1546
1547 # Maybe move this to the terminal subclass?
1547 # Maybe move this to the terminal subclass?
1548 def pre_readline(self):
1548 def pre_readline(self):
1549 """readline hook to be used at the start of each line.
1549 """readline hook to be used at the start of each line.
1550
1550
1551 Currently it handles auto-indent only."""
1551 Currently it handles auto-indent only."""
1552
1552
1553 if self.rl_do_indent:
1553 if self.rl_do_indent:
1554 self.readline.insert_text(self._indent_current_str())
1554 self.readline.insert_text(self._indent_current_str())
1555 if self.rl_next_input is not None:
1555 if self.rl_next_input is not None:
1556 self.readline.insert_text(self.rl_next_input)
1556 self.readline.insert_text(self.rl_next_input)
1557 self.rl_next_input = None
1557 self.rl_next_input = None
1558
1558
1559 def _indent_current_str(self):
1559 def _indent_current_str(self):
1560 """return the current level of indentation as a string"""
1560 """return the current level of indentation as a string"""
1561 return self.indent_current_nsp * ' '
1561 #return self.indent_current_nsp * ' '
1562 return self.input_splitter.indent_spaces * ' '
1562
1563
1563 #-------------------------------------------------------------------------
1564 #-------------------------------------------------------------------------
1564 # Things related to text completion
1565 # Things related to text completion
1565 #-------------------------------------------------------------------------
1566 #-------------------------------------------------------------------------
1566
1567
1567 def init_completer(self):
1568 def init_completer(self):
1568 """Initialize the completion machinery.
1569 """Initialize the completion machinery.
1569
1570
1570 This creates completion machinery that can be used by client code,
1571 This creates completion machinery that can be used by client code,
1571 either interactively in-process (typically triggered by the readline
1572 either interactively in-process (typically triggered by the readline
1572 library), programatically (such as in test suites) or out-of-prcess
1573 library), programatically (such as in test suites) or out-of-prcess
1573 (typically over the network by remote frontends).
1574 (typically over the network by remote frontends).
1574 """
1575 """
1575 from IPython.core.completer import IPCompleter
1576 from IPython.core.completer import IPCompleter
1576 from IPython.core.completerlib import (module_completer,
1577 from IPython.core.completerlib import (module_completer,
1577 magic_run_completer, cd_completer)
1578 magic_run_completer, cd_completer)
1578
1579
1579 self.Completer = IPCompleter(self,
1580 self.Completer = IPCompleter(self,
1580 self.user_ns,
1581 self.user_ns,
1581 self.user_global_ns,
1582 self.user_global_ns,
1582 self.readline_omit__names,
1583 self.readline_omit__names,
1583 self.alias_manager.alias_table,
1584 self.alias_manager.alias_table,
1584 self.has_readline)
1585 self.has_readline)
1585
1586
1586 # Add custom completers to the basic ones built into IPCompleter
1587 # Add custom completers to the basic ones built into IPCompleter
1587 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1588 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1588 self.strdispatchers['complete_command'] = sdisp
1589 self.strdispatchers['complete_command'] = sdisp
1589 self.Completer.custom_completers = sdisp
1590 self.Completer.custom_completers = sdisp
1590
1591
1591 self.set_hook('complete_command', module_completer, str_key = 'import')
1592 self.set_hook('complete_command', module_completer, str_key = 'import')
1592 self.set_hook('complete_command', module_completer, str_key = 'from')
1593 self.set_hook('complete_command', module_completer, str_key = 'from')
1593 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1594 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1594 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1595 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1595
1596
1596 # Only configure readline if we truly are using readline. IPython can
1597 # Only configure readline if we truly are using readline. IPython can
1597 # do tab-completion over the network, in GUIs, etc, where readline
1598 # do tab-completion over the network, in GUIs, etc, where readline
1598 # itself may be absent
1599 # itself may be absent
1599 if self.has_readline:
1600 if self.has_readline:
1600 self.set_readline_completer()
1601 self.set_readline_completer()
1601
1602
1602 def complete(self, text, line=None, cursor_pos=None):
1603 def complete(self, text, line=None, cursor_pos=None):
1603 """Return the completed text and a list of completions.
1604 """Return the completed text and a list of completions.
1604
1605
1605 Parameters
1606 Parameters
1606 ----------
1607 ----------
1607
1608
1608 text : string
1609 text : string
1609 A string of text to be completed on. It can be given as empty and
1610 A string of text to be completed on. It can be given as empty and
1610 instead a line/position pair are given. In this case, the
1611 instead a line/position pair are given. In this case, the
1611 completer itself will split the line like readline does.
1612 completer itself will split the line like readline does.
1612
1613
1613 line : string, optional
1614 line : string, optional
1614 The complete line that text is part of.
1615 The complete line that text is part of.
1615
1616
1616 cursor_pos : int, optional
1617 cursor_pos : int, optional
1617 The position of the cursor on the input line.
1618 The position of the cursor on the input line.
1618
1619
1619 Returns
1620 Returns
1620 -------
1621 -------
1621 text : string
1622 text : string
1622 The actual text that was completed.
1623 The actual text that was completed.
1623
1624
1624 matches : list
1625 matches : list
1625 A sorted list with all possible completions.
1626 A sorted list with all possible completions.
1626
1627
1627 The optional arguments allow the completion to take more context into
1628 The optional arguments allow the completion to take more context into
1628 account, and are part of the low-level completion API.
1629 account, and are part of the low-level completion API.
1629
1630
1630 This is a wrapper around the completion mechanism, similar to what
1631 This is a wrapper around the completion mechanism, similar to what
1631 readline does at the command line when the TAB key is hit. By
1632 readline does at the command line when the TAB key is hit. By
1632 exposing it as a method, it can be used by other non-readline
1633 exposing it as a method, it can be used by other non-readline
1633 environments (such as GUIs) for text completion.
1634 environments (such as GUIs) for text completion.
1634
1635
1635 Simple usage example:
1636 Simple usage example:
1636
1637
1637 In [1]: x = 'hello'
1638 In [1]: x = 'hello'
1638
1639
1639 In [2]: _ip.complete('x.l')
1640 In [2]: _ip.complete('x.l')
1640 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1641 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1641 """
1642 """
1642
1643
1643 # Inject names into __builtin__ so we can complete on the added names.
1644 # Inject names into __builtin__ so we can complete on the added names.
1644 with self.builtin_trap:
1645 with self.builtin_trap:
1645 return self.Completer.complete(text, line, cursor_pos)
1646 return self.Completer.complete(text, line, cursor_pos)
1646
1647
1647 def set_custom_completer(self, completer, pos=0):
1648 def set_custom_completer(self, completer, pos=0):
1648 """Adds a new custom completer function.
1649 """Adds a new custom completer function.
1649
1650
1650 The position argument (defaults to 0) is the index in the completers
1651 The position argument (defaults to 0) is the index in the completers
1651 list where you want the completer to be inserted."""
1652 list where you want the completer to be inserted."""
1652
1653
1653 newcomp = new.instancemethod(completer,self.Completer,
1654 newcomp = new.instancemethod(completer,self.Completer,
1654 self.Completer.__class__)
1655 self.Completer.__class__)
1655 self.Completer.matchers.insert(pos,newcomp)
1656 self.Completer.matchers.insert(pos,newcomp)
1656
1657
1657 def set_readline_completer(self):
1658 def set_readline_completer(self):
1658 """Reset readline's completer to be our own."""
1659 """Reset readline's completer to be our own."""
1659 self.readline.set_completer(self.Completer.rlcomplete)
1660 self.readline.set_completer(self.Completer.rlcomplete)
1660
1661
1661 def set_completer_frame(self, frame=None):
1662 def set_completer_frame(self, frame=None):
1662 """Set the frame of the completer."""
1663 """Set the frame of the completer."""
1663 if frame:
1664 if frame:
1664 self.Completer.namespace = frame.f_locals
1665 self.Completer.namespace = frame.f_locals
1665 self.Completer.global_namespace = frame.f_globals
1666 self.Completer.global_namespace = frame.f_globals
1666 else:
1667 else:
1667 self.Completer.namespace = self.user_ns
1668 self.Completer.namespace = self.user_ns
1668 self.Completer.global_namespace = self.user_global_ns
1669 self.Completer.global_namespace = self.user_global_ns
1669
1670
1670 #-------------------------------------------------------------------------
1671 #-------------------------------------------------------------------------
1671 # Things related to magics
1672 # Things related to magics
1672 #-------------------------------------------------------------------------
1673 #-------------------------------------------------------------------------
1673
1674
1674 def init_magics(self):
1675 def init_magics(self):
1675 # FIXME: Move the color initialization to the DisplayHook, which
1676 # FIXME: Move the color initialization to the DisplayHook, which
1676 # should be split into a prompt manager and displayhook. We probably
1677 # should be split into a prompt manager and displayhook. We probably
1677 # even need a centralize colors management object.
1678 # even need a centralize colors management object.
1678 self.magic_colors(self.colors)
1679 self.magic_colors(self.colors)
1679 # History was moved to a separate module
1680 # History was moved to a separate module
1680 from . import history
1681 from . import history
1681 history.init_ipython(self)
1682 history.init_ipython(self)
1682
1683
1683 def magic(self,arg_s):
1684 def magic(self,arg_s):
1684 """Call a magic function by name.
1685 """Call a magic function by name.
1685
1686
1686 Input: a string containing the name of the magic function to call and
1687 Input: a string containing the name of the magic function to call and
1687 any additional arguments to be passed to the magic.
1688 any additional arguments to be passed to the magic.
1688
1689
1689 magic('name -opt foo bar') is equivalent to typing at the ipython
1690 magic('name -opt foo bar') is equivalent to typing at the ipython
1690 prompt:
1691 prompt:
1691
1692
1692 In[1]: %name -opt foo bar
1693 In[1]: %name -opt foo bar
1693
1694
1694 To call a magic without arguments, simply use magic('name').
1695 To call a magic without arguments, simply use magic('name').
1695
1696
1696 This provides a proper Python function to call IPython's magics in any
1697 This provides a proper Python function to call IPython's magics in any
1697 valid Python code you can type at the interpreter, including loops and
1698 valid Python code you can type at the interpreter, including loops and
1698 compound statements.
1699 compound statements.
1699 """
1700 """
1700 args = arg_s.split(' ',1)
1701 args = arg_s.split(' ',1)
1701 magic_name = args[0]
1702 magic_name = args[0]
1702 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1703 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1703
1704
1704 try:
1705 try:
1705 magic_args = args[1]
1706 magic_args = args[1]
1706 except IndexError:
1707 except IndexError:
1707 magic_args = ''
1708 magic_args = ''
1708 fn = getattr(self,'magic_'+magic_name,None)
1709 fn = getattr(self,'magic_'+magic_name,None)
1709 if fn is None:
1710 if fn is None:
1710 error("Magic function `%s` not found." % magic_name)
1711 error("Magic function `%s` not found." % magic_name)
1711 else:
1712 else:
1712 magic_args = self.var_expand(magic_args,1)
1713 magic_args = self.var_expand(magic_args,1)
1713 with nested(self.builtin_trap,):
1714 with nested(self.builtin_trap,):
1714 result = fn(magic_args)
1715 result = fn(magic_args)
1715 return result
1716 return result
1716
1717
1717 def define_magic(self, magicname, func):
1718 def define_magic(self, magicname, func):
1718 """Expose own function as magic function for ipython
1719 """Expose own function as magic function for ipython
1719
1720
1720 def foo_impl(self,parameter_s=''):
1721 def foo_impl(self,parameter_s=''):
1721 'My very own magic!. (Use docstrings, IPython reads them).'
1722 'My very own magic!. (Use docstrings, IPython reads them).'
1722 print 'Magic function. Passed parameter is between < >:'
1723 print 'Magic function. Passed parameter is between < >:'
1723 print '<%s>' % parameter_s
1724 print '<%s>' % parameter_s
1724 print 'The self object is:',self
1725 print 'The self object is:',self
1725
1726
1726 self.define_magic('foo',foo_impl)
1727 self.define_magic('foo',foo_impl)
1727 """
1728 """
1728
1729
1729 import new
1730 import new
1730 im = new.instancemethod(func,self, self.__class__)
1731 im = new.instancemethod(func,self, self.__class__)
1731 old = getattr(self, "magic_" + magicname, None)
1732 old = getattr(self, "magic_" + magicname, None)
1732 setattr(self, "magic_" + magicname, im)
1733 setattr(self, "magic_" + magicname, im)
1733 return old
1734 return old
1734
1735
1735 #-------------------------------------------------------------------------
1736 #-------------------------------------------------------------------------
1736 # Things related to macros
1737 # Things related to macros
1737 #-------------------------------------------------------------------------
1738 #-------------------------------------------------------------------------
1738
1739
1739 def define_macro(self, name, themacro):
1740 def define_macro(self, name, themacro):
1740 """Define a new macro
1741 """Define a new macro
1741
1742
1742 Parameters
1743 Parameters
1743 ----------
1744 ----------
1744 name : str
1745 name : str
1745 The name of the macro.
1746 The name of the macro.
1746 themacro : str or Macro
1747 themacro : str or Macro
1747 The action to do upon invoking the macro. If a string, a new
1748 The action to do upon invoking the macro. If a string, a new
1748 Macro object is created by passing the string to it.
1749 Macro object is created by passing the string to it.
1749 """
1750 """
1750
1751
1751 from IPython.core import macro
1752 from IPython.core import macro
1752
1753
1753 if isinstance(themacro, basestring):
1754 if isinstance(themacro, basestring):
1754 themacro = macro.Macro(themacro)
1755 themacro = macro.Macro(themacro)
1755 if not isinstance(themacro, macro.Macro):
1756 if not isinstance(themacro, macro.Macro):
1756 raise ValueError('A macro must be a string or a Macro instance.')
1757 raise ValueError('A macro must be a string or a Macro instance.')
1757 self.user_ns[name] = themacro
1758 self.user_ns[name] = themacro
1758
1759
1759 #-------------------------------------------------------------------------
1760 #-------------------------------------------------------------------------
1760 # Things related to the running of system commands
1761 # Things related to the running of system commands
1761 #-------------------------------------------------------------------------
1762 #-------------------------------------------------------------------------
1762
1763
1763 def system(self, cmd):
1764 def system(self, cmd):
1764 """Call the given cmd in a subprocess.
1765 """Call the given cmd in a subprocess.
1765
1766
1766 Parameters
1767 Parameters
1767 ----------
1768 ----------
1768 cmd : str
1769 cmd : str
1769 Command to execute (can not end in '&', as bacground processes are
1770 Command to execute (can not end in '&', as bacground processes are
1770 not supported.
1771 not supported.
1771 """
1772 """
1772 # We do not support backgrounding processes because we either use
1773 # We do not support backgrounding processes because we either use
1773 # pexpect or pipes to read from. Users can always just call
1774 # pexpect or pipes to read from. Users can always just call
1774 # os.system() if they really want a background process.
1775 # os.system() if they really want a background process.
1775 if cmd.endswith('&'):
1776 if cmd.endswith('&'):
1776 raise OSError("Background processes not supported.")
1777 raise OSError("Background processes not supported.")
1777
1778
1778 return system(self.var_expand(cmd, depth=2))
1779 return system(self.var_expand(cmd, depth=2))
1779
1780
1780 def getoutput(self, cmd, split=True):
1781 def getoutput(self, cmd, split=True):
1781 """Get output (possibly including stderr) from a subprocess.
1782 """Get output (possibly including stderr) from a subprocess.
1782
1783
1783 Parameters
1784 Parameters
1784 ----------
1785 ----------
1785 cmd : str
1786 cmd : str
1786 Command to execute (can not end in '&', as background processes are
1787 Command to execute (can not end in '&', as background processes are
1787 not supported.
1788 not supported.
1788 split : bool, optional
1789 split : bool, optional
1789
1790
1790 If True, split the output into an IPython SList. Otherwise, an
1791 If True, split the output into an IPython SList. Otherwise, an
1791 IPython LSString is returned. These are objects similar to normal
1792 IPython LSString is returned. These are objects similar to normal
1792 lists and strings, with a few convenience attributes for easier
1793 lists and strings, with a few convenience attributes for easier
1793 manipulation of line-based output. You can use '?' on them for
1794 manipulation of line-based output. You can use '?' on them for
1794 details.
1795 details.
1795 """
1796 """
1796 if cmd.endswith('&'):
1797 if cmd.endswith('&'):
1797 raise OSError("Background processes not supported.")
1798 raise OSError("Background processes not supported.")
1798 out = getoutput(self.var_expand(cmd, depth=2))
1799 out = getoutput(self.var_expand(cmd, depth=2))
1799 if split:
1800 if split:
1800 out = SList(out.splitlines())
1801 out = SList(out.splitlines())
1801 else:
1802 else:
1802 out = LSString(out)
1803 out = LSString(out)
1803 return out
1804 return out
1804
1805
1805 #-------------------------------------------------------------------------
1806 #-------------------------------------------------------------------------
1806 # Things related to aliases
1807 # Things related to aliases
1807 #-------------------------------------------------------------------------
1808 #-------------------------------------------------------------------------
1808
1809
1809 def init_alias(self):
1810 def init_alias(self):
1810 self.alias_manager = AliasManager(shell=self, config=self.config)
1811 self.alias_manager = AliasManager(shell=self, config=self.config)
1811 self.ns_table['alias'] = self.alias_manager.alias_table,
1812 self.ns_table['alias'] = self.alias_manager.alias_table,
1812
1813
1813 #-------------------------------------------------------------------------
1814 #-------------------------------------------------------------------------
1814 # Things related to extensions and plugins
1815 # Things related to extensions and plugins
1815 #-------------------------------------------------------------------------
1816 #-------------------------------------------------------------------------
1816
1817
1817 def init_extension_manager(self):
1818 def init_extension_manager(self):
1818 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1819 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1819
1820
1820 def init_plugin_manager(self):
1821 def init_plugin_manager(self):
1821 self.plugin_manager = PluginManager(config=self.config)
1822 self.plugin_manager = PluginManager(config=self.config)
1822
1823
1823 #-------------------------------------------------------------------------
1824 #-------------------------------------------------------------------------
1824 # Things related to payloads
1825 # Things related to payloads
1825 #-------------------------------------------------------------------------
1826 #-------------------------------------------------------------------------
1826
1827
1827 def init_payload(self):
1828 def init_payload(self):
1828 self.payload_manager = PayloadManager(config=self.config)
1829 self.payload_manager = PayloadManager(config=self.config)
1829
1830
1830 #-------------------------------------------------------------------------
1831 #-------------------------------------------------------------------------
1831 # Things related to the prefilter
1832 # Things related to the prefilter
1832 #-------------------------------------------------------------------------
1833 #-------------------------------------------------------------------------
1833
1834
1834 def init_prefilter(self):
1835 def init_prefilter(self):
1835 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1836 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1836 # Ultimately this will be refactored in the new interpreter code, but
1837 # Ultimately this will be refactored in the new interpreter code, but
1837 # for now, we should expose the main prefilter method (there's legacy
1838 # for now, we should expose the main prefilter method (there's legacy
1838 # code out there that may rely on this).
1839 # code out there that may rely on this).
1839 self.prefilter = self.prefilter_manager.prefilter_lines
1840 self.prefilter = self.prefilter_manager.prefilter_lines
1840
1841
1841
1842
1842 def auto_rewrite_input(self, cmd):
1843 def auto_rewrite_input(self, cmd):
1843 """Print to the screen the rewritten form of the user's command.
1844 """Print to the screen the rewritten form of the user's command.
1844
1845
1845 This shows visual feedback by rewriting input lines that cause
1846 This shows visual feedback by rewriting input lines that cause
1846 automatic calling to kick in, like::
1847 automatic calling to kick in, like::
1847
1848
1848 /f x
1849 /f x
1849
1850
1850 into::
1851 into::
1851
1852
1852 ------> f(x)
1853 ------> f(x)
1853
1854
1854 after the user's input prompt. This helps the user understand that the
1855 after the user's input prompt. This helps the user understand that the
1855 input line was transformed automatically by IPython.
1856 input line was transformed automatically by IPython.
1856 """
1857 """
1857 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1858 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1858
1859
1859 try:
1860 try:
1860 # plain ascii works better w/ pyreadline, on some machines, so
1861 # plain ascii works better w/ pyreadline, on some machines, so
1861 # we use it and only print uncolored rewrite if we have unicode
1862 # we use it and only print uncolored rewrite if we have unicode
1862 rw = str(rw)
1863 rw = str(rw)
1863 print >> IPython.utils.io.Term.cout, rw
1864 print >> IPython.utils.io.Term.cout, rw
1864 except UnicodeEncodeError:
1865 except UnicodeEncodeError:
1865 print "------> " + cmd
1866 print "------> " + cmd
1866
1867
1867 #-------------------------------------------------------------------------
1868 #-------------------------------------------------------------------------
1868 # Things related to extracting values/expressions from kernel and user_ns
1869 # Things related to extracting values/expressions from kernel and user_ns
1869 #-------------------------------------------------------------------------
1870 #-------------------------------------------------------------------------
1870
1871
1871 def _simple_error(self):
1872 def _simple_error(self):
1872 etype, value = sys.exc_info()[:2]
1873 etype, value = sys.exc_info()[:2]
1873 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1874 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1874
1875
1875 def user_variables(self, names):
1876 def user_variables(self, names):
1876 """Get a list of variable names from the user's namespace.
1877 """Get a list of variable names from the user's namespace.
1877
1878
1878 Parameters
1879 Parameters
1879 ----------
1880 ----------
1880 names : list of strings
1881 names : list of strings
1881 A list of names of variables to be read from the user namespace.
1882 A list of names of variables to be read from the user namespace.
1882
1883
1883 Returns
1884 Returns
1884 -------
1885 -------
1885 A dict, keyed by the input names and with the repr() of each value.
1886 A dict, keyed by the input names and with the repr() of each value.
1886 """
1887 """
1887 out = {}
1888 out = {}
1888 user_ns = self.user_ns
1889 user_ns = self.user_ns
1889 for varname in names:
1890 for varname in names:
1890 try:
1891 try:
1891 value = repr(user_ns[varname])
1892 value = repr(user_ns[varname])
1892 except:
1893 except:
1893 value = self._simple_error()
1894 value = self._simple_error()
1894 out[varname] = value
1895 out[varname] = value
1895 return out
1896 return out
1896
1897
1897 def user_expressions(self, expressions):
1898 def user_expressions(self, expressions):
1898 """Evaluate a dict of expressions in the user's namespace.
1899 """Evaluate a dict of expressions in the user's namespace.
1899
1900
1900 Parameters
1901 Parameters
1901 ----------
1902 ----------
1902 expressions : dict
1903 expressions : dict
1903 A dict with string keys and string values. The expression values
1904 A dict with string keys and string values. The expression values
1904 should be valid Python expressions, each of which will be evaluated
1905 should be valid Python expressions, each of which will be evaluated
1905 in the user namespace.
1906 in the user namespace.
1906
1907
1907 Returns
1908 Returns
1908 -------
1909 -------
1909 A dict, keyed like the input expressions dict, with the repr() of each
1910 A dict, keyed like the input expressions dict, with the repr() of each
1910 value.
1911 value.
1911 """
1912 """
1912 out = {}
1913 out = {}
1913 user_ns = self.user_ns
1914 user_ns = self.user_ns
1914 global_ns = self.user_global_ns
1915 global_ns = self.user_global_ns
1915 for key, expr in expressions.iteritems():
1916 for key, expr in expressions.iteritems():
1916 try:
1917 try:
1917 value = repr(eval(expr, global_ns, user_ns))
1918 value = repr(eval(expr, global_ns, user_ns))
1918 except:
1919 except:
1919 value = self._simple_error()
1920 value = self._simple_error()
1920 out[key] = value
1921 out[key] = value
1921 return out
1922 return out
1922
1923
1923 #-------------------------------------------------------------------------
1924 #-------------------------------------------------------------------------
1924 # Things related to the running of code
1925 # Things related to the running of code
1925 #-------------------------------------------------------------------------
1926 #-------------------------------------------------------------------------
1926
1927
1927 def ex(self, cmd):
1928 def ex(self, cmd):
1928 """Execute a normal python statement in user namespace."""
1929 """Execute a normal python statement in user namespace."""
1929 with nested(self.builtin_trap,):
1930 with nested(self.builtin_trap,):
1930 exec cmd in self.user_global_ns, self.user_ns
1931 exec cmd in self.user_global_ns, self.user_ns
1931
1932
1932 def ev(self, expr):
1933 def ev(self, expr):
1933 """Evaluate python expression expr in user namespace.
1934 """Evaluate python expression expr in user namespace.
1934
1935
1935 Returns the result of evaluation
1936 Returns the result of evaluation
1936 """
1937 """
1937 with nested(self.builtin_trap,):
1938 with nested(self.builtin_trap,):
1938 return eval(expr, self.user_global_ns, self.user_ns)
1939 return eval(expr, self.user_global_ns, self.user_ns)
1939
1940
1940 def safe_execfile(self, fname, *where, **kw):
1941 def safe_execfile(self, fname, *where, **kw):
1941 """A safe version of the builtin execfile().
1942 """A safe version of the builtin execfile().
1942
1943
1943 This version will never throw an exception, but instead print
1944 This version will never throw an exception, but instead print
1944 helpful error messages to the screen. This only works on pure
1945 helpful error messages to the screen. This only works on pure
1945 Python files with the .py extension.
1946 Python files with the .py extension.
1946
1947
1947 Parameters
1948 Parameters
1948 ----------
1949 ----------
1949 fname : string
1950 fname : string
1950 The name of the file to be executed.
1951 The name of the file to be executed.
1951 where : tuple
1952 where : tuple
1952 One or two namespaces, passed to execfile() as (globals,locals).
1953 One or two namespaces, passed to execfile() as (globals,locals).
1953 If only one is given, it is passed as both.
1954 If only one is given, it is passed as both.
1954 exit_ignore : bool (False)
1955 exit_ignore : bool (False)
1955 If True, then silence SystemExit for non-zero status (it is always
1956 If True, then silence SystemExit for non-zero status (it is always
1956 silenced for zero status, as it is so common).
1957 silenced for zero status, as it is so common).
1957 """
1958 """
1958 kw.setdefault('exit_ignore', False)
1959 kw.setdefault('exit_ignore', False)
1959
1960
1960 fname = os.path.abspath(os.path.expanduser(fname))
1961 fname = os.path.abspath(os.path.expanduser(fname))
1961
1962
1962 # Make sure we have a .py file
1963 # Make sure we have a .py file
1963 if not fname.endswith('.py'):
1964 if not fname.endswith('.py'):
1964 warn('File must end with .py to be run using execfile: <%s>' % fname)
1965 warn('File must end with .py to be run using execfile: <%s>' % fname)
1965
1966
1966 # Make sure we can open the file
1967 # Make sure we can open the file
1967 try:
1968 try:
1968 with open(fname) as thefile:
1969 with open(fname) as thefile:
1969 pass
1970 pass
1970 except:
1971 except:
1971 warn('Could not open file <%s> for safe execution.' % fname)
1972 warn('Could not open file <%s> for safe execution.' % fname)
1972 return
1973 return
1973
1974
1974 # Find things also in current directory. This is needed to mimic the
1975 # Find things also in current directory. This is needed to mimic the
1975 # behavior of running a script from the system command line, where
1976 # behavior of running a script from the system command line, where
1976 # Python inserts the script's directory into sys.path
1977 # Python inserts the script's directory into sys.path
1977 dname = os.path.dirname(fname)
1978 dname = os.path.dirname(fname)
1978
1979
1979 with prepended_to_syspath(dname):
1980 with prepended_to_syspath(dname):
1980 try:
1981 try:
1981 execfile(fname,*where)
1982 execfile(fname,*where)
1982 except SystemExit, status:
1983 except SystemExit, status:
1983 # If the call was made with 0 or None exit status (sys.exit(0)
1984 # If the call was made with 0 or None exit status (sys.exit(0)
1984 # or sys.exit() ), don't bother showing a traceback, as both of
1985 # or sys.exit() ), don't bother showing a traceback, as both of
1985 # these are considered normal by the OS:
1986 # these are considered normal by the OS:
1986 # > python -c'import sys;sys.exit(0)'; echo $?
1987 # > python -c'import sys;sys.exit(0)'; echo $?
1987 # 0
1988 # 0
1988 # > python -c'import sys;sys.exit()'; echo $?
1989 # > python -c'import sys;sys.exit()'; echo $?
1989 # 0
1990 # 0
1990 # For other exit status, we show the exception unless
1991 # For other exit status, we show the exception unless
1991 # explicitly silenced, but only in short form.
1992 # explicitly silenced, but only in short form.
1992 if status.code not in (0, None) and not kw['exit_ignore']:
1993 if status.code not in (0, None) and not kw['exit_ignore']:
1993 self.showtraceback(exception_only=True)
1994 self.showtraceback(exception_only=True)
1994 except:
1995 except:
1995 self.showtraceback()
1996 self.showtraceback()
1996
1997
1997 def safe_execfile_ipy(self, fname):
1998 def safe_execfile_ipy(self, fname):
1998 """Like safe_execfile, but for .ipy files with IPython syntax.
1999 """Like safe_execfile, but for .ipy files with IPython syntax.
1999
2000
2000 Parameters
2001 Parameters
2001 ----------
2002 ----------
2002 fname : str
2003 fname : str
2003 The name of the file to execute. The filename must have a
2004 The name of the file to execute. The filename must have a
2004 .ipy extension.
2005 .ipy extension.
2005 """
2006 """
2006 fname = os.path.abspath(os.path.expanduser(fname))
2007 fname = os.path.abspath(os.path.expanduser(fname))
2007
2008
2008 # Make sure we have a .py file
2009 # Make sure we have a .py file
2009 if not fname.endswith('.ipy'):
2010 if not fname.endswith('.ipy'):
2010 warn('File must end with .py to be run using execfile: <%s>' % fname)
2011 warn('File must end with .py to be run using execfile: <%s>' % fname)
2011
2012
2012 # Make sure we can open the file
2013 # Make sure we can open the file
2013 try:
2014 try:
2014 with open(fname) as thefile:
2015 with open(fname) as thefile:
2015 pass
2016 pass
2016 except:
2017 except:
2017 warn('Could not open file <%s> for safe execution.' % fname)
2018 warn('Could not open file <%s> for safe execution.' % fname)
2018 return
2019 return
2019
2020
2020 # Find things also in current directory. This is needed to mimic the
2021 # Find things also in current directory. This is needed to mimic the
2021 # behavior of running a script from the system command line, where
2022 # behavior of running a script from the system command line, where
2022 # Python inserts the script's directory into sys.path
2023 # Python inserts the script's directory into sys.path
2023 dname = os.path.dirname(fname)
2024 dname = os.path.dirname(fname)
2024
2025
2025 with prepended_to_syspath(dname):
2026 with prepended_to_syspath(dname):
2026 try:
2027 try:
2027 with open(fname) as thefile:
2028 with open(fname) as thefile:
2028 script = thefile.read()
2029 script = thefile.read()
2029 # self.runlines currently captures all exceptions
2030 # self.runlines currently captures all exceptions
2030 # raise in user code. It would be nice if there were
2031 # raise in user code. It would be nice if there were
2031 # versions of runlines, execfile that did raise, so
2032 # versions of runlines, execfile that did raise, so
2032 # we could catch the errors.
2033 # we could catch the errors.
2033 self.runlines(script, clean=True)
2034 self.runlines(script, clean=True)
2034 except:
2035 except:
2035 self.showtraceback()
2036 self.showtraceback()
2036 warn('Unknown failure executing file: <%s>' % fname)
2037 warn('Unknown failure executing file: <%s>' % fname)
2037
2038
2038 def run_cell(self, cell):
2039 def run_cell(self, cell):
2039 """Run the contents of an entire multiline 'cell' of code.
2040 """Run the contents of an entire multiline 'cell' of code.
2040
2041
2041 The cell is split into separate blocks which can be executed
2042 The cell is split into separate blocks which can be executed
2042 individually. Then, based on how many blocks there are, they are
2043 individually. Then, based on how many blocks there are, they are
2043 executed as follows:
2044 executed as follows:
2044
2045
2045 - A single block: 'single' mode.
2046 - A single block: 'single' mode.
2046
2047
2047 If there's more than one block, it depends:
2048 If there's more than one block, it depends:
2048
2049
2049 - if the last one is no more than two lines long, run all but the last
2050 - if the last one is no more than two lines long, run all but the last
2050 in 'exec' mode and the very last one in 'single' mode. This makes it
2051 in 'exec' mode and the very last one in 'single' mode. This makes it
2051 easy to type simple expressions at the end to see computed values. -
2052 easy to type simple expressions at the end to see computed values. -
2052 otherwise (last one is also multiline), run all in 'exec' mode
2053 otherwise (last one is also multiline), run all in 'exec' mode
2053
2054
2054 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2055 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2055 results are displayed and output prompts are computed. In 'exec' mode,
2056 results are displayed and output prompts are computed. In 'exec' mode,
2056 no results are displayed unless :func:`print` is called explicitly;
2057 no results are displayed unless :func:`print` is called explicitly;
2057 this mode is more akin to running a script.
2058 this mode is more akin to running a script.
2058
2059
2059 Parameters
2060 Parameters
2060 ----------
2061 ----------
2061 cell : str
2062 cell : str
2062 A single or multiline string.
2063 A single or multiline string.
2063 """
2064 """
2064 #################################################################
2065 #################################################################
2065 # FIXME
2066 # FIXME
2066 # =====
2067 # =====
2067 # This execution logic should stop calling runlines altogether, and
2068 # This execution logic should stop calling runlines altogether, and
2068 # instead we should do what runlines does, in a controlled manner, here
2069 # instead we should do what runlines does, in a controlled manner, here
2069 # (runlines mutates lots of state as it goes calling sub-methods that
2070 # (runlines mutates lots of state as it goes calling sub-methods that
2070 # also mutate state). Basically we should:
2071 # also mutate state). Basically we should:
2071 # - apply dynamic transforms for single-line input (the ones that
2072 # - apply dynamic transforms for single-line input (the ones that
2072 # split_blocks won't apply since they need context).
2073 # split_blocks won't apply since they need context).
2073 # - increment the global execution counter (we need to pull that out
2074 # - increment the global execution counter (we need to pull that out
2074 # from outputcache's control; outputcache should instead read it from
2075 # from outputcache's control; outputcache should instead read it from
2075 # the main object).
2076 # the main object).
2076 # - do any logging of input
2077 # - do any logging of input
2077 # - update histories (raw/translated)
2078 # - update histories (raw/translated)
2078 # - then, call plain runsource (for single blocks, so displayhook is
2079 # - then, call plain runsource (for single blocks, so displayhook is
2079 # triggered) or runcode (for multiline blocks in exec mode).
2080 # triggered) or runcode (for multiline blocks in exec mode).
2080 #
2081 #
2081 # Once this is done, we'll be able to stop using runlines and we'll
2082 # Once this is done, we'll be able to stop using runlines and we'll
2082 # also have a much cleaner separation of logging, input history and
2083 # also have a much cleaner separation of logging, input history and
2083 # output cache management.
2084 # output cache management.
2084 #################################################################
2085 #################################################################
2085
2086
2086 # We need to break up the input into executable blocks that can be run
2087 # We need to break up the input into executable blocks that can be run
2087 # in 'single' mode, to provide comfortable user behavior.
2088 # in 'single' mode, to provide comfortable user behavior.
2088 blocks = self.input_splitter.split_blocks(cell)
2089 blocks = self.input_splitter.split_blocks(cell)
2089
2090
2090 if not blocks:
2091 if not blocks:
2091 return
2092 return
2092
2093
2093 # Store the 'ipython' version of the cell as well, since that's what
2094 # Store the 'ipython' version of the cell as well, since that's what
2094 # needs to go into the translated history and get executed (the
2095 # needs to go into the translated history and get executed (the
2095 # original cell may contain non-python syntax).
2096 # original cell may contain non-python syntax).
2096 ipy_cell = ''.join(blocks)
2097 ipy_cell = ''.join(blocks)
2097
2098
2098 # Each cell is a *single* input, regardless of how many lines it has
2099 self.execution_count += 1
2100
2101 # Store raw and processed history
2099 # Store raw and processed history
2102 self.history_manager.store_inputs(ipy_cell, cell)
2100 self.history_manager.store_inputs(ipy_cell, cell)
2103
2101
2104 # dbg code!!!
2102 # dbg code!!!
2105 def myapp(self, val): # dbg
2103 if 0:
2106 import traceback as tb
2104 def myapp(self, val): # dbg
2107 stack = ''.join(tb.format_stack())
2105 import traceback as tb
2108 print 'Value:', val
2106 stack = ''.join(tb.format_stack())
2109 print 'Stack:\n', stack
2107 print 'Value:', val
2110 list.append(self, val)
2108 print 'Stack:\n', stack
2111
2109 list.append(self, val)
2112 import new
2110
2113 self.input_hist.append = new.instancemethod(myapp, self.input_hist,
2111 import new
2114 list)
2112 self.input_hist.append = new.instancemethod(myapp, self.input_hist,
2113 list)
2115 # End dbg
2114 # End dbg
2116
2115
2117 # All user code execution must happen with our context managers active
2116 # All user code execution must happen with our context managers active
2118 with nested(self.builtin_trap, self.display_trap):
2117 with nested(self.builtin_trap, self.display_trap):
2118
2119 # Single-block input should behave like an interactive prompt
2119 # Single-block input should behave like an interactive prompt
2120 if len(blocks) == 1:
2120 if len(blocks) == 1:
2121 return self.run_one_block(blocks[0])
2121 # since we return here, we need to update the execution count
2122 out = self.run_one_block(blocks[0])
2123 self.execution_count += 1
2124 return out
2122
2125
2123 # In multi-block input, if the last block is a simple (one-two
2126 # In multi-block input, if the last block is a simple (one-two
2124 # lines) expression, run it in single mode so it produces output.
2127 # lines) expression, run it in single mode so it produces output.
2125 # Otherwise just feed the whole thing to runcode. This seems like
2128 # Otherwise just feed the whole thing to runcode. This seems like
2126 # a reasonable usability design.
2129 # a reasonable usability design.
2127 last = blocks[-1]
2130 last = blocks[-1]
2128 last_nlines = len(last.splitlines())
2131 last_nlines = len(last.splitlines())
2129
2132
2130 # Note: below, whenever we call runcode, we must sync history
2133 # Note: below, whenever we call runcode, we must sync history
2131 # ourselves, because runcode is NOT meant to manage history at all.
2134 # ourselves, because runcode is NOT meant to manage history at all.
2132 if last_nlines < 2:
2135 if last_nlines < 2:
2133 # Here we consider the cell split between 'body' and 'last',
2136 # Here we consider the cell split between 'body' and 'last',
2134 # store all history and execute 'body', and if successful, then
2137 # store all history and execute 'body', and if successful, then
2135 # proceed to execute 'last'.
2138 # proceed to execute 'last'.
2136
2139
2137 # Get the main body to run as a cell
2140 # Get the main body to run as a cell
2138 ipy_body = ''.join(blocks[:-1])
2141 ipy_body = ''.join(blocks[:-1])
2139 retcode = self.runcode(ipy_body, post_execute=False)
2142 retcode = self.runcode(ipy_body, post_execute=False)
2140 if retcode==0:
2143 if retcode==0:
2141 # And the last expression via runlines so it produces output
2144 # And the last expression via runlines so it produces output
2142 self.run_one_block(last)
2145 self.run_one_block(last)
2143 else:
2146 else:
2144 # Run the whole cell as one entity, storing both raw and
2147 # Run the whole cell as one entity, storing both raw and
2145 # processed input in history
2148 # processed input in history
2146 self.runcode(ipy_cell)
2149 self.runcode(ipy_cell)
2147
2150
2151 # Each cell is a *single* input, regardless of how many lines it has
2152 self.execution_count += 1
2153
2148 def run_one_block(self, block):
2154 def run_one_block(self, block):
2149 """Run a single interactive block.
2155 """Run a single interactive block.
2150
2156
2151 If the block is single-line, dynamic transformations are applied to it
2157 If the block is single-line, dynamic transformations are applied to it
2152 (like automagics, autocall and alias recognition).
2158 (like automagics, autocall and alias recognition).
2153 """
2159 """
2154 if len(block.splitlines()) <= 1:
2160 if len(block.splitlines()) <= 1:
2155 out = self.run_single_line(block)
2161 out = self.run_single_line(block)
2156 else:
2162 else:
2157 out = self.runcode(block)
2163 out = self.runcode(block)
2158 return out
2164 return out
2159
2165
2160 def run_single_line(self, line):
2166 def run_single_line(self, line):
2161 """Run a single-line interactive statement.
2167 """Run a single-line interactive statement.
2162
2168
2163 This assumes the input has been transformed to IPython syntax by
2169 This assumes the input has been transformed to IPython syntax by
2164 applying all static transformations (those with an explicit prefix like
2170 applying all static transformations (those with an explicit prefix like
2165 % or !), but it will further try to apply the dynamic ones.
2171 % or !), but it will further try to apply the dynamic ones.
2166
2172
2167 It does not update history.
2173 It does not update history.
2168 """
2174 """
2169 tline = self.prefilter_manager.prefilter_line(line)
2175 tline = self.prefilter_manager.prefilter_line(line)
2170 return self.runsource(tline)
2176 return self.runsource(tline)
2171
2177
2172 def runlines(self, lines, clean=False):
2178 def runlines(self, lines, clean=False):
2173 """Run a string of one or more lines of source.
2179 """Run a string of one or more lines of source.
2174
2180
2175 This method is capable of running a string containing multiple source
2181 This method is capable of running a string containing multiple source
2176 lines, as if they had been entered at the IPython prompt. Since it
2182 lines, as if they had been entered at the IPython prompt. Since it
2177 exposes IPython's processing machinery, the given strings can contain
2183 exposes IPython's processing machinery, the given strings can contain
2178 magic calls (%magic), special shell access (!cmd), etc.
2184 magic calls (%magic), special shell access (!cmd), etc.
2179 """
2185 """
2180
2186
2181 if isinstance(lines, (list, tuple)):
2187 if isinstance(lines, (list, tuple)):
2182 lines = '\n'.join(lines)
2188 lines = '\n'.join(lines)
2183
2189
2184 if clean:
2190 if clean:
2185 lines = self._cleanup_ipy_script(lines)
2191 lines = self._cleanup_ipy_script(lines)
2186
2192
2187 # We must start with a clean buffer, in case this is run from an
2193 # We must start with a clean buffer, in case this is run from an
2188 # interactive IPython session (via a magic, for example).
2194 # interactive IPython session (via a magic, for example).
2189 self.resetbuffer()
2195 self.resetbuffer()
2190 lines = lines.splitlines()
2196 lines = lines.splitlines()
2191
2197
2192 # Since we will prefilter all lines, store the user's raw input too
2198 # Since we will prefilter all lines, store the user's raw input too
2193 # before we apply any transformations
2199 # before we apply any transformations
2194 self.buffer_raw[:] = [ l+'\n' for l in lines]
2200 self.buffer_raw[:] = [ l+'\n' for l in lines]
2195
2201
2196 more = False
2202 more = False
2197 prefilter_lines = self.prefilter_manager.prefilter_lines
2203 prefilter_lines = self.prefilter_manager.prefilter_lines
2198 with nested(self.builtin_trap, self.display_trap):
2204 with nested(self.builtin_trap, self.display_trap):
2199 for line in lines:
2205 for line in lines:
2200 # skip blank lines so we don't mess up the prompt counter, but
2206 # skip blank lines so we don't mess up the prompt counter, but
2201 # do NOT skip even a blank line if we are in a code block (more
2207 # do NOT skip even a blank line if we are in a code block (more
2202 # is true)
2208 # is true)
2203
2209
2204 if line or more:
2210 if line or more:
2205 more = self.push_line(prefilter_lines(line, more))
2211 more = self.push_line(prefilter_lines(line, more))
2206 # IPython's runsource returns None if there was an error
2212 # IPython's runsource returns None if there was an error
2207 # compiling the code. This allows us to stop processing
2213 # compiling the code. This allows us to stop processing
2208 # right away, so the user gets the error message at the
2214 # right away, so the user gets the error message at the
2209 # right place.
2215 # right place.
2210 if more is None:
2216 if more is None:
2211 break
2217 break
2212 # final newline in case the input didn't have it, so that the code
2218 # final newline in case the input didn't have it, so that the code
2213 # actually does get executed
2219 # actually does get executed
2214 if more:
2220 if more:
2215 self.push_line('\n')
2221 self.push_line('\n')
2216
2222
2217 def runsource(self, source, filename='<input>', symbol='single'):
2223 def runsource(self, source, filename='<ipython console>', symbol='single'):
2218 """Compile and run some source in the interpreter.
2224 """Compile and run some source in the interpreter.
2219
2225
2220 Arguments are as for compile_command().
2226 Arguments are as for compile_command().
2221
2227
2222 One several things can happen:
2228 One several things can happen:
2223
2229
2224 1) The input is incorrect; compile_command() raised an
2230 1) The input is incorrect; compile_command() raised an
2225 exception (SyntaxError or OverflowError). A syntax traceback
2231 exception (SyntaxError or OverflowError). A syntax traceback
2226 will be printed by calling the showsyntaxerror() method.
2232 will be printed by calling the showsyntaxerror() method.
2227
2233
2228 2) The input is incomplete, and more input is required;
2234 2) The input is incomplete, and more input is required;
2229 compile_command() returned None. Nothing happens.
2235 compile_command() returned None. Nothing happens.
2230
2236
2231 3) The input is complete; compile_command() returned a code
2237 3) The input is complete; compile_command() returned a code
2232 object. The code is executed by calling self.runcode() (which
2238 object. The code is executed by calling self.runcode() (which
2233 also handles run-time exceptions, except for SystemExit).
2239 also handles run-time exceptions, except for SystemExit).
2234
2240
2235 The return value is:
2241 The return value is:
2236
2242
2237 - True in case 2
2243 - True in case 2
2238
2244
2239 - False in the other cases, unless an exception is raised, where
2245 - False in the other cases, unless an exception is raised, where
2240 None is returned instead. This can be used by external callers to
2246 None is returned instead. This can be used by external callers to
2241 know whether to continue feeding input or not.
2247 know whether to continue feeding input or not.
2242
2248
2243 The return value can be used to decide whether to use sys.ps1 or
2249 The return value can be used to decide whether to use sys.ps1 or
2244 sys.ps2 to prompt the next line."""
2250 sys.ps2 to prompt the next line."""
2245
2251
2246 # We need to ensure that the source is unicode from here on.
2252 # We need to ensure that the source is unicode from here on.
2247 if type(source)==str:
2253 if type(source)==str:
2248 source = source.decode(self.stdin_encoding)
2254 source = source.decode(self.stdin_encoding)
2249
2255
2250 # if the source code has leading blanks, add 'if 1:\n' to it
2251 # this allows execution of indented pasted code. It is tempting
2252 # to add '\n' at the end of source to run commands like ' a=1'
2253 # directly, but this fails for more complicated scenarios
2254
2255 if source[:1] in [' ', '\t']:
2256 source = u'if 1:\n%s' % source
2257
2258 try:
2256 try:
2259 code = self.compile(source,filename,symbol)
2257 code = self.compile(source,filename,symbol)
2260 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2258 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2261 # Case 1
2259 # Case 1
2262 self.showsyntaxerror(filename)
2260 self.showsyntaxerror(filename)
2263 return None
2261 return None
2264
2262
2265 if code is None:
2263 if code is None:
2266 # Case 2
2264 # Case 2
2267 return True
2265 return True
2268
2266
2269 # Case 3
2267 # Case 3
2270 # We store the code object so that threaded shells and
2268 # We store the code object so that threaded shells and
2271 # custom exception handlers can access all this info if needed.
2269 # custom exception handlers can access all this info if needed.
2272 # The source corresponding to this can be obtained from the
2270 # The source corresponding to this can be obtained from the
2273 # buffer attribute as '\n'.join(self.buffer).
2271 # buffer attribute as '\n'.join(self.buffer).
2274 self.code_to_run = code
2272 self.code_to_run = code
2275 # now actually execute the code object
2273 # now actually execute the code object
2276 if self.runcode(code) == 0:
2274 if self.runcode(code) == 0:
2277 return False
2275 return False
2278 else:
2276 else:
2279 return None
2277 return None
2280
2278
2281 def runcode(self, code_obj, post_execute=True):
2279 def runcode(self, code_obj, post_execute=True):
2282 """Execute a code object.
2280 """Execute a code object.
2283
2281
2284 When an exception occurs, self.showtraceback() is called to display a
2282 When an exception occurs, self.showtraceback() is called to display a
2285 traceback.
2283 traceback.
2286
2284
2287 Return value: a flag indicating whether the code to be run completed
2285 Return value: a flag indicating whether the code to be run completed
2288 successfully:
2286 successfully:
2289
2287
2290 - 0: successful execution.
2288 - 0: successful execution.
2291 - 1: an error occurred.
2289 - 1: an error occurred.
2292 """
2290 """
2293
2291
2294 # Set our own excepthook in case the user code tries to call it
2292 # Set our own excepthook in case the user code tries to call it
2295 # directly, so that the IPython crash handler doesn't get triggered
2293 # directly, so that the IPython crash handler doesn't get triggered
2296 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2294 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2297
2295
2298 # we save the original sys.excepthook in the instance, in case config
2296 # we save the original sys.excepthook in the instance, in case config
2299 # code (such as magics) needs access to it.
2297 # code (such as magics) needs access to it.
2300 self.sys_excepthook = old_excepthook
2298 self.sys_excepthook = old_excepthook
2301 outflag = 1 # happens in more places, so it's easier as default
2299 outflag = 1 # happens in more places, so it's easier as default
2302 try:
2300 try:
2303 try:
2301 try:
2304 self.hooks.pre_runcode_hook()
2302 self.hooks.pre_runcode_hook()
2305 #rprint('Running code') # dbg
2303 #rprint('Running code') # dbg
2306 exec code_obj in self.user_global_ns, self.user_ns
2304 exec code_obj in self.user_global_ns, self.user_ns
2307 finally:
2305 finally:
2308 # Reset our crash handler in place
2306 # Reset our crash handler in place
2309 sys.excepthook = old_excepthook
2307 sys.excepthook = old_excepthook
2310 except SystemExit:
2308 except SystemExit:
2311 self.resetbuffer()
2309 self.resetbuffer()
2312 self.showtraceback(exception_only=True)
2310 self.showtraceback(exception_only=True)
2313 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2311 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2314 except self.custom_exceptions:
2312 except self.custom_exceptions:
2315 etype,value,tb = sys.exc_info()
2313 etype,value,tb = sys.exc_info()
2316 self.CustomTB(etype,value,tb)
2314 self.CustomTB(etype,value,tb)
2317 except:
2315 except:
2318 self.showtraceback()
2316 self.showtraceback()
2319 else:
2317 else:
2320 outflag = 0
2318 outflag = 0
2321 if softspace(sys.stdout, 0):
2319 if softspace(sys.stdout, 0):
2322 print
2320 print
2323
2321
2324 # Execute any registered post-execution functions. Here, any errors
2322 # Execute any registered post-execution functions. Here, any errors
2325 # are reported only minimally and just on the terminal, because the
2323 # are reported only minimally and just on the terminal, because the
2326 # main exception channel may be occupied with a user traceback.
2324 # main exception channel may be occupied with a user traceback.
2327 # FIXME: we need to think this mechanism a little more carefully.
2325 # FIXME: we need to think this mechanism a little more carefully.
2328 if post_execute:
2326 if post_execute:
2329 for func in self._post_execute:
2327 for func in self._post_execute:
2330 try:
2328 try:
2331 func()
2329 func()
2332 except:
2330 except:
2333 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2331 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2334 func
2332 func
2335 print >> io.Term.cout, head
2333 print >> io.Term.cout, head
2336 print >> io.Term.cout, self._simple_error()
2334 print >> io.Term.cout, self._simple_error()
2337 print >> io.Term.cout, 'Removing from post_execute'
2335 print >> io.Term.cout, 'Removing from post_execute'
2338 self._post_execute.remove(func)
2336 self._post_execute.remove(func)
2339
2337
2340 # Flush out code object which has been run (and source)
2338 # Flush out code object which has been run (and source)
2341 self.code_to_run = None
2339 self.code_to_run = None
2342 return outflag
2340 return outflag
2343
2341
2344 def push_line(self, line):
2342 def push_line(self, line):
2345 """Push a line to the interpreter.
2343 """Push a line to the interpreter.
2346
2344
2347 The line should not have a trailing newline; it may have
2345 The line should not have a trailing newline; it may have
2348 internal newlines. The line is appended to a buffer and the
2346 internal newlines. The line is appended to a buffer and the
2349 interpreter's runsource() method is called with the
2347 interpreter's runsource() method is called with the
2350 concatenated contents of the buffer as source. If this
2348 concatenated contents of the buffer as source. If this
2351 indicates that the command was executed or invalid, the buffer
2349 indicates that the command was executed or invalid, the buffer
2352 is reset; otherwise, the command is incomplete, and the buffer
2350 is reset; otherwise, the command is incomplete, and the buffer
2353 is left as it was after the line was appended. The return
2351 is left as it was after the line was appended. The return
2354 value is 1 if more input is required, 0 if the line was dealt
2352 value is 1 if more input is required, 0 if the line was dealt
2355 with in some way (this is the same as runsource()).
2353 with in some way (this is the same as runsource()).
2356 """
2354 """
2357
2355
2358 # autoindent management should be done here, and not in the
2356 # autoindent management should be done here, and not in the
2359 # interactive loop, since that one is only seen by keyboard input. We
2357 # interactive loop, since that one is only seen by keyboard input. We
2360 # need this done correctly even for code run via runlines (which uses
2358 # need this done correctly even for code run via runlines (which uses
2361 # push).
2359 # push).
2362
2360
2363 #print 'push line: <%s>' % line # dbg
2361 #print 'push line: <%s>' % line # dbg
2364 for subline in line.splitlines():
2365 self._autoindent_update(subline)
2366 self.buffer.append(line)
2362 self.buffer.append(line)
2367 full_source = '\n'.join(self.buffer)
2363 full_source = '\n'.join(self.buffer)
2368 more = self.runsource(full_source, self.filename)
2364 more = self.runsource(full_source, self.filename)
2369 if not more:
2365 if not more:
2370 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2366 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2371 full_source)
2367 full_source)
2372 self.resetbuffer()
2368 self.resetbuffer()
2373 self.execution_count += 1
2369 self.execution_count += 1
2374 return more
2370 return more
2375
2371
2376 def resetbuffer(self):
2372 def resetbuffer(self):
2377 """Reset the input buffer."""
2373 """Reset the input buffer."""
2378 self.buffer[:] = []
2374 self.buffer[:] = []
2379 self.buffer_raw[:] = []
2375 self.buffer_raw[:] = []
2376 self.input_splitter.reset()
2380
2377
2381 def _is_secondary_block_start(self, s):
2378 def _is_secondary_block_start(self, s):
2382 if not s.endswith(':'):
2379 if not s.endswith(':'):
2383 return False
2380 return False
2384 if (s.startswith('elif') or
2381 if (s.startswith('elif') or
2385 s.startswith('else') or
2382 s.startswith('else') or
2386 s.startswith('except') or
2383 s.startswith('except') or
2387 s.startswith('finally')):
2384 s.startswith('finally')):
2388 return True
2385 return True
2389
2386
2390 def _cleanup_ipy_script(self, script):
2387 def _cleanup_ipy_script(self, script):
2391 """Make a script safe for self.runlines()
2388 """Make a script safe for self.runlines()
2392
2389
2393 Currently, IPython is lines based, with blocks being detected by
2390 Currently, IPython is lines based, with blocks being detected by
2394 empty lines. This is a problem for block based scripts that may
2391 empty lines. This is a problem for block based scripts that may
2395 not have empty lines after blocks. This script adds those empty
2392 not have empty lines after blocks. This script adds those empty
2396 lines to make scripts safe for running in the current line based
2393 lines to make scripts safe for running in the current line based
2397 IPython.
2394 IPython.
2398 """
2395 """
2399 res = []
2396 res = []
2400 lines = script.splitlines()
2397 lines = script.splitlines()
2401 level = 0
2398 level = 0
2402
2399
2403 for l in lines:
2400 for l in lines:
2404 lstripped = l.lstrip()
2401 lstripped = l.lstrip()
2405 stripped = l.strip()
2402 stripped = l.strip()
2406 if not stripped:
2403 if not stripped:
2407 continue
2404 continue
2408 newlevel = len(l) - len(lstripped)
2405 newlevel = len(l) - len(lstripped)
2409 if level > 0 and newlevel == 0 and \
2406 if level > 0 and newlevel == 0 and \
2410 not self._is_secondary_block_start(stripped):
2407 not self._is_secondary_block_start(stripped):
2411 # add empty line
2408 # add empty line
2412 res.append('')
2409 res.append('')
2413 res.append(l)
2410 res.append(l)
2414 level = newlevel
2411 level = newlevel
2415
2412
2416 return '\n'.join(res) + '\n'
2413 return '\n'.join(res) + '\n'
2417
2414
2418 def _autoindent_update(self,line):
2419 """Keep track of the indent level."""
2420
2421 #debugx('line')
2422 #debugx('self.indent_current_nsp')
2423 if self.autoindent:
2424 if line:
2425 inisp = num_ini_spaces(line)
2426 if inisp < self.indent_current_nsp:
2427 self.indent_current_nsp = inisp
2428
2429 if line[-1] == ':':
2430 self.indent_current_nsp += 4
2431 elif dedent_re.match(line):
2432 self.indent_current_nsp -= 4
2433 else:
2434 self.indent_current_nsp = 0
2435
2436 #-------------------------------------------------------------------------
2415 #-------------------------------------------------------------------------
2437 # Things related to GUI support and pylab
2416 # Things related to GUI support and pylab
2438 #-------------------------------------------------------------------------
2417 #-------------------------------------------------------------------------
2439
2418
2440 def enable_pylab(self, gui=None):
2419 def enable_pylab(self, gui=None):
2441 raise NotImplementedError('Implement enable_pylab in a subclass')
2420 raise NotImplementedError('Implement enable_pylab in a subclass')
2442
2421
2443 #-------------------------------------------------------------------------
2422 #-------------------------------------------------------------------------
2444 # Utilities
2423 # Utilities
2445 #-------------------------------------------------------------------------
2424 #-------------------------------------------------------------------------
2446
2425
2447 def var_expand(self,cmd,depth=0):
2426 def var_expand(self,cmd,depth=0):
2448 """Expand python variables in a string.
2427 """Expand python variables in a string.
2449
2428
2450 The depth argument indicates how many frames above the caller should
2429 The depth argument indicates how many frames above the caller should
2451 be walked to look for the local namespace where to expand variables.
2430 be walked to look for the local namespace where to expand variables.
2452
2431
2453 The global namespace for expansion is always the user's interactive
2432 The global namespace for expansion is always the user's interactive
2454 namespace.
2433 namespace.
2455 """
2434 """
2456
2435
2457 return str(ItplNS(cmd,
2436 return str(ItplNS(cmd,
2458 self.user_ns, # globals
2437 self.user_ns, # globals
2459 # Skip our own frame in searching for locals:
2438 # Skip our own frame in searching for locals:
2460 sys._getframe(depth+1).f_locals # locals
2439 sys._getframe(depth+1).f_locals # locals
2461 ))
2440 ))
2462
2441
2463 def mktempfile(self,data=None):
2442 def mktempfile(self,data=None):
2464 """Make a new tempfile and return its filename.
2443 """Make a new tempfile and return its filename.
2465
2444
2466 This makes a call to tempfile.mktemp, but it registers the created
2445 This makes a call to tempfile.mktemp, but it registers the created
2467 filename internally so ipython cleans it up at exit time.
2446 filename internally so ipython cleans it up at exit time.
2468
2447
2469 Optional inputs:
2448 Optional inputs:
2470
2449
2471 - data(None): if data is given, it gets written out to the temp file
2450 - data(None): if data is given, it gets written out to the temp file
2472 immediately, and the file is closed again."""
2451 immediately, and the file is closed again."""
2473
2452
2474 filename = tempfile.mktemp('.py','ipython_edit_')
2453 filename = tempfile.mktemp('.py','ipython_edit_')
2475 self.tempfiles.append(filename)
2454 self.tempfiles.append(filename)
2476
2455
2477 if data:
2456 if data:
2478 tmp_file = open(filename,'w')
2457 tmp_file = open(filename,'w')
2479 tmp_file.write(data)
2458 tmp_file.write(data)
2480 tmp_file.close()
2459 tmp_file.close()
2481 return filename
2460 return filename
2482
2461
2483 # TODO: This should be removed when Term is refactored.
2462 # TODO: This should be removed when Term is refactored.
2484 def write(self,data):
2463 def write(self,data):
2485 """Write a string to the default output"""
2464 """Write a string to the default output"""
2486 io.Term.cout.write(data)
2465 io.Term.cout.write(data)
2487
2466
2488 # TODO: This should be removed when Term is refactored.
2467 # TODO: This should be removed when Term is refactored.
2489 def write_err(self,data):
2468 def write_err(self,data):
2490 """Write a string to the default error output"""
2469 """Write a string to the default error output"""
2491 io.Term.cerr.write(data)
2470 io.Term.cerr.write(data)
2492
2471
2493 def ask_yes_no(self,prompt,default=True):
2472 def ask_yes_no(self,prompt,default=True):
2494 if self.quiet:
2473 if self.quiet:
2495 return True
2474 return True
2496 return ask_yes_no(prompt,default)
2475 return ask_yes_no(prompt,default)
2497
2476
2498 def show_usage(self):
2477 def show_usage(self):
2499 """Show a usage message"""
2478 """Show a usage message"""
2500 page.page(IPython.core.usage.interactive_usage)
2479 page.page(IPython.core.usage.interactive_usage)
2501
2480
2502 #-------------------------------------------------------------------------
2481 #-------------------------------------------------------------------------
2503 # Things related to IPython exiting
2482 # Things related to IPython exiting
2504 #-------------------------------------------------------------------------
2483 #-------------------------------------------------------------------------
2505 def atexit_operations(self):
2484 def atexit_operations(self):
2506 """This will be executed at the time of exit.
2485 """This will be executed at the time of exit.
2507
2486
2508 Cleanup operations and saving of persistent data that is done
2487 Cleanup operations and saving of persistent data that is done
2509 unconditionally by IPython should be performed here.
2488 unconditionally by IPython should be performed here.
2510
2489
2511 For things that may depend on startup flags or platform specifics (such
2490 For things that may depend on startup flags or platform specifics (such
2512 as having readline or not), register a separate atexit function in the
2491 as having readline or not), register a separate atexit function in the
2513 code that has the appropriate information, rather than trying to
2492 code that has the appropriate information, rather than trying to
2514 clutter
2493 clutter
2515 """
2494 """
2516 # Cleanup all tempfiles left around
2495 # Cleanup all tempfiles left around
2517 for tfile in self.tempfiles:
2496 for tfile in self.tempfiles:
2518 try:
2497 try:
2519 os.unlink(tfile)
2498 os.unlink(tfile)
2520 except OSError:
2499 except OSError:
2521 pass
2500 pass
2522
2501
2523 # Clear all user namespaces to release all references cleanly.
2502 # Clear all user namespaces to release all references cleanly.
2524 self.reset()
2503 self.reset()
2525
2504
2526 # Run user hooks
2505 # Run user hooks
2527 self.hooks.shutdown_hook()
2506 self.hooks.shutdown_hook()
2528
2507
2529 def cleanup(self):
2508 def cleanup(self):
2530 self.restore_sys_module_state()
2509 self.restore_sys_module_state()
2531
2510
2532
2511
2533 class InteractiveShellABC(object):
2512 class InteractiveShellABC(object):
2534 """An abstract base class for InteractiveShell."""
2513 """An abstract base class for InteractiveShell."""
2535 __metaclass__ = abc.ABCMeta
2514 __metaclass__ = abc.ABCMeta
2536
2515
2537 InteractiveShellABC.register(InteractiveShell)
2516 InteractiveShellABC.register(InteractiveShell)
@@ -1,1014 +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').splitlines()
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 =%s" % cmd)
489 expr = make_quoted_expr("sc =%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 self.shell.auto_rewrite_input(newcmd)
919 self.shell.auto_rewrite_input(newcmd)
920
920
921 # 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
922 # final newline)
922 # final newline)
923 self.shell.log(line,newcmd,continue_prompt)
923 self.shell.log(line,newcmd,continue_prompt)
924 return newcmd
924 return newcmd
925
925
926
926
927 class HelpHandler(PrefilterHandler):
927 class HelpHandler(PrefilterHandler):
928
928
929 handler_name = Str('help')
929 handler_name = Str('help')
930 esc_strings = List([ESC_HELP])
930 esc_strings = List([ESC_HELP])
931
931
932 def handle(self, line_info):
932 def handle(self, line_info):
933 """Try to get some help for the object.
933 """Try to get some help for the object.
934
934
935 obj? or ?obj -> basic information.
935 obj? or ?obj -> basic information.
936 obj?? or ??obj -> more details.
936 obj?? or ??obj -> more details.
937 """
937 """
938 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
938 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
939 line = line_info.line
939 line = line_info.line
940 # 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
941 # otherwise valid python, such as "x=1 # what?"
941 # otherwise valid python, such as "x=1 # what?"
942 try:
942 try:
943 codeop.compile_command(line)
943 codeop.compile_command(line)
944 except SyntaxError:
944 except SyntaxError:
945 # 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
946 if line[0]==ESC_HELP:
946 if line[0]==ESC_HELP:
947 line = line[1:]
947 line = line[1:]
948 elif line[-1]==ESC_HELP:
948 elif line[-1]==ESC_HELP:
949 line = line[:-1]
949 line = line[:-1]
950 self.shell.log(line, '#?'+line, line_info.continue_prompt)
950 self.shell.log(line, '#?'+line, line_info.continue_prompt)
951 if line:
951 if line:
952 #print 'line:<%r>' % line # dbg
952 #print 'line:<%r>' % line # dbg
953 self.shell.magic_pinfo(line)
953 self.shell.magic_pinfo(line)
954 else:
954 else:
955 self.shell.show_usage()
955 self.shell.show_usage()
956 return '' # Empty string is needed here!
956 return '' # Empty string is needed here!
957 except:
957 except:
958 raise
958 raise
959 # Pass any other exceptions through to the normal handler
959 # Pass any other exceptions through to the normal handler
960 return normal_handler.handle(line_info)
960 return normal_handler.handle(line_info)
961 else:
961 else:
962 # If the code compiles ok, we should handle it normally
962 # If the code compiles ok, we should handle it normally
963 return normal_handler.handle(line_info)
963 return normal_handler.handle(line_info)
964
964
965
965
966 class EmacsHandler(PrefilterHandler):
966 class EmacsHandler(PrefilterHandler):
967
967
968 handler_name = Str('emacs')
968 handler_name = Str('emacs')
969 esc_strings = List([])
969 esc_strings = List([])
970
970
971 def handle(self, line_info):
971 def handle(self, line_info):
972 """Handle input lines marked by python-mode."""
972 """Handle input lines marked by python-mode."""
973
973
974 # Currently, nothing is done. Later more functionality can be added
974 # Currently, nothing is done. Later more functionality can be added
975 # here if needed.
975 # here if needed.
976
976
977 # The input cache shouldn't be updated
977 # The input cache shouldn't be updated
978 return line_info.line
978 return line_info.line
979
979
980
980
981 #-----------------------------------------------------------------------------
981 #-----------------------------------------------------------------------------
982 # Defaults
982 # Defaults
983 #-----------------------------------------------------------------------------
983 #-----------------------------------------------------------------------------
984
984
985
985
986 _default_transformers = [
986 _default_transformers = [
987 AssignSystemTransformer,
987 AssignSystemTransformer,
988 AssignMagicTransformer,
988 AssignMagicTransformer,
989 PyPromptTransformer,
989 PyPromptTransformer,
990 IPyPromptTransformer,
990 IPyPromptTransformer,
991 ]
991 ]
992
992
993 _default_checkers = [
993 _default_checkers = [
994 EmacsChecker,
994 EmacsChecker,
995 ShellEscapeChecker,
995 ShellEscapeChecker,
996 IPyAutocallChecker,
996 IPyAutocallChecker,
997 MultiLineMagicChecker,
997 MultiLineMagicChecker,
998 EscCharsChecker,
998 EscCharsChecker,
999 AssignmentChecker,
999 AssignmentChecker,
1000 AutoMagicChecker,
1000 AutoMagicChecker,
1001 AliasChecker,
1001 AliasChecker,
1002 PythonOpsChecker,
1002 PythonOpsChecker,
1003 AutocallChecker
1003 AutocallChecker
1004 ]
1004 ]
1005
1005
1006 _default_handlers = [
1006 _default_handlers = [
1007 PrefilterHandler,
1007 PrefilterHandler,
1008 AliasHandler,
1008 AliasHandler,
1009 ShellEscapeHandler,
1009 ShellEscapeHandler,
1010 MagicHandler,
1010 MagicHandler,
1011 AutoHandler,
1011 AutoHandler,
1012 HelpHandler,
1012 HelpHandler,
1013 EmacsHandler
1013 EmacsHandler
1014 ]
1014 ]
@@ -1,667 +1,675 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for the inputsplitter module.
2 """Tests for the inputsplitter module.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2010 The IPython Development Team
5 # Copyright (C) 2010 The IPython Development Team
6 #
6 #
7 # Distributed under the terms of the BSD License. The full license is in
7 # Distributed under the terms of the BSD License. The full license is in
8 # the file COPYING, distributed as part of this software.
8 # the file COPYING, distributed as part of this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # stdlib
14 # stdlib
15 import unittest
15 import unittest
16 import sys
16 import sys
17
17
18 # Third party
18 # Third party
19 import nose.tools as nt
19 import nose.tools as nt
20
20
21 # Our own
21 # Our own
22 from IPython.core import inputsplitter as isp
22 from IPython.core import inputsplitter as isp
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Semi-complete examples (also used as tests)
25 # Semi-complete examples (also used as tests)
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 # Note: at the bottom, there's a slightly more complete version of this that
28 # Note: at the bottom, there's a slightly more complete version of this that
29 # can be useful during development of code here.
29 # can be useful during development of code here.
30
30
31 def mini_interactive_loop(raw_input):
31 def mini_interactive_loop(raw_input):
32 """Minimal example of the logic of an interactive interpreter loop.
32 """Minimal example of the logic of an interactive interpreter loop.
33
33
34 This serves as an example, and it is used by the test system with a fake
34 This serves as an example, and it is used by the test system with a fake
35 raw_input that simulates interactive input."""
35 raw_input that simulates interactive input."""
36
36
37 from IPython.core.inputsplitter import InputSplitter
37 from IPython.core.inputsplitter import InputSplitter
38
38
39 isp = InputSplitter()
39 isp = InputSplitter()
40 # In practice, this input loop would be wrapped in an outside loop to read
40 # In practice, this input loop would be wrapped in an outside loop to read
41 # input indefinitely, until some exit/quit command was issued. Here we
41 # input indefinitely, until some exit/quit command was issued. Here we
42 # only illustrate the basic inner loop.
42 # only illustrate the basic inner loop.
43 while isp.push_accepts_more():
43 while isp.push_accepts_more():
44 indent = ' '*isp.indent_spaces
44 indent = ' '*isp.indent_spaces
45 prompt = '>>> ' + indent
45 prompt = '>>> ' + indent
46 line = indent + raw_input(prompt)
46 line = indent + raw_input(prompt)
47 isp.push(line)
47 isp.push(line)
48
48
49 # Here we just return input so we can use it in a test suite, but a real
49 # Here we just return input so we can use it in a test suite, but a real
50 # interpreter would instead send it for execution somewhere.
50 # interpreter would instead send it for execution somewhere.
51 src = isp.source_reset()
51 src = isp.source_reset()
52 #print 'Input source was:\n', src # dbg
52 #print 'Input source was:\n', src # dbg
53 return src
53 return src
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Test utilities, just for local use
56 # Test utilities, just for local use
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59 def assemble(block):
59 def assemble(block):
60 """Assemble a block into multi-line sub-blocks."""
60 """Assemble a block into multi-line sub-blocks."""
61 return ['\n'.join(sub_block)+'\n' for sub_block in block]
61 return ['\n'.join(sub_block)+'\n' for sub_block in block]
62
62
63
63
64 def pseudo_input(lines):
64 def pseudo_input(lines):
65 """Return a function that acts like raw_input but feeds the input list."""
65 """Return a function that acts like raw_input but feeds the input list."""
66 ilines = iter(lines)
66 ilines = iter(lines)
67 def raw_in(prompt):
67 def raw_in(prompt):
68 try:
68 try:
69 return next(ilines)
69 return next(ilines)
70 except StopIteration:
70 except StopIteration:
71 return ''
71 return ''
72 return raw_in
72 return raw_in
73
73
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75 # Tests
75 # Tests
76 #-----------------------------------------------------------------------------
76 #-----------------------------------------------------------------------------
77 def test_spaces():
77 def test_spaces():
78 tests = [('', 0),
78 tests = [('', 0),
79 (' ', 1),
79 (' ', 1),
80 ('\n', 0),
80 ('\n', 0),
81 (' \n', 1),
81 (' \n', 1),
82 ('x', 0),
82 ('x', 0),
83 (' x', 1),
83 (' x', 1),
84 (' x',2),
84 (' x',2),
85 (' x',4),
85 (' x',4),
86 # Note: tabs are counted as a single whitespace!
86 # Note: tabs are counted as a single whitespace!
87 ('\tx', 1),
87 ('\tx', 1),
88 ('\t x', 2),
88 ('\t x', 2),
89 ]
89 ]
90
90
91 for s, nsp in tests:
91 for s, nsp in tests:
92 nt.assert_equal(isp.num_ini_spaces(s), nsp)
92 nt.assert_equal(isp.num_ini_spaces(s), nsp)
93
93
94
94
95 def test_remove_comments():
95 def test_remove_comments():
96 tests = [('text', 'text'),
96 tests = [('text', 'text'),
97 ('text # comment', 'text '),
97 ('text # comment', 'text '),
98 ('text # comment\n', 'text \n'),
98 ('text # comment\n', 'text \n'),
99 ('text # comment \n', 'text \n'),
99 ('text # comment \n', 'text \n'),
100 ('line # c \nline\n','line \nline\n'),
100 ('line # c \nline\n','line \nline\n'),
101 ('line # c \nline#c2 \nline\nline #c\n\n',
101 ('line # c \nline#c2 \nline\nline #c\n\n',
102 'line \nline\nline\nline \n\n'),
102 'line \nline\nline\nline \n\n'),
103 ]
103 ]
104
104
105 for inp, out in tests:
105 for inp, out in tests:
106 nt.assert_equal(isp.remove_comments(inp), out)
106 nt.assert_equal(isp.remove_comments(inp), out)
107
107
108
108
109 def test_get_input_encoding():
109 def test_get_input_encoding():
110 encoding = isp.get_input_encoding()
110 encoding = isp.get_input_encoding()
111 nt.assert_true(isinstance(encoding, basestring))
111 nt.assert_true(isinstance(encoding, basestring))
112 # simple-minded check that at least encoding a simple string works with the
112 # simple-minded check that at least encoding a simple string works with the
113 # encoding we got.
113 # encoding we got.
114 nt.assert_equal('test'.encode(encoding), 'test')
114 nt.assert_equal('test'.encode(encoding), 'test')
115
115
116
116
117 class NoInputEncodingTestCase(unittest.TestCase):
117 class NoInputEncodingTestCase(unittest.TestCase):
118 def setUp(self):
118 def setUp(self):
119 self.old_stdin = sys.stdin
119 self.old_stdin = sys.stdin
120 class X: pass
120 class X: pass
121 fake_stdin = X()
121 fake_stdin = X()
122 sys.stdin = fake_stdin
122 sys.stdin = fake_stdin
123
123
124 def test(self):
124 def test(self):
125 # Verify that if sys.stdin has no 'encoding' attribute we do the right
125 # Verify that if sys.stdin has no 'encoding' attribute we do the right
126 # thing
126 # thing
127 enc = isp.get_input_encoding()
127 enc = isp.get_input_encoding()
128 self.assertEqual(enc, 'ascii')
128 self.assertEqual(enc, 'ascii')
129
129
130 def tearDown(self):
130 def tearDown(self):
131 sys.stdin = self.old_stdin
131 sys.stdin = self.old_stdin
132
132
133
133
134 class InputSplitterTestCase(unittest.TestCase):
134 class InputSplitterTestCase(unittest.TestCase):
135 def setUp(self):
135 def setUp(self):
136 self.isp = isp.InputSplitter()
136 self.isp = isp.InputSplitter()
137
137
138 def test_reset(self):
138 def test_reset(self):
139 isp = self.isp
139 isp = self.isp
140 isp.push('x=1')
140 isp.push('x=1')
141 isp.reset()
141 isp.reset()
142 self.assertEqual(isp._buffer, [])
142 self.assertEqual(isp._buffer, [])
143 self.assertEqual(isp.indent_spaces, 0)
143 self.assertEqual(isp.indent_spaces, 0)
144 self.assertEqual(isp.source, '')
144 self.assertEqual(isp.source, '')
145 self.assertEqual(isp.code, None)
145 self.assertEqual(isp.code, None)
146 self.assertEqual(isp._is_complete, False)
146 self.assertEqual(isp._is_complete, False)
147
147
148 def test_source(self):
148 def test_source(self):
149 self.isp._store('1')
149 self.isp._store('1')
150 self.isp._store('2')
150 self.isp._store('2')
151 self.assertEqual(self.isp.source, '1\n2\n')
151 self.assertEqual(self.isp.source, '1\n2\n')
152 self.assertTrue(len(self.isp._buffer)>0)
152 self.assertTrue(len(self.isp._buffer)>0)
153 self.assertEqual(self.isp.source_reset(), '1\n2\n')
153 self.assertEqual(self.isp.source_reset(), '1\n2\n')
154 self.assertEqual(self.isp._buffer, [])
154 self.assertEqual(self.isp._buffer, [])
155 self.assertEqual(self.isp.source, '')
155 self.assertEqual(self.isp.source, '')
156
156
157 def test_indent(self):
157 def test_indent(self):
158 isp = self.isp # shorthand
158 isp = self.isp # shorthand
159 isp.push('x=1')
159 isp.push('x=1')
160 self.assertEqual(isp.indent_spaces, 0)
160 self.assertEqual(isp.indent_spaces, 0)
161 isp.push('if 1:\n x=1')
161 isp.push('if 1:\n x=1')
162 self.assertEqual(isp.indent_spaces, 4)
162 self.assertEqual(isp.indent_spaces, 4)
163 isp.push('y=2\n')
163 isp.push('y=2\n')
164 self.assertEqual(isp.indent_spaces, 0)
164 self.assertEqual(isp.indent_spaces, 0)
165
166 def test_indent2(self):
167 # In cell mode, inputs must be fed in whole blocks, so skip this test
168 if self.isp.input_mode == 'cell': return
169
170 isp = self.isp
165 isp.push('if 1:')
171 isp.push('if 1:')
166 self.assertEqual(isp.indent_spaces, 4)
172 self.assertEqual(isp.indent_spaces, 4)
167 isp.push(' x=1')
173 isp.push(' x=1')
168 self.assertEqual(isp.indent_spaces, 4)
174 self.assertEqual(isp.indent_spaces, 4)
169 # Blank lines shouldn't change the indent level
175 # Blank lines shouldn't change the indent level
170 isp.push(' '*2)
176 isp.push(' '*2)
171 self.assertEqual(isp.indent_spaces, 4)
177 self.assertEqual(isp.indent_spaces, 4)
172
178
173 def test_indent2(self):
179 def test_indent3(self):
180 # In cell mode, inputs must be fed in whole blocks, so skip this test
181 if self.isp.input_mode == 'cell': return
182
174 isp = self.isp
183 isp = self.isp
175 # When a multiline statement contains parens or multiline strings, we
184 # When a multiline statement contains parens or multiline strings, we
176 # shouldn't get confused.
185 # shouldn't get confused.
177 isp.push("if 1:")
186 isp.push("if 1:")
178 isp.push(" x = (1+\n 2)")
187 isp.push(" x = (1+\n 2)")
179 self.assertEqual(isp.indent_spaces, 4)
188 self.assertEqual(isp.indent_spaces, 4)
180
189
181 def test_dedent(self):
190 def test_dedent(self):
182 isp = self.isp # shorthand
191 isp = self.isp # shorthand
183 isp.push('if 1:')
192 isp.push('if 1:')
184 self.assertEqual(isp.indent_spaces, 4)
193 self.assertEqual(isp.indent_spaces, 4)
185 isp.push(' pass')
194 isp.push(' pass')
186 self.assertEqual(isp.indent_spaces, 0)
195 self.assertEqual(isp.indent_spaces, 0)
187
196
188 def test_push(self):
197 def test_push(self):
189 isp = self.isp
198 isp = self.isp
190 self.assertTrue(isp.push('x=1'))
199 self.assertTrue(isp.push('x=1'))
191
200
192 def test_push2(self):
201 def test_push2(self):
193 isp = self.isp
202 isp = self.isp
194 self.assertFalse(isp.push('if 1:'))
203 self.assertFalse(isp.push('if 1:'))
195 for line in [' x=1', '# a comment', ' y=2']:
204 for line in [' x=1', '# a comment', ' y=2']:
196 self.assertTrue(isp.push(line))
205 self.assertTrue(isp.push(line))
197
206
198 def test_push3(self):
199 """Test input with leading whitespace"""
200 isp = self.isp
201 isp.push(' x=1')
202 isp.push(' y=2')
203 self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n')
204
205 def test_replace_mode(self):
207 def test_replace_mode(self):
206 isp = self.isp
208 isp = self.isp
207 isp.input_mode = 'cell'
209 isp.input_mode = 'cell'
208 isp.push('x=1')
210 isp.push('x=1')
209 self.assertEqual(isp.source, 'x=1\n')
211 self.assertEqual(isp.source, 'x=1\n')
210 isp.push('x=2')
212 isp.push('x=2')
211 self.assertEqual(isp.source, 'x=2\n')
213 self.assertEqual(isp.source, 'x=2\n')
212
214
213 def test_push_accepts_more(self):
215 def test_push_accepts_more(self):
214 isp = self.isp
216 isp = self.isp
215 isp.push('x=1')
217 isp.push('x=1')
216 self.assertFalse(isp.push_accepts_more())
218 self.assertFalse(isp.push_accepts_more())
217
219
218 def test_push_accepts_more2(self):
220 def test_push_accepts_more2(self):
221 # In cell mode, inputs must be fed in whole blocks, so skip this test
222 if self.isp.input_mode == 'cell': return
223
219 isp = self.isp
224 isp = self.isp
220 isp.push('if 1:')
225 isp.push('if 1:')
221 self.assertTrue(isp.push_accepts_more())
226 self.assertTrue(isp.push_accepts_more())
222 isp.push(' x=1')
227 isp.push(' x=1')
223 self.assertTrue(isp.push_accepts_more())
228 self.assertTrue(isp.push_accepts_more())
224 isp.push('')
229 isp.push('')
225 self.assertFalse(isp.push_accepts_more())
230 self.assertFalse(isp.push_accepts_more())
226
231
227 def test_push_accepts_more3(self):
232 def test_push_accepts_more3(self):
228 isp = self.isp
233 isp = self.isp
229 isp.push("x = (2+\n3)")
234 isp.push("x = (2+\n3)")
230 self.assertFalse(isp.push_accepts_more())
235 self.assertFalse(isp.push_accepts_more())
231
236
232 def test_push_accepts_more4(self):
237 def test_push_accepts_more4(self):
238 # In cell mode, inputs must be fed in whole blocks, so skip this test
239 if self.isp.input_mode == 'cell': return
240
233 isp = self.isp
241 isp = self.isp
234 # When a multiline statement contains parens or multiline strings, we
242 # When a multiline statement contains parens or multiline strings, we
235 # shouldn't get confused.
243 # shouldn't get confused.
236 # FIXME: we should be able to better handle de-dents in statements like
244 # FIXME: we should be able to better handle de-dents in statements like
237 # multiline strings and multiline expressions (continued with \ or
245 # multiline strings and multiline expressions (continued with \ or
238 # parens). Right now we aren't handling the indentation tracking quite
246 # parens). Right now we aren't handling the indentation tracking quite
239 # correctly with this, though in practice it may not be too much of a
247 # correctly with this, though in practice it may not be too much of a
240 # problem. We'll need to see.
248 # problem. We'll need to see.
241 isp.push("if 1:")
249 isp.push("if 1:")
242 isp.push(" x = (2+")
250 isp.push(" x = (2+")
243 isp.push(" 3)")
251 isp.push(" 3)")
244 self.assertTrue(isp.push_accepts_more())
252 self.assertTrue(isp.push_accepts_more())
245 isp.push(" y = 3")
253 isp.push(" y = 3")
246 self.assertTrue(isp.push_accepts_more())
254 self.assertTrue(isp.push_accepts_more())
247 isp.push('')
255 isp.push('')
248 self.assertFalse(isp.push_accepts_more())
256 self.assertFalse(isp.push_accepts_more())
249
257
250 def test_continuation(self):
258 def test_continuation(self):
251 isp = self.isp
259 isp = self.isp
252 isp.push("import os, \\")
260 isp.push("import os, \\")
253 self.assertTrue(isp.push_accepts_more())
261 self.assertTrue(isp.push_accepts_more())
254 isp.push("sys")
262 isp.push("sys")
255 self.assertFalse(isp.push_accepts_more())
263 self.assertFalse(isp.push_accepts_more())
256
264
257 def test_syntax_error(self):
265 def test_syntax_error(self):
258 isp = self.isp
266 isp = self.isp
259 # Syntax errors immediately produce a 'ready' block, so the invalid
267 # Syntax errors immediately produce a 'ready' block, so the invalid
260 # Python can be sent to the kernel for evaluation with possible ipython
268 # Python can be sent to the kernel for evaluation with possible ipython
261 # special-syntax conversion.
269 # special-syntax conversion.
262 isp.push('run foo')
270 isp.push('run foo')
263 self.assertFalse(isp.push_accepts_more())
271 self.assertFalse(isp.push_accepts_more())
264
272
265 def check_split(self, block_lines, compile=True):
273 def check_split(self, block_lines, compile=True):
266 blocks = assemble(block_lines)
274 blocks = assemble(block_lines)
267 lines = ''.join(blocks)
275 lines = ''.join(blocks)
268 oblock = self.isp.split_blocks(lines)
276 oblock = self.isp.split_blocks(lines)
269 self.assertEqual(oblock, blocks)
277 self.assertEqual(oblock, blocks)
270 if compile:
278 if compile:
271 for block in blocks:
279 for block in blocks:
272 self.isp._compile(block)
280 self.isp._compile(block)
273
281
274 def test_split(self):
282 def test_split(self):
275 # All blocks of input we want to test in a list. The format for each
283 # All blocks of input we want to test in a list. The format for each
276 # block is a list of lists, with each inner lists consisting of all the
284 # block is a list of lists, with each inner lists consisting of all the
277 # lines (as single-lines) that should make up a sub-block.
285 # lines (as single-lines) that should make up a sub-block.
278
286
279 # Note: do NOT put here sub-blocks that don't compile, as the
287 # Note: do NOT put here sub-blocks that don't compile, as the
280 # check_split() routine makes a final verification pass to check that
288 # check_split() routine makes a final verification pass to check that
281 # each sub_block, as returned by split_blocks(), does compile
289 # each sub_block, as returned by split_blocks(), does compile
282 # correctly.
290 # correctly.
283 all_blocks = [ [['x=1']],
291 all_blocks = [ [['x=1']],
284
292
285 [['x=1'],
293 [['x=1'],
286 ['y=2']],
294 ['y=2']],
287
295
288 [['x=1',
296 [['x=1',
289 '# a comment'],
297 '# a comment'],
290 ['y=11']],
298 ['y=11']],
291
299
292 [['if 1:',
300 [['if 1:',
293 ' x=1'],
301 ' x=1'],
294 ['y=3']],
302 ['y=3']],
295
303
296 [['def f(x):',
304 [['def f(x):',
297 ' return x'],
305 ' return x'],
298 ['x=1']],
306 ['x=1']],
299
307
300 [['def f(x):',
308 [['def f(x):',
301 ' x+=1',
309 ' x+=1',
302 ' ',
310 ' ',
303 ' return x'],
311 ' return x'],
304 ['x=1']],
312 ['x=1']],
305
313
306 [['def f(x):',
314 [['def f(x):',
307 ' if x>0:',
315 ' if x>0:',
308 ' y=1',
316 ' y=1',
309 ' # a comment',
317 ' # a comment',
310 ' else:',
318 ' else:',
311 ' y=4',
319 ' y=4',
312 ' ',
320 ' ',
313 ' return y'],
321 ' return y'],
314 ['x=1'],
322 ['x=1'],
315 ['if 1:',
323 ['if 1:',
316 ' y=11'] ],
324 ' y=11'] ],
317
325
318 [['for i in range(10):'
326 [['for i in range(10):'
319 ' x=i**2']],
327 ' x=i**2']],
320
328
321 [['for i in range(10):'
329 [['for i in range(10):'
322 ' x=i**2'],
330 ' x=i**2'],
323 ['z = 1']],
331 ['z = 1']],
324 ]
332 ]
325 for block_lines in all_blocks:
333 for block_lines in all_blocks:
326 self.check_split(block_lines)
334 self.check_split(block_lines)
327
335
328 def test_split_syntax_errors(self):
336 def test_split_syntax_errors(self):
329 # Block splitting with invalid syntax
337 # Block splitting with invalid syntax
330 all_blocks = [ [['a syntax error']],
338 all_blocks = [ [['a syntax error']],
331
339
332 [['x=1',
340 [['x=1',
333 'another syntax error']],
341 'another syntax error']],
334
342
335 [['for i in range(10):'
343 [['for i in range(10):'
336 ' yet another error']],
344 ' yet another error']],
337
345
338 ]
346 ]
339 for block_lines in all_blocks:
347 for block_lines in all_blocks:
340 self.check_split(block_lines, compile=False)
348 self.check_split(block_lines, compile=False)
341
349
342
350
343 class InteractiveLoopTestCase(unittest.TestCase):
351 class InteractiveLoopTestCase(unittest.TestCase):
344 """Tests for an interactive loop like a python shell.
352 """Tests for an interactive loop like a python shell.
345 """
353 """
346 def check_ns(self, lines, ns):
354 def check_ns(self, lines, ns):
347 """Validate that the given input lines produce the resulting namespace.
355 """Validate that the given input lines produce the resulting namespace.
348
356
349 Note: the input lines are given exactly as they would be typed in an
357 Note: the input lines are given exactly as they would be typed in an
350 auto-indenting environment, as mini_interactive_loop above already does
358 auto-indenting environment, as mini_interactive_loop above already does
351 auto-indenting and prepends spaces to the input.
359 auto-indenting and prepends spaces to the input.
352 """
360 """
353 src = mini_interactive_loop(pseudo_input(lines))
361 src = mini_interactive_loop(pseudo_input(lines))
354 test_ns = {}
362 test_ns = {}
355 exec src in test_ns
363 exec src in test_ns
356 # We can't check that the provided ns is identical to the test_ns,
364 # We can't check that the provided ns is identical to the test_ns,
357 # because Python fills test_ns with extra keys (copyright, etc). But
365 # because Python fills test_ns with extra keys (copyright, etc). But
358 # we can check that the given dict is *contained* in test_ns
366 # we can check that the given dict is *contained* in test_ns
359 for k,v in ns.items():
367 for k,v in ns.items():
360 self.assertEqual(test_ns[k], v)
368 self.assertEqual(test_ns[k], v)
361
369
362 def test_simple(self):
370 def test_simple(self):
363 self.check_ns(['x=1'], dict(x=1))
371 self.check_ns(['x=1'], dict(x=1))
364
372
365 def test_simple2(self):
373 def test_simple2(self):
366 self.check_ns(['if 1:', 'x=2'], dict(x=2))
374 self.check_ns(['if 1:', 'x=2'], dict(x=2))
367
375
368 def test_xy(self):
376 def test_xy(self):
369 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
377 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
370
378
371 def test_abc(self):
379 def test_abc(self):
372 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
380 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
373
381
374 def test_multi(self):
382 def test_multi(self):
375 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
383 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
376
384
377
385
378 def test_LineInfo():
386 def test_LineInfo():
379 """Simple test for LineInfo construction and str()"""
387 """Simple test for LineInfo construction and str()"""
380 linfo = isp.LineInfo(' %cd /home')
388 linfo = isp.LineInfo(' %cd /home')
381 nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]')
389 nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]')
382
390
383
391
384 def test_split_user_input():
392 def test_split_user_input():
385 """Unicode test - split_user_input already has good doctests"""
393 """Unicode test - split_user_input already has good doctests"""
386 line = u"PΓ©rez Fernando"
394 line = u"PΓ©rez Fernando"
387 parts = isp.split_user_input(line)
395 parts = isp.split_user_input(line)
388 parts_expected = (u'', u'', u'', line)
396 parts_expected = (u'', u'', u'', line)
389 nt.assert_equal(parts, parts_expected)
397 nt.assert_equal(parts, parts_expected)
390
398
391
399
392 # Transformer tests
400 # Transformer tests
393 def transform_checker(tests, func):
401 def transform_checker(tests, func):
394 """Utility to loop over test inputs"""
402 """Utility to loop over test inputs"""
395 for inp, tr in tests:
403 for inp, tr in tests:
396 nt.assert_equals(func(inp), tr)
404 nt.assert_equals(func(inp), tr)
397
405
398 # Data for all the syntax tests in the form of lists of pairs of
406 # Data for all the syntax tests in the form of lists of pairs of
399 # raw/transformed input. We store it here as a global dict so that we can use
407 # raw/transformed input. We store it here as a global dict so that we can use
400 # it both within single-function tests and also to validate the behavior of the
408 # it both within single-function tests and also to validate the behavior of the
401 # larger objects
409 # larger objects
402
410
403 syntax = \
411 syntax = \
404 dict(assign_system =
412 dict(assign_system =
405 [('a =! ls', 'a = get_ipython().getoutput("ls")'),
413 [('a =! ls', 'a = get_ipython().getoutput("ls")'),
406 ('b = !ls', 'b = get_ipython().getoutput("ls")'),
414 ('b = !ls', 'b = get_ipython().getoutput("ls")'),
407 ('x=1', 'x=1'), # normal input is unmodified
415 ('x=1', 'x=1'), # normal input is unmodified
408 (' ',' '), # blank lines are kept intact
416 (' ',' '), # blank lines are kept intact
409 ],
417 ],
410
418
411 assign_magic =
419 assign_magic =
412 [('a =% who', 'a = get_ipython().magic("who")'),
420 [('a =% who', 'a = get_ipython().magic("who")'),
413 ('b = %who', 'b = get_ipython().magic("who")'),
421 ('b = %who', 'b = get_ipython().magic("who")'),
414 ('x=1', 'x=1'), # normal input is unmodified
422 ('x=1', 'x=1'), # normal input is unmodified
415 (' ',' '), # blank lines are kept intact
423 (' ',' '), # blank lines are kept intact
416 ],
424 ],
417
425
418 classic_prompt =
426 classic_prompt =
419 [('>>> x=1', 'x=1'),
427 [('>>> x=1', 'x=1'),
420 ('x=1', 'x=1'), # normal input is unmodified
428 ('x=1', 'x=1'), # normal input is unmodified
421 (' ', ' '), # blank lines are kept intact
429 (' ', ' '), # blank lines are kept intact
422 ('... ', ''), # continuation prompts
430 ('... ', ''), # continuation prompts
423 ],
431 ],
424
432
425 ipy_prompt =
433 ipy_prompt =
426 [('In [1]: x=1', 'x=1'),
434 [('In [1]: x=1', 'x=1'),
427 ('x=1', 'x=1'), # normal input is unmodified
435 ('x=1', 'x=1'), # normal input is unmodified
428 (' ',' '), # blank lines are kept intact
436 (' ',' '), # blank lines are kept intact
429 (' ....: ', ''), # continuation prompts
437 (' ....: ', ''), # continuation prompts
430 ],
438 ],
431
439
432 # Tests for the escape transformer to leave normal code alone
440 # Tests for the escape transformer to leave normal code alone
433 escaped_noesc =
441 escaped_noesc =
434 [ (' ', ' '),
442 [ (' ', ' '),
435 ('x=1', 'x=1'),
443 ('x=1', 'x=1'),
436 ],
444 ],
437
445
438 # System calls
446 # System calls
439 escaped_shell =
447 escaped_shell =
440 [ ('!ls', 'get_ipython().system("ls")'),
448 [ ('!ls', 'get_ipython().system("ls")'),
441 # Double-escape shell, this means to capture the output of the
449 # Double-escape shell, this means to capture the output of the
442 # subprocess and return it
450 # subprocess and return it
443 ('!!ls', 'get_ipython().getoutput("ls")'),
451 ('!!ls', 'get_ipython().getoutput("ls")'),
444 ],
452 ],
445
453
446 # Help/object info
454 # Help/object info
447 escaped_help =
455 escaped_help =
448 [ ('?', 'get_ipython().show_usage()'),
456 [ ('?', 'get_ipython().show_usage()'),
449 ('?x1', 'get_ipython().magic("pinfo x1")'),
457 ('?x1', 'get_ipython().magic("pinfo x1")'),
450 ('??x2', 'get_ipython().magic("pinfo2 x2")'),
458 ('??x2', 'get_ipython().magic("pinfo2 x2")'),
451 ('x3?', 'get_ipython().magic("pinfo x3")'),
459 ('x3?', 'get_ipython().magic("pinfo x3")'),
452 ('x4??', 'get_ipython().magic("pinfo2 x4")'),
460 ('x4??', 'get_ipython().magic("pinfo2 x4")'),
453 ('%hist?', 'get_ipython().magic("pinfo %hist")'),
461 ('%hist?', 'get_ipython().magic("pinfo %hist")'),
454 ('f*?', 'get_ipython().magic("psearch f*")'),
462 ('f*?', 'get_ipython().magic("psearch f*")'),
455 ('ax.*aspe*?', 'get_ipython().magic("psearch ax.*aspe*")'),
463 ('ax.*aspe*?', 'get_ipython().magic("psearch ax.*aspe*")'),
456 ],
464 ],
457
465
458 # Explicit magic calls
466 # Explicit magic calls
459 escaped_magic =
467 escaped_magic =
460 [ ('%cd', 'get_ipython().magic("cd")'),
468 [ ('%cd', 'get_ipython().magic("cd")'),
461 ('%cd /home', 'get_ipython().magic("cd /home")'),
469 ('%cd /home', 'get_ipython().magic("cd /home")'),
462 (' %magic', ' get_ipython().magic("magic")'),
470 (' %magic', ' get_ipython().magic("magic")'),
463 ],
471 ],
464
472
465 # Quoting with separate arguments
473 # Quoting with separate arguments
466 escaped_quote =
474 escaped_quote =
467 [ (',f', 'f("")'),
475 [ (',f', 'f("")'),
468 (',f x', 'f("x")'),
476 (',f x', 'f("x")'),
469 (' ,f y', ' f("y")'),
477 (' ,f y', ' f("y")'),
470 (',f a b', 'f("a", "b")'),
478 (',f a b', 'f("a", "b")'),
471 ],
479 ],
472
480
473 # Quoting with single argument
481 # Quoting with single argument
474 escaped_quote2 =
482 escaped_quote2 =
475 [ (';f', 'f("")'),
483 [ (';f', 'f("")'),
476 (';f x', 'f("x")'),
484 (';f x', 'f("x")'),
477 (' ;f y', ' f("y")'),
485 (' ;f y', ' f("y")'),
478 (';f a b', 'f("a b")'),
486 (';f a b', 'f("a b")'),
479 ],
487 ],
480
488
481 # Simply apply parens
489 # Simply apply parens
482 escaped_paren =
490 escaped_paren =
483 [ ('/f', 'f()'),
491 [ ('/f', 'f()'),
484 ('/f x', 'f(x)'),
492 ('/f x', 'f(x)'),
485 (' /f y', ' f(y)'),
493 (' /f y', ' f(y)'),
486 ('/f a b', 'f(a, b)'),
494 ('/f a b', 'f(a, b)'),
487 ],
495 ],
488
496
489 )
497 )
490
498
491 # multiline syntax examples. Each of these should be a list of lists, with
499 # multiline syntax examples. Each of these should be a list of lists, with
492 # each entry itself having pairs of raw/transformed input. The union (with
500 # each entry itself having pairs of raw/transformed input. The union (with
493 # '\n'.join() of the transformed inputs is what the splitter should produce
501 # '\n'.join() of the transformed inputs is what the splitter should produce
494 # when fed the raw lines one at a time via push.
502 # when fed the raw lines one at a time via push.
495 syntax_ml = \
503 syntax_ml = \
496 dict(classic_prompt =
504 dict(classic_prompt =
497 [ [('>>> for i in range(10):','for i in range(10):'),
505 [ [('>>> for i in range(10):','for i in range(10):'),
498 ('... print i',' print i'),
506 ('... print i',' print i'),
499 ('... ', ''),
507 ('... ', ''),
500 ],
508 ],
501 ],
509 ],
502
510
503 ipy_prompt =
511 ipy_prompt =
504 [ [('In [24]: for i in range(10):','for i in range(10):'),
512 [ [('In [24]: for i in range(10):','for i in range(10):'),
505 (' ....: print i',' print i'),
513 (' ....: print i',' print i'),
506 (' ....: ', ''),
514 (' ....: ', ''),
507 ],
515 ],
508 ],
516 ],
509 )
517 )
510
518
511
519
512 def test_assign_system():
520 def test_assign_system():
513 transform_checker(syntax['assign_system'], isp.transform_assign_system)
521 transform_checker(syntax['assign_system'], isp.transform_assign_system)
514
522
515
523
516 def test_assign_magic():
524 def test_assign_magic():
517 transform_checker(syntax['assign_magic'], isp.transform_assign_magic)
525 transform_checker(syntax['assign_magic'], isp.transform_assign_magic)
518
526
519
527
520 def test_classic_prompt():
528 def test_classic_prompt():
521 transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt)
529 transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt)
522 for example in syntax_ml['classic_prompt']:
530 for example in syntax_ml['classic_prompt']:
523 transform_checker(example, isp.transform_classic_prompt)
531 transform_checker(example, isp.transform_classic_prompt)
524
532
525
533
526 def test_ipy_prompt():
534 def test_ipy_prompt():
527 transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt)
535 transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt)
528 for example in syntax_ml['ipy_prompt']:
536 for example in syntax_ml['ipy_prompt']:
529 transform_checker(example, isp.transform_ipy_prompt)
537 transform_checker(example, isp.transform_ipy_prompt)
530
538
531
539
532 def test_escaped_noesc():
540 def test_escaped_noesc():
533 transform_checker(syntax['escaped_noesc'], isp.transform_escaped)
541 transform_checker(syntax['escaped_noesc'], isp.transform_escaped)
534
542
535
543
536 def test_escaped_shell():
544 def test_escaped_shell():
537 transform_checker(syntax['escaped_shell'], isp.transform_escaped)
545 transform_checker(syntax['escaped_shell'], isp.transform_escaped)
538
546
539
547
540 def test_escaped_help():
548 def test_escaped_help():
541 transform_checker(syntax['escaped_help'], isp.transform_escaped)
549 transform_checker(syntax['escaped_help'], isp.transform_escaped)
542
550
543
551
544 def test_escaped_magic():
552 def test_escaped_magic():
545 transform_checker(syntax['escaped_magic'], isp.transform_escaped)
553 transform_checker(syntax['escaped_magic'], isp.transform_escaped)
546
554
547
555
548 def test_escaped_quote():
556 def test_escaped_quote():
549 transform_checker(syntax['escaped_quote'], isp.transform_escaped)
557 transform_checker(syntax['escaped_quote'], isp.transform_escaped)
550
558
551
559
552 def test_escaped_quote2():
560 def test_escaped_quote2():
553 transform_checker(syntax['escaped_quote2'], isp.transform_escaped)
561 transform_checker(syntax['escaped_quote2'], isp.transform_escaped)
554
562
555
563
556 def test_escaped_paren():
564 def test_escaped_paren():
557 transform_checker(syntax['escaped_paren'], isp.transform_escaped)
565 transform_checker(syntax['escaped_paren'], isp.transform_escaped)
558
566
559
567
560 class IPythonInputTestCase(InputSplitterTestCase):
568 class IPythonInputTestCase(InputSplitterTestCase):
561 """By just creating a new class whose .isp is a different instance, we
569 """By just creating a new class whose .isp is a different instance, we
562 re-run the same test battery on the new input splitter.
570 re-run the same test battery on the new input splitter.
563
571
564 In addition, this runs the tests over the syntax and syntax_ml dicts that
572 In addition, this runs the tests over the syntax and syntax_ml dicts that
565 were tested by individual functions, as part of the OO interface.
573 were tested by individual functions, as part of the OO interface.
566
574
567 It also makes some checks on the raw buffer storage.
575 It also makes some checks on the raw buffer storage.
568 """
576 """
569
577
570 def setUp(self):
578 def setUp(self):
571 self.isp = isp.IPythonInputSplitter(input_mode='line')
579 self.isp = isp.IPythonInputSplitter(input_mode='line')
572
580
573 def test_syntax(self):
581 def test_syntax(self):
574 """Call all single-line syntax tests from the main object"""
582 """Call all single-line syntax tests from the main object"""
575 isp = self.isp
583 isp = self.isp
576 for example in syntax.itervalues():
584 for example in syntax.itervalues():
577 for raw, out_t in example:
585 for raw, out_t in example:
578 if raw.startswith(' '):
586 if raw.startswith(' '):
579 continue
587 continue
580
588
581 isp.push(raw)
589 isp.push(raw)
582 out, out_raw = isp.source_raw_reset()
590 out, out_raw = isp.source_raw_reset()
583 self.assertEqual(out.rstrip(), out_t)
591 self.assertEqual(out.rstrip(), out_t)
584 self.assertEqual(out_raw.rstrip(), raw.rstrip())
592 self.assertEqual(out_raw.rstrip(), raw.rstrip())
585
593
586 def test_syntax_multiline(self):
594 def test_syntax_multiline(self):
587 isp = self.isp
595 isp = self.isp
588 for example in syntax_ml.itervalues():
596 for example in syntax_ml.itervalues():
589 out_t_parts = []
597 out_t_parts = []
590 raw_parts = []
598 raw_parts = []
591 for line_pairs in example:
599 for line_pairs in example:
592 for lraw, out_t_part in line_pairs:
600 for lraw, out_t_part in line_pairs:
593 isp.push(lraw)
601 isp.push(lraw)
594 out_t_parts.append(out_t_part)
602 out_t_parts.append(out_t_part)
595 raw_parts.append(lraw)
603 raw_parts.append(lraw)
596
604
597 out, out_raw = isp.source_raw_reset()
605 out, out_raw = isp.source_raw_reset()
598 out_t = '\n'.join(out_t_parts).rstrip()
606 out_t = '\n'.join(out_t_parts).rstrip()
599 raw = '\n'.join(raw_parts).rstrip()
607 raw = '\n'.join(raw_parts).rstrip()
600 self.assertEqual(out.rstrip(), out_t)
608 self.assertEqual(out.rstrip(), out_t)
601 self.assertEqual(out_raw.rstrip(), raw)
609 self.assertEqual(out_raw.rstrip(), raw)
602
610
603
611
604 class BlockIPythonInputTestCase(IPythonInputTestCase):
612 class BlockIPythonInputTestCase(IPythonInputTestCase):
605
613
606 # Deactivate tests that don't make sense for the block mode
614 # Deactivate tests that don't make sense for the block mode
607 test_push3 = test_split = lambda s: None
615 test_push3 = test_split = lambda s: None
608
616
609 def setUp(self):
617 def setUp(self):
610 self.isp = isp.IPythonInputSplitter(input_mode='cell')
618 self.isp = isp.IPythonInputSplitter(input_mode='cell')
611
619
612 def test_syntax_multiline(self):
620 def test_syntax_multiline(self):
613 isp = self.isp
621 isp = self.isp
614 for example in syntax_ml.itervalues():
622 for example in syntax_ml.itervalues():
615 raw_parts = []
623 raw_parts = []
616 out_t_parts = []
624 out_t_parts = []
617 for line_pairs in example:
625 for line_pairs in example:
618 for raw, out_t_part in line_pairs:
626 for raw, out_t_part in line_pairs:
619 raw_parts.append(raw)
627 raw_parts.append(raw)
620 out_t_parts.append(out_t_part)
628 out_t_parts.append(out_t_part)
621
629
622 raw = '\n'.join(raw_parts)
630 raw = '\n'.join(raw_parts)
623 out_t = '\n'.join(out_t_parts)
631 out_t = '\n'.join(out_t_parts)
624
632
625 isp.push(raw)
633 isp.push(raw)
626 out, out_raw = isp.source_raw_reset()
634 out, out_raw = isp.source_raw_reset()
627 # Match ignoring trailing whitespace
635 # Match ignoring trailing whitespace
628 self.assertEqual(out.rstrip(), out_t.rstrip())
636 self.assertEqual(out.rstrip(), out_t.rstrip())
629 self.assertEqual(out_raw.rstrip(), raw.rstrip())
637 self.assertEqual(out_raw.rstrip(), raw.rstrip())
630
638
631
639
632 #-----------------------------------------------------------------------------
640 #-----------------------------------------------------------------------------
633 # Main - use as a script, mostly for developer experiments
641 # Main - use as a script, mostly for developer experiments
634 #-----------------------------------------------------------------------------
642 #-----------------------------------------------------------------------------
635
643
636 if __name__ == '__main__':
644 if __name__ == '__main__':
637 # A simple demo for interactive experimentation. This code will not get
645 # A simple demo for interactive experimentation. This code will not get
638 # picked up by any test suite.
646 # picked up by any test suite.
639 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
647 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
640
648
641 # configure here the syntax to use, prompt and whether to autoindent
649 # configure here the syntax to use, prompt and whether to autoindent
642 #isp, start_prompt = InputSplitter(), '>>> '
650 #isp, start_prompt = InputSplitter(), '>>> '
643 isp, start_prompt = IPythonInputSplitter(), 'In> '
651 isp, start_prompt = IPythonInputSplitter(), 'In> '
644
652
645 autoindent = True
653 autoindent = True
646 #autoindent = False
654 #autoindent = False
647
655
648 try:
656 try:
649 while True:
657 while True:
650 prompt = start_prompt
658 prompt = start_prompt
651 while isp.push_accepts_more():
659 while isp.push_accepts_more():
652 indent = ' '*isp.indent_spaces
660 indent = ' '*isp.indent_spaces
653 if autoindent:
661 if autoindent:
654 line = indent + raw_input(prompt+indent)
662 line = indent + raw_input(prompt+indent)
655 else:
663 else:
656 line = raw_input(prompt)
664 line = raw_input(prompt)
657 isp.push(line)
665 isp.push(line)
658 prompt = '... '
666 prompt = '... '
659
667
660 # Here we just return input so we can use it in a test suite, but a
668 # Here we just return input so we can use it in a test suite, but a
661 # real interpreter would instead send it for execution somewhere.
669 # real interpreter would instead send it for execution somewhere.
662 #src = isp.source; raise EOFError # dbg
670 #src = isp.source; raise EOFError # dbg
663 src, raw = isp.source_raw_reset()
671 src, raw = isp.source_raw_reset()
664 print 'Input source was:\n', src
672 print 'Input source was:\n', src
665 print 'Raw source was:\n', raw
673 print 'Raw source was:\n', raw
666 except EOFError:
674 except EOFError:
667 print 'Bye'
675 print 'Bye'
@@ -1,688 +1,615 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
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 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 from contextlib import nested
19 from contextlib import nested
20 import os
20 import os
21 import re
21 import re
22 import sys
22 import sys
23
23
24 from IPython.core.error import TryNext
24 from IPython.core.error import TryNext
25 from IPython.core.usage import interactive_usage, default_banner
25 from IPython.core.usage import interactive_usage, default_banner
26 from IPython.core.inputlist import InputList
26 from IPython.core.inputlist import InputList
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
28 from IPython.lib.inputhook import enable_gui
28 from IPython.lib.inputhook import enable_gui
29 from IPython.lib.pylabtools import pylab_activate
29 from IPython.lib.pylabtools import pylab_activate
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.process import abbrev_cwd
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
33 from IPython.utils.text import num_ini_spaces
33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool
34 from IPython.utils.traitlets import Int, Str, CBool
35
35
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Utilities
38 # Utilities
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41
41
42 def get_default_editor():
42 def get_default_editor():
43 try:
43 try:
44 ed = os.environ['EDITOR']
44 ed = os.environ['EDITOR']
45 except KeyError:
45 except KeyError:
46 if os.name == 'posix':
46 if os.name == 'posix':
47 ed = 'vi' # the only one guaranteed to be there!
47 ed = 'vi' # the only one guaranteed to be there!
48 else:
48 else:
49 ed = 'notepad' # same in Windows!
49 ed = 'notepad' # same in Windows!
50 return ed
50 return ed
51
51
52
52
53 # store the builtin raw_input globally, and use this always, in case user code
53 # store the builtin raw_input globally, and use this always, in case user code
54 # overwrites it (like wx.py.PyShell does)
54 # overwrites it (like wx.py.PyShell does)
55 raw_input_original = raw_input
55 raw_input_original = raw_input
56
56
57
57
58 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
59 # Main class
59 # Main class
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61
61
62
62
63 class TerminalInteractiveShell(InteractiveShell):
63 class TerminalInteractiveShell(InteractiveShell):
64
64
65 autoedit_syntax = CBool(False, config=True)
65 autoedit_syntax = CBool(False, config=True)
66 banner = Str('')
66 banner = Str('')
67 banner1 = Str(default_banner, config=True)
67 banner1 = Str(default_banner, config=True)
68 banner2 = Str('', config=True)
68 banner2 = Str('', config=True)
69 confirm_exit = CBool(True, config=True)
69 confirm_exit = CBool(True, config=True)
70 # This display_banner only controls whether or not self.show_banner()
70 # This display_banner only controls whether or not self.show_banner()
71 # is called when mainloop/interact are called. The default is False
71 # is called when mainloop/interact are called. The default is False
72 # because for the terminal based application, the banner behavior
72 # because for the terminal based application, the banner behavior
73 # is controlled by Global.display_banner, which IPythonApp looks at
73 # is controlled by Global.display_banner, which IPythonApp looks at
74 # to determine if *it* should call show_banner() by hand or not.
74 # to determine if *it* should call show_banner() by hand or not.
75 display_banner = CBool(False) # This isn't configurable!
75 display_banner = CBool(False) # This isn't configurable!
76 embedded = CBool(False)
76 embedded = CBool(False)
77 embedded_active = CBool(False)
77 embedded_active = CBool(False)
78 editor = Str(get_default_editor(), config=True)
78 editor = Str(get_default_editor(), config=True)
79 pager = Str('less', config=True)
79 pager = Str('less', config=True)
80
80
81 screen_length = Int(0, config=True)
81 screen_length = Int(0, config=True)
82 term_title = CBool(False, config=True)
82 term_title = CBool(False, config=True)
83
83
84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
85 user_global_ns=None, custom_exceptions=((),None),
85 user_global_ns=None, custom_exceptions=((),None),
86 usage=None, banner1=None, banner2=None,
86 usage=None, banner1=None, banner2=None,
87 display_banner=None):
87 display_banner=None):
88
88
89 super(TerminalInteractiveShell, self).__init__(
89 super(TerminalInteractiveShell, self).__init__(
90 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
90 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
91 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
91 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
92 )
92 )
93 self.init_term_title()
93 self.init_term_title()
94 self.init_usage(usage)
94 self.init_usage(usage)
95 self.init_banner(banner1, banner2, display_banner)
95 self.init_banner(banner1, banner2, display_banner)
96
96
97 #-------------------------------------------------------------------------
97 #-------------------------------------------------------------------------
98 # Things related to the terminal
98 # Things related to the terminal
99 #-------------------------------------------------------------------------
99 #-------------------------------------------------------------------------
100
100
101 @property
101 @property
102 def usable_screen_length(self):
102 def usable_screen_length(self):
103 if self.screen_length == 0:
103 if self.screen_length == 0:
104 return 0
104 return 0
105 else:
105 else:
106 num_lines_bot = self.separate_in.count('\n')+1
106 num_lines_bot = self.separate_in.count('\n')+1
107 return self.screen_length - num_lines_bot
107 return self.screen_length - num_lines_bot
108
108
109 def init_term_title(self):
109 def init_term_title(self):
110 # Enable or disable the terminal title.
110 # Enable or disable the terminal title.
111 if self.term_title:
111 if self.term_title:
112 toggle_set_term_title(True)
112 toggle_set_term_title(True)
113 set_term_title('IPython: ' + abbrev_cwd())
113 set_term_title('IPython: ' + abbrev_cwd())
114 else:
114 else:
115 toggle_set_term_title(False)
115 toggle_set_term_title(False)
116
116
117 #-------------------------------------------------------------------------
117 #-------------------------------------------------------------------------
118 # Things related to aliases
118 # Things related to aliases
119 #-------------------------------------------------------------------------
119 #-------------------------------------------------------------------------
120
120
121 def init_alias(self):
121 def init_alias(self):
122 # The parent class defines aliases that can be safely used with any
122 # The parent class defines aliases that can be safely used with any
123 # frontend.
123 # frontend.
124 super(TerminalInteractiveShell, self).init_alias()
124 super(TerminalInteractiveShell, self).init_alias()
125
125
126 # Now define aliases that only make sense on the terminal, because they
126 # Now define aliases that only make sense on the terminal, because they
127 # need direct access to the console in a way that we can't emulate in
127 # need direct access to the console in a way that we can't emulate in
128 # GUI or web frontend
128 # GUI or web frontend
129 if os.name == 'posix':
129 if os.name == 'posix':
130 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
130 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
131 ('man', 'man')]
131 ('man', 'man')]
132 elif os.name == 'nt':
132 elif os.name == 'nt':
133 aliases = [('cls', 'cls')]
133 aliases = [('cls', 'cls')]
134
134
135
135
136 for name, cmd in aliases:
136 for name, cmd in aliases:
137 self.alias_manager.define_alias(name, cmd)
137 self.alias_manager.define_alias(name, cmd)
138
138
139 #-------------------------------------------------------------------------
139 #-------------------------------------------------------------------------
140 # Things related to the banner and usage
140 # Things related to the banner and usage
141 #-------------------------------------------------------------------------
141 #-------------------------------------------------------------------------
142
142
143 def _banner1_changed(self):
143 def _banner1_changed(self):
144 self.compute_banner()
144 self.compute_banner()
145
145
146 def _banner2_changed(self):
146 def _banner2_changed(self):
147 self.compute_banner()
147 self.compute_banner()
148
148
149 def _term_title_changed(self, name, new_value):
149 def _term_title_changed(self, name, new_value):
150 self.init_term_title()
150 self.init_term_title()
151
151
152 def init_banner(self, banner1, banner2, display_banner):
152 def init_banner(self, banner1, banner2, display_banner):
153 if banner1 is not None:
153 if banner1 is not None:
154 self.banner1 = banner1
154 self.banner1 = banner1
155 if banner2 is not None:
155 if banner2 is not None:
156 self.banner2 = banner2
156 self.banner2 = banner2
157 if display_banner is not None:
157 if display_banner is not None:
158 self.display_banner = display_banner
158 self.display_banner = display_banner
159 self.compute_banner()
159 self.compute_banner()
160
160
161 def show_banner(self, banner=None):
161 def show_banner(self, banner=None):
162 if banner is None:
162 if banner is None:
163 banner = self.banner
163 banner = self.banner
164 self.write(banner)
164 self.write(banner)
165
165
166 def compute_banner(self):
166 def compute_banner(self):
167 self.banner = self.banner1
167 self.banner = self.banner1
168 if self.profile:
168 if self.profile:
169 self.banner += '\nIPython profile: %s\n' % self.profile
169 self.banner += '\nIPython profile: %s\n' % self.profile
170 if self.banner2:
170 if self.banner2:
171 self.banner += '\n' + self.banner2
171 self.banner += '\n' + self.banner2
172
172
173 def init_usage(self, usage=None):
173 def init_usage(self, usage=None):
174 if usage is None:
174 if usage is None:
175 self.usage = interactive_usage
175 self.usage = interactive_usage
176 else:
176 else:
177 self.usage = usage
177 self.usage = usage
178
178
179 #-------------------------------------------------------------------------
179 #-------------------------------------------------------------------------
180 # Mainloop and code execution logic
180 # Mainloop and code execution logic
181 #-------------------------------------------------------------------------
181 #-------------------------------------------------------------------------
182
182
183 def mainloop(self, display_banner=None):
183 def mainloop(self, display_banner=None):
184 """Start the mainloop.
184 """Start the mainloop.
185
185
186 If an optional banner argument is given, it will override the
186 If an optional banner argument is given, it will override the
187 internally created default banner.
187 internally created default banner.
188 """
188 """
189
189
190 with nested(self.builtin_trap, self.display_trap):
190 with nested(self.builtin_trap, self.display_trap):
191
191
192 # if you run stuff with -c <cmd>, raw hist is not updated
192 # if you run stuff with -c <cmd>, raw hist is not updated
193 # ensure that it's in sync
193 # ensure that it's in sync
194 self.history_manager.sync_inputs()
194 self.history_manager.sync_inputs()
195
195
196 while 1:
196 while 1:
197 try:
197 try:
198 self.interact(display_banner=display_banner)
198 self.interact(display_banner=display_banner)
199 #self.interact_with_readline()
199 #self.interact_with_readline()
200 # XXX for testing of a readline-decoupled repl loop, call
200 # XXX for testing of a readline-decoupled repl loop, call
201 # interact_with_readline above
201 # interact_with_readline above
202 break
202 break
203 except KeyboardInterrupt:
203 except KeyboardInterrupt:
204 # this should not be necessary, but KeyboardInterrupt
204 # this should not be necessary, but KeyboardInterrupt
205 # handling seems rather unpredictable...
205 # handling seems rather unpredictable...
206 self.write("\nKeyboardInterrupt in interact()\n")
206 self.write("\nKeyboardInterrupt in interact()\n")
207
207
208 def interact(self, display_banner=None):
208 def interact(self, display_banner=None):
209 """Closely emulate the interactive Python console."""
209 """Closely emulate the interactive Python console."""
210
210
211 # batch run -> do not interact
211 # batch run -> do not interact
212 if self.exit_now:
212 if self.exit_now:
213 return
213 return
214
214
215 if display_banner is None:
215 if display_banner is None:
216 display_banner = self.display_banner
216 display_banner = self.display_banner
217 if display_banner:
217 if display_banner:
218 self.show_banner()
218 self.show_banner()
219
219
220 more = False
220 more = False
221
221
222 # Mark activity in the builtins
222 # Mark activity in the builtins
223 __builtin__.__dict__['__IPYTHON__active'] += 1
223 __builtin__.__dict__['__IPYTHON__active'] += 1
224
224
225 if self.has_readline:
225 if self.has_readline:
226 self.readline_startup_hook(self.pre_readline)
226 self.readline_startup_hook(self.pre_readline)
227 # exit_now is set by a call to %Exit or %Quit, through the
227 # exit_now is set by a call to %Exit or %Quit, through the
228 # ask_exit callback.
228 # ask_exit callback.
229
229
230 # Before showing any prompts, if the counter is at zero, we execute an
231 # empty line to ensure the user only sees prompts starting at one.
232 if self.execution_count == 0:
233 self.execution_count += 1
234
235 while not self.exit_now:
230 while not self.exit_now:
236 self.hooks.pre_prompt_hook()
231 self.hooks.pre_prompt_hook()
237 if more:
232 if more:
238 try:
233 try:
239 prompt = self.hooks.generate_prompt(True)
234 prompt = self.hooks.generate_prompt(True)
240 except:
235 except:
241 self.showtraceback()
236 self.showtraceback()
242 if self.autoindent:
237 if self.autoindent:
243 self.rl_do_indent = True
238 self.rl_do_indent = True
244
239
245 else:
240 else:
246 try:
241 try:
247 prompt = self.hooks.generate_prompt(False)
242 prompt = self.hooks.generate_prompt(False)
248 except:
243 except:
249 self.showtraceback()
244 self.showtraceback()
250 try:
245 try:
251 line = self.raw_input(prompt)
246 line = self.raw_input(prompt)
252 if self.exit_now:
247 if self.exit_now:
253 # quick exit on sys.std[in|out] close
248 # quick exit on sys.std[in|out] close
254 break
249 break
255 if self.autoindent:
250 if self.autoindent:
256 self.rl_do_indent = False
251 self.rl_do_indent = False
257
252
258 except KeyboardInterrupt:
253 except KeyboardInterrupt:
259 #double-guard against keyboardinterrupts during kbdint handling
254 #double-guard against keyboardinterrupts during kbdint handling
260 try:
255 try:
261 self.write('\nKeyboardInterrupt\n')
256 self.write('\nKeyboardInterrupt\n')
262 self.resetbuffer()
257 self.resetbuffer()
263 # keep cache in sync with the prompt counter:
264 self.displayhook.prompt_count -= 1
265
266 if self.autoindent:
267 self.indent_current_nsp = 0
268 more = False
258 more = False
269 except KeyboardInterrupt:
259 except KeyboardInterrupt:
270 pass
260 pass
271 except EOFError:
261 except EOFError:
272 if self.autoindent:
262 if self.autoindent:
273 self.rl_do_indent = False
263 self.rl_do_indent = False
274 if self.has_readline:
264 if self.has_readline:
275 self.readline_startup_hook(None)
265 self.readline_startup_hook(None)
276 self.write('\n')
266 self.write('\n')
277 self.exit()
267 self.exit()
278 except bdb.BdbQuit:
268 except bdb.BdbQuit:
279 warn('The Python debugger has exited with a BdbQuit exception.\n'
269 warn('The Python debugger has exited with a BdbQuit exception.\n'
280 'Because of how pdb handles the stack, it is impossible\n'
270 'Because of how pdb handles the stack, it is impossible\n'
281 'for IPython to properly format this particular exception.\n'
271 'for IPython to properly format this particular exception.\n'
282 'IPython will resume normal operation.')
272 'IPython will resume normal operation.')
283 except:
273 except:
284 # exceptions here are VERY RARE, but they can be triggered
274 # exceptions here are VERY RARE, but they can be triggered
285 # asynchronously by signal handlers, for example.
275 # asynchronously by signal handlers, for example.
286 self.showtraceback()
276 self.showtraceback()
287 else:
277 else:
288 #more = self.push_line(line)
289 self.input_splitter.push(line)
278 self.input_splitter.push(line)
290 more = self.input_splitter.push_accepts_more()
279 more = self.input_splitter.push_accepts_more()
291 if (self.SyntaxTB.last_syntax_error and
280 if (self.SyntaxTB.last_syntax_error and
292 self.autoedit_syntax):
281 self.autoedit_syntax):
293 self.edit_syntax_error()
282 self.edit_syntax_error()
294 if not more:
283 if not more:
295 pass
284 source_raw = self.input_splitter.source_raw_reset()[1]
285 self.run_cell(source_raw)
296
286
297 # We are off again...
287 # We are off again...
298 __builtin__.__dict__['__IPYTHON__active'] -= 1
288 __builtin__.__dict__['__IPYTHON__active'] -= 1
299
289
300 # Turn off the exit flag, so the mainloop can be restarted if desired
290 # Turn off the exit flag, so the mainloop can be restarted if desired
301 self.exit_now = False
291 self.exit_now = False
302
292
303 def raw_input(self, prompt='', continue_prompt=False):
293 def raw_input(self, prompt='', continue_prompt=False):
304 """Write a prompt and read a line.
294 """Write a prompt and read a line.
305
295
306 The returned line does not include the trailing newline.
296 The returned line does not include the trailing newline.
307 When the user enters the EOF key sequence, EOFError is raised.
297 When the user enters the EOF key sequence, EOFError is raised.
308
298
309 Optional inputs:
299 Optional inputs:
310
300
311 - prompt(''): a string to be printed to prompt the user.
301 - prompt(''): a string to be printed to prompt the user.
312
302
313 - continue_prompt(False): whether this line is the first one or a
303 - continue_prompt(False): whether this line is the first one or a
314 continuation in a sequence of inputs.
304 continuation in a sequence of inputs.
315 """
305 """
316 # Code run by the user may have modified the readline completer state.
306 # Code run by the user may have modified the readline completer state.
317 # We must ensure that our completer is back in place.
307 # We must ensure that our completer is back in place.
318
308
319 if self.has_readline:
309 if self.has_readline:
320 self.set_readline_completer()
310 self.set_readline_completer()
321
311
322 try:
312 try:
323 line = raw_input_original(prompt).decode(self.stdin_encoding)
313 line = raw_input_original(prompt).decode(self.stdin_encoding)
324 except ValueError:
314 except ValueError:
325 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
315 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
326 " or sys.stdout.close()!\nExiting IPython!")
316 " or sys.stdout.close()!\nExiting IPython!")
327 self.ask_exit()
317 self.ask_exit()
328 return ""
318 return ""
329
319
330 # Try to be reasonably smart about not re-indenting pasted input more
320 # Try to be reasonably smart about not re-indenting pasted input more
331 # than necessary. We do this by trimming out the auto-indent initial
321 # than necessary. We do this by trimming out the auto-indent initial
332 # spaces, if the user's actual input started itself with whitespace.
322 # spaces, if the user's actual input started itself with whitespace.
333 if self.autoindent:
323 if self.autoindent:
334 if num_ini_spaces(line) > self.indent_current_nsp:
324 if num_ini_spaces(line) > self.indent_current_nsp:
335 line = line[self.indent_current_nsp:]
325 line = line[self.indent_current_nsp:]
336 self.indent_current_nsp = 0
326 self.indent_current_nsp = 0
337
327
338 # store the unfiltered input before the user has any chance to modify
328 # store the unfiltered input before the user has any chance to modify
339 # it.
329 # it.
340 if line.strip():
330 if line.strip():
341 if continue_prompt:
331 if continue_prompt:
342 if self.has_readline and self.readline_use:
332 if self.has_readline and self.readline_use:
343 histlen = self.readline.get_current_history_length()
333 histlen = self.readline.get_current_history_length()
344 if histlen > 1:
334 if histlen > 1:
345 newhist = self.input_hist_raw[-1].rstrip()
335 newhist = self.input_hist_raw[-1].rstrip()
346 self.readline.remove_history_item(histlen-1)
336 self.readline.remove_history_item(histlen-1)
347 self.readline.replace_history_item(histlen-2,
337 self.readline.replace_history_item(histlen-2,
348 newhist.encode(self.stdin_encoding))
338 newhist.encode(self.stdin_encoding))
349 else:
339 else:
350 self.input_hist_raw.append('%s\n' % line)
340 self.input_hist_raw.append('%s\n' % line)
351 elif not continue_prompt:
341 elif not continue_prompt:
352 self.input_hist_raw.append('\n')
342 self.input_hist_raw.append('\n')
353 try:
343 try:
354 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
344 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
355 except:
345 except:
356 # blanket except, in case a user-defined prefilter crashes, so it
346 # blanket except, in case a user-defined prefilter crashes, so it
357 # can't take all of ipython with it.
347 # can't take all of ipython with it.
358 self.showtraceback()
348 self.showtraceback()
359 return ''
349 return ''
360 else:
350 else:
361 return lineout
351 return lineout
362
352
363
353
364 def raw_input(self, prompt=''):
354 def raw_input(self, prompt=''):
365 """Write a prompt and read a line.
355 """Write a prompt and read a line.
366
356
367 The returned line does not include the trailing newline.
357 The returned line does not include the trailing newline.
368 When the user enters the EOF key sequence, EOFError is raised.
358 When the user enters the EOF key sequence, EOFError is raised.
369
359
370 Optional inputs:
360 Optional inputs:
371
361
372 - prompt(''): a string to be printed to prompt the user.
362 - prompt(''): a string to be printed to prompt the user.
373
363
374 - continue_prompt(False): whether this line is the first one or a
364 - continue_prompt(False): whether this line is the first one or a
375 continuation in a sequence of inputs.
365 continuation in a sequence of inputs.
376 """
366 """
377 # Code run by the user may have modified the readline completer state.
367 # Code run by the user may have modified the readline completer state.
378 # We must ensure that our completer is back in place.
368 # We must ensure that our completer is back in place.
379
369
380 if self.has_readline:
370 if self.has_readline:
381 self.set_readline_completer()
371 self.set_readline_completer()
382
372
383 try:
373 try:
384 line = raw_input_original(prompt).decode(self.stdin_encoding)
374 line = raw_input_original(prompt).decode(self.stdin_encoding)
385 except ValueError:
375 except ValueError:
386 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
376 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
387 " or sys.stdout.close()!\nExiting IPython!")
377 " or sys.stdout.close()!\nExiting IPython!")
388 self.ask_exit()
378 self.ask_exit()
389 return ""
379 return ""
390
380
391 # Try to be reasonably smart about not re-indenting pasted input more
381 # Try to be reasonably smart about not re-indenting pasted input more
392 # than necessary. We do this by trimming out the auto-indent initial
382 # than necessary. We do this by trimming out the auto-indent initial
393 # spaces, if the user's actual input started itself with whitespace.
383 # spaces, if the user's actual input started itself with whitespace.
394 if self.autoindent:
384 if self.autoindent:
395 if num_ini_spaces(line) > self.indent_current_nsp:
385 if num_ini_spaces(line) > self.indent_current_nsp:
396 line = line[self.indent_current_nsp:]
386 line = line[self.indent_current_nsp:]
397 self.indent_current_nsp = 0
387 self.indent_current_nsp = 0
398
388
399 return line
389 return line
400
390
401
402 # TODO: The following three methods are an early attempt to refactor
403 # the main code execution logic. We don't use them, but they may be
404 # helpful when we refactor the code execution logic further.
405 # def interact_prompt(self):
406 # """ Print the prompt (in read-eval-print loop)
407 #
408 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
409 # used in standard IPython flow.
410 # """
411 # if self.more:
412 # try:
413 # prompt = self.hooks.generate_prompt(True)
414 # except:
415 # self.showtraceback()
416 # if self.autoindent:
417 # self.rl_do_indent = True
418 #
419 # else:
420 # try:
421 # prompt = self.hooks.generate_prompt(False)
422 # except:
423 # self.showtraceback()
424 # self.write(prompt)
425 #
426 # def interact_handle_input(self,line):
427 # """ Handle the input line (in read-eval-print loop)
428 #
429 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
430 # used in standard IPython flow.
431 # """
432 # if line.lstrip() == line:
433 # self.shadowhist.add(line.strip())
434 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
435 #
436 # if line.strip():
437 # if self.more:
438 # self.input_hist_raw[-1] += '%s\n' % line
439 # else:
440 # self.input_hist_raw.append('%s\n' % line)
441 #
442 #
443 # self.more = self.push_line(lineout)
444 # if (self.SyntaxTB.last_syntax_error and
445 # self.autoedit_syntax):
446 # self.edit_syntax_error()
447 #
448 # def interact_with_readline(self):
449 # """ Demo of using interact_handle_input, interact_prompt
450 #
451 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
452 # it should work like this.
453 # """
454 # self.readline_startup_hook(self.pre_readline)
455 # while not self.exit_now:
456 # self.interact_prompt()
457 # if self.more:
458 # self.rl_do_indent = True
459 # else:
460 # self.rl_do_indent = False
461 # line = raw_input_original().decode(self.stdin_encoding)
462 # self.interact_handle_input(line)
463
464 #-------------------------------------------------------------------------
391 #-------------------------------------------------------------------------
465 # Methods to support auto-editing of SyntaxErrors.
392 # Methods to support auto-editing of SyntaxErrors.
466 #-------------------------------------------------------------------------
393 #-------------------------------------------------------------------------
467
394
468 def edit_syntax_error(self):
395 def edit_syntax_error(self):
469 """The bottom half of the syntax error handler called in the main loop.
396 """The bottom half of the syntax error handler called in the main loop.
470
397
471 Loop until syntax error is fixed or user cancels.
398 Loop until syntax error is fixed or user cancels.
472 """
399 """
473
400
474 while self.SyntaxTB.last_syntax_error:
401 while self.SyntaxTB.last_syntax_error:
475 # copy and clear last_syntax_error
402 # copy and clear last_syntax_error
476 err = self.SyntaxTB.clear_err_state()
403 err = self.SyntaxTB.clear_err_state()
477 if not self._should_recompile(err):
404 if not self._should_recompile(err):
478 return
405 return
479 try:
406 try:
480 # may set last_syntax_error again if a SyntaxError is raised
407 # may set last_syntax_error again if a SyntaxError is raised
481 self.safe_execfile(err.filename,self.user_ns)
408 self.safe_execfile(err.filename,self.user_ns)
482 except:
409 except:
483 self.showtraceback()
410 self.showtraceback()
484 else:
411 else:
485 try:
412 try:
486 f = file(err.filename)
413 f = file(err.filename)
487 try:
414 try:
488 # This should be inside a display_trap block and I
415 # This should be inside a display_trap block and I
489 # think it is.
416 # think it is.
490 sys.displayhook(f.read())
417 sys.displayhook(f.read())
491 finally:
418 finally:
492 f.close()
419 f.close()
493 except:
420 except:
494 self.showtraceback()
421 self.showtraceback()
495
422
496 def _should_recompile(self,e):
423 def _should_recompile(self,e):
497 """Utility routine for edit_syntax_error"""
424 """Utility routine for edit_syntax_error"""
498
425
499 if e.filename in ('<ipython console>','<input>','<string>',
426 if e.filename in ('<ipython console>','<input>','<string>',
500 '<console>','<BackgroundJob compilation>',
427 '<console>','<BackgroundJob compilation>',
501 None):
428 None):
502
429
503 return False
430 return False
504 try:
431 try:
505 if (self.autoedit_syntax and
432 if (self.autoedit_syntax and
506 not self.ask_yes_no('Return to editor to correct syntax error? '
433 not self.ask_yes_no('Return to editor to correct syntax error? '
507 '[Y/n] ','y')):
434 '[Y/n] ','y')):
508 return False
435 return False
509 except EOFError:
436 except EOFError:
510 return False
437 return False
511
438
512 def int0(x):
439 def int0(x):
513 try:
440 try:
514 return int(x)
441 return int(x)
515 except TypeError:
442 except TypeError:
516 return 0
443 return 0
517 # always pass integer line and offset values to editor hook
444 # always pass integer line and offset values to editor hook
518 try:
445 try:
519 self.hooks.fix_error_editor(e.filename,
446 self.hooks.fix_error_editor(e.filename,
520 int0(e.lineno),int0(e.offset),e.msg)
447 int0(e.lineno),int0(e.offset),e.msg)
521 except TryNext:
448 except TryNext:
522 warn('Could not open editor')
449 warn('Could not open editor')
523 return False
450 return False
524 return True
451 return True
525
452
526 #-------------------------------------------------------------------------
453 #-------------------------------------------------------------------------
527 # Things related to GUI support and pylab
454 # Things related to GUI support and pylab
528 #-------------------------------------------------------------------------
455 #-------------------------------------------------------------------------
529
456
530 def enable_pylab(self, gui=None):
457 def enable_pylab(self, gui=None):
531 """Activate pylab support at runtime.
458 """Activate pylab support at runtime.
532
459
533 This turns on support for matplotlib, preloads into the interactive
460 This turns on support for matplotlib, preloads into the interactive
534 namespace all of numpy and pylab, and configures IPython to correcdtly
461 namespace all of numpy and pylab, and configures IPython to correcdtly
535 interact with the GUI event loop. The GUI backend to be used can be
462 interact with the GUI event loop. The GUI backend to be used can be
536 optionally selected with the optional :param:`gui` argument.
463 optionally selected with the optional :param:`gui` argument.
537
464
538 Parameters
465 Parameters
539 ----------
466 ----------
540 gui : optional, string
467 gui : optional, string
541
468
542 If given, dictates the choice of matplotlib GUI backend to use
469 If given, dictates the choice of matplotlib GUI backend to use
543 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
470 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
544 'gtk'), otherwise we use the default chosen by matplotlib (as
471 'gtk'), otherwise we use the default chosen by matplotlib (as
545 dictated by the matplotlib build-time options plus the user's
472 dictated by the matplotlib build-time options plus the user's
546 matplotlibrc configuration file).
473 matplotlibrc configuration file).
547 """
474 """
548 # We want to prevent the loading of pylab to pollute the user's
475 # We want to prevent the loading of pylab to pollute the user's
549 # namespace as shown by the %who* magics, so we execute the activation
476 # namespace as shown by the %who* magics, so we execute the activation
550 # code in an empty namespace, and we update *both* user_ns and
477 # code in an empty namespace, and we update *both* user_ns and
551 # user_ns_hidden with this information.
478 # user_ns_hidden with this information.
552 ns = {}
479 ns = {}
553 gui = pylab_activate(ns, gui)
480 gui = pylab_activate(ns, gui)
554 self.user_ns.update(ns)
481 self.user_ns.update(ns)
555 self.user_ns_hidden.update(ns)
482 self.user_ns_hidden.update(ns)
556 # Now we must activate the gui pylab wants to use, and fix %run to take
483 # Now we must activate the gui pylab wants to use, and fix %run to take
557 # plot updates into account
484 # plot updates into account
558 enable_gui(gui)
485 enable_gui(gui)
559 self.magic_run = self._pylab_magic_run
486 self.magic_run = self._pylab_magic_run
560
487
561 #-------------------------------------------------------------------------
488 #-------------------------------------------------------------------------
562 # Things related to exiting
489 # Things related to exiting
563 #-------------------------------------------------------------------------
490 #-------------------------------------------------------------------------
564
491
565 def ask_exit(self):
492 def ask_exit(self):
566 """ Ask the shell to exit. Can be overiden and used as a callback. """
493 """ Ask the shell to exit. Can be overiden and used as a callback. """
567 self.exit_now = True
494 self.exit_now = True
568
495
569 def exit(self):
496 def exit(self):
570 """Handle interactive exit.
497 """Handle interactive exit.
571
498
572 This method calls the ask_exit callback."""
499 This method calls the ask_exit callback."""
573 if self.confirm_exit:
500 if self.confirm_exit:
574 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
501 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
575 self.ask_exit()
502 self.ask_exit()
576 else:
503 else:
577 self.ask_exit()
504 self.ask_exit()
578
505
579 #------------------------------------------------------------------------
506 #------------------------------------------------------------------------
580 # Magic overrides
507 # Magic overrides
581 #------------------------------------------------------------------------
508 #------------------------------------------------------------------------
582 # Once the base class stops inheriting from magic, this code needs to be
509 # Once the base class stops inheriting from magic, this code needs to be
583 # moved into a separate machinery as well. For now, at least isolate here
510 # moved into a separate machinery as well. For now, at least isolate here
584 # the magics which this class needs to implement differently from the base
511 # the magics which this class needs to implement differently from the base
585 # class, or that are unique to it.
512 # class, or that are unique to it.
586
513
587 def magic_autoindent(self, parameter_s = ''):
514 def magic_autoindent(self, parameter_s = ''):
588 """Toggle autoindent on/off (if available)."""
515 """Toggle autoindent on/off (if available)."""
589
516
590 self.shell.set_autoindent()
517 self.shell.set_autoindent()
591 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
518 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
592
519
593 def magic_cpaste(self, parameter_s=''):
520 def magic_cpaste(self, parameter_s=''):
594 """Paste & execute a pre-formatted code block from clipboard.
521 """Paste & execute a pre-formatted code block from clipboard.
595
522
596 You must terminate the block with '--' (two minus-signs) alone on the
523 You must terminate the block with '--' (two minus-signs) alone on the
597 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
524 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
598 is the new sentinel for this operation)
525 is the new sentinel for this operation)
599
526
600 The block is dedented prior to execution to enable execution of method
527 The block is dedented prior to execution to enable execution of method
601 definitions. '>' and '+' characters at the beginning of a line are
528 definitions. '>' and '+' characters at the beginning of a line are
602 ignored, to allow pasting directly from e-mails, diff files and
529 ignored, to allow pasting directly from e-mails, diff files and
603 doctests (the '...' continuation prompt is also stripped). The
530 doctests (the '...' continuation prompt is also stripped). The
604 executed block is also assigned to variable named 'pasted_block' for
531 executed block is also assigned to variable named 'pasted_block' for
605 later editing with '%edit pasted_block'.
532 later editing with '%edit pasted_block'.
606
533
607 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
534 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
608 This assigns the pasted block to variable 'foo' as string, without
535 This assigns the pasted block to variable 'foo' as string, without
609 dedenting or executing it (preceding >>> and + is still stripped)
536 dedenting or executing it (preceding >>> and + is still stripped)
610
537
611 '%cpaste -r' re-executes the block previously entered by cpaste.
538 '%cpaste -r' re-executes the block previously entered by cpaste.
612
539
613 Do not be alarmed by garbled output on Windows (it's a readline bug).
540 Do not be alarmed by garbled output on Windows (it's a readline bug).
614 Just press enter and type -- (and press enter again) and the block
541 Just press enter and type -- (and press enter again) and the block
615 will be what was just pasted.
542 will be what was just pasted.
616
543
617 IPython statements (magics, shell escapes) are not supported (yet).
544 IPython statements (magics, shell escapes) are not supported (yet).
618
545
619 See also
546 See also
620 --------
547 --------
621 paste: automatically pull code from clipboard.
548 paste: automatically pull code from clipboard.
622 """
549 """
623
550
624 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
551 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
625 par = args.strip()
552 par = args.strip()
626 if opts.has_key('r'):
553 if opts.has_key('r'):
627 self._rerun_pasted()
554 self._rerun_pasted()
628 return
555 return
629
556
630 sentinel = opts.get('s','--')
557 sentinel = opts.get('s','--')
631
558
632 block = self._strip_pasted_lines_for_code(
559 block = self._strip_pasted_lines_for_code(
633 self._get_pasted_lines(sentinel))
560 self._get_pasted_lines(sentinel))
634
561
635 self._execute_block(block, par)
562 self._execute_block(block, par)
636
563
637 def magic_paste(self, parameter_s=''):
564 def magic_paste(self, parameter_s=''):
638 """Paste & execute a pre-formatted code block from clipboard.
565 """Paste & execute a pre-formatted code block from clipboard.
639
566
640 The text is pulled directly from the clipboard without user
567 The text is pulled directly from the clipboard without user
641 intervention and printed back on the screen before execution (unless
568 intervention and printed back on the screen before execution (unless
642 the -q flag is given to force quiet mode).
569 the -q flag is given to force quiet mode).
643
570
644 The block is dedented prior to execution to enable execution of method
571 The block is dedented prior to execution to enable execution of method
645 definitions. '>' and '+' characters at the beginning of a line are
572 definitions. '>' and '+' characters at the beginning of a line are
646 ignored, to allow pasting directly from e-mails, diff files and
573 ignored, to allow pasting directly from e-mails, diff files and
647 doctests (the '...' continuation prompt is also stripped). The
574 doctests (the '...' continuation prompt is also stripped). The
648 executed block is also assigned to variable named 'pasted_block' for
575 executed block is also assigned to variable named 'pasted_block' for
649 later editing with '%edit pasted_block'.
576 later editing with '%edit pasted_block'.
650
577
651 You can also pass a variable name as an argument, e.g. '%paste foo'.
578 You can also pass a variable name as an argument, e.g. '%paste foo'.
652 This assigns the pasted block to variable 'foo' as string, without
579 This assigns the pasted block to variable 'foo' as string, without
653 dedenting or executing it (preceding >>> and + is still stripped)
580 dedenting or executing it (preceding >>> and + is still stripped)
654
581
655 Options
582 Options
656 -------
583 -------
657
584
658 -r: re-executes the block previously entered by cpaste.
585 -r: re-executes the block previously entered by cpaste.
659
586
660 -q: quiet mode: do not echo the pasted text back to the terminal.
587 -q: quiet mode: do not echo the pasted text back to the terminal.
661
588
662 IPython statements (magics, shell escapes) are not supported (yet).
589 IPython statements (magics, shell escapes) are not supported (yet).
663
590
664 See also
591 See also
665 --------
592 --------
666 cpaste: manually paste code into terminal until you mark its end.
593 cpaste: manually paste code into terminal until you mark its end.
667 """
594 """
668 opts,args = self.parse_options(parameter_s,'rq',mode='string')
595 opts,args = self.parse_options(parameter_s,'rq',mode='string')
669 par = args.strip()
596 par = args.strip()
670 if opts.has_key('r'):
597 if opts.has_key('r'):
671 self._rerun_pasted()
598 self._rerun_pasted()
672 return
599 return
673
600
674 text = self.shell.hooks.clipboard_get()
601 text = self.shell.hooks.clipboard_get()
675 block = self._strip_pasted_lines_for_code(text.splitlines())
602 block = self._strip_pasted_lines_for_code(text.splitlines())
676
603
677 # By default, echo back to terminal unless quiet mode is requested
604 # By default, echo back to terminal unless quiet mode is requested
678 if not opts.has_key('q'):
605 if not opts.has_key('q'):
679 write = self.shell.write
606 write = self.shell.write
680 write(self.shell.pycolorize(block))
607 write(self.shell.pycolorize(block))
681 if not block.endswith('\n'):
608 if not block.endswith('\n'):
682 write('\n')
609 write('\n')
683 write("## -- End pasted text --\n")
610 write("## -- End pasted text --\n")
684
611
685 self._execute_block(block, par)
612 self._execute_block(block, par)
686
613
687
614
688 InteractiveShellABC.register(TerminalInteractiveShell)
615 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,627 +1,627 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """A simple interactive kernel that talks to a frontend over 0MQ.
2 """A simple interactive kernel that talks to a frontend over 0MQ.
3
3
4 Things to do:
4 Things to do:
5
5
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 call set_parent on all the PUB objects with the message about to be executed.
7 call set_parent on all the PUB objects with the message about to be executed.
8 * Implement random port and security key logic.
8 * Implement random port and security key logic.
9 * Implement control messages.
9 * Implement control messages.
10 * Implement event loop and poll version.
10 * Implement event loop and poll version.
11 """
11 """
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 # Standard library imports.
18 # Standard library imports.
19 import __builtin__
19 import __builtin__
20 import atexit
20 import atexit
21 import sys
21 import sys
22 import time
22 import time
23 import traceback
23 import traceback
24
24
25 # System library imports.
25 # System library imports.
26 import zmq
26 import zmq
27
27
28 # Local imports.
28 # Local imports.
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.utils import io
30 from IPython.utils import io
31 from IPython.utils.jsonutil import json_clean
31 from IPython.utils.jsonutil import json_clean
32 from IPython.lib import pylabtools
32 from IPython.lib import pylabtools
33 from IPython.utils.traitlets import Instance, Float
33 from IPython.utils.traitlets import Instance, Float
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
35 start_kernel)
35 start_kernel)
36 from iostream import OutStream
36 from iostream import OutStream
37 from session import Session, Message
37 from session import Session, Message
38 from zmqshell import ZMQInteractiveShell
38 from zmqshell import ZMQInteractiveShell
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Main kernel class
41 # Main kernel class
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 class Kernel(Configurable):
44 class Kernel(Configurable):
45
45
46 #---------------------------------------------------------------------------
46 #---------------------------------------------------------------------------
47 # Kernel interface
47 # Kernel interface
48 #---------------------------------------------------------------------------
48 #---------------------------------------------------------------------------
49
49
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 session = Instance(Session)
51 session = Instance(Session)
52 reply_socket = Instance('zmq.Socket')
52 reply_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
55
55
56 # Private interface
56 # Private interface
57
57
58 # Time to sleep after flushing the stdout/err buffers in each execute
58 # Time to sleep after flushing the stdout/err buffers in each execute
59 # cycle. While this introduces a hard limit on the minimal latency of the
59 # cycle. While this introduces a hard limit on the minimal latency of the
60 # execute cycle, it helps prevent output synchronization problems for
60 # execute cycle, it helps prevent output synchronization problems for
61 # clients.
61 # clients.
62 # Units are in seconds. The minimum zmq latency on local host is probably
62 # Units are in seconds. The minimum zmq latency on local host is probably
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 # a little if it's not enough after more interactive testing.
64 # a little if it's not enough after more interactive testing.
65 _execute_sleep = Float(0.0005, config=True)
65 _execute_sleep = Float(0.0005, config=True)
66
66
67 # Frequency of the kernel's event loop.
67 # Frequency of the kernel's event loop.
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 # adapt to milliseconds.
69 # adapt to milliseconds.
70 _poll_interval = Float(0.05, config=True)
70 _poll_interval = Float(0.05, config=True)
71
71
72 # If the shutdown was requested over the network, we leave here the
72 # If the shutdown was requested over the network, we leave here the
73 # necessary reply message so it can be sent by our registered atexit
73 # necessary reply message so it can be sent by our registered atexit
74 # handler. This ensures that the reply is only sent to clients truly at
74 # handler. This ensures that the reply is only sent to clients truly at
75 # the end of our shutdown process (which happens after the underlying
75 # the end of our shutdown process (which happens after the underlying
76 # IPython shell's own shutdown).
76 # IPython shell's own shutdown).
77 _shutdown_message = None
77 _shutdown_message = None
78
78
79 # This is a dict of port number that the kernel is listening on. It is set
79 # This is a dict of port number that the kernel is listening on. It is set
80 # by record_ports and used by connect_request.
80 # by record_ports and used by connect_request.
81 _recorded_ports = None
81 _recorded_ports = None
82
82
83 def __init__(self, **kwargs):
83 def __init__(self, **kwargs):
84 super(Kernel, self).__init__(**kwargs)
84 super(Kernel, self).__init__(**kwargs)
85
85
86 # Before we even start up the shell, register *first* our exit handlers
86 # Before we even start up the shell, register *first* our exit handlers
87 # so they come before the shell's
87 # so they come before the shell's
88 atexit.register(self._at_shutdown)
88 atexit.register(self._at_shutdown)
89
89
90 # Initialize the InteractiveShell subclass
90 # Initialize the InteractiveShell subclass
91 self.shell = ZMQInteractiveShell.instance()
91 self.shell = ZMQInteractiveShell.instance()
92 self.shell.displayhook.session = self.session
92 self.shell.displayhook.session = self.session
93 self.shell.displayhook.pub_socket = self.pub_socket
93 self.shell.displayhook.pub_socket = self.pub_socket
94
94
95 # TMP - hack while developing
95 # TMP - hack while developing
96 self.shell._reply_content = None
96 self.shell._reply_content = None
97
97
98 # Build dict of handlers for message types
98 # Build dict of handlers for message types
99 msg_types = [ 'execute_request', 'complete_request',
99 msg_types = [ 'execute_request', 'complete_request',
100 'object_info_request', 'history_request',
100 'object_info_request', 'history_request',
101 'connect_request', 'shutdown_request']
101 'connect_request', 'shutdown_request']
102 self.handlers = {}
102 self.handlers = {}
103 for msg_type in msg_types:
103 for msg_type in msg_types:
104 self.handlers[msg_type] = getattr(self, msg_type)
104 self.handlers[msg_type] = getattr(self, msg_type)
105
105
106 def do_one_iteration(self):
106 def do_one_iteration(self):
107 """Do one iteration of the kernel's evaluation loop.
107 """Do one iteration of the kernel's evaluation loop.
108 """
108 """
109 try:
109 try:
110 ident = self.reply_socket.recv(zmq.NOBLOCK)
110 ident = self.reply_socket.recv(zmq.NOBLOCK)
111 except zmq.ZMQError, e:
111 except zmq.ZMQError, e:
112 if e.errno == zmq.EAGAIN:
112 if e.errno == zmq.EAGAIN:
113 return
113 return
114 else:
114 else:
115 raise
115 raise
116 # FIXME: Bug in pyzmq/zmq?
116 # FIXME: Bug in pyzmq/zmq?
117 # assert self.reply_socket.rcvmore(), "Missing message part."
117 # assert self.reply_socket.rcvmore(), "Missing message part."
118 msg = self.reply_socket.recv_json()
118 msg = self.reply_socket.recv_json()
119
119
120 # Print some info about this message and leave a '--->' marker, so it's
120 # Print some info about this message and leave a '--->' marker, so it's
121 # easier to trace visually the message chain when debugging. Each
121 # easier to trace visually the message chain when debugging. Each
122 # handler prints its message at the end.
122 # handler prints its message at the end.
123 # Eventually we'll move these from stdout to a logger.
123 # Eventually we'll move these from stdout to a logger.
124 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
124 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
125 io.raw_print(' Content: ', msg['content'],
125 io.raw_print(' Content: ', msg['content'],
126 '\n --->\n ', sep='', end='')
126 '\n --->\n ', sep='', end='')
127
127
128 # Find and call actual handler for message
128 # Find and call actual handler for message
129 handler = self.handlers.get(msg['msg_type'], None)
129 handler = self.handlers.get(msg['msg_type'], None)
130 if handler is None:
130 if handler is None:
131 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
131 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
132 else:
132 else:
133 handler(ident, msg)
133 handler(ident, msg)
134
134
135 # Check whether we should exit, in case the incoming message set the
135 # Check whether we should exit, in case the incoming message set the
136 # exit flag on
136 # exit flag on
137 if self.shell.exit_now:
137 if self.shell.exit_now:
138 io.raw_print('\nExiting IPython kernel...')
138 io.raw_print('\nExiting IPython kernel...')
139 # We do a normal, clean exit, which allows any actions registered
139 # We do a normal, clean exit, which allows any actions registered
140 # via atexit (such as history saving) to take place.
140 # via atexit (such as history saving) to take place.
141 sys.exit(0)
141 sys.exit(0)
142
142
143
143
144 def start(self):
144 def start(self):
145 """ Start the kernel main loop.
145 """ Start the kernel main loop.
146 """
146 """
147 while True:
147 while True:
148 time.sleep(self._poll_interval)
148 time.sleep(self._poll_interval)
149 self.do_one_iteration()
149 self.do_one_iteration()
150
150
151 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
151 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
152 """Record the ports that this kernel is using.
152 """Record the ports that this kernel is using.
153
153
154 The creator of the Kernel instance must call this methods if they
154 The creator of the Kernel instance must call this methods if they
155 want the :meth:`connect_request` method to return the port numbers.
155 want the :meth:`connect_request` method to return the port numbers.
156 """
156 """
157 self._recorded_ports = {
157 self._recorded_ports = {
158 'xrep_port' : xrep_port,
158 'xrep_port' : xrep_port,
159 'pub_port' : pub_port,
159 'pub_port' : pub_port,
160 'req_port' : req_port,
160 'req_port' : req_port,
161 'hb_port' : hb_port
161 'hb_port' : hb_port
162 }
162 }
163
163
164 #---------------------------------------------------------------------------
164 #---------------------------------------------------------------------------
165 # Kernel request handlers
165 # Kernel request handlers
166 #---------------------------------------------------------------------------
166 #---------------------------------------------------------------------------
167
167
168 def _publish_pyin(self, code, parent):
168 def _publish_pyin(self, code, parent):
169 """Publish the code request on the pyin stream."""
169 """Publish the code request on the pyin stream."""
170
170
171 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
171 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
172 self.pub_socket.send_json(pyin_msg)
172 self.pub_socket.send_json(pyin_msg)
173
173
174 def execute_request(self, ident, parent):
174 def execute_request(self, ident, parent):
175
175
176 status_msg = self.session.msg(
176 status_msg = self.session.msg(
177 u'status',
177 u'status',
178 {u'execution_state':u'busy'},
178 {u'execution_state':u'busy'},
179 parent=parent
179 parent=parent
180 )
180 )
181 self.pub_socket.send_json(status_msg)
181 self.pub_socket.send_json(status_msg)
182
182
183 try:
183 try:
184 content = parent[u'content']
184 content = parent[u'content']
185 code = content[u'code']
185 code = content[u'code']
186 silent = content[u'silent']
186 silent = content[u'silent']
187 except:
187 except:
188 io.raw_print_err("Got bad msg: ")
188 io.raw_print_err("Got bad msg: ")
189 io.raw_print_err(Message(parent))
189 io.raw_print_err(Message(parent))
190 return
190 return
191
191
192 shell = self.shell # we'll need this a lot here
192 shell = self.shell # we'll need this a lot here
193
193
194 # Replace raw_input. Note that is not sufficient to replace
194 # Replace raw_input. Note that is not sufficient to replace
195 # raw_input in the user namespace.
195 # raw_input in the user namespace.
196 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
196 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
197 __builtin__.raw_input = raw_input
197 __builtin__.raw_input = raw_input
198
198
199 # Set the parent message of the display hook and out streams.
199 # Set the parent message of the display hook and out streams.
200 shell.displayhook.set_parent(parent)
200 shell.displayhook.set_parent(parent)
201 sys.stdout.set_parent(parent)
201 sys.stdout.set_parent(parent)
202 sys.stderr.set_parent(parent)
202 sys.stderr.set_parent(parent)
203
203
204 # Re-broadcast our input for the benefit of listening clients, and
204 # Re-broadcast our input for the benefit of listening clients, and
205 # start computing output
205 # start computing output
206 if not silent:
206 if not silent:
207 self._publish_pyin(code, parent)
207 self._publish_pyin(code, parent)
208
208
209 reply_content = {}
209 reply_content = {}
210 try:
210 try:
211 if silent:
211 if silent:
212 # runcode uses 'exec' mode, so no displayhook will fire, and it
212 # runcode uses 'exec' mode, so no displayhook will fire, and it
213 # doesn't call logging or history manipulations. Print
213 # doesn't call logging or history manipulations. Print
214 # statements in that code will obviously still execute.
214 # statements in that code will obviously still execute.
215 shell.runcode(code)
215 shell.runcode(code)
216 else:
216 else:
217 # FIXME: runlines calls the exception handler itself.
217 # FIXME: runlines calls the exception handler itself.
218 shell._reply_content = None
218 shell._reply_content = None
219
219
220 # For now leave this here until we're sure we can stop using it
220 # For now leave this here until we're sure we can stop using it
221 #shell.runlines(code)
221 #shell.runlines(code)
222
222
223 # Experimental: cell mode! Test more before turning into
223 # Experimental: cell mode! Test more before turning into
224 # default and removing the hacks around runlines.
224 # default and removing the hacks around runlines.
225 shell.run_cell(code)
225 shell.run_cell(code)
226 except:
226 except:
227 status = u'error'
227 status = u'error'
228 # FIXME: this code right now isn't being used yet by default,
228 # FIXME: this code right now isn't being used yet by default,
229 # because the runlines() call above directly fires off exception
229 # because the runlines() call above directly fires off exception
230 # reporting. This code, therefore, is only active in the scenario
230 # reporting. This code, therefore, is only active in the scenario
231 # where runlines itself has an unhandled exception. We need to
231 # where runlines itself has an unhandled exception. We need to
232 # uniformize this, for all exception construction to come from a
232 # uniformize this, for all exception construction to come from a
233 # single location in the codbase.
233 # single location in the codbase.
234 etype, evalue, tb = sys.exc_info()
234 etype, evalue, tb = sys.exc_info()
235 tb_list = traceback.format_exception(etype, evalue, tb)
235 tb_list = traceback.format_exception(etype, evalue, tb)
236 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
236 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
237 else:
237 else:
238 status = u'ok'
238 status = u'ok'
239
239
240 reply_content[u'status'] = status
240 reply_content[u'status'] = status
241
241
242 # Return the execution counter so clients can display prompts
242 # Return the execution counter so clients can display prompts
243 reply_content['execution_count'] = shell.execution_count
243 reply_content['execution_count'] = shell.execution_count -1
244
244
245 # FIXME - fish exception info out of shell, possibly left there by
245 # FIXME - fish exception info out of shell, possibly left there by
246 # runlines. We'll need to clean up this logic later.
246 # runlines. We'll need to clean up this logic later.
247 if shell._reply_content is not None:
247 if shell._reply_content is not None:
248 reply_content.update(shell._reply_content)
248 reply_content.update(shell._reply_content)
249
249
250 # At this point, we can tell whether the main code execution succeeded
250 # At this point, we can tell whether the main code execution succeeded
251 # or not. If it did, we proceed to evaluate user_variables/expressions
251 # or not. If it did, we proceed to evaluate user_variables/expressions
252 if reply_content['status'] == 'ok':
252 if reply_content['status'] == 'ok':
253 reply_content[u'user_variables'] = \
253 reply_content[u'user_variables'] = \
254 shell.user_variables(content[u'user_variables'])
254 shell.user_variables(content[u'user_variables'])
255 reply_content[u'user_expressions'] = \
255 reply_content[u'user_expressions'] = \
256 shell.user_expressions(content[u'user_expressions'])
256 shell.user_expressions(content[u'user_expressions'])
257 else:
257 else:
258 # If there was an error, don't even try to compute variables or
258 # If there was an error, don't even try to compute variables or
259 # expressions
259 # expressions
260 reply_content[u'user_variables'] = {}
260 reply_content[u'user_variables'] = {}
261 reply_content[u'user_expressions'] = {}
261 reply_content[u'user_expressions'] = {}
262
262
263 # Payloads should be retrieved regardless of outcome, so we can both
263 # Payloads should be retrieved regardless of outcome, so we can both
264 # recover partial output (that could have been generated early in a
264 # recover partial output (that could have been generated early in a
265 # block, before an error) and clear the payload system always.
265 # block, before an error) and clear the payload system always.
266 reply_content[u'payload'] = shell.payload_manager.read_payload()
266 reply_content[u'payload'] = shell.payload_manager.read_payload()
267 # Be agressive about clearing the payload because we don't want
267 # Be agressive about clearing the payload because we don't want
268 # it to sit in memory until the next execute_request comes in.
268 # it to sit in memory until the next execute_request comes in.
269 shell.payload_manager.clear_payload()
269 shell.payload_manager.clear_payload()
270
270
271 # Send the reply.
271 # Send the reply.
272 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
272 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
273 io.raw_print(reply_msg)
273 io.raw_print(reply_msg)
274
274
275 # Flush output before sending the reply.
275 # Flush output before sending the reply.
276 sys.stdout.flush()
276 sys.stdout.flush()
277 sys.stderr.flush()
277 sys.stderr.flush()
278 # FIXME: on rare occasions, the flush doesn't seem to make it to the
278 # FIXME: on rare occasions, the flush doesn't seem to make it to the
279 # clients... This seems to mitigate the problem, but we definitely need
279 # clients... This seems to mitigate the problem, but we definitely need
280 # to better understand what's going on.
280 # to better understand what's going on.
281 if self._execute_sleep:
281 if self._execute_sleep:
282 time.sleep(self._execute_sleep)
282 time.sleep(self._execute_sleep)
283
283
284 self.reply_socket.send(ident, zmq.SNDMORE)
284 self.reply_socket.send(ident, zmq.SNDMORE)
285 self.reply_socket.send_json(reply_msg)
285 self.reply_socket.send_json(reply_msg)
286 if reply_msg['content']['status'] == u'error':
286 if reply_msg['content']['status'] == u'error':
287 self._abort_queue()
287 self._abort_queue()
288
288
289 status_msg = self.session.msg(
289 status_msg = self.session.msg(
290 u'status',
290 u'status',
291 {u'execution_state':u'idle'},
291 {u'execution_state':u'idle'},
292 parent=parent
292 parent=parent
293 )
293 )
294 self.pub_socket.send_json(status_msg)
294 self.pub_socket.send_json(status_msg)
295
295
296 def complete_request(self, ident, parent):
296 def complete_request(self, ident, parent):
297 txt, matches = self._complete(parent)
297 txt, matches = self._complete(parent)
298 matches = {'matches' : matches,
298 matches = {'matches' : matches,
299 'matched_text' : txt,
299 'matched_text' : txt,
300 'status' : 'ok'}
300 'status' : 'ok'}
301 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
301 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
302 matches, parent, ident)
302 matches, parent, ident)
303 io.raw_print(completion_msg)
303 io.raw_print(completion_msg)
304
304
305 def object_info_request(self, ident, parent):
305 def object_info_request(self, ident, parent):
306 object_info = self.shell.object_inspect(parent['content']['oname'])
306 object_info = self.shell.object_inspect(parent['content']['oname'])
307 # Before we send this object over, we scrub it for JSON usage
307 # Before we send this object over, we scrub it for JSON usage
308 oinfo = json_clean(object_info)
308 oinfo = json_clean(object_info)
309 msg = self.session.send(self.reply_socket, 'object_info_reply',
309 msg = self.session.send(self.reply_socket, 'object_info_reply',
310 oinfo, parent, ident)
310 oinfo, parent, ident)
311 io.raw_print(msg)
311 io.raw_print(msg)
312
312
313 def history_request(self, ident, parent):
313 def history_request(self, ident, parent):
314 output = parent['content']['output']
314 output = parent['content']['output']
315 index = parent['content']['index']
315 index = parent['content']['index']
316 raw = parent['content']['raw']
316 raw = parent['content']['raw']
317 hist = self.shell.get_history(index=index, raw=raw, output=output)
317 hist = self.shell.get_history(index=index, raw=raw, output=output)
318 content = {'history' : hist}
318 content = {'history' : hist}
319 msg = self.session.send(self.reply_socket, 'history_reply',
319 msg = self.session.send(self.reply_socket, 'history_reply',
320 content, parent, ident)
320 content, parent, ident)
321 io.raw_print(msg)
321 io.raw_print(msg)
322
322
323 def connect_request(self, ident, parent):
323 def connect_request(self, ident, parent):
324 if self._recorded_ports is not None:
324 if self._recorded_ports is not None:
325 content = self._recorded_ports.copy()
325 content = self._recorded_ports.copy()
326 else:
326 else:
327 content = {}
327 content = {}
328 msg = self.session.send(self.reply_socket, 'connect_reply',
328 msg = self.session.send(self.reply_socket, 'connect_reply',
329 content, parent, ident)
329 content, parent, ident)
330 io.raw_print(msg)
330 io.raw_print(msg)
331
331
332 def shutdown_request(self, ident, parent):
332 def shutdown_request(self, ident, parent):
333 self.shell.exit_now = True
333 self.shell.exit_now = True
334 self._shutdown_message = self.session.msg(u'shutdown_reply', {}, parent)
334 self._shutdown_message = self.session.msg(u'shutdown_reply', {}, parent)
335 sys.exit(0)
335 sys.exit(0)
336
336
337 #---------------------------------------------------------------------------
337 #---------------------------------------------------------------------------
338 # Protected interface
338 # Protected interface
339 #---------------------------------------------------------------------------
339 #---------------------------------------------------------------------------
340
340
341 def _abort_queue(self):
341 def _abort_queue(self):
342 while True:
342 while True:
343 try:
343 try:
344 ident = self.reply_socket.recv(zmq.NOBLOCK)
344 ident = self.reply_socket.recv(zmq.NOBLOCK)
345 except zmq.ZMQError, e:
345 except zmq.ZMQError, e:
346 if e.errno == zmq.EAGAIN:
346 if e.errno == zmq.EAGAIN:
347 break
347 break
348 else:
348 else:
349 assert self.reply_socket.rcvmore(), \
349 assert self.reply_socket.rcvmore(), \
350 "Unexpected missing message part."
350 "Unexpected missing message part."
351 msg = self.reply_socket.recv_json()
351 msg = self.reply_socket.recv_json()
352 io.raw_print("Aborting:\n", Message(msg))
352 io.raw_print("Aborting:\n", Message(msg))
353 msg_type = msg['msg_type']
353 msg_type = msg['msg_type']
354 reply_type = msg_type.split('_')[0] + '_reply'
354 reply_type = msg_type.split('_')[0] + '_reply'
355 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
355 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
356 io.raw_print(reply_msg)
356 io.raw_print(reply_msg)
357 self.reply_socket.send(ident,zmq.SNDMORE)
357 self.reply_socket.send(ident,zmq.SNDMORE)
358 self.reply_socket.send_json(reply_msg)
358 self.reply_socket.send_json(reply_msg)
359 # We need to wait a bit for requests to come in. This can probably
359 # We need to wait a bit for requests to come in. This can probably
360 # be set shorter for true asynchronous clients.
360 # be set shorter for true asynchronous clients.
361 time.sleep(0.1)
361 time.sleep(0.1)
362
362
363 def _raw_input(self, prompt, ident, parent):
363 def _raw_input(self, prompt, ident, parent):
364 # Flush output before making the request.
364 # Flush output before making the request.
365 sys.stderr.flush()
365 sys.stderr.flush()
366 sys.stdout.flush()
366 sys.stdout.flush()
367
367
368 # Send the input request.
368 # Send the input request.
369 content = dict(prompt=prompt)
369 content = dict(prompt=prompt)
370 msg = self.session.msg(u'input_request', content, parent)
370 msg = self.session.msg(u'input_request', content, parent)
371 self.req_socket.send_json(msg)
371 self.req_socket.send_json(msg)
372
372
373 # Await a response.
373 # Await a response.
374 reply = self.req_socket.recv_json()
374 reply = self.req_socket.recv_json()
375 try:
375 try:
376 value = reply['content']['value']
376 value = reply['content']['value']
377 except:
377 except:
378 io.raw_print_err("Got bad raw_input reply: ")
378 io.raw_print_err("Got bad raw_input reply: ")
379 io.raw_print_err(Message(parent))
379 io.raw_print_err(Message(parent))
380 value = ''
380 value = ''
381 return value
381 return value
382
382
383 def _complete(self, msg):
383 def _complete(self, msg):
384 c = msg['content']
384 c = msg['content']
385 try:
385 try:
386 cpos = int(c['cursor_pos'])
386 cpos = int(c['cursor_pos'])
387 except:
387 except:
388 # If we don't get something that we can convert to an integer, at
388 # If we don't get something that we can convert to an integer, at
389 # least attempt the completion guessing the cursor is at the end of
389 # least attempt the completion guessing the cursor is at the end of
390 # the text, if there's any, and otherwise of the line
390 # the text, if there's any, and otherwise of the line
391 cpos = len(c['text'])
391 cpos = len(c['text'])
392 if cpos==0:
392 if cpos==0:
393 cpos = len(c['line'])
393 cpos = len(c['line'])
394 return self.shell.complete(c['text'], c['line'], cpos)
394 return self.shell.complete(c['text'], c['line'], cpos)
395
395
396 def _object_info(self, context):
396 def _object_info(self, context):
397 symbol, leftover = self._symbol_from_context(context)
397 symbol, leftover = self._symbol_from_context(context)
398 if symbol is not None and not leftover:
398 if symbol is not None and not leftover:
399 doc = getattr(symbol, '__doc__', '')
399 doc = getattr(symbol, '__doc__', '')
400 else:
400 else:
401 doc = ''
401 doc = ''
402 object_info = dict(docstring = doc)
402 object_info = dict(docstring = doc)
403 return object_info
403 return object_info
404
404
405 def _symbol_from_context(self, context):
405 def _symbol_from_context(self, context):
406 if not context:
406 if not context:
407 return None, context
407 return None, context
408
408
409 base_symbol_string = context[0]
409 base_symbol_string = context[0]
410 symbol = self.shell.user_ns.get(base_symbol_string, None)
410 symbol = self.shell.user_ns.get(base_symbol_string, None)
411 if symbol is None:
411 if symbol is None:
412 symbol = __builtin__.__dict__.get(base_symbol_string, None)
412 symbol = __builtin__.__dict__.get(base_symbol_string, None)
413 if symbol is None:
413 if symbol is None:
414 return None, context
414 return None, context
415
415
416 context = context[1:]
416 context = context[1:]
417 for i, name in enumerate(context):
417 for i, name in enumerate(context):
418 new_symbol = getattr(symbol, name, None)
418 new_symbol = getattr(symbol, name, None)
419 if new_symbol is None:
419 if new_symbol is None:
420 return symbol, context[i:]
420 return symbol, context[i:]
421 else:
421 else:
422 symbol = new_symbol
422 symbol = new_symbol
423
423
424 return symbol, []
424 return symbol, []
425
425
426 def _at_shutdown(self):
426 def _at_shutdown(self):
427 """Actions taken at shutdown by the kernel, called by python's atexit.
427 """Actions taken at shutdown by the kernel, called by python's atexit.
428 """
428 """
429 # io.rprint("Kernel at_shutdown") # dbg
429 # io.rprint("Kernel at_shutdown") # dbg
430 if self._shutdown_message is not None:
430 if self._shutdown_message is not None:
431 self.reply_socket.send_json(self._shutdown_message)
431 self.reply_socket.send_json(self._shutdown_message)
432 io.raw_print(self._shutdown_message)
432 io.raw_print(self._shutdown_message)
433 # A very short sleep to give zmq time to flush its message buffers
433 # A very short sleep to give zmq time to flush its message buffers
434 # before Python truly shuts down.
434 # before Python truly shuts down.
435 time.sleep(0.01)
435 time.sleep(0.01)
436
436
437
437
438 class QtKernel(Kernel):
438 class QtKernel(Kernel):
439 """A Kernel subclass with Qt support."""
439 """A Kernel subclass with Qt support."""
440
440
441 def start(self):
441 def start(self):
442 """Start a kernel with QtPy4 event loop integration."""
442 """Start a kernel with QtPy4 event loop integration."""
443
443
444 from PyQt4 import QtCore
444 from PyQt4 import QtCore
445 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
445 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
446
446
447 self.app = get_app_qt4([" "])
447 self.app = get_app_qt4([" "])
448 self.app.setQuitOnLastWindowClosed(False)
448 self.app.setQuitOnLastWindowClosed(False)
449 self.timer = QtCore.QTimer()
449 self.timer = QtCore.QTimer()
450 self.timer.timeout.connect(self.do_one_iteration)
450 self.timer.timeout.connect(self.do_one_iteration)
451 # Units for the timer are in milliseconds
451 # Units for the timer are in milliseconds
452 self.timer.start(1000*self._poll_interval)
452 self.timer.start(1000*self._poll_interval)
453 start_event_loop_qt4(self.app)
453 start_event_loop_qt4(self.app)
454
454
455
455
456 class WxKernel(Kernel):
456 class WxKernel(Kernel):
457 """A Kernel subclass with Wx support."""
457 """A Kernel subclass with Wx support."""
458
458
459 def start(self):
459 def start(self):
460 """Start a kernel with wx event loop support."""
460 """Start a kernel with wx event loop support."""
461
461
462 import wx
462 import wx
463 from IPython.lib.guisupport import start_event_loop_wx
463 from IPython.lib.guisupport import start_event_loop_wx
464
464
465 doi = self.do_one_iteration
465 doi = self.do_one_iteration
466 # Wx uses milliseconds
466 # Wx uses milliseconds
467 poll_interval = int(1000*self._poll_interval)
467 poll_interval = int(1000*self._poll_interval)
468
468
469 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
469 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
470 # We make the Frame hidden when we create it in the main app below.
470 # We make the Frame hidden when we create it in the main app below.
471 class TimerFrame(wx.Frame):
471 class TimerFrame(wx.Frame):
472 def __init__(self, func):
472 def __init__(self, func):
473 wx.Frame.__init__(self, None, -1)
473 wx.Frame.__init__(self, None, -1)
474 self.timer = wx.Timer(self)
474 self.timer = wx.Timer(self)
475 # Units for the timer are in milliseconds
475 # Units for the timer are in milliseconds
476 self.timer.Start(poll_interval)
476 self.timer.Start(poll_interval)
477 self.Bind(wx.EVT_TIMER, self.on_timer)
477 self.Bind(wx.EVT_TIMER, self.on_timer)
478 self.func = func
478 self.func = func
479
479
480 def on_timer(self, event):
480 def on_timer(self, event):
481 self.func()
481 self.func()
482
482
483 # We need a custom wx.App to create our Frame subclass that has the
483 # We need a custom wx.App to create our Frame subclass that has the
484 # wx.Timer to drive the ZMQ event loop.
484 # wx.Timer to drive the ZMQ event loop.
485 class IPWxApp(wx.App):
485 class IPWxApp(wx.App):
486 def OnInit(self):
486 def OnInit(self):
487 self.frame = TimerFrame(doi)
487 self.frame = TimerFrame(doi)
488 self.frame.Show(False)
488 self.frame.Show(False)
489 return True
489 return True
490
490
491 # The redirect=False here makes sure that wx doesn't replace
491 # The redirect=False here makes sure that wx doesn't replace
492 # sys.stdout/stderr with its own classes.
492 # sys.stdout/stderr with its own classes.
493 self.app = IPWxApp(redirect=False)
493 self.app = IPWxApp(redirect=False)
494 start_event_loop_wx(self.app)
494 start_event_loop_wx(self.app)
495
495
496
496
497 class TkKernel(Kernel):
497 class TkKernel(Kernel):
498 """A Kernel subclass with Tk support."""
498 """A Kernel subclass with Tk support."""
499
499
500 def start(self):
500 def start(self):
501 """Start a Tk enabled event loop."""
501 """Start a Tk enabled event loop."""
502
502
503 import Tkinter
503 import Tkinter
504 doi = self.do_one_iteration
504 doi = self.do_one_iteration
505 # Tk uses milliseconds
505 # Tk uses milliseconds
506 poll_interval = int(1000*self._poll_interval)
506 poll_interval = int(1000*self._poll_interval)
507 # For Tkinter, we create a Tk object and call its withdraw method.
507 # For Tkinter, we create a Tk object and call its withdraw method.
508 class Timer(object):
508 class Timer(object):
509 def __init__(self, func):
509 def __init__(self, func):
510 self.app = Tkinter.Tk()
510 self.app = Tkinter.Tk()
511 self.app.withdraw()
511 self.app.withdraw()
512 self.func = func
512 self.func = func
513
513
514 def on_timer(self):
514 def on_timer(self):
515 self.func()
515 self.func()
516 self.app.after(poll_interval, self.on_timer)
516 self.app.after(poll_interval, self.on_timer)
517
517
518 def start(self):
518 def start(self):
519 self.on_timer() # Call it once to get things going.
519 self.on_timer() # Call it once to get things going.
520 self.app.mainloop()
520 self.app.mainloop()
521
521
522 self.timer = Timer(doi)
522 self.timer = Timer(doi)
523 self.timer.start()
523 self.timer.start()
524
524
525
525
526 class GTKKernel(Kernel):
526 class GTKKernel(Kernel):
527 """A Kernel subclass with GTK support."""
527 """A Kernel subclass with GTK support."""
528
528
529 def start(self):
529 def start(self):
530 """Start the kernel, coordinating with the GTK event loop"""
530 """Start the kernel, coordinating with the GTK event loop"""
531 from .gui.gtkembed import GTKEmbed
531 from .gui.gtkembed import GTKEmbed
532
532
533 gtk_kernel = GTKEmbed(self)
533 gtk_kernel = GTKEmbed(self)
534 gtk_kernel.start()
534 gtk_kernel.start()
535
535
536
536
537 #-----------------------------------------------------------------------------
537 #-----------------------------------------------------------------------------
538 # Kernel main and launch functions
538 # Kernel main and launch functions
539 #-----------------------------------------------------------------------------
539 #-----------------------------------------------------------------------------
540
540
541 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0,
541 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0,
542 independent=False, pylab=False):
542 independent=False, pylab=False):
543 """Launches a localhost kernel, binding to the specified ports.
543 """Launches a localhost kernel, binding to the specified ports.
544
544
545 Parameters
545 Parameters
546 ----------
546 ----------
547 xrep_port : int, optional
547 xrep_port : int, optional
548 The port to use for XREP channel.
548 The port to use for XREP channel.
549
549
550 pub_port : int, optional
550 pub_port : int, optional
551 The port to use for the SUB channel.
551 The port to use for the SUB channel.
552
552
553 req_port : int, optional
553 req_port : int, optional
554 The port to use for the REQ (raw input) channel.
554 The port to use for the REQ (raw input) channel.
555
555
556 hb_port : int, optional
556 hb_port : int, optional
557 The port to use for the hearbeat REP channel.
557 The port to use for the hearbeat REP channel.
558
558
559 independent : bool, optional (default False)
559 independent : bool, optional (default False)
560 If set, the kernel process is guaranteed to survive if this process
560 If set, the kernel process is guaranteed to survive if this process
561 dies. If not set, an effort is made to ensure that the kernel is killed
561 dies. If not set, an effort is made to ensure that the kernel is killed
562 when this process dies. Note that in this case it is still good practice
562 when this process dies. Note that in this case it is still good practice
563 to kill kernels manually before exiting.
563 to kill kernels manually before exiting.
564
564
565 pylab : bool or string, optional (default False)
565 pylab : bool or string, optional (default False)
566 If not False, the kernel will be launched with pylab enabled. If a
566 If not False, the kernel will be launched with pylab enabled. If a
567 string is passed, matplotlib will use the specified backend. Otherwise,
567 string is passed, matplotlib will use the specified backend. Otherwise,
568 matplotlib's default backend will be used.
568 matplotlib's default backend will be used.
569
569
570 Returns
570 Returns
571 -------
571 -------
572 A tuple of form:
572 A tuple of form:
573 (kernel_process, xrep_port, pub_port, req_port)
573 (kernel_process, xrep_port, pub_port, req_port)
574 where kernel_process is a Popen object and the ports are integers.
574 where kernel_process is a Popen object and the ports are integers.
575 """
575 """
576 extra_arguments = []
576 extra_arguments = []
577 if pylab:
577 if pylab:
578 extra_arguments.append('--pylab')
578 extra_arguments.append('--pylab')
579 if isinstance(pylab, basestring):
579 if isinstance(pylab, basestring):
580 extra_arguments.append(pylab)
580 extra_arguments.append(pylab)
581 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
581 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
582 xrep_port, pub_port, req_port, hb_port,
582 xrep_port, pub_port, req_port, hb_port,
583 independent, extra_arguments)
583 independent, extra_arguments)
584
584
585
585
586 def main():
586 def main():
587 """ The IPython kernel main entry point.
587 """ The IPython kernel main entry point.
588 """
588 """
589 parser = make_argument_parser()
589 parser = make_argument_parser()
590 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
590 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
591 const='auto', help = \
591 const='auto', help = \
592 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
592 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
593 given, the GUI backend is matplotlib's, otherwise use one of: \
593 given, the GUI backend is matplotlib's, otherwise use one of: \
594 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
594 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
595 namespace = parser.parse_args()
595 namespace = parser.parse_args()
596
596
597 kernel_class = Kernel
597 kernel_class = Kernel
598
598
599 kernel_classes = {
599 kernel_classes = {
600 'qt' : QtKernel,
600 'qt' : QtKernel,
601 'qt4': QtKernel,
601 'qt4': QtKernel,
602 'inline': Kernel,
602 'inline': Kernel,
603 'wx' : WxKernel,
603 'wx' : WxKernel,
604 'tk' : TkKernel,
604 'tk' : TkKernel,
605 'gtk': GTKKernel,
605 'gtk': GTKKernel,
606 }
606 }
607 if namespace.pylab:
607 if namespace.pylab:
608 if namespace.pylab == 'auto':
608 if namespace.pylab == 'auto':
609 gui, backend = pylabtools.find_gui_and_backend()
609 gui, backend = pylabtools.find_gui_and_backend()
610 else:
610 else:
611 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
611 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
612 kernel_class = kernel_classes.get(gui)
612 kernel_class = kernel_classes.get(gui)
613 if kernel_class is None:
613 if kernel_class is None:
614 raise ValueError('GUI is not supported: %r' % gui)
614 raise ValueError('GUI is not supported: %r' % gui)
615 pylabtools.activate_matplotlib(backend)
615 pylabtools.activate_matplotlib(backend)
616
616
617 kernel = make_kernel(namespace, kernel_class, OutStream)
617 kernel = make_kernel(namespace, kernel_class, OutStream)
618
618
619 if namespace.pylab:
619 if namespace.pylab:
620 pylabtools.import_pylab(kernel.shell.user_ns, backend,
620 pylabtools.import_pylab(kernel.shell.user_ns, backend,
621 shell=kernel.shell)
621 shell=kernel.shell)
622
622
623 start_kernel(namespace, kernel)
623 start_kernel(namespace, kernel)
624
624
625
625
626 if __name__ == '__main__':
626 if __name__ == '__main__':
627 main()
627 main()
General Comments 0
You need to be logged in to leave comments. Login now