##// END OF EJS Templates
Add support for accessing raw data to inputsplitter....
Fernando Perez -
Show More
@@ -1,431 +1,462 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 # Fill the history zero entry, user counter starts at 1
65 self.input_hist.append('\n')
66 self.input_hist_raw.append('\n')
67
68 # Objects related to shadow history management
64 # Objects related to shadow history management
69 self._init_shadow_hist()
65 self._init_shadow_hist()
70
66
67 # Fill the history zero entry, user counter starts at 1
68 self.store_inputs('\n', '\n')
69
71 # For backwards compatibility, we must put these back in the shell
70 # For backwards compatibility, we must put these back in the shell
72 # 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
73 # the shell itself.
72 # the shell itself.
74 shell.input_hist = self.input_hist
73 shell.input_hist = self.input_hist
75 shell.input_hist_raw = self.input_hist_raw
74 shell.input_hist_raw = self.input_hist_raw
76 shell.output_hist = self.output_hist
75 shell.output_hist = self.output_hist
77 shell.dir_hist = self.dir_hist
76 shell.dir_hist = self.dir_hist
78 shell.histfile = self.hist_file
77 shell.histfile = self.hist_file
79 shell.shadowhist = self.shadow_hist
78 shell.shadowhist = self.shadow_hist
80 shell.db = self.shadow_db
79 shell.db = self.shadow_db
81
80
82 def _init_shadow_hist(self):
81 def _init_shadow_hist(self):
83 try:
82 try:
84 self.shadow_db = PickleShareDB(os.path.join(
83 self.shadow_db = PickleShareDB(os.path.join(
85 self.shell.ipython_dir, 'db'))
84 self.shell.ipython_dir, 'db'))
86 except UnicodeDecodeError:
85 except UnicodeDecodeError:
87 print("Your ipython_dir can't be decoded to unicode!")
86 print("Your ipython_dir can't be decoded to unicode!")
88 print("Please set HOME environment variable to something that")
87 print("Please set HOME environment variable to something that")
89 print(r"only has ASCII characters, e.g. c:\home")
88 print(r"only has ASCII characters, e.g. c:\home")
90 print("Now it is", self.ipython_dir)
89 print("Now it is", self.ipython_dir)
91 sys.exit()
90 sys.exit()
92 self.shadow_hist = ShadowHist(self.shadow_db)
91 self.shadow_hist = ShadowHist(self.shadow_db)
93
92
94 def save_hist(self):
93 def save_hist(self):
95 """Save input history to a file (via readline library)."""
94 """Save input history to a file (via readline library)."""
96
95
97 try:
96 try:
98 self.shell.readline.write_history_file(self.hist_file)
97 self.shell.readline.write_history_file(self.hist_file)
99 except:
98 except:
100 print('Unable to save IPython command history to file: ' +
99 print('Unable to save IPython command history to file: ' +
101 `self.hist_file`)
100 `self.hist_file`)
102
101
103 def reload_hist(self):
102 def reload_hist(self):
104 """Reload the input history from disk file."""
103 """Reload the input history from disk file."""
105
104
106 try:
105 try:
107 self.shell.readline.clear_history()
106 self.shell.readline.clear_history()
108 self.shell.readline.read_history_file(self.hist_file)
107 self.shell.readline.read_history_file(self.hist_file)
109 except AttributeError:
108 except AttributeError:
110 pass
109 pass
111
110
112 def get_history(self, index=None, raw=False, output=True):
111 def get_history(self, index=None, raw=False, output=True):
113 """Get the history list.
112 """Get the history list.
114
113
115 Get the input and output history.
114 Get the input and output history.
116
115
117 Parameters
116 Parameters
118 ----------
117 ----------
119 index : n or (n1, n2) or None
118 index : n or (n1, n2) or None
120 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
121 range(n1, n2). If None, then all entries. Raises IndexError if
120 range(n1, n2). If None, then all entries. Raises IndexError if
122 the format of index is incorrect.
121 the format of index is incorrect.
123 raw : bool
122 raw : bool
124 If True, return the raw input.
123 If True, return the raw input.
125 output : bool
124 output : bool
126 If True, then return the output as well.
125 If True, then return the output as well.
127
126
128 Returns
127 Returns
129 -------
128 -------
130 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
131 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
132 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
133 IndexError if no history is found.
132 IndexError if no history is found.
134 """
133 """
135 if raw:
134 if raw:
136 input_hist = self.input_hist_raw
135 input_hist = self.input_hist_raw
137 else:
136 else:
138 input_hist = self.input_hist
137 input_hist = self.input_hist
139 if output:
138 if output:
140 output_hist = self.output_hist
139 output_hist = self.output_hist
141 n = len(input_hist)
140 n = len(input_hist)
142 if index is None:
141 if index is None:
143 start=0; stop=n
142 start=0; stop=n
144 elif isinstance(index, int):
143 elif isinstance(index, int):
145 start=n-index; stop=n
144 start=n-index; stop=n
146 elif isinstance(index, tuple) and len(index) == 2:
145 elif isinstance(index, tuple) and len(index) == 2:
147 start=index[0]; stop=index[1]
146 start=index[0]; stop=index[1]
148 else:
147 else:
149 raise IndexError('Not a valid index for the input history: %r'
148 raise IndexError('Not a valid index for the input history: %r'
150 % index)
149 % index)
151 hist = {}
150 hist = {}
152 for i in range(start, stop):
151 for i in range(start, stop):
153 if output:
152 if output:
154 hist[i] = (input_hist[i], output_hist.get(i))
153 hist[i] = (input_hist[i], output_hist.get(i))
155 else:
154 else:
156 hist[i] = input_hist[i]
155 hist[i] = input_hist[i]
157 if len(hist)==0:
156 if not hist:
158 raise IndexError('No history for range of indices: %r' % index)
157 raise IndexError('No history for range of indices: %r' % index)
159 return hist
158 return hist
160
159
160 def store_inputs(self, source, source_raw=None):
161 """Store source and raw input in history.
162
163 Parameters
164 ----------
165 source : str
166 Python input.
167
168 source_raw : str, optional
169 If given, this is the raw input without any IPython transformations
170 applied to it. If not given, ``source`` is used.
171 """
172 if source_raw is None:
173 source_raw = source
174 self.input_hist.append(source)
175 self.input_hist_raw.append(source_raw)
176 self.shadow_hist.add(source)
177
178 def sync_inputs(self):
179 """Ensure raw and translated histories have same length."""
180 if len(self.input_hist) != len (self.input_hist_raw):
181 self.input_hist_raw = InputList(self.input_hist)
182
183
184 def reset(self):
185 """Clear all histories managed by this object."""
186 self.input_hist[:] = []
187 self.input_hist_raw[:] = []
188 self.output_hist.clear()
189 # The directory history can't be completely empty
190 self.dir_hist[:] = [os.getcwd()]
191
161
192
162 def magic_history(self, parameter_s = ''):
193 def magic_history(self, parameter_s = ''):
163 """Print input history (_i<n> variables), with most recent last.
194 """Print input history (_i<n> variables), with most recent last.
164
195
165 %history -> print at most 40 inputs (some may be multi-line)\\
196 %history -> print at most 40 inputs (some may be multi-line)\\
166 %history n -> print at most n inputs\\
197 %history n -> print at most n inputs\\
167 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
198 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
168
199
169 By default, input history is printed without line numbers so it can be
200 By default, input history is printed without line numbers so it can be
170 directly pasted into an editor.
201 directly pasted into an editor.
171
202
172 With -n, each input's number <n> is shown, and is accessible as the
203 With -n, each input's number <n> is shown, and is accessible as the
173 automatically generated variable _i<n> as well as In[<n>]. Multi-line
204 automatically generated variable _i<n> as well as In[<n>]. Multi-line
174 statements are printed starting at a new line for easy copy/paste.
205 statements are printed starting at a new line for easy copy/paste.
175
206
176 Options:
207 Options:
177
208
178 -n: print line numbers for each input.
209 -n: print line numbers for each input.
179 This feature is only available if numbered prompts are in use.
210 This feature is only available if numbered prompts are in use.
180
211
181 -o: also print outputs for each input.
212 -o: also print outputs for each input.
182
213
183 -p: print classic '>>>' python prompts before each input. This is useful
214 -p: print classic '>>>' python prompts before each input. This is useful
184 for making documentation, and in conjunction with -o, for producing
215 for making documentation, and in conjunction with -o, for producing
185 doctest-ready output.
216 doctest-ready output.
186
217
187 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
218 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
188
219
189 -t: print the 'translated' history, as IPython understands it. IPython
220 -t: print the 'translated' history, as IPython understands it. IPython
190 filters your input and converts it all into valid Python source before
221 filters your input and converts it all into valid Python source before
191 executing it (things like magics or aliases are turned into function
222 executing it (things like magics or aliases are turned into function
192 calls, for example). With this option, you'll see the native history
223 calls, for example). With this option, you'll see the native history
193 instead of the user-entered version: '%cd /' will be seen as
224 instead of the user-entered version: '%cd /' will be seen as
194 'get_ipython().magic("%cd /")' instead of '%cd /'.
225 'get_ipython().magic("%cd /")' instead of '%cd /'.
195
226
196 -g: treat the arg as a pattern to grep for in (full) history.
227 -g: treat the arg as a pattern to grep for in (full) history.
197 This includes the "shadow history" (almost all commands ever written).
228 This includes the "shadow history" (almost all commands ever written).
198 Use '%hist -g' to show full shadow history (may be very long).
229 Use '%hist -g' to show full shadow history (may be very long).
199 In shadow history, every index nuwber starts with 0.
230 In shadow history, every index nuwber starts with 0.
200
231
201 -f FILENAME: instead of printing the output to the screen, redirect it to
232 -f FILENAME: instead of printing the output to the screen, redirect it to
202 the given file. The file is always overwritten, though IPython asks for
233 the given file. The file is always overwritten, though IPython asks for
203 confirmation first if it already exists.
234 confirmation first if it already exists.
204 """
235 """
205
236
206 if not self.shell.displayhook.do_full_cache:
237 if not self.shell.displayhook.do_full_cache:
207 print('This feature is only available if numbered prompts are in use.')
238 print('This feature is only available if numbered prompts are in use.')
208 return
239 return
209 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
240 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
210
241
211 # Check if output to specific file was requested.
242 # Check if output to specific file was requested.
212 try:
243 try:
213 outfname = opts['f']
244 outfname = opts['f']
214 except KeyError:
245 except KeyError:
215 outfile = IPython.utils.io.Term.cout # default
246 outfile = IPython.utils.io.Term.cout # default
216 # We don't want to close stdout at the end!
247 # We don't want to close stdout at the end!
217 close_at_end = False
248 close_at_end = False
218 else:
249 else:
219 if os.path.exists(outfname):
250 if os.path.exists(outfname):
220 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
251 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
221 print('Aborting.')
252 print('Aborting.')
222 return
253 return
223
254
224 outfile = open(outfname,'w')
255 outfile = open(outfname,'w')
225 close_at_end = True
256 close_at_end = True
226
257
227 if 't' in opts:
258 if 't' in opts:
228 input_hist = self.shell.input_hist
259 input_hist = self.shell.input_hist
229 elif 'r' in opts:
260 elif 'r' in opts:
230 input_hist = self.shell.input_hist_raw
261 input_hist = self.shell.input_hist_raw
231 else:
262 else:
232 # Raw history is the default
263 # Raw history is the default
233 input_hist = self.shell.input_hist_raw
264 input_hist = self.shell.input_hist_raw
234
265
235 default_length = 40
266 default_length = 40
236 pattern = None
267 pattern = None
237 if 'g' in opts:
268 if 'g' in opts:
238 init = 1
269 init = 1
239 final = len(input_hist)
270 final = len(input_hist)
240 parts = parameter_s.split(None, 1)
271 parts = parameter_s.split(None, 1)
241 if len(parts) == 1:
272 if len(parts) == 1:
242 parts += '*'
273 parts += '*'
243 head, pattern = parts
274 head, pattern = parts
244 pattern = "*" + pattern + "*"
275 pattern = "*" + pattern + "*"
245 elif len(args) == 0:
276 elif len(args) == 0:
246 final = len(input_hist)-1
277 final = len(input_hist)-1
247 init = max(1,final-default_length)
278 init = max(1,final-default_length)
248 elif len(args) == 1:
279 elif len(args) == 1:
249 final = len(input_hist)
280 final = len(input_hist)
250 init = max(1, final-int(args[0]))
281 init = max(1, final-int(args[0]))
251 elif len(args) == 2:
282 elif len(args) == 2:
252 init, final = map(int, args)
283 init, final = map(int, args)
253 else:
284 else:
254 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
285 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
255 print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout)
286 print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout)
256 return
287 return
257
288
258 width = len(str(final))
289 width = len(str(final))
259 line_sep = ['','\n']
290 line_sep = ['','\n']
260 print_nums = 'n' in opts
291 print_nums = 'n' in opts
261 print_outputs = 'o' in opts
292 print_outputs = 'o' in opts
262 pyprompts = 'p' in opts
293 pyprompts = 'p' in opts
263
294
264 found = False
295 found = False
265 if pattern is not None:
296 if pattern is not None:
266 sh = self.shell.shadowhist.all()
297 sh = self.shell.shadowhist.all()
267 for idx, s in sh:
298 for idx, s in sh:
268 if fnmatch.fnmatch(s, pattern):
299 if fnmatch.fnmatch(s, pattern):
269 print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
300 print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
270 found = True
301 found = True
271
302
272 if found:
303 if found:
273 print("===", file=outfile)
304 print("===", file=outfile)
274 print("shadow history ends, fetch by %rep <number> (must start with 0)",
305 print("shadow history ends, fetch by %rep <number> (must start with 0)",
275 file=outfile)
306 file=outfile)
276 print("=== start of normal history ===", file=outfile)
307 print("=== start of normal history ===", file=outfile)
277
308
278 for in_num in range(init, final):
309 for in_num in range(init, final):
279 # Print user history with tabs expanded to 4 spaces. The GUI clients
310 # Print user history with tabs expanded to 4 spaces. The GUI clients
280 # use hard tabs for easier usability in auto-indented code, but we want
311 # use hard tabs for easier usability in auto-indented code, but we want
281 # to produce PEP-8 compliant history for safe pasting into an editor.
312 # to produce PEP-8 compliant history for safe pasting into an editor.
282 inline = input_hist[in_num].expandtabs(4)
313 inline = input_hist[in_num].expandtabs(4)
283
314
284 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
315 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
285 continue
316 continue
286
317
287 multiline = int(inline.count('\n') > 1)
318 multiline = int(inline.count('\n') > 1)
288 if print_nums:
319 if print_nums:
289 print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
320 print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
290 file=outfile)
321 file=outfile)
291 if pyprompts:
322 if pyprompts:
292 print('>>>', file=outfile)
323 print('>>>', file=outfile)
293 if multiline:
324 if multiline:
294 lines = inline.splitlines()
325 lines = inline.splitlines()
295 print('\n... '.join(lines), file=outfile)
326 print('\n... '.join(lines), file=outfile)
296 print('... ', file=outfile)
327 print('... ', file=outfile)
297 else:
328 else:
298 print(inline, end='', file=outfile)
329 print(inline, end='', file=outfile)
299 else:
330 else:
300 print(inline,end='', file=outfile)
331 print(inline,end='', file=outfile)
301 if print_outputs:
332 if print_outputs:
302 output = self.shell.output_hist.get(in_num)
333 output = self.shell.output_hist.get(in_num)
303 if output is not None:
334 if output is not None:
304 print(repr(output), file=outfile)
335 print(repr(output), file=outfile)
305
336
306 if close_at_end:
337 if close_at_end:
307 outfile.close()
338 outfile.close()
308
339
309
340
310 def magic_hist(self, parameter_s=''):
341 def magic_hist(self, parameter_s=''):
311 """Alternate name for %history."""
342 """Alternate name for %history."""
312 return self.magic_history(parameter_s)
343 return self.magic_history(parameter_s)
313
344
314
345
315 def rep_f(self, arg):
346 def rep_f(self, arg):
316 r""" Repeat a command, or get command to input line for editing
347 r""" Repeat a command, or get command to input line for editing
317
348
318 - %rep (no arguments):
349 - %rep (no arguments):
319
350
320 Place a string version of last computation result (stored in the special '_'
351 Place a string version of last computation result (stored in the special '_'
321 variable) to the next input prompt. Allows you to create elaborate command
352 variable) to the next input prompt. Allows you to create elaborate command
322 lines without using copy-paste::
353 lines without using copy-paste::
323
354
324 $ l = ["hei", "vaan"]
355 $ l = ["hei", "vaan"]
325 $ "".join(l)
356 $ "".join(l)
326 ==> heivaan
357 ==> heivaan
327 $ %rep
358 $ %rep
328 $ heivaan_ <== cursor blinking
359 $ heivaan_ <== cursor blinking
329
360
330 %rep 45
361 %rep 45
331
362
332 Place history line 45 to next input prompt. Use %hist to find out the
363 Place history line 45 to next input prompt. Use %hist to find out the
333 number.
364 number.
334
365
335 %rep 1-4 6-7 3
366 %rep 1-4 6-7 3
336
367
337 Repeat the specified lines immediately. Input slice syntax is the same as
368 Repeat the specified lines immediately. Input slice syntax is the same as
338 in %macro and %save.
369 in %macro and %save.
339
370
340 %rep foo
371 %rep foo
341
372
342 Place the most recent line that has the substring "foo" to next input.
373 Place the most recent line that has the substring "foo" to next input.
343 (e.g. 'svn ci -m foobar').
374 (e.g. 'svn ci -m foobar').
344 """
375 """
345
376
346 opts,args = self.parse_options(arg,'',mode='list')
377 opts,args = self.parse_options(arg,'',mode='list')
347 if not args:
378 if not args:
348 self.set_next_input(str(self.shell.user_ns["_"]))
379 self.set_next_input(str(self.shell.user_ns["_"]))
349 return
380 return
350
381
351 if len(args) == 1 and not '-' in args[0]:
382 if len(args) == 1 and not '-' in args[0]:
352 arg = args[0]
383 arg = args[0]
353 if len(arg) > 1 and arg.startswith('0'):
384 if len(arg) > 1 and arg.startswith('0'):
354 # get from shadow hist
385 # get from shadow hist
355 num = int(arg[1:])
386 num = int(arg[1:])
356 line = self.shell.shadowhist.get(num)
387 line = self.shell.shadowhist.get(num)
357 self.set_next_input(str(line))
388 self.set_next_input(str(line))
358 return
389 return
359 try:
390 try:
360 num = int(args[0])
391 num = int(args[0])
361 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
392 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
362 return
393 return
363 except ValueError:
394 except ValueError:
364 pass
395 pass
365
396
366 for h in reversed(self.shell.input_hist_raw):
397 for h in reversed(self.shell.input_hist_raw):
367 if 'rep' in h:
398 if 'rep' in h:
368 continue
399 continue
369 if fnmatch.fnmatch(h,'*' + arg + '*'):
400 if fnmatch.fnmatch(h,'*' + arg + '*'):
370 self.set_next_input(str(h).rstrip())
401 self.set_next_input(str(h).rstrip())
371 return
402 return
372
403
373 try:
404 try:
374 lines = self.extract_input_slices(args, True)
405 lines = self.extract_input_slices(args, True)
375 print("lines", lines)
406 print("lines", lines)
376 self.runlines(lines)
407 self.runlines(lines)
377 except ValueError:
408 except ValueError:
378 print("Not found in recent history:", args)
409 print("Not found in recent history:", args)
379
410
380
411
381 _sentinel = object()
412 _sentinel = object()
382
413
383 class ShadowHist(object):
414 class ShadowHist(object):
384 def __init__(self, db):
415 def __init__(self, db):
385 # cmd => idx mapping
416 # cmd => idx mapping
386 self.curidx = 0
417 self.curidx = 0
387 self.db = db
418 self.db = db
388 self.disabled = False
419 self.disabled = False
389
420
390 def inc_idx(self):
421 def inc_idx(self):
391 idx = self.db.get('shadowhist_idx', 1)
422 idx = self.db.get('shadowhist_idx', 1)
392 self.db['shadowhist_idx'] = idx + 1
423 self.db['shadowhist_idx'] = idx + 1
393 return idx
424 return idx
394
425
395 def add(self, ent):
426 def add(self, ent):
396 if self.disabled:
427 if self.disabled:
397 return
428 return
398 try:
429 try:
399 old = self.db.hget('shadowhist', ent, _sentinel)
430 old = self.db.hget('shadowhist', ent, _sentinel)
400 if old is not _sentinel:
431 if old is not _sentinel:
401 return
432 return
402 newidx = self.inc_idx()
433 newidx = self.inc_idx()
403 #print("new", newidx) # dbg
434 #print("new", newidx) # dbg
404 self.db.hset('shadowhist',ent, newidx)
435 self.db.hset('shadowhist',ent, newidx)
405 except:
436 except:
406 ipapi.get().showtraceback()
437 ipapi.get().showtraceback()
407 print("WARNING: disabling shadow history")
438 print("WARNING: disabling shadow history")
408 self.disabled = True
439 self.disabled = True
409
440
410 def all(self):
441 def all(self):
411 d = self.db.hdict('shadowhist')
442 d = self.db.hdict('shadowhist')
412 items = [(i,s) for (s,i) in d.items()]
443 items = [(i,s) for (s,i) in d.items()]
413 items.sort()
444 items.sort()
414 return items
445 return items
415
446
416 def get(self, idx):
447 def get(self, idx):
417 all = self.all()
448 all = self.all()
418
449
419 for k, v in all:
450 for k, v in all:
420 if k == idx:
451 if k == idx:
421 return v
452 return v
422
453
423
454
424 def init_ipython(ip):
455 def init_ipython(ip):
425 ip.define_magic("rep",rep_f)
456 ip.define_magic("rep",rep_f)
426 ip.define_magic("hist",magic_hist)
457 ip.define_magic("hist",magic_hist)
427 ip.define_magic("history",magic_history)
458 ip.define_magic("history",magic_history)
428
459
429 # XXX - ipy_completers are in quarantine, need to be updated to new apis
460 # XXX - ipy_completers are in quarantine, need to be updated to new apis
430 #import ipy_completers
461 #import ipy_completers
431 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
462 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,987 +1,1020 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
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
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'
376 # to add '\n' at the end of source to run commands like ' a=1'
377 # directly, but this fails for more complicated scenarios
377 # directly, but this fails for more complicated scenarios
378
378
379 if not self._buffer and lines[:1] in [' ', '\t'] and \
379 if not self._buffer and lines[:1] in [' ', '\t'] and \
380 not comment_line_re.match(lines):
380 not comment_line_re.match(lines):
381 lines = 'if 1:\n%s' % lines
381 lines = 'if 1:\n%s' % lines
382
382
383 self._store(lines)
383 self._store(lines)
384 source = self.source
384 source = self.source
385
385
386 # Before calling _compile(), reset the code object to None so that if an
386 # 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
387 # exception is raised in compilation, we don't mislead by having
388 # inconsistent code/source attributes.
388 # inconsistent code/source attributes.
389 self.code, self._is_complete = None, None
389 self.code, self._is_complete = None, None
390
390
391 # Honor termination lines properly
391 # Honor termination lines properly
392 if source.rstrip().endswith('\\'):
392 if source.rstrip().endswith('\\'):
393 return False
393 return False
394
394
395 self._update_indent(lines)
395 self._update_indent(lines)
396 try:
396 try:
397 self.code = self._compile(source)
397 self.code = self._compile(source)
398 # Invalid syntax can produce any of a number of different errors from
398 # 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
399 # inside the compiler, so we have to catch them all. Syntax errors
400 # immediately produce a 'ready' block, so the invalid Python can be
400 # immediately produce a 'ready' block, so the invalid Python can be
401 # sent to the kernel for evaluation with possible ipython
401 # sent to the kernel for evaluation with possible ipython
402 # special-syntax conversion.
402 # special-syntax conversion.
403 except (SyntaxError, OverflowError, ValueError, TypeError,
403 except (SyntaxError, OverflowError, ValueError, TypeError,
404 MemoryError):
404 MemoryError):
405 self._is_complete = True
405 self._is_complete = True
406 else:
406 else:
407 # Compilation didn't produce any exceptions (though it may not have
407 # Compilation didn't produce any exceptions (though it may not have
408 # given a complete code object)
408 # given a complete code object)
409 self._is_complete = self.code is not None
409 self._is_complete = self.code is not None
410
410
411 return self._is_complete
411 return self._is_complete
412
412
413 def push_accepts_more(self):
413 def push_accepts_more(self):
414 """Return whether a block of interactive input can accept more input.
414 """Return whether a block of interactive input can accept more input.
415
415
416 This method is meant to be used by line-oriented frontends, who need to
416 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
417 guess whether a block is complete or not based solely on prior and
418 current input lines. The InputSplitter considers it has a complete
418 current input lines. The InputSplitter considers it has a complete
419 interactive block and will not accept more input only when either a
419 interactive block and will not accept more input only when either a
420 SyntaxError is raised, or *all* of the following are true:
420 SyntaxError is raised, or *all* of the following are true:
421
421
422 1. The input compiles to a complete statement.
422 1. The input compiles to a complete statement.
423
423
424 2. The indentation level is flush-left (because if we are indented,
424 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
425 like inside a function definition or for loop, we need to keep
426 reading new input).
426 reading new input).
427
427
428 3. There is one extra line consisting only of whitespace.
428 3. There is one extra line consisting only of whitespace.
429
429
430 Because of condition #3, this method should be used only by
430 Because of condition #3, this method should be used only by
431 *line-oriented* frontends, since it means that intermediate blank lines
431 *line-oriented* frontends, since it means that intermediate blank lines
432 are not allowed in function definitions (or any other indented block).
432 are not allowed in function definitions (or any other indented block).
433
433
434 Block-oriented frontends that have a separate keyboard event to
434 Block-oriented frontends that have a separate keyboard event to
435 indicate execution should use the :meth:`split_blocks` method instead.
435 indicate execution should use the :meth:`split_blocks` method instead.
436
436
437 If the current input produces a syntax error, this method immediately
437 If the current input produces a syntax error, this method immediately
438 returns False but does *not* raise the syntax error exception, as
438 returns False but does *not* raise the syntax error exception, as
439 typically clients will want to send invalid syntax to an execution
439 typically clients will want to send invalid syntax to an execution
440 backend which might convert the invalid syntax into valid Python via
440 backend which might convert the invalid syntax into valid Python via
441 one of the dynamic IPython mechanisms.
441 one of the dynamic IPython mechanisms.
442 """
442 """
443
443
444 # With incomplete input, unconditionally accept more
444 # With incomplete input, unconditionally accept more
445 if not self._is_complete:
445 if not self._is_complete:
446 return True
446 return True
447
447
448 # If we already have complete input and we're flush left, the answer
448 # 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
449 # 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
450 # 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
451 # 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
452 # the client has entered full 'cell' mode and is feeding lines that
453 # each is complete. In this case we should then keep accepting.
453 # each is complete. In this case we should then keep accepting.
454 # The Qt terminal-like console does precisely this, to provide the
454 # The Qt terminal-like console does precisely this, to provide the
455 # convenience of terminal-like input of single expressions, but
455 # convenience of terminal-like input of single expressions, but
456 # allowing the user (with a separate keystroke) to switch to 'cell'
456 # allowing the user (with a separate keystroke) to switch to 'cell'
457 # mode and type multiple expressions in one shot.
457 # mode and type multiple expressions in one shot.
458 if self.indent_spaces==0:
458 if self.indent_spaces==0:
459 if self.input_mode=='line':
459 if self.input_mode=='line':
460 return False
460 return False
461 else:
461 else:
462 nblocks = len(split_blocks(''.join(self._buffer)))
462 nblocks = len(split_blocks(''.join(self._buffer)))
463 if nblocks==1:
463 if nblocks==1:
464 return False
464 return False
465
465
466 # When input is complete, then termination is marked by an extra blank
466 # When input is complete, then termination is marked by an extra blank
467 # line at the end.
467 # line at the end.
468 last_line = self.source.splitlines()[-1]
468 last_line = self.source.splitlines()[-1]
469 return bool(last_line and not last_line.isspace())
469 return bool(last_line and not last_line.isspace())
470
470
471 def split_blocks(self, lines):
471 def split_blocks(self, lines):
472 """Split a multiline string into multiple input blocks.
472 """Split a multiline string into multiple input blocks.
473
473
474 Note: this method starts by performing a full reset().
474 Note: this method starts by performing a full reset().
475
475
476 Parameters
476 Parameters
477 ----------
477 ----------
478 lines : str
478 lines : str
479 A possibly multiline string.
479 A possibly multiline string.
480
480
481 Returns
481 Returns
482 -------
482 -------
483 blocks : list
483 blocks : list
484 A list of strings, each possibly multiline. Each string corresponds
484 A list of strings, each possibly multiline. Each string corresponds
485 to a single block that can be compiled in 'single' mode (unless it
485 to a single block that can be compiled in 'single' mode (unless it
486 has a syntax error)."""
486 has a syntax error)."""
487
487
488 # This code is fairly delicate. If you make any changes here, make
488 # 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
489 # absolutely sure that you do run the full test suite and ALL tests
490 # pass.
490 # pass.
491
491
492 self.reset()
492 self.reset()
493 blocks = []
493 blocks = []
494
494
495 # Reversed copy so we can use pop() efficiently and consume the input
495 # Reversed copy so we can use pop() efficiently and consume the input
496 # as a stack
496 # as a stack
497 lines = lines.splitlines()[::-1]
497 lines = lines.splitlines()[::-1]
498 # Outer loop over all input
498 # Outer loop over all input
499 while lines:
499 while lines:
500 #print 'Current lines:', lines # dbg
500 #print 'Current lines:', lines # dbg
501 # Inner loop to build each block
501 # Inner loop to build each block
502 while True:
502 while True:
503 # Safety exit from inner loop
503 # Safety exit from inner loop
504 if not lines:
504 if not lines:
505 break
505 break
506 # Grab next line but don't push it yet
506 # Grab next line but don't push it yet
507 next_line = lines.pop()
507 next_line = lines.pop()
508 # Blank/empty lines are pushed as-is
508 # Blank/empty lines are pushed as-is
509 if not next_line or next_line.isspace():
509 if not next_line or next_line.isspace():
510 self.push(next_line)
510 self.push(next_line)
511 continue
511 continue
512
512
513 # Check indentation changes caused by the *next* line
513 # Check indentation changes caused by the *next* line
514 indent_spaces, _full_dedent = self._find_indent(next_line)
514 indent_spaces, _full_dedent = self._find_indent(next_line)
515
515
516 # If the next line causes a dedent, it can be for two differnt
516 # 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
517 # reasons: either an explicit de-dent by the user or a
518 # return/raise/pass statement. These MUST be handled
518 # return/raise/pass statement. These MUST be handled
519 # separately:
519 # separately:
520 #
520 #
521 # 1. the first case is only detected when the actual explicit
521 # 1. the first case is only detected when the actual explicit
522 # dedent happens, and that would be the *first* line of a *new*
522 # 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
523 # block. Thus, we must put the line back into the input buffer
524 # so that it starts a new block on the next pass.
524 # so that it starts a new block on the next pass.
525 #
525 #
526 # 2. the second case is detected in the line before the actual
526 # 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
527 # dedent happens, so , we consume the line and we can break out
528 # to start a new block.
528 # to start a new block.
529
529
530 # Case 1, explicit dedent causes a break.
530 # Case 1, explicit dedent causes a break.
531 # Note: check that we weren't on the very last line, else we'll
531 # Note: check that we weren't on the very last line, else we'll
532 # enter an infinite loop adding/removing the last line.
532 # enter an infinite loop adding/removing the last line.
533 if _full_dedent and lines and not next_line.startswith(' '):
533 if _full_dedent and lines and not next_line.startswith(' '):
534 lines.append(next_line)
534 lines.append(next_line)
535 break
535 break
536
536
537 # Otherwise any line is pushed
537 # Otherwise any line is pushed
538 self.push(next_line)
538 self.push(next_line)
539
539
540 # Case 2, full dedent with full block ready:
540 # Case 2, full dedent with full block ready:
541 if _full_dedent or \
541 if _full_dedent or \
542 self.indent_spaces==0 and not self.push_accepts_more():
542 self.indent_spaces==0 and not self.push_accepts_more():
543 break
543 break
544 # Form the new block with the current source input
544 # Form the new block with the current source input
545 blocks.append(self.source_reset())
545 blocks.append(self.source_reset())
546
546
547 #return blocks
547 #return blocks
548 # HACK!!! Now that our input is in blocks but guaranteed to be pure
548 # 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
549 # python syntax, feed it back a second time through the AST-based
550 # splitter, which is more accurate than ours.
550 # splitter, which is more accurate than ours.
551 return split_blocks(''.join(blocks))
551 return split_blocks(''.join(blocks))
552
552
553 #------------------------------------------------------------------------
553 #------------------------------------------------------------------------
554 # Private interface
554 # Private interface
555 #------------------------------------------------------------------------
555 #------------------------------------------------------------------------
556
556
557 def _find_indent(self, line):
557 def _find_indent(self, line):
558 """Compute the new indentation level for a single line.
558 """Compute the new indentation level for a single line.
559
559
560 Parameters
560 Parameters
561 ----------
561 ----------
562 line : str
562 line : str
563 A single new line of non-whitespace, non-comment Python input.
563 A single new line of non-whitespace, non-comment Python input.
564
564
565 Returns
565 Returns
566 -------
566 -------
567 indent_spaces : int
567 indent_spaces : int
568 New value for the indent level (it may be equal to self.indent_spaces
568 New value for the indent level (it may be equal to self.indent_spaces
569 if indentation doesn't change.
569 if indentation doesn't change.
570
570
571 full_dedent : boolean
571 full_dedent : boolean
572 Whether the new line causes a full flush-left dedent.
572 Whether the new line causes a full flush-left dedent.
573 """
573 """
574 indent_spaces = self.indent_spaces
574 indent_spaces = self.indent_spaces
575 full_dedent = self._full_dedent
575 full_dedent = self._full_dedent
576
576
577 inisp = num_ini_spaces(line)
577 inisp = num_ini_spaces(line)
578 if inisp < indent_spaces:
578 if inisp < indent_spaces:
579 indent_spaces = inisp
579 indent_spaces = inisp
580 if indent_spaces <= 0:
580 if indent_spaces <= 0:
581 #print 'Full dedent in text',self.source # dbg
581 #print 'Full dedent in text',self.source # dbg
582 full_dedent = True
582 full_dedent = True
583
583
584 if line[-1] == ':':
584 if line[-1] == ':':
585 indent_spaces += 4
585 indent_spaces += 4
586 elif dedent_re.match(line):
586 elif dedent_re.match(line):
587 indent_spaces -= 4
587 indent_spaces -= 4
588 if indent_spaces <= 0:
588 if indent_spaces <= 0:
589 full_dedent = True
589 full_dedent = True
590
590
591 # Safety
591 # Safety
592 if indent_spaces < 0:
592 if indent_spaces < 0:
593 indent_spaces = 0
593 indent_spaces = 0
594 #print 'safety' # dbg
594 #print 'safety' # dbg
595
595
596 return indent_spaces, full_dedent
596 return indent_spaces, full_dedent
597
597
598 def _update_indent(self, lines):
598 def _update_indent(self, lines):
599 for line in remove_comments(lines).splitlines():
599 for line in remove_comments(lines).splitlines():
600 if line and not line.isspace():
600 if line and not line.isspace():
601 self.indent_spaces, self._full_dedent = self._find_indent(line)
601 self.indent_spaces, self._full_dedent = self._find_indent(line)
602
602
603 def _store(self, lines):
603 def _store(self, lines, buffer=None, store='source'):
604 """Store one or more lines of input.
604 """Store one or more lines of input.
605
605
606 If input lines are not newline-terminated, a newline is automatically
606 If input lines are not newline-terminated, a newline is automatically
607 appended."""
607 appended."""
608
608
609 if buffer is None:
610 buffer = self._buffer
611
609 if lines.endswith('\n'):
612 if lines.endswith('\n'):
610 self._buffer.append(lines)
613 buffer.append(lines)
611 else:
614 else:
612 self._buffer.append(lines+'\n')
615 buffer.append(lines+'\n')
613 self._set_source()
616 setattr(self, store, self._set_source(buffer))
614
617
615 def _set_source(self):
618 def _set_source(self, buffer):
616 self.source = ''.join(self._buffer).encode(self.encoding)
619 return ''.join(buffer).encode(self.encoding)
617
620
618
621
619 #-----------------------------------------------------------------------------
622 #-----------------------------------------------------------------------------
620 # Functions and classes for IPython-specific syntactic support
623 # Functions and classes for IPython-specific syntactic support
621 #-----------------------------------------------------------------------------
624 #-----------------------------------------------------------------------------
622
625
623 # RegExp for splitting line contents into pre-char//first word-method//rest.
626 # RegExp for splitting line contents into pre-char//first word-method//rest.
624 # For clarity, each group in on one line.
627 # For clarity, each group in on one line.
625
628
626 line_split = re.compile("""
629 line_split = re.compile("""
627 ^(\s*) # any leading space
630 ^(\s*) # any leading space
628 ([,;/%]|!!?|\?\??) # escape character or characters
631 ([,;/%]|!!?|\?\??) # escape character or characters
629 \s*(%?[\w\.\*]*) # function/method, possibly with leading %
632 \s*(%?[\w\.\*]*) # function/method, possibly with leading %
630 # to correctly treat things like '?%magic'
633 # to correctly treat things like '?%magic'
631 (\s+.*$|$) # rest of line
634 (\s+.*$|$) # rest of line
632 """, re.VERBOSE)
635 """, re.VERBOSE)
633
636
634
637
635 def split_user_input(line):
638 def split_user_input(line):
636 """Split user input into early whitespace, esc-char, function part and rest.
639 """Split user input into early whitespace, esc-char, function part and rest.
637
640
638 This is currently handles lines with '=' in them in a very inconsistent
641 This is currently handles lines with '=' in them in a very inconsistent
639 manner.
642 manner.
640
643
641 Examples
644 Examples
642 ========
645 ========
643 >>> split_user_input('x=1')
646 >>> split_user_input('x=1')
644 ('', '', 'x=1', '')
647 ('', '', 'x=1', '')
645 >>> split_user_input('?')
648 >>> split_user_input('?')
646 ('', '?', '', '')
649 ('', '?', '', '')
647 >>> split_user_input('??')
650 >>> split_user_input('??')
648 ('', '??', '', '')
651 ('', '??', '', '')
649 >>> split_user_input(' ?')
652 >>> split_user_input(' ?')
650 (' ', '?', '', '')
653 (' ', '?', '', '')
651 >>> split_user_input(' ??')
654 >>> split_user_input(' ??')
652 (' ', '??', '', '')
655 (' ', '??', '', '')
653 >>> split_user_input('??x')
656 >>> split_user_input('??x')
654 ('', '??', 'x', '')
657 ('', '??', 'x', '')
655 >>> split_user_input('?x=1')
658 >>> split_user_input('?x=1')
656 ('', '', '?x=1', '')
659 ('', '', '?x=1', '')
657 >>> split_user_input('!ls')
660 >>> split_user_input('!ls')
658 ('', '!', 'ls', '')
661 ('', '!', 'ls', '')
659 >>> split_user_input(' !ls')
662 >>> split_user_input(' !ls')
660 (' ', '!', 'ls', '')
663 (' ', '!', 'ls', '')
661 >>> split_user_input('!!ls')
664 >>> split_user_input('!!ls')
662 ('', '!!', 'ls', '')
665 ('', '!!', 'ls', '')
663 >>> split_user_input(' !!ls')
666 >>> split_user_input(' !!ls')
664 (' ', '!!', 'ls', '')
667 (' ', '!!', 'ls', '')
665 >>> split_user_input(',ls')
668 >>> split_user_input(',ls')
666 ('', ',', 'ls', '')
669 ('', ',', 'ls', '')
667 >>> split_user_input(';ls')
670 >>> split_user_input(';ls')
668 ('', ';', 'ls', '')
671 ('', ';', 'ls', '')
669 >>> split_user_input(' ;ls')
672 >>> split_user_input(' ;ls')
670 (' ', ';', 'ls', '')
673 (' ', ';', 'ls', '')
671 >>> split_user_input('f.g(x)')
674 >>> split_user_input('f.g(x)')
672 ('', '', 'f.g(x)', '')
675 ('', '', 'f.g(x)', '')
673 >>> split_user_input('f.g (x)')
676 >>> split_user_input('f.g (x)')
674 ('', '', 'f.g', '(x)')
677 ('', '', 'f.g', '(x)')
675 >>> split_user_input('?%hist')
678 >>> split_user_input('?%hist')
676 ('', '?', '%hist', '')
679 ('', '?', '%hist', '')
677 >>> split_user_input('?x*')
680 >>> split_user_input('?x*')
678 ('', '?', 'x*', '')
681 ('', '?', 'x*', '')
679 """
682 """
680 match = line_split.match(line)
683 match = line_split.match(line)
681 if match:
684 if match:
682 lspace, esc, fpart, rest = match.groups()
685 lspace, esc, fpart, rest = match.groups()
683 else:
686 else:
684 # print "match failed for line '%s'" % line
687 # print "match failed for line '%s'" % line
685 try:
688 try:
686 fpart, rest = line.split(None, 1)
689 fpart, rest = line.split(None, 1)
687 except ValueError:
690 except ValueError:
688 # print "split failed for line '%s'" % line
691 # print "split failed for line '%s'" % line
689 fpart, rest = line,''
692 fpart, rest = line,''
690 lspace = re.match('^(\s*)(.*)', line).groups()[0]
693 lspace = re.match('^(\s*)(.*)', line).groups()[0]
691 esc = ''
694 esc = ''
692
695
693 # fpart has to be a valid python identifier, so it better be only pure
696 # fpart has to be a valid python identifier, so it better be only pure
694 # ascii, no unicode:
697 # ascii, no unicode:
695 try:
698 try:
696 fpart = fpart.encode('ascii')
699 fpart = fpart.encode('ascii')
697 except UnicodeEncodeError:
700 except UnicodeEncodeError:
698 lspace = unicode(lspace)
701 lspace = unicode(lspace)
699 rest = fpart + u' ' + rest
702 rest = fpart + u' ' + rest
700 fpart = u''
703 fpart = u''
701
704
702 #print 'line:<%s>' % line # dbg
705 #print 'line:<%s>' % line # dbg
703 #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg
706 #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg
704 return lspace, esc, fpart.strip(), rest.lstrip()
707 return lspace, esc, fpart.strip(), rest.lstrip()
705
708
706
709
707 # The escaped translators ALL receive a line where their own escape has been
710 # The escaped translators ALL receive a line where their own escape has been
708 # stripped. Only '?' is valid at the end of the line, all others can only be
711 # stripped. Only '?' is valid at the end of the line, all others can only be
709 # placed at the start.
712 # placed at the start.
710
713
711 class LineInfo(object):
714 class LineInfo(object):
712 """A single line of input and associated info.
715 """A single line of input and associated info.
713
716
714 This is a utility class that mostly wraps the output of
717 This is a utility class that mostly wraps the output of
715 :func:`split_user_input` into a convenient object to be passed around
718 :func:`split_user_input` into a convenient object to be passed around
716 during input transformations.
719 during input transformations.
717
720
718 Includes the following as properties:
721 Includes the following as properties:
719
722
720 line
723 line
721 The original, raw line
724 The original, raw line
722
725
723 lspace
726 lspace
724 Any early whitespace before actual text starts.
727 Any early whitespace before actual text starts.
725
728
726 esc
729 esc
727 The initial esc character (or characters, for double-char escapes like
730 The initial esc character (or characters, for double-char escapes like
728 '??' or '!!').
731 '??' or '!!').
729
732
730 fpart
733 fpart
731 The 'function part', which is basically the maximal initial sequence
734 The 'function part', which is basically the maximal initial sequence
732 of valid python identifiers and the '.' character. This is what is
735 of valid python identifiers and the '.' character. This is what is
733 checked for alias and magic transformations, used for auto-calling,
736 checked for alias and magic transformations, used for auto-calling,
734 etc.
737 etc.
735
738
736 rest
739 rest
737 Everything else on the line.
740 Everything else on the line.
738 """
741 """
739 def __init__(self, line):
742 def __init__(self, line):
740 self.line = line
743 self.line = line
741 self.lspace, self.esc, self.fpart, self.rest = \
744 self.lspace, self.esc, self.fpart, self.rest = \
742 split_user_input(line)
745 split_user_input(line)
743
746
744 def __str__(self):
747 def __str__(self):
745 return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc,
748 return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc,
746 self.fpart, self.rest)
749 self.fpart, self.rest)
747
750
748
751
749 # Transformations of the special syntaxes that don't rely on an explicit escape
752 # Transformations of the special syntaxes that don't rely on an explicit escape
750 # character but instead on patterns on the input line
753 # character but instead on patterns on the input line
751
754
752 # The core transformations are implemented as standalone functions that can be
755 # The core transformations are implemented as standalone functions that can be
753 # tested and validated in isolation. Each of these uses a regexp, we
756 # tested and validated in isolation. Each of these uses a regexp, we
754 # pre-compile these and keep them close to each function definition for clarity
757 # pre-compile these and keep them close to each function definition for clarity
755
758
756 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
759 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
757 r'\s*=\s*!\s*(?P<cmd>.*)')
760 r'\s*=\s*!\s*(?P<cmd>.*)')
758
761
759 def transform_assign_system(line):
762 def transform_assign_system(line):
760 """Handle the `files = !ls` syntax."""
763 """Handle the `files = !ls` syntax."""
761 m = _assign_system_re.match(line)
764 m = _assign_system_re.match(line)
762 if m is not None:
765 if m is not None:
763 cmd = m.group('cmd')
766 cmd = m.group('cmd')
764 lhs = m.group('lhs')
767 lhs = m.group('lhs')
765 expr = make_quoted_expr(cmd)
768 expr = make_quoted_expr(cmd)
766 new_line = '%s = get_ipython().getoutput(%s)' % (lhs, expr)
769 new_line = '%s = get_ipython().getoutput(%s)' % (lhs, expr)
767 return new_line
770 return new_line
768 return line
771 return line
769
772
770
773
771 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
774 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
772 r'\s*=\s*%\s*(?P<cmd>.*)')
775 r'\s*=\s*%\s*(?P<cmd>.*)')
773
776
774 def transform_assign_magic(line):
777 def transform_assign_magic(line):
775 """Handle the `a = %who` syntax."""
778 """Handle the `a = %who` syntax."""
776 m = _assign_magic_re.match(line)
779 m = _assign_magic_re.match(line)
777 if m is not None:
780 if m is not None:
778 cmd = m.group('cmd')
781 cmd = m.group('cmd')
779 lhs = m.group('lhs')
782 lhs = m.group('lhs')
780 expr = make_quoted_expr(cmd)
783 expr = make_quoted_expr(cmd)
781 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
784 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
782 return new_line
785 return new_line
783 return line
786 return line
784
787
785
788
786 _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')
789 _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')
787
790
788 def transform_classic_prompt(line):
791 def transform_classic_prompt(line):
789 """Handle inputs that start with '>>> ' syntax."""
792 """Handle inputs that start with '>>> ' syntax."""
790
793
791 if not line or line.isspace():
794 if not line or line.isspace():
792 return line
795 return line
793 m = _classic_prompt_re.match(line)
796 m = _classic_prompt_re.match(line)
794 if m:
797 if m:
795 return line[len(m.group(0)):]
798 return line[len(m.group(0)):]
796 else:
799 else:
797 return line
800 return line
798
801
799
802
800 _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
803 _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
801
804
802 def transform_ipy_prompt(line):
805 def transform_ipy_prompt(line):
803 """Handle inputs that start classic IPython prompt syntax."""
806 """Handle inputs that start classic IPython prompt syntax."""
804
807
805 if not line or line.isspace():
808 if not line or line.isspace():
806 return line
809 return line
807 #print 'LINE: %r' % line # dbg
810 #print 'LINE: %r' % line # dbg
808 m = _ipy_prompt_re.match(line)
811 m = _ipy_prompt_re.match(line)
809 if m:
812 if m:
810 #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
813 #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
811 return line[len(m.group(0)):]
814 return line[len(m.group(0)):]
812 else:
815 else:
813 return line
816 return line
814
817
815
818
816 class EscapedTransformer(object):
819 class EscapedTransformer(object):
817 """Class to transform lines that are explicitly escaped out."""
820 """Class to transform lines that are explicitly escaped out."""
818
821
819 def __init__(self):
822 def __init__(self):
820 tr = { ESC_SHELL : self._tr_system,
823 tr = { ESC_SHELL : self._tr_system,
821 ESC_SH_CAP : self._tr_system2,
824 ESC_SH_CAP : self._tr_system2,
822 ESC_HELP : self._tr_help,
825 ESC_HELP : self._tr_help,
823 ESC_HELP2 : self._tr_help,
826 ESC_HELP2 : self._tr_help,
824 ESC_MAGIC : self._tr_magic,
827 ESC_MAGIC : self._tr_magic,
825 ESC_QUOTE : self._tr_quote,
828 ESC_QUOTE : self._tr_quote,
826 ESC_QUOTE2 : self._tr_quote2,
829 ESC_QUOTE2 : self._tr_quote2,
827 ESC_PAREN : self._tr_paren }
830 ESC_PAREN : self._tr_paren }
828 self.tr = tr
831 self.tr = tr
829
832
830 # Support for syntax transformations that use explicit escapes typed by the
833 # Support for syntax transformations that use explicit escapes typed by the
831 # user at the beginning of a line
834 # user at the beginning of a line
832 @staticmethod
835 @staticmethod
833 def _tr_system(line_info):
836 def _tr_system(line_info):
834 "Translate lines escaped with: !"
837 "Translate lines escaped with: !"
835 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
838 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
836 return '%sget_ipython().system(%s)' % (line_info.lspace,
839 return '%sget_ipython().system(%s)' % (line_info.lspace,
837 make_quoted_expr(cmd))
840 make_quoted_expr(cmd))
838
841
839 @staticmethod
842 @staticmethod
840 def _tr_system2(line_info):
843 def _tr_system2(line_info):
841 "Translate lines escaped with: !!"
844 "Translate lines escaped with: !!"
842 cmd = line_info.line.lstrip()[2:]
845 cmd = line_info.line.lstrip()[2:]
843 return '%sget_ipython().getoutput(%s)' % (line_info.lspace,
846 return '%sget_ipython().getoutput(%s)' % (line_info.lspace,
844 make_quoted_expr(cmd))
847 make_quoted_expr(cmd))
845
848
846 @staticmethod
849 @staticmethod
847 def _tr_help(line_info):
850 def _tr_help(line_info):
848 "Translate lines escaped with: ?/??"
851 "Translate lines escaped with: ?/??"
849 # A naked help line should just fire the intro help screen
852 # A naked help line should just fire the intro help screen
850 if not line_info.line[1:]:
853 if not line_info.line[1:]:
851 return 'get_ipython().show_usage()'
854 return 'get_ipython().show_usage()'
852
855
853 # There may be one or two '?' at the end, move them to the front so that
856 # There may be one or two '?' at the end, move them to the front so that
854 # the rest of the logic can assume escapes are at the start
857 # the rest of the logic can assume escapes are at the start
855 l_ori = line_info
858 l_ori = line_info
856 line = line_info.line
859 line = line_info.line
857 if line.endswith('?'):
860 if line.endswith('?'):
858 line = line[-1] + line[:-1]
861 line = line[-1] + line[:-1]
859 if line.endswith('?'):
862 if line.endswith('?'):
860 line = line[-1] + line[:-1]
863 line = line[-1] + line[:-1]
861 line_info = LineInfo(line)
864 line_info = LineInfo(line)
862
865
863 # From here on, simply choose which level of detail to get, and
866 # From here on, simply choose which level of detail to get, and
864 # special-case the psearch syntax
867 # special-case the psearch syntax
865 if '*' in line_info.line:
868 if '*' in line_info.line:
866 pinfo = 'psearch'
869 pinfo = 'psearch'
867 elif line_info.esc == '?':
870 elif line_info.esc == '?':
868 pinfo = 'pinfo'
871 pinfo = 'pinfo'
869 elif line_info.esc == '??':
872 elif line_info.esc == '??':
870 pinfo = 'pinfo2'
873 pinfo = 'pinfo2'
871
874
872 tpl = '%sget_ipython().magic("%s %s")'
875 tpl = '%sget_ipython().magic("%s %s")'
873 return tpl % (line_info.lspace, pinfo,
876 return tpl % (line_info.lspace, pinfo,
874 ' '.join([line_info.fpart, line_info.rest]).strip())
877 ' '.join([line_info.fpart, line_info.rest]).strip())
875
878
876 @staticmethod
879 @staticmethod
877 def _tr_magic(line_info):
880 def _tr_magic(line_info):
878 "Translate lines escaped with: %"
881 "Translate lines escaped with: %"
879 tpl = '%sget_ipython().magic(%s)'
882 tpl = '%sget_ipython().magic(%s)'
880 cmd = make_quoted_expr(' '.join([line_info.fpart,
883 cmd = make_quoted_expr(' '.join([line_info.fpart,
881 line_info.rest]).strip())
884 line_info.rest]).strip())
882 return tpl % (line_info.lspace, cmd)
885 return tpl % (line_info.lspace, cmd)
883
886
884 @staticmethod
887 @staticmethod
885 def _tr_quote(line_info):
888 def _tr_quote(line_info):
886 "Translate lines escaped with: ,"
889 "Translate lines escaped with: ,"
887 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
890 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
888 '", "'.join(line_info.rest.split()) )
891 '", "'.join(line_info.rest.split()) )
889
892
890 @staticmethod
893 @staticmethod
891 def _tr_quote2(line_info):
894 def _tr_quote2(line_info):
892 "Translate lines escaped with: ;"
895 "Translate lines escaped with: ;"
893 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
896 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
894 line_info.rest)
897 line_info.rest)
895
898
896 @staticmethod
899 @staticmethod
897 def _tr_paren(line_info):
900 def _tr_paren(line_info):
898 "Translate lines escaped with: /"
901 "Translate lines escaped with: /"
899 return '%s%s(%s)' % (line_info.lspace, line_info.fpart,
902 return '%s%s(%s)' % (line_info.lspace, line_info.fpart,
900 ", ".join(line_info.rest.split()))
903 ", ".join(line_info.rest.split()))
901
904
902 def __call__(self, line):
905 def __call__(self, line):
903 """Class to transform lines that are explicitly escaped out.
906 """Class to transform lines that are explicitly escaped out.
904
907
905 This calls the above _tr_* static methods for the actual line
908 This calls the above _tr_* static methods for the actual line
906 translations."""
909 translations."""
907
910
908 # Empty lines just get returned unmodified
911 # Empty lines just get returned unmodified
909 if not line or line.isspace():
912 if not line or line.isspace():
910 return line
913 return line
911
914
912 # Get line endpoints, where the escapes can be
915 # Get line endpoints, where the escapes can be
913 line_info = LineInfo(line)
916 line_info = LineInfo(line)
914
917
915 # If the escape is not at the start, only '?' needs to be special-cased.
918 # If the escape is not at the start, only '?' needs to be special-cased.
916 # All other escapes are only valid at the start
919 # All other escapes are only valid at the start
917 if not line_info.esc in self.tr:
920 if not line_info.esc in self.tr:
918 if line.endswith(ESC_HELP):
921 if line.endswith(ESC_HELP):
919 return self._tr_help(line_info)
922 return self._tr_help(line_info)
920 else:
923 else:
921 # If we don't recognize the escape, don't modify the line
924 # If we don't recognize the escape, don't modify the line
922 return line
925 return line
923
926
924 return self.tr[line_info.esc](line_info)
927 return self.tr[line_info.esc](line_info)
925
928
926
929
927 # A function-looking object to be used by the rest of the code. The purpose of
930 # A function-looking object to be used by the rest of the code. The purpose of
928 # the class in this case is to organize related functionality, more than to
931 # the class in this case is to organize related functionality, more than to
929 # manage state.
932 # manage state.
930 transform_escaped = EscapedTransformer()
933 transform_escaped = EscapedTransformer()
931
934
932
935
933 class IPythonInputSplitter(InputSplitter):
936 class IPythonInputSplitter(InputSplitter):
934 """An input splitter that recognizes all of IPython's special syntax."""
937 """An input splitter that recognizes all of IPython's special syntax."""
935
938
939 # String with raw, untransformed input.
940 source_raw = ''
941
942 # Private attributes
943
944 # List with lines of raw input accumulated so far.
945 _buffer_raw = None
946
947 def __init__(self, input_mode=None):
948 InputSplitter.__init__(self, input_mode)
949 self._buffer_raw = []
950
951 def reset(self):
952 """Reset the input buffer and associated state."""
953 InputSplitter.reset(self)
954 self._buffer_raw[:] = []
955 self.source_raw = ''
956
957 def source_raw_reset(self):
958 """Return input and raw source and perform a full reset.
959 """
960 out = self.source
961 out_r = self.source_raw
962 self.reset()
963 return out, out_r
964
936 def push(self, lines):
965 def push(self, lines):
937 """Push one or more lines of IPython input.
966 """Push one or more lines of IPython input.
938 """
967 """
939 if not lines:
968 if not lines:
940 return super(IPythonInputSplitter, self).push(lines)
969 return super(IPythonInputSplitter, self).push(lines)
941
970
942 lines_list = lines.splitlines()
971 lines_list = lines.splitlines()
943
972
944 transforms = [transform_escaped, transform_assign_system,
973 transforms = [transform_escaped, transform_assign_system,
945 transform_assign_magic, transform_ipy_prompt,
974 transform_assign_magic, transform_ipy_prompt,
946 transform_classic_prompt]
975 transform_classic_prompt]
947
976
948 # Transform logic
977 # Transform logic
949 #
978 #
950 # We only apply the line transformers to the input if we have either no
979 # We only apply the line transformers to the input if we have either no
951 # input yet, or complete input, or if the last line of the buffer ends
980 # input yet, or complete input, or if the last line of the buffer ends
952 # with ':' (opening an indented block). This prevents the accidental
981 # with ':' (opening an indented block). This prevents the accidental
953 # transformation of escapes inside multiline expressions like
982 # transformation of escapes inside multiline expressions like
954 # triple-quoted strings or parenthesized expressions.
983 # triple-quoted strings or parenthesized expressions.
955 #
984 #
956 # The last heuristic, while ugly, ensures that the first line of an
985 # The last heuristic, while ugly, ensures that the first line of an
957 # indented block is correctly transformed.
986 # indented block is correctly transformed.
958 #
987 #
959 # FIXME: try to find a cleaner approach for this last bit.
988 # FIXME: try to find a cleaner approach for this last bit.
960
989
961 # If we were in 'block' mode, since we're going to pump the parent
990 # If we were in 'block' mode, since we're going to pump the parent
962 # class by hand line by line, we need to temporarily switch out to
991 # class by hand line by line, we need to temporarily switch out to
963 # 'line' mode, do a single manual reset and then feed the lines one
992 # 'line' mode, do a single manual reset and then feed the lines one
964 # by one. Note that this only matters if the input has more than one
993 # by one. Note that this only matters if the input has more than one
965 # line.
994 # line.
966 changed_input_mode = False
995 changed_input_mode = False
967
996
968 if len(lines_list)>1 and self.input_mode == 'cell':
997 if self.input_mode == 'cell':
969 self.reset()
998 self.reset()
970 changed_input_mode = True
999 changed_input_mode = True
971 saved_input_mode = 'cell'
1000 saved_input_mode = 'cell'
972 self.input_mode = 'line'
1001 self.input_mode = 'line'
973
1002
1003 # Store raw source before applying any transformations to it. Note
1004 # that this must be done *after* the reset() call that would otherwise
1005 # flush the buffer.
1006 self._store(lines, self._buffer_raw, 'source_raw')
1007
974 try:
1008 try:
975 push = super(IPythonInputSplitter, self).push
1009 push = super(IPythonInputSplitter, self).push
976 for line in lines_list:
1010 for line in lines_list:
977 if self._is_complete or not self._buffer or \
1011 if self._is_complete or not self._buffer or \
978 (self._buffer and self._buffer[-1].rstrip().endswith(':')):
1012 (self._buffer and self._buffer[-1].rstrip().endswith(':')):
979 for f in transforms:
1013 for f in transforms:
980 line = f(line)
1014 line = f(line)
981
1015
982 out = push(line)
1016 out = push(line)
983 finally:
1017 finally:
984 if changed_input_mode:
1018 if changed_input_mode:
985 self.input_mode = saved_input_mode
1019 self.input_mode = saved_input_mode
986
987 return out
1020 return out
@@ -1,2539 +1,2537 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 buffer
372 # User input buffers
373 self.buffer = []
373 self.buffer = []
374 self.buffer_raw = []
374
375
375 # Make an empty namespace, which extension writers can rely on both
376 # Make an empty namespace, which extension writers can rely on both
376 # 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
377 # convenient location for storing additional information and state
378 # convenient location for storing additional information and state
378 # their extensions may require, without fear of collisions with other
379 # their extensions may require, without fear of collisions with other
379 # ipython names that may develop later.
380 # ipython names that may develop later.
380 self.meta = Struct()
381 self.meta = Struct()
381
382
382 # Object variable to store code object waiting execution. This is
383 # Object variable to store code object waiting execution. This is
383 # 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
384 # 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
385 # item which gets cleared once run.
386 # item which gets cleared once run.
386 self.code_to_run = None
387 self.code_to_run = None
387
388
388 # Temporary files used for various purposes. Deleted at exit.
389 # Temporary files used for various purposes. Deleted at exit.
389 self.tempfiles = []
390 self.tempfiles = []
390
391
391 # Keep track of readline usage (later set by init_readline)
392 # Keep track of readline usage (later set by init_readline)
392 self.has_readline = False
393 self.has_readline = False
393
394
394 # 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)
395 # This is not being used anywhere currently.
396 # This is not being used anywhere currently.
396 self.starting_dir = os.getcwd()
397 self.starting_dir = os.getcwd()
397
398
398 # Indentation management
399 # Indentation management
399 self.indent_current_nsp = 0
400 self.indent_current_nsp = 0
400
401
401 # Increasing execution counter
402 # Increasing execution counter
402 self.execution_count = 0
403 self.execution_count = 0
403
404
404 def init_environment(self):
405 def init_environment(self):
405 """Any changes we need to make to the user's environment."""
406 """Any changes we need to make to the user's environment."""
406 pass
407 pass
407
408
408 def init_encoding(self):
409 def init_encoding(self):
409 # Get system encoding at startup time. Certain terminals (like Emacs
410 # Get system encoding at startup time. Certain terminals (like Emacs
410 # 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
411 # encoding to use in the raw_input() method
412 # encoding to use in the raw_input() method
412 try:
413 try:
413 self.stdin_encoding = sys.stdin.encoding or 'ascii'
414 self.stdin_encoding = sys.stdin.encoding or 'ascii'
414 except AttributeError:
415 except AttributeError:
415 self.stdin_encoding = 'ascii'
416 self.stdin_encoding = 'ascii'
416
417
417 def init_syntax_highlighting(self):
418 def init_syntax_highlighting(self):
418 # Python source parser/formatter for syntax highlighting
419 # Python source parser/formatter for syntax highlighting
419 pyformat = PyColorize.Parser().format
420 pyformat = PyColorize.Parser().format
420 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
421 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
421
422
422 def init_pushd_popd_magic(self):
423 def init_pushd_popd_magic(self):
423 # for pushd/popd management
424 # for pushd/popd management
424 try:
425 try:
425 self.home_dir = get_home_dir()
426 self.home_dir = get_home_dir()
426 except HomeDirError, msg:
427 except HomeDirError, msg:
427 fatal(msg)
428 fatal(msg)
428
429
429 self.dir_stack = []
430 self.dir_stack = []
430
431
431 def init_logger(self):
432 def init_logger(self):
432 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
433 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
433 # local shortcut, this is used a LOT
434 # local shortcut, this is used a LOT
434 self.log = self.logger.log
435 self.log = self.logger.log
435
436
436 def init_logstart(self):
437 def init_logstart(self):
437 if self.logappend:
438 if self.logappend:
438 self.magic_logstart(self.logappend + ' append')
439 self.magic_logstart(self.logappend + ' append')
439 elif self.logfile:
440 elif self.logfile:
440 self.magic_logstart(self.logfile)
441 self.magic_logstart(self.logfile)
441 elif self.logstart:
442 elif self.logstart:
442 self.magic_logstart()
443 self.magic_logstart()
443
444
444 def init_builtins(self):
445 def init_builtins(self):
445 self.builtin_trap = BuiltinTrap(shell=self)
446 self.builtin_trap = BuiltinTrap(shell=self)
446
447
447 def init_inspector(self):
448 def init_inspector(self):
448 # Object inspector
449 # Object inspector
449 self.inspector = oinspect.Inspector(oinspect.InspectColors,
450 self.inspector = oinspect.Inspector(oinspect.InspectColors,
450 PyColorize.ANSICodeColors,
451 PyColorize.ANSICodeColors,
451 'NoColor',
452 'NoColor',
452 self.object_info_string_level)
453 self.object_info_string_level)
453
454
454 def init_io(self):
455 def init_io(self):
455 # 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
456 # 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
457 # *before* instantiating this class, because Term holds onto
458 # *before* instantiating this class, because Term holds onto
458 # references to the underlying streams.
459 # references to the underlying streams.
459 if sys.platform == 'win32' and self.has_readline:
460 if sys.platform == 'win32' and self.has_readline:
460 Term = io.IOTerm(cout=self.readline._outputfile,
461 Term = io.IOTerm(cout=self.readline._outputfile,
461 cerr=self.readline._outputfile)
462 cerr=self.readline._outputfile)
462 else:
463 else:
463 Term = io.IOTerm()
464 Term = io.IOTerm()
464 io.Term = Term
465 io.Term = Term
465
466
466 def init_prompts(self):
467 def init_prompts(self):
467 # 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
468 # the DisplayHook. Once there is a separate prompt manager, this
469 # the DisplayHook. Once there is a separate prompt manager, this
469 # will initialize that object and all prompt related information.
470 # will initialize that object and all prompt related information.
470 pass
471 pass
471
472
472 def init_displayhook(self):
473 def init_displayhook(self):
473 # Initialize displayhook, set in/out prompts and printing system
474 # Initialize displayhook, set in/out prompts and printing system
474 self.displayhook = self.displayhook_class(
475 self.displayhook = self.displayhook_class(
475 shell=self,
476 shell=self,
476 cache_size=self.cache_size,
477 cache_size=self.cache_size,
477 input_sep = self.separate_in,
478 input_sep = self.separate_in,
478 output_sep = self.separate_out,
479 output_sep = self.separate_out,
479 output_sep2 = self.separate_out2,
480 output_sep2 = self.separate_out2,
480 ps1 = self.prompt_in1,
481 ps1 = self.prompt_in1,
481 ps2 = self.prompt_in2,
482 ps2 = self.prompt_in2,
482 ps_out = self.prompt_out,
483 ps_out = self.prompt_out,
483 pad_left = self.prompts_pad_left
484 pad_left = self.prompts_pad_left
484 )
485 )
485 # This is a context manager that installs/revmoes the displayhook at
486 # This is a context manager that installs/revmoes the displayhook at
486 # the appropriate time.
487 # the appropriate time.
487 self.display_trap = DisplayTrap(hook=self.displayhook)
488 self.display_trap = DisplayTrap(hook=self.displayhook)
488
489
489 def init_reload_doctest(self):
490 def init_reload_doctest(self):
490 # Do a proper resetting of doctest, including the necessary displayhook
491 # Do a proper resetting of doctest, including the necessary displayhook
491 # monkeypatching
492 # monkeypatching
492 try:
493 try:
493 doctest_reload()
494 doctest_reload()
494 except ImportError:
495 except ImportError:
495 warn("doctest module does not exist.")
496 warn("doctest module does not exist.")
496
497
497 #-------------------------------------------------------------------------
498 #-------------------------------------------------------------------------
498 # Things related to injections into the sys module
499 # Things related to injections into the sys module
499 #-------------------------------------------------------------------------
500 #-------------------------------------------------------------------------
500
501
501 def save_sys_module_state(self):
502 def save_sys_module_state(self):
502 """Save the state of hooks in the sys module.
503 """Save the state of hooks in the sys module.
503
504
504 This has to be called after self.user_ns is created.
505 This has to be called after self.user_ns is created.
505 """
506 """
506 self._orig_sys_module_state = {}
507 self._orig_sys_module_state = {}
507 self._orig_sys_module_state['stdin'] = sys.stdin
508 self._orig_sys_module_state['stdin'] = sys.stdin
508 self._orig_sys_module_state['stdout'] = sys.stdout
509 self._orig_sys_module_state['stdout'] = sys.stdout
509 self._orig_sys_module_state['stderr'] = sys.stderr
510 self._orig_sys_module_state['stderr'] = sys.stderr
510 self._orig_sys_module_state['excepthook'] = sys.excepthook
511 self._orig_sys_module_state['excepthook'] = sys.excepthook
511 try:
512 try:
512 self._orig_sys_modules_main_name = self.user_ns['__name__']
513 self._orig_sys_modules_main_name = self.user_ns['__name__']
513 except KeyError:
514 except KeyError:
514 pass
515 pass
515
516
516 def restore_sys_module_state(self):
517 def restore_sys_module_state(self):
517 """Restore the state of the sys module."""
518 """Restore the state of the sys module."""
518 try:
519 try:
519 for k, v in self._orig_sys_module_state.items():
520 for k, v in self._orig_sys_module_state.items():
520 setattr(sys, k, v)
521 setattr(sys, k, v)
521 except AttributeError:
522 except AttributeError:
522 pass
523 pass
523 # Reset what what done in self.init_sys_modules
524 # Reset what what done in self.init_sys_modules
524 try:
525 try:
525 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
526 except (AttributeError, KeyError):
527 except (AttributeError, KeyError):
527 pass
528 pass
528
529
529 #-------------------------------------------------------------------------
530 #-------------------------------------------------------------------------
530 # Things related to hooks
531 # Things related to hooks
531 #-------------------------------------------------------------------------
532 #-------------------------------------------------------------------------
532
533
533 def init_hooks(self):
534 def init_hooks(self):
534 # hooks holds pointers used for user-side customizations
535 # hooks holds pointers used for user-side customizations
535 self.hooks = Struct()
536 self.hooks = Struct()
536
537
537 self.strdispatchers = {}
538 self.strdispatchers = {}
538
539
539 # Set all default hooks, defined in the IPython.hooks module.
540 # Set all default hooks, defined in the IPython.hooks module.
540 hooks = IPython.core.hooks
541 hooks = IPython.core.hooks
541 for hook_name in hooks.__all__:
542 for hook_name in hooks.__all__:
542 # 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
543 # 0-100 priority
544 # 0-100 priority
544 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
545 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
545
546
546 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):
547 """set_hook(name,hook) -> sets an internal IPython hook.
548 """set_hook(name,hook) -> sets an internal IPython hook.
548
549
549 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
550 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
551 behavior to call at runtime your own routines."""
552 behavior to call at runtime your own routines."""
552
553
553 # 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
554 # 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
555 # of args it's supposed to.
556 # of args it's supposed to.
556
557
557 f = new.instancemethod(hook,self,self.__class__)
558 f = new.instancemethod(hook,self,self.__class__)
558
559
559 # check if the hook is for strdispatcher first
560 # check if the hook is for strdispatcher first
560 if str_key is not None:
561 if str_key is not None:
561 sdp = self.strdispatchers.get(name, StrDispatch())
562 sdp = self.strdispatchers.get(name, StrDispatch())
562 sdp.add_s(str_key, f, priority )
563 sdp.add_s(str_key, f, priority )
563 self.strdispatchers[name] = sdp
564 self.strdispatchers[name] = sdp
564 return
565 return
565 if re_key is not None:
566 if re_key is not None:
566 sdp = self.strdispatchers.get(name, StrDispatch())
567 sdp = self.strdispatchers.get(name, StrDispatch())
567 sdp.add_re(re.compile(re_key), f, priority )
568 sdp.add_re(re.compile(re_key), f, priority )
568 self.strdispatchers[name] = sdp
569 self.strdispatchers[name] = sdp
569 return
570 return
570
571
571 dp = getattr(self.hooks, name, None)
572 dp = getattr(self.hooks, name, None)
572 if name not in IPython.core.hooks.__all__:
573 if name not in IPython.core.hooks.__all__:
573 print "Warning! Hook '%s' is not one of %s" % \
574 print "Warning! Hook '%s' is not one of %s" % \
574 (name, IPython.core.hooks.__all__ )
575 (name, IPython.core.hooks.__all__ )
575 if not dp:
576 if not dp:
576 dp = IPython.core.hooks.CommandChainDispatcher()
577 dp = IPython.core.hooks.CommandChainDispatcher()
577
578
578 try:
579 try:
579 dp.add(f,priority)
580 dp.add(f,priority)
580 except AttributeError:
581 except AttributeError:
581 # it was not commandchain, plain old func - replace
582 # it was not commandchain, plain old func - replace
582 dp = f
583 dp = f
583
584
584 setattr(self.hooks,name, dp)
585 setattr(self.hooks,name, dp)
585
586
586 def register_post_execute(self, func):
587 def register_post_execute(self, func):
587 """Register a function for calling after code execution.
588 """Register a function for calling after code execution.
588 """
589 """
589 if not callable(func):
590 if not callable(func):
590 raise ValueError('argument %s must be callable' % func)
591 raise ValueError('argument %s must be callable' % func)
591 self._post_execute.add(func)
592 self._post_execute.add(func)
592
593
593 #-------------------------------------------------------------------------
594 #-------------------------------------------------------------------------
594 # Things related to the "main" module
595 # Things related to the "main" module
595 #-------------------------------------------------------------------------
596 #-------------------------------------------------------------------------
596
597
597 def new_main_mod(self,ns=None):
598 def new_main_mod(self,ns=None):
598 """Return a new 'main' module object for user code execution.
599 """Return a new 'main' module object for user code execution.
599 """
600 """
600 main_mod = self._user_main_module
601 main_mod = self._user_main_module
601 init_fakemod_dict(main_mod,ns)
602 init_fakemod_dict(main_mod,ns)
602 return main_mod
603 return main_mod
603
604
604 def cache_main_mod(self,ns,fname):
605 def cache_main_mod(self,ns,fname):
605 """Cache a main module's namespace.
606 """Cache a main module's namespace.
606
607
607 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
608 namespace of their __main__ module (a FakeModule instance) around so
609 namespace of their __main__ module (a FakeModule instance) around so
609 that Python doesn't clear it, rendering objects defined therein
610 that Python doesn't clear it, rendering objects defined therein
610 useless.
611 useless.
611
612
612 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
613 absolute path of the module object (which corresponds to the script
614 absolute path of the module object (which corresponds to the script
614 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
615 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
616 leaks from old references while allowing the objects from the last
617 leaks from old references while allowing the objects from the last
617 execution to be accessible.
618 execution to be accessible.
618
619
619 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,
620 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
621 references to None without regard for reference counts). This method
622 references to None without regard for reference counts). This method
622 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
623 original module's __dict__ to be cleared and reused.
624 original module's __dict__ to be cleared and reused.
624
625
625
626
626 Parameters
627 Parameters
627 ----------
628 ----------
628 ns : a namespace (a dict, typically)
629 ns : a namespace (a dict, typically)
629
630
630 fname : str
631 fname : str
631 Filename associated with the namespace.
632 Filename associated with the namespace.
632
633
633 Examples
634 Examples
634 --------
635 --------
635
636
636 In [10]: import IPython
637 In [10]: import IPython
637
638
638 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
639 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
639
640
640 In [12]: IPython.__file__ in _ip._main_ns_cache
641 In [12]: IPython.__file__ in _ip._main_ns_cache
641 Out[12]: True
642 Out[12]: True
642 """
643 """
643 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
644 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
644
645
645 def clear_main_mod_cache(self):
646 def clear_main_mod_cache(self):
646 """Clear the cache of main modules.
647 """Clear the cache of main modules.
647
648
648 Mainly for use by utilities like %reset.
649 Mainly for use by utilities like %reset.
649
650
650 Examples
651 Examples
651 --------
652 --------
652
653
653 In [15]: import IPython
654 In [15]: import IPython
654
655
655 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
656 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
656
657
657 In [17]: len(_ip._main_ns_cache) > 0
658 In [17]: len(_ip._main_ns_cache) > 0
658 Out[17]: True
659 Out[17]: True
659
660
660 In [18]: _ip.clear_main_mod_cache()
661 In [18]: _ip.clear_main_mod_cache()
661
662
662 In [19]: len(_ip._main_ns_cache) == 0
663 In [19]: len(_ip._main_ns_cache) == 0
663 Out[19]: True
664 Out[19]: True
664 """
665 """
665 self._main_ns_cache.clear()
666 self._main_ns_cache.clear()
666
667
667 #-------------------------------------------------------------------------
668 #-------------------------------------------------------------------------
668 # Things related to debugging
669 # Things related to debugging
669 #-------------------------------------------------------------------------
670 #-------------------------------------------------------------------------
670
671
671 def init_pdb(self):
672 def init_pdb(self):
672 # Set calling of pdb on exceptions
673 # Set calling of pdb on exceptions
673 # self.call_pdb is a property
674 # self.call_pdb is a property
674 self.call_pdb = self.pdb
675 self.call_pdb = self.pdb
675
676
676 def _get_call_pdb(self):
677 def _get_call_pdb(self):
677 return self._call_pdb
678 return self._call_pdb
678
679
679 def _set_call_pdb(self,val):
680 def _set_call_pdb(self,val):
680
681
681 if val not in (0,1,False,True):
682 if val not in (0,1,False,True):
682 raise ValueError,'new call_pdb value must be boolean'
683 raise ValueError,'new call_pdb value must be boolean'
683
684
684 # store value in instance
685 # store value in instance
685 self._call_pdb = val
686 self._call_pdb = val
686
687
687 # notify the actual exception handlers
688 # notify the actual exception handlers
688 self.InteractiveTB.call_pdb = val
689 self.InteractiveTB.call_pdb = val
689
690
690 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
691 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
691 'Control auto-activation of pdb at exceptions')
692 'Control auto-activation of pdb at exceptions')
692
693
693 def debugger(self,force=False):
694 def debugger(self,force=False):
694 """Call the pydb/pdb debugger.
695 """Call the pydb/pdb debugger.
695
696
696 Keywords:
697 Keywords:
697
698
698 - force(False): by default, this routine checks the instance call_pdb
699 - force(False): by default, this routine checks the instance call_pdb
699 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.
700 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
701 is false.
702 is false.
702 """
703 """
703
704
704 if not (force or self.call_pdb):
705 if not (force or self.call_pdb):
705 return
706 return
706
707
707 if not hasattr(sys,'last_traceback'):
708 if not hasattr(sys,'last_traceback'):
708 error('No traceback has been produced, nothing to debug.')
709 error('No traceback has been produced, nothing to debug.')
709 return
710 return
710
711
711 # use pydb if available
712 # use pydb if available
712 if debugger.has_pydb:
713 if debugger.has_pydb:
713 from pydb import pm
714 from pydb import pm
714 else:
715 else:
715 # fallback to our internal debugger
716 # fallback to our internal debugger
716 pm = lambda : self.InteractiveTB.debugger(force=True)
717 pm = lambda : self.InteractiveTB.debugger(force=True)
717 self.history_saving_wrapper(pm)()
718 self.history_saving_wrapper(pm)()
718
719
719 #-------------------------------------------------------------------------
720 #-------------------------------------------------------------------------
720 # Things related to IPython's various namespaces
721 # Things related to IPython's various namespaces
721 #-------------------------------------------------------------------------
722 #-------------------------------------------------------------------------
722
723
723 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):
724 # Create the namespace where the user will operate. user_ns is
725 # Create the namespace where the user will operate. user_ns is
725 # 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
726 # 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
727 # given as the exec 'globals' argument, This is useful in embedding
728 # given as the exec 'globals' argument, This is useful in embedding
728 # situations where the ipython shell opens in a context where the
729 # situations where the ipython shell opens in a context where the
729 # distinction between locals and globals is meaningful. For
730 # distinction between locals and globals is meaningful. For
730 # 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.
731
732
732 # FIXME. For some strange reason, __builtins__ is showing up at user
733 # FIXME. For some strange reason, __builtins__ is showing up at user
733 # 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
734 # should really track down where the problem is coming from. Alex
735 # should really track down where the problem is coming from. Alex
735 # Schmolck reported this problem first.
736 # Schmolck reported this problem first.
736
737
737 # A useful post by Alex Martelli on this topic:
738 # A useful post by Alex Martelli on this topic:
738 # Re: inconsistent value from __builtins__
739 # Re: inconsistent value from __builtins__
739 # Von: Alex Martelli <aleaxit@yahoo.com>
740 # Von: Alex Martelli <aleaxit@yahoo.com>
740 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
741 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
741 # Gruppen: comp.lang.python
742 # Gruppen: comp.lang.python
742
743
743 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
744 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
744 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
745 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
745 # > <type 'dict'>
746 # > <type 'dict'>
746 # > >>> print type(__builtins__)
747 # > >>> print type(__builtins__)
747 # > <type 'module'>
748 # > <type 'module'>
748 # > Is this difference in return value intentional?
749 # > Is this difference in return value intentional?
749
750
750 # Well, it's documented that '__builtins__' can be either a dictionary
751 # Well, it's documented that '__builtins__' can be either a dictionary
751 # 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
752 # 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
753 # 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
754 # should start with "import __builtin__" (note, no 's') which will
755 # should start with "import __builtin__" (note, no 's') which will
755 # definitely give you a module. Yeah, it's somewhat confusing:-(.
756 # definitely give you a module. Yeah, it's somewhat confusing:-(.
756
757
757 # 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
758 # 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
759 # properly initialized namespaces.
760 # properly initialized namespaces.
760 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
761 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
761 user_global_ns)
762 user_global_ns)
762
763
763 # Assign namespaces
764 # Assign namespaces
764 # This is the namespace where all normal user variables live
765 # This is the namespace where all normal user variables live
765 self.user_ns = user_ns
766 self.user_ns = user_ns
766 self.user_global_ns = user_global_ns
767 self.user_global_ns = user_global_ns
767
768
768 # 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
769 # 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
770 # 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
771 # doesn't need to be separately tracked in the ns_table.
772 # doesn't need to be separately tracked in the ns_table.
772 self.user_ns_hidden = {}
773 self.user_ns_hidden = {}
773
774
774 # A namespace to keep track of internal data structures to prevent
775 # A namespace to keep track of internal data structures to prevent
775 # them from cluttering user-visible stuff. Will be updated later
776 # them from cluttering user-visible stuff. Will be updated later
776 self.internal_ns = {}
777 self.internal_ns = {}
777
778
778 # 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
779 # problem: after script execution (via %run), the module where the user
780 # problem: after script execution (via %run), the module where the user
780 # 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
781 # so docetst and other tools work correctly), the Python module
782 # so docetst and other tools work correctly), the Python module
782 # teardown mechanism runs over it, and sets to None every variable
783 # teardown mechanism runs over it, and sets to None every variable
783 # present in that module. Top-level references to objects from the
784 # present in that module. Top-level references to objects from the
784 # script survive, because the user_ns is updated with them. However,
785 # script survive, because the user_ns is updated with them. However,
785 # calling functions defined in the script that use other things from
786 # calling functions defined in the script that use other things from
786 # the script will fail, because the function's closure had references
787 # the script will fail, because the function's closure had references
787 # 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
788 # these modules from deletion by keeping a cache.
789 # these modules from deletion by keeping a cache.
789 #
790 #
790 # 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
791 # 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
792 # 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,
793 # however, that we must cache the module *namespace contents* (their
794 # however, that we must cache the module *namespace contents* (their
794 # __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
795 # (uncached) could be destroyed while still holding references (such as
796 # (uncached) could be destroyed while still holding references (such as
796 # those held by GUI objects that tend to be long-lived)>
797 # those held by GUI objects that tend to be long-lived)>
797 #
798 #
798 # 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()
799 # and clear_main_mod_cache() methods for details on use.
800 # and clear_main_mod_cache() methods for details on use.
800
801
801 # This is the cache used for 'main' namespaces
802 # This is the cache used for 'main' namespaces
802 self._main_ns_cache = {}
803 self._main_ns_cache = {}
803 # 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
804 # copying and clearing for reuse on each %run
805 # copying and clearing for reuse on each %run
805 self._user_main_module = FakeModule()
806 self._user_main_module = FakeModule()
806
807
807 # A table holding all the namespaces IPython deals with, so that
808 # A table holding all the namespaces IPython deals with, so that
808 # introspection facilities can search easily.
809 # introspection facilities can search easily.
809 self.ns_table = {'user':user_ns,
810 self.ns_table = {'user':user_ns,
810 'user_global':user_global_ns,
811 'user_global':user_global_ns,
811 'internal':self.internal_ns,
812 'internal':self.internal_ns,
812 'builtin':__builtin__.__dict__
813 'builtin':__builtin__.__dict__
813 }
814 }
814
815
815 # Similarly, track all namespaces where references can be held and that
816 # Similarly, track all namespaces where references can be held and that
816 # 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
817 # a simple list.
818 # a simple list.
818 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,
819 self.internal_ns, self._main_ns_cache ]
820 self.internal_ns, self._main_ns_cache ]
820
821
821 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):
822 """Return a valid local and global user interactive namespaces.
823 """Return a valid local and global user interactive namespaces.
823
824
824 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
825 valid IPython user namespace, which you can pass to the various
826 valid IPython user namespace, which you can pass to the various
826 embedding classes in ipython. The default implementation returns the
827 embedding classes in ipython. The default implementation returns the
827 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
828 refer to variables in the namespace. Customized implementations can
829 refer to variables in the namespace. Customized implementations can
829 return different dicts. The locals dictionary can actually be anything
830 return different dicts. The locals dictionary can actually be anything
830 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
831 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
832 custom object for the locals namespace synchronize with the globals
833 custom object for the locals namespace synchronize with the globals
833 dict somehow.
834 dict somehow.
834
835
835 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.
836
837
837 Parameters
838 Parameters
838 ----------
839 ----------
839 user_ns : dict-like, optional
840 user_ns : dict-like, optional
840 The current user namespace. The items in this namespace should
841 The current user namespace. The items in this namespace should
841 be included in the output. If None, an appropriate blank
842 be included in the output. If None, an appropriate blank
842 namespace should be created.
843 namespace should be created.
843 user_global_ns : dict, optional
844 user_global_ns : dict, optional
844 The current user global namespace. The items in this namespace
845 The current user global namespace. The items in this namespace
845 should be included in the output. If None, an appropriate
846 should be included in the output. If None, an appropriate
846 blank namespace should be created.
847 blank namespace should be created.
847
848
848 Returns
849 Returns
849 -------
850 -------
850 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
851 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.
852 """
853 """
853
854
854
855
855 # We must ensure that __builtin__ (without the final 's') is always
856 # We must ensure that __builtin__ (without the final 's') is always
856 # available and pointing to the __builtin__ *module*. For more details:
857 # available and pointing to the __builtin__ *module*. For more details:
857 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
858 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
858
859
859 if user_ns is None:
860 if user_ns is None:
860 # Set __name__ to __main__ to better match the behavior of the
861 # Set __name__ to __main__ to better match the behavior of the
861 # normal interpreter.
862 # normal interpreter.
862 user_ns = {'__name__' :'__main__',
863 user_ns = {'__name__' :'__main__',
863 '__builtin__' : __builtin__,
864 '__builtin__' : __builtin__,
864 '__builtins__' : __builtin__,
865 '__builtins__' : __builtin__,
865 }
866 }
866 else:
867 else:
867 user_ns.setdefault('__name__','__main__')
868 user_ns.setdefault('__name__','__main__')
868 user_ns.setdefault('__builtin__',__builtin__)
869 user_ns.setdefault('__builtin__',__builtin__)
869 user_ns.setdefault('__builtins__',__builtin__)
870 user_ns.setdefault('__builtins__',__builtin__)
870
871
871 if user_global_ns is None:
872 if user_global_ns is None:
872 user_global_ns = user_ns
873 user_global_ns = user_ns
873 if type(user_global_ns) is not dict:
874 if type(user_global_ns) is not dict:
874 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"
875 % type(user_global_ns))
876 % type(user_global_ns))
876
877
877 return user_ns, user_global_ns
878 return user_ns, user_global_ns
878
879
879 def init_sys_modules(self):
880 def init_sys_modules(self):
880 # 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
881 # module but which accesses the IPython namespace, for shelve and
882 # module but which accesses the IPython namespace, for shelve and
882 # pickle to work interactively. Normally they rely on getting
883 # pickle to work interactively. Normally they rely on getting
883 # everything out of __main__, but for embedding purposes each IPython
884 # everything out of __main__, but for embedding purposes each IPython
884 # 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
885 # everything into __main__.
886 # everything into __main__.
886
887
887 # note, however, that we should only do this for non-embedded
888 # note, however, that we should only do this for non-embedded
888 # ipythons, which really mimic the __main__.__dict__ with their own
889 # ipythons, which really mimic the __main__.__dict__ with their own
889 # namespace. Embedded instances, on the other hand, should not do
890 # namespace. Embedded instances, on the other hand, should not do
890 # this because they need to manage the user local/global namespaces
891 # this because they need to manage the user local/global namespaces
891 # only, but they live within a 'normal' __main__ (meaning, they
892 # only, but they live within a 'normal' __main__ (meaning, they
892 # shouldn't overtake the execution environment of the script they're
893 # shouldn't overtake the execution environment of the script they're
893 # embedded in).
894 # embedded in).
894
895
895 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
896 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
896
897
897 try:
898 try:
898 main_name = self.user_ns['__name__']
899 main_name = self.user_ns['__name__']
899 except KeyError:
900 except KeyError:
900 raise KeyError('user_ns dictionary MUST have a "__name__" key')
901 raise KeyError('user_ns dictionary MUST have a "__name__" key')
901 else:
902 else:
902 sys.modules[main_name] = FakeModule(self.user_ns)
903 sys.modules[main_name] = FakeModule(self.user_ns)
903
904
904 def init_user_ns(self):
905 def init_user_ns(self):
905 """Initialize all user-visible namespaces to their minimum defaults.
906 """Initialize all user-visible namespaces to their minimum defaults.
906
907
907 Certain history lists are also initialized here, as they effectively
908 Certain history lists are also initialized here, as they effectively
908 act as user namespaces.
909 act as user namespaces.
909
910
910 Notes
911 Notes
911 -----
912 -----
912 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
913 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
914 therm.
915 therm.
915 """
916 """
916 # 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
917 # 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
918 # 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
919 # 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
920 # session (probably nothing, so theye really only see their own stuff)
921 # session (probably nothing, so theye really only see their own stuff)
921
922
922 # The user dict must *always* have a __builtin__ reference to the
923 # The user dict must *always* have a __builtin__ reference to the
923 # Python standard __builtin__ namespace, which must be imported.
924 # Python standard __builtin__ namespace, which must be imported.
924 # This is so that certain operations in prompt evaluation can be
925 # This is so that certain operations in prompt evaluation can be
925 # reliably executed with builtins. Note that we can NOT use
926 # reliably executed with builtins. Note that we can NOT use
926 # __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
927 # module, and can even mutate at runtime, depending on the context
928 # module, and can even mutate at runtime, depending on the context
928 # (Python makes no guarantees on it). In contrast, __builtin__ is
929 # (Python makes no guarantees on it). In contrast, __builtin__ is
929 # always a module object, though it must be explicitly imported.
930 # always a module object, though it must be explicitly imported.
930
931
931 # For more details:
932 # For more details:
932 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
933 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
933 ns = dict(__builtin__ = __builtin__)
934 ns = dict(__builtin__ = __builtin__)
934
935
935 # Put 'help' in the user namespace
936 # Put 'help' in the user namespace
936 try:
937 try:
937 from site import _Helper
938 from site import _Helper
938 ns['help'] = _Helper()
939 ns['help'] = _Helper()
939 except ImportError:
940 except ImportError:
940 warn('help() not available - check site.py')
941 warn('help() not available - check site.py')
941
942
942 # make global variables for user access to the histories
943 # make global variables for user access to the histories
943 ns['_ih'] = self.input_hist
944 ns['_ih'] = self.input_hist
944 ns['_oh'] = self.output_hist
945 ns['_oh'] = self.output_hist
945 ns['_dh'] = self.dir_hist
946 ns['_dh'] = self.dir_hist
946
947
947 ns['_sh'] = shadowns
948 ns['_sh'] = shadowns
948
949
949 # 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
950 # in %who, as they can have very large reprs.
951 # in %who, as they can have very large reprs.
951 ns['In'] = self.input_hist
952 ns['In'] = self.input_hist
952 ns['Out'] = self.output_hist
953 ns['Out'] = self.output_hist
953
954
954 # Store myself as the public api!!!
955 # Store myself as the public api!!!
955 ns['get_ipython'] = self.get_ipython
956 ns['get_ipython'] = self.get_ipython
956
957
957 # 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
958 # by %who
959 # by %who
959 self.user_ns_hidden.update(ns)
960 self.user_ns_hidden.update(ns)
960
961
961 # 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
962 # 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
963 # stuff, not our variables.
964 # stuff, not our variables.
964
965
965 # Finally, update the real user's namespace
966 # Finally, update the real user's namespace
966 self.user_ns.update(ns)
967 self.user_ns.update(ns)
967
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 for ns in self.ns_refs_table:
975 # Clear histories
976 ns.clear()
976 self.history_manager.reset()
977
978 self.alias_manager.clear_aliases()
979
980 # Clear input and output histories
981 self.input_hist[:] = []
982 self.input_hist_raw[:] = []
983 self.output_hist.clear()
984
977
985 # Reset counter used to index all histories
978 # Reset counter used to index all histories
986 self.execution_count = 0
979 self.execution_count = 0
987
980
988 # Restore the user namespaces to minimal usability
981 # Restore the user namespaces to minimal usability
982 for ns in self.ns_refs_table:
983 ns.clear()
989 self.init_user_ns()
984 self.init_user_ns()
990
985
991 # Restore the default and user aliases
986 # Restore the default and user aliases
987 self.alias_manager.clear_aliases()
992 self.alias_manager.init_aliases()
988 self.alias_manager.init_aliases()
993
989
994 def reset_selective(self, regex=None):
990 def reset_selective(self, regex=None):
995 """Clear selective variables from internal namespaces based on a
991 """Clear selective variables from internal namespaces based on a
996 specified regular expression.
992 specified regular expression.
997
993
998 Parameters
994 Parameters
999 ----------
995 ----------
1000 regex : string or compiled pattern, optional
996 regex : string or compiled pattern, optional
1001 A regular expression pattern that will be used in searching
997 A regular expression pattern that will be used in searching
1002 variable names in the users namespaces.
998 variable names in the users namespaces.
1003 """
999 """
1004 if regex is not None:
1000 if regex is not None:
1005 try:
1001 try:
1006 m = re.compile(regex)
1002 m = re.compile(regex)
1007 except TypeError:
1003 except TypeError:
1008 raise TypeError('regex must be a string or compiled pattern')
1004 raise TypeError('regex must be a string or compiled pattern')
1009 # Search for keys in each namespace that match the given regex
1005 # Search for keys in each namespace that match the given regex
1010 # If a match is found, delete the key/value pair.
1006 # If a match is found, delete the key/value pair.
1011 for ns in self.ns_refs_table:
1007 for ns in self.ns_refs_table:
1012 for var in ns:
1008 for var in ns:
1013 if m.search(var):
1009 if m.search(var):
1014 del ns[var]
1010 del ns[var]
1015
1011
1016 def push(self, variables, interactive=True):
1012 def push(self, variables, interactive=True):
1017 """Inject a group of variables into the IPython user namespace.
1013 """Inject a group of variables into the IPython user namespace.
1018
1014
1019 Parameters
1015 Parameters
1020 ----------
1016 ----------
1021 variables : dict, str or list/tuple of str
1017 variables : dict, str or list/tuple of str
1022 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
1023 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
1024 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
1025 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
1026 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
1027 callers frame.
1023 callers frame.
1028 interactive : bool
1024 interactive : bool
1029 If True (default), the variables will be listed with the ``who``
1025 If True (default), the variables will be listed with the ``who``
1030 magic.
1026 magic.
1031 """
1027 """
1032 vdict = None
1028 vdict = None
1033
1029
1034 # 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.
1035 if isinstance(variables, dict):
1031 if isinstance(variables, dict):
1036 vdict = variables
1032 vdict = variables
1037 elif isinstance(variables, (basestring, list, tuple)):
1033 elif isinstance(variables, (basestring, list, tuple)):
1038 if isinstance(variables, basestring):
1034 if isinstance(variables, basestring):
1039 vlist = variables.split()
1035 vlist = variables.split()
1040 else:
1036 else:
1041 vlist = variables
1037 vlist = variables
1042 vdict = {}
1038 vdict = {}
1043 cf = sys._getframe(1)
1039 cf = sys._getframe(1)
1044 for name in vlist:
1040 for name in vlist:
1045 try:
1041 try:
1046 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1042 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1047 except:
1043 except:
1048 print ('Could not get variable %s from %s' %
1044 print ('Could not get variable %s from %s' %
1049 (name,cf.f_code.co_name))
1045 (name,cf.f_code.co_name))
1050 else:
1046 else:
1051 raise ValueError('variables must be a dict/str/list/tuple')
1047 raise ValueError('variables must be a dict/str/list/tuple')
1052
1048
1053 # Propagate variables to user namespace
1049 # Propagate variables to user namespace
1054 self.user_ns.update(vdict)
1050 self.user_ns.update(vdict)
1055
1051
1056 # And configure interactive visibility
1052 # And configure interactive visibility
1057 config_ns = self.user_ns_hidden
1053 config_ns = self.user_ns_hidden
1058 if interactive:
1054 if interactive:
1059 for name, val in vdict.iteritems():
1055 for name, val in vdict.iteritems():
1060 config_ns.pop(name, None)
1056 config_ns.pop(name, None)
1061 else:
1057 else:
1062 for name,val in vdict.iteritems():
1058 for name,val in vdict.iteritems():
1063 config_ns[name] = val
1059 config_ns[name] = val
1064
1060
1065 #-------------------------------------------------------------------------
1061 #-------------------------------------------------------------------------
1066 # Things related to object introspection
1062 # Things related to object introspection
1067 #-------------------------------------------------------------------------
1063 #-------------------------------------------------------------------------
1068
1064
1069 def _ofind(self, oname, namespaces=None):
1065 def _ofind(self, oname, namespaces=None):
1070 """Find an object in the available namespaces.
1066 """Find an object in the available namespaces.
1071
1067
1072 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1068 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1073
1069
1074 Has special code to detect magic functions.
1070 Has special code to detect magic functions.
1075 """
1071 """
1076 #oname = oname.strip()
1072 #oname = oname.strip()
1077 #print '1- oname: <%r>' % oname # dbg
1073 #print '1- oname: <%r>' % oname # dbg
1078 try:
1074 try:
1079 oname = oname.strip().encode('ascii')
1075 oname = oname.strip().encode('ascii')
1080 #print '2- oname: <%r>' % oname # dbg
1076 #print '2- oname: <%r>' % oname # dbg
1081 except UnicodeEncodeError:
1077 except UnicodeEncodeError:
1082 print 'Python identifiers can only contain ascii characters.'
1078 print 'Python identifiers can only contain ascii characters.'
1083 return dict(found=False)
1079 return dict(found=False)
1084
1080
1085 alias_ns = None
1081 alias_ns = None
1086 if namespaces is None:
1082 if namespaces is None:
1087 # Namespaces to search in:
1083 # Namespaces to search in:
1088 # 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
1089 # find things in the same order that Python finds them.
1085 # find things in the same order that Python finds them.
1090 namespaces = [ ('Interactive', self.user_ns),
1086 namespaces = [ ('Interactive', self.user_ns),
1091 ('IPython internal', self.internal_ns),
1087 ('IPython internal', self.internal_ns),
1092 ('Python builtin', __builtin__.__dict__),
1088 ('Python builtin', __builtin__.__dict__),
1093 ('Alias', self.alias_manager.alias_table),
1089 ('Alias', self.alias_manager.alias_table),
1094 ]
1090 ]
1095 alias_ns = self.alias_manager.alias_table
1091 alias_ns = self.alias_manager.alias_table
1096
1092
1097 # initialize results to 'null'
1093 # initialize results to 'null'
1098 found = False; obj = None; ospace = None; ds = None;
1094 found = False; obj = None; ospace = None; ds = None;
1099 ismagic = False; isalias = False; parent = None
1095 ismagic = False; isalias = False; parent = None
1100
1096
1101 # 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
1102 # 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
1103 # loaded with a future import. In this case, just bail.
1099 # loaded with a future import. In this case, just bail.
1104 if (oname == 'print' and not (self.compile.compiler.flags &
1100 if (oname == 'print' and not (self.compile.compiler.flags &
1105 __future__.CO_FUTURE_PRINT_FUNCTION)):
1101 __future__.CO_FUTURE_PRINT_FUNCTION)):
1106 return {'found':found, 'obj':obj, 'namespace':ospace,
1102 return {'found':found, 'obj':obj, 'namespace':ospace,
1107 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1103 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1108
1104
1109 # 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
1110 # 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
1111 # declare success if we can find them all.
1107 # declare success if we can find them all.
1112 oname_parts = oname.split('.')
1108 oname_parts = oname.split('.')
1113 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1109 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1114 for nsname,ns in namespaces:
1110 for nsname,ns in namespaces:
1115 try:
1111 try:
1116 obj = ns[oname_head]
1112 obj = ns[oname_head]
1117 except KeyError:
1113 except KeyError:
1118 continue
1114 continue
1119 else:
1115 else:
1120 #print 'oname_rest:', oname_rest # dbg
1116 #print 'oname_rest:', oname_rest # dbg
1121 for part in oname_rest:
1117 for part in oname_rest:
1122 try:
1118 try:
1123 parent = obj
1119 parent = obj
1124 obj = getattr(obj,part)
1120 obj = getattr(obj,part)
1125 except:
1121 except:
1126 # Blanket except b/c some badly implemented objects
1122 # Blanket except b/c some badly implemented objects
1127 # allow __getattr__ to raise exceptions other than
1123 # allow __getattr__ to raise exceptions other than
1128 # AttributeError, which then crashes IPython.
1124 # AttributeError, which then crashes IPython.
1129 break
1125 break
1130 else:
1126 else:
1131 # 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
1132 found = True
1128 found = True
1133 ospace = nsname
1129 ospace = nsname
1134 if ns == alias_ns:
1130 if ns == alias_ns:
1135 isalias = True
1131 isalias = True
1136 break # namespace loop
1132 break # namespace loop
1137
1133
1138 # Try to see if it's magic
1134 # Try to see if it's magic
1139 if not found:
1135 if not found:
1140 if oname.startswith(ESC_MAGIC):
1136 if oname.startswith(ESC_MAGIC):
1141 oname = oname[1:]
1137 oname = oname[1:]
1142 obj = getattr(self,'magic_'+oname,None)
1138 obj = getattr(self,'magic_'+oname,None)
1143 if obj is not None:
1139 if obj is not None:
1144 found = True
1140 found = True
1145 ospace = 'IPython internal'
1141 ospace = 'IPython internal'
1146 ismagic = True
1142 ismagic = True
1147
1143
1148 # Last try: special-case some literals like '', [], {}, etc:
1144 # Last try: special-case some literals like '', [], {}, etc:
1149 if not found and oname_head in ["''",'""','[]','{}','()']:
1145 if not found and oname_head in ["''",'""','[]','{}','()']:
1150 obj = eval(oname_head)
1146 obj = eval(oname_head)
1151 found = True
1147 found = True
1152 ospace = 'Interactive'
1148 ospace = 'Interactive'
1153
1149
1154 return {'found':found, 'obj':obj, 'namespace':ospace,
1150 return {'found':found, 'obj':obj, 'namespace':ospace,
1155 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1151 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1156
1152
1157 def _ofind_property(self, oname, info):
1153 def _ofind_property(self, oname, info):
1158 """Second part of object finding, to look for property details."""
1154 """Second part of object finding, to look for property details."""
1159 if info.found:
1155 if info.found:
1160 # Get the docstring of the class property if it exists.
1156 # Get the docstring of the class property if it exists.
1161 path = oname.split('.')
1157 path = oname.split('.')
1162 root = '.'.join(path[:-1])
1158 root = '.'.join(path[:-1])
1163 if info.parent is not None:
1159 if info.parent is not None:
1164 try:
1160 try:
1165 target = getattr(info.parent, '__class__')
1161 target = getattr(info.parent, '__class__')
1166 # The object belongs to a class instance.
1162 # The object belongs to a class instance.
1167 try:
1163 try:
1168 target = getattr(target, path[-1])
1164 target = getattr(target, path[-1])
1169 # The class defines the object.
1165 # The class defines the object.
1170 if isinstance(target, property):
1166 if isinstance(target, property):
1171 oname = root + '.__class__.' + path[-1]
1167 oname = root + '.__class__.' + path[-1]
1172 info = Struct(self._ofind(oname))
1168 info = Struct(self._ofind(oname))
1173 except AttributeError: pass
1169 except AttributeError: pass
1174 except AttributeError: pass
1170 except AttributeError: pass
1175
1171
1176 # 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
1177 # hadn't been found
1173 # hadn't been found
1178 return info
1174 return info
1179
1175
1180 def _object_find(self, oname, namespaces=None):
1176 def _object_find(self, oname, namespaces=None):
1181 """Find an object and return a struct with info about it."""
1177 """Find an object and return a struct with info about it."""
1182 inf = Struct(self._ofind(oname, namespaces))
1178 inf = Struct(self._ofind(oname, namespaces))
1183 return Struct(self._ofind_property(oname, inf))
1179 return Struct(self._ofind_property(oname, inf))
1184
1180
1185 def _inspect(self, meth, oname, namespaces=None, **kw):
1181 def _inspect(self, meth, oname, namespaces=None, **kw):
1186 """Generic interface to the inspector system.
1182 """Generic interface to the inspector system.
1187
1183
1188 This function is meant to be called by pdef, pdoc & friends."""
1184 This function is meant to be called by pdef, pdoc & friends."""
1189 info = self._object_find(oname)
1185 info = self._object_find(oname)
1190 if info.found:
1186 if info.found:
1191 pmethod = getattr(self.inspector, meth)
1187 pmethod = getattr(self.inspector, meth)
1192 formatter = format_screen if info.ismagic else None
1188 formatter = format_screen if info.ismagic else None
1193 if meth == 'pdoc':
1189 if meth == 'pdoc':
1194 pmethod(info.obj, oname, formatter)
1190 pmethod(info.obj, oname, formatter)
1195 elif meth == 'pinfo':
1191 elif meth == 'pinfo':
1196 pmethod(info.obj, oname, formatter, info, **kw)
1192 pmethod(info.obj, oname, formatter, info, **kw)
1197 else:
1193 else:
1198 pmethod(info.obj, oname)
1194 pmethod(info.obj, oname)
1199 else:
1195 else:
1200 print 'Object `%s` not found.' % oname
1196 print 'Object `%s` not found.' % oname
1201 return 'not found' # so callers can take other action
1197 return 'not found' # so callers can take other action
1202
1198
1203 def object_inspect(self, oname):
1199 def object_inspect(self, oname):
1204 info = self._object_find(oname)
1200 info = self._object_find(oname)
1205 if info.found:
1201 if info.found:
1206 return self.inspector.info(info.obj, oname, info=info)
1202 return self.inspector.info(info.obj, oname, info=info)
1207 else:
1203 else:
1208 return oinspect.object_info(name=oname, found=False)
1204 return oinspect.object_info(name=oname, found=False)
1209
1205
1210 #-------------------------------------------------------------------------
1206 #-------------------------------------------------------------------------
1211 # Things related to history management
1207 # Things related to history management
1212 #-------------------------------------------------------------------------
1208 #-------------------------------------------------------------------------
1213
1209
1214 def init_history(self):
1210 def init_history(self):
1215 self.history_manager = HistoryManager(shell=self)
1211 self.history_manager = HistoryManager(shell=self)
1216
1212
1217 def savehist(self):
1213 def savehist(self):
1218 """Save input history to a file (via readline library)."""
1214 """Save input history to a file (via readline library)."""
1219 self.history_manager.save_hist()
1215 self.history_manager.save_hist()
1220
1216
1221 def reloadhist(self):
1217 def reloadhist(self):
1222 """Reload the input history from disk file."""
1218 """Reload the input history from disk file."""
1223 self.history_manager.reload_hist()
1219 self.history_manager.reload_hist()
1224
1220
1225 def history_saving_wrapper(self, func):
1221 def history_saving_wrapper(self, func):
1226 """ Wrap func for readline history saving
1222 """ Wrap func for readline history saving
1227
1223
1228 Convert func into callable that saves & restores
1224 Convert func into callable that saves & restores
1229 history around the call """
1225 history around the call """
1230
1226
1231 if self.has_readline:
1227 if self.has_readline:
1232 from IPython.utils import rlineimpl as readline
1228 from IPython.utils import rlineimpl as readline
1233 else:
1229 else:
1234 return func
1230 return func
1235
1231
1236 def wrapper():
1232 def wrapper():
1237 self.savehist()
1233 self.savehist()
1238 try:
1234 try:
1239 func()
1235 func()
1240 finally:
1236 finally:
1241 readline.read_history_file(self.histfile)
1237 readline.read_history_file(self.histfile)
1242 return wrapper
1238 return wrapper
1243
1239
1244 #-------------------------------------------------------------------------
1240 #-------------------------------------------------------------------------
1245 # Things related to exception handling and tracebacks (not debugging)
1241 # Things related to exception handling and tracebacks (not debugging)
1246 #-------------------------------------------------------------------------
1242 #-------------------------------------------------------------------------
1247
1243
1248 def init_traceback_handlers(self, custom_exceptions):
1244 def init_traceback_handlers(self, custom_exceptions):
1249 # Syntax error handler.
1245 # Syntax error handler.
1250 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1246 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1251
1247
1252 # The interactive one is initialized with an offset, meaning we always
1248 # The interactive one is initialized with an offset, meaning we always
1253 # 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
1254 # internal code. Valid modes: ['Plain','Context','Verbose']
1250 # internal code. Valid modes: ['Plain','Context','Verbose']
1255 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1251 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1256 color_scheme='NoColor',
1252 color_scheme='NoColor',
1257 tb_offset = 1)
1253 tb_offset = 1)
1258
1254
1259 # 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,
1260 # 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
1261 # during the read-eval loop, it may get temporarily overwritten.
1257 # during the read-eval loop, it may get temporarily overwritten.
1262 self.sys_excepthook = sys.excepthook
1258 self.sys_excepthook = sys.excepthook
1263
1259
1264 # and add any custom exception handlers the user may have specified
1260 # and add any custom exception handlers the user may have specified
1265 self.set_custom_exc(*custom_exceptions)
1261 self.set_custom_exc(*custom_exceptions)
1266
1262
1267 # Set the exception mode
1263 # Set the exception mode
1268 self.InteractiveTB.set_mode(mode=self.xmode)
1264 self.InteractiveTB.set_mode(mode=self.xmode)
1269
1265
1270 def set_custom_exc(self, exc_tuple, handler):
1266 def set_custom_exc(self, exc_tuple, handler):
1271 """set_custom_exc(exc_tuple,handler)
1267 """set_custom_exc(exc_tuple,handler)
1272
1268
1273 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
1274 exceptions in exc_tuple occur in the mainloop (specifically, in the
1270 exceptions in exc_tuple occur in the mainloop (specifically, in the
1275 runcode() method.
1271 runcode() method.
1276
1272
1277 Inputs:
1273 Inputs:
1278
1274
1279 - exc_tuple: a *tuple* of valid exceptions to call the defined
1275 - exc_tuple: a *tuple* of valid exceptions to call the defined
1280 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
1281 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
1282 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:
1283
1279
1284 exc_tuple == (MyCustomException,)
1280 exc_tuple == (MyCustomException,)
1285
1281
1286 - handler: this must be defined as a function with the following
1282 - handler: this must be defined as a function with the following
1287 basic interface::
1283 basic interface::
1288
1284
1289 def my_handler(self, etype, value, tb, tb_offset=None)
1285 def my_handler(self, etype, value, tb, tb_offset=None)
1290 ...
1286 ...
1291 # The return value must be
1287 # The return value must be
1292 return structured_traceback
1288 return structured_traceback
1293
1289
1294 This will be made into an instance method (via new.instancemethod)
1290 This will be made into an instance method (via new.instancemethod)
1295 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
1296 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
1297 internal basic one is used, which just prints basic info.
1293 internal basic one is used, which just prints basic info.
1298
1294
1299 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
1300 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
1301 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."""
1302
1298
1303 assert type(exc_tuple)==type(()) , \
1299 assert type(exc_tuple)==type(()) , \
1304 "The custom exceptions must be given AS A TUPLE."
1300 "The custom exceptions must be given AS A TUPLE."
1305
1301
1306 def dummy_handler(self,etype,value,tb):
1302 def dummy_handler(self,etype,value,tb):
1307 print '*** Simple custom exception handler ***'
1303 print '*** Simple custom exception handler ***'
1308 print 'Exception type :',etype
1304 print 'Exception type :',etype
1309 print 'Exception value:',value
1305 print 'Exception value:',value
1310 print 'Traceback :',tb
1306 print 'Traceback :',tb
1311 print 'Source code :','\n'.join(self.buffer)
1307 print 'Source code :','\n'.join(self.buffer)
1312
1308
1313 if handler is None: handler = dummy_handler
1309 if handler is None: handler = dummy_handler
1314
1310
1315 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1311 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1316 self.custom_exceptions = exc_tuple
1312 self.custom_exceptions = exc_tuple
1317
1313
1318 def excepthook(self, etype, value, tb):
1314 def excepthook(self, etype, value, tb):
1319 """One more defense for GUI apps that call sys.excepthook.
1315 """One more defense for GUI apps that call sys.excepthook.
1320
1316
1321 GUI frameworks like wxPython trap exceptions and call
1317 GUI frameworks like wxPython trap exceptions and call
1322 sys.excepthook themselves. I guess this is a feature that
1318 sys.excepthook themselves. I guess this is a feature that
1323 enables them to keep running after exceptions that would
1319 enables them to keep running after exceptions that would
1324 otherwise kill their mainloop. This is a bother for IPython
1320 otherwise kill their mainloop. This is a bother for IPython
1325 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:
1326 except: statement.
1322 except: statement.
1327
1323
1328 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1324 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1329 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
1330 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
1331 CrashHandler and replace it with this excepthook instead, which prints a
1327 CrashHandler and replace it with this excepthook instead, which prints a
1332 regular traceback using our InteractiveTB. In this fashion, apps which
1328 regular traceback using our InteractiveTB. In this fashion, apps which
1333 call sys.excepthook will generate a regular-looking exception from
1329 call sys.excepthook will generate a regular-looking exception from
1334 IPython, and the CrashHandler will only be triggered by real IPython
1330 IPython, and the CrashHandler will only be triggered by real IPython
1335 crashes.
1331 crashes.
1336
1332
1337 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
1338 to be true IPython errors.
1334 to be true IPython errors.
1339 """
1335 """
1340 self.showtraceback((etype,value,tb),tb_offset=0)
1336 self.showtraceback((etype,value,tb),tb_offset=0)
1341
1337
1342 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1338 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1343 exception_only=False):
1339 exception_only=False):
1344 """Display the exception that just occurred.
1340 """Display the exception that just occurred.
1345
1341
1346 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
1347 should be used throughout the code for presenting user tracebacks,
1343 should be used throughout the code for presenting user tracebacks,
1348 rather than directly invoking the InteractiveTB object.
1344 rather than directly invoking the InteractiveTB object.
1349
1345
1350 A specific showsyntaxerror() also exists, but this method can take
1346 A specific showsyntaxerror() also exists, but this method can take
1351 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
1352 SyntaxError exception, don't try to analyze the stack manually and
1348 SyntaxError exception, don't try to analyze the stack manually and
1353 simply call this method."""
1349 simply call this method."""
1354
1350
1355 try:
1351 try:
1356 if exc_tuple is None:
1352 if exc_tuple is None:
1357 etype, value, tb = sys.exc_info()
1353 etype, value, tb = sys.exc_info()
1358 else:
1354 else:
1359 etype, value, tb = exc_tuple
1355 etype, value, tb = exc_tuple
1360
1356
1361 if etype is None:
1357 if etype is None:
1362 if hasattr(sys, 'last_type'):
1358 if hasattr(sys, 'last_type'):
1363 etype, value, tb = sys.last_type, sys.last_value, \
1359 etype, value, tb = sys.last_type, sys.last_value, \
1364 sys.last_traceback
1360 sys.last_traceback
1365 else:
1361 else:
1366 self.write_err('No traceback available to show.\n')
1362 self.write_err('No traceback available to show.\n')
1367 return
1363 return
1368
1364
1369 if etype is SyntaxError:
1365 if etype is SyntaxError:
1370 # 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
1371 # line, there may be SyntaxError cases whith imported code.
1367 # line, there may be SyntaxError cases whith imported code.
1372 self.showsyntaxerror(filename)
1368 self.showsyntaxerror(filename)
1373 elif etype is UsageError:
1369 elif etype is UsageError:
1374 print "UsageError:", value
1370 print "UsageError:", value
1375 else:
1371 else:
1376 # WARNING: these variables are somewhat deprecated and not
1372 # WARNING: these variables are somewhat deprecated and not
1377 # necessarily safe to use in a threaded environment, but tools
1373 # necessarily safe to use in a threaded environment, but tools
1378 # 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
1379 # 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.
1380 sys.last_type = etype
1376 sys.last_type = etype
1381 sys.last_value = value
1377 sys.last_value = value
1382 sys.last_traceback = tb
1378 sys.last_traceback = tb
1383
1379
1384 if etype in self.custom_exceptions:
1380 if etype in self.custom_exceptions:
1385 # FIXME: Old custom traceback objects may just return a
1381 # FIXME: Old custom traceback objects may just return a
1386 # string, in that case we just put it into a list
1382 # string, in that case we just put it into a list
1387 stb = self.CustomTB(etype, value, tb, tb_offset)
1383 stb = self.CustomTB(etype, value, tb, tb_offset)
1388 if isinstance(ctb, basestring):
1384 if isinstance(ctb, basestring):
1389 stb = [stb]
1385 stb = [stb]
1390 else:
1386 else:
1391 if exception_only:
1387 if exception_only:
1392 stb = ['An exception has occurred, use %tb to see '
1388 stb = ['An exception has occurred, use %tb to see '
1393 'the full traceback.\n']
1389 'the full traceback.\n']
1394 stb.extend(self.InteractiveTB.get_exception_only(etype,
1390 stb.extend(self.InteractiveTB.get_exception_only(etype,
1395 value))
1391 value))
1396 else:
1392 else:
1397 stb = self.InteractiveTB.structured_traceback(etype,
1393 stb = self.InteractiveTB.structured_traceback(etype,
1398 value, tb, tb_offset=tb_offset)
1394 value, tb, tb_offset=tb_offset)
1399 # FIXME: the pdb calling should be done by us, not by
1395 # FIXME: the pdb calling should be done by us, not by
1400 # the code computing the traceback.
1396 # the code computing the traceback.
1401 if self.InteractiveTB.call_pdb:
1397 if self.InteractiveTB.call_pdb:
1402 # pdb mucks up readline, fix it back
1398 # pdb mucks up readline, fix it back
1403 self.set_readline_completer()
1399 self.set_readline_completer()
1404
1400
1405 # Actually show the traceback
1401 # Actually show the traceback
1406 self._showtraceback(etype, value, stb)
1402 self._showtraceback(etype, value, stb)
1407
1403
1408 except KeyboardInterrupt:
1404 except KeyboardInterrupt:
1409 self.write_err("\nKeyboardInterrupt\n")
1405 self.write_err("\nKeyboardInterrupt\n")
1410
1406
1411 def _showtraceback(self, etype, evalue, stb):
1407 def _showtraceback(self, etype, evalue, stb):
1412 """Actually show a traceback.
1408 """Actually show a traceback.
1413
1409
1414 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
1415 place, like a side channel.
1411 place, like a side channel.
1416 """
1412 """
1417 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1413 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1418
1414
1419 def showsyntaxerror(self, filename=None):
1415 def showsyntaxerror(self, filename=None):
1420 """Display the syntax error that just occurred.
1416 """Display the syntax error that just occurred.
1421
1417
1422 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.
1423
1419
1424 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
1425 of what was there before (because Python's parser always uses
1421 of what was there before (because Python's parser always uses
1426 "<string>" when reading from a string).
1422 "<string>" when reading from a string).
1427 """
1423 """
1428 etype, value, last_traceback = sys.exc_info()
1424 etype, value, last_traceback = sys.exc_info()
1429
1425
1430 # See note about these variables in showtraceback() above
1426 # See note about these variables in showtraceback() above
1431 sys.last_type = etype
1427 sys.last_type = etype
1432 sys.last_value = value
1428 sys.last_value = value
1433 sys.last_traceback = last_traceback
1429 sys.last_traceback = last_traceback
1434
1430
1435 if filename and etype is SyntaxError:
1431 if filename and etype is SyntaxError:
1436 # Work hard to stuff the correct filename in the exception
1432 # Work hard to stuff the correct filename in the exception
1437 try:
1433 try:
1438 msg, (dummy_filename, lineno, offset, line) = value
1434 msg, (dummy_filename, lineno, offset, line) = value
1439 except:
1435 except:
1440 # Not the format we expect; leave it alone
1436 # Not the format we expect; leave it alone
1441 pass
1437 pass
1442 else:
1438 else:
1443 # Stuff in the right filename
1439 # Stuff in the right filename
1444 try:
1440 try:
1445 # Assume SyntaxError is a class exception
1441 # Assume SyntaxError is a class exception
1446 value = SyntaxError(msg, (filename, lineno, offset, line))
1442 value = SyntaxError(msg, (filename, lineno, offset, line))
1447 except:
1443 except:
1448 # If that failed, assume SyntaxError is a string
1444 # If that failed, assume SyntaxError is a string
1449 value = msg, (filename, lineno, offset, line)
1445 value = msg, (filename, lineno, offset, line)
1450 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1446 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1451 self._showtraceback(etype, value, stb)
1447 self._showtraceback(etype, value, stb)
1452
1448
1453 #-------------------------------------------------------------------------
1449 #-------------------------------------------------------------------------
1454 # Things related to readline
1450 # Things related to readline
1455 #-------------------------------------------------------------------------
1451 #-------------------------------------------------------------------------
1456
1452
1457 def init_readline(self):
1453 def init_readline(self):
1458 """Command history completion/saving/reloading."""
1454 """Command history completion/saving/reloading."""
1459
1455
1460 if self.readline_use:
1456 if self.readline_use:
1461 import IPython.utils.rlineimpl as readline
1457 import IPython.utils.rlineimpl as readline
1462
1458
1463 self.rl_next_input = None
1459 self.rl_next_input = None
1464 self.rl_do_indent = False
1460 self.rl_do_indent = False
1465
1461
1466 if not self.readline_use or not readline.have_readline:
1462 if not self.readline_use or not readline.have_readline:
1467 self.has_readline = False
1463 self.has_readline = False
1468 self.readline = None
1464 self.readline = None
1469 # 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
1470 self.savehist = no_op
1466 self.savehist = no_op
1471 self.reloadhist = no_op
1467 self.reloadhist = no_op
1472 self.set_readline_completer = no_op
1468 self.set_readline_completer = no_op
1473 self.set_custom_completer = no_op
1469 self.set_custom_completer = no_op
1474 self.set_completer_frame = no_op
1470 self.set_completer_frame = no_op
1475 warn('Readline services not available or not loaded.')
1471 warn('Readline services not available or not loaded.')
1476 else:
1472 else:
1477 self.has_readline = True
1473 self.has_readline = True
1478 self.readline = readline
1474 self.readline = readline
1479 sys.modules['readline'] = readline
1475 sys.modules['readline'] = readline
1480
1476
1481 # Platform-specific configuration
1477 # Platform-specific configuration
1482 if os.name == 'nt':
1478 if os.name == 'nt':
1483 # FIXME - check with Frederick to see if we can harmonize
1479 # FIXME - check with Frederick to see if we can harmonize
1484 # naming conventions with pyreadline to avoid this
1480 # naming conventions with pyreadline to avoid this
1485 # platform-dependent check
1481 # platform-dependent check
1486 self.readline_startup_hook = readline.set_pre_input_hook
1482 self.readline_startup_hook = readline.set_pre_input_hook
1487 else:
1483 else:
1488 self.readline_startup_hook = readline.set_startup_hook
1484 self.readline_startup_hook = readline.set_startup_hook
1489
1485
1490 # Load user's initrc file (readline config)
1486 # Load user's initrc file (readline config)
1491 # Or if libedit is used, load editrc.
1487 # Or if libedit is used, load editrc.
1492 inputrc_name = os.environ.get('INPUTRC')
1488 inputrc_name = os.environ.get('INPUTRC')
1493 if inputrc_name is None:
1489 if inputrc_name is None:
1494 home_dir = get_home_dir()
1490 home_dir = get_home_dir()
1495 if home_dir is not None:
1491 if home_dir is not None:
1496 inputrc_name = '.inputrc'
1492 inputrc_name = '.inputrc'
1497 if readline.uses_libedit:
1493 if readline.uses_libedit:
1498 inputrc_name = '.editrc'
1494 inputrc_name = '.editrc'
1499 inputrc_name = os.path.join(home_dir, inputrc_name)
1495 inputrc_name = os.path.join(home_dir, inputrc_name)
1500 if os.path.isfile(inputrc_name):
1496 if os.path.isfile(inputrc_name):
1501 try:
1497 try:
1502 readline.read_init_file(inputrc_name)
1498 readline.read_init_file(inputrc_name)
1503 except:
1499 except:
1504 warn('Problems reading readline initialization file <%s>'
1500 warn('Problems reading readline initialization file <%s>'
1505 % inputrc_name)
1501 % inputrc_name)
1506
1502
1507 # Configure readline according to user's prefs
1503 # Configure readline according to user's prefs
1508 # 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
1509 # is being used (as on Leopard) the readline config is
1505 # is being used (as on Leopard) the readline config is
1510 # not run as the syntax for libedit is different.
1506 # not run as the syntax for libedit is different.
1511 if not readline.uses_libedit:
1507 if not readline.uses_libedit:
1512 for rlcommand in self.readline_parse_and_bind:
1508 for rlcommand in self.readline_parse_and_bind:
1513 #print "loading rl:",rlcommand # dbg
1509 #print "loading rl:",rlcommand # dbg
1514 readline.parse_and_bind(rlcommand)
1510 readline.parse_and_bind(rlcommand)
1515
1511
1516 # Remove some chars from the delimiters list. If we encounter
1512 # Remove some chars from the delimiters list. If we encounter
1517 # unicode chars, discard them.
1513 # unicode chars, discard them.
1518 delims = readline.get_completer_delims().encode("ascii", "ignore")
1514 delims = readline.get_completer_delims().encode("ascii", "ignore")
1519 delims = delims.translate(string._idmap,
1515 delims = delims.translate(string._idmap,
1520 self.readline_remove_delims)
1516 self.readline_remove_delims)
1521 delims = delims.replace(ESC_MAGIC, '')
1517 delims = delims.replace(ESC_MAGIC, '')
1522 readline.set_completer_delims(delims)
1518 readline.set_completer_delims(delims)
1523 # otherwise we end up with a monster history after a while:
1519 # otherwise we end up with a monster history after a while:
1524 readline.set_history_length(1000)
1520 readline.set_history_length(1000)
1525 try:
1521 try:
1526 #print '*** Reading readline history' # dbg
1522 #print '*** Reading readline history' # dbg
1527 readline.read_history_file(self.histfile)
1523 readline.read_history_file(self.histfile)
1528 except IOError:
1524 except IOError:
1529 pass # It doesn't exist yet.
1525 pass # It doesn't exist yet.
1530
1526
1531 # If we have readline, we want our history saved upon ipython
1527 # If we have readline, we want our history saved upon ipython
1532 # exiting.
1528 # exiting.
1533 atexit.register(self.savehist)
1529 atexit.register(self.savehist)
1534
1530
1535 # Configure auto-indent for all platforms
1531 # Configure auto-indent for all platforms
1536 self.set_autoindent(self.autoindent)
1532 self.set_autoindent(self.autoindent)
1537
1533
1538 def set_next_input(self, s):
1534 def set_next_input(self, s):
1539 """ Sets the 'default' input string for the next command line.
1535 """ Sets the 'default' input string for the next command line.
1540
1536
1541 Requires readline.
1537 Requires readline.
1542
1538
1543 Example:
1539 Example:
1544
1540
1545 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1541 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1546 [D:\ipython]|2> Hello Word_ # cursor is here
1542 [D:\ipython]|2> Hello Word_ # cursor is here
1547 """
1543 """
1548
1544
1549 self.rl_next_input = s
1545 self.rl_next_input = s
1550
1546
1551 # Maybe move this to the terminal subclass?
1547 # Maybe move this to the terminal subclass?
1552 def pre_readline(self):
1548 def pre_readline(self):
1553 """readline hook to be used at the start of each line.
1549 """readline hook to be used at the start of each line.
1554
1550
1555 Currently it handles auto-indent only."""
1551 Currently it handles auto-indent only."""
1556
1552
1557 if self.rl_do_indent:
1553 if self.rl_do_indent:
1558 self.readline.insert_text(self._indent_current_str())
1554 self.readline.insert_text(self._indent_current_str())
1559 if self.rl_next_input is not None:
1555 if self.rl_next_input is not None:
1560 self.readline.insert_text(self.rl_next_input)
1556 self.readline.insert_text(self.rl_next_input)
1561 self.rl_next_input = None
1557 self.rl_next_input = None
1562
1558
1563 def _indent_current_str(self):
1559 def _indent_current_str(self):
1564 """return the current level of indentation as a string"""
1560 """return the current level of indentation as a string"""
1565 return self.indent_current_nsp * ' '
1561 return self.indent_current_nsp * ' '
1566
1562
1567 #-------------------------------------------------------------------------
1563 #-------------------------------------------------------------------------
1568 # Things related to text completion
1564 # Things related to text completion
1569 #-------------------------------------------------------------------------
1565 #-------------------------------------------------------------------------
1570
1566
1571 def init_completer(self):
1567 def init_completer(self):
1572 """Initialize the completion machinery.
1568 """Initialize the completion machinery.
1573
1569
1574 This creates completion machinery that can be used by client code,
1570 This creates completion machinery that can be used by client code,
1575 either interactively in-process (typically triggered by the readline
1571 either interactively in-process (typically triggered by the readline
1576 library), programatically (such as in test suites) or out-of-prcess
1572 library), programatically (such as in test suites) or out-of-prcess
1577 (typically over the network by remote frontends).
1573 (typically over the network by remote frontends).
1578 """
1574 """
1579 from IPython.core.completer import IPCompleter
1575 from IPython.core.completer import IPCompleter
1580 from IPython.core.completerlib import (module_completer,
1576 from IPython.core.completerlib import (module_completer,
1581 magic_run_completer, cd_completer)
1577 magic_run_completer, cd_completer)
1582
1578
1583 self.Completer = IPCompleter(self,
1579 self.Completer = IPCompleter(self,
1584 self.user_ns,
1580 self.user_ns,
1585 self.user_global_ns,
1581 self.user_global_ns,
1586 self.readline_omit__names,
1582 self.readline_omit__names,
1587 self.alias_manager.alias_table,
1583 self.alias_manager.alias_table,
1588 self.has_readline)
1584 self.has_readline)
1589
1585
1590 # Add custom completers to the basic ones built into IPCompleter
1586 # Add custom completers to the basic ones built into IPCompleter
1591 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1587 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1592 self.strdispatchers['complete_command'] = sdisp
1588 self.strdispatchers['complete_command'] = sdisp
1593 self.Completer.custom_completers = sdisp
1589 self.Completer.custom_completers = sdisp
1594
1590
1595 self.set_hook('complete_command', module_completer, str_key = 'import')
1591 self.set_hook('complete_command', module_completer, str_key = 'import')
1596 self.set_hook('complete_command', module_completer, str_key = 'from')
1592 self.set_hook('complete_command', module_completer, str_key = 'from')
1597 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1593 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1598 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1594 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1599
1595
1600 # Only configure readline if we truly are using readline. IPython can
1596 # Only configure readline if we truly are using readline. IPython can
1601 # do tab-completion over the network, in GUIs, etc, where readline
1597 # do tab-completion over the network, in GUIs, etc, where readline
1602 # itself may be absent
1598 # itself may be absent
1603 if self.has_readline:
1599 if self.has_readline:
1604 self.set_readline_completer()
1600 self.set_readline_completer()
1605
1601
1606 def complete(self, text, line=None, cursor_pos=None):
1602 def complete(self, text, line=None, cursor_pos=None):
1607 """Return the completed text and a list of completions.
1603 """Return the completed text and a list of completions.
1608
1604
1609 Parameters
1605 Parameters
1610 ----------
1606 ----------
1611
1607
1612 text : string
1608 text : string
1613 A string of text to be completed on. It can be given as empty and
1609 A string of text to be completed on. It can be given as empty and
1614 instead a line/position pair are given. In this case, the
1610 instead a line/position pair are given. In this case, the
1615 completer itself will split the line like readline does.
1611 completer itself will split the line like readline does.
1616
1612
1617 line : string, optional
1613 line : string, optional
1618 The complete line that text is part of.
1614 The complete line that text is part of.
1619
1615
1620 cursor_pos : int, optional
1616 cursor_pos : int, optional
1621 The position of the cursor on the input line.
1617 The position of the cursor on the input line.
1622
1618
1623 Returns
1619 Returns
1624 -------
1620 -------
1625 text : string
1621 text : string
1626 The actual text that was completed.
1622 The actual text that was completed.
1627
1623
1628 matches : list
1624 matches : list
1629 A sorted list with all possible completions.
1625 A sorted list with all possible completions.
1630
1626
1631 The optional arguments allow the completion to take more context into
1627 The optional arguments allow the completion to take more context into
1632 account, and are part of the low-level completion API.
1628 account, and are part of the low-level completion API.
1633
1629
1634 This is a wrapper around the completion mechanism, similar to what
1630 This is a wrapper around the completion mechanism, similar to what
1635 readline does at the command line when the TAB key is hit. By
1631 readline does at the command line when the TAB key is hit. By
1636 exposing it as a method, it can be used by other non-readline
1632 exposing it as a method, it can be used by other non-readline
1637 environments (such as GUIs) for text completion.
1633 environments (such as GUIs) for text completion.
1638
1634
1639 Simple usage example:
1635 Simple usage example:
1640
1636
1641 In [1]: x = 'hello'
1637 In [1]: x = 'hello'
1642
1638
1643 In [2]: _ip.complete('x.l')
1639 In [2]: _ip.complete('x.l')
1644 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1640 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1645 """
1641 """
1646
1642
1647 # Inject names into __builtin__ so we can complete on the added names.
1643 # Inject names into __builtin__ so we can complete on the added names.
1648 with self.builtin_trap:
1644 with self.builtin_trap:
1649 return self.Completer.complete(text, line, cursor_pos)
1645 return self.Completer.complete(text, line, cursor_pos)
1650
1646
1651 def set_custom_completer(self, completer, pos=0):
1647 def set_custom_completer(self, completer, pos=0):
1652 """Adds a new custom completer function.
1648 """Adds a new custom completer function.
1653
1649
1654 The position argument (defaults to 0) is the index in the completers
1650 The position argument (defaults to 0) is the index in the completers
1655 list where you want the completer to be inserted."""
1651 list where you want the completer to be inserted."""
1656
1652
1657 newcomp = new.instancemethod(completer,self.Completer,
1653 newcomp = new.instancemethod(completer,self.Completer,
1658 self.Completer.__class__)
1654 self.Completer.__class__)
1659 self.Completer.matchers.insert(pos,newcomp)
1655 self.Completer.matchers.insert(pos,newcomp)
1660
1656
1661 def set_readline_completer(self):
1657 def set_readline_completer(self):
1662 """Reset readline's completer to be our own."""
1658 """Reset readline's completer to be our own."""
1663 self.readline.set_completer(self.Completer.rlcomplete)
1659 self.readline.set_completer(self.Completer.rlcomplete)
1664
1660
1665 def set_completer_frame(self, frame=None):
1661 def set_completer_frame(self, frame=None):
1666 """Set the frame of the completer."""
1662 """Set the frame of the completer."""
1667 if frame:
1663 if frame:
1668 self.Completer.namespace = frame.f_locals
1664 self.Completer.namespace = frame.f_locals
1669 self.Completer.global_namespace = frame.f_globals
1665 self.Completer.global_namespace = frame.f_globals
1670 else:
1666 else:
1671 self.Completer.namespace = self.user_ns
1667 self.Completer.namespace = self.user_ns
1672 self.Completer.global_namespace = self.user_global_ns
1668 self.Completer.global_namespace = self.user_global_ns
1673
1669
1674 #-------------------------------------------------------------------------
1670 #-------------------------------------------------------------------------
1675 # Things related to magics
1671 # Things related to magics
1676 #-------------------------------------------------------------------------
1672 #-------------------------------------------------------------------------
1677
1673
1678 def init_magics(self):
1674 def init_magics(self):
1679 # FIXME: Move the color initialization to the DisplayHook, which
1675 # FIXME: Move the color initialization to the DisplayHook, which
1680 # should be split into a prompt manager and displayhook. We probably
1676 # should be split into a prompt manager and displayhook. We probably
1681 # even need a centralize colors management object.
1677 # even need a centralize colors management object.
1682 self.magic_colors(self.colors)
1678 self.magic_colors(self.colors)
1683 # History was moved to a separate module
1679 # History was moved to a separate module
1684 from . import history
1680 from . import history
1685 history.init_ipython(self)
1681 history.init_ipython(self)
1686
1682
1687 def magic(self,arg_s):
1683 def magic(self,arg_s):
1688 """Call a magic function by name.
1684 """Call a magic function by name.
1689
1685
1690 Input: a string containing the name of the magic function to call and
1686 Input: a string containing the name of the magic function to call and
1691 any additional arguments to be passed to the magic.
1687 any additional arguments to be passed to the magic.
1692
1688
1693 magic('name -opt foo bar') is equivalent to typing at the ipython
1689 magic('name -opt foo bar') is equivalent to typing at the ipython
1694 prompt:
1690 prompt:
1695
1691
1696 In[1]: %name -opt foo bar
1692 In[1]: %name -opt foo bar
1697
1693
1698 To call a magic without arguments, simply use magic('name').
1694 To call a magic without arguments, simply use magic('name').
1699
1695
1700 This provides a proper Python function to call IPython's magics in any
1696 This provides a proper Python function to call IPython's magics in any
1701 valid Python code you can type at the interpreter, including loops and
1697 valid Python code you can type at the interpreter, including loops and
1702 compound statements.
1698 compound statements.
1703 """
1699 """
1704 args = arg_s.split(' ',1)
1700 args = arg_s.split(' ',1)
1705 magic_name = args[0]
1701 magic_name = args[0]
1706 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1702 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1707
1703
1708 try:
1704 try:
1709 magic_args = args[1]
1705 magic_args = args[1]
1710 except IndexError:
1706 except IndexError:
1711 magic_args = ''
1707 magic_args = ''
1712 fn = getattr(self,'magic_'+magic_name,None)
1708 fn = getattr(self,'magic_'+magic_name,None)
1713 if fn is None:
1709 if fn is None:
1714 error("Magic function `%s` not found." % magic_name)
1710 error("Magic function `%s` not found." % magic_name)
1715 else:
1711 else:
1716 magic_args = self.var_expand(magic_args,1)
1712 magic_args = self.var_expand(magic_args,1)
1717 with nested(self.builtin_trap,):
1713 with nested(self.builtin_trap,):
1718 result = fn(magic_args)
1714 result = fn(magic_args)
1719 return result
1715 return result
1720
1716
1721 def define_magic(self, magicname, func):
1717 def define_magic(self, magicname, func):
1722 """Expose own function as magic function for ipython
1718 """Expose own function as magic function for ipython
1723
1719
1724 def foo_impl(self,parameter_s=''):
1720 def foo_impl(self,parameter_s=''):
1725 'My very own magic!. (Use docstrings, IPython reads them).'
1721 'My very own magic!. (Use docstrings, IPython reads them).'
1726 print 'Magic function. Passed parameter is between < >:'
1722 print 'Magic function. Passed parameter is between < >:'
1727 print '<%s>' % parameter_s
1723 print '<%s>' % parameter_s
1728 print 'The self object is:',self
1724 print 'The self object is:',self
1729
1725
1730 self.define_magic('foo',foo_impl)
1726 self.define_magic('foo',foo_impl)
1731 """
1727 """
1732
1728
1733 import new
1729 import new
1734 im = new.instancemethod(func,self, self.__class__)
1730 im = new.instancemethod(func,self, self.__class__)
1735 old = getattr(self, "magic_" + magicname, None)
1731 old = getattr(self, "magic_" + magicname, None)
1736 setattr(self, "magic_" + magicname, im)
1732 setattr(self, "magic_" + magicname, im)
1737 return old
1733 return old
1738
1734
1739 #-------------------------------------------------------------------------
1735 #-------------------------------------------------------------------------
1740 # Things related to macros
1736 # Things related to macros
1741 #-------------------------------------------------------------------------
1737 #-------------------------------------------------------------------------
1742
1738
1743 def define_macro(self, name, themacro):
1739 def define_macro(self, name, themacro):
1744 """Define a new macro
1740 """Define a new macro
1745
1741
1746 Parameters
1742 Parameters
1747 ----------
1743 ----------
1748 name : str
1744 name : str
1749 The name of the macro.
1745 The name of the macro.
1750 themacro : str or Macro
1746 themacro : str or Macro
1751 The action to do upon invoking the macro. If a string, a new
1747 The action to do upon invoking the macro. If a string, a new
1752 Macro object is created by passing the string to it.
1748 Macro object is created by passing the string to it.
1753 """
1749 """
1754
1750
1755 from IPython.core import macro
1751 from IPython.core import macro
1756
1752
1757 if isinstance(themacro, basestring):
1753 if isinstance(themacro, basestring):
1758 themacro = macro.Macro(themacro)
1754 themacro = macro.Macro(themacro)
1759 if not isinstance(themacro, macro.Macro):
1755 if not isinstance(themacro, macro.Macro):
1760 raise ValueError('A macro must be a string or a Macro instance.')
1756 raise ValueError('A macro must be a string or a Macro instance.')
1761 self.user_ns[name] = themacro
1757 self.user_ns[name] = themacro
1762
1758
1763 #-------------------------------------------------------------------------
1759 #-------------------------------------------------------------------------
1764 # Things related to the running of system commands
1760 # Things related to the running of system commands
1765 #-------------------------------------------------------------------------
1761 #-------------------------------------------------------------------------
1766
1762
1767 def system(self, cmd):
1763 def system(self, cmd):
1768 """Call the given cmd in a subprocess.
1764 """Call the given cmd in a subprocess.
1769
1765
1770 Parameters
1766 Parameters
1771 ----------
1767 ----------
1772 cmd : str
1768 cmd : str
1773 Command to execute (can not end in '&', as bacground processes are
1769 Command to execute (can not end in '&', as bacground processes are
1774 not supported.
1770 not supported.
1775 """
1771 """
1776 # We do not support backgrounding processes because we either use
1772 # We do not support backgrounding processes because we either use
1777 # pexpect or pipes to read from. Users can always just call
1773 # pexpect or pipes to read from. Users can always just call
1778 # os.system() if they really want a background process.
1774 # os.system() if they really want a background process.
1779 if cmd.endswith('&'):
1775 if cmd.endswith('&'):
1780 raise OSError("Background processes not supported.")
1776 raise OSError("Background processes not supported.")
1781
1777
1782 return system(self.var_expand(cmd, depth=2))
1778 return system(self.var_expand(cmd, depth=2))
1783
1779
1784 def getoutput(self, cmd, split=True):
1780 def getoutput(self, cmd, split=True):
1785 """Get output (possibly including stderr) from a subprocess.
1781 """Get output (possibly including stderr) from a subprocess.
1786
1782
1787 Parameters
1783 Parameters
1788 ----------
1784 ----------
1789 cmd : str
1785 cmd : str
1790 Command to execute (can not end in '&', as background processes are
1786 Command to execute (can not end in '&', as background processes are
1791 not supported.
1787 not supported.
1792 split : bool, optional
1788 split : bool, optional
1793
1789
1794 If True, split the output into an IPython SList. Otherwise, an
1790 If True, split the output into an IPython SList. Otherwise, an
1795 IPython LSString is returned. These are objects similar to normal
1791 IPython LSString is returned. These are objects similar to normal
1796 lists and strings, with a few convenience attributes for easier
1792 lists and strings, with a few convenience attributes for easier
1797 manipulation of line-based output. You can use '?' on them for
1793 manipulation of line-based output. You can use '?' on them for
1798 details.
1794 details.
1799 """
1795 """
1800 if cmd.endswith('&'):
1796 if cmd.endswith('&'):
1801 raise OSError("Background processes not supported.")
1797 raise OSError("Background processes not supported.")
1802 out = getoutput(self.var_expand(cmd, depth=2))
1798 out = getoutput(self.var_expand(cmd, depth=2))
1803 if split:
1799 if split:
1804 out = SList(out.splitlines())
1800 out = SList(out.splitlines())
1805 else:
1801 else:
1806 out = LSString(out)
1802 out = LSString(out)
1807 return out
1803 return out
1808
1804
1809 #-------------------------------------------------------------------------
1805 #-------------------------------------------------------------------------
1810 # Things related to aliases
1806 # Things related to aliases
1811 #-------------------------------------------------------------------------
1807 #-------------------------------------------------------------------------
1812
1808
1813 def init_alias(self):
1809 def init_alias(self):
1814 self.alias_manager = AliasManager(shell=self, config=self.config)
1810 self.alias_manager = AliasManager(shell=self, config=self.config)
1815 self.ns_table['alias'] = self.alias_manager.alias_table,
1811 self.ns_table['alias'] = self.alias_manager.alias_table,
1816
1812
1817 #-------------------------------------------------------------------------
1813 #-------------------------------------------------------------------------
1818 # Things related to extensions and plugins
1814 # Things related to extensions and plugins
1819 #-------------------------------------------------------------------------
1815 #-------------------------------------------------------------------------
1820
1816
1821 def init_extension_manager(self):
1817 def init_extension_manager(self):
1822 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1818 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1823
1819
1824 def init_plugin_manager(self):
1820 def init_plugin_manager(self):
1825 self.plugin_manager = PluginManager(config=self.config)
1821 self.plugin_manager = PluginManager(config=self.config)
1826
1822
1827 #-------------------------------------------------------------------------
1823 #-------------------------------------------------------------------------
1828 # Things related to payloads
1824 # Things related to payloads
1829 #-------------------------------------------------------------------------
1825 #-------------------------------------------------------------------------
1830
1826
1831 def init_payload(self):
1827 def init_payload(self):
1832 self.payload_manager = PayloadManager(config=self.config)
1828 self.payload_manager = PayloadManager(config=self.config)
1833
1829
1834 #-------------------------------------------------------------------------
1830 #-------------------------------------------------------------------------
1835 # Things related to the prefilter
1831 # Things related to the prefilter
1836 #-------------------------------------------------------------------------
1832 #-------------------------------------------------------------------------
1837
1833
1838 def init_prefilter(self):
1834 def init_prefilter(self):
1839 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1835 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1840 # Ultimately this will be refactored in the new interpreter code, but
1836 # Ultimately this will be refactored in the new interpreter code, but
1841 # for now, we should expose the main prefilter method (there's legacy
1837 # for now, we should expose the main prefilter method (there's legacy
1842 # code out there that may rely on this).
1838 # code out there that may rely on this).
1843 self.prefilter = self.prefilter_manager.prefilter_lines
1839 self.prefilter = self.prefilter_manager.prefilter_lines
1844
1840
1845
1841
1846 def auto_rewrite_input(self, cmd):
1842 def auto_rewrite_input(self, cmd):
1847 """Print to the screen the rewritten form of the user's command.
1843 """Print to the screen the rewritten form of the user's command.
1848
1844
1849 This shows visual feedback by rewriting input lines that cause
1845 This shows visual feedback by rewriting input lines that cause
1850 automatic calling to kick in, like::
1846 automatic calling to kick in, like::
1851
1847
1852 /f x
1848 /f x
1853
1849
1854 into::
1850 into::
1855
1851
1856 ------> f(x)
1852 ------> f(x)
1857
1853
1858 after the user's input prompt. This helps the user understand that the
1854 after the user's input prompt. This helps the user understand that the
1859 input line was transformed automatically by IPython.
1855 input line was transformed automatically by IPython.
1860 """
1856 """
1861 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1857 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1862
1858
1863 try:
1859 try:
1864 # plain ascii works better w/ pyreadline, on some machines, so
1860 # plain ascii works better w/ pyreadline, on some machines, so
1865 # we use it and only print uncolored rewrite if we have unicode
1861 # we use it and only print uncolored rewrite if we have unicode
1866 rw = str(rw)
1862 rw = str(rw)
1867 print >> IPython.utils.io.Term.cout, rw
1863 print >> IPython.utils.io.Term.cout, rw
1868 except UnicodeEncodeError:
1864 except UnicodeEncodeError:
1869 print "------> " + cmd
1865 print "------> " + cmd
1870
1866
1871 #-------------------------------------------------------------------------
1867 #-------------------------------------------------------------------------
1872 # Things related to extracting values/expressions from kernel and user_ns
1868 # Things related to extracting values/expressions from kernel and user_ns
1873 #-------------------------------------------------------------------------
1869 #-------------------------------------------------------------------------
1874
1870
1875 def _simple_error(self):
1871 def _simple_error(self):
1876 etype, value = sys.exc_info()[:2]
1872 etype, value = sys.exc_info()[:2]
1877 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1873 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1878
1874
1879 def user_variables(self, names):
1875 def user_variables(self, names):
1880 """Get a list of variable names from the user's namespace.
1876 """Get a list of variable names from the user's namespace.
1881
1877
1882 Parameters
1878 Parameters
1883 ----------
1879 ----------
1884 names : list of strings
1880 names : list of strings
1885 A list of names of variables to be read from the user namespace.
1881 A list of names of variables to be read from the user namespace.
1886
1882
1887 Returns
1883 Returns
1888 -------
1884 -------
1889 A dict, keyed by the input names and with the repr() of each value.
1885 A dict, keyed by the input names and with the repr() of each value.
1890 """
1886 """
1891 out = {}
1887 out = {}
1892 user_ns = self.user_ns
1888 user_ns = self.user_ns
1893 for varname in names:
1889 for varname in names:
1894 try:
1890 try:
1895 value = repr(user_ns[varname])
1891 value = repr(user_ns[varname])
1896 except:
1892 except:
1897 value = self._simple_error()
1893 value = self._simple_error()
1898 out[varname] = value
1894 out[varname] = value
1899 return out
1895 return out
1900
1896
1901 def user_expressions(self, expressions):
1897 def user_expressions(self, expressions):
1902 """Evaluate a dict of expressions in the user's namespace.
1898 """Evaluate a dict of expressions in the user's namespace.
1903
1899
1904 Parameters
1900 Parameters
1905 ----------
1901 ----------
1906 expressions : dict
1902 expressions : dict
1907 A dict with string keys and string values. The expression values
1903 A dict with string keys and string values. The expression values
1908 should be valid Python expressions, each of which will be evaluated
1904 should be valid Python expressions, each of which will be evaluated
1909 in the user namespace.
1905 in the user namespace.
1910
1906
1911 Returns
1907 Returns
1912 -------
1908 -------
1913 A dict, keyed like the input expressions dict, with the repr() of each
1909 A dict, keyed like the input expressions dict, with the repr() of each
1914 value.
1910 value.
1915 """
1911 """
1916 out = {}
1912 out = {}
1917 user_ns = self.user_ns
1913 user_ns = self.user_ns
1918 global_ns = self.user_global_ns
1914 global_ns = self.user_global_ns
1919 for key, expr in expressions.iteritems():
1915 for key, expr in expressions.iteritems():
1920 try:
1916 try:
1921 value = repr(eval(expr, global_ns, user_ns))
1917 value = repr(eval(expr, global_ns, user_ns))
1922 except:
1918 except:
1923 value = self._simple_error()
1919 value = self._simple_error()
1924 out[key] = value
1920 out[key] = value
1925 return out
1921 return out
1926
1922
1927 #-------------------------------------------------------------------------
1923 #-------------------------------------------------------------------------
1928 # Things related to the running of code
1924 # Things related to the running of code
1929 #-------------------------------------------------------------------------
1925 #-------------------------------------------------------------------------
1930
1926
1931 def ex(self, cmd):
1927 def ex(self, cmd):
1932 """Execute a normal python statement in user namespace."""
1928 """Execute a normal python statement in user namespace."""
1933 with nested(self.builtin_trap,):
1929 with nested(self.builtin_trap,):
1934 exec cmd in self.user_global_ns, self.user_ns
1930 exec cmd in self.user_global_ns, self.user_ns
1935
1931
1936 def ev(self, expr):
1932 def ev(self, expr):
1937 """Evaluate python expression expr in user namespace.
1933 """Evaluate python expression expr in user namespace.
1938
1934
1939 Returns the result of evaluation
1935 Returns the result of evaluation
1940 """
1936 """
1941 with nested(self.builtin_trap,):
1937 with nested(self.builtin_trap,):
1942 return eval(expr, self.user_global_ns, self.user_ns)
1938 return eval(expr, self.user_global_ns, self.user_ns)
1943
1939
1944 def safe_execfile(self, fname, *where, **kw):
1940 def safe_execfile(self, fname, *where, **kw):
1945 """A safe version of the builtin execfile().
1941 """A safe version of the builtin execfile().
1946
1942
1947 This version will never throw an exception, but instead print
1943 This version will never throw an exception, but instead print
1948 helpful error messages to the screen. This only works on pure
1944 helpful error messages to the screen. This only works on pure
1949 Python files with the .py extension.
1945 Python files with the .py extension.
1950
1946
1951 Parameters
1947 Parameters
1952 ----------
1948 ----------
1953 fname : string
1949 fname : string
1954 The name of the file to be executed.
1950 The name of the file to be executed.
1955 where : tuple
1951 where : tuple
1956 One or two namespaces, passed to execfile() as (globals,locals).
1952 One or two namespaces, passed to execfile() as (globals,locals).
1957 If only one is given, it is passed as both.
1953 If only one is given, it is passed as both.
1958 exit_ignore : bool (False)
1954 exit_ignore : bool (False)
1959 If True, then silence SystemExit for non-zero status (it is always
1955 If True, then silence SystemExit for non-zero status (it is always
1960 silenced for zero status, as it is so common).
1956 silenced for zero status, as it is so common).
1961 """
1957 """
1962 kw.setdefault('exit_ignore', False)
1958 kw.setdefault('exit_ignore', False)
1963
1959
1964 fname = os.path.abspath(os.path.expanduser(fname))
1960 fname = os.path.abspath(os.path.expanduser(fname))
1965
1961
1966 # Make sure we have a .py file
1962 # Make sure we have a .py file
1967 if not fname.endswith('.py'):
1963 if not fname.endswith('.py'):
1968 warn('File must end with .py to be run using execfile: <%s>' % fname)
1964 warn('File must end with .py to be run using execfile: <%s>' % fname)
1969
1965
1970 # Make sure we can open the file
1966 # Make sure we can open the file
1971 try:
1967 try:
1972 with open(fname) as thefile:
1968 with open(fname) as thefile:
1973 pass
1969 pass
1974 except:
1970 except:
1975 warn('Could not open file <%s> for safe execution.' % fname)
1971 warn('Could not open file <%s> for safe execution.' % fname)
1976 return
1972 return
1977
1973
1978 # Find things also in current directory. This is needed to mimic the
1974 # Find things also in current directory. This is needed to mimic the
1979 # behavior of running a script from the system command line, where
1975 # behavior of running a script from the system command line, where
1980 # Python inserts the script's directory into sys.path
1976 # Python inserts the script's directory into sys.path
1981 dname = os.path.dirname(fname)
1977 dname = os.path.dirname(fname)
1982
1978
1983 with prepended_to_syspath(dname):
1979 with prepended_to_syspath(dname):
1984 try:
1980 try:
1985 execfile(fname,*where)
1981 execfile(fname,*where)
1986 except SystemExit, status:
1982 except SystemExit, status:
1987 # If the call was made with 0 or None exit status (sys.exit(0)
1983 # If the call was made with 0 or None exit status (sys.exit(0)
1988 # or sys.exit() ), don't bother showing a traceback, as both of
1984 # or sys.exit() ), don't bother showing a traceback, as both of
1989 # these are considered normal by the OS:
1985 # these are considered normal by the OS:
1990 # > python -c'import sys;sys.exit(0)'; echo $?
1986 # > python -c'import sys;sys.exit(0)'; echo $?
1991 # 0
1987 # 0
1992 # > python -c'import sys;sys.exit()'; echo $?
1988 # > python -c'import sys;sys.exit()'; echo $?
1993 # 0
1989 # 0
1994 # For other exit status, we show the exception unless
1990 # For other exit status, we show the exception unless
1995 # explicitly silenced, but only in short form.
1991 # explicitly silenced, but only in short form.
1996 if status.code not in (0, None) and not kw['exit_ignore']:
1992 if status.code not in (0, None) and not kw['exit_ignore']:
1997 self.showtraceback(exception_only=True)
1993 self.showtraceback(exception_only=True)
1998 except:
1994 except:
1999 self.showtraceback()
1995 self.showtraceback()
2000
1996
2001 def safe_execfile_ipy(self, fname):
1997 def safe_execfile_ipy(self, fname):
2002 """Like safe_execfile, but for .ipy files with IPython syntax.
1998 """Like safe_execfile, but for .ipy files with IPython syntax.
2003
1999
2004 Parameters
2000 Parameters
2005 ----------
2001 ----------
2006 fname : str
2002 fname : str
2007 The name of the file to execute. The filename must have a
2003 The name of the file to execute. The filename must have a
2008 .ipy extension.
2004 .ipy extension.
2009 """
2005 """
2010 fname = os.path.abspath(os.path.expanduser(fname))
2006 fname = os.path.abspath(os.path.expanduser(fname))
2011
2007
2012 # Make sure we have a .py file
2008 # Make sure we have a .py file
2013 if not fname.endswith('.ipy'):
2009 if not fname.endswith('.ipy'):
2014 warn('File must end with .py to be run using execfile: <%s>' % fname)
2010 warn('File must end with .py to be run using execfile: <%s>' % fname)
2015
2011
2016 # Make sure we can open the file
2012 # Make sure we can open the file
2017 try:
2013 try:
2018 with open(fname) as thefile:
2014 with open(fname) as thefile:
2019 pass
2015 pass
2020 except:
2016 except:
2021 warn('Could not open file <%s> for safe execution.' % fname)
2017 warn('Could not open file <%s> for safe execution.' % fname)
2022 return
2018 return
2023
2019
2024 # Find things also in current directory. This is needed to mimic the
2020 # Find things also in current directory. This is needed to mimic the
2025 # behavior of running a script from the system command line, where
2021 # behavior of running a script from the system command line, where
2026 # Python inserts the script's directory into sys.path
2022 # Python inserts the script's directory into sys.path
2027 dname = os.path.dirname(fname)
2023 dname = os.path.dirname(fname)
2028
2024
2029 with prepended_to_syspath(dname):
2025 with prepended_to_syspath(dname):
2030 try:
2026 try:
2031 with open(fname) as thefile:
2027 with open(fname) as thefile:
2032 script = thefile.read()
2028 script = thefile.read()
2033 # self.runlines currently captures all exceptions
2029 # self.runlines currently captures all exceptions
2034 # raise in user code. It would be nice if there were
2030 # raise in user code. It would be nice if there were
2035 # versions of runlines, execfile that did raise, so
2031 # versions of runlines, execfile that did raise, so
2036 # we could catch the errors.
2032 # we could catch the errors.
2037 self.runlines(script, clean=True)
2033 self.runlines(script, clean=True)
2038 except:
2034 except:
2039 self.showtraceback()
2035 self.showtraceback()
2040 warn('Unknown failure executing file: <%s>' % fname)
2036 warn('Unknown failure executing file: <%s>' % fname)
2041
2037
2042 def run_cell(self, cell):
2038 def run_cell(self, cell):
2043 """Run the contents of an entire multiline 'cell' of code.
2039 """Run the contents of an entire multiline 'cell' of code.
2044
2040
2045 The cell is split into separate blocks which can be executed
2041 The cell is split into separate blocks which can be executed
2046 individually. Then, based on how many blocks there are, they are
2042 individually. Then, based on how many blocks there are, they are
2047 executed as follows:
2043 executed as follows:
2048
2044
2049 - A single block: 'single' mode.
2045 - A single block: 'single' mode.
2050
2046
2051 If there's more than one block, it depends:
2047 If there's more than one block, it depends:
2052
2048
2053 - if the last one is no more than two lines long, run all but the last
2049 - if the last one is no more than two lines long, run all but the last
2054 in 'exec' mode and the very last one in 'single' mode. This makes it
2050 in 'exec' mode and the very last one in 'single' mode. This makes it
2055 easy to type simple expressions at the end to see computed values. -
2051 easy to type simple expressions at the end to see computed values. -
2056 otherwise (last one is also multiline), run all in 'exec' mode
2052 otherwise (last one is also multiline), run all in 'exec' mode
2057
2053
2058 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2054 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2059 results are displayed and output prompts are computed. In 'exec' mode,
2055 results are displayed and output prompts are computed. In 'exec' mode,
2060 no results are displayed unless :func:`print` is called explicitly;
2056 no results are displayed unless :func:`print` is called explicitly;
2061 this mode is more akin to running a script.
2057 this mode is more akin to running a script.
2062
2058
2063 Parameters
2059 Parameters
2064 ----------
2060 ----------
2065 cell : str
2061 cell : str
2066 A single or multiline string.
2062 A single or multiline string.
2067 """
2063 """
2068 #################################################################
2064 #################################################################
2069 # FIXME
2065 # FIXME
2070 # =====
2066 # =====
2071 # This execution logic should stop calling runlines altogether, and
2067 # This execution logic should stop calling runlines altogether, and
2072 # instead we should do what runlines does, in a controlled manner, here
2068 # instead we should do what runlines does, in a controlled manner, here
2073 # (runlines mutates lots of state as it goes calling sub-methods that
2069 # (runlines mutates lots of state as it goes calling sub-methods that
2074 # also mutate state). Basically we should:
2070 # also mutate state). Basically we should:
2075 # - apply dynamic transforms for single-line input (the ones that
2071 # - apply dynamic transforms for single-line input (the ones that
2076 # split_blocks won't apply since they need context).
2072 # split_blocks won't apply since they need context).
2077 # - increment the global execution counter (we need to pull that out
2073 # - increment the global execution counter (we need to pull that out
2078 # from outputcache's control; outputcache should instead read it from
2074 # from outputcache's control; outputcache should instead read it from
2079 # the main object).
2075 # the main object).
2080 # - do any logging of input
2076 # - do any logging of input
2081 # - update histories (raw/translated)
2077 # - update histories (raw/translated)
2082 # - then, call plain runsource (for single blocks, so displayhook is
2078 # - then, call plain runsource (for single blocks, so displayhook is
2083 # triggered) or runcode (for multiline blocks in exec mode).
2079 # triggered) or runcode (for multiline blocks in exec mode).
2084 #
2080 #
2085 # Once this is done, we'll be able to stop using runlines and we'll
2081 # Once this is done, we'll be able to stop using runlines and we'll
2086 # also have a much cleaner separation of logging, input history and
2082 # also have a much cleaner separation of logging, input history and
2087 # output cache management.
2083 # output cache management.
2088 #################################################################
2084 #################################################################
2089
2085
2090 # We need to break up the input into executable blocks that can be run
2086 # We need to break up the input into executable blocks that can be run
2091 # in 'single' mode, to provide comfortable user behavior.
2087 # in 'single' mode, to provide comfortable user behavior.
2092 blocks = self.input_splitter.split_blocks(cell)
2088 blocks = self.input_splitter.split_blocks(cell)
2093
2089
2094 if not blocks:
2090 if not blocks:
2095 return
2091 return
2096
2092
2097 # Store the 'ipython' version of the cell as well, since that's what
2093 # Store the 'ipython' version of the cell as well, since that's what
2098 # needs to go into the translated history and get executed (the
2094 # needs to go into the translated history and get executed (the
2099 # original cell may contain non-python syntax).
2095 # original cell may contain non-python syntax).
2100 ipy_cell = ''.join(blocks)
2096 ipy_cell = ''.join(blocks)
2101
2097
2102 # Each cell is a *single* input, regardless of how many lines it has
2098 # Each cell is a *single* input, regardless of how many lines it has
2103 self.execution_count += 1
2099 self.execution_count += 1
2104
2100
2105 # Store raw and processed history
2101 # Store raw and processed history
2106 self.input_hist_raw.append(cell)
2102 self.history_manager.store_inputs(ipy_cell, cell)
2107 self.input_hist.append(ipy_cell)
2108
2109
2103
2110 # dbg code!!!
2104 # dbg code!!!
2111 def myapp(self, val): # dbg
2105 def myapp(self, val): # dbg
2112 import traceback as tb
2106 import traceback as tb
2113 stack = ''.join(tb.format_stack())
2107 stack = ''.join(tb.format_stack())
2114 print 'Value:', val
2108 print 'Value:', val
2115 print 'Stack:\n', stack
2109 print 'Stack:\n', stack
2116 list.append(self, val)
2110 list.append(self, val)
2117
2111
2118 import new
2112 import new
2119 self.input_hist.append = new.instancemethod(myapp, self.input_hist,
2113 self.input_hist.append = new.instancemethod(myapp, self.input_hist,
2120 list)
2114 list)
2121 # End dbg
2115 # End dbg
2122
2116
2123 # All user code execution must happen with our context managers active
2117 # All user code execution must happen with our context managers active
2124 with nested(self.builtin_trap, self.display_trap):
2118 with nested(self.builtin_trap, self.display_trap):
2125 # Single-block input should behave like an interactive prompt
2119 # Single-block input should behave like an interactive prompt
2126 if len(blocks) == 1:
2120 if len(blocks) == 1:
2127 return self.run_one_block(blocks[0])
2121 return self.run_one_block(blocks[0])
2128
2122
2129 # In multi-block input, if the last block is a simple (one-two
2123 # In multi-block input, if the last block is a simple (one-two
2130 # lines) expression, run it in single mode so it produces output.
2124 # lines) expression, run it in single mode so it produces output.
2131 # Otherwise just feed the whole thing to runcode. This seems like
2125 # Otherwise just feed the whole thing to runcode. This seems like
2132 # a reasonable usability design.
2126 # a reasonable usability design.
2133 last = blocks[-1]
2127 last = blocks[-1]
2134 last_nlines = len(last.splitlines())
2128 last_nlines = len(last.splitlines())
2135
2129
2136 # Note: below, whenever we call runcode, we must sync history
2130 # Note: below, whenever we call runcode, we must sync history
2137 # ourselves, because runcode is NOT meant to manage history at all.
2131 # ourselves, because runcode is NOT meant to manage history at all.
2138 if last_nlines < 2:
2132 if last_nlines < 2:
2139 # Here we consider the cell split between 'body' and 'last',
2133 # Here we consider the cell split between 'body' and 'last',
2140 # store all history and execute 'body', and if successful, then
2134 # store all history and execute 'body', and if successful, then
2141 # proceed to execute 'last'.
2135 # proceed to execute 'last'.
2142
2136
2143 # Get the main body to run as a cell
2137 # Get the main body to run as a cell
2144 ipy_body = ''.join(blocks[:-1])
2138 ipy_body = ''.join(blocks[:-1])
2145 retcode = self.runcode(ipy_body, post_execute=False)
2139 retcode = self.runcode(ipy_body, post_execute=False)
2146 if retcode==0:
2140 if retcode==0:
2147 # And the last expression via runlines so it produces output
2141 # And the last expression via runlines so it produces output
2148 self.run_one_block(last)
2142 self.run_one_block(last)
2149 else:
2143 else:
2150 # Run the whole cell as one entity, storing both raw and
2144 # Run the whole cell as one entity, storing both raw and
2151 # processed input in history
2145 # processed input in history
2152 self.runcode(ipy_cell)
2146 self.runcode(ipy_cell)
2153
2147
2154 def run_one_block(self, block):
2148 def run_one_block(self, block):
2155 """Run a single interactive block.
2149 """Run a single interactive block.
2156
2150
2157 If the block is single-line, dynamic transformations are applied to it
2151 If the block is single-line, dynamic transformations are applied to it
2158 (like automagics, autocall and alias recognition).
2152 (like automagics, autocall and alias recognition).
2159 """
2153 """
2160 if len(block.splitlines()) <= 1:
2154 if len(block.splitlines()) <= 1:
2161 out = self.run_single_line(block)
2155 out = self.run_single_line(block)
2162 else:
2156 else:
2163 out = self.runcode(block)
2157 out = self.runcode(block)
2164 return out
2158 return out
2165
2159
2166 def run_single_line(self, line):
2160 def run_single_line(self, line):
2167 """Run a single-line interactive statement.
2161 """Run a single-line interactive statement.
2168
2162
2169 This assumes the input has been transformed to IPython syntax by
2163 This assumes the input has been transformed to IPython syntax by
2170 applying all static transformations (those with an explicit prefix like
2164 applying all static transformations (those with an explicit prefix like
2171 % or !), but it will further try to apply the dynamic ones.
2165 % or !), but it will further try to apply the dynamic ones.
2172
2166
2173 It does not update history.
2167 It does not update history.
2174 """
2168 """
2175 tline = self.prefilter_manager.prefilter_line(line)
2169 tline = self.prefilter_manager.prefilter_line(line)
2176 return self.runsource(tline)
2170 return self.runsource(tline)
2177
2171
2178 def runlines(self, lines, clean=False):
2172 def runlines(self, lines, clean=False):
2179 """Run a string of one or more lines of source.
2173 """Run a string of one or more lines of source.
2180
2174
2181 This method is capable of running a string containing multiple source
2175 This method is capable of running a string containing multiple source
2182 lines, as if they had been entered at the IPython prompt. Since it
2176 lines, as if they had been entered at the IPython prompt. Since it
2183 exposes IPython's processing machinery, the given strings can contain
2177 exposes IPython's processing machinery, the given strings can contain
2184 magic calls (%magic), special shell access (!cmd), etc.
2178 magic calls (%magic), special shell access (!cmd), etc.
2185 """
2179 """
2186
2180
2187 if isinstance(lines, (list, tuple)):
2181 if isinstance(lines, (list, tuple)):
2188 lines = '\n'.join(lines)
2182 lines = '\n'.join(lines)
2189
2183
2190 if clean:
2184 if clean:
2191 lines = self._cleanup_ipy_script(lines)
2185 lines = self._cleanup_ipy_script(lines)
2192
2186
2193 # We must start with a clean buffer, in case this is run from an
2187 # We must start with a clean buffer, in case this is run from an
2194 # interactive IPython session (via a magic, for example).
2188 # interactive IPython session (via a magic, for example).
2195 self.resetbuffer()
2189 self.resetbuffer()
2196 lines = lines.splitlines()
2190 lines = lines.splitlines()
2197 more = 0
2191
2192 # Since we will prefilter all lines, store the user's raw input too
2193 # before we apply any transformations
2194 self.buffer_raw[:] = [ l+'\n' for l in lines]
2195
2196 more = False
2197 prefilter_lines = self.prefilter_manager.prefilter_lines
2198 with nested(self.builtin_trap, self.display_trap):
2198 with nested(self.builtin_trap, self.display_trap):
2199 for line in lines:
2199 for line in lines:
2200 # skip blank lines so we don't mess up the prompt counter, but
2200 # 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
2201 # do NOT skip even a blank line if we are in a code block (more
2202 # is true)
2202 # is true)
2203
2203
2204 if line or more:
2204 if line or more:
2205 # push to raw history, so hist line numbers stay in sync
2205 more = self.push_line(prefilter_lines(line, more))
2206 self.input_hist_raw.append(line + '\n')
2207 prefiltered = self.prefilter_manager.prefilter_lines(line,
2208 more)
2209 more = self.push_line(prefiltered)
2210 # IPython's runsource returns None if there was an error
2206 # IPython's runsource returns None if there was an error
2211 # compiling the code. This allows us to stop processing
2207 # compiling the code. This allows us to stop processing
2212 # right away, so the user gets the error message at the
2208 # right away, so the user gets the error message at the
2213 # right place.
2209 # right place.
2214 if more is None:
2210 if more is None:
2215 break
2211 break
2216 else:
2217 self.input_hist_raw.append("\n")
2218 # final newline in case the input didn't have it, so that the code
2212 # final newline in case the input didn't have it, so that the code
2219 # actually does get executed
2213 # actually does get executed
2220 if more:
2214 if more:
2221 self.push_line('\n')
2215 self.push_line('\n')
2222
2216
2223 def runsource(self, source, filename='<input>', symbol='single'):
2217 def runsource(self, source, filename='<input>', symbol='single'):
2224 """Compile and run some source in the interpreter.
2218 """Compile and run some source in the interpreter.
2225
2219
2226 Arguments are as for compile_command().
2220 Arguments are as for compile_command().
2227
2221
2228 One several things can happen:
2222 One several things can happen:
2229
2223
2230 1) The input is incorrect; compile_command() raised an
2224 1) The input is incorrect; compile_command() raised an
2231 exception (SyntaxError or OverflowError). A syntax traceback
2225 exception (SyntaxError or OverflowError). A syntax traceback
2232 will be printed by calling the showsyntaxerror() method.
2226 will be printed by calling the showsyntaxerror() method.
2233
2227
2234 2) The input is incomplete, and more input is required;
2228 2) The input is incomplete, and more input is required;
2235 compile_command() returned None. Nothing happens.
2229 compile_command() returned None. Nothing happens.
2236
2230
2237 3) The input is complete; compile_command() returned a code
2231 3) The input is complete; compile_command() returned a code
2238 object. The code is executed by calling self.runcode() (which
2232 object. The code is executed by calling self.runcode() (which
2239 also handles run-time exceptions, except for SystemExit).
2233 also handles run-time exceptions, except for SystemExit).
2240
2234
2241 The return value is:
2235 The return value is:
2242
2236
2243 - True in case 2
2237 - True in case 2
2244
2238
2245 - False in the other cases, unless an exception is raised, where
2239 - False in the other cases, unless an exception is raised, where
2246 None is returned instead. This can be used by external callers to
2240 None is returned instead. This can be used by external callers to
2247 know whether to continue feeding input or not.
2241 know whether to continue feeding input or not.
2248
2242
2249 The return value can be used to decide whether to use sys.ps1 or
2243 The return value can be used to decide whether to use sys.ps1 or
2250 sys.ps2 to prompt the next line."""
2244 sys.ps2 to prompt the next line."""
2251
2245
2252 # We need to ensure that the source is unicode from here on.
2246 # We need to ensure that the source is unicode from here on.
2253 if type(source)==str:
2247 if type(source)==str:
2254 source = source.decode(self.stdin_encoding)
2248 source = source.decode(self.stdin_encoding)
2255
2249
2256 # if the source code has leading blanks, add 'if 1:\n' to it
2250 # if the source code has leading blanks, add 'if 1:\n' to it
2257 # this allows execution of indented pasted code. It is tempting
2251 # this allows execution of indented pasted code. It is tempting
2258 # to add '\n' at the end of source to run commands like ' a=1'
2252 # to add '\n' at the end of source to run commands like ' a=1'
2259 # directly, but this fails for more complicated scenarios
2253 # directly, but this fails for more complicated scenarios
2260
2254
2261 if source[:1] in [' ', '\t']:
2255 if source[:1] in [' ', '\t']:
2262 source = u'if 1:\n%s' % source
2256 source = u'if 1:\n%s' % source
2263
2257
2264 try:
2258 try:
2265 code = self.compile(source,filename,symbol)
2259 code = self.compile(source,filename,symbol)
2266 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2260 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2267 # Case 1
2261 # Case 1
2268 self.showsyntaxerror(filename)
2262 self.showsyntaxerror(filename)
2269 return None
2263 return None
2270
2264
2271 if code is None:
2265 if code is None:
2272 # Case 2
2266 # Case 2
2273 return True
2267 return True
2274
2268
2275 # Case 3
2269 # Case 3
2276 # We store the code object so that threaded shells and
2270 # We store the code object so that threaded shells and
2277 # custom exception handlers can access all this info if needed.
2271 # custom exception handlers can access all this info if needed.
2278 # The source corresponding to this can be obtained from the
2272 # The source corresponding to this can be obtained from the
2279 # buffer attribute as '\n'.join(self.buffer).
2273 # buffer attribute as '\n'.join(self.buffer).
2280 self.code_to_run = code
2274 self.code_to_run = code
2281 # now actually execute the code object
2275 # now actually execute the code object
2282 if self.runcode(code) == 0:
2276 if self.runcode(code) == 0:
2283 return False
2277 return False
2284 else:
2278 else:
2285 return None
2279 return None
2286
2280
2287 def runcode(self, code_obj, post_execute=True):
2281 def runcode(self, code_obj, post_execute=True):
2288 """Execute a code object.
2282 """Execute a code object.
2289
2283
2290 When an exception occurs, self.showtraceback() is called to display a
2284 When an exception occurs, self.showtraceback() is called to display a
2291 traceback.
2285 traceback.
2292
2286
2293 Return value: a flag indicating whether the code to be run completed
2287 Return value: a flag indicating whether the code to be run completed
2294 successfully:
2288 successfully:
2295
2289
2296 - 0: successful execution.
2290 - 0: successful execution.
2297 - 1: an error occurred.
2291 - 1: an error occurred.
2298 """
2292 """
2299
2293
2300 # Set our own excepthook in case the user code tries to call it
2294 # Set our own excepthook in case the user code tries to call it
2301 # directly, so that the IPython crash handler doesn't get triggered
2295 # directly, so that the IPython crash handler doesn't get triggered
2302 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2296 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2303
2297
2304 # we save the original sys.excepthook in the instance, in case config
2298 # we save the original sys.excepthook in the instance, in case config
2305 # code (such as magics) needs access to it.
2299 # code (such as magics) needs access to it.
2306 self.sys_excepthook = old_excepthook
2300 self.sys_excepthook = old_excepthook
2307 outflag = 1 # happens in more places, so it's easier as default
2301 outflag = 1 # happens in more places, so it's easier as default
2308 try:
2302 try:
2309 try:
2303 try:
2310 self.hooks.pre_runcode_hook()
2304 self.hooks.pre_runcode_hook()
2311 #rprint('Running code') # dbg
2305 #rprint('Running code') # dbg
2312 exec code_obj in self.user_global_ns, self.user_ns
2306 exec code_obj in self.user_global_ns, self.user_ns
2313 finally:
2307 finally:
2314 # Reset our crash handler in place
2308 # Reset our crash handler in place
2315 sys.excepthook = old_excepthook
2309 sys.excepthook = old_excepthook
2316 except SystemExit:
2310 except SystemExit:
2317 self.resetbuffer()
2311 self.resetbuffer()
2318 self.showtraceback(exception_only=True)
2312 self.showtraceback(exception_only=True)
2319 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2313 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2320 except self.custom_exceptions:
2314 except self.custom_exceptions:
2321 etype,value,tb = sys.exc_info()
2315 etype,value,tb = sys.exc_info()
2322 self.CustomTB(etype,value,tb)
2316 self.CustomTB(etype,value,tb)
2323 except:
2317 except:
2324 self.showtraceback()
2318 self.showtraceback()
2325 else:
2319 else:
2326 outflag = 0
2320 outflag = 0
2327 if softspace(sys.stdout, 0):
2321 if softspace(sys.stdout, 0):
2328 print
2322 print
2329
2323
2330 # Execute any registered post-execution functions. Here, any errors
2324 # Execute any registered post-execution functions. Here, any errors
2331 # are reported only minimally and just on the terminal, because the
2325 # are reported only minimally and just on the terminal, because the
2332 # main exception channel may be occupied with a user traceback.
2326 # main exception channel may be occupied with a user traceback.
2333 # FIXME: we need to think this mechanism a little more carefully.
2327 # FIXME: we need to think this mechanism a little more carefully.
2334 if post_execute:
2328 if post_execute:
2335 for func in self._post_execute:
2329 for func in self._post_execute:
2336 try:
2330 try:
2337 func()
2331 func()
2338 except:
2332 except:
2339 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2333 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2340 func
2334 func
2341 print >> io.Term.cout, head
2335 print >> io.Term.cout, head
2342 print >> io.Term.cout, self._simple_error()
2336 print >> io.Term.cout, self._simple_error()
2343 print >> io.Term.cout, 'Removing from post_execute'
2337 print >> io.Term.cout, 'Removing from post_execute'
2344 self._post_execute.remove(func)
2338 self._post_execute.remove(func)
2345
2339
2346 # Flush out code object which has been run (and source)
2340 # Flush out code object which has been run (and source)
2347 self.code_to_run = None
2341 self.code_to_run = None
2348 return outflag
2342 return outflag
2349
2343
2350 def push_line(self, line):
2344 def push_line(self, line):
2351 """Push a line to the interpreter.
2345 """Push a line to the interpreter.
2352
2346
2353 The line should not have a trailing newline; it may have
2347 The line should not have a trailing newline; it may have
2354 internal newlines. The line is appended to a buffer and the
2348 internal newlines. The line is appended to a buffer and the
2355 interpreter's runsource() method is called with the
2349 interpreter's runsource() method is called with the
2356 concatenated contents of the buffer as source. If this
2350 concatenated contents of the buffer as source. If this
2357 indicates that the command was executed or invalid, the buffer
2351 indicates that the command was executed or invalid, the buffer
2358 is reset; otherwise, the command is incomplete, and the buffer
2352 is reset; otherwise, the command is incomplete, and the buffer
2359 is left as it was after the line was appended. The return
2353 is left as it was after the line was appended. The return
2360 value is 1 if more input is required, 0 if the line was dealt
2354 value is 1 if more input is required, 0 if the line was dealt
2361 with in some way (this is the same as runsource()).
2355 with in some way (this is the same as runsource()).
2362 """
2356 """
2363
2357
2364 # autoindent management should be done here, and not in the
2358 # autoindent management should be done here, and not in the
2365 # interactive loop, since that one is only seen by keyboard input. We
2359 # interactive loop, since that one is only seen by keyboard input. We
2366 # need this done correctly even for code run via runlines (which uses
2360 # need this done correctly even for code run via runlines (which uses
2367 # push).
2361 # push).
2368
2362
2369 #print 'push line: <%s>' % line # dbg
2363 #print 'push line: <%s>' % line # dbg
2370 for subline in line.splitlines():
2364 for subline in line.splitlines():
2371 self._autoindent_update(subline)
2365 self._autoindent_update(subline)
2372 self.buffer.append(line)
2366 self.buffer.append(line)
2373 more = self.runsource('\n'.join(self.buffer), self.filename)
2367 full_source = '\n'.join(self.buffer)
2368 more = self.runsource(full_source, self.filename)
2374 if not more:
2369 if not more:
2370 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2371 full_source)
2375 self.resetbuffer()
2372 self.resetbuffer()
2376 self.execution_count += 1
2373 self.execution_count += 1
2377 return more
2374 return more
2378
2375
2379 def resetbuffer(self):
2376 def resetbuffer(self):
2380 """Reset the input buffer."""
2377 """Reset the input buffer."""
2381 self.buffer[:] = []
2378 self.buffer[:] = []
2379 self.buffer_raw[:] = []
2382
2380
2383 def _is_secondary_block_start(self, s):
2381 def _is_secondary_block_start(self, s):
2384 if not s.endswith(':'):
2382 if not s.endswith(':'):
2385 return False
2383 return False
2386 if (s.startswith('elif') or
2384 if (s.startswith('elif') or
2387 s.startswith('else') or
2385 s.startswith('else') or
2388 s.startswith('except') or
2386 s.startswith('except') or
2389 s.startswith('finally')):
2387 s.startswith('finally')):
2390 return True
2388 return True
2391
2389
2392 def _cleanup_ipy_script(self, script):
2390 def _cleanup_ipy_script(self, script):
2393 """Make a script safe for self.runlines()
2391 """Make a script safe for self.runlines()
2394
2392
2395 Currently, IPython is lines based, with blocks being detected by
2393 Currently, IPython is lines based, with blocks being detected by
2396 empty lines. This is a problem for block based scripts that may
2394 empty lines. This is a problem for block based scripts that may
2397 not have empty lines after blocks. This script adds those empty
2395 not have empty lines after blocks. This script adds those empty
2398 lines to make scripts safe for running in the current line based
2396 lines to make scripts safe for running in the current line based
2399 IPython.
2397 IPython.
2400 """
2398 """
2401 res = []
2399 res = []
2402 lines = script.splitlines()
2400 lines = script.splitlines()
2403 level = 0
2401 level = 0
2404
2402
2405 for l in lines:
2403 for l in lines:
2406 lstripped = l.lstrip()
2404 lstripped = l.lstrip()
2407 stripped = l.strip()
2405 stripped = l.strip()
2408 if not stripped:
2406 if not stripped:
2409 continue
2407 continue
2410 newlevel = len(l) - len(lstripped)
2408 newlevel = len(l) - len(lstripped)
2411 if level > 0 and newlevel == 0 and \
2409 if level > 0 and newlevel == 0 and \
2412 not self._is_secondary_block_start(stripped):
2410 not self._is_secondary_block_start(stripped):
2413 # add empty line
2411 # add empty line
2414 res.append('')
2412 res.append('')
2415 res.append(l)
2413 res.append(l)
2416 level = newlevel
2414 level = newlevel
2417
2415
2418 return '\n'.join(res) + '\n'
2416 return '\n'.join(res) + '\n'
2419
2417
2420 def _autoindent_update(self,line):
2418 def _autoindent_update(self,line):
2421 """Keep track of the indent level."""
2419 """Keep track of the indent level."""
2422
2420
2423 #debugx('line')
2421 #debugx('line')
2424 #debugx('self.indent_current_nsp')
2422 #debugx('self.indent_current_nsp')
2425 if self.autoindent:
2423 if self.autoindent:
2426 if line:
2424 if line:
2427 inisp = num_ini_spaces(line)
2425 inisp = num_ini_spaces(line)
2428 if inisp < self.indent_current_nsp:
2426 if inisp < self.indent_current_nsp:
2429 self.indent_current_nsp = inisp
2427 self.indent_current_nsp = inisp
2430
2428
2431 if line[-1] == ':':
2429 if line[-1] == ':':
2432 self.indent_current_nsp += 4
2430 self.indent_current_nsp += 4
2433 elif dedent_re.match(line):
2431 elif dedent_re.match(line):
2434 self.indent_current_nsp -= 4
2432 self.indent_current_nsp -= 4
2435 else:
2433 else:
2436 self.indent_current_nsp = 0
2434 self.indent_current_nsp = 0
2437
2435
2438 #-------------------------------------------------------------------------
2436 #-------------------------------------------------------------------------
2439 # Things related to GUI support and pylab
2437 # Things related to GUI support and pylab
2440 #-------------------------------------------------------------------------
2438 #-------------------------------------------------------------------------
2441
2439
2442 def enable_pylab(self, gui=None):
2440 def enable_pylab(self, gui=None):
2443 raise NotImplementedError('Implement enable_pylab in a subclass')
2441 raise NotImplementedError('Implement enable_pylab in a subclass')
2444
2442
2445 #-------------------------------------------------------------------------
2443 #-------------------------------------------------------------------------
2446 # Utilities
2444 # Utilities
2447 #-------------------------------------------------------------------------
2445 #-------------------------------------------------------------------------
2448
2446
2449 def var_expand(self,cmd,depth=0):
2447 def var_expand(self,cmd,depth=0):
2450 """Expand python variables in a string.
2448 """Expand python variables in a string.
2451
2449
2452 The depth argument indicates how many frames above the caller should
2450 The depth argument indicates how many frames above the caller should
2453 be walked to look for the local namespace where to expand variables.
2451 be walked to look for the local namespace where to expand variables.
2454
2452
2455 The global namespace for expansion is always the user's interactive
2453 The global namespace for expansion is always the user's interactive
2456 namespace.
2454 namespace.
2457 """
2455 """
2458
2456
2459 return str(ItplNS(cmd,
2457 return str(ItplNS(cmd,
2460 self.user_ns, # globals
2458 self.user_ns, # globals
2461 # Skip our own frame in searching for locals:
2459 # Skip our own frame in searching for locals:
2462 sys._getframe(depth+1).f_locals # locals
2460 sys._getframe(depth+1).f_locals # locals
2463 ))
2461 ))
2464
2462
2465 def mktempfile(self,data=None):
2463 def mktempfile(self,data=None):
2466 """Make a new tempfile and return its filename.
2464 """Make a new tempfile and return its filename.
2467
2465
2468 This makes a call to tempfile.mktemp, but it registers the created
2466 This makes a call to tempfile.mktemp, but it registers the created
2469 filename internally so ipython cleans it up at exit time.
2467 filename internally so ipython cleans it up at exit time.
2470
2468
2471 Optional inputs:
2469 Optional inputs:
2472
2470
2473 - data(None): if data is given, it gets written out to the temp file
2471 - data(None): if data is given, it gets written out to the temp file
2474 immediately, and the file is closed again."""
2472 immediately, and the file is closed again."""
2475
2473
2476 filename = tempfile.mktemp('.py','ipython_edit_')
2474 filename = tempfile.mktemp('.py','ipython_edit_')
2477 self.tempfiles.append(filename)
2475 self.tempfiles.append(filename)
2478
2476
2479 if data:
2477 if data:
2480 tmp_file = open(filename,'w')
2478 tmp_file = open(filename,'w')
2481 tmp_file.write(data)
2479 tmp_file.write(data)
2482 tmp_file.close()
2480 tmp_file.close()
2483 return filename
2481 return filename
2484
2482
2485 # TODO: This should be removed when Term is refactored.
2483 # TODO: This should be removed when Term is refactored.
2486 def write(self,data):
2484 def write(self,data):
2487 """Write a string to the default output"""
2485 """Write a string to the default output"""
2488 io.Term.cout.write(data)
2486 io.Term.cout.write(data)
2489
2487
2490 # TODO: This should be removed when Term is refactored.
2488 # TODO: This should be removed when Term is refactored.
2491 def write_err(self,data):
2489 def write_err(self,data):
2492 """Write a string to the default error output"""
2490 """Write a string to the default error output"""
2493 io.Term.cerr.write(data)
2491 io.Term.cerr.write(data)
2494
2492
2495 def ask_yes_no(self,prompt,default=True):
2493 def ask_yes_no(self,prompt,default=True):
2496 if self.quiet:
2494 if self.quiet:
2497 return True
2495 return True
2498 return ask_yes_no(prompt,default)
2496 return ask_yes_no(prompt,default)
2499
2497
2500 def show_usage(self):
2498 def show_usage(self):
2501 """Show a usage message"""
2499 """Show a usage message"""
2502 page.page(IPython.core.usage.interactive_usage)
2500 page.page(IPython.core.usage.interactive_usage)
2503
2501
2504 #-------------------------------------------------------------------------
2502 #-------------------------------------------------------------------------
2505 # Things related to IPython exiting
2503 # Things related to IPython exiting
2506 #-------------------------------------------------------------------------
2504 #-------------------------------------------------------------------------
2507 def atexit_operations(self):
2505 def atexit_operations(self):
2508 """This will be executed at the time of exit.
2506 """This will be executed at the time of exit.
2509
2507
2510 Cleanup operations and saving of persistent data that is done
2508 Cleanup operations and saving of persistent data that is done
2511 unconditionally by IPython should be performed here.
2509 unconditionally by IPython should be performed here.
2512
2510
2513 For things that may depend on startup flags or platform specifics (such
2511 For things that may depend on startup flags or platform specifics (such
2514 as having readline or not), register a separate atexit function in the
2512 as having readline or not), register a separate atexit function in the
2515 code that has the appropriate information, rather than trying to
2513 code that has the appropriate information, rather than trying to
2516 clutter
2514 clutter
2517 """
2515 """
2518 # Cleanup all tempfiles left around
2516 # Cleanup all tempfiles left around
2519 for tfile in self.tempfiles:
2517 for tfile in self.tempfiles:
2520 try:
2518 try:
2521 os.unlink(tfile)
2519 os.unlink(tfile)
2522 except OSError:
2520 except OSError:
2523 pass
2521 pass
2524
2522
2525 # Clear all user namespaces to release all references cleanly.
2523 # Clear all user namespaces to release all references cleanly.
2526 self.reset()
2524 self.reset()
2527
2525
2528 # Run user hooks
2526 # Run user hooks
2529 self.hooks.shutdown_hook()
2527 self.hooks.shutdown_hook()
2530
2528
2531 def cleanup(self):
2529 def cleanup(self):
2532 self.restore_sys_module_state()
2530 self.restore_sys_module_state()
2533
2531
2534
2532
2535 class InteractiveShellABC(object):
2533 class InteractiveShellABC(object):
2536 """An abstract base class for InteractiveShell."""
2534 """An abstract base class for InteractiveShell."""
2537 __metaclass__ = abc.ABCMeta
2535 __metaclass__ = abc.ABCMeta
2538
2536
2539 InteractiveShellABC.register(InteractiveShell)
2537 InteractiveShellABC.register(InteractiveShell)
@@ -1,265 +1,266 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Logger class for IPython's logging facilities.
3 Logger class for IPython's logging facilities.
4 """
4 """
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 # Python standard modules
17 # Python standard modules
18 import glob
18 import glob
19 import os
19 import os
20 import time
20 import time
21
21
22 #****************************************************************************
22 #****************************************************************************
23 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
23 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
24 # ipython and does input cache management. Finish cleanup later...
24 # ipython and does input cache management. Finish cleanup later...
25
25
26 class Logger(object):
26 class Logger(object):
27 """A Logfile class with different policies for file creation"""
27 """A Logfile class with different policies for file creation"""
28
28
29 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
29 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
30
30
31 self._i00,self._i,self._ii,self._iii = '','','',''
31 self._i00,self._i,self._ii,self._iii = '','','',''
32
32
33 # this is the full ipython instance, we need some attributes from it
33 # this is the full ipython instance, we need some attributes from it
34 # which won't exist until later. What a mess, clean up later...
34 # which won't exist until later. What a mess, clean up later...
35 self.shell = shell
35 self.shell = shell
36
36
37 self.logfname = logfname
37 self.logfname = logfname
38 self.loghead = loghead
38 self.loghead = loghead
39 self.logmode = logmode
39 self.logmode = logmode
40 self.logfile = None
40 self.logfile = None
41
41
42 # Whether to log raw or processed input
42 # Whether to log raw or processed input
43 self.log_raw_input = False
43 self.log_raw_input = False
44
44
45 # whether to also log output
45 # whether to also log output
46 self.log_output = False
46 self.log_output = False
47
47
48 # whether to put timestamps before each log entry
48 # whether to put timestamps before each log entry
49 self.timestamp = False
49 self.timestamp = False
50
50
51 # activity control flags
51 # activity control flags
52 self.log_active = False
52 self.log_active = False
53
53
54 # logmode is a validated property
54 # logmode is a validated property
55 def _set_mode(self,mode):
55 def _set_mode(self,mode):
56 if mode not in ['append','backup','global','over','rotate']:
56 if mode not in ['append','backup','global','over','rotate']:
57 raise ValueError,'invalid log mode %s given' % mode
57 raise ValueError,'invalid log mode %s given' % mode
58 self._logmode = mode
58 self._logmode = mode
59
59
60 def _get_mode(self):
60 def _get_mode(self):
61 return self._logmode
61 return self._logmode
62
62
63 logmode = property(_get_mode,_set_mode)
63 logmode = property(_get_mode,_set_mode)
64
64
65 def logstart(self,logfname=None,loghead=None,logmode=None,
65 def logstart(self,logfname=None,loghead=None,logmode=None,
66 log_output=False,timestamp=False,log_raw_input=False):
66 log_output=False,timestamp=False,log_raw_input=False):
67 """Generate a new log-file with a default header.
67 """Generate a new log-file with a default header.
68
68
69 Raises RuntimeError if the log has already been started"""
69 Raises RuntimeError if the log has already been started"""
70
70
71 if self.logfile is not None:
71 if self.logfile is not None:
72 raise RuntimeError('Log file is already active: %s' %
72 raise RuntimeError('Log file is already active: %s' %
73 self.logfname)
73 self.logfname)
74
74
75 self.log_active = True
75 self.log_active = True
76
76
77 # The parameters can override constructor defaults
77 # The parameters can override constructor defaults
78 if logfname is not None: self.logfname = logfname
78 if logfname is not None: self.logfname = logfname
79 if loghead is not None: self.loghead = loghead
79 if loghead is not None: self.loghead = loghead
80 if logmode is not None: self.logmode = logmode
80 if logmode is not None: self.logmode = logmode
81
81
82 # Parameters not part of the constructor
82 # Parameters not part of the constructor
83 self.timestamp = timestamp
83 self.timestamp = timestamp
84 self.log_output = log_output
84 self.log_output = log_output
85 self.log_raw_input = log_raw_input
85 self.log_raw_input = log_raw_input
86
86
87 # init depending on the log mode requested
87 # init depending on the log mode requested
88 isfile = os.path.isfile
88 isfile = os.path.isfile
89 logmode = self.logmode
89 logmode = self.logmode
90
90
91 if logmode == 'append':
91 if logmode == 'append':
92 self.logfile = open(self.logfname,'a')
92 self.logfile = open(self.logfname,'a')
93
93
94 elif logmode == 'backup':
94 elif logmode == 'backup':
95 if isfile(self.logfname):
95 if isfile(self.logfname):
96 backup_logname = self.logfname+'~'
96 backup_logname = self.logfname+'~'
97 # Manually remove any old backup, since os.rename may fail
97 # Manually remove any old backup, since os.rename may fail
98 # under Windows.
98 # under Windows.
99 if isfile(backup_logname):
99 if isfile(backup_logname):
100 os.remove(backup_logname)
100 os.remove(backup_logname)
101 os.rename(self.logfname,backup_logname)
101 os.rename(self.logfname,backup_logname)
102 self.logfile = open(self.logfname,'w')
102 self.logfile = open(self.logfname,'w')
103
103
104 elif logmode == 'global':
104 elif logmode == 'global':
105 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
105 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
106 self.logfile = open(self.logfname, 'a')
106 self.logfile = open(self.logfname, 'a')
107
107
108 elif logmode == 'over':
108 elif logmode == 'over':
109 if isfile(self.logfname):
109 if isfile(self.logfname):
110 os.remove(self.logfname)
110 os.remove(self.logfname)
111 self.logfile = open(self.logfname,'w')
111 self.logfile = open(self.logfname,'w')
112
112
113 elif logmode == 'rotate':
113 elif logmode == 'rotate':
114 if isfile(self.logfname):
114 if isfile(self.logfname):
115 if isfile(self.logfname+'.001~'):
115 if isfile(self.logfname+'.001~'):
116 old = glob.glob(self.logfname+'.*~')
116 old = glob.glob(self.logfname+'.*~')
117 old.sort()
117 old.sort()
118 old.reverse()
118 old.reverse()
119 for f in old:
119 for f in old:
120 root, ext = os.path.splitext(f)
120 root, ext = os.path.splitext(f)
121 num = int(ext[1:-1])+1
121 num = int(ext[1:-1])+1
122 os.rename(f, root+'.'+`num`.zfill(3)+'~')
122 os.rename(f, root+'.'+`num`.zfill(3)+'~')
123 os.rename(self.logfname, self.logfname+'.001~')
123 os.rename(self.logfname, self.logfname+'.001~')
124 self.logfile = open(self.logfname,'w')
124 self.logfile = open(self.logfname,'w')
125
125
126 if logmode != 'append':
126 if logmode != 'append':
127 self.logfile.write(self.loghead)
127 self.logfile.write(self.loghead)
128
128
129 self.logfile.flush()
129 self.logfile.flush()
130
130
131 def switch_log(self,val):
131 def switch_log(self,val):
132 """Switch logging on/off. val should be ONLY a boolean."""
132 """Switch logging on/off. val should be ONLY a boolean."""
133
133
134 if val not in [False,True,0,1]:
134 if val not in [False,True,0,1]:
135 raise ValueError, \
135 raise ValueError, \
136 'Call switch_log ONLY with a boolean argument, not with:',val
136 'Call switch_log ONLY with a boolean argument, not with:',val
137
137
138 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
139
139
140 if self.logfile is None:
140 if self.logfile is None:
141 print """
141 print """
142 Logging hasn't been started yet (use logstart for that).
142 Logging hasn't been started yet (use logstart for that).
143
143
144 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 %logon/%logoff are for temporarily starting and stopping logging for a logfile
145 which already exists. But you must first start the logging process with
145 which already exists. But you must first start the logging process with
146 %logstart (optionally giving a logfile name)."""
146 %logstart (optionally giving a logfile name)."""
147
147
148 else:
148 else:
149 if self.log_active == val:
149 if self.log_active == val:
150 print 'Logging is already',label[val]
150 print 'Logging is already',label[val]
151 else:
151 else:
152 print 'Switching logging',label[val]
152 print 'Switching logging',label[val]
153 self.log_active = not self.log_active
153 self.log_active = not self.log_active
154 self.log_active_out = self.log_active
154 self.log_active_out = self.log_active
155
155
156 def logstate(self):
156 def logstate(self):
157 """Print a status message about the logger."""
157 """Print a status message about the logger."""
158 if self.logfile is None:
158 if self.logfile is None:
159 print 'Logging has not been activated.'
159 print 'Logging has not been activated.'
160 else:
160 else:
161 state = self.log_active and 'active' or 'temporarily suspended'
161 state = self.log_active and 'active' or 'temporarily suspended'
162 print 'Filename :',self.logfname
162 print 'Filename :',self.logfname
163 print 'Mode :',self.logmode
163 print 'Mode :',self.logmode
164 print 'Output logging :',self.log_output
164 print 'Output logging :',self.log_output
165 print 'Raw input log :',self.log_raw_input
165 print 'Raw input log :',self.log_raw_input
166 print 'Timestamping :',self.timestamp
166 print 'Timestamping :',self.timestamp
167 print 'State :',state
167 print 'State :',state
168
168
169 def log(self,line_ori,line_mod,continuation=None):
169 def log(self,line_ori,line_mod,continuation=None):
170 """Write the line to a log and create input cache variables _i*.
170 """Write the line to a log and create input cache variables _i*.
171
171
172 Inputs:
172 Inputs:
173
173
174 - line_ori: unmodified input line from the user. This is not
174 - line_ori: unmodified input line from the user. This is not
175 necessarily valid Python.
175 necessarily valid Python.
176
176
177 - line_mod: possibly modified input, such as the transformations made
177 - line_mod: possibly modified input, such as the transformations made
178 by input prefilters or input handlers of various kinds. This should
178 by input prefilters or input handlers of various kinds. This should
179 always be valid Python.
179 always be valid Python.
180
180
181 - continuation: if True, indicates this is part of multi-line input."""
181 - continuation: if True, indicates this is part of multi-line input."""
182
182
183 # update the auto _i tables
183 # update the auto _i tables
184 #print '***logging line',line_mod # dbg
184 #print '***logging line',line_mod # dbg
185 #print '***cache_count', self.shell.displayhook.prompt_count # dbg
185 #print '***cache_count', self.shell.displayhook.prompt_count # dbg
186 try:
186 try:
187 input_hist = self.shell.user_ns['_ih']
187 input_hist = self.shell.user_ns['_ih']
188 except:
188 except:
189 #print 'userns:',self.shell.user_ns.keys() # dbg
189 #print 'userns:',self.shell.user_ns.keys() # dbg
190 return
190 return
191
191
192 out_cache = self.shell.displayhook
192 out_cache = self.shell.displayhook
193
193
194 # add blank lines if the input cache fell out of sync.
194 # add blank lines if the input cache fell out of sync.
195 if out_cache.do_full_cache and \
195 if out_cache.do_full_cache and \
196 out_cache.prompt_count +1 > len(input_hist):
196 out_cache.prompt_count +1 > len(input_hist):
197 input_hist.extend(['\n'] * (out_cache.prompt_count - len(input_hist)))
197 pass
198 #input_hist.extend(['\n'] * (out_cache.prompt_count - len(input_hist)))
198
199
199 if not continuation and line_mod:
200 if not continuation and line_mod:
200 self._iii = self._ii
201 self._iii = self._ii
201 self._ii = self._i
202 self._ii = self._i
202 self._i = self._i00
203 self._i = self._i00
203 # put back the final \n of every input line
204 # put back the final \n of every input line
204 self._i00 = line_mod+'\n'
205 self._i00 = line_mod+'\n'
205 #print 'Logging input:<%s>' % line_mod # dbg
206 #print 'Logging input:<%s>' % line_mod # dbg
206 input_hist.append(self._i00)
207 #input_hist.append(self._i00)
207 #print '---[%s]' % (len(input_hist)-1,) # dbg
208 #print '---[%s]' % (len(input_hist)-1,) # dbg
208
209
209 # hackish access to top-level namespace to create _i1,_i2... dynamically
210 # hackish access to top-level namespace to create _i1,_i2... dynamically
210 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
211 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
211 if self.shell.displayhook.do_full_cache:
212 if self.shell.displayhook.do_full_cache:
212 in_num = self.shell.displayhook.prompt_count
213 in_num = self.shell.displayhook.prompt_count
213
214
214 # but if the opposite is true (a macro can produce multiple inputs
215 # but if the opposite is true (a macro can produce multiple inputs
215 # with no output display called), then bring the output counter in
216 # with no output display called), then bring the output counter in
216 # sync:
217 # sync:
217 ## last_num = len(input_hist)-1
218 ## last_num = len(input_hist)-1
218 ## if in_num != last_num:
219 ## if in_num != last_num:
219 ## pass # dbg
220 ## pass # dbg
220 ## #in_num = self.shell.execution_count = last_num
221 ## #in_num = self.shell.execution_count = last_num
221
222
222 new_i = '_i%s' % in_num
223 new_i = '_i%s' % in_num
223 if continuation:
224 if continuation:
224 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod)
225 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod)
225 input_hist[in_num] = self._i00
226 #input_hist[in_num] = self._i00
226 to_main[new_i] = self._i00
227 to_main[new_i] = self._i00
227 self.shell.user_ns.update(to_main)
228 self.shell.user_ns.update(to_main)
228
229
229 # Write the log line, but decide which one according to the
230 # Write the log line, but decide which one according to the
230 # log_raw_input flag, set when the log is started.
231 # log_raw_input flag, set when the log is started.
231 if self.log_raw_input:
232 if self.log_raw_input:
232 self.log_write(line_ori)
233 self.log_write(line_ori)
233 else:
234 else:
234 self.log_write(line_mod)
235 self.log_write(line_mod)
235
236
236 def log_write(self,data,kind='input'):
237 def log_write(self,data,kind='input'):
237 """Write data to the log file, if active"""
238 """Write data to the log file, if active"""
238
239
239 #print 'data: %r' % data # dbg
240 #print 'data: %r' % data # dbg
240 if self.log_active and data:
241 if self.log_active and data:
241 write = self.logfile.write
242 write = self.logfile.write
242 if kind=='input':
243 if kind=='input':
243 if self.timestamp:
244 if self.timestamp:
244 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
245 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
245 time.localtime()))
246 time.localtime()))
246 write('%s\n' % data)
247 write('%s\n' % data)
247 elif kind=='output' and self.log_output:
248 elif kind=='output' and self.log_output:
248 odata = '\n'.join(['#[Out]# %s' % s
249 odata = '\n'.join(['#[Out]# %s' % s
249 for s in data.split('\n')])
250 for s in data.split('\n')])
250 write('%s\n' % odata)
251 write('%s\n' % odata)
251 self.logfile.flush()
252 self.logfile.flush()
252
253
253 def logstop(self):
254 def logstop(self):
254 """Fully stop logging and close log file.
255 """Fully stop logging and close log file.
255
256
256 In order to start logging again, a new logstart() call needs to be
257 In order to start logging again, a new logstart() call needs to be
257 made, possibly (though not necessarily) with a new filename, mode and
258 made, possibly (though not necessarily) with a new filename, mode and
258 other options."""
259 other options."""
259
260
260 self.logfile.close()
261 self.logfile.close()
261 self.logfile = None
262 self.logfile = None
262 self.log_active = False
263 self.log_active = False
263
264
264 # For backwards compatibility, in case anyone was using this.
265 # For backwards compatibility, in case anyone was using this.
265 close_log = logstop
266 close_log = logstop
@@ -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').split('\n')
431 llines = lines.rstrip('\n').splitlines()
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,658 +1,667 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 isp.push('if 1:')
165 isp.push('if 1:')
166 self.assertEqual(isp.indent_spaces, 4)
166 self.assertEqual(isp.indent_spaces, 4)
167 isp.push(' x=1')
167 isp.push(' x=1')
168 self.assertEqual(isp.indent_spaces, 4)
168 self.assertEqual(isp.indent_spaces, 4)
169 # Blank lines shouldn't change the indent level
169 # Blank lines shouldn't change the indent level
170 isp.push(' '*2)
170 isp.push(' '*2)
171 self.assertEqual(isp.indent_spaces, 4)
171 self.assertEqual(isp.indent_spaces, 4)
172
172
173 def test_indent2(self):
173 def test_indent2(self):
174 isp = self.isp
174 isp = self.isp
175 # When a multiline statement contains parens or multiline strings, we
175 # When a multiline statement contains parens or multiline strings, we
176 # shouldn't get confused.
176 # shouldn't get confused.
177 isp.push("if 1:")
177 isp.push("if 1:")
178 isp.push(" x = (1+\n 2)")
178 isp.push(" x = (1+\n 2)")
179 self.assertEqual(isp.indent_spaces, 4)
179 self.assertEqual(isp.indent_spaces, 4)
180
180
181 def test_dedent(self):
181 def test_dedent(self):
182 isp = self.isp # shorthand
182 isp = self.isp # shorthand
183 isp.push('if 1:')
183 isp.push('if 1:')
184 self.assertEqual(isp.indent_spaces, 4)
184 self.assertEqual(isp.indent_spaces, 4)
185 isp.push(' pass')
185 isp.push(' pass')
186 self.assertEqual(isp.indent_spaces, 0)
186 self.assertEqual(isp.indent_spaces, 0)
187
187
188 def test_push(self):
188 def test_push(self):
189 isp = self.isp
189 isp = self.isp
190 self.assertTrue(isp.push('x=1'))
190 self.assertTrue(isp.push('x=1'))
191
191
192 def test_push2(self):
192 def test_push2(self):
193 isp = self.isp
193 isp = self.isp
194 self.assertFalse(isp.push('if 1:'))
194 self.assertFalse(isp.push('if 1:'))
195 for line in [' x=1', '# a comment', ' y=2']:
195 for line in [' x=1', '# a comment', ' y=2']:
196 self.assertTrue(isp.push(line))
196 self.assertTrue(isp.push(line))
197
197
198 def test_push3(self):
198 def test_push3(self):
199 """Test input with leading whitespace"""
199 """Test input with leading whitespace"""
200 isp = self.isp
200 isp = self.isp
201 isp.push(' x=1')
201 isp.push(' x=1')
202 isp.push(' y=2')
202 isp.push(' y=2')
203 self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n')
203 self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n')
204
204
205 def test_replace_mode(self):
205 def test_replace_mode(self):
206 isp = self.isp
206 isp = self.isp
207 isp.input_mode = 'cell'
207 isp.input_mode = 'cell'
208 isp.push('x=1')
208 isp.push('x=1')
209 self.assertEqual(isp.source, 'x=1\n')
209 self.assertEqual(isp.source, 'x=1\n')
210 isp.push('x=2')
210 isp.push('x=2')
211 self.assertEqual(isp.source, 'x=2\n')
211 self.assertEqual(isp.source, 'x=2\n')
212
212
213 def test_push_accepts_more(self):
213 def test_push_accepts_more(self):
214 isp = self.isp
214 isp = self.isp
215 isp.push('x=1')
215 isp.push('x=1')
216 self.assertFalse(isp.push_accepts_more())
216 self.assertFalse(isp.push_accepts_more())
217
217
218 def test_push_accepts_more2(self):
218 def test_push_accepts_more2(self):
219 isp = self.isp
219 isp = self.isp
220 isp.push('if 1:')
220 isp.push('if 1:')
221 self.assertTrue(isp.push_accepts_more())
221 self.assertTrue(isp.push_accepts_more())
222 isp.push(' x=1')
222 isp.push(' x=1')
223 self.assertTrue(isp.push_accepts_more())
223 self.assertTrue(isp.push_accepts_more())
224 isp.push('')
224 isp.push('')
225 self.assertFalse(isp.push_accepts_more())
225 self.assertFalse(isp.push_accepts_more())
226
226
227 def test_push_accepts_more3(self):
227 def test_push_accepts_more3(self):
228 isp = self.isp
228 isp = self.isp
229 isp.push("x = (2+\n3)")
229 isp.push("x = (2+\n3)")
230 self.assertFalse(isp.push_accepts_more())
230 self.assertFalse(isp.push_accepts_more())
231
231
232 def test_push_accepts_more4(self):
232 def test_push_accepts_more4(self):
233 isp = self.isp
233 isp = self.isp
234 # When a multiline statement contains parens or multiline strings, we
234 # When a multiline statement contains parens or multiline strings, we
235 # shouldn't get confused.
235 # shouldn't get confused.
236 # FIXME: we should be able to better handle de-dents in statements like
236 # FIXME: we should be able to better handle de-dents in statements like
237 # multiline strings and multiline expressions (continued with \ or
237 # multiline strings and multiline expressions (continued with \ or
238 # parens). Right now we aren't handling the indentation tracking quite
238 # 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
239 # correctly with this, though in practice it may not be too much of a
240 # problem. We'll need to see.
240 # problem. We'll need to see.
241 isp.push("if 1:")
241 isp.push("if 1:")
242 isp.push(" x = (2+")
242 isp.push(" x = (2+")
243 isp.push(" 3)")
243 isp.push(" 3)")
244 self.assertTrue(isp.push_accepts_more())
244 self.assertTrue(isp.push_accepts_more())
245 isp.push(" y = 3")
245 isp.push(" y = 3")
246 self.assertTrue(isp.push_accepts_more())
246 self.assertTrue(isp.push_accepts_more())
247 isp.push('')
247 isp.push('')
248 self.assertFalse(isp.push_accepts_more())
248 self.assertFalse(isp.push_accepts_more())
249
249
250 def test_continuation(self):
250 def test_continuation(self):
251 isp = self.isp
251 isp = self.isp
252 isp.push("import os, \\")
252 isp.push("import os, \\")
253 self.assertTrue(isp.push_accepts_more())
253 self.assertTrue(isp.push_accepts_more())
254 isp.push("sys")
254 isp.push("sys")
255 self.assertFalse(isp.push_accepts_more())
255 self.assertFalse(isp.push_accepts_more())
256
256
257 def test_syntax_error(self):
257 def test_syntax_error(self):
258 isp = self.isp
258 isp = self.isp
259 # Syntax errors immediately produce a 'ready' block, so the invalid
259 # Syntax errors immediately produce a 'ready' block, so the invalid
260 # Python can be sent to the kernel for evaluation with possible ipython
260 # Python can be sent to the kernel for evaluation with possible ipython
261 # special-syntax conversion.
261 # special-syntax conversion.
262 isp.push('run foo')
262 isp.push('run foo')
263 self.assertFalse(isp.push_accepts_more())
263 self.assertFalse(isp.push_accepts_more())
264
264
265 def check_split(self, block_lines, compile=True):
265 def check_split(self, block_lines, compile=True):
266 blocks = assemble(block_lines)
266 blocks = assemble(block_lines)
267 lines = ''.join(blocks)
267 lines = ''.join(blocks)
268 oblock = self.isp.split_blocks(lines)
268 oblock = self.isp.split_blocks(lines)
269 self.assertEqual(oblock, blocks)
269 self.assertEqual(oblock, blocks)
270 if compile:
270 if compile:
271 for block in blocks:
271 for block in blocks:
272 self.isp._compile(block)
272 self.isp._compile(block)
273
273
274 def test_split(self):
274 def test_split(self):
275 # All blocks of input we want to test in a list. The format for each
275 # 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
276 # 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.
277 # lines (as single-lines) that should make up a sub-block.
278
278
279 # Note: do NOT put here sub-blocks that don't compile, as the
279 # 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
280 # check_split() routine makes a final verification pass to check that
281 # each sub_block, as returned by split_blocks(), does compile
281 # each sub_block, as returned by split_blocks(), does compile
282 # correctly.
282 # correctly.
283 all_blocks = [ [['x=1']],
283 all_blocks = [ [['x=1']],
284
284
285 [['x=1'],
285 [['x=1'],
286 ['y=2']],
286 ['y=2']],
287
287
288 [['x=1',
288 [['x=1',
289 '# a comment'],
289 '# a comment'],
290 ['y=11']],
290 ['y=11']],
291
291
292 [['if 1:',
292 [['if 1:',
293 ' x=1'],
293 ' x=1'],
294 ['y=3']],
294 ['y=3']],
295
295
296 [['def f(x):',
296 [['def f(x):',
297 ' return x'],
297 ' return x'],
298 ['x=1']],
298 ['x=1']],
299
299
300 [['def f(x):',
300 [['def f(x):',
301 ' x+=1',
301 ' x+=1',
302 ' ',
302 ' ',
303 ' return x'],
303 ' return x'],
304 ['x=1']],
304 ['x=1']],
305
305
306 [['def f(x):',
306 [['def f(x):',
307 ' if x>0:',
307 ' if x>0:',
308 ' y=1',
308 ' y=1',
309 ' # a comment',
309 ' # a comment',
310 ' else:',
310 ' else:',
311 ' y=4',
311 ' y=4',
312 ' ',
312 ' ',
313 ' return y'],
313 ' return y'],
314 ['x=1'],
314 ['x=1'],
315 ['if 1:',
315 ['if 1:',
316 ' y=11'] ],
316 ' y=11'] ],
317
317
318 [['for i in range(10):'
318 [['for i in range(10):'
319 ' x=i**2']],
319 ' x=i**2']],
320
320
321 [['for i in range(10):'
321 [['for i in range(10):'
322 ' x=i**2'],
322 ' x=i**2'],
323 ['z = 1']],
323 ['z = 1']],
324 ]
324 ]
325 for block_lines in all_blocks:
325 for block_lines in all_blocks:
326 self.check_split(block_lines)
326 self.check_split(block_lines)
327
327
328 def test_split_syntax_errors(self):
328 def test_split_syntax_errors(self):
329 # Block splitting with invalid syntax
329 # Block splitting with invalid syntax
330 all_blocks = [ [['a syntax error']],
330 all_blocks = [ [['a syntax error']],
331
331
332 [['x=1',
332 [['x=1',
333 'another syntax error']],
333 'another syntax error']],
334
334
335 [['for i in range(10):'
335 [['for i in range(10):'
336 ' yet another error']],
336 ' yet another error']],
337
337
338 ]
338 ]
339 for block_lines in all_blocks:
339 for block_lines in all_blocks:
340 self.check_split(block_lines, compile=False)
340 self.check_split(block_lines, compile=False)
341
341
342
342
343 class InteractiveLoopTestCase(unittest.TestCase):
343 class InteractiveLoopTestCase(unittest.TestCase):
344 """Tests for an interactive loop like a python shell.
344 """Tests for an interactive loop like a python shell.
345 """
345 """
346 def check_ns(self, lines, ns):
346 def check_ns(self, lines, ns):
347 """Validate that the given input lines produce the resulting namespace.
347 """Validate that the given input lines produce the resulting namespace.
348
348
349 Note: the input lines are given exactly as they would be typed in an
349 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
350 auto-indenting environment, as mini_interactive_loop above already does
351 auto-indenting and prepends spaces to the input.
351 auto-indenting and prepends spaces to the input.
352 """
352 """
353 src = mini_interactive_loop(pseudo_input(lines))
353 src = mini_interactive_loop(pseudo_input(lines))
354 test_ns = {}
354 test_ns = {}
355 exec src in test_ns
355 exec src in test_ns
356 # We can't check that the provided ns is identical to the test_ns,
356 # 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
357 # because Python fills test_ns with extra keys (copyright, etc). But
358 # we can check that the given dict is *contained* in test_ns
358 # we can check that the given dict is *contained* in test_ns
359 for k,v in ns.items():
359 for k,v in ns.items():
360 self.assertEqual(test_ns[k], v)
360 self.assertEqual(test_ns[k], v)
361
361
362 def test_simple(self):
362 def test_simple(self):
363 self.check_ns(['x=1'], dict(x=1))
363 self.check_ns(['x=1'], dict(x=1))
364
364
365 def test_simple2(self):
365 def test_simple2(self):
366 self.check_ns(['if 1:', 'x=2'], dict(x=2))
366 self.check_ns(['if 1:', 'x=2'], dict(x=2))
367
367
368 def test_xy(self):
368 def test_xy(self):
369 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
369 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
370
370
371 def test_abc(self):
371 def test_abc(self):
372 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
372 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
373
373
374 def test_multi(self):
374 def test_multi(self):
375 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
375 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
376
376
377
377
378 def test_LineInfo():
378 def test_LineInfo():
379 """Simple test for LineInfo construction and str()"""
379 """Simple test for LineInfo construction and str()"""
380 linfo = isp.LineInfo(' %cd /home')
380 linfo = isp.LineInfo(' %cd /home')
381 nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]')
381 nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]')
382
382
383
383
384 def test_split_user_input():
384 def test_split_user_input():
385 """Unicode test - split_user_input already has good doctests"""
385 """Unicode test - split_user_input already has good doctests"""
386 line = u"PΓ©rez Fernando"
386 line = u"PΓ©rez Fernando"
387 parts = isp.split_user_input(line)
387 parts = isp.split_user_input(line)
388 parts_expected = (u'', u'', u'', line)
388 parts_expected = (u'', u'', u'', line)
389 nt.assert_equal(parts, parts_expected)
389 nt.assert_equal(parts, parts_expected)
390
390
391
391
392 # Transformer tests
392 # Transformer tests
393 def transform_checker(tests, func):
393 def transform_checker(tests, func):
394 """Utility to loop over test inputs"""
394 """Utility to loop over test inputs"""
395 for inp, tr in tests:
395 for inp, tr in tests:
396 nt.assert_equals(func(inp), tr)
396 nt.assert_equals(func(inp), tr)
397
397
398 # Data for all the syntax tests in the form of lists of pairs of
398 # 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
399 # 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
400 # it both within single-function tests and also to validate the behavior of the
401 # larger objects
401 # larger objects
402
402
403 syntax = \
403 syntax = \
404 dict(assign_system =
404 dict(assign_system =
405 [('a =! ls', 'a = get_ipython().getoutput("ls")'),
405 [('a =! ls', 'a = get_ipython().getoutput("ls")'),
406 ('b = !ls', 'b = get_ipython().getoutput("ls")'),
406 ('b = !ls', 'b = get_ipython().getoutput("ls")'),
407 ('x=1', 'x=1'), # normal input is unmodified
407 ('x=1', 'x=1'), # normal input is unmodified
408 (' ',' '), # blank lines are kept intact
408 (' ',' '), # blank lines are kept intact
409 ],
409 ],
410
410
411 assign_magic =
411 assign_magic =
412 [('a =% who', 'a = get_ipython().magic("who")'),
412 [('a =% who', 'a = get_ipython().magic("who")'),
413 ('b = %who', 'b = get_ipython().magic("who")'),
413 ('b = %who', 'b = get_ipython().magic("who")'),
414 ('x=1', 'x=1'), # normal input is unmodified
414 ('x=1', 'x=1'), # normal input is unmodified
415 (' ',' '), # blank lines are kept intact
415 (' ',' '), # blank lines are kept intact
416 ],
416 ],
417
417
418 classic_prompt =
418 classic_prompt =
419 [('>>> x=1', 'x=1'),
419 [('>>> x=1', 'x=1'),
420 ('x=1', 'x=1'), # normal input is unmodified
420 ('x=1', 'x=1'), # normal input is unmodified
421 (' ', ' '), # blank lines are kept intact
421 (' ', ' '), # blank lines are kept intact
422 ('... ', ''), # continuation prompts
422 ('... ', ''), # continuation prompts
423 ],
423 ],
424
424
425 ipy_prompt =
425 ipy_prompt =
426 [('In [1]: x=1', 'x=1'),
426 [('In [1]: x=1', 'x=1'),
427 ('x=1', 'x=1'), # normal input is unmodified
427 ('x=1', 'x=1'), # normal input is unmodified
428 (' ',' '), # blank lines are kept intact
428 (' ',' '), # blank lines are kept intact
429 (' ....: ', ''), # continuation prompts
429 (' ....: ', ''), # continuation prompts
430 ],
430 ],
431
431
432 # Tests for the escape transformer to leave normal code alone
432 # Tests for the escape transformer to leave normal code alone
433 escaped_noesc =
433 escaped_noesc =
434 [ (' ', ' '),
434 [ (' ', ' '),
435 ('x=1', 'x=1'),
435 ('x=1', 'x=1'),
436 ],
436 ],
437
437
438 # System calls
438 # System calls
439 escaped_shell =
439 escaped_shell =
440 [ ('!ls', 'get_ipython().system("ls")'),
440 [ ('!ls', 'get_ipython().system("ls")'),
441 # Double-escape shell, this means to capture the output of the
441 # Double-escape shell, this means to capture the output of the
442 # subprocess and return it
442 # subprocess and return it
443 ('!!ls', 'get_ipython().getoutput("ls")'),
443 ('!!ls', 'get_ipython().getoutput("ls")'),
444 ],
444 ],
445
445
446 # Help/object info
446 # Help/object info
447 escaped_help =
447 escaped_help =
448 [ ('?', 'get_ipython().show_usage()'),
448 [ ('?', 'get_ipython().show_usage()'),
449 ('?x1', 'get_ipython().magic("pinfo x1")'),
449 ('?x1', 'get_ipython().magic("pinfo x1")'),
450 ('??x2', 'get_ipython().magic("pinfo2 x2")'),
450 ('??x2', 'get_ipython().magic("pinfo2 x2")'),
451 ('x3?', 'get_ipython().magic("pinfo x3")'),
451 ('x3?', 'get_ipython().magic("pinfo x3")'),
452 ('x4??', 'get_ipython().magic("pinfo2 x4")'),
452 ('x4??', 'get_ipython().magic("pinfo2 x4")'),
453 ('%hist?', 'get_ipython().magic("pinfo %hist")'),
453 ('%hist?', 'get_ipython().magic("pinfo %hist")'),
454 ('f*?', 'get_ipython().magic("psearch f*")'),
454 ('f*?', 'get_ipython().magic("psearch f*")'),
455 ('ax.*aspe*?', 'get_ipython().magic("psearch ax.*aspe*")'),
455 ('ax.*aspe*?', 'get_ipython().magic("psearch ax.*aspe*")'),
456 ],
456 ],
457
457
458 # Explicit magic calls
458 # Explicit magic calls
459 escaped_magic =
459 escaped_magic =
460 [ ('%cd', 'get_ipython().magic("cd")'),
460 [ ('%cd', 'get_ipython().magic("cd")'),
461 ('%cd /home', 'get_ipython().magic("cd /home")'),
461 ('%cd /home', 'get_ipython().magic("cd /home")'),
462 (' %magic', ' get_ipython().magic("magic")'),
462 (' %magic', ' get_ipython().magic("magic")'),
463 ],
463 ],
464
464
465 # Quoting with separate arguments
465 # Quoting with separate arguments
466 escaped_quote =
466 escaped_quote =
467 [ (',f', 'f("")'),
467 [ (',f', 'f("")'),
468 (',f x', 'f("x")'),
468 (',f x', 'f("x")'),
469 (' ,f y', ' f("y")'),
469 (' ,f y', ' f("y")'),
470 (',f a b', 'f("a", "b")'),
470 (',f a b', 'f("a", "b")'),
471 ],
471 ],
472
472
473 # Quoting with single argument
473 # Quoting with single argument
474 escaped_quote2 =
474 escaped_quote2 =
475 [ (';f', 'f("")'),
475 [ (';f', 'f("")'),
476 (';f x', 'f("x")'),
476 (';f x', 'f("x")'),
477 (' ;f y', ' f("y")'),
477 (' ;f y', ' f("y")'),
478 (';f a b', 'f("a b")'),
478 (';f a b', 'f("a b")'),
479 ],
479 ],
480
480
481 # Simply apply parens
481 # Simply apply parens
482 escaped_paren =
482 escaped_paren =
483 [ ('/f', 'f()'),
483 [ ('/f', 'f()'),
484 ('/f x', 'f(x)'),
484 ('/f x', 'f(x)'),
485 (' /f y', ' f(y)'),
485 (' /f y', ' f(y)'),
486 ('/f a b', 'f(a, b)'),
486 ('/f a b', 'f(a, b)'),
487 ],
487 ],
488
488
489 )
489 )
490
490
491 # multiline syntax examples. Each of these should be a list of lists, with
491 # 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
492 # 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
493 # '\n'.join() of the transformed inputs is what the splitter should produce
494 # when fed the raw lines one at a time via push.
494 # when fed the raw lines one at a time via push.
495 syntax_ml = \
495 syntax_ml = \
496 dict(classic_prompt =
496 dict(classic_prompt =
497 [ [('>>> for i in range(10):','for i in range(10):'),
497 [ [('>>> for i in range(10):','for i in range(10):'),
498 ('... print i',' print i'),
498 ('... print i',' print i'),
499 ('... ', ''),
499 ('... ', ''),
500 ],
500 ],
501 ],
501 ],
502
502
503 ipy_prompt =
503 ipy_prompt =
504 [ [('In [24]: for i in range(10):','for i in range(10):'),
504 [ [('In [24]: for i in range(10):','for i in range(10):'),
505 (' ....: print i',' print i'),
505 (' ....: print i',' print i'),
506 (' ....: ', ''),
506 (' ....: ', ''),
507 ],
507 ],
508 ],
508 ],
509 )
509 )
510
510
511
511
512 def test_assign_system():
512 def test_assign_system():
513 transform_checker(syntax['assign_system'], isp.transform_assign_system)
513 transform_checker(syntax['assign_system'], isp.transform_assign_system)
514
514
515
515
516 def test_assign_magic():
516 def test_assign_magic():
517 transform_checker(syntax['assign_magic'], isp.transform_assign_magic)
517 transform_checker(syntax['assign_magic'], isp.transform_assign_magic)
518
518
519
519
520 def test_classic_prompt():
520 def test_classic_prompt():
521 transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt)
521 transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt)
522 for example in syntax_ml['classic_prompt']:
522 for example in syntax_ml['classic_prompt']:
523 transform_checker(example, isp.transform_classic_prompt)
523 transform_checker(example, isp.transform_classic_prompt)
524
524
525
525
526 def test_ipy_prompt():
526 def test_ipy_prompt():
527 transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt)
527 transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt)
528 for example in syntax_ml['ipy_prompt']:
528 for example in syntax_ml['ipy_prompt']:
529 transform_checker(example, isp.transform_ipy_prompt)
529 transform_checker(example, isp.transform_ipy_prompt)
530
530
531
531
532 def test_escaped_noesc():
532 def test_escaped_noesc():
533 transform_checker(syntax['escaped_noesc'], isp.transform_escaped)
533 transform_checker(syntax['escaped_noesc'], isp.transform_escaped)
534
534
535
535
536 def test_escaped_shell():
536 def test_escaped_shell():
537 transform_checker(syntax['escaped_shell'], isp.transform_escaped)
537 transform_checker(syntax['escaped_shell'], isp.transform_escaped)
538
538
539
539
540 def test_escaped_help():
540 def test_escaped_help():
541 transform_checker(syntax['escaped_help'], isp.transform_escaped)
541 transform_checker(syntax['escaped_help'], isp.transform_escaped)
542
542
543
543
544 def test_escaped_magic():
544 def test_escaped_magic():
545 transform_checker(syntax['escaped_magic'], isp.transform_escaped)
545 transform_checker(syntax['escaped_magic'], isp.transform_escaped)
546
546
547
547
548 def test_escaped_quote():
548 def test_escaped_quote():
549 transform_checker(syntax['escaped_quote'], isp.transform_escaped)
549 transform_checker(syntax['escaped_quote'], isp.transform_escaped)
550
550
551
551
552 def test_escaped_quote2():
552 def test_escaped_quote2():
553 transform_checker(syntax['escaped_quote2'], isp.transform_escaped)
553 transform_checker(syntax['escaped_quote2'], isp.transform_escaped)
554
554
555
555
556 def test_escaped_paren():
556 def test_escaped_paren():
557 transform_checker(syntax['escaped_paren'], isp.transform_escaped)
557 transform_checker(syntax['escaped_paren'], isp.transform_escaped)
558
558
559
559
560 class IPythonInputTestCase(InputSplitterTestCase):
560 class IPythonInputTestCase(InputSplitterTestCase):
561 """By just creating a new class whose .isp is a different instance, we
561 """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.
562 re-run the same test battery on the new input splitter.
563
563
564 In addition, this runs the tests over the syntax and syntax_ml dicts that
564 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.
565 were tested by individual functions, as part of the OO interface.
566
567 It also makes some checks on the raw buffer storage.
566 """
568 """
567
569
568 def setUp(self):
570 def setUp(self):
569 self.isp = isp.IPythonInputSplitter(input_mode='line')
571 self.isp = isp.IPythonInputSplitter(input_mode='line')
570
572
571 def test_syntax(self):
573 def test_syntax(self):
572 """Call all single-line syntax tests from the main object"""
574 """Call all single-line syntax tests from the main object"""
573 isp = self.isp
575 isp = self.isp
574 for example in syntax.itervalues():
576 for example in syntax.itervalues():
575 for raw, out_t in example:
577 for raw, out_t in example:
576 if raw.startswith(' '):
578 if raw.startswith(' '):
577 continue
579 continue
578
580
579 isp.push(raw)
581 isp.push(raw)
580 out = isp.source_reset().rstrip()
582 out, out_raw = isp.source_raw_reset()
581 self.assertEqual(out, out_t)
583 self.assertEqual(out.rstrip(), out_t)
584 self.assertEqual(out_raw.rstrip(), raw.rstrip())
582
585
583 def test_syntax_multiline(self):
586 def test_syntax_multiline(self):
584 isp = self.isp
587 isp = self.isp
585 for example in syntax_ml.itervalues():
588 for example in syntax_ml.itervalues():
586 out_t_parts = []
589 out_t_parts = []
590 raw_parts = []
587 for line_pairs in example:
591 for line_pairs in example:
588 for raw, out_t_part in line_pairs:
592 for lraw, out_t_part in line_pairs:
589 isp.push(raw)
593 isp.push(lraw)
590 out_t_parts.append(out_t_part)
594 out_t_parts.append(out_t_part)
595 raw_parts.append(lraw)
591
596
592 out = isp.source_reset().rstrip()
597 out, out_raw = isp.source_raw_reset()
593 out_t = '\n'.join(out_t_parts).rstrip()
598 out_t = '\n'.join(out_t_parts).rstrip()
594 self.assertEqual(out, out_t)
599 raw = '\n'.join(raw_parts).rstrip()
600 self.assertEqual(out.rstrip(), out_t)
601 self.assertEqual(out_raw.rstrip(), raw)
595
602
596
603
597 class BlockIPythonInputTestCase(IPythonInputTestCase):
604 class BlockIPythonInputTestCase(IPythonInputTestCase):
598
605
599 # Deactivate tests that don't make sense for the block mode
606 # Deactivate tests that don't make sense for the block mode
600 test_push3 = test_split = lambda s: None
607 test_push3 = test_split = lambda s: None
601
608
602 def setUp(self):
609 def setUp(self):
603 self.isp = isp.IPythonInputSplitter(input_mode='cell')
610 self.isp = isp.IPythonInputSplitter(input_mode='cell')
604
611
605 def test_syntax_multiline(self):
612 def test_syntax_multiline(self):
606 isp = self.isp
613 isp = self.isp
607 for example in syntax_ml.itervalues():
614 for example in syntax_ml.itervalues():
608 raw_parts = []
615 raw_parts = []
609 out_t_parts = []
616 out_t_parts = []
610 for line_pairs in example:
617 for line_pairs in example:
611 for raw, out_t_part in line_pairs:
618 for raw, out_t_part in line_pairs:
612 raw_parts.append(raw)
619 raw_parts.append(raw)
613 out_t_parts.append(out_t_part)
620 out_t_parts.append(out_t_part)
614
621
615 raw = '\n'.join(raw_parts)
622 raw = '\n'.join(raw_parts)
616 out_t = '\n'.join(out_t_parts)
623 out_t = '\n'.join(out_t_parts)
617
624
618 isp.push(raw)
625 isp.push(raw)
619 out = isp.source_reset()
626 out, out_raw = isp.source_raw_reset()
620 # Match ignoring trailing whitespace
627 # Match ignoring trailing whitespace
621 self.assertEqual(out.rstrip(), out_t.rstrip())
628 self.assertEqual(out.rstrip(), out_t.rstrip())
629 self.assertEqual(out_raw.rstrip(), raw.rstrip())
622
630
623
631
624 #-----------------------------------------------------------------------------
632 #-----------------------------------------------------------------------------
625 # Main - use as a script, mostly for developer experiments
633 # Main - use as a script, mostly for developer experiments
626 #-----------------------------------------------------------------------------
634 #-----------------------------------------------------------------------------
627
635
628 if __name__ == '__main__':
636 if __name__ == '__main__':
629 # A simple demo for interactive experimentation. This code will not get
637 # A simple demo for interactive experimentation. This code will not get
630 # picked up by any test suite.
638 # picked up by any test suite.
631 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
639 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
632
640
633 # configure here the syntax to use, prompt and whether to autoindent
641 # configure here the syntax to use, prompt and whether to autoindent
634 #isp, start_prompt = InputSplitter(), '>>> '
642 #isp, start_prompt = InputSplitter(), '>>> '
635 isp, start_prompt = IPythonInputSplitter(), 'In> '
643 isp, start_prompt = IPythonInputSplitter(), 'In> '
636
644
637 autoindent = True
645 autoindent = True
638 #autoindent = False
646 #autoindent = False
639
647
640 try:
648 try:
641 while True:
649 while True:
642 prompt = start_prompt
650 prompt = start_prompt
643 while isp.push_accepts_more():
651 while isp.push_accepts_more():
644 indent = ' '*isp.indent_spaces
652 indent = ' '*isp.indent_spaces
645 if autoindent:
653 if autoindent:
646 line = indent + raw_input(prompt+indent)
654 line = indent + raw_input(prompt+indent)
647 else:
655 else:
648 line = raw_input(prompt)
656 line = raw_input(prompt)
649 isp.push(line)
657 isp.push(line)
650 prompt = '... '
658 prompt = '... '
651
659
652 # Here we just return input so we can use it in a test suite, but a
660 # Here we just return input so we can use it in a test suite, but a
653 # real interpreter would instead send it for execution somewhere.
661 # real interpreter would instead send it for execution somewhere.
654 #src = isp.source; raise EOFError # dbg
662 #src = isp.source; raise EOFError # dbg
655 src = isp.source_reset()
663 src, raw = isp.source_raw_reset()
656 print 'Input source was:\n', src
664 print 'Input source was:\n', src
665 print 'Raw source was:\n', raw
657 except EOFError:
666 except EOFError:
658 print 'Bye'
667 print 'Bye'
@@ -1,657 +1,688 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 if len(self.input_hist) != len (self.input_hist_raw):
194 self.history_manager.sync_inputs()
195 self.input_hist_raw = InputList(self.input_hist)
196
195
197 while 1:
196 while 1:
198 try:
197 try:
199 self.interact(display_banner=display_banner)
198 self.interact(display_banner=display_banner)
200 #self.interact_with_readline()
199 #self.interact_with_readline()
201 # XXX for testing of a readline-decoupled repl loop, call
200 # XXX for testing of a readline-decoupled repl loop, call
202 # interact_with_readline above
201 # interact_with_readline above
203 break
202 break
204 except KeyboardInterrupt:
203 except KeyboardInterrupt:
205 # this should not be necessary, but KeyboardInterrupt
204 # this should not be necessary, but KeyboardInterrupt
206 # handling seems rather unpredictable...
205 # handling seems rather unpredictable...
207 self.write("\nKeyboardInterrupt in interact()\n")
206 self.write("\nKeyboardInterrupt in interact()\n")
208
207
209 def interact(self, display_banner=None):
208 def interact(self, display_banner=None):
210 """Closely emulate the interactive Python console."""
209 """Closely emulate the interactive Python console."""
211
210
212 # batch run -> do not interact
211 # batch run -> do not interact
213 if self.exit_now:
212 if self.exit_now:
214 return
213 return
215
214
216 if display_banner is None:
215 if display_banner is None:
217 display_banner = self.display_banner
216 display_banner = self.display_banner
218 if display_banner:
217 if display_banner:
219 self.show_banner()
218 self.show_banner()
220
219
221 more = 0
220 more = False
222
221
223 # Mark activity in the builtins
222 # Mark activity in the builtins
224 __builtin__.__dict__['__IPYTHON__active'] += 1
223 __builtin__.__dict__['__IPYTHON__active'] += 1
225
224
226 if self.has_readline:
225 if self.has_readline:
227 self.readline_startup_hook(self.pre_readline)
226 self.readline_startup_hook(self.pre_readline)
228 # 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
229 # ask_exit callback.
228 # ask_exit callback.
230
229
231 # Before showing any prompts, if the counter is at zero, we execute an
230 # Before showing any prompts, if the counter is at zero, we execute an
232 # empty line to ensure the user only sees prompts starting at one.
231 # empty line to ensure the user only sees prompts starting at one.
233 if self.execution_count == 0:
232 if self.execution_count == 0:
234 self.push_line('\n')
233 self.execution_count += 1
235
234
236 while not self.exit_now:
235 while not self.exit_now:
237 self.hooks.pre_prompt_hook()
236 self.hooks.pre_prompt_hook()
238 if more:
237 if more:
239 try:
238 try:
240 prompt = self.hooks.generate_prompt(True)
239 prompt = self.hooks.generate_prompt(True)
241 except:
240 except:
242 self.showtraceback()
241 self.showtraceback()
243 if self.autoindent:
242 if self.autoindent:
244 self.rl_do_indent = True
243 self.rl_do_indent = True
245
244
246 else:
245 else:
247 try:
246 try:
248 prompt = self.hooks.generate_prompt(False)
247 prompt = self.hooks.generate_prompt(False)
249 except:
248 except:
250 self.showtraceback()
249 self.showtraceback()
251 try:
250 try:
252 line = self.raw_input(prompt, more)
251 line = self.raw_input(prompt)
253 if self.exit_now:
252 if self.exit_now:
254 # quick exit on sys.std[in|out] close
253 # quick exit on sys.std[in|out] close
255 break
254 break
256 if self.autoindent:
255 if self.autoindent:
257 self.rl_do_indent = False
256 self.rl_do_indent = False
258
257
259 except KeyboardInterrupt:
258 except KeyboardInterrupt:
260 #double-guard against keyboardinterrupts during kbdint handling
259 #double-guard against keyboardinterrupts during kbdint handling
261 try:
260 try:
262 self.write('\nKeyboardInterrupt\n')
261 self.write('\nKeyboardInterrupt\n')
263 self.resetbuffer()
262 self.resetbuffer()
264 # keep cache in sync with the prompt counter:
263 # keep cache in sync with the prompt counter:
265 self.displayhook.prompt_count -= 1
264 self.displayhook.prompt_count -= 1
266
265
267 if self.autoindent:
266 if self.autoindent:
268 self.indent_current_nsp = 0
267 self.indent_current_nsp = 0
269 more = 0
268 more = False
270 except KeyboardInterrupt:
269 except KeyboardInterrupt:
271 pass
270 pass
272 except EOFError:
271 except EOFError:
273 if self.autoindent:
272 if self.autoindent:
274 self.rl_do_indent = False
273 self.rl_do_indent = False
275 if self.has_readline:
274 if self.has_readline:
276 self.readline_startup_hook(None)
275 self.readline_startup_hook(None)
277 self.write('\n')
276 self.write('\n')
278 self.exit()
277 self.exit()
279 except bdb.BdbQuit:
278 except bdb.BdbQuit:
280 warn('The Python debugger has exited with a BdbQuit exception.\n'
279 warn('The Python debugger has exited with a BdbQuit exception.\n'
281 'Because of how pdb handles the stack, it is impossible\n'
280 'Because of how pdb handles the stack, it is impossible\n'
282 'for IPython to properly format this particular exception.\n'
281 'for IPython to properly format this particular exception.\n'
283 'IPython will resume normal operation.')
282 'IPython will resume normal operation.')
284 except:
283 except:
285 # exceptions here are VERY RARE, but they can be triggered
284 # exceptions here are VERY RARE, but they can be triggered
286 # asynchronously by signal handlers, for example.
285 # asynchronously by signal handlers, for example.
287 self.showtraceback()
286 self.showtraceback()
288 else:
287 else:
289 more = self.push_line(line)
288 #more = self.push_line(line)
289 self.input_splitter.push(line)
290 more = self.input_splitter.push_accepts_more()
290 if (self.SyntaxTB.last_syntax_error and
291 if (self.SyntaxTB.last_syntax_error and
291 self.autoedit_syntax):
292 self.autoedit_syntax):
292 self.edit_syntax_error()
293 self.edit_syntax_error()
293
294 if not more:
295 pass
296
294 # We are off again...
297 # We are off again...
295 __builtin__.__dict__['__IPYTHON__active'] -= 1
298 __builtin__.__dict__['__IPYTHON__active'] -= 1
296
299
297 # Turn off the exit flag, so the mainloop can be restarted if desired
300 # Turn off the exit flag, so the mainloop can be restarted if desired
298 self.exit_now = False
301 self.exit_now = False
299
302
300 def raw_input(self,prompt='',continue_prompt=False):
303 def raw_input(self, prompt='', continue_prompt=False):
301 """Write a prompt and read a line.
304 """Write a prompt and read a line.
302
305
303 The returned line does not include the trailing newline.
306 The returned line does not include the trailing newline.
304 When the user enters the EOF key sequence, EOFError is raised.
307 When the user enters the EOF key sequence, EOFError is raised.
305
308
306 Optional inputs:
309 Optional inputs:
307
310
308 - prompt(''): a string to be printed to prompt the user.
311 - prompt(''): a string to be printed to prompt the user.
309
312
310 - continue_prompt(False): whether this line is the first one or a
313 - continue_prompt(False): whether this line is the first one or a
311 continuation in a sequence of inputs.
314 continuation in a sequence of inputs.
312 """
315 """
313 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
314
315 # Code run by the user may have modified the readline completer state.
316 # Code run by the user may have modified the readline completer state.
316 # We must ensure that our completer is back in place.
317 # We must ensure that our completer is back in place.
317
318
318 if self.has_readline:
319 if self.has_readline:
319 self.set_readline_completer()
320 self.set_readline_completer()
320
321
321 try:
322 try:
322 line = raw_input_original(prompt).decode(self.stdin_encoding)
323 line = raw_input_original(prompt).decode(self.stdin_encoding)
323 except ValueError:
324 except ValueError:
324 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
325 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
325 " or sys.stdout.close()!\nExiting IPython!")
326 " or sys.stdout.close()!\nExiting IPython!")
326 self.ask_exit()
327 self.ask_exit()
327 return ""
328 return ""
328
329
329 # Try to be reasonably smart about not re-indenting pasted input more
330 # Try to be reasonably smart about not re-indenting pasted input more
330 # than necessary. We do this by trimming out the auto-indent initial
331 # than necessary. We do this by trimming out the auto-indent initial
331 # spaces, if the user's actual input started itself with whitespace.
332 # spaces, if the user's actual input started itself with whitespace.
332 #debugx('self.buffer[-1]')
333
334 if self.autoindent:
333 if self.autoindent:
335 if num_ini_spaces(line) > self.indent_current_nsp:
334 if num_ini_spaces(line) > self.indent_current_nsp:
336 line = line[self.indent_current_nsp:]
335 line = line[self.indent_current_nsp:]
337 self.indent_current_nsp = 0
336 self.indent_current_nsp = 0
338
337
339 # store the unfiltered input before the user has any chance to modify
338 # store the unfiltered input before the user has any chance to modify
340 # it.
339 # it.
341 if line.strip():
340 if line.strip():
342 if continue_prompt:
341 if continue_prompt:
343 self.input_hist_raw[-1] += '%s\n' % line
344 if self.has_readline and self.readline_use:
342 if self.has_readline and self.readline_use:
345 try:
343 histlen = self.readline.get_current_history_length()
346 histlen = self.readline.get_current_history_length()
344 if histlen > 1:
347 if histlen > 1:
345 newhist = self.input_hist_raw[-1].rstrip()
348 newhist = self.input_hist_raw[-1].rstrip()
346 self.readline.remove_history_item(histlen-1)
349 self.readline.remove_history_item(histlen-1)
347 self.readline.replace_history_item(histlen-2,
350 self.readline.replace_history_item(histlen-2,
348 newhist.encode(self.stdin_encoding))
351 newhist.encode(self.stdin_encoding))
352 except AttributeError:
353 pass # re{move,place}_history_item are new in 2.4.
354 else:
349 else:
355 self.input_hist_raw.append('%s\n' % line)
350 self.input_hist_raw.append('%s\n' % line)
356 # only entries starting at first column go to shadow history
357 if line.lstrip() == line:
358 self.shadowhist.add(line.strip())
359 elif not continue_prompt:
351 elif not continue_prompt:
360 self.input_hist_raw.append('\n')
352 self.input_hist_raw.append('\n')
361 try:
353 try:
362 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
354 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
363 except:
355 except:
364 # blanket except, in case a user-defined prefilter crashes, so it
356 # blanket except, in case a user-defined prefilter crashes, so it
365 # can't take all of ipython with it.
357 # can't take all of ipython with it.
366 self.showtraceback()
358 self.showtraceback()
367 return ''
359 return ''
368 else:
360 else:
369 return lineout
361 return lineout
370
362
363
364 def raw_input(self, prompt=''):
365 """Write a prompt and read a line.
366
367 The returned line does not include the trailing newline.
368 When the user enters the EOF key sequence, EOFError is raised.
369
370 Optional inputs:
371
372 - prompt(''): a string to be printed to prompt the user.
373
374 - continue_prompt(False): whether this line is the first one or a
375 continuation in a sequence of inputs.
376 """
377 # Code run by the user may have modified the readline completer state.
378 # We must ensure that our completer is back in place.
379
380 if self.has_readline:
381 self.set_readline_completer()
382
383 try:
384 line = raw_input_original(prompt).decode(self.stdin_encoding)
385 except ValueError:
386 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
387 " or sys.stdout.close()!\nExiting IPython!")
388 self.ask_exit()
389 return ""
390
391 # 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
393 # spaces, if the user's actual input started itself with whitespace.
394 if self.autoindent:
395 if num_ini_spaces(line) > self.indent_current_nsp:
396 line = line[self.indent_current_nsp:]
397 self.indent_current_nsp = 0
398
399 return line
400
401
371 # TODO: The following three methods are an early attempt to refactor
402 # TODO: The following three methods are an early attempt to refactor
372 # the main code execution logic. We don't use them, but they may be
403 # the main code execution logic. We don't use them, but they may be
373 # helpful when we refactor the code execution logic further.
404 # helpful when we refactor the code execution logic further.
374 # def interact_prompt(self):
405 # def interact_prompt(self):
375 # """ Print the prompt (in read-eval-print loop)
406 # """ Print the prompt (in read-eval-print loop)
376 #
407 #
377 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
408 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
378 # used in standard IPython flow.
409 # used in standard IPython flow.
379 # """
410 # """
380 # if self.more:
411 # if self.more:
381 # try:
412 # try:
382 # prompt = self.hooks.generate_prompt(True)
413 # prompt = self.hooks.generate_prompt(True)
383 # except:
414 # except:
384 # self.showtraceback()
415 # self.showtraceback()
385 # if self.autoindent:
416 # if self.autoindent:
386 # self.rl_do_indent = True
417 # self.rl_do_indent = True
387 #
418 #
388 # else:
419 # else:
389 # try:
420 # try:
390 # prompt = self.hooks.generate_prompt(False)
421 # prompt = self.hooks.generate_prompt(False)
391 # except:
422 # except:
392 # self.showtraceback()
423 # self.showtraceback()
393 # self.write(prompt)
424 # self.write(prompt)
394 #
425 #
395 # def interact_handle_input(self,line):
426 # def interact_handle_input(self,line):
396 # """ Handle the input line (in read-eval-print loop)
427 # """ Handle the input line (in read-eval-print loop)
397 #
428 #
398 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
429 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
399 # used in standard IPython flow.
430 # used in standard IPython flow.
400 # """
431 # """
401 # if line.lstrip() == line:
432 # if line.lstrip() == line:
402 # self.shadowhist.add(line.strip())
433 # self.shadowhist.add(line.strip())
403 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
434 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
404 #
435 #
405 # if line.strip():
436 # if line.strip():
406 # if self.more:
437 # if self.more:
407 # self.input_hist_raw[-1] += '%s\n' % line
438 # self.input_hist_raw[-1] += '%s\n' % line
408 # else:
439 # else:
409 # self.input_hist_raw.append('%s\n' % line)
440 # self.input_hist_raw.append('%s\n' % line)
410 #
441 #
411 #
442 #
412 # self.more = self.push_line(lineout)
443 # self.more = self.push_line(lineout)
413 # if (self.SyntaxTB.last_syntax_error and
444 # if (self.SyntaxTB.last_syntax_error and
414 # self.autoedit_syntax):
445 # self.autoedit_syntax):
415 # self.edit_syntax_error()
446 # self.edit_syntax_error()
416 #
447 #
417 # def interact_with_readline(self):
448 # def interact_with_readline(self):
418 # """ Demo of using interact_handle_input, interact_prompt
449 # """ Demo of using interact_handle_input, interact_prompt
419 #
450 #
420 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
451 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
421 # it should work like this.
452 # it should work like this.
422 # """
453 # """
423 # self.readline_startup_hook(self.pre_readline)
454 # self.readline_startup_hook(self.pre_readline)
424 # while not self.exit_now:
455 # while not self.exit_now:
425 # self.interact_prompt()
456 # self.interact_prompt()
426 # if self.more:
457 # if self.more:
427 # self.rl_do_indent = True
458 # self.rl_do_indent = True
428 # else:
459 # else:
429 # self.rl_do_indent = False
460 # self.rl_do_indent = False
430 # line = raw_input_original().decode(self.stdin_encoding)
461 # line = raw_input_original().decode(self.stdin_encoding)
431 # self.interact_handle_input(line)
462 # self.interact_handle_input(line)
432
463
433 #-------------------------------------------------------------------------
464 #-------------------------------------------------------------------------
434 # Methods to support auto-editing of SyntaxErrors.
465 # Methods to support auto-editing of SyntaxErrors.
435 #-------------------------------------------------------------------------
466 #-------------------------------------------------------------------------
436
467
437 def edit_syntax_error(self):
468 def edit_syntax_error(self):
438 """The bottom half of the syntax error handler called in the main loop.
469 """The bottom half of the syntax error handler called in the main loop.
439
470
440 Loop until syntax error is fixed or user cancels.
471 Loop until syntax error is fixed or user cancels.
441 """
472 """
442
473
443 while self.SyntaxTB.last_syntax_error:
474 while self.SyntaxTB.last_syntax_error:
444 # copy and clear last_syntax_error
475 # copy and clear last_syntax_error
445 err = self.SyntaxTB.clear_err_state()
476 err = self.SyntaxTB.clear_err_state()
446 if not self._should_recompile(err):
477 if not self._should_recompile(err):
447 return
478 return
448 try:
479 try:
449 # may set last_syntax_error again if a SyntaxError is raised
480 # may set last_syntax_error again if a SyntaxError is raised
450 self.safe_execfile(err.filename,self.user_ns)
481 self.safe_execfile(err.filename,self.user_ns)
451 except:
482 except:
452 self.showtraceback()
483 self.showtraceback()
453 else:
484 else:
454 try:
485 try:
455 f = file(err.filename)
486 f = file(err.filename)
456 try:
487 try:
457 # This should be inside a display_trap block and I
488 # This should be inside a display_trap block and I
458 # think it is.
489 # think it is.
459 sys.displayhook(f.read())
490 sys.displayhook(f.read())
460 finally:
491 finally:
461 f.close()
492 f.close()
462 except:
493 except:
463 self.showtraceback()
494 self.showtraceback()
464
495
465 def _should_recompile(self,e):
496 def _should_recompile(self,e):
466 """Utility routine for edit_syntax_error"""
497 """Utility routine for edit_syntax_error"""
467
498
468 if e.filename in ('<ipython console>','<input>','<string>',
499 if e.filename in ('<ipython console>','<input>','<string>',
469 '<console>','<BackgroundJob compilation>',
500 '<console>','<BackgroundJob compilation>',
470 None):
501 None):
471
502
472 return False
503 return False
473 try:
504 try:
474 if (self.autoedit_syntax and
505 if (self.autoedit_syntax and
475 not self.ask_yes_no('Return to editor to correct syntax error? '
506 not self.ask_yes_no('Return to editor to correct syntax error? '
476 '[Y/n] ','y')):
507 '[Y/n] ','y')):
477 return False
508 return False
478 except EOFError:
509 except EOFError:
479 return False
510 return False
480
511
481 def int0(x):
512 def int0(x):
482 try:
513 try:
483 return int(x)
514 return int(x)
484 except TypeError:
515 except TypeError:
485 return 0
516 return 0
486 # always pass integer line and offset values to editor hook
517 # always pass integer line and offset values to editor hook
487 try:
518 try:
488 self.hooks.fix_error_editor(e.filename,
519 self.hooks.fix_error_editor(e.filename,
489 int0(e.lineno),int0(e.offset),e.msg)
520 int0(e.lineno),int0(e.offset),e.msg)
490 except TryNext:
521 except TryNext:
491 warn('Could not open editor')
522 warn('Could not open editor')
492 return False
523 return False
493 return True
524 return True
494
525
495 #-------------------------------------------------------------------------
526 #-------------------------------------------------------------------------
496 # Things related to GUI support and pylab
527 # Things related to GUI support and pylab
497 #-------------------------------------------------------------------------
528 #-------------------------------------------------------------------------
498
529
499 def enable_pylab(self, gui=None):
530 def enable_pylab(self, gui=None):
500 """Activate pylab support at runtime.
531 """Activate pylab support at runtime.
501
532
502 This turns on support for matplotlib, preloads into the interactive
533 This turns on support for matplotlib, preloads into the interactive
503 namespace all of numpy and pylab, and configures IPython to correcdtly
534 namespace all of numpy and pylab, and configures IPython to correcdtly
504 interact with the GUI event loop. The GUI backend to be used can be
535 interact with the GUI event loop. The GUI backend to be used can be
505 optionally selected with the optional :param:`gui` argument.
536 optionally selected with the optional :param:`gui` argument.
506
537
507 Parameters
538 Parameters
508 ----------
539 ----------
509 gui : optional, string
540 gui : optional, string
510
541
511 If given, dictates the choice of matplotlib GUI backend to use
542 If given, dictates the choice of matplotlib GUI backend to use
512 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
543 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
513 'gtk'), otherwise we use the default chosen by matplotlib (as
544 'gtk'), otherwise we use the default chosen by matplotlib (as
514 dictated by the matplotlib build-time options plus the user's
545 dictated by the matplotlib build-time options plus the user's
515 matplotlibrc configuration file).
546 matplotlibrc configuration file).
516 """
547 """
517 # We want to prevent the loading of pylab to pollute the user's
548 # We want to prevent the loading of pylab to pollute the user's
518 # namespace as shown by the %who* magics, so we execute the activation
549 # namespace as shown by the %who* magics, so we execute the activation
519 # code in an empty namespace, and we update *both* user_ns and
550 # code in an empty namespace, and we update *both* user_ns and
520 # user_ns_hidden with this information.
551 # user_ns_hidden with this information.
521 ns = {}
552 ns = {}
522 gui = pylab_activate(ns, gui)
553 gui = pylab_activate(ns, gui)
523 self.user_ns.update(ns)
554 self.user_ns.update(ns)
524 self.user_ns_hidden.update(ns)
555 self.user_ns_hidden.update(ns)
525 # Now we must activate the gui pylab wants to use, and fix %run to take
556 # Now we must activate the gui pylab wants to use, and fix %run to take
526 # plot updates into account
557 # plot updates into account
527 enable_gui(gui)
558 enable_gui(gui)
528 self.magic_run = self._pylab_magic_run
559 self.magic_run = self._pylab_magic_run
529
560
530 #-------------------------------------------------------------------------
561 #-------------------------------------------------------------------------
531 # Things related to exiting
562 # Things related to exiting
532 #-------------------------------------------------------------------------
563 #-------------------------------------------------------------------------
533
564
534 def ask_exit(self):
565 def ask_exit(self):
535 """ Ask the shell to exit. Can be overiden and used as a callback. """
566 """ Ask the shell to exit. Can be overiden and used as a callback. """
536 self.exit_now = True
567 self.exit_now = True
537
568
538 def exit(self):
569 def exit(self):
539 """Handle interactive exit.
570 """Handle interactive exit.
540
571
541 This method calls the ask_exit callback."""
572 This method calls the ask_exit callback."""
542 if self.confirm_exit:
573 if self.confirm_exit:
543 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
574 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
544 self.ask_exit()
575 self.ask_exit()
545 else:
576 else:
546 self.ask_exit()
577 self.ask_exit()
547
578
548 #------------------------------------------------------------------------
579 #------------------------------------------------------------------------
549 # Magic overrides
580 # Magic overrides
550 #------------------------------------------------------------------------
581 #------------------------------------------------------------------------
551 # Once the base class stops inheriting from magic, this code needs to be
582 # Once the base class stops inheriting from magic, this code needs to be
552 # moved into a separate machinery as well. For now, at least isolate here
583 # moved into a separate machinery as well. For now, at least isolate here
553 # the magics which this class needs to implement differently from the base
584 # the magics which this class needs to implement differently from the base
554 # class, or that are unique to it.
585 # class, or that are unique to it.
555
586
556 def magic_autoindent(self, parameter_s = ''):
587 def magic_autoindent(self, parameter_s = ''):
557 """Toggle autoindent on/off (if available)."""
588 """Toggle autoindent on/off (if available)."""
558
589
559 self.shell.set_autoindent()
590 self.shell.set_autoindent()
560 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
591 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
561
592
562 def magic_cpaste(self, parameter_s=''):
593 def magic_cpaste(self, parameter_s=''):
563 """Paste & execute a pre-formatted code block from clipboard.
594 """Paste & execute a pre-formatted code block from clipboard.
564
595
565 You must terminate the block with '--' (two minus-signs) alone on the
596 You must terminate the block with '--' (two minus-signs) alone on the
566 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
597 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
567 is the new sentinel for this operation)
598 is the new sentinel for this operation)
568
599
569 The block is dedented prior to execution to enable execution of method
600 The block is dedented prior to execution to enable execution of method
570 definitions. '>' and '+' characters at the beginning of a line are
601 definitions. '>' and '+' characters at the beginning of a line are
571 ignored, to allow pasting directly from e-mails, diff files and
602 ignored, to allow pasting directly from e-mails, diff files and
572 doctests (the '...' continuation prompt is also stripped). The
603 doctests (the '...' continuation prompt is also stripped). The
573 executed block is also assigned to variable named 'pasted_block' for
604 executed block is also assigned to variable named 'pasted_block' for
574 later editing with '%edit pasted_block'.
605 later editing with '%edit pasted_block'.
575
606
576 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
607 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
577 This assigns the pasted block to variable 'foo' as string, without
608 This assigns the pasted block to variable 'foo' as string, without
578 dedenting or executing it (preceding >>> and + is still stripped)
609 dedenting or executing it (preceding >>> and + is still stripped)
579
610
580 '%cpaste -r' re-executes the block previously entered by cpaste.
611 '%cpaste -r' re-executes the block previously entered by cpaste.
581
612
582 Do not be alarmed by garbled output on Windows (it's a readline bug).
613 Do not be alarmed by garbled output on Windows (it's a readline bug).
583 Just press enter and type -- (and press enter again) and the block
614 Just press enter and type -- (and press enter again) and the block
584 will be what was just pasted.
615 will be what was just pasted.
585
616
586 IPython statements (magics, shell escapes) are not supported (yet).
617 IPython statements (magics, shell escapes) are not supported (yet).
587
618
588 See also
619 See also
589 --------
620 --------
590 paste: automatically pull code from clipboard.
621 paste: automatically pull code from clipboard.
591 """
622 """
592
623
593 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
624 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
594 par = args.strip()
625 par = args.strip()
595 if opts.has_key('r'):
626 if opts.has_key('r'):
596 self._rerun_pasted()
627 self._rerun_pasted()
597 return
628 return
598
629
599 sentinel = opts.get('s','--')
630 sentinel = opts.get('s','--')
600
631
601 block = self._strip_pasted_lines_for_code(
632 block = self._strip_pasted_lines_for_code(
602 self._get_pasted_lines(sentinel))
633 self._get_pasted_lines(sentinel))
603
634
604 self._execute_block(block, par)
635 self._execute_block(block, par)
605
636
606 def magic_paste(self, parameter_s=''):
637 def magic_paste(self, parameter_s=''):
607 """Paste & execute a pre-formatted code block from clipboard.
638 """Paste & execute a pre-formatted code block from clipboard.
608
639
609 The text is pulled directly from the clipboard without user
640 The text is pulled directly from the clipboard without user
610 intervention and printed back on the screen before execution (unless
641 intervention and printed back on the screen before execution (unless
611 the -q flag is given to force quiet mode).
642 the -q flag is given to force quiet mode).
612
643
613 The block is dedented prior to execution to enable execution of method
644 The block is dedented prior to execution to enable execution of method
614 definitions. '>' and '+' characters at the beginning of a line are
645 definitions. '>' and '+' characters at the beginning of a line are
615 ignored, to allow pasting directly from e-mails, diff files and
646 ignored, to allow pasting directly from e-mails, diff files and
616 doctests (the '...' continuation prompt is also stripped). The
647 doctests (the '...' continuation prompt is also stripped). The
617 executed block is also assigned to variable named 'pasted_block' for
648 executed block is also assigned to variable named 'pasted_block' for
618 later editing with '%edit pasted_block'.
649 later editing with '%edit pasted_block'.
619
650
620 You can also pass a variable name as an argument, e.g. '%paste foo'.
651 You can also pass a variable name as an argument, e.g. '%paste foo'.
621 This assigns the pasted block to variable 'foo' as string, without
652 This assigns the pasted block to variable 'foo' as string, without
622 dedenting or executing it (preceding >>> and + is still stripped)
653 dedenting or executing it (preceding >>> and + is still stripped)
623
654
624 Options
655 Options
625 -------
656 -------
626
657
627 -r: re-executes the block previously entered by cpaste.
658 -r: re-executes the block previously entered by cpaste.
628
659
629 -q: quiet mode: do not echo the pasted text back to the terminal.
660 -q: quiet mode: do not echo the pasted text back to the terminal.
630
661
631 IPython statements (magics, shell escapes) are not supported (yet).
662 IPython statements (magics, shell escapes) are not supported (yet).
632
663
633 See also
664 See also
634 --------
665 --------
635 cpaste: manually paste code into terminal until you mark its end.
666 cpaste: manually paste code into terminal until you mark its end.
636 """
667 """
637 opts,args = self.parse_options(parameter_s,'rq',mode='string')
668 opts,args = self.parse_options(parameter_s,'rq',mode='string')
638 par = args.strip()
669 par = args.strip()
639 if opts.has_key('r'):
670 if opts.has_key('r'):
640 self._rerun_pasted()
671 self._rerun_pasted()
641 return
672 return
642
673
643 text = self.shell.hooks.clipboard_get()
674 text = self.shell.hooks.clipboard_get()
644 block = self._strip_pasted_lines_for_code(text.splitlines())
675 block = self._strip_pasted_lines_for_code(text.splitlines())
645
676
646 # By default, echo back to terminal unless quiet mode is requested
677 # By default, echo back to terminal unless quiet mode is requested
647 if not opts.has_key('q'):
678 if not opts.has_key('q'):
648 write = self.shell.write
679 write = self.shell.write
649 write(self.shell.pycolorize(block))
680 write(self.shell.pycolorize(block))
650 if not block.endswith('\n'):
681 if not block.endswith('\n'):
651 write('\n')
682 write('\n')
652 write("## -- End pasted text --\n")
683 write("## -- End pasted text --\n")
653
684
654 self._execute_block(block, par)
685 self._execute_block(block, par)
655
686
656
687
657 InteractiveShellABC.register(TerminalInteractiveShell)
688 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now