interactiveshell.py
1021 lines
| 37.2 KiB
| text/x-python
|
PythonLexer
Matthias Bussonnier
|
r22557 | """IPython terminal interface using prompt_toolkit""" | ||
Thomas Kluyver
|
r21846 | |||
Min RK
|
r22549 | import os | ||
import sys | ||||
Matthias Bussonnier
|
r28551 | import inspect | ||
Pierre Gerold
|
r22092 | from warnings import warn | ||
Matthias Bussonnier
|
r28399 | from typing import Union as UnionType, Optional | ||
Brian Granger
|
r2761 | |||
Min RK
|
r27387 | from IPython.core.async_helpers import get_asyncio_loop | ||
Min RK
|
r22549 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC | ||
Hugo
|
r24010 | from IPython.utils.py3compat import input | ||
Георгий Фролов
|
r25194 | from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title | ||
Min RK
|
r22549 | from IPython.utils.process import abbrev_cwd | ||
Thomas Kluyver
|
r23580 | from traitlets import ( | ||
Martin Skarzynski
|
r26113 | Bool, | ||
Unicode, | ||||
Dict, | ||||
Integer, | ||||
krassowski
|
r28074 | List, | ||
Martin Skarzynski
|
r26113 | observe, | ||
Instance, | ||||
Type, | ||||
default, | ||||
Enum, | ||||
Union, | ||||
Any, | ||||
validate, | ||||
Float, | ||||
Thomas Kluyver
|
r23580 | ) | ||
Min RK
|
r22549 | |||
Martin Skarzynski
|
r26102 | from prompt_toolkit.auto_suggest import AutoSuggestFromHistory | ||
Thomas Kluyver
|
r22642 | from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode | ||
krassowski
|
r28074 | from prompt_toolkit.filters import HasFocus, Condition, IsDone | ||
Jonathan Slenders
|
r24376 | from prompt_toolkit.formatted_text import PygmentsTokens | ||
Matthias Bussonnier
|
r27595 | from prompt_toolkit.history import History | ||
Min RK
|
r22549 | from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor | ||
Thomas Kluyver
|
r24377 | from prompt_toolkit.output import ColorDepth | ||
Jonathan Slenders
|
r24376 | from prompt_toolkit.patch_stdout import patch_stdout | ||
Thomas Kluyver
|
r24379 | from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text | ||
Jonathan Slenders
|
r24376 | from prompt_toolkit.styles import DynamicStyle, merge_styles | ||
from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict | ||||
Jonathan Slenders
|
r25268 | from prompt_toolkit import __version__ as ptk_version | ||
Min RK
|
r22549 | |||
Thomas Kluyver
|
r23995 | from pygments.styles import get_style_by_name | ||
memeplex
|
r22766 | from pygments.style import Style | ||
Min RK
|
r22549 | from pygments.token import Token | ||
from .debugger import TerminalPdb, Pdb | ||||
from .magics import TerminalMagics | ||||
Thomas Kluyver
|
r22913 | from .pt_inputhooks import get_inputhook_name_and_func | ||
Min RK
|
r22549 | from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook | ||
from .ptutils import IPythonPTCompleter, IPythonPTLexer | ||||
krassowski
|
r28074 | from .shortcuts import ( | ||
krassowski
|
r28191 | KEY_BINDINGS, | ||
krassowski
|
r28074 | create_ipython_shortcuts, | ||
create_identifier, | ||||
RuntimeBinding, | ||||
add_binding, | ||||
) | ||||
from .shortcuts.filters import KEYBINDING_FILTERS, filter_from_string | ||||
krassowski
|
r28041 | from .shortcuts.auto_suggest import ( | ||
NavigableAutoSuggestFromHistory, | ||||
AppendAutoSuggestionInAnyLine, | ||||
) | ||||
Min RK
|
r22549 | |||
Jonathan Slenders
|
r25268 | PTK3 = ptk_version.startswith('3.') | ||
Matthias Bussonnier
|
r22562 | |||
Min RK
|
r22549 | |||
Matthias Bussonnier
|
r28551 | class _NoStyle(Style): | ||
pass | ||||
Matthias Bussonnier
|
r22578 | |||
_style_overrides_light_bg = { | ||||
Tobias Bengfort
|
r25894 | Token.Prompt: '#ansibrightblue', | ||
Token.PromptNum: '#ansiblue bold', | ||||
Token.OutPrompt: '#ansibrightred', | ||||
Token.OutPromptNum: '#ansired bold', | ||||
Matthias Bussonnier
|
r22578 | } | ||
_style_overrides_linux = { | ||||
Tobias Bengfort
|
r25894 | Token.Prompt: '#ansibrightgreen', | ||
Token.PromptNum: '#ansigreen bold', | ||||
Token.OutPrompt: '#ansibrightred', | ||||
Token.OutPromptNum: '#ansired bold', | ||||
Matthias Bussonnier
|
r22578 | } | ||
Matthias Bussonnier
|
r28551 | |||
def _backward_compat_continuation_prompt_tokens(method, width: int, *, lineno: int): | ||||
""" | ||||
Sagemath use custom prompt and we broke them in 8.19. | ||||
""" | ||||
sig = inspect.signature(method) | ||||
if "lineno" in inspect.signature(method).parameters or any( | ||||
[p.kind == p.VAR_KEYWORD for p in sig.parameters.values()] | ||||
): | ||||
return method(width, lineno=lineno) | ||||
else: | ||||
return method(width) | ||||
Min RK
|
r22549 | def get_default_editor(): | ||
try: | ||||
Srinivas Reddy Thatiparthy
|
r23085 | return os.environ['EDITOR'] | ||
Min RK
|
r22549 | except KeyError: | ||
pass | ||||
except UnicodeError: | ||||
warn("$EDITOR environment variable is not pure ASCII. Using platform " | ||||
"default editor.") | ||||
if os.name == 'posix': | ||||
return 'vi' # the only one guaranteed to be there! | ||||
else: | ||||
Matthias Bussonnier
|
r28552 | return "notepad" # same in Windows! | ||
Min RK
|
r22549 | |||
Min RK
|
r22758 | # conservatively check for tty | ||
# overridden streams can result in things like: | ||||
# - sys.stdin = None | ||||
# - no isatty method | ||||
for _name in ('stdin', 'stdout', 'stderr'): | ||||
_stream = getattr(sys, _name) | ||||
Jacob Hall
|
r27749 | try: | ||
if not _stream or not hasattr(_stream, "isatty") or not _stream.isatty(): | ||||
_is_tty = False | ||||
break | ||||
except ValueError: | ||||
# stream is closed | ||||
Min RK
|
r22758 | _is_tty = False | ||
break | ||||
Min RK
|
r22549 | else: | ||
Min RK
|
r22758 | _is_tty = True | ||
Min RK
|
r22549 | |||
_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty) | ||||
Matthias Bussonnier
|
r25142 | def black_reformat_handler(text_before_cursor): | ||
Matthias Bussonnier
|
r27324 | """ | ||
We do not need to protect against error, | ||||
this is taken care at a higher level where any reformat error is ignored. | ||||
Indeed we may call reformatting on incomplete code. | ||||
""" | ||||
Matthias Bussonnier
|
r25142 | import black | ||
Matthias Bussonnier
|
r27324 | |||
Matthias Bussonnier
|
r25142 | formatted_text = black.format_str(text_before_cursor, mode=black.FileMode()) | ||
Matthias Bussonnier
|
r27324 | if not text_before_cursor.endswith("\n") and formatted_text.endswith("\n"): | ||
formatted_text = formatted_text[:-1] | ||||
Matthias Bussonnier
|
r25142 | return formatted_text | ||
Anton Älgmyr
|
r27523 | def yapf_reformat_handler(text_before_cursor): | ||
from yapf.yapflib import file_resources | ||||
from yapf.yapflib import yapf_api | ||||
style_config = file_resources.GetDefaultStyleForDir(os.getcwd()) | ||||
Anton Älgmyr
|
r27524 | formatted_text, was_formatted = yapf_api.FormatCode( | ||
text_before_cursor, style_config=style_config | ||||
) | ||||
Anton Älgmyr
|
r27523 | if was_formatted: | ||
if not text_before_cursor.endswith("\n") and formatted_text.endswith("\n"): | ||||
formatted_text = formatted_text[:-1] | ||||
return formatted_text | ||||
else: | ||||
return text_before_cursor | ||||
Matthias Bussonnier
|
r27595 | class PtkHistoryAdapter(History): | ||
""" | ||||
Prompt toolkit has it's own way of handling history, Where it assumes it can | ||||
Push/pull from history. | ||||
""" | ||||
def __init__(self, shell): | ||||
super().__init__() | ||||
self.shell = shell | ||||
self._refresh() | ||||
def append_string(self, string): | ||||
# we rely on sql for that. | ||||
self._loaded = False | ||||
self._refresh() | ||||
def _refresh(self): | ||||
if not self._loaded: | ||||
self._loaded_strings = list(self.load_history_strings()) | ||||
def load_history_strings(self): | ||||
last_cell = "" | ||||
res = [] | ||||
for __, ___, cell in self.shell.history_manager.get_tail( | ||||
self.shell.history_load_length, include_latest=True | ||||
): | ||||
# Ignore blank lines and consecutive duplicates | ||||
cell = cell.rstrip() | ||||
if cell and (cell != last_cell): | ||||
res.append(cell) | ||||
last_cell = cell | ||||
yield from res[::-1] | ||||
def store_string(self, string: str) -> None: | ||||
pass | ||||
Min RK
|
r22549 | class TerminalInteractiveShell(InteractiveShell): | ||
Matthias Bussonnier
|
r25164 | mime_renderers = Dict().tag(config=True) | ||
Min RK
|
r22549 | space_for_menu = Integer(6, help='Number of line at the bottom of the screen ' | ||
Matthias Bussonnier
|
r25752 | 'to reserve for the tab completion menu, ' | ||
'search history, ...etc, the height of ' | ||||
'these menus will at most this value. ' | ||||
'Increase it is you prefer long and skinny ' | ||||
'menus, decrease for short and wide.' | ||||
Min RK
|
r22549 | ).tag(config=True) | ||
krassowski
|
r28014 | pt_app: UnionType[PromptSession, None] = None | ||
krassowski
|
r28068 | auto_suggest: UnionType[ | ||
AutoSuggestFromHistory, NavigableAutoSuggestFromHistory, None | ||||
] = None | ||||
Min RK
|
r22549 | debugger_history = None | ||
Matthias Bussonnier
|
r26809 | debugger_history_file = Unicode( | ||
"~/.pdbhistory", help="File in which to store and read history" | ||||
).tag(config=True) | ||||
Min RK
|
r22549 | simple_prompt = Bool(_use_simple_prompt, | ||
Ximin Luo
|
r23704 | help="""Use `raw_input` for the REPL, without completion and prompt colors. | ||
Min RK
|
r22549 | |||
Niall Dooley
|
r28732 | Useful when controlling IPython as a subprocess, and piping | ||
STDIN/OUT/ERR. Known usage are: IPython's own testing machinery, | ||||
and emacs' inferior-python subprocess (assuming you have set | ||||
`python-shell-interpreter` to "ipython") available through the | ||||
built-in `M-x run-python` and third party packages such as elpy. | ||||
Min RK
|
r22549 | |||
This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT` | ||||
Matthias Bussonnier
|
r28730 | environment variable is set, or the current terminal is not a tty. | ||
Thus the Default value reported in --help-all, or config will often | ||||
be incorrectly reported. | ||||
""", | ||||
).tag(config=True) | ||||
Min RK
|
r22549 | |||
@property | ||||
def debugger_cls(self): | ||||
return Pdb if self.simple_prompt else TerminalPdb | ||||
confirm_exit = Bool(True, | ||||
help=""" | ||||
Set to confirm when you try to exit IPython with an EOF (Control-D | ||||
in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', | ||||
you can force a direct exit without any confirmation.""", | ||||
).tag(config=True) | ||||
editing_mode = Unicode('emacs', | ||||
help="Shortcut style to use at the prompt. 'vi' or 'emacs'.", | ||||
).tag(config=True) | ||||
Matthias Bussonnier
|
r26091 | emacs_bindings_in_vi_insert_mode = Bool( | ||
True, | ||||
Martin Skarzynski
|
r26067 | help="Add shortcuts from 'emacs' insert mode to 'vi' insert mode.", | ||
).tag(config=True) | ||||
Martin Skarzynski
|
r26113 | modal_cursor = Bool( | ||
True, | ||||
help=""" | ||||
Cursor shape changes depending on vi mode: beam in vi insert mode, | ||||
block in nav mode, underscore in replace mode.""", | ||||
).tag(config=True) | ||||
ttimeoutlen = Float( | ||||
0.01, | ||||
help="""The time in milliseconds that is waited for a key code | ||||
to complete.""", | ||||
).tag(config=True) | ||||
timeoutlen = Float( | ||||
0.5, | ||||
help="""The time in milliseconds that is waited for a mapped key | ||||
sequence to complete.""", | ||||
).tag(config=True) | ||||
Matthias Bussonnier
|
r27324 | autoformatter = Unicode( | ||
Adam Johnson
|
r27543 | None, | ||
Anton Älgmyr
|
r27523 | help="Autoformatter to reformat Terminal code. Can be `'black'`, `'yapf'` or `None`", | ||
Matthias Bussonnier
|
r25142 | allow_none=True | ||
).tag(config=True) | ||||
Martin Skarzynski
|
r27375 | auto_match = Bool( | ||
False, | ||||
help=""" | ||||
Automatically add/delete closing bracket or quote when opening bracket or quote is entered/deleted. | ||||
Brackets: (), [], {} | ||||
Quotes: '', \"\" | ||||
""", | ||||
).tag(config=True) | ||||
Min RK
|
r22549 | mouse_support = Bool(False, | ||
ormung
|
r23846 | help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)" | ||
Min RK
|
r22549 | ).tag(config=True) | ||
Thomas Kluyver
|
r23994 | # We don't load the list of styles for the help string, because loading | ||
# Pygments plugins takes time and can cause unexpected errors. | ||||
memeplex
|
r22766 | highlighting_style = Union([Unicode('legacy'), Type(klass=Style)], | ||
help="""The name or class of a Pygments style to use for syntax | ||||
Thomas Kluyver
|
r23994 | highlighting. To see available styles, run `pygmentize -L styles`.""" | ||
Min RK
|
r22549 | ).tag(config=True) | ||
Matthias Bussonnier
|
r24684 | @validate('editing_mode') | ||
def _validate_editing_mode(self, proposal): | ||||
if proposal['value'].lower() == 'vim': | ||||
proposal['value']= 'vi' | ||||
elif proposal['value'].lower() == 'default': | ||||
proposal['value']= 'emacs' | ||||
if hasattr(EditingMode, proposal['value'].upper()): | ||||
return proposal['value'].lower() | ||||
return self.editing_mode | ||||
Artur Svistunov
|
r26746 | @observe('editing_mode') | ||
Artur Svistunov
|
r26747 | def _editing_mode(self, change): | ||
Matthias Bussonnier
|
r24718 | if self.pt_app: | ||
Artur Svistunov
|
r26748 | self.pt_app.editing_mode = getattr(EditingMode, change.new.upper()) | ||
Jamshed Vesuna
|
r22859 | |||
Matthias Bussonnier
|
r27324 | def _set_formatter(self, formatter): | ||
Matthias Bussonnier
|
r25142 | if formatter is None: | ||
self.reformat_handler = lambda x:x | ||||
elif formatter == 'black': | ||||
self.reformat_handler = black_reformat_handler | ||||
Anton Älgmyr
|
r27525 | elif formatter == "yapf": | ||
Anton Älgmyr
|
r27523 | self.reformat_handler = yapf_reformat_handler | ||
Matthias Bussonnier
|
r25142 | else: | ||
raise ValueError | ||||
Matthias Bussonnier
|
r27324 | @observe("autoformatter") | ||
def _autoformatter_changed(self, change): | ||||
formatter = change.new | ||||
self._set_formatter(formatter) | ||||
Min RK
|
r22549 | @observe('highlighting_style') | ||
Matthias Bussonnier
|
r22578 | @observe('colors') | ||
Min RK
|
r22549 | def _highlighting_style_changed(self, change): | ||
Matthias Bussonnier
|
r22578 | self.refresh_style() | ||
def refresh_style(self): | ||||
memeplex
|
r22766 | self._style = self._make_style_from_name_or_cls(self.highlighting_style) | ||
Min RK
|
r22549 | |||
highlighting_style_overrides = Dict( | ||||
help="Override highlighting format for specific tokens" | ||||
).tag(config=True) | ||||
Jacob Niehus
|
r22682 | true_color = Bool(False, | ||
Reilly Tucker Siemens
|
r26122 | help="""Use 24bit colors instead of 256 colors in prompt highlighting. | ||
If your terminal supports true color, the following command should | ||||
print ``TRUECOLOR`` in orange:: | ||||
printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\" | ||||
""", | ||||
Jacob Niehus
|
r22682 | ).tag(config=True) | ||
Min RK
|
r22549 | editor = Unicode(get_default_editor(), | ||
help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." | ||||
).tag(config=True) | ||||
prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True) | ||||
prompts = Instance(Prompts) | ||||
@default('prompts') | ||||
def _prompts_default(self): | ||||
return self.prompts_class(self) | ||||
Jonathan Slenders
|
r24376 | # @observe('prompts') | ||
# def _(self, change): | ||||
# self._update_layout() | ||||
Min RK
|
r22549 | |||
@default('displayhook_class') | ||||
def _displayhook_class_default(self): | ||||
return RichPromptDisplayHook | ||||
term_title = Bool(True, | ||||
help="Automatically set the terminal title" | ||||
).tag(config=True) | ||||
Tory Haavik
|
r23623 | term_title_format = Unicode("IPython: {cwd}", | ||
help="Customize the terminal title format. This is a python format string. " + | ||||
"Available substitutions are: {cwd}." | ||||
).tag(config=True) | ||||
Jamshed Vesuna
|
r22859 | display_completions = Enum(('column', 'multicolumn','readlinelike'), | ||
michaelpacer
|
r22726 | help= ( "Options for displaying tab completions, 'column', 'multicolumn', and " | ||
"'readlinelike'. These options are for `prompt_toolkit`, see " | ||||
"`prompt_toolkit` documentation for more information." | ||||
michaelpacer
|
r22720 | ), | ||
default_value='multicolumn').tag(config=True) | ||||
Matthias Bussonnier
|
r22554 | |||
Min RK
|
r22549 | highlight_matching_brackets = Bool(True, | ||
Thomas Kluyver
|
r23409 | help="Highlight matching brackets.", | ||
).tag(config=True) | ||||
extra_open_editor_shortcuts = Bool(False, | ||||
help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. " | ||||
"This is in addition to the F2 binding, which is always enabled." | ||||
Min RK
|
r22549 | ).tag(config=True) | ||
Thomas Kluyver
|
r23580 | handle_return = Any(None, | ||
help="Provide an alternative handler to be called when the user presses " | ||||
"Return. This is an advanced option intended for debugging, which " | ||||
"may be changed or removed in later releases." | ||||
).tag(config=True) | ||||
Shailyn javier Ortiz jimenez
|
r24147 | enable_history_search = Bool(True, | ||
help="Allows to enable/disable the prompt toolkit history search" | ||||
).tag(config=True) | ||||
Alexander Steppke
|
r27454 | autosuggestions_provider = Unicode( | ||
krassowski
|
r28014 | "NavigableAutoSuggestFromHistory", | ||
Alexander Steppke
|
r27454 | help="Specifies from which source automatic suggestions are provided. " | ||
krassowski
|
r28014 | "Can be set to ``'NavigableAutoSuggestFromHistory'`` (:kbd:`up` and " | ||
":kbd:`down` swap suggestions), ``'AutoSuggestFromHistory'``, " | ||||
" or ``None`` to disable automatic suggestions. " | ||||
"Default is `'NavigableAutoSuggestFromHistory`'.", | ||||
Alexander Steppke
|
r27454 | allow_none=True, | ||
Alexander Steppke
|
r27433 | ).tag(config=True) | ||
Alexander Steppke
|
r27454 | def _set_autosuggestions(self, provider): | ||
krassowski
|
r28014 | # disconnect old handler | ||
krassowski
|
r28017 | if self.auto_suggest and isinstance( | ||
self.auto_suggest, NavigableAutoSuggestFromHistory | ||||
): | ||||
krassowski
|
r28014 | self.auto_suggest.disconnect() | ||
Alexander Steppke
|
r27454 | if provider is None: | ||
self.auto_suggest = None | ||||
elif provider == "AutoSuggestFromHistory": | ||||
self.auto_suggest = AutoSuggestFromHistory() | ||||
krassowski
|
r28014 | elif provider == "NavigableAutoSuggestFromHistory": | ||
self.auto_suggest = NavigableAutoSuggestFromHistory() | ||||
Alexander Steppke
|
r27454 | else: | ||
raise ValueError("No valid provider.") | ||||
if self.pt_app: | ||||
self.pt_app.auto_suggest = self.auto_suggest | ||||
@observe("autosuggestions_provider") | ||||
def _autosuggestions_provider_changed(self, change): | ||||
provider = change.new | ||||
self._set_autosuggestions(provider) | ||||
krassowski
|
r28074 | shortcuts = List( | ||
trait=Dict( | ||||
key_trait=Enum( | ||||
[ | ||||
"command", | ||||
"match_keys", | ||||
"match_filter", | ||||
"new_keys", | ||||
"new_filter", | ||||
"create", | ||||
] | ||||
), | ||||
per_key_traits={ | ||||
"command": Unicode(), | ||||
"match_keys": List(Unicode()), | ||||
"match_filter": Unicode(), | ||||
"new_keys": List(Unicode()), | ||||
"new_filter": Unicode(), | ||||
krassowski
|
r28077 | "create": Bool(False), | ||
krassowski
|
r28074 | }, | ||
), | ||||
krassowski
|
r28076 | help="""Add, disable or modifying shortcuts. | ||
krassowski
|
r28074 | |||
Each entry on the list should be a dictionary with ``command`` key | ||||
identifying the target function executed by the shortcut and at least | ||||
krassowski
|
r28076 | one of the following: | ||
krassowski
|
r28074 | - ``match_keys``: list of keys used to match an existing shortcut, | ||
- ``match_filter``: shortcut filter used to match an existing shortcut, | ||||
- ``new_keys``: list of keys to set, | ||||
- ``new_filter``: a new shortcut filter to set | ||||
The filters have to be composed of pre-defined verbs and joined by one | ||||
krassowski
|
r28076 | of the following conjunctions: ``&`` (and), ``|`` (or), ``~`` (not). | ||
The pre-defined verbs are: | ||||
{} | ||||
krassowski
|
r28074 | |||
To disable a shortcut set ``new_keys`` to an empty list. | ||||
To add a shortcut add key ``create`` with value ``True``. | ||||
When modifying/disabling shortcuts, ``match_keys``/``match_filter`` can | ||||
be omitted if the provided specification uniquely identifies a shortcut | ||||
to be modified/disabled. When modifying a shortcut ``new_filter`` or | ||||
``new_keys`` can be omitted which will result in reuse of the existing | ||||
filter/keys. | ||||
krassowski
|
r28076 | Only shortcuts defined in IPython (and not default prompt-toolkit | ||
shortcuts) can be modified or disabled. The full list of shortcuts, | ||||
command identifiers and filters is available under | ||||
:ref:`terminal-shortcuts-list`. | ||||
""".format( | ||||
"\n ".join([f"- `{k}`" for k in KEYBINDING_FILTERS]) | ||||
), | ||||
krassowski
|
r28074 | ).tag(config=True) | ||
@observe("shortcuts") | ||||
def _shortcuts_changed(self, change): | ||||
krassowski
|
r28097 | if self.pt_app: | ||
self.pt_app.key_bindings = self._merge_shortcuts(user_shortcuts=change.new) | ||||
def _merge_shortcuts(self, user_shortcuts): | ||||
krassowski
|
r28074 | # rebuild the bindings list from scratch | ||
key_bindings = create_ipython_shortcuts(self) | ||||
# for now we only allow adding shortcuts for commands which are already | ||||
# registered; this is a security precaution. | ||||
known_commands = { | ||||
krassowski
|
r28191 | create_identifier(binding.command): binding.command | ||
for binding in KEY_BINDINGS | ||||
krassowski
|
r28074 | } | ||
shortcuts_to_skip = [] | ||||
shortcuts_to_add = [] | ||||
for shortcut in user_shortcuts: | ||||
command_id = shortcut["command"] | ||||
if command_id not in known_commands: | ||||
allowed_commands = "\n - ".join(known_commands) | ||||
raise ValueError( | ||||
f"{command_id} is not a known shortcut command." | ||||
f" Allowed commands are: \n - {allowed_commands}" | ||||
) | ||||
old_keys = shortcut.get("match_keys", None) | ||||
old_filter = ( | ||||
filter_from_string(shortcut["match_filter"]) | ||||
if "match_filter" in shortcut | ||||
else None | ||||
) | ||||
matching = [ | ||||
binding | ||||
krassowski
|
r28191 | for binding in KEY_BINDINGS | ||
krassowski
|
r28074 | if ( | ||
(old_filter is None or binding.filter == old_filter) | ||||
and (old_keys is None or [k for k in binding.keys] == old_keys) | ||||
krassowski
|
r28191 | and create_identifier(binding.command) == command_id | ||
krassowski
|
r28074 | ) | ||
] | ||||
new_keys = shortcut.get("new_keys", None) | ||||
new_filter = shortcut.get("new_filter", None) | ||||
command = known_commands[command_id] | ||||
creating_new = shortcut.get("create", False) | ||||
modifying_existing = not creating_new and ( | ||||
new_keys is not None or new_filter | ||||
) | ||||
if creating_new and new_keys == []: | ||||
raise ValueError("Cannot add a shortcut without keys") | ||||
if modifying_existing: | ||||
specification = { | ||||
key: shortcut[key] | ||||
for key in ["command", "filter"] | ||||
if key in shortcut | ||||
} | ||||
if len(matching) == 0: | ||||
Matthias Bussonnier
|
r28130 | raise ValueError( | ||
krassowski
|
r28191 | f"No shortcuts matching {specification} found in {KEY_BINDINGS}" | ||
Matthias Bussonnier
|
r28130 | ) | ||
krassowski
|
r28074 | elif len(matching) > 1: | ||
raise ValueError( | ||||
f"Multiple shortcuts matching {specification} found," | ||||
f" please add keys/filter to select one of: {matching}" | ||||
) | ||||
krassowski
|
r28099 | matched = matching[0] | ||
old_filter = matched.filter | ||||
old_keys = list(matched.keys) | ||||
shortcuts_to_skip.append( | ||||
RuntimeBinding( | ||||
command, | ||||
keys=old_keys, | ||||
filter=old_filter, | ||||
krassowski
|
r28074 | ) | ||
krassowski
|
r28099 | ) | ||
krassowski
|
r28074 | |||
if new_keys != []: | ||||
shortcuts_to_add.append( | ||||
krassowski
|
r28099 | RuntimeBinding( | ||
krassowski
|
r28074 | command, | ||
krassowski
|
r28099 | keys=new_keys or old_keys, | ||
filter=filter_from_string(new_filter) | ||||
if new_filter is not None | ||||
else ( | ||||
old_filter | ||||
if old_filter is not None | ||||
else filter_from_string("always") | ||||
), | ||||
krassowski
|
r28074 | ) | ||
) | ||||
# rebuild the bindings list from scratch | ||||
key_bindings = create_ipython_shortcuts(self, skip=shortcuts_to_skip) | ||||
for binding in shortcuts_to_add: | ||||
add_binding(key_bindings, binding) | ||||
krassowski
|
r28097 | |||
return key_bindings | ||||
krassowski
|
r28074 | |||
Antony Lee
|
r24832 | prompt_includes_vi_mode = Bool(True, | ||
help="Display the current vi mode (when using vi editing mode)." | ||||
).tag(config=True) | ||||
Matthias Bussonnier
|
r28537 | prompt_line_number_format = Unicode( | ||
"", | ||||
help="The format for line numbering, will be passed `line` (int, 1 based)" | ||||
" the current line number and `rel_line` the relative line number." | ||||
" for example to display both you can use the following template string :" | ||||
" c.TerminalInteractiveShell.prompt_line_number_format='{line: 4d}/{rel_line:+03d} | '" | ||||
" This will display the current line number, with leading space and a width of at least 4" | ||||
" character, as well as the relative line number 0 padded and always with a + or - sign." | ||||
" Note that when using Emacs mode the prompt of the first line may not update.", | ||||
).tag(config=True) | ||||
Min RK
|
r22549 | @observe('term_title') | ||
def init_term_title(self, change=None): | ||||
# Enable or disable the terminal title. | ||||
Maciej Goszczycki
|
r27830 | if self.term_title and _is_tty: | ||
Min RK
|
r22549 | toggle_set_term_title(True) | ||
Tory Haavik
|
r23623 | set_term_title(self.term_title_format.format(cwd=abbrev_cwd())) | ||
Min RK
|
r22549 | else: | ||
toggle_set_term_title(False) | ||||
Георгий Фролов
|
r25194 | def restore_term_title(self): | ||
Maciej Goszczycki
|
r27830 | if self.term_title and _is_tty: | ||
Георгий Фролов
|
r25194 | restore_term_title() | ||
Min RK
|
r22549 | def init_display_formatter(self): | ||
super(TerminalInteractiveShell, self).init_display_formatter() | ||||
# terminal only supports plain text | ||||
Matthias Bussonnier
|
r25819 | self.display_formatter.active_types = ["text/plain"] | ||
Min RK
|
r22549 | |||
def init_prompt_toolkit_cli(self): | ||||
if self.simple_prompt: | ||||
# Fall back to plain non-interactive output for tests. | ||||
Thomas Kluyver
|
r24167 | # This is very limited. | ||
Min RK
|
r22549 | def prompt(): | ||
Ximin Luo
|
r23705 | prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens()) | ||
Thomas Kluyver
|
r24167 | lines = [input(prompt_text)] | ||
Ximin Luo
|
r23705 | prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens()) | ||
Thomas Kluyver
|
r24180 | while self.check_complete('\n'.join(lines))[0] == 'incomplete': | ||
Thomas Kluyver
|
r24167 | lines.append( input(prompt_continuation) ) | ||
return '\n'.join(lines) | ||||
Min RK
|
r22549 | self.prompt_for_code = prompt | ||
return | ||||
Thomas Kluyver
|
r22642 | # Set up keyboard shortcuts | ||
krassowski
|
r28097 | key_bindings = self._merge_shortcuts(user_shortcuts=self.shortcuts) | ||
Matthias Bussonnier
|
r27595 | |||
Min RK
|
r22549 | # Pre-populate history from IPython's history database | ||
Matthias Bussonnier
|
r27595 | history = PtkHistoryAdapter(self) | ||
Min RK
|
r22549 | |||
memeplex
|
r22766 | self._style = self._make_style_from_name_or_cls(self.highlighting_style) | ||
memeplex
|
r23571 | self.style = DynamicStyle(lambda: self._style) | ||
Min RK
|
r22549 | |||
editing_mode = getattr(EditingMode, self.editing_mode.upper()) | ||||
Jonathan Slenders
|
r28508 | self._use_asyncio_inputhook = False | ||
Jonathan Slenders
|
r24376 | self.pt_app = PromptSession( | ||
Alexander Steppke
|
r27454 | auto_suggest=self.auto_suggest, | ||
Matthias Bussonnier
|
r26104 | editing_mode=editing_mode, | ||
key_bindings=key_bindings, | ||||
history=history, | ||||
completer=IPythonPTCompleter(shell=self), | ||||
enable_history_search=self.enable_history_search, | ||||
style=self.style, | ||||
include_default_pygments_style=False, | ||||
mouse_support=self.mouse_support, | ||||
enable_open_in_editor=self.extra_open_editor_shortcuts, | ||||
color_depth=self.color_depth, | ||||
tempfile_suffix=".py", | ||||
krassowski
|
r28074 | **self._extra_prompt_options(), | ||
Matthias Bussonnier
|
r26104 | ) | ||
krassowski
|
r28014 | if isinstance(self.auto_suggest, NavigableAutoSuggestFromHistory): | ||
self.auto_suggest.connect(self.pt_app) | ||||
Min RK
|
r22549 | |||
memeplex
|
r22766 | def _make_style_from_name_or_cls(self, name_or_cls): | ||
Min RK
|
r22549 | """ | ||
Small wrapper that make an IPython compatible style from a style name | ||||
Jamshed Vesuna
|
r22859 | We need that to add style for prompt ... etc. | ||
Min RK
|
r22549 | """ | ||
Matthias Bussonnier
|
r22609 | style_overrides = {} | ||
memeplex
|
r22766 | if name_or_cls == 'legacy': | ||
Matthias Bussonnier
|
r22578 | legacy = self.colors.lower() | ||
if legacy == 'linux': | ||||
style_cls = get_style_by_name('monokai') | ||||
style_overrides = _style_overrides_linux | ||||
elif legacy == 'lightbg': | ||||
style_overrides = _style_overrides_light_bg | ||||
Matthias Bussonnier
|
r22609 | style_cls = get_style_by_name('pastie') | ||
elif legacy == 'neutral': | ||||
Matthias Bussonnier
|
r22578 | # The default theme needs to be visible on both a dark background | ||
# and a light background, because we can't tell what the terminal | ||||
# looks like. These tweaks to the default theme help with that. | ||||
Matthias Bussonnier
|
r22609 | style_cls = get_style_by_name('default') | ||
Matthias Bussonnier
|
r22578 | style_overrides.update({ | ||
Tobias Bengfort
|
r25894 | Token.Number: '#ansigreen', | ||
Matthias Bussonnier
|
r22578 | Token.Operator: 'noinherit', | ||
Tobias Bengfort
|
r25894 | Token.String: '#ansiyellow', | ||
Token.Name.Function: '#ansiblue', | ||||
Token.Name.Class: 'bold #ansiblue', | ||||
Token.Name.Namespace: 'bold #ansiblue', | ||||
Matthias Bussonnier
|
r25896 | Token.Name.Variable.Magic: '#ansiblue', | ||
Tobias Bengfort
|
r25894 | Token.Prompt: '#ansigreen', | ||
Matthias Bussonnier
|
r24680 | Token.PromptNum: '#ansibrightgreen bold', | ||
Tobias Bengfort
|
r25894 | Token.OutPrompt: '#ansired', | ||
Matthias Bussonnier
|
r24680 | Token.OutPromptNum: '#ansibrightred bold', | ||
Matthias Bussonnier
|
r22578 | }) | ||
Segev Finer
|
r23317 | |||
# Hack: Due to limited color support on the Windows console | ||||
# the prompt colors will be wrong without this | ||||
if os.name == 'nt': | ||||
style_overrides.update({ | ||||
Token.Prompt: '#ansidarkgreen', | ||||
Token.PromptNum: '#ansigreen bold', | ||||
Token.OutPrompt: '#ansidarkred', | ||||
Token.OutPromptNum: '#ansired bold', | ||||
}) | ||||
Matthias Bussonnier
|
r22578 | elif legacy =='nocolor': | ||
style_cls=_NoStyle | ||||
style_overrides = {} | ||||
else : | ||||
raise ValueError('Got unknown colors: ', legacy) | ||||
else : | ||||
Srinivas Reddy Thatiparthy
|
r23037 | if isinstance(name_or_cls, str): | ||
memeplex
|
r22766 | style_cls = get_style_by_name(name_or_cls) | ||
else: | ||||
style_cls = name_or_cls | ||||
Matthias Bussonnier
|
r22578 | style_overrides = { | ||
Tobias Bengfort
|
r25894 | Token.Prompt: '#ansigreen', | ||
Matthias Bussonnier
|
r24680 | Token.PromptNum: '#ansibrightgreen bold', | ||
Tobias Bengfort
|
r25894 | Token.OutPrompt: '#ansired', | ||
Matthias Bussonnier
|
r24680 | Token.OutPromptNum: '#ansibrightred bold', | ||
Matthias Bussonnier
|
r22578 | } | ||
Min RK
|
r22549 | style_overrides.update(self.highlighting_style_overrides) | ||
Jonathan Slenders
|
r24376 | style = merge_styles([ | ||
style_from_pygments_cls(style_cls), | ||||
style_from_pygments_dict(style_overrides), | ||||
]) | ||||
Min RK
|
r22549 | |||
return style | ||||
Jonathan Slenders
|
r24376 | @property | ||
def pt_complete_style(self): | ||||
return { | ||||
'multicolumn': CompleteStyle.MULTI_COLUMN, | ||||
'column': CompleteStyle.COLUMN, | ||||
'readlinelike': CompleteStyle.READLINE_LIKE, | ||||
Yutao Yuan
|
r24397 | }[self.display_completions] | ||
Jonathan Slenders
|
r24376 | |||
Kyungdahm Yun
|
r24902 | @property | ||
def color_depth(self): | ||||
return (ColorDepth.TRUE_COLOR if self.true_color else None) | ||||
Jonathan Slenders
|
r24376 | def _extra_prompt_options(self): | ||
Min RK
|
r22549 | """ | ||
Return the current layout option for the current Terminal InteractiveShell | ||||
""" | ||||
Matthias Bussonnier
|
r25219 | def get_message(): | ||
return PygmentsTokens(self.prompts.in_prompt_tokens()) | ||||
Matthias Bussonnier
|
r28540 | if self.editing_mode == "emacs" and self.prompt_line_number_format == "": | ||
Matthias Bussonnier
|
r25219 | # with emacs mode the prompt is (usually) static, so we call only | ||
# the function once. With VI mode it can toggle between [ins] and | ||||
# [nor] so we can't precompute. | ||||
# here I'm going to favor the default keybinding which almost | ||||
# everybody uses to decrease CPU usage. | ||||
# if we have issues with users with custom Prompts we can see how to | ||||
# work around this. | ||||
get_message = get_message() | ||||
Jonathan Slenders
|
r24376 | |||
Jonathan Slenders
|
r25268 | options = { | ||
krassowski
|
r28041 | "complete_in_thread": False, | ||
"lexer": IPythonPTLexer(), | ||||
"reserve_space_for_menu": self.space_for_menu, | ||||
"message": get_message, | ||||
"prompt_continuation": ( | ||||
lambda width, lineno, is_soft_wrap: PygmentsTokens( | ||||
Matthias Bussonnier
|
r28551 | _backward_compat_continuation_prompt_tokens( | ||
self.prompts.continuation_prompt_tokens, width, lineno=lineno | ||||
) | ||||
krassowski
|
r28041 | ) | ||
), | ||||
"multiline": True, | ||||
"complete_style": self.pt_complete_style, | ||||
"input_processors": [ | ||||
Min RK
|
r22549 | # Highlight matching brackets, but only when this setting is | ||
# enabled, and only when the DEFAULT_BUFFER has the focus. | ||||
krassowski
|
r28041 | ConditionalProcessor( | ||
processor=HighlightMatchingBracketProcessor(chars="[](){}"), | ||||
filter=HasFocus(DEFAULT_BUFFER) | ||||
& ~IsDone() | ||||
& Condition(lambda: self.highlight_matching_brackets), | ||||
), | ||||
# Show auto-suggestion in lines other than the last line. | ||||
ConditionalProcessor( | ||||
processor=AppendAutoSuggestionInAnyLine(), | ||||
filter=HasFocus(DEFAULT_BUFFER) | ||||
& ~IsDone() | ||||
& Condition( | ||||
lambda: isinstance( | ||||
self.auto_suggest, NavigableAutoSuggestFromHistory | ||||
) | ||||
), | ||||
), | ||||
], | ||||
} | ||||
Jonathan Slenders
|
r25268 | if not PTK3: | ||
Matthias Bussonnier
|
r25325 | options['inputhook'] = self.inputhook | ||
Jonathan Slenders
|
r25268 | |||
return options | ||||
Min RK
|
r22549 | |||
def prompt_for_code(self): | ||||
Jonathan Slenders
|
r24376 | if self.rl_next_input: | ||
default = self.rl_next_input | ||||
self.rl_next_input = None | ||||
else: | ||||
default = '' | ||||
Jonathan Slenders
|
r25309 | # In order to make sure that asyncio code written in the | ||
# interactive shell doesn't interfere with the prompt, we run the | ||||
# prompt in a different event loop. | ||||
# If we don't do this, people could spawn coroutine with a | ||||
# while/true inside which will freeze the prompt. | ||||
Jonathan Slenders
|
r25276 | |||
Jonathan Slenders
|
r28508 | with patch_stdout(raw=True): | ||
if self._use_asyncio_inputhook: | ||||
# When we integrate the asyncio event loop, run the UI in the | ||||
# same event loop as the rest of the code. don't use an actual | ||||
# input hook. (Asyncio is not made for nesting event loops.) | ||||
asyncio_loop = get_asyncio_loop() | ||||
text = asyncio_loop.run_until_complete( | ||||
self.pt_app.prompt_async( | ||||
default=default, **self._extra_prompt_options() | ||||
) | ||||
) | ||||
else: | ||||
Jonathan Slenders
|
r25276 | text = self.pt_app.prompt( | ||
default=default, | ||||
Jonathan Slenders
|
r28508 | inputhook=self._inputhook, | ||
**self._extra_prompt_options(), | ||||
) | ||||
Jonathan Slenders
|
r25309 | |||
Jonathan Slenders
|
r24376 | return text | ||
Min RK
|
r22549 | |||
kousik
|
r25247 | def enable_win_unicode_console(self): | ||
# Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows | ||||
# console by default, so WUC shouldn't be needed. | ||||
warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future", | ||||
DeprecationWarning, | ||||
stacklevel=2) | ||||
Min RK
|
r22549 | def init_io(self): | ||
if sys.platform not in {'win32', 'cli'}: | ||||
return | ||||
Thomas Kluyver
|
r22701 | import colorama | ||
Min RK
|
r22549 | colorama.init() | ||
def init_magics(self): | ||||
super(TerminalInteractiveShell, self).init_magics() | ||||
self.register_magics(TerminalMagics) | ||||
def init_alias(self): | ||||
# The parent class defines aliases that can be safely used with any | ||||
# frontend. | ||||
super(TerminalInteractiveShell, self).init_alias() | ||||
# Now define aliases that only make sense on the terminal, because they | ||||
# need direct access to the console in a way that we can't emulate in | ||||
# GUI or web frontend | ||||
if os.name == 'posix': | ||||
Jesse Widner
|
r24889 | for cmd in ('clear', 'more', 'less', 'man'): | ||
Min RK
|
r22549 | self.alias_manager.soft_define_alias(cmd, cmd) | ||
Fernando Perez
|
r5435 | |||
Matthias Bussonnier
|
r28031 | def __init__(self, *args, **kwargs) -> None: | ||
Min RK
|
r22549 | super(TerminalInteractiveShell, self).__init__(*args, **kwargs) | ||
Alexander Steppke
|
r27454 | self._set_autosuggestions(self.autosuggestions_provider) | ||
Min RK
|
r22549 | self.init_prompt_toolkit_cli() | ||
self.init_term_title() | ||||
self.keep_running = True | ||||
Matthias Bussonnier
|
r27324 | self._set_formatter(self.autoformatter) | ||
Min RK
|
r22549 | |||
def ask_exit(self): | ||||
self.keep_running = False | ||||
rl_next_input = None | ||||
Matthias Bussonnier
|
r27216 | def interact(self): | ||
Min RK
|
r22764 | self.keep_running = True | ||
Min RK
|
r22549 | while self.keep_running: | ||
print(self.separate_in, end='') | ||||
try: | ||||
code = self.prompt_for_code() | ||||
except EOFError: | ||||
if (not self.confirm_exit) \ | ||||
or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): | ||||
self.ask_exit() | ||||
else: | ||||
if code: | ||||
self.run_cell(code, store_history=True) | ||||
Matthias Bussonnier
|
r27216 | def mainloop(self): | ||
Min RK
|
r22549 | # An extra layer of protection in case someone mashing Ctrl-C breaks | ||
# out of our internal code. | ||||
while True: | ||||
try: | ||||
self.interact() | ||||
break | ||||
Jeroen Demeyer
|
r23258 | except KeyboardInterrupt as e: | ||
print("\n%s escaped interact()\n" % type(e).__name__) | ||||
Thomas Kluyver
|
r23259 | finally: | ||
Jeroen Demeyer
|
r23258 | # An interrupt during the eventloop will mess up the | ||
# internal state of the prompt_toolkit library. | ||||
# Stopping the eventloop fixes this, see | ||||
# https://github.com/ipython/ipython/pull/9867 | ||||
if hasattr(self, '_eventloop'): | ||||
self._eventloop.stop() | ||||
Min RK
|
r22549 | |||
Георгий Фролов
|
r25194 | self.restore_term_title() | ||
Matthias Bussonnier
|
r26428 | # try to call some at-exit operation optimistically as some things can't | ||
# be done during interpreter shutdown. this is technically inaccurate as | ||||
# this make mainlool not re-callable, but that should be a rare if not | ||||
# in existent use case. | ||||
self._atexit_once() | ||||
Min RK
|
r22549 | _inputhook = None | ||
def inputhook(self, context): | ||||
if self._inputhook is not None: | ||||
self._inputhook(context) | ||||
Matthias Bussonnier
|
r28399 | active_eventloop: Optional[str] = None | ||
def enable_gui(self, gui: Optional[str] = None) -> None: | ||||
Ian Thomas
|
r28785 | if gui: | ||
from ..core.pylabtools import _convert_gui_from_matplotlib | ||||
gui = _convert_gui_from_matplotlib(gui) | ||||
Emilio Graff
|
r28352 | if self.simple_prompt is True and gui is not None: | ||
Emilio Graff
|
r28353 | print( | ||
f'Cannot install event loop hook for "{gui}" when running with `--simple-prompt`.' | ||||
) | ||||
print( | ||||
"NOTE: Tk is supported natively; use Tk apps and Tk backends with `--simple-prompt`." | ||||
) | ||||
Emilio Graff
|
r28352 | return | ||
Emilio Graff
|
r28353 | |||
Emilio Graff
|
r28144 | if self._inputhook is None and gui is None: | ||
print("No event loop hook running.") | ||||
return | ||||
Emilio Graff
|
r27991 | if self._inputhook is not None and gui is not None: | ||
Matthias Bussonnier
|
r28399 | newev, newinhook = get_inputhook_name_and_func(gui) | ||
if self._inputhook == newinhook: | ||||
# same inputhook, do nothing | ||||
self.log.info( | ||||
f"Shell is already running the {self.active_eventloop} eventloop. Doing nothing" | ||||
) | ||||
return | ||||
self.log.warning( | ||||
f"Shell is already running a different gui event loop for {self.active_eventloop}. " | ||||
Emilio Graff
|
r28149 | "Call with no arguments to disable the current loop." | ||
Emilio Graff
|
r28034 | ) | ||
Emilio Graff
|
r28140 | return | ||
Emilio Graff
|
r28143 | if self._inputhook is not None and gui is None: | ||
self.active_eventloop = self._inputhook = None | ||||
Ian Thomas
|
r28714 | if gui and (gui not in {None, "webagg"}): | ||
Emilio Graff
|
r27986 | # This hook runs with each cycle of the `prompt_toolkit`'s event loop. | ||
Matthias Bussonnier
|
r27858 | self.active_eventloop, self._inputhook = get_inputhook_name_and_func(gui) | ||
Min RK
|
r22549 | else: | ||
Thomas Kluyver
|
r22913 | self.active_eventloop = self._inputhook = None | ||
Min RK
|
r22549 | |||
Jonathan Slenders
|
r28508 | self._use_asyncio_inputhook = gui == "asyncio" | ||
Jonathan Slenders
|
r25268 | |||
Min RK
|
r22549 | # Run !system commands directly, not through pipes, so terminal programs | ||
# work correctly. | ||||
system = InteractiveShell.system_raw | ||||
def auto_rewrite_input(self, cmd): | ||||
"""Overridden from the parent class to use fancy rewriting prompt""" | ||||
if not self.show_rewritten_input: | ||||
return | ||||
tokens = self.prompts.rewrite_prompt_tokens() | ||||
Jonathan Slenders
|
r24376 | if self.pt_app: | ||
Thomas Kluyver
|
r24379 | print_formatted_text(PygmentsTokens(tokens), end='', | ||
style=self.pt_app.app.style) | ||||
Min RK
|
r22549 | print(cmd) | ||
else: | ||||
prompt = ''.join(s for t, s in tokens) | ||||
print(prompt, cmd, sep='') | ||||
_prompts_before = None | ||||
def switch_doctest_mode(self, mode): | ||||
"""Switch prompts to classic for %doctest_mode""" | ||||
if mode: | ||||
self._prompts_before = self.prompts | ||||
self.prompts = ClassicPrompts(self) | ||||
elif self._prompts_before: | ||||
self.prompts = self._prompts_before | ||||
self._prompts_before = None | ||||
Jonathan Slenders
|
r24376 | # self._update_layout() | ||
Min RK
|
r22549 | |||
InteractiveShellABC.register(TerminalInteractiveShell) | ||||
if __name__ == '__main__': | ||||
TerminalInteractiveShell.instance().interact() | ||||