##// END OF EJS Templates
Merge branch 'master' into fix-rm-harcoded-colors
Merge branch 'master' into fix-rm-harcoded-colors

File last commit:

r25902:21ac5592 merge
r25902:21ac5592 merge
Show More
interactiveshell.py
646 lines | 24.6 KiB | text/x-python | PythonLexer
Matthias Bussonnier
Remove readline mention, fit IPython typo.
r22557 """IPython terminal interface using prompt_toolkit"""
Thomas Kluyver
Move most readline code from InteractiveShell to terminal subclass...
r21846
Jonathan Slenders
Run the prompt in a separate asyncio loop....
r25276 import asyncio
Min RK
undeprecate terminal.interactiveshell...
r22549 import os
import sys
Min RK
fix some deprecations...
r22742 import warnings
Pierre Gerold
Replace all import of IPython.utils.warn module
r22092 from warnings import warn
Brian Granger
Complete reorganization of InteractiveShell....
r2761
Min RK
undeprecate terminal.interactiveshell...
r22549 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
Min RK
fix some deprecations...
r22742 from IPython.utils import io
Hugo
Remove redundant Python 2 code
r24010 from IPython.utils.py3compat import input
Георгий Фролов
restore terminal title on exit (xterm)
r25194 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
Min RK
undeprecate terminal.interactiveshell...
r22549 from IPython.utils.process import abbrev_cwd
Thomas Kluyver
Allow configuring a function to handle return in the terminal...
r23580 from traitlets import (
Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
Matthias Bussonnier
Give some love to the VI mode....
r24684 Any, validate
Thomas Kluyver
Allow configuring a function to handle return in the terminal...
r23580 )
Min RK
undeprecate terminal.interactiveshell...
r22549
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 from prompt_toolkit.formatted_text import PygmentsTokens
Min RK
undeprecate terminal.interactiveshell...
r22549 from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
Thomas Kluyver
Arrange imports, add missing, remove unused
r24377 from prompt_toolkit.output import ColorDepth
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 from prompt_toolkit.patch_stdout import patch_stdout
Thomas Kluyver
Fix input rewrite prompt
r24379 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
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
Support prompt_toolkit 3.0 as well.
r25268 from prompt_toolkit import __version__ as ptk_version
Min RK
undeprecate terminal.interactiveshell...
r22549
Thomas Kluyver
Remove unused import
r23995 from pygments.styles import get_style_by_name
memeplex
Allow to pass a pygments class to highlighting_style....
r22766 from pygments.style import Style
Min RK
undeprecate terminal.interactiveshell...
r22549 from pygments.token import Token
from .debugger import TerminalPdb, Pdb
from .magics import TerminalMagics
Thomas Kluyver
Let IPython.lib.guisupport detect terminal-integrated event loops...
r22913 from .pt_inputhooks import get_inputhook_name_and_func
Min RK
undeprecate terminal.interactiveshell...
r22549 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
from .ptutils import IPythonPTCompleter, IPythonPTLexer
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 from .shortcuts import create_ipython_shortcuts
Min RK
undeprecate terminal.interactiveshell...
r22549
Matthias Bussonnier
Fix interact() and mainloop() for backward compat.
r22562 DISPLAY_BANNER_DEPRECATED = object()
Jonathan Slenders
Support prompt_toolkit 3.0 as well.
r25268 PTK3 = ptk_version.startswith('3.')
Matthias Bussonnier
Fix interact() and mainloop() for backward compat.
r22562
Min RK
undeprecate terminal.interactiveshell...
r22549
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 class _NoStyle(Style): pass
_style_overrides_light_bg = {
Tobias Bengfort
replace hardcoded colors by ANSI colors...
r25894 Token.Prompt: '#ansibrightblue',
Token.PromptNum: '#ansiblue bold',
Token.OutPrompt: '#ansibrightred',
Token.OutPromptNum: '#ansired bold',
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 }
_style_overrides_linux = {
Tobias Bengfort
replace hardcoded colors by ANSI colors...
r25894 Token.Prompt: '#ansibrightgreen',
Token.PromptNum: '#ansigreen bold',
Token.OutPrompt: '#ansibrightred',
Token.OutPromptNum: '#ansired bold',
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 }
Min RK
undeprecate terminal.interactiveshell...
r22549 def get_default_editor():
try:
Srinivas Reddy Thatiparthy
remove PY3
r23085 return os.environ['EDITOR']
Min RK
undeprecate terminal.interactiveshell...
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:
return 'notepad' # same in Windows!
Min RK
safer check for isatty...
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)
if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
_is_tty = False
break
Min RK
undeprecate terminal.interactiveshell...
r22549 else:
Min RK
safer check for isatty...
r22758 _is_tty = True
Min RK
undeprecate terminal.interactiveshell...
r22549
_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
Matthias Bussonnier
some more work
r25142 def black_reformat_handler(text_before_cursor):
import black
formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
formatted_text = formatted_text[:-1]
return formatted_text
Min RK
undeprecate terminal.interactiveshell...
r22549 class TerminalInteractiveShell(InteractiveShell):
Matthias Bussonnier
Provide hooks for arbitrary mimetypes handling....
r25164 mime_renderers = Dict().tag(config=True)
Min RK
undeprecate terminal.interactiveshell...
r22549 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
Matthias Bussonnier
Better documentation for `space_for_menu`.
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
undeprecate terminal.interactiveshell...
r22549 ).tag(config=True)
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 pt_app = None
Min RK
undeprecate terminal.interactiveshell...
r22549 debugger_history = None
simple_prompt = Bool(_use_simple_prompt,
Ximin Luo
Support multiline input in --simple-prompt (fixes: #9816)
r23704 help="""Use `raw_input` for the REPL, without completion and prompt colors.
Min RK
undeprecate terminal.interactiveshell...
r22549
Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
IPython own testing machinery, and emacs inferior-shell integration through elpy.
This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
Matthias Bussonnier
Fix a couple of warnings/errors in doc builds.
r23477 environment variable is set, or the current terminal is not a tty."""
Min RK
undeprecate terminal.interactiveshell...
r22549 ).tag(config=True)
@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
some more work
r25142 autoformatter = Unicode(None,
help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
allow_none=True
).tag(config=True)
Min RK
undeprecate terminal.interactiveshell...
r22549 mouse_support = Bool(False,
ormung
Add note to config option...
r23846 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
Min RK
undeprecate terminal.interactiveshell...
r22549 ).tag(config=True)
Thomas Kluyver
Don't list pygments styles on import...
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
Allow to pass a pygments class to highlighting_style....
r22766 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
help="""The name or class of a Pygments style to use for syntax
Thomas Kluyver
Don't list pygments styles on import...
r23994 highlighting. To see available styles, run `pygmentize -L styles`."""
Min RK
undeprecate terminal.interactiveshell...
r22549 ).tag(config=True)
Matthias Bussonnier
Give some love to the VI mode....
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
@observe('editing_mode')
def _editing_mode(self, change):
u_mode = change.new.upper()
Matthias Bussonnier
Fix starting IPython in vi editing mode...
r24718 if self.pt_app:
self.pt_app.editing_mode = u_mode
Jamshed Vesuna
Only track unique history of commands
r22859
Matthias Bussonnier
some more work
r25142 @observe('autoformatter')
def _autoformatter_changed(self, change):
formatter = change.new
if formatter is None:
self.reformat_handler = lambda x:x
elif formatter == 'black':
self.reformat_handler = black_reformat_handler
else:
raise ValueError
Min RK
undeprecate terminal.interactiveshell...
r22549 @observe('highlighting_style')
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 @observe('colors')
Min RK
undeprecate terminal.interactiveshell...
r22549 def _highlighting_style_changed(self, change):
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 self.refresh_style()
def refresh_style(self):
memeplex
Allow to pass a pygments class to highlighting_style....
r22766 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
Min RK
undeprecate terminal.interactiveshell...
r22549
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578
Min RK
undeprecate terminal.interactiveshell...
r22549 highlighting_style_overrides = Dict(
help="Override highlighting format for specific tokens"
).tag(config=True)
Jacob Niehus
Add true_color option for prompt_toolkit
r22682 true_color = Bool(False,
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\"")
).tag(config=True)
Min RK
undeprecate terminal.interactiveshell...
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
Upgrade to prompt_toolkit 2.0
r24376 # @observe('prompts')
# def _(self, change):
# self._update_layout()
Min RK
undeprecate terminal.interactiveshell...
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
Add --term-title-format flag to customize terminal title format
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
Only track unique history of commands
r22859 display_completions = Enum(('column', 'multicolumn','readlinelike'),
michaelpacer
Fixed formatting at end of lines
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
added help line tointeractiveshell.py
r22720 ),
default_value='multicolumn').tag(config=True)
Matthias Bussonnier
Extend the completion layout to use a third readlinelike option....
r22554
Min RK
undeprecate terminal.interactiveshell...
r22549 highlight_matching_brackets = Bool(True,
Thomas Kluyver
Add config option for vi/emacs style open-editor shortcuts...
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
undeprecate terminal.interactiveshell...
r22549 ).tag(config=True)
Thomas Kluyver
Allow configuring a function to handle return in the terminal...
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
Applying feedbacks - changing enable_history_search from an envvar to a configurable
r24147 enable_history_search = Bool(True,
help="Allows to enable/disable the prompt toolkit history search"
).tag(config=True)
Antony Lee
Make inclusion of vi mode in prompt togglable.
r24832 prompt_includes_vi_mode = Bool(True,
help="Display the current vi mode (when using vi editing mode)."
).tag(config=True)
Min RK
undeprecate terminal.interactiveshell...
r22549 @observe('term_title')
def init_term_title(self, change=None):
# Enable or disable the terminal title.
if self.term_title:
toggle_set_term_title(True)
Tory Haavik
Add --term-title-format flag to customize terminal title format
r23623 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
Min RK
undeprecate terminal.interactiveshell...
r22549 else:
toggle_set_term_title(False)
Георгий Фролов
restore terminal title on exit (xterm)
r25194 def restore_term_title(self):
if self.term_title:
restore_term_title()
Min RK
undeprecate terminal.interactiveshell...
r22549 def init_display_formatter(self):
super(TerminalInteractiveShell, self).init_display_formatter()
# terminal only supports plain text
self.display_formatter.active_types = ['text/plain']
Min RK
disable `_ipython_display_` in terminal IPython...
r23307 # disable `_ipython_display_`
self.display_formatter.ipython_display_formatter.enabled = False
Min RK
undeprecate terminal.interactiveshell...
r22549
def init_prompt_toolkit_cli(self):
if self.simple_prompt:
# Fall back to plain non-interactive output for tests.
Thomas Kluyver
Fix fallback prompt & improve info on test failure
r24167 # This is very limited.
Min RK
undeprecate terminal.interactiveshell...
r22549 def prompt():
Ximin Luo
simple-prompt: use prompts from self.prompts...
r23705 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
Thomas Kluyver
Fix fallback prompt & improve info on test failure
r24167 lines = [input(prompt_text)]
Ximin Luo
simple-prompt: use prompts from self.prompts...
r23705 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
Thomas Kluyver
Add shell.check_complete() method...
r24180 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
Thomas Kluyver
Fix fallback prompt & improve info on test failure
r24167 lines.append( input(prompt_continuation) )
return '\n'.join(lines)
Min RK
undeprecate terminal.interactiveshell...
r22549 self.prompt_for_code = prompt
return
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 # Set up keyboard shortcuts
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 key_bindings = create_ipython_shortcuts(self)
Min RK
undeprecate terminal.interactiveshell...
r22549
# Pre-populate history from IPython's history database
history = InMemoryHistory()
last_cell = u""
for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
include_latest=True):
# Ignore blank lines and consecutive duplicates
cell = cell.rstrip()
if cell and (cell != last_cell):
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 history.append_string(cell)
Jamshed Vesuna
Only track unique history of commands
r22859 last_cell = cell
Min RK
undeprecate terminal.interactiveshell...
r22549
memeplex
Allow to pass a pygments class to highlighting_style....
r22766 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
memeplex
Make pdb use pt style. Fixes #10478
r23571 self.style = DynamicStyle(lambda: self._style)
Min RK
undeprecate terminal.interactiveshell...
r22549
editing_mode = getattr(EditingMode, self.editing_mode.upper())
Jonathan Slenders
Run the prompt in a separate asyncio loop....
r25276 self.pt_loop = asyncio.new_event_loop()
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 self.pt_app = PromptSession(
Min RK
undeprecate terminal.interactiveshell...
r22549 editing_mode=editing_mode,
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 key_bindings=key_bindings,
Min RK
undeprecate terminal.interactiveshell...
r22549 history=history,
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 completer=IPythonPTCompleter(shell=self),
enable_history_search = self.enable_history_search,
memeplex
Make pdb use pt style. Fixes #10478
r23571 style=self.style,
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 include_default_pygments_style=False,
Min RK
undeprecate terminal.interactiveshell...
r22549 mouse_support=self.mouse_support,
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 enable_open_in_editor=self.extra_open_editor_shortcuts,
Kyungdahm Yun
Make color_depth property for reuse
r24902 color_depth=self.color_depth,
foobarbyte
Pass tempfile_suffix argument to PromptSession....
r25566 tempfile_suffix=".py",
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 **self._extra_prompt_options())
Min RK
undeprecate terminal.interactiveshell...
r22549
memeplex
Allow to pass a pygments class to highlighting_style....
r22766 def _make_style_from_name_or_cls(self, name_or_cls):
Min RK
undeprecate terminal.interactiveshell...
r22549 """
Small wrapper that make an IPython compatible style from a style name
Jamshed Vesuna
Only track unique history of commands
r22859 We need that to add style for prompt ... etc.
Min RK
undeprecate terminal.interactiveshell...
r22549 """
Matthias Bussonnier
Make everyone happy with a neutral colortheme by default.
r22609 style_overrides = {}
memeplex
Allow to pass a pygments class to highlighting_style....
r22766 if name_or_cls == 'legacy':
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
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
Make everyone happy with a neutral colortheme by default.
r22609 style_cls = get_style_by_name('pastie')
elif legacy == 'neutral':
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
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
Make everyone happy with a neutral colortheme by default.
r22609 style_cls = get_style_by_name('default')
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 style_overrides.update({
Tobias Bengfort
replace hardcoded colors by ANSI colors...
r25894 Token.Number: '#ansigreen',
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 Token.Operator: 'noinherit',
Tobias Bengfort
replace hardcoded colors by ANSI colors...
r25894 Token.String: '#ansiyellow',
Token.Name.Function: '#ansiblue',
Token.Name.Class: 'bold #ansiblue',
Token.Name.Namespace: 'bold #ansiblue',
Matthias Bussonnier
Make `x.__doc__` a reasonable default color.
r25896 Token.Name.Variable.Magic: '#ansiblue',
Tobias Bengfort
replace hardcoded colors by ANSI colors...
r25894 Token.Prompt: '#ansigreen',
Matthias Bussonnier
Use ansi code for soon-to-be released prompt_toolkit....
r24680 Token.PromptNum: '#ansibrightgreen bold',
Tobias Bengfort
replace hardcoded colors by ANSI colors...
r25894 Token.OutPrompt: '#ansired',
Matthias Bussonnier
Use ansi code for soon-to-be released prompt_toolkit....
r24680 Token.OutPromptNum: '#ansibrightred bold',
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 })
Segev Finer
Fix the rest of the colors used on Windows so they are more visible...
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
Restore the ability to use %colors to switch terminal theme....
r22578 elif legacy =='nocolor':
style_cls=_NoStyle
style_overrides = {}
else :
raise ValueError('Got unknown colors: ', legacy)
else :
Srinivas Reddy Thatiparthy
convert string_types to str
r23037 if isinstance(name_or_cls, str):
memeplex
Allow to pass a pygments class to highlighting_style....
r22766 style_cls = get_style_by_name(name_or_cls)
else:
style_cls = name_or_cls
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 style_overrides = {
Tobias Bengfort
replace hardcoded colors by ANSI colors...
r25894 Token.Prompt: '#ansigreen',
Matthias Bussonnier
Use ansi code for soon-to-be released prompt_toolkit....
r24680 Token.PromptNum: '#ansibrightgreen bold',
Tobias Bengfort
replace hardcoded colors by ANSI colors...
r25894 Token.OutPrompt: '#ansired',
Matthias Bussonnier
Use ansi code for soon-to-be released prompt_toolkit....
r24680 Token.OutPromptNum: '#ansibrightred bold',
Matthias Bussonnier
Restore the ability to use %colors to switch terminal theme....
r22578 }
Min RK
undeprecate terminal.interactiveshell...
r22549 style_overrides.update(self.highlighting_style_overrides)
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 style = merge_styles([
style_from_pygments_cls(style_cls),
style_from_pygments_dict(style_overrides),
])
Min RK
undeprecate terminal.interactiveshell...
r22549
return style
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 @property
def pt_complete_style(self):
return {
'multicolumn': CompleteStyle.MULTI_COLUMN,
'column': CompleteStyle.COLUMN,
'readlinelike': CompleteStyle.READLINE_LIKE,
Yutao Yuan
Fix config option TerminalInteractiveShell.display_completions...
r24397 }[self.display_completions]
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376
Kyungdahm Yun
Make color_depth property for reuse
r24902 @property
def color_depth(self):
return (ColorDepth.TRUE_COLOR if self.true_color else None)
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 def _extra_prompt_options(self):
Min RK
undeprecate terminal.interactiveshell...
r22549 """
Return the current layout option for the current Terminal InteractiveShell
"""
Matthias Bussonnier
Do no precompute when using vi mode.
r25219 def get_message():
return PygmentsTokens(self.prompts.in_prompt_tokens())
if self.editing_mode == 'emacs':
# 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
Upgrade to prompt_toolkit 2.0
r24376
Jonathan Slenders
Support prompt_toolkit 3.0 as well.
r25268 options = {
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 'complete_in_thread': False,
Min RK
undeprecate terminal.interactiveshell...
r22549 'lexer':IPythonPTLexer(),
'reserve_space_for_menu':self.space_for_menu,
Matthias Bussonnier
Do no precompute when using vi mode.
r25219 'message': get_message,
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 'prompt_continuation': (
lambda width, lineno, is_soft_wrap:
PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
'multiline': True,
'complete_style': self.pt_complete_style,
Min RK
undeprecate terminal.interactiveshell...
r22549
# Highlight matching brackets, but only when this setting is
# enabled, and only when the DEFAULT_BUFFER has the focus.
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 'input_processors': [ConditionalProcessor(
Min RK
undeprecate terminal.interactiveshell...
r22549 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 Condition(lambda: self.highlight_matching_brackets))],
Min RK
undeprecate terminal.interactiveshell...
r22549 }
Jonathan Slenders
Support prompt_toolkit 3.0 as well.
r25268 if not PTK3:
Matthias Bussonnier
Fix the right inputhook...
r25325 options['inputhook'] = self.inputhook
Jonathan Slenders
Support prompt_toolkit 3.0 as well.
r25268
return options
Min RK
undeprecate terminal.interactiveshell...
r22549
def prompt_for_code(self):
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 if self.rl_next_input:
default = self.rl_next_input
self.rl_next_input = None
else:
default = ''
Jonathan Slenders
Handle situation where the user used 'asyncio.run' and clears the event loop.
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
Run the prompt in a separate asyncio loop....
r25276
Jonathan Slenders
Handle situation where the user used 'asyncio.run' and clears the event loop.
r25309 try:
Jonathan Slenders
Run the prompt in a separate asyncio loop....
r25276 old_loop = asyncio.get_event_loop()
Jonathan Slenders
Handle situation where the user used 'asyncio.run' and clears the event loop.
r25309 except RuntimeError:
# This happens when the user used `asyncio.run()`.
old_loop = None
asyncio.set_event_loop(self.pt_loop)
try:
with patch_stdout(raw=True):
Jonathan Slenders
Run the prompt in a separate asyncio loop....
r25276 text = self.pt_app.prompt(
default=default,
**self._extra_prompt_options())
Jonathan Slenders
Handle situation where the user used 'asyncio.run' and clears the event loop.
r25309 finally:
# Restore the original event loop.
asyncio.set_event_loop(old_loop)
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 return text
Min RK
undeprecate terminal.interactiveshell...
r22549
kousik
Added deprecation warning for enable_win_unicode_console #11953
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.
from warnings import warn
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
undeprecate terminal.interactiveshell...
r22549 def init_io(self):
if sys.platform not in {'win32', 'cli'}:
return
Thomas Kluyver
Be more lenient when bytes are sent to stdout/stderr on Py2+Windows...
r22701 import colorama
Min RK
undeprecate terminal.interactiveshell...
r22549 colorama.init()
# For some reason we make these wrappers around stdout/stderr.
# For now, we need to reset them so all output gets coloured.
# https://github.com/ipython/ipython/issues/8669
Min RK
fix some deprecations...
r22742 # io.std* are deprecated, but don't show our own deprecation warnings
# during initialization of the deprecated API.
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
io.stdout = io.IOStream(sys.stdout)
io.stderr = io.IOStream(sys.stderr)
Min RK
undeprecate terminal.interactiveshell...
r22549
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
Adds posix aliases after a %reset....
r24889 for cmd in ('clear', 'more', 'less', 'man'):
Min RK
undeprecate terminal.interactiveshell...
r22549 self.alias_manager.soft_define_alias(cmd, cmd)
Fernando Perez
Fix paste/cpaste bug and refactor/cleanup that code a lot....
r5435
Matthias Bussonnier
Improve deprecation warning....
r22442
Thomas Kluyver
Remove the readline shell machinery...
r22436 def __init__(self, *args, **kwargs):
Min RK
undeprecate terminal.interactiveshell...
r22549 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
self.init_prompt_toolkit_cli()
self.init_term_title()
self.keep_running = True
self.debugger_history = InMemoryHistory()
def ask_exit(self):
self.keep_running = False
rl_next_input = None
Matthias Bussonnier
Fix interact() and mainloop() for backward compat.
r22562 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
if display_banner is not DISPLAY_BANNER_DEPRECATED:
warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
Min RK
Allow starting TerminalInteractiveShell more than once...
r22764 self.keep_running = True
Min RK
undeprecate terminal.interactiveshell...
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
Fix interact() and mainloop() for backward compat.
r22562 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
Min RK
undeprecate terminal.interactiveshell...
r22549 # An extra layer of protection in case someone mashing Ctrl-C breaks
# out of our internal code.
Matthias Bussonnier
Fix interact() and mainloop() for backward compat.
r22562 if display_banner is not DISPLAY_BANNER_DEPRECATED:
warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
Min RK
undeprecate terminal.interactiveshell...
r22549 while True:
try:
self.interact()
break
Jeroen Demeyer
Better support for KeyboardInterrupt during prompt
r23258 except KeyboardInterrupt as e:
print("\n%s escaped interact()\n" % type(e).__name__)
Thomas Kluyver
Put cleanup in finally block...
r23259 finally:
Jeroen Demeyer
Better support for KeyboardInterrupt during prompt
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
undeprecate terminal.interactiveshell...
r22549
Георгий Фролов
restore terminal title on exit (xterm)
r25194 self.restore_term_title()
Min RK
undeprecate terminal.interactiveshell...
r22549 _inputhook = None
def inputhook(self, context):
if self._inputhook is not None:
self._inputhook(context)
Thomas Kluyver
Let IPython.lib.guisupport detect terminal-integrated event loops...
r22913 active_eventloop = None
Min RK
undeprecate terminal.interactiveshell...
r22549 def enable_gui(self, gui=None):
Matthias Bussonnier
Update documentation, and prepare inine matplotlib.
r25241 if gui and (gui != 'inline') :
Thomas Kluyver
Let IPython.lib.guisupport detect terminal-integrated event loops...
r22913 self.active_eventloop, self._inputhook =\
get_inputhook_name_and_func(gui)
Min RK
undeprecate terminal.interactiveshell...
r22549 else:
Thomas Kluyver
Let IPython.lib.guisupport detect terminal-integrated event loops...
r22913 self.active_eventloop = self._inputhook = None
Min RK
undeprecate terminal.interactiveshell...
r22549
Jonathan Slenders
Support prompt_toolkit 3.0 as well.
r25268 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
# this inputhook.
if PTK3:
Jonathan Slenders
Don't nest asyncio input hooks....
r25308 import asyncio
from prompt_toolkit.eventloop import new_eventloop_with_inputhook
if gui == 'asyncio':
# 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.)
self.pt_loop = asyncio.get_event_loop()
elif self._inputhook:
# If an inputhook was set, create a new asyncio event loop with
# this inputhook for the prompt.
Jonathan Slenders
Run the prompt in a separate asyncio loop....
r25276 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
Jonathan Slenders
Support prompt_toolkit 3.0 as well.
r25268 else:
Jonathan Slenders
Don't nest asyncio input hooks....
r25308 # When there's no inputhook, run the prompt in a separate
# asyncio event loop.
Jonathan Slenders
Run the prompt in a separate asyncio loop....
r25276 self.pt_loop = asyncio.new_event_loop()
Jonathan Slenders
Support prompt_toolkit 3.0 as well.
r25268
Min RK
undeprecate terminal.interactiveshell...
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
Upgrade to prompt_toolkit 2.0
r24376 if self.pt_app:
Thomas Kluyver
Fix input rewrite prompt
r24379 print_formatted_text(PygmentsTokens(tokens), end='',
style=self.pt_app.app.style)
Min RK
undeprecate terminal.interactiveshell...
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
Upgrade to prompt_toolkit 2.0
r24376 # self._update_layout()
Min RK
undeprecate terminal.interactiveshell...
r22549
InteractiveShellABC.register(TerminalInteractiveShell)
if __name__ == '__main__':
TerminalInteractiveShell.instance().interact()