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