##// END OF EJS Templates
Remove duplicate raw_input in TerminalInteractiveShell
Thomas Kluyver -
Show More
@@ -1,619 +1,558 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.interactiveshell import InteractiveShell, InteractiveShellABC
26 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 from IPython.lib.inputhook import enable_gui
27 from IPython.lib.inputhook import enable_gui
28 from IPython.lib.pylabtools import pylab_activate
28 from IPython.lib.pylabtools import pylab_activate
29 from IPython.testing import decorators as testdec
29 from IPython.testing import decorators as testdec
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 # Utilities
37 # Utilities
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 def get_default_editor():
40 def get_default_editor():
41 try:
41 try:
42 ed = os.environ['EDITOR']
42 ed = os.environ['EDITOR']
43 except KeyError:
43 except KeyError:
44 if os.name == 'posix':
44 if os.name == 'posix':
45 ed = 'vi' # the only one guaranteed to be there!
45 ed = 'vi' # the only one guaranteed to be there!
46 else:
46 else:
47 ed = 'notepad' # same in Windows!
47 ed = 'notepad' # same in Windows!
48 return ed
48 return ed
49
49
50
50
51 # store the builtin raw_input globally, and use this always, in case user code
51 # store the builtin raw_input globally, and use this always, in case user code
52 # overwrites it (like wx.py.PyShell does)
52 # overwrites it (like wx.py.PyShell does)
53 raw_input_original = raw_input
53 raw_input_original = raw_input
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Main class
56 # Main class
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59 class TerminalInteractiveShell(InteractiveShell):
59 class TerminalInteractiveShell(InteractiveShell):
60
60
61 autoedit_syntax = CBool(False, config=True)
61 autoedit_syntax = CBool(False, config=True)
62 banner = Str('')
62 banner = Str('')
63 banner1 = Str(default_banner, config=True)
63 banner1 = Str(default_banner, config=True)
64 banner2 = Str('', config=True)
64 banner2 = Str('', config=True)
65 confirm_exit = CBool(True, config=True)
65 confirm_exit = CBool(True, config=True)
66 # This display_banner only controls whether or not self.show_banner()
66 # This display_banner only controls whether or not self.show_banner()
67 # is called when mainloop/interact are called. The default is False
67 # is called when mainloop/interact are called. The default is False
68 # because for the terminal based application, the banner behavior
68 # because for the terminal based application, the banner behavior
69 # is controlled by Global.display_banner, which IPythonApp looks at
69 # is controlled by Global.display_banner, which IPythonApp looks at
70 # to determine if *it* should call show_banner() by hand or not.
70 # to determine if *it* should call show_banner() by hand or not.
71 display_banner = CBool(False) # This isn't configurable!
71 display_banner = CBool(False) # This isn't configurable!
72 embedded = CBool(False)
72 embedded = CBool(False)
73 embedded_active = CBool(False)
73 embedded_active = CBool(False)
74 editor = Str(get_default_editor(), config=True)
74 editor = Str(get_default_editor(), config=True)
75 pager = Str('less', config=True)
75 pager = Str('less', config=True)
76
76
77 screen_length = Int(0, config=True)
77 screen_length = Int(0, config=True)
78 term_title = CBool(False, config=True)
78 term_title = CBool(False, config=True)
79
79
80 def __init__(self, config=None, ipython_dir=None, user_ns=None,
80 def __init__(self, config=None, ipython_dir=None, user_ns=None,
81 user_global_ns=None, custom_exceptions=((),None),
81 user_global_ns=None, custom_exceptions=((),None),
82 usage=None, banner1=None, banner2=None,
82 usage=None, banner1=None, banner2=None,
83 display_banner=None):
83 display_banner=None):
84
84
85 super(TerminalInteractiveShell, self).__init__(
85 super(TerminalInteractiveShell, self).__init__(
86 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
86 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
87 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
87 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
88 )
88 )
89 self.init_term_title()
89 self.init_term_title()
90 self.init_usage(usage)
90 self.init_usage(usage)
91 self.init_banner(banner1, banner2, display_banner)
91 self.init_banner(banner1, banner2, display_banner)
92
92
93 #-------------------------------------------------------------------------
93 #-------------------------------------------------------------------------
94 # Things related to the terminal
94 # Things related to the terminal
95 #-------------------------------------------------------------------------
95 #-------------------------------------------------------------------------
96
96
97 @property
97 @property
98 def usable_screen_length(self):
98 def usable_screen_length(self):
99 if self.screen_length == 0:
99 if self.screen_length == 0:
100 return 0
100 return 0
101 else:
101 else:
102 num_lines_bot = self.separate_in.count('\n')+1
102 num_lines_bot = self.separate_in.count('\n')+1
103 return self.screen_length - num_lines_bot
103 return self.screen_length - num_lines_bot
104
104
105 def init_term_title(self):
105 def init_term_title(self):
106 # Enable or disable the terminal title.
106 # Enable or disable the terminal title.
107 if self.term_title:
107 if self.term_title:
108 toggle_set_term_title(True)
108 toggle_set_term_title(True)
109 set_term_title('IPython: ' + abbrev_cwd())
109 set_term_title('IPython: ' + abbrev_cwd())
110 else:
110 else:
111 toggle_set_term_title(False)
111 toggle_set_term_title(False)
112
112
113 #-------------------------------------------------------------------------
113 #-------------------------------------------------------------------------
114 # Things related to aliases
114 # Things related to aliases
115 #-------------------------------------------------------------------------
115 #-------------------------------------------------------------------------
116
116
117 def init_alias(self):
117 def init_alias(self):
118 # The parent class defines aliases that can be safely used with any
118 # The parent class defines aliases that can be safely used with any
119 # frontend.
119 # frontend.
120 super(TerminalInteractiveShell, self).init_alias()
120 super(TerminalInteractiveShell, self).init_alias()
121
121
122 # Now define aliases that only make sense on the terminal, because they
122 # Now define aliases that only make sense on the terminal, because they
123 # need direct access to the console in a way that we can't emulate in
123 # need direct access to the console in a way that we can't emulate in
124 # GUI or web frontend
124 # GUI or web frontend
125 if os.name == 'posix':
125 if os.name == 'posix':
126 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
126 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
127 ('man', 'man')]
127 ('man', 'man')]
128 elif os.name == 'nt':
128 elif os.name == 'nt':
129 aliases = [('cls', 'cls')]
129 aliases = [('cls', 'cls')]
130
130
131
131
132 for name, cmd in aliases:
132 for name, cmd in aliases:
133 self.alias_manager.define_alias(name, cmd)
133 self.alias_manager.define_alias(name, cmd)
134
134
135 #-------------------------------------------------------------------------
135 #-------------------------------------------------------------------------
136 # Things related to the banner and usage
136 # Things related to the banner and usage
137 #-------------------------------------------------------------------------
137 #-------------------------------------------------------------------------
138
138
139 def _banner1_changed(self):
139 def _banner1_changed(self):
140 self.compute_banner()
140 self.compute_banner()
141
141
142 def _banner2_changed(self):
142 def _banner2_changed(self):
143 self.compute_banner()
143 self.compute_banner()
144
144
145 def _term_title_changed(self, name, new_value):
145 def _term_title_changed(self, name, new_value):
146 self.init_term_title()
146 self.init_term_title()
147
147
148 def init_banner(self, banner1, banner2, display_banner):
148 def init_banner(self, banner1, banner2, display_banner):
149 if banner1 is not None:
149 if banner1 is not None:
150 self.banner1 = banner1
150 self.banner1 = banner1
151 if banner2 is not None:
151 if banner2 is not None:
152 self.banner2 = banner2
152 self.banner2 = banner2
153 if display_banner is not None:
153 if display_banner is not None:
154 self.display_banner = display_banner
154 self.display_banner = display_banner
155 self.compute_banner()
155 self.compute_banner()
156
156
157 def show_banner(self, banner=None):
157 def show_banner(self, banner=None):
158 if banner is None:
158 if banner is None:
159 banner = self.banner
159 banner = self.banner
160 self.write(banner)
160 self.write(banner)
161
161
162 def compute_banner(self):
162 def compute_banner(self):
163 self.banner = self.banner1
163 self.banner = self.banner1
164 if self.profile:
164 if self.profile:
165 self.banner += '\nIPython profile: %s\n' % self.profile
165 self.banner += '\nIPython profile: %s\n' % self.profile
166 if self.banner2:
166 if self.banner2:
167 self.banner += '\n' + self.banner2
167 self.banner += '\n' + self.banner2
168
168
169 def init_usage(self, usage=None):
169 def init_usage(self, usage=None):
170 if usage is None:
170 if usage is None:
171 self.usage = interactive_usage
171 self.usage = interactive_usage
172 else:
172 else:
173 self.usage = usage
173 self.usage = usage
174
174
175 #-------------------------------------------------------------------------
175 #-------------------------------------------------------------------------
176 # Mainloop and code execution logic
176 # Mainloop and code execution logic
177 #-------------------------------------------------------------------------
177 #-------------------------------------------------------------------------
178
178
179 def mainloop(self, display_banner=None):
179 def mainloop(self, display_banner=None):
180 """Start the mainloop.
180 """Start the mainloop.
181
181
182 If an optional banner argument is given, it will override the
182 If an optional banner argument is given, it will override the
183 internally created default banner.
183 internally created default banner.
184 """
184 """
185
185
186 with nested(self.builtin_trap, self.display_trap):
186 with nested(self.builtin_trap, self.display_trap):
187
187
188 while 1:
188 while 1:
189 try:
189 try:
190 self.interact(display_banner=display_banner)
190 self.interact(display_banner=display_banner)
191 #self.interact_with_readline()
191 #self.interact_with_readline()
192 # XXX for testing of a readline-decoupled repl loop, call
192 # XXX for testing of a readline-decoupled repl loop, call
193 # interact_with_readline above
193 # interact_with_readline above
194 break
194 break
195 except KeyboardInterrupt:
195 except KeyboardInterrupt:
196 # this should not be necessary, but KeyboardInterrupt
196 # this should not be necessary, but KeyboardInterrupt
197 # handling seems rather unpredictable...
197 # handling seems rather unpredictable...
198 self.write("\nKeyboardInterrupt in interact()\n")
198 self.write("\nKeyboardInterrupt in interact()\n")
199
199
200 def interact(self, display_banner=None):
200 def interact(self, display_banner=None):
201 """Closely emulate the interactive Python console."""
201 """Closely emulate the interactive Python console."""
202
202
203 # batch run -> do not interact
203 # batch run -> do not interact
204 if self.exit_now:
204 if self.exit_now:
205 return
205 return
206
206
207 if display_banner is None:
207 if display_banner is None:
208 display_banner = self.display_banner
208 display_banner = self.display_banner
209 if display_banner:
209 if display_banner:
210 self.show_banner()
210 self.show_banner()
211
211
212 more = False
212 more = False
213
213
214 # Mark activity in the builtins
214 # Mark activity in the builtins
215 __builtin__.__dict__['__IPYTHON__active'] += 1
215 __builtin__.__dict__['__IPYTHON__active'] += 1
216
216
217 if self.has_readline:
217 if self.has_readline:
218 self.readline_startup_hook(self.pre_readline)
218 self.readline_startup_hook(self.pre_readline)
219 # exit_now is set by a call to %Exit or %Quit, through the
219 # exit_now is set by a call to %Exit or %Quit, through the
220 # ask_exit callback.
220 # ask_exit callback.
221
221
222 while not self.exit_now:
222 while not self.exit_now:
223 self.hooks.pre_prompt_hook()
223 self.hooks.pre_prompt_hook()
224 if more:
224 if more:
225 try:
225 try:
226 prompt = self.hooks.generate_prompt(True)
226 prompt = self.hooks.generate_prompt(True)
227 except:
227 except:
228 self.showtraceback()
228 self.showtraceback()
229 if self.autoindent:
229 if self.autoindent:
230 self.rl_do_indent = True
230 self.rl_do_indent = True
231
231
232 else:
232 else:
233 try:
233 try:
234 prompt = self.hooks.generate_prompt(False)
234 prompt = self.hooks.generate_prompt(False)
235 except:
235 except:
236 self.showtraceback()
236 self.showtraceback()
237 try:
237 try:
238 line = self.raw_input(prompt)
238 line = self.raw_input(prompt)
239 if self.exit_now:
239 if self.exit_now:
240 # quick exit on sys.std[in|out] close
240 # quick exit on sys.std[in|out] close
241 break
241 break
242 if self.autoindent:
242 if self.autoindent:
243 self.rl_do_indent = False
243 self.rl_do_indent = False
244
244
245 except KeyboardInterrupt:
245 except KeyboardInterrupt:
246 #double-guard against keyboardinterrupts during kbdint handling
246 #double-guard against keyboardinterrupts during kbdint handling
247 try:
247 try:
248 self.write('\nKeyboardInterrupt\n')
248 self.write('\nKeyboardInterrupt\n')
249 self.resetbuffer()
249 self.resetbuffer()
250 more = False
250 more = False
251 except KeyboardInterrupt:
251 except KeyboardInterrupt:
252 pass
252 pass
253 except EOFError:
253 except EOFError:
254 if self.autoindent:
254 if self.autoindent:
255 self.rl_do_indent = False
255 self.rl_do_indent = False
256 if self.has_readline:
256 if self.has_readline:
257 self.readline_startup_hook(None)
257 self.readline_startup_hook(None)
258 self.write('\n')
258 self.write('\n')
259 self.exit()
259 self.exit()
260 except bdb.BdbQuit:
260 except bdb.BdbQuit:
261 warn('The Python debugger has exited with a BdbQuit exception.\n'
261 warn('The Python debugger has exited with a BdbQuit exception.\n'
262 'Because of how pdb handles the stack, it is impossible\n'
262 'Because of how pdb handles the stack, it is impossible\n'
263 'for IPython to properly format this particular exception.\n'
263 'for IPython to properly format this particular exception.\n'
264 'IPython will resume normal operation.')
264 'IPython will resume normal operation.')
265 except:
265 except:
266 # exceptions here are VERY RARE, but they can be triggered
266 # exceptions here are VERY RARE, but they can be triggered
267 # asynchronously by signal handlers, for example.
267 # asynchronously by signal handlers, for example.
268 self.showtraceback()
268 self.showtraceback()
269 else:
269 else:
270 self.input_splitter.push(line)
270 self.input_splitter.push(line)
271 more = self.input_splitter.push_accepts_more()
271 more = self.input_splitter.push_accepts_more()
272 if (self.SyntaxTB.last_syntax_error and
272 if (self.SyntaxTB.last_syntax_error and
273 self.autoedit_syntax):
273 self.autoedit_syntax):
274 self.edit_syntax_error()
274 self.edit_syntax_error()
275 if not more:
275 if not more:
276 source_raw = self.input_splitter.source_raw_reset()[1]
276 source_raw = self.input_splitter.source_raw_reset()[1]
277 self.run_cell(source_raw)
277 self.run_cell(source_raw)
278
278
279 # We are off again...
279 # We are off again...
280 __builtin__.__dict__['__IPYTHON__active'] -= 1
280 __builtin__.__dict__['__IPYTHON__active'] -= 1
281
281
282 # Turn off the exit flag, so the mainloop can be restarted if desired
282 # Turn off the exit flag, so the mainloop can be restarted if desired
283 self.exit_now = False
283 self.exit_now = False
284
284
285 def raw_input(self, prompt='', continue_prompt=False):
286 """Write a prompt and read a line.
287
288 The returned line does not include the trailing newline.
289 When the user enters the EOF key sequence, EOFError is raised.
290
291 Optional inputs:
292
293 - prompt(''): a string to be printed to prompt the user.
294
295 - continue_prompt(False): whether this line is the first one or a
296 continuation in a sequence of inputs.
297 """
298 # Code run by the user may have modified the readline completer state.
299 # We must ensure that our completer is back in place.
300
301 if self.has_readline:
302 self.set_readline_completer()
303
304 try:
305 line = raw_input_original(prompt).decode(self.stdin_encoding)
306 except ValueError:
307 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
308 " or sys.stdout.close()!\nExiting IPython!")
309 self.ask_exit()
310 return ""
311
312 # Try to be reasonably smart about not re-indenting pasted input more
313 # than necessary. We do this by trimming out the auto-indent initial
314 # spaces, if the user's actual input started itself with whitespace.
315 if self.autoindent:
316 if num_ini_spaces(line) > self.indent_current_nsp:
317 line = line[self.indent_current_nsp:]
318 self.indent_current_nsp = 0
319
320 # store the unfiltered input before the user has any chance to modify
321 # it.
322 if line.strip():
323 if continue_prompt:
324 if self.has_readline and self.readline_use:
325 histlen = self.readline.get_current_history_length()
326 if histlen > 1:
327 newhist = self.history_manager.input_hist_raw[-1].rstrip()
328 self.readline.remove_history_item(histlen-1)
329 self.readline.replace_history_item(histlen-2,
330 newhist.encode(self.stdin_encoding))
331 else:
332 self.history_manager.input_hist_raw.append('%s\n' % line)
333 elif not continue_prompt:
334 self.history_manager.input_hist_raw.append('\n')
335 try:
336 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
337 except:
338 # blanket except, in case a user-defined prefilter crashes, so it
339 # can't take all of ipython with it.
340 self.showtraceback()
341 return ''
342 else:
343 return lineout
344
345
346 def raw_input(self, prompt=''):
285 def raw_input(self, prompt=''):
347 """Write a prompt and read a line.
286 """Write a prompt and read a line.
348
287
349 The returned line does not include the trailing newline.
288 The returned line does not include the trailing newline.
350 When the user enters the EOF key sequence, EOFError is raised.
289 When the user enters the EOF key sequence, EOFError is raised.
351
290
352 Optional inputs:
291 Optional inputs:
353
292
354 - prompt(''): a string to be printed to prompt the user.
293 - prompt(''): a string to be printed to prompt the user.
355
294
356 - continue_prompt(False): whether this line is the first one or a
295 - continue_prompt(False): whether this line is the first one or a
357 continuation in a sequence of inputs.
296 continuation in a sequence of inputs.
358 """
297 """
359 # Code run by the user may have modified the readline completer state.
298 # Code run by the user may have modified the readline completer state.
360 # We must ensure that our completer is back in place.
299 # We must ensure that our completer is back in place.
361
300
362 if self.has_readline:
301 if self.has_readline:
363 self.set_readline_completer()
302 self.set_readline_completer()
364
303
365 try:
304 try:
366 line = raw_input_original(prompt).decode(self.stdin_encoding)
305 line = raw_input_original(prompt).decode(self.stdin_encoding)
367 except ValueError:
306 except ValueError:
368 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
307 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
369 " or sys.stdout.close()!\nExiting IPython!")
308 " or sys.stdout.close()!\nExiting IPython!")
370 self.ask_exit()
309 self.ask_exit()
371 return ""
310 return ""
372
311
373 # Try to be reasonably smart about not re-indenting pasted input more
312 # Try to be reasonably smart about not re-indenting pasted input more
374 # than necessary. We do this by trimming out the auto-indent initial
313 # than necessary. We do this by trimming out the auto-indent initial
375 # spaces, if the user's actual input started itself with whitespace.
314 # spaces, if the user's actual input started itself with whitespace.
376 if self.autoindent:
315 if self.autoindent:
377 if num_ini_spaces(line) > self.indent_current_nsp:
316 if num_ini_spaces(line) > self.indent_current_nsp:
378 line = line[self.indent_current_nsp:]
317 line = line[self.indent_current_nsp:]
379 self.indent_current_nsp = 0
318 self.indent_current_nsp = 0
380
319
381 return line
320 return line
382
321
383 #-------------------------------------------------------------------------
322 #-------------------------------------------------------------------------
384 # Methods to support auto-editing of SyntaxErrors.
323 # Methods to support auto-editing of SyntaxErrors.
385 #-------------------------------------------------------------------------
324 #-------------------------------------------------------------------------
386
325
387 def edit_syntax_error(self):
326 def edit_syntax_error(self):
388 """The bottom half of the syntax error handler called in the main loop.
327 """The bottom half of the syntax error handler called in the main loop.
389
328
390 Loop until syntax error is fixed or user cancels.
329 Loop until syntax error is fixed or user cancels.
391 """
330 """
392
331
393 while self.SyntaxTB.last_syntax_error:
332 while self.SyntaxTB.last_syntax_error:
394 # copy and clear last_syntax_error
333 # copy and clear last_syntax_error
395 err = self.SyntaxTB.clear_err_state()
334 err = self.SyntaxTB.clear_err_state()
396 if not self._should_recompile(err):
335 if not self._should_recompile(err):
397 return
336 return
398 try:
337 try:
399 # may set last_syntax_error again if a SyntaxError is raised
338 # may set last_syntax_error again if a SyntaxError is raised
400 self.safe_execfile(err.filename,self.user_ns)
339 self.safe_execfile(err.filename,self.user_ns)
401 except:
340 except:
402 self.showtraceback()
341 self.showtraceback()
403 else:
342 else:
404 try:
343 try:
405 f = file(err.filename)
344 f = file(err.filename)
406 try:
345 try:
407 # This should be inside a display_trap block and I
346 # This should be inside a display_trap block and I
408 # think it is.
347 # think it is.
409 sys.displayhook(f.read())
348 sys.displayhook(f.read())
410 finally:
349 finally:
411 f.close()
350 f.close()
412 except:
351 except:
413 self.showtraceback()
352 self.showtraceback()
414
353
415 def _should_recompile(self,e):
354 def _should_recompile(self,e):
416 """Utility routine for edit_syntax_error"""
355 """Utility routine for edit_syntax_error"""
417
356
418 if e.filename in ('<ipython console>','<input>','<string>',
357 if e.filename in ('<ipython console>','<input>','<string>',
419 '<console>','<BackgroundJob compilation>',
358 '<console>','<BackgroundJob compilation>',
420 None):
359 None):
421
360
422 return False
361 return False
423 try:
362 try:
424 if (self.autoedit_syntax and
363 if (self.autoedit_syntax and
425 not self.ask_yes_no('Return to editor to correct syntax error? '
364 not self.ask_yes_no('Return to editor to correct syntax error? '
426 '[Y/n] ','y')):
365 '[Y/n] ','y')):
427 return False
366 return False
428 except EOFError:
367 except EOFError:
429 return False
368 return False
430
369
431 def int0(x):
370 def int0(x):
432 try:
371 try:
433 return int(x)
372 return int(x)
434 except TypeError:
373 except TypeError:
435 return 0
374 return 0
436 # always pass integer line and offset values to editor hook
375 # always pass integer line and offset values to editor hook
437 try:
376 try:
438 self.hooks.fix_error_editor(e.filename,
377 self.hooks.fix_error_editor(e.filename,
439 int0(e.lineno),int0(e.offset),e.msg)
378 int0(e.lineno),int0(e.offset),e.msg)
440 except TryNext:
379 except TryNext:
441 warn('Could not open editor')
380 warn('Could not open editor')
442 return False
381 return False
443 return True
382 return True
444
383
445 #-------------------------------------------------------------------------
384 #-------------------------------------------------------------------------
446 # Things related to GUI support and pylab
385 # Things related to GUI support and pylab
447 #-------------------------------------------------------------------------
386 #-------------------------------------------------------------------------
448
387
449 def enable_pylab(self, gui=None):
388 def enable_pylab(self, gui=None):
450 """Activate pylab support at runtime.
389 """Activate pylab support at runtime.
451
390
452 This turns on support for matplotlib, preloads into the interactive
391 This turns on support for matplotlib, preloads into the interactive
453 namespace all of numpy and pylab, and configures IPython to correcdtly
392 namespace all of numpy and pylab, and configures IPython to correcdtly
454 interact with the GUI event loop. The GUI backend to be used can be
393 interact with the GUI event loop. The GUI backend to be used can be
455 optionally selected with the optional :param:`gui` argument.
394 optionally selected with the optional :param:`gui` argument.
456
395
457 Parameters
396 Parameters
458 ----------
397 ----------
459 gui : optional, string
398 gui : optional, string
460
399
461 If given, dictates the choice of matplotlib GUI backend to use
400 If given, dictates the choice of matplotlib GUI backend to use
462 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
401 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
463 'gtk'), otherwise we use the default chosen by matplotlib (as
402 'gtk'), otherwise we use the default chosen by matplotlib (as
464 dictated by the matplotlib build-time options plus the user's
403 dictated by the matplotlib build-time options plus the user's
465 matplotlibrc configuration file).
404 matplotlibrc configuration file).
466 """
405 """
467 # We want to prevent the loading of pylab to pollute the user's
406 # We want to prevent the loading of pylab to pollute the user's
468 # namespace as shown by the %who* magics, so we execute the activation
407 # namespace as shown by the %who* magics, so we execute the activation
469 # code in an empty namespace, and we update *both* user_ns and
408 # code in an empty namespace, and we update *both* user_ns and
470 # user_ns_hidden with this information.
409 # user_ns_hidden with this information.
471 ns = {}
410 ns = {}
472 gui = pylab_activate(ns, gui)
411 gui = pylab_activate(ns, gui)
473 self.user_ns.update(ns)
412 self.user_ns.update(ns)
474 self.user_ns_hidden.update(ns)
413 self.user_ns_hidden.update(ns)
475 # Now we must activate the gui pylab wants to use, and fix %run to take
414 # Now we must activate the gui pylab wants to use, and fix %run to take
476 # plot updates into account
415 # plot updates into account
477 enable_gui(gui)
416 enable_gui(gui)
478 self.magic_run = self._pylab_magic_run
417 self.magic_run = self._pylab_magic_run
479
418
480 #-------------------------------------------------------------------------
419 #-------------------------------------------------------------------------
481 # Things related to exiting
420 # Things related to exiting
482 #-------------------------------------------------------------------------
421 #-------------------------------------------------------------------------
483
422
484 def ask_exit(self):
423 def ask_exit(self):
485 """ Ask the shell to exit. Can be overiden and used as a callback. """
424 """ Ask the shell to exit. Can be overiden and used as a callback. """
486 self.exit_now = True
425 self.exit_now = True
487
426
488 def exit(self):
427 def exit(self):
489 """Handle interactive exit.
428 """Handle interactive exit.
490
429
491 This method calls the ask_exit callback."""
430 This method calls the ask_exit callback."""
492 if self.confirm_exit:
431 if self.confirm_exit:
493 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
432 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
494 self.ask_exit()
433 self.ask_exit()
495 else:
434 else:
496 self.ask_exit()
435 self.ask_exit()
497
436
498 #------------------------------------------------------------------------
437 #------------------------------------------------------------------------
499 # Magic overrides
438 # Magic overrides
500 #------------------------------------------------------------------------
439 #------------------------------------------------------------------------
501 # Once the base class stops inheriting from magic, this code needs to be
440 # Once the base class stops inheriting from magic, this code needs to be
502 # moved into a separate machinery as well. For now, at least isolate here
441 # moved into a separate machinery as well. For now, at least isolate here
503 # the magics which this class needs to implement differently from the base
442 # the magics which this class needs to implement differently from the base
504 # class, or that are unique to it.
443 # class, or that are unique to it.
505
444
506 def magic_autoindent(self, parameter_s = ''):
445 def magic_autoindent(self, parameter_s = ''):
507 """Toggle autoindent on/off (if available)."""
446 """Toggle autoindent on/off (if available)."""
508
447
509 self.shell.set_autoindent()
448 self.shell.set_autoindent()
510 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
449 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
511
450
512 @testdec.skip_doctest
451 @testdec.skip_doctest
513 def magic_cpaste(self, parameter_s=''):
452 def magic_cpaste(self, parameter_s=''):
514 """Paste & execute a pre-formatted code block from clipboard.
453 """Paste & execute a pre-formatted code block from clipboard.
515
454
516 You must terminate the block with '--' (two minus-signs) alone on the
455 You must terminate the block with '--' (two minus-signs) alone on the
517 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
456 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
518 is the new sentinel for this operation)
457 is the new sentinel for this operation)
519
458
520 The block is dedented prior to execution to enable execution of method
459 The block is dedented prior to execution to enable execution of method
521 definitions. '>' and '+' characters at the beginning of a line are
460 definitions. '>' and '+' characters at the beginning of a line are
522 ignored, to allow pasting directly from e-mails, diff files and
461 ignored, to allow pasting directly from e-mails, diff files and
523 doctests (the '...' continuation prompt is also stripped). The
462 doctests (the '...' continuation prompt is also stripped). The
524 executed block is also assigned to variable named 'pasted_block' for
463 executed block is also assigned to variable named 'pasted_block' for
525 later editing with '%edit pasted_block'.
464 later editing with '%edit pasted_block'.
526
465
527 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
466 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
528 This assigns the pasted block to variable 'foo' as string, without
467 This assigns the pasted block to variable 'foo' as string, without
529 dedenting or executing it (preceding >>> and + is still stripped)
468 dedenting or executing it (preceding >>> and + is still stripped)
530
469
531 '%cpaste -r' re-executes the block previously entered by cpaste.
470 '%cpaste -r' re-executes the block previously entered by cpaste.
532
471
533 Do not be alarmed by garbled output on Windows (it's a readline bug).
472 Do not be alarmed by garbled output on Windows (it's a readline bug).
534 Just press enter and type -- (and press enter again) and the block
473 Just press enter and type -- (and press enter again) and the block
535 will be what was just pasted.
474 will be what was just pasted.
536
475
537 IPython statements (magics, shell escapes) are not supported (yet).
476 IPython statements (magics, shell escapes) are not supported (yet).
538
477
539 See also
478 See also
540 --------
479 --------
541 paste: automatically pull code from clipboard.
480 paste: automatically pull code from clipboard.
542
481
543 Examples
482 Examples
544 --------
483 --------
545 ::
484 ::
546
485
547 In [8]: %cpaste
486 In [8]: %cpaste
548 Pasting code; enter '--' alone on the line to stop.
487 Pasting code; enter '--' alone on the line to stop.
549 :>>> a = ["world!", "Hello"]
488 :>>> a = ["world!", "Hello"]
550 :>>> print " ".join(sorted(a))
489 :>>> print " ".join(sorted(a))
551 :--
490 :--
552 Hello world!
491 Hello world!
553 """
492 """
554
493
555 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
494 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
556 par = args.strip()
495 par = args.strip()
557 if opts.has_key('r'):
496 if opts.has_key('r'):
558 self._rerun_pasted()
497 self._rerun_pasted()
559 return
498 return
560
499
561 sentinel = opts.get('s','--')
500 sentinel = opts.get('s','--')
562
501
563 block = self._strip_pasted_lines_for_code(
502 block = self._strip_pasted_lines_for_code(
564 self._get_pasted_lines(sentinel))
503 self._get_pasted_lines(sentinel))
565
504
566 self._execute_block(block, par)
505 self._execute_block(block, par)
567
506
568 def magic_paste(self, parameter_s=''):
507 def magic_paste(self, parameter_s=''):
569 """Paste & execute a pre-formatted code block from clipboard.
508 """Paste & execute a pre-formatted code block from clipboard.
570
509
571 The text is pulled directly from the clipboard without user
510 The text is pulled directly from the clipboard without user
572 intervention and printed back on the screen before execution (unless
511 intervention and printed back on the screen before execution (unless
573 the -q flag is given to force quiet mode).
512 the -q flag is given to force quiet mode).
574
513
575 The block is dedented prior to execution to enable execution of method
514 The block is dedented prior to execution to enable execution of method
576 definitions. '>' and '+' characters at the beginning of a line are
515 definitions. '>' and '+' characters at the beginning of a line are
577 ignored, to allow pasting directly from e-mails, diff files and
516 ignored, to allow pasting directly from e-mails, diff files and
578 doctests (the '...' continuation prompt is also stripped). The
517 doctests (the '...' continuation prompt is also stripped). The
579 executed block is also assigned to variable named 'pasted_block' for
518 executed block is also assigned to variable named 'pasted_block' for
580 later editing with '%edit pasted_block'.
519 later editing with '%edit pasted_block'.
581
520
582 You can also pass a variable name as an argument, e.g. '%paste foo'.
521 You can also pass a variable name as an argument, e.g. '%paste foo'.
583 This assigns the pasted block to variable 'foo' as string, without
522 This assigns the pasted block to variable 'foo' as string, without
584 dedenting or executing it (preceding >>> and + is still stripped)
523 dedenting or executing it (preceding >>> and + is still stripped)
585
524
586 Options
525 Options
587 -------
526 -------
588
527
589 -r: re-executes the block previously entered by cpaste.
528 -r: re-executes the block previously entered by cpaste.
590
529
591 -q: quiet mode: do not echo the pasted text back to the terminal.
530 -q: quiet mode: do not echo the pasted text back to the terminal.
592
531
593 IPython statements (magics, shell escapes) are not supported (yet).
532 IPython statements (magics, shell escapes) are not supported (yet).
594
533
595 See also
534 See also
596 --------
535 --------
597 cpaste: manually paste code into terminal until you mark its end.
536 cpaste: manually paste code into terminal until you mark its end.
598 """
537 """
599 opts,args = self.parse_options(parameter_s,'rq',mode='string')
538 opts,args = self.parse_options(parameter_s,'rq',mode='string')
600 par = args.strip()
539 par = args.strip()
601 if opts.has_key('r'):
540 if opts.has_key('r'):
602 self._rerun_pasted()
541 self._rerun_pasted()
603 return
542 return
604
543
605 text = self.shell.hooks.clipboard_get()
544 text = self.shell.hooks.clipboard_get()
606 block = self._strip_pasted_lines_for_code(text.splitlines())
545 block = self._strip_pasted_lines_for_code(text.splitlines())
607
546
608 # By default, echo back to terminal unless quiet mode is requested
547 # By default, echo back to terminal unless quiet mode is requested
609 if not opts.has_key('q'):
548 if not opts.has_key('q'):
610 write = self.shell.write
549 write = self.shell.write
611 write(self.shell.pycolorize(block))
550 write(self.shell.pycolorize(block))
612 if not block.endswith('\n'):
551 if not block.endswith('\n'):
613 write('\n')
552 write('\n')
614 write("## -- End pasted text --\n")
553 write("## -- End pasted text --\n")
615
554
616 self._execute_block(block, par)
555 self._execute_block(block, par)
617
556
618
557
619 InteractiveShellABC.register(TerminalInteractiveShell)
558 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now