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