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