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