##// END OF EJS Templates
Properly clean up input for interactive pasting....
Fernando Perez -
Show More
@@ -1,676 +1,727 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-2011 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 bdb
18 18 import os
19 19 import re
20 20 import sys
21 21 import textwrap
22 22
23 23 # We need to use nested to support python 2.6, once we move to >=2.7, we can
24 24 # use the with keyword's new builtin support for nested managers
25 25 try:
26 26 from contextlib import nested
27 27 except:
28 28 from IPython.utils.nested_context import nested
29 29
30 30 from IPython.core.error import TryNext, UsageError
31 31 from IPython.core.usage import interactive_usage, default_banner
32 from IPython.core.inputsplitter import IPythonInputSplitter
32 33 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
33 34 from IPython.core.magic import Magics, magics_class, line_magic
34 35 from IPython.testing.skipdoctest import skip_doctest
35 36 from IPython.utils.encoding import get_stream_enc
36 37 from IPython.utils import py3compat
37 38 from IPython.utils.terminal import toggle_set_term_title, set_term_title
38 39 from IPython.utils.process import abbrev_cwd
39 40 from IPython.utils.warn import warn, error
40 from IPython.utils.text import num_ini_spaces, SList
41 from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes
41 42 from IPython.utils.traitlets import Integer, CBool, Unicode
42 43
43 44 #-----------------------------------------------------------------------------
44 45 # Utilities
45 46 #-----------------------------------------------------------------------------
46 47
47 48 def get_default_editor():
48 49 try:
49 50 ed = os.environ['EDITOR']
50 51 except KeyError:
51 52 if os.name == 'posix':
52 53 ed = 'vi' # the only one guaranteed to be there!
53 54 else:
54 55 ed = 'notepad' # same in Windows!
55 56 return ed
56 57
57 58
58 59 def get_pasted_lines(sentinel, l_input=py3compat.input):
59 60 """ Yield pasted lines until the user enters the given sentinel value.
60 61 """
61 62 print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
62 63 % sentinel
63 64 while True:
64 65 try:
65 66 l = l_input(':')
66 67 if l == sentinel:
67 68 return
68 69 else:
69 70 yield l
70 71 except EOFError:
71 72 print '<EOF>'
72 73 return
73 74
74 75
75 def strip_email_quotes(raw_lines):
76 """ Strip email quotation marks at the beginning of each line.
77
78 We don't do any more input transofrmations here because the main shell's
79 prefiltering handles other cases.
80 """
81 lines = [re.sub(r'^\s*(\s?>)+', '', l) for l in raw_lines]
82 return '\n'.join(lines) + '\n'
83
84
85 76 #------------------------------------------------------------------------
86 77 # Terminal-specific magics
87 78 #------------------------------------------------------------------------
88 79
89 80 @magics_class
90 81 class TerminalMagics(Magics):
82 def __init__(self, shell):
83 super(TerminalMagics, self).__init__(shell)
84 self.input_splitter = IPythonInputSplitter(input_mode='line')
85
86 def cleanup_input(block):
87 """Apply all possible IPython cleanups to an input block.
88
89 This means:
90
91 - remove any global leading whitespace (dedent)
92 - remove any email quotes ('>') if they are present in *all* lines
93 - apply all static inputsplitter transforms and break into sub-blocks
94 - apply prefilter() to each sub-block that is a single line.
95
96 Parameters
97 ----------
98 block : str
99 A possibly multiline input string of code.
100
101 Returns
102 -------
103 transformed block : str
104 The input, with all transformations above applied.
105 """
106 # We have to effectively implement client-side the loop that is done by
107 # the terminal frontend, and furthermore do it on a block that can
108 # possibly contain multiple statments pasted in one go.
109
110 # First, run the input through the block splitting code. We should
111 # eventually make this a self-contained method in the inputsplitter.
112 isp = self.input_splitter
113 isp.reset()
114 b = textwrap.dedent(block)
115
116 # Remove email quotes first. These must be consistently applied to
117 # *all* lines to be removed
118 b = strip_email_quotes(b)
119
120 # Split the input into independent sub-blocks so we can later do
121 # prefiltering (which must be done *only* to single-line inputs)
122 blocks = []
123 last_block = []
124 for line in b.splitlines():
125 isp.push(line)
126 last_block.append(line)
127 if not isp.push_accepts_more():
128 blocks.append(isp.source_reset())
129 last_block = []
130 if last_block:
131 blocks.append('\n'.join(last_block))
132
133 # Now, apply prefiltering to any one-line block to match the behavior
134 # of the interactive terminal
135 final_blocks = []
136 for block in blocks:
137 lines = block.splitlines()
138 if len(lines) == 1:
139 final_blocks.append(self.shell.prefilter(lines[0]))
140 else:
141 final_blocks.append(block)
142
143 # We now have the final version of the input code as a list of blocks,
144 # with all inputsplitter transformations applied and single-line blocks
145 # run through prefilter. For further processing, turn into a single
146 # string as the rest of our apis use string inputs.
147 return '\n'.join(final_blocks)
91 148
92 149 def store_or_execute(self, block, name):
93 150 """ Execute a block, or store it in a variable, per the user's request.
94 151 """
95 # Dedent and prefilter so what we store matches what is executed by
96 # run_cell.
97 b = self.shell.prefilter(textwrap.dedent(block))
98
152 b = self.cleanup_input(block)
99 153 if name:
100 # If storing it for further editing, run the prefilter on it
154 # If storing it for further editing
101 155 self.shell.user_ns[name] = SList(b.splitlines())
102 156 print "Block assigned to '%s'" % name
103 157 else:
104 158 self.shell.user_ns['pasted_block'] = b
105 159 self.shell.run_cell(b)
106 160
107
108 161 def rerun_pasted(self, name='pasted_block'):
109 162 """ Rerun a previously pasted command.
110 163 """
111 164 b = self.shell.user_ns.get(name)
112 165
113 166 # Sanity checks
114 167 if b is None:
115 168 raise UsageError('No previous pasted block available')
116 169 if not isinstance(b, basestring):
117 170 raise UsageError(
118 171 "Variable 'pasted_block' is not a string, can't execute")
119 172
120 173 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
121 174 self.shell.run_cell(b)
122 175
123 176 @line_magic
124 177 def autoindent(self, parameter_s = ''):
125 178 """Toggle autoindent on/off (if available)."""
126 179
127 180 self.shell.set_autoindent()
128 181 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
129 182
130 183 @skip_doctest
131 184 @line_magic
132 185 def cpaste(self, parameter_s=''):
133 186 """Paste & execute a pre-formatted code block from clipboard.
134 187
135 188 You must terminate the block with '--' (two minus-signs) or Ctrl-D
136 189 alone on the line. You can also provide your own sentinel with '%paste
137 190 -s %%' ('%%' is the new sentinel for this operation)
138 191
139 192 The block is dedented prior to execution to enable execution of method
140 193 definitions. '>' and '+' characters at the beginning of a line are
141 194 ignored, to allow pasting directly from e-mails, diff files and
142 195 doctests (the '...' continuation prompt is also stripped). The
143 196 executed block is also assigned to variable named 'pasted_block' for
144 197 later editing with '%edit pasted_block'.
145 198
146 199 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
147 200 This assigns the pasted block to variable 'foo' as string, without
148 201 dedenting or executing it (preceding >>> and + is still stripped)
149 202
150 203 '%cpaste -r' re-executes the block previously entered by cpaste.
151 204
152 205 Do not be alarmed by garbled output on Windows (it's a readline bug).
153 206 Just press enter and type -- (and press enter again) and the block
154 207 will be what was just pasted.
155 208
156 209 IPython statements (magics, shell escapes) are not supported (yet).
157 210
158 211 See also
159 212 --------
160 213 paste: automatically pull code from clipboard.
161 214
162 215 Examples
163 216 --------
164 217 ::
165 218
166 219 In [8]: %cpaste
167 220 Pasting code; enter '--' alone on the line to stop.
168 221 :>>> a = ["world!", "Hello"]
169 222 :>>> print " ".join(sorted(a))
170 223 :--
171 224 Hello world!
172 225 """
173
174 226 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
175 227 if 'r' in opts:
176 228 self.rerun_pasted()
177 229 return
178 230
179 231 sentinel = opts.get('s', '--')
180 block = strip_email_quotes(get_pasted_lines(sentinel))
232 block = '\n'.join(get_pasted_lines(sentinel))
181 233 self.store_or_execute(block, name)
182 234
183 235 @line_magic
184 236 def paste(self, parameter_s=''):
185 237 """Paste & execute a pre-formatted code block from clipboard.
186 238
187 239 The text is pulled directly from the clipboard without user
188 240 intervention and printed back on the screen before execution (unless
189 241 the -q flag is given to force quiet mode).
190 242
191 243 The block is dedented prior to execution to enable execution of method
192 244 definitions. '>' and '+' characters at the beginning of a line are
193 245 ignored, to allow pasting directly from e-mails, diff files and
194 246 doctests (the '...' continuation prompt is also stripped). The
195 247 executed block is also assigned to variable named 'pasted_block' for
196 248 later editing with '%edit pasted_block'.
197 249
198 250 You can also pass a variable name as an argument, e.g. '%paste foo'.
199 251 This assigns the pasted block to variable 'foo' as string, without
200 dedenting or executing it (preceding >>> and + is still stripped)
252 executing it (preceding >>> and + is still stripped).
201 253
202 254 Options
203 255 -------
204 256
205 257 -r: re-executes the block previously entered by cpaste.
206 258
207 259 -q: quiet mode: do not echo the pasted text back to the terminal.
208 260
209 261 IPython statements (magics, shell escapes) are not supported (yet).
210 262
211 263 See also
212 264 --------
213 265 cpaste: manually paste code into terminal until you mark its end.
214 266 """
215 267 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
216 268 if 'r' in opts:
217 269 self.rerun_pasted()
218 270 return
219 271 try:
220 text = self.shell.hooks.clipboard_get()
221 block = strip_email_quotes(text.splitlines())
272 block = self.shell.hooks.clipboard_get()
222 273 except TryNext as clipboard_exc:
223 274 message = getattr(clipboard_exc, 'args')
224 275 if message:
225 276 error(message[0])
226 277 else:
227 278 error('Could not get text from the clipboard.')
228 279 return
229 280
230 281 # By default, echo back to terminal unless quiet mode is requested
231 282 if 'q' not in opts:
232 283 write = self.shell.write
233 284 write(self.shell.pycolorize(block))
234 285 if not block.endswith('\n'):
235 286 write('\n')
236 287 write("## -- End pasted text --\n")
237 288
238 289 self.store_or_execute(block, name)
239 290
240 291 # Class-level: add a '%cls' magic only on Windows
241 292 if sys.platform == 'win32':
242 293 @line_magic
243 294 def cls(self, s):
244 295 """Clear screen.
245 296 """
246 297 os.system("cls")
247 298
248 299 #-----------------------------------------------------------------------------
249 300 # Main class
250 301 #-----------------------------------------------------------------------------
251 302
252 303 class TerminalInteractiveShell(InteractiveShell):
253 304
254 305 autoedit_syntax = CBool(False, config=True,
255 306 help="auto editing of files with syntax errors.")
256 307 banner = Unicode('')
257 308 banner1 = Unicode(default_banner, config=True,
258 309 help="""The part of the banner to be printed before the profile"""
259 310 )
260 311 banner2 = Unicode('', config=True,
261 312 help="""The part of the banner to be printed after the profile"""
262 313 )
263 314 confirm_exit = CBool(True, config=True,
264 315 help="""
265 316 Set to confirm when you try to exit IPython with an EOF (Control-D
266 317 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
267 318 you can force a direct exit without any confirmation.""",
268 319 )
269 320 # This display_banner only controls whether or not self.show_banner()
270 321 # is called when mainloop/interact are called. The default is False
271 322 # because for the terminal based application, the banner behavior
272 323 # is controlled by Global.display_banner, which IPythonApp looks at
273 324 # to determine if *it* should call show_banner() by hand or not.
274 325 display_banner = CBool(False) # This isn't configurable!
275 326 embedded = CBool(False)
276 327 embedded_active = CBool(False)
277 328 editor = Unicode(get_default_editor(), config=True,
278 329 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
279 330 )
280 331 pager = Unicode('less', config=True,
281 332 help="The shell program to be used for paging.")
282 333
283 334 screen_length = Integer(0, config=True,
284 335 help=
285 336 """Number of lines of your screen, used to control printing of very
286 337 long strings. Strings longer than this number of lines will be sent
287 338 through a pager instead of directly printed. The default value for
288 339 this is 0, which means IPython will auto-detect your screen size every
289 340 time it needs to print certain potentially long strings (this doesn't
290 341 change the behavior of the 'print' keyword, it's only triggered
291 342 internally). If for some reason this isn't working well (it needs
292 343 curses support), specify it yourself. Otherwise don't change the
293 344 default.""",
294 345 )
295 346 term_title = CBool(False, config=True,
296 347 help="Enable auto setting the terminal title."
297 348 )
298 349
299 350 # In the terminal, GUI control is done via PyOS_InputHook
300 351 from IPython.lib.inputhook import enable_gui
301 352 enable_gui = staticmethod(enable_gui)
302 353
303 354 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
304 355 user_ns=None, user_module=None, custom_exceptions=((),None),
305 356 usage=None, banner1=None, banner2=None, display_banner=None):
306 357
307 358 super(TerminalInteractiveShell, self).__init__(
308 359 config=config, profile_dir=profile_dir, user_ns=user_ns,
309 360 user_module=user_module, custom_exceptions=custom_exceptions
310 361 )
311 362 # use os.system instead of utils.process.system by default,
312 363 # because piped system doesn't make sense in the Terminal:
313 364 self.system = self.system_raw
314 365
315 366 self.init_term_title()
316 367 self.init_usage(usage)
317 368 self.init_banner(banner1, banner2, display_banner)
318 369
319 370 #-------------------------------------------------------------------------
320 371 # Things related to the terminal
321 372 #-------------------------------------------------------------------------
322 373
323 374 @property
324 375 def usable_screen_length(self):
325 376 if self.screen_length == 0:
326 377 return 0
327 378 else:
328 379 num_lines_bot = self.separate_in.count('\n')+1
329 380 return self.screen_length - num_lines_bot
330 381
331 382 def init_term_title(self):
332 383 # Enable or disable the terminal title.
333 384 if self.term_title:
334 385 toggle_set_term_title(True)
335 386 set_term_title('IPython: ' + abbrev_cwd())
336 387 else:
337 388 toggle_set_term_title(False)
338 389
339 390 #-------------------------------------------------------------------------
340 391 # Things related to aliases
341 392 #-------------------------------------------------------------------------
342 393
343 394 def init_alias(self):
344 395 # The parent class defines aliases that can be safely used with any
345 396 # frontend.
346 397 super(TerminalInteractiveShell, self).init_alias()
347 398
348 399 # Now define aliases that only make sense on the terminal, because they
349 400 # need direct access to the console in a way that we can't emulate in
350 401 # GUI or web frontend
351 402 if os.name == 'posix':
352 403 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
353 404 ('man', 'man')]
354 405 elif os.name == 'nt':
355 406 aliases = [('cls', 'cls')]
356 407
357 408
358 409 for name, cmd in aliases:
359 410 self.alias_manager.define_alias(name, cmd)
360 411
361 412 #-------------------------------------------------------------------------
362 413 # Things related to the banner and usage
363 414 #-------------------------------------------------------------------------
364 415
365 416 def _banner1_changed(self):
366 417 self.compute_banner()
367 418
368 419 def _banner2_changed(self):
369 420 self.compute_banner()
370 421
371 422 def _term_title_changed(self, name, new_value):
372 423 self.init_term_title()
373 424
374 425 def init_banner(self, banner1, banner2, display_banner):
375 426 if banner1 is not None:
376 427 self.banner1 = banner1
377 428 if banner2 is not None:
378 429 self.banner2 = banner2
379 430 if display_banner is not None:
380 431 self.display_banner = display_banner
381 432 self.compute_banner()
382 433
383 434 def show_banner(self, banner=None):
384 435 if banner is None:
385 436 banner = self.banner
386 437 self.write(banner)
387 438
388 439 def compute_banner(self):
389 440 self.banner = self.banner1
390 441 if self.profile and self.profile != 'default':
391 442 self.banner += '\nIPython profile: %s\n' % self.profile
392 443 if self.banner2:
393 444 self.banner += '\n' + self.banner2
394 445
395 446 def init_usage(self, usage=None):
396 447 if usage is None:
397 448 self.usage = interactive_usage
398 449 else:
399 450 self.usage = usage
400 451
401 452 #-------------------------------------------------------------------------
402 453 # Mainloop and code execution logic
403 454 #-------------------------------------------------------------------------
404 455
405 456 def mainloop(self, display_banner=None):
406 457 """Start the mainloop.
407 458
408 459 If an optional banner argument is given, it will override the
409 460 internally created default banner.
410 461 """
411 462
412 463 with nested(self.builtin_trap, self.display_trap):
413 464
414 465 while 1:
415 466 try:
416 467 self.interact(display_banner=display_banner)
417 468 #self.interact_with_readline()
418 469 # XXX for testing of a readline-decoupled repl loop, call
419 470 # interact_with_readline above
420 471 break
421 472 except KeyboardInterrupt:
422 473 # this should not be necessary, but KeyboardInterrupt
423 474 # handling seems rather unpredictable...
424 475 self.write("\nKeyboardInterrupt in interact()\n")
425 476
426 477 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
427 478 """Store multiple lines as a single entry in history"""
428 479
429 480 # do nothing without readline or disabled multiline
430 481 if not self.has_readline or not self.multiline_history:
431 482 return hlen_before_cell
432 483
433 484 # windows rl has no remove_history_item
434 485 if not hasattr(self.readline, "remove_history_item"):
435 486 return hlen_before_cell
436 487
437 488 # skip empty cells
438 489 if not source_raw.rstrip():
439 490 return hlen_before_cell
440 491
441 492 # nothing changed do nothing, e.g. when rl removes consecutive dups
442 493 hlen = self.readline.get_current_history_length()
443 494 if hlen == hlen_before_cell:
444 495 return hlen_before_cell
445 496
446 497 for i in range(hlen - hlen_before_cell):
447 498 self.readline.remove_history_item(hlen - i - 1)
448 499 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
449 500 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
450 501 stdin_encoding))
451 502 return self.readline.get_current_history_length()
452 503
453 504 def interact(self, display_banner=None):
454 505 """Closely emulate the interactive Python console."""
455 506
456 507 # batch run -> do not interact
457 508 if self.exit_now:
458 509 return
459 510
460 511 if display_banner is None:
461 512 display_banner = self.display_banner
462 513
463 514 if isinstance(display_banner, basestring):
464 515 self.show_banner(display_banner)
465 516 elif display_banner:
466 517 self.show_banner()
467 518
468 519 more = False
469 520
470 521 if self.has_readline:
471 522 self.readline_startup_hook(self.pre_readline)
472 523 hlen_b4_cell = self.readline.get_current_history_length()
473 524 else:
474 525 hlen_b4_cell = 0
475 526 # exit_now is set by a call to %Exit or %Quit, through the
476 527 # ask_exit callback.
477 528
478 529 while not self.exit_now:
479 530 self.hooks.pre_prompt_hook()
480 531 if more:
481 532 try:
482 533 prompt = self.prompt_manager.render('in2')
483 534 except:
484 535 self.showtraceback()
485 536 if self.autoindent:
486 537 self.rl_do_indent = True
487 538
488 539 else:
489 540 try:
490 541 prompt = self.separate_in + self.prompt_manager.render('in')
491 542 except:
492 543 self.showtraceback()
493 544 try:
494 545 line = self.raw_input(prompt)
495 546 if self.exit_now:
496 547 # quick exit on sys.std[in|out] close
497 548 break
498 549 if self.autoindent:
499 550 self.rl_do_indent = False
500 551
501 552 except KeyboardInterrupt:
502 553 #double-guard against keyboardinterrupts during kbdint handling
503 554 try:
504 555 self.write('\nKeyboardInterrupt\n')
505 556 source_raw = self.input_splitter.source_raw_reset()[1]
506 557 hlen_b4_cell = \
507 558 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
508 559 more = False
509 560 except KeyboardInterrupt:
510 561 pass
511 562 except EOFError:
512 563 if self.autoindent:
513 564 self.rl_do_indent = False
514 565 if self.has_readline:
515 566 self.readline_startup_hook(None)
516 567 self.write('\n')
517 568 self.exit()
518 569 except bdb.BdbQuit:
519 570 warn('The Python debugger has exited with a BdbQuit exception.\n'
520 571 'Because of how pdb handles the stack, it is impossible\n'
521 572 'for IPython to properly format this particular exception.\n'
522 573 'IPython will resume normal operation.')
523 574 except:
524 575 # exceptions here are VERY RARE, but they can be triggered
525 576 # asynchronously by signal handlers, for example.
526 577 self.showtraceback()
527 578 else:
528 579 self.input_splitter.push(line)
529 580 more = self.input_splitter.push_accepts_more()
530 581 if (self.SyntaxTB.last_syntax_error and
531 582 self.autoedit_syntax):
532 583 self.edit_syntax_error()
533 584 if not more:
534 585 source_raw = self.input_splitter.source_raw_reset()[1]
535 586 self.run_cell(source_raw, store_history=True)
536 587 hlen_b4_cell = \
537 588 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
538 589
539 590 # Turn off the exit flag, so the mainloop can be restarted if desired
540 591 self.exit_now = False
541 592
542 593 def raw_input(self, prompt=''):
543 594 """Write a prompt and read a line.
544 595
545 596 The returned line does not include the trailing newline.
546 597 When the user enters the EOF key sequence, EOFError is raised.
547 598
548 599 Optional inputs:
549 600
550 601 - prompt(''): a string to be printed to prompt the user.
551 602
552 603 - continue_prompt(False): whether this line is the first one or a
553 604 continuation in a sequence of inputs.
554 605 """
555 606 # Code run by the user may have modified the readline completer state.
556 607 # We must ensure that our completer is back in place.
557 608
558 609 if self.has_readline:
559 610 self.set_readline_completer()
560 611
561 612 # raw_input expects str, but we pass it unicode sometimes
562 613 prompt = py3compat.cast_bytes_py2(prompt)
563 614
564 615 try:
565 616 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
566 617 except ValueError:
567 618 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
568 619 " or sys.stdout.close()!\nExiting IPython!\n")
569 620 self.ask_exit()
570 621 return ""
571 622
572 623 # Try to be reasonably smart about not re-indenting pasted input more
573 624 # than necessary. We do this by trimming out the auto-indent initial
574 625 # spaces, if the user's actual input started itself with whitespace.
575 626 if self.autoindent:
576 627 if num_ini_spaces(line) > self.indent_current_nsp:
577 628 line = line[self.indent_current_nsp:]
578 629 self.indent_current_nsp = 0
579 630
580 631 return line
581 632
582 633 #-------------------------------------------------------------------------
583 634 # Methods to support auto-editing of SyntaxErrors.
584 635 #-------------------------------------------------------------------------
585 636
586 637 def edit_syntax_error(self):
587 638 """The bottom half of the syntax error handler called in the main loop.
588 639
589 640 Loop until syntax error is fixed or user cancels.
590 641 """
591 642
592 643 while self.SyntaxTB.last_syntax_error:
593 644 # copy and clear last_syntax_error
594 645 err = self.SyntaxTB.clear_err_state()
595 646 if not self._should_recompile(err):
596 647 return
597 648 try:
598 649 # may set last_syntax_error again if a SyntaxError is raised
599 650 self.safe_execfile(err.filename,self.user_ns)
600 651 except:
601 652 self.showtraceback()
602 653 else:
603 654 try:
604 655 f = open(err.filename)
605 656 try:
606 657 # This should be inside a display_trap block and I
607 658 # think it is.
608 659 sys.displayhook(f.read())
609 660 finally:
610 661 f.close()
611 662 except:
612 663 self.showtraceback()
613 664
614 665 def _should_recompile(self,e):
615 666 """Utility routine for edit_syntax_error"""
616 667
617 668 if e.filename in ('<ipython console>','<input>','<string>',
618 669 '<console>','<BackgroundJob compilation>',
619 670 None):
620 671
621 672 return False
622 673 try:
623 674 if (self.autoedit_syntax and
624 675 not self.ask_yes_no('Return to editor to correct syntax error? '
625 676 '[Y/n] ','y')):
626 677 return False
627 678 except EOFError:
628 679 return False
629 680
630 681 def int0(x):
631 682 try:
632 683 return int(x)
633 684 except TypeError:
634 685 return 0
635 686 # always pass integer line and offset values to editor hook
636 687 try:
637 688 self.hooks.fix_error_editor(e.filename,
638 689 int0(e.lineno),int0(e.offset),e.msg)
639 690 except TryNext:
640 691 warn('Could not open editor')
641 692 return False
642 693 return True
643 694
644 695 #-------------------------------------------------------------------------
645 696 # Things related to exiting
646 697 #-------------------------------------------------------------------------
647 698
648 699 def ask_exit(self):
649 700 """ Ask the shell to exit. Can be overiden and used as a callback. """
650 701 self.exit_now = True
651 702
652 703 def exit(self):
653 704 """Handle interactive exit.
654 705
655 706 This method calls the ask_exit callback."""
656 707 if self.confirm_exit:
657 708 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
658 709 self.ask_exit()
659 710 else:
660 711 self.ask_exit()
661 712
662 713 #-------------------------------------------------------------------------
663 714 # Things related to magics
664 715 #-------------------------------------------------------------------------
665 716
666 717 def init_magics(self):
667 718 super(TerminalInteractiveShell, self).init_magics()
668 719 self.register_magics(TerminalMagics)
669 720
670 721 def showindentationerror(self):
671 722 super(TerminalInteractiveShell, self).showindentationerror()
672 723 print("If you want to paste code into IPython, try the "
673 724 "%paste and %cpaste magic functions.")
674 725
675 726
676 727 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now