##// END OF EJS Templates
Make `x.__doc__` a reasonable default color.
Matthias Bussonnier -
Show More
@@ -1,645 +1,646 b''
1 1 """IPython terminal interface using prompt_toolkit"""
2 2
3 3 import asyncio
4 4 import os
5 5 import sys
6 6 import warnings
7 7 from warnings import warn
8 8
9 9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
10 10 from IPython.utils import io
11 11 from IPython.utils.py3compat import input
12 12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
13 13 from IPython.utils.process import abbrev_cwd
14 14 from traitlets import (
15 15 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
16 16 Any, validate
17 17 )
18 18
19 19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
20 20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
21 21 from prompt_toolkit.formatted_text import PygmentsTokens
22 22 from prompt_toolkit.history import InMemoryHistory
23 23 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
24 24 from prompt_toolkit.output import ColorDepth
25 25 from prompt_toolkit.patch_stdout import patch_stdout
26 26 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
27 27 from prompt_toolkit.styles import DynamicStyle, merge_styles
28 28 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
29 29 from prompt_toolkit import __version__ as ptk_version
30 30
31 31 from pygments.styles import get_style_by_name
32 32 from pygments.style import Style
33 33 from pygments.token import Token
34 34
35 35 from .debugger import TerminalPdb, Pdb
36 36 from .magics import TerminalMagics
37 37 from .pt_inputhooks import get_inputhook_name_and_func
38 38 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
39 39 from .ptutils import IPythonPTCompleter, IPythonPTLexer
40 40 from .shortcuts import create_ipython_shortcuts
41 41
42 42 DISPLAY_BANNER_DEPRECATED = object()
43 43 PTK3 = ptk_version.startswith('3.')
44 44
45 45
46 46 class _NoStyle(Style): pass
47 47
48 48
49 49
50 50 _style_overrides_light_bg = {
51 51 Token.Prompt: '#0000ff',
52 52 Token.PromptNum: '#0000ee bold',
53 53 Token.OutPrompt: '#cc0000',
54 54 Token.OutPromptNum: '#bb0000 bold',
55 55 }
56 56
57 57 _style_overrides_linux = {
58 58 Token.Prompt: '#00cc00',
59 59 Token.PromptNum: '#00bb00 bold',
60 60 Token.OutPrompt: '#cc0000',
61 61 Token.OutPromptNum: '#bb0000 bold',
62 62 }
63 63
64 64 def get_default_editor():
65 65 try:
66 66 return os.environ['EDITOR']
67 67 except KeyError:
68 68 pass
69 69 except UnicodeError:
70 70 warn("$EDITOR environment variable is not pure ASCII. Using platform "
71 71 "default editor.")
72 72
73 73 if os.name == 'posix':
74 74 return 'vi' # the only one guaranteed to be there!
75 75 else:
76 76 return 'notepad' # same in Windows!
77 77
78 78 # conservatively check for tty
79 79 # overridden streams can result in things like:
80 80 # - sys.stdin = None
81 81 # - no isatty method
82 82 for _name in ('stdin', 'stdout', 'stderr'):
83 83 _stream = getattr(sys, _name)
84 84 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
85 85 _is_tty = False
86 86 break
87 87 else:
88 88 _is_tty = True
89 89
90 90
91 91 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
92 92
93 93 def black_reformat_handler(text_before_cursor):
94 94 import black
95 95 formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
96 96 if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
97 97 formatted_text = formatted_text[:-1]
98 98 return formatted_text
99 99
100 100
101 101 class TerminalInteractiveShell(InteractiveShell):
102 102 mime_renderers = Dict().tag(config=True)
103 103
104 104 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
105 105 'to reserve for the tab completion menu, '
106 106 'search history, ...etc, the height of '
107 107 'these menus will at most this value. '
108 108 'Increase it is you prefer long and skinny '
109 109 'menus, decrease for short and wide.'
110 110 ).tag(config=True)
111 111
112 112 pt_app = None
113 113 debugger_history = None
114 114
115 115 simple_prompt = Bool(_use_simple_prompt,
116 116 help="""Use `raw_input` for the REPL, without completion and prompt colors.
117 117
118 118 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
119 119 IPython own testing machinery, and emacs inferior-shell integration through elpy.
120 120
121 121 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
122 122 environment variable is set, or the current terminal is not a tty."""
123 123 ).tag(config=True)
124 124
125 125 @property
126 126 def debugger_cls(self):
127 127 return Pdb if self.simple_prompt else TerminalPdb
128 128
129 129 confirm_exit = Bool(True,
130 130 help="""
131 131 Set to confirm when you try to exit IPython with an EOF (Control-D
132 132 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
133 133 you can force a direct exit without any confirmation.""",
134 134 ).tag(config=True)
135 135
136 136 editing_mode = Unicode('emacs',
137 137 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
138 138 ).tag(config=True)
139 139
140 140 autoformatter = Unicode(None,
141 141 help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
142 142 allow_none=True
143 143 ).tag(config=True)
144 144
145 145 mouse_support = Bool(False,
146 146 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
147 147 ).tag(config=True)
148 148
149 149 # We don't load the list of styles for the help string, because loading
150 150 # Pygments plugins takes time and can cause unexpected errors.
151 151 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
152 152 help="""The name or class of a Pygments style to use for syntax
153 153 highlighting. To see available styles, run `pygmentize -L styles`."""
154 154 ).tag(config=True)
155 155
156 156 @validate('editing_mode')
157 157 def _validate_editing_mode(self, proposal):
158 158 if proposal['value'].lower() == 'vim':
159 159 proposal['value']= 'vi'
160 160 elif proposal['value'].lower() == 'default':
161 161 proposal['value']= 'emacs'
162 162
163 163 if hasattr(EditingMode, proposal['value'].upper()):
164 164 return proposal['value'].lower()
165 165
166 166 return self.editing_mode
167 167
168 168
169 169 @observe('editing_mode')
170 170 def _editing_mode(self, change):
171 171 u_mode = change.new.upper()
172 172 if self.pt_app:
173 173 self.pt_app.editing_mode = u_mode
174 174
175 175 @observe('autoformatter')
176 176 def _autoformatter_changed(self, change):
177 177 formatter = change.new
178 178 if formatter is None:
179 179 self.reformat_handler = lambda x:x
180 180 elif formatter == 'black':
181 181 self.reformat_handler = black_reformat_handler
182 182 else:
183 183 raise ValueError
184 184
185 185 @observe('highlighting_style')
186 186 @observe('colors')
187 187 def _highlighting_style_changed(self, change):
188 188 self.refresh_style()
189 189
190 190 def refresh_style(self):
191 191 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
192 192
193 193
194 194 highlighting_style_overrides = Dict(
195 195 help="Override highlighting format for specific tokens"
196 196 ).tag(config=True)
197 197
198 198 true_color = Bool(False,
199 199 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
200 200 "If your terminal supports true color, the following command "
201 201 "should print 'TRUECOLOR' in orange: "
202 202 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
203 203 ).tag(config=True)
204 204
205 205 editor = Unicode(get_default_editor(),
206 206 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
207 207 ).tag(config=True)
208 208
209 209 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
210 210
211 211 prompts = Instance(Prompts)
212 212
213 213 @default('prompts')
214 214 def _prompts_default(self):
215 215 return self.prompts_class(self)
216 216
217 217 # @observe('prompts')
218 218 # def _(self, change):
219 219 # self._update_layout()
220 220
221 221 @default('displayhook_class')
222 222 def _displayhook_class_default(self):
223 223 return RichPromptDisplayHook
224 224
225 225 term_title = Bool(True,
226 226 help="Automatically set the terminal title"
227 227 ).tag(config=True)
228 228
229 229 term_title_format = Unicode("IPython: {cwd}",
230 230 help="Customize the terminal title format. This is a python format string. " +
231 231 "Available substitutions are: {cwd}."
232 232 ).tag(config=True)
233 233
234 234 display_completions = Enum(('column', 'multicolumn','readlinelike'),
235 235 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
236 236 "'readlinelike'. These options are for `prompt_toolkit`, see "
237 237 "`prompt_toolkit` documentation for more information."
238 238 ),
239 239 default_value='multicolumn').tag(config=True)
240 240
241 241 highlight_matching_brackets = Bool(True,
242 242 help="Highlight matching brackets.",
243 243 ).tag(config=True)
244 244
245 245 extra_open_editor_shortcuts = Bool(False,
246 246 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
247 247 "This is in addition to the F2 binding, which is always enabled."
248 248 ).tag(config=True)
249 249
250 250 handle_return = Any(None,
251 251 help="Provide an alternative handler to be called when the user presses "
252 252 "Return. This is an advanced option intended for debugging, which "
253 253 "may be changed or removed in later releases."
254 254 ).tag(config=True)
255 255
256 256 enable_history_search = Bool(True,
257 257 help="Allows to enable/disable the prompt toolkit history search"
258 258 ).tag(config=True)
259 259
260 260 prompt_includes_vi_mode = Bool(True,
261 261 help="Display the current vi mode (when using vi editing mode)."
262 262 ).tag(config=True)
263 263
264 264 @observe('term_title')
265 265 def init_term_title(self, change=None):
266 266 # Enable or disable the terminal title.
267 267 if self.term_title:
268 268 toggle_set_term_title(True)
269 269 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
270 270 else:
271 271 toggle_set_term_title(False)
272 272
273 273 def restore_term_title(self):
274 274 if self.term_title:
275 275 restore_term_title()
276 276
277 277 def init_display_formatter(self):
278 278 super(TerminalInteractiveShell, self).init_display_formatter()
279 279 # terminal only supports plain text
280 280 self.display_formatter.active_types = ['text/plain']
281 281 # disable `_ipython_display_`
282 282 self.display_formatter.ipython_display_formatter.enabled = False
283 283
284 284 def init_prompt_toolkit_cli(self):
285 285 if self.simple_prompt:
286 286 # Fall back to plain non-interactive output for tests.
287 287 # This is very limited.
288 288 def prompt():
289 289 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
290 290 lines = [input(prompt_text)]
291 291 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
292 292 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
293 293 lines.append( input(prompt_continuation) )
294 294 return '\n'.join(lines)
295 295 self.prompt_for_code = prompt
296 296 return
297 297
298 298 # Set up keyboard shortcuts
299 299 key_bindings = create_ipython_shortcuts(self)
300 300
301 301 # Pre-populate history from IPython's history database
302 302 history = InMemoryHistory()
303 303 last_cell = u""
304 304 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
305 305 include_latest=True):
306 306 # Ignore blank lines and consecutive duplicates
307 307 cell = cell.rstrip()
308 308 if cell and (cell != last_cell):
309 309 history.append_string(cell)
310 310 last_cell = cell
311 311
312 312 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
313 313 self.style = DynamicStyle(lambda: self._style)
314 314
315 315 editing_mode = getattr(EditingMode, self.editing_mode.upper())
316 316
317 317 self.pt_loop = asyncio.new_event_loop()
318 318 self.pt_app = PromptSession(
319 319 editing_mode=editing_mode,
320 320 key_bindings=key_bindings,
321 321 history=history,
322 322 completer=IPythonPTCompleter(shell=self),
323 323 enable_history_search = self.enable_history_search,
324 324 style=self.style,
325 325 include_default_pygments_style=False,
326 326 mouse_support=self.mouse_support,
327 327 enable_open_in_editor=self.extra_open_editor_shortcuts,
328 328 color_depth=self.color_depth,
329 329 tempfile_suffix=".py",
330 330 **self._extra_prompt_options())
331 331
332 332 def _make_style_from_name_or_cls(self, name_or_cls):
333 333 """
334 334 Small wrapper that make an IPython compatible style from a style name
335 335
336 336 We need that to add style for prompt ... etc.
337 337 """
338 338 style_overrides = {}
339 339 if name_or_cls == 'legacy':
340 340 legacy = self.colors.lower()
341 341 if legacy == 'linux':
342 342 style_cls = get_style_by_name('monokai')
343 343 style_overrides = _style_overrides_linux
344 344 elif legacy == 'lightbg':
345 345 style_overrides = _style_overrides_light_bg
346 346 style_cls = get_style_by_name('pastie')
347 347 elif legacy == 'neutral':
348 348 # The default theme needs to be visible on both a dark background
349 349 # and a light background, because we can't tell what the terminal
350 350 # looks like. These tweaks to the default theme help with that.
351 351 style_cls = get_style_by_name('default')
352 352 style_overrides.update({
353 353 Token.Number: '#007700',
354 354 Token.Operator: 'noinherit',
355 355 Token.String: '#BB6622',
356 356 Token.Name.Function: '#2080D0',
357 357 Token.Name.Class: 'bold #2080D0',
358 358 Token.Name.Namespace: 'bold #2080D0',
359 Token.Name.Variable.Magic: '#ansiblue',
359 360 Token.Prompt: '#009900',
360 361 Token.PromptNum: '#ansibrightgreen bold',
361 362 Token.OutPrompt: '#990000',
362 363 Token.OutPromptNum: '#ansibrightred bold',
363 364 })
364 365
365 366 # Hack: Due to limited color support on the Windows console
366 367 # the prompt colors will be wrong without this
367 368 if os.name == 'nt':
368 369 style_overrides.update({
369 370 Token.Prompt: '#ansidarkgreen',
370 371 Token.PromptNum: '#ansigreen bold',
371 372 Token.OutPrompt: '#ansidarkred',
372 373 Token.OutPromptNum: '#ansired bold',
373 374 })
374 375 elif legacy =='nocolor':
375 376 style_cls=_NoStyle
376 377 style_overrides = {}
377 378 else :
378 379 raise ValueError('Got unknown colors: ', legacy)
379 380 else :
380 381 if isinstance(name_or_cls, str):
381 382 style_cls = get_style_by_name(name_or_cls)
382 383 else:
383 384 style_cls = name_or_cls
384 385 style_overrides = {
385 386 Token.Prompt: '#009900',
386 387 Token.PromptNum: '#ansibrightgreen bold',
387 388 Token.OutPrompt: '#990000',
388 389 Token.OutPromptNum: '#ansibrightred bold',
389 390 }
390 391 style_overrides.update(self.highlighting_style_overrides)
391 392 style = merge_styles([
392 393 style_from_pygments_cls(style_cls),
393 394 style_from_pygments_dict(style_overrides),
394 395 ])
395 396
396 397 return style
397 398
398 399 @property
399 400 def pt_complete_style(self):
400 401 return {
401 402 'multicolumn': CompleteStyle.MULTI_COLUMN,
402 403 'column': CompleteStyle.COLUMN,
403 404 'readlinelike': CompleteStyle.READLINE_LIKE,
404 405 }[self.display_completions]
405 406
406 407 @property
407 408 def color_depth(self):
408 409 return (ColorDepth.TRUE_COLOR if self.true_color else None)
409 410
410 411 def _extra_prompt_options(self):
411 412 """
412 413 Return the current layout option for the current Terminal InteractiveShell
413 414 """
414 415 def get_message():
415 416 return PygmentsTokens(self.prompts.in_prompt_tokens())
416 417
417 418 if self.editing_mode == 'emacs':
418 419 # with emacs mode the prompt is (usually) static, so we call only
419 420 # the function once. With VI mode it can toggle between [ins] and
420 421 # [nor] so we can't precompute.
421 422 # here I'm going to favor the default keybinding which almost
422 423 # everybody uses to decrease CPU usage.
423 424 # if we have issues with users with custom Prompts we can see how to
424 425 # work around this.
425 426 get_message = get_message()
426 427
427 428 options = {
428 429 'complete_in_thread': False,
429 430 'lexer':IPythonPTLexer(),
430 431 'reserve_space_for_menu':self.space_for_menu,
431 432 'message': get_message,
432 433 'prompt_continuation': (
433 434 lambda width, lineno, is_soft_wrap:
434 435 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
435 436 'multiline': True,
436 437 'complete_style': self.pt_complete_style,
437 438
438 439 # Highlight matching brackets, but only when this setting is
439 440 # enabled, and only when the DEFAULT_BUFFER has the focus.
440 441 'input_processors': [ConditionalProcessor(
441 442 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
442 443 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
443 444 Condition(lambda: self.highlight_matching_brackets))],
444 445 }
445 446 if not PTK3:
446 447 options['inputhook'] = self.inputhook
447 448
448 449 return options
449 450
450 451 def prompt_for_code(self):
451 452 if self.rl_next_input:
452 453 default = self.rl_next_input
453 454 self.rl_next_input = None
454 455 else:
455 456 default = ''
456 457
457 458 # In order to make sure that asyncio code written in the
458 459 # interactive shell doesn't interfere with the prompt, we run the
459 460 # prompt in a different event loop.
460 461 # If we don't do this, people could spawn coroutine with a
461 462 # while/true inside which will freeze the prompt.
462 463
463 464 try:
464 465 old_loop = asyncio.get_event_loop()
465 466 except RuntimeError:
466 467 # This happens when the user used `asyncio.run()`.
467 468 old_loop = None
468 469
469 470 asyncio.set_event_loop(self.pt_loop)
470 471 try:
471 472 with patch_stdout(raw=True):
472 473 text = self.pt_app.prompt(
473 474 default=default,
474 475 **self._extra_prompt_options())
475 476 finally:
476 477 # Restore the original event loop.
477 478 asyncio.set_event_loop(old_loop)
478 479
479 480 return text
480 481
481 482 def enable_win_unicode_console(self):
482 483 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
483 484 # console by default, so WUC shouldn't be needed.
484 485 from warnings import warn
485 486 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
486 487 DeprecationWarning,
487 488 stacklevel=2)
488 489
489 490 def init_io(self):
490 491 if sys.platform not in {'win32', 'cli'}:
491 492 return
492 493
493 494 import colorama
494 495 colorama.init()
495 496
496 497 # For some reason we make these wrappers around stdout/stderr.
497 498 # For now, we need to reset them so all output gets coloured.
498 499 # https://github.com/ipython/ipython/issues/8669
499 500 # io.std* are deprecated, but don't show our own deprecation warnings
500 501 # during initialization of the deprecated API.
501 502 with warnings.catch_warnings():
502 503 warnings.simplefilter('ignore', DeprecationWarning)
503 504 io.stdout = io.IOStream(sys.stdout)
504 505 io.stderr = io.IOStream(sys.stderr)
505 506
506 507 def init_magics(self):
507 508 super(TerminalInteractiveShell, self).init_magics()
508 509 self.register_magics(TerminalMagics)
509 510
510 511 def init_alias(self):
511 512 # The parent class defines aliases that can be safely used with any
512 513 # frontend.
513 514 super(TerminalInteractiveShell, self).init_alias()
514 515
515 516 # Now define aliases that only make sense on the terminal, because they
516 517 # need direct access to the console in a way that we can't emulate in
517 518 # GUI or web frontend
518 519 if os.name == 'posix':
519 520 for cmd in ('clear', 'more', 'less', 'man'):
520 521 self.alias_manager.soft_define_alias(cmd, cmd)
521 522
522 523
523 524 def __init__(self, *args, **kwargs):
524 525 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
525 526 self.init_prompt_toolkit_cli()
526 527 self.init_term_title()
527 528 self.keep_running = True
528 529
529 530 self.debugger_history = InMemoryHistory()
530 531
531 532 def ask_exit(self):
532 533 self.keep_running = False
533 534
534 535 rl_next_input = None
535 536
536 537 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
537 538
538 539 if display_banner is not DISPLAY_BANNER_DEPRECATED:
539 540 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
540 541
541 542 self.keep_running = True
542 543 while self.keep_running:
543 544 print(self.separate_in, end='')
544 545
545 546 try:
546 547 code = self.prompt_for_code()
547 548 except EOFError:
548 549 if (not self.confirm_exit) \
549 550 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
550 551 self.ask_exit()
551 552
552 553 else:
553 554 if code:
554 555 self.run_cell(code, store_history=True)
555 556
556 557 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
557 558 # An extra layer of protection in case someone mashing Ctrl-C breaks
558 559 # out of our internal code.
559 560 if display_banner is not DISPLAY_BANNER_DEPRECATED:
560 561 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
561 562 while True:
562 563 try:
563 564 self.interact()
564 565 break
565 566 except KeyboardInterrupt as e:
566 567 print("\n%s escaped interact()\n" % type(e).__name__)
567 568 finally:
568 569 # An interrupt during the eventloop will mess up the
569 570 # internal state of the prompt_toolkit library.
570 571 # Stopping the eventloop fixes this, see
571 572 # https://github.com/ipython/ipython/pull/9867
572 573 if hasattr(self, '_eventloop'):
573 574 self._eventloop.stop()
574 575
575 576 self.restore_term_title()
576 577
577 578
578 579 _inputhook = None
579 580 def inputhook(self, context):
580 581 if self._inputhook is not None:
581 582 self._inputhook(context)
582 583
583 584 active_eventloop = None
584 585 def enable_gui(self, gui=None):
585 586 if gui and (gui != 'inline') :
586 587 self.active_eventloop, self._inputhook =\
587 588 get_inputhook_name_and_func(gui)
588 589 else:
589 590 self.active_eventloop = self._inputhook = None
590 591
591 592 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
592 593 # this inputhook.
593 594 if PTK3:
594 595 import asyncio
595 596 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
596 597
597 598 if gui == 'asyncio':
598 599 # When we integrate the asyncio event loop, run the UI in the
599 600 # same event loop as the rest of the code. don't use an actual
600 601 # input hook. (Asyncio is not made for nesting event loops.)
601 602 self.pt_loop = asyncio.get_event_loop()
602 603
603 604 elif self._inputhook:
604 605 # If an inputhook was set, create a new asyncio event loop with
605 606 # this inputhook for the prompt.
606 607 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
607 608 else:
608 609 # When there's no inputhook, run the prompt in a separate
609 610 # asyncio event loop.
610 611 self.pt_loop = asyncio.new_event_loop()
611 612
612 613 # Run !system commands directly, not through pipes, so terminal programs
613 614 # work correctly.
614 615 system = InteractiveShell.system_raw
615 616
616 617 def auto_rewrite_input(self, cmd):
617 618 """Overridden from the parent class to use fancy rewriting prompt"""
618 619 if not self.show_rewritten_input:
619 620 return
620 621
621 622 tokens = self.prompts.rewrite_prompt_tokens()
622 623 if self.pt_app:
623 624 print_formatted_text(PygmentsTokens(tokens), end='',
624 625 style=self.pt_app.app.style)
625 626 print(cmd)
626 627 else:
627 628 prompt = ''.join(s for t, s in tokens)
628 629 print(prompt, cmd, sep='')
629 630
630 631 _prompts_before = None
631 632 def switch_doctest_mode(self, mode):
632 633 """Switch prompts to classic for %doctest_mode"""
633 634 if mode:
634 635 self._prompts_before = self.prompts
635 636 self.prompts = ClassicPrompts(self)
636 637 elif self._prompts_before:
637 638 self.prompts = self._prompts_before
638 639 self._prompts_before = None
639 640 # self._update_layout()
640 641
641 642
642 643 InteractiveShellABC.register(TerminalInteractiveShell)
643 644
644 645 if __name__ == '__main__':
645 646 TerminalInteractiveShell.instance().interact()
General Comments 0
You need to be logged in to leave comments. Login now