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