diff options
| author | smosker <[email protected]> | 2022-02-10 16:48:21 +0300 |
|---|---|---|
| committer | Daniil Cherednik <[email protected]> | 2022-02-10 16:48:21 +0300 |
| commit | dd14d17a747a9c259858faf2fcc3ea6b92df4e15 (patch) | |
| tree | f332cd81782832c17c48d8c3b4511924cd9e47fd /contrib/python/ipython/py2/IPython/terminal | |
| parent | b637e2fa3213638fbabe52c15dad14c8237945ac (diff) | |
Restoring authorship annotation for <[email protected]>. Commit 1 of 2.
Diffstat (limited to 'contrib/python/ipython/py2/IPython/terminal')
11 files changed, 298 insertions, 298 deletions
diff --git a/contrib/python/ipython/py2/IPython/terminal/console.py b/contrib/python/ipython/py2/IPython/terminal/console.py index 65571a7572d..a3e4a7abffd 100644 --- a/contrib/python/ipython/py2/IPython/terminal/console.py +++ b/contrib/python/ipython/py2/IPython/terminal/console.py @@ -9,7 +9,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The `IPython.terminal.console` package has been deprecated since IPython 4.0. " +warn("The `IPython.terminal.console` package has been deprecated since IPython 4.0. " "You should import from jupyter_console instead.", ShimWarning) # Unconditionally insert the shim into sys.modules so that further import calls diff --git a/contrib/python/ipython/py2/IPython/terminal/debugger.py b/contrib/python/ipython/py2/IPython/terminal/debugger.py index c68a3204a68..11819f71ccf 100644 --- a/contrib/python/ipython/py2/IPython/terminal/debugger.py +++ b/contrib/python/ipython/py2/IPython/terminal/debugger.py @@ -1,24 +1,24 @@ -import signal -import sys - +import signal +import sys + from IPython.core.debugger import Pdb from IPython.core.completer import IPCompleter from .ptutils import IPythonPTCompleter -from .shortcuts import suspend_to_bg, cursor_in_leading_ws +from .shortcuts import suspend_to_bg, cursor_in_leading_ws -from prompt_toolkit.enums import DEFAULT_BUFFER -from prompt_toolkit.filters import (Condition, HasFocus, HasSelection, - ViInsertMode, EmacsInsertMode) -from prompt_toolkit.keys import Keys -from prompt_toolkit.key_binding.manager import KeyBindingManager -from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline +from prompt_toolkit.enums import DEFAULT_BUFFER +from prompt_toolkit.filters import (Condition, HasFocus, HasSelection, + ViInsertMode, EmacsInsertMode) +from prompt_toolkit.keys import Keys +from prompt_toolkit.key_binding.manager import KeyBindingManager +from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline from prompt_toolkit.token import Token from prompt_toolkit.shortcuts import create_prompt_application from prompt_toolkit.interface import CommandLineInterface from prompt_toolkit.enums import EditingMode - + class TerminalPdb(Pdb): def __init__(self, *args, **kwargs): Pdb.__init__(self, *args, **kwargs) @@ -29,9 +29,9 @@ class TerminalPdb(Pdb): def get_prompt_tokens(cli): return [(Token.Prompt, self.prompt)] - def patch_stdout(**kwargs): - return self.pt_cli.patch_stdout_context(**kwargs) - + def patch_stdout(**kwargs): + return self.pt_cli.patch_stdout_context(**kwargs) + if self._ptcomp is None: compl = IPCompleter(shell=self.shell, namespace={}, @@ -39,32 +39,32 @@ class TerminalPdb(Pdb): use_readline=False, parent=self.shell, ) - self._ptcomp = IPythonPTCompleter(compl, patch_stdout=patch_stdout) - - kbmanager = KeyBindingManager.for_prompt() - supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) - kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend - )(suspend_to_bg) - - if self.shell.display_completions == 'readlinelike': - kbmanager.registry.add_binding(Keys.ControlI, - filter=(HasFocus(DEFAULT_BUFFER) - & ~HasSelection() - & ViInsertMode() | EmacsInsertMode() - & ~cursor_in_leading_ws - ))(display_completions_like_readline) - multicolumn = (self.shell.display_completions == 'multicolumn') + self._ptcomp = IPythonPTCompleter(compl, patch_stdout=patch_stdout) + kbmanager = KeyBindingManager.for_prompt() + supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) + kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend + )(suspend_to_bg) + + if self.shell.display_completions == 'readlinelike': + kbmanager.registry.add_binding(Keys.ControlI, + filter=(HasFocus(DEFAULT_BUFFER) + & ~HasSelection() + & ViInsertMode() | EmacsInsertMode() + & ~cursor_in_leading_ws + ))(display_completions_like_readline) + multicolumn = (self.shell.display_completions == 'multicolumn') + self._pt_app = create_prompt_application( editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()), - key_bindings_registry=kbmanager.registry, + key_bindings_registry=kbmanager.registry, history=self.shell.debugger_history, completer= self._ptcomp, enable_history_search=True, mouse_support=self.shell.mouse_support, - get_prompt_tokens=get_prompt_tokens, - display_completions_in_columns=multicolumn, - style=self.shell.style + get_prompt_tokens=get_prompt_tokens, + display_completions_in_columns=multicolumn, + style=self.shell.style ) self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self.shell._eventloop) @@ -104,11 +104,11 @@ class TerminalPdb(Pdb): raise -def set_trace(frame=None): - """ - Start debugging from `frame`. - - If frame is not specified, debugging starts from caller's frame. - """ - TerminalPdb().set_trace(frame or sys._getframe().f_back) - +def set_trace(frame=None): + """ + Start debugging from `frame`. + + If frame is not specified, debugging starts from caller's frame. + """ + TerminalPdb().set_trace(frame or sys._getframe().f_back) + diff --git a/contrib/python/ipython/py2/IPython/terminal/embed.py b/contrib/python/ipython/py2/IPython/terminal/embed.py index 5ad70431e42..f906091dc11 100644 --- a/contrib/python/ipython/py2/IPython/terminal/embed.py +++ b/contrib/python/ipython/py2/IPython/terminal/embed.py @@ -12,7 +12,7 @@ import sys import warnings from IPython.core import ultratb, compilerop -from IPython.core import magic_arguments +from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic from IPython.core.interactiveshell import DummyMod, InteractiveShell from IPython.terminal.interactiveshell import TerminalInteractiveShell @@ -28,70 +28,70 @@ class KillEmbeded(Exception):pass class EmbeddedMagics(Magics): @line_magic - @magic_arguments.magic_arguments() - @magic_arguments.argument('-i', '--instance', action='store_true', - help='Kill instance instead of call location') - @magic_arguments.argument('-x', '--exit', action='store_true', - help='Also exit the current session') - @magic_arguments.argument('-y', '--yes', action='store_true', - help='Do not ask confirmation') + @magic_arguments.magic_arguments() + @magic_arguments.argument('-i', '--instance', action='store_true', + help='Kill instance instead of call location') + @magic_arguments.argument('-x', '--exit', action='store_true', + help='Also exit the current session') + @magic_arguments.argument('-y', '--yes', action='store_true', + help='Do not ask confirmation') def kill_embedded(self, parameter_s=''): - """%kill_embedded : deactivate for good the current embedded IPython + """%kill_embedded : deactivate for good the current embedded IPython This function (after asking for confirmation) sets an internal flag so - that an embedded IPython will never activate again for the given call - location. This is useful to permanently disable a shell that is being - called inside a loop: once you've figured out what you needed from it, - you may then kill it and the program will then continue to run without - the interactive shell interfering again. - - - Kill Instance Option - -------------------- - - If for some reasons you need to kill the location where the instance is - created and not called, for example if you create a single instance in - one place and debug in many locations, you can use the ``--instance`` - option to kill this specific instance. Like for the ``call location`` - killing an "instance" should work even if it is recreated within a - loop. - - .. note:: - - This was the default behavior before IPython 5.2 - + that an embedded IPython will never activate again for the given call + location. This is useful to permanently disable a shell that is being + called inside a loop: once you've figured out what you needed from it, + you may then kill it and the program will then continue to run without + the interactive shell interfering again. + + + Kill Instance Option + -------------------- + + If for some reasons you need to kill the location where the instance is + created and not called, for example if you create a single instance in + one place and debug in many locations, you can use the ``--instance`` + option to kill this specific instance. Like for the ``call location`` + killing an "instance" should work even if it is recreated within a + loop. + + .. note:: + + This was the default behavior before IPython 5.2 + """ - args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s) - print(args) - if args.instance: - # let no ask - if not args.yes: - kill = ask_yes_no( - "Are you sure you want to kill this embedded instance? [y/N] ", 'n') - else: - kill = True - if kill: - self.shell._disable_init_location() - print("This embedded IPython instance will not reactivate anymore " - "once you exit.") - else: - if not args.yes: - kill = ask_yes_no( - "Are you sure you want to kill this embedded call_location? [y/N] ", 'n') - else: - kill = True - if kill: - self.shell.embedded_active = False - print("This embedded IPython call location will not reactivate anymore " - "once you exit.") - - if args.exit: - # Ask-exit does not really ask, it just set internals flags to exit - # on next loop. - self.shell.ask_exit() + args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s) + print(args) + if args.instance: + # let no ask + if not args.yes: + kill = ask_yes_no( + "Are you sure you want to kill this embedded instance? [y/N] ", 'n') + else: + kill = True + if kill: + self.shell._disable_init_location() + print("This embedded IPython instance will not reactivate anymore " + "once you exit.") + else: + if not args.yes: + kill = ask_yes_no( + "Are you sure you want to kill this embedded call_location? [y/N] ", 'n') + else: + kill = True + if kill: + self.shell.embedded_active = False + print("This embedded IPython call location will not reactivate anymore " + "once you exit.") + if args.exit: + # Ask-exit does not really ask, it just set internals flags to exit + # on next loop. + self.shell.ask_exit() + @line_magic def exit_raise(self, parameter_s=''): """%exit_raise Make the current embedded kernel exit and raise and exception. @@ -126,34 +126,34 @@ class InteractiveShellEmbed(TerminalInteractiveShell): @property def embedded_active(self): - return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\ - and (self._init_location_id not in InteractiveShellEmbed._inactive_locations) - - def _disable_init_location(self): - """Disable the current Instance creation location""" - InteractiveShellEmbed._inactive_locations.add(self._init_location_id) + return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\ + and (self._init_location_id not in InteractiveShellEmbed._inactive_locations) + def _disable_init_location(self): + """Disable the current Instance creation location""" + InteractiveShellEmbed._inactive_locations.add(self._init_location_id) + @embedded_active.setter def embedded_active(self, value): - if value: - InteractiveShellEmbed._inactive_locations.discard( - self._call_location_id) - InteractiveShellEmbed._inactive_locations.discard( - self._init_location_id) + if value: + InteractiveShellEmbed._inactive_locations.discard( + self._call_location_id) + InteractiveShellEmbed._inactive_locations.discard( + self._init_location_id) else: - InteractiveShellEmbed._inactive_locations.add( - self._call_location_id) + InteractiveShellEmbed._inactive_locations.add( + self._call_location_id) def __init__(self, **kw): if kw.get('user_global_ns', None) is not None: - raise DeprecationWarning( - "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.") + raise DeprecationWarning( + "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.") - clid = kw.pop('_init_location_id', None) - if not clid: - frame = sys._getframe(1) - clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) - self._init_location_id = clid + clid = kw.pop('_init_location_id', None) + if not clid: + frame = sys._getframe(1) + clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) + self._init_location_id = clid super(InteractiveShellEmbed,self).__init__(**kw) @@ -164,9 +164,9 @@ class InteractiveShellEmbed(TerminalInteractiveShell): call_pdb=self.pdb) def init_sys_modules(self): - """ - Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing. - """ + """ + Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing. + """ pass def init_magics(self): @@ -174,7 +174,7 @@ class InteractiveShellEmbed(TerminalInteractiveShell): self.register_magics(EmbeddedMagics) def __call__(self, header='', local_ns=None, module=None, dummy=None, - stack_depth=1, global_ns=None, compile_flags=None, **kw): + stack_depth=1, global_ns=None, compile_flags=None, **kw): """Activate the interactive interpreter. __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start @@ -191,16 +191,16 @@ class InteractiveShellEmbed(TerminalInteractiveShell): can still have a specific call work by making it as IPShell(dummy=False). """ - # we are called, set the underlying interactiveshell not to exit. - self.keep_running = True - + # we are called, set the underlying interactiveshell not to exit. + self.keep_running = True + # If the user has turned it off, go away - clid = kw.pop('_call_location_id', None) - if not clid: - frame = sys._getframe(1) - clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) - self._call_location_id = clid - + clid = kw.pop('_call_location_id', None) + if not clid: + frame = sys._getframe(1) + clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) + self._call_location_id = clid + if not self.embedded_active: return @@ -379,10 +379,10 @@ def embed(**kwargs): cls = type(saved_shell_instance) cls.clear_instance() frame = sys._getframe(1) - shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % ( - frame.f_code.co_filename, frame.f_lineno), **kwargs) - shell(header=header, stack_depth=2, compile_flags=compile_flags, - _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) + shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % ( + frame.f_code.co_filename, frame.f_lineno), **kwargs) + shell(header=header, stack_depth=2, compile_flags=compile_flags, + _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) InteractiveShellEmbed.clear_instance() #restore previous instance if saved_shell_instance is not None: diff --git a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py index f67cc6b5020..247235c1fd0 100644 --- a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py +++ b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py @@ -8,12 +8,12 @@ from warnings import warn from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC from IPython.utils import io -from IPython.utils.py3compat import PY3, cast_unicode_py2, input, string_types +from IPython.utils.py3compat import PY3, cast_unicode_py2, input, string_types from IPython.utils.terminal import toggle_set_term_title, set_term_title from IPython.utils.process import abbrev_cwd -from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union +from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union -from prompt_toolkit.document import Document +from prompt_toolkit.document import Document from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode from prompt_toolkit.filters import (HasFocus, Condition, IsDone) from prompt_toolkit.history import InMemoryHistory @@ -23,13 +23,13 @@ from prompt_toolkit.key_binding.manager import KeyBindingManager from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor from prompt_toolkit.styles import PygmentsStyle, DynamicStyle -from pygments.styles import get_style_by_name -from pygments.style import Style +from pygments.styles import get_style_by_name +from pygments.style import Style from pygments.token import Token from .debugger import TerminalPdb, Pdb from .magics import TerminalMagics -from .pt_inputhooks import get_inputhook_name_and_func +from .pt_inputhooks import get_inputhook_name_and_func from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook from .ptutils import IPythonPTCompleter, IPythonPTLexer from .shortcuts import register_ipython_shortcuts @@ -104,7 +104,7 @@ class TerminalInteractiveShell(InteractiveShell): _pt_app = None simple_prompt = Bool(_use_simple_prompt, - help="""Use `raw_input` for the REPL, without completion and prompt colors. + help="""Use `raw_input` for the REPL, without completion and prompt colors. 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. @@ -134,21 +134,21 @@ class TerminalInteractiveShell(InteractiveShell): help="Enable mouse support in the prompt" ).tag(config=True) - # We don't load the list of styles for the help string, because loading - # Pygments plugins takes time and can cause unexpected errors. - highlighting_style = Union([Unicode('legacy'), Type(klass=Style)], - help="""The name or class of a Pygments style to use for syntax - highlighting. To see available styles, run `pygmentize -L styles`.""" + # We don't load the list of styles for the help string, because loading + # Pygments plugins takes time and can cause unexpected errors. + highlighting_style = Union([Unicode('legacy'), Type(klass=Style)], + help="""The name or class of a Pygments style to use for syntax + highlighting. To see available styles, run `pygmentize -L styles`.""" ).tag(config=True) - + @observe('highlighting_style') @observe('colors') def _highlighting_style_changed(self, change): self.refresh_style() def refresh_style(self): - self._style = self._make_style_from_name_or_cls(self.highlighting_style) + self._style = self._make_style_from_name_or_cls(self.highlighting_style) highlighting_style_overrides = Dict( @@ -186,7 +186,7 @@ class TerminalInteractiveShell(InteractiveShell): help="Automatically set the terminal title" ).tag(config=True) - display_completions = Enum(('column', 'multicolumn','readlinelike'), + display_completions = Enum(('column', 'multicolumn','readlinelike'), help= ( "Options for displaying tab completions, 'column', 'multicolumn', and " "'readlinelike'. These options are for `prompt_toolkit`, see " "`prompt_toolkit` documentation for more information." @@ -194,14 +194,14 @@ class TerminalInteractiveShell(InteractiveShell): default_value='multicolumn').tag(config=True) highlight_matching_brackets = Bool(True, - 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." + 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." + ).tag(config=True) + @observe('term_title') def init_term_title(self, change=None): # Enable or disable the terminal title. @@ -215,29 +215,29 @@ class TerminalInteractiveShell(InteractiveShell): super(TerminalInteractiveShell, self).init_display_formatter() # terminal only supports plain text self.display_formatter.active_types = ['text/plain'] - # disable `_ipython_display_` - self.display_formatter.ipython_display_formatter.enabled = False + # disable `_ipython_display_` + self.display_formatter.ipython_display_formatter.enabled = False def init_prompt_toolkit_cli(self): if self.simple_prompt: # Fall back to plain non-interactive output for tests. # This is very limited, and only accepts a single line. def prompt(): - isp = self.input_splitter - prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens()) - prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens()) - while isp.push_accepts_more(): - line = cast_unicode_py2(input(prompt_text)) - isp.push(line) - prompt_text = prompt_continuation - return isp.source_reset() + isp = self.input_splitter + prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens()) + prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens()) + while isp.push_accepts_more(): + line = cast_unicode_py2(input(prompt_text)) + isp.push(line) + prompt_text = prompt_continuation + return isp.source_reset() self.prompt_for_code = prompt return # Set up keyboard shortcuts - kbmanager = KeyBindingManager.for_prompt( - enable_open_in_editor=self.extra_open_editor_shortcuts, - ) + kbmanager = KeyBindingManager.for_prompt( + enable_open_in_editor=self.extra_open_editor_shortcuts, + ) register_ipython_shortcuts(kbmanager.registry, self) # Pre-populate history from IPython's history database @@ -249,24 +249,24 @@ class TerminalInteractiveShell(InteractiveShell): cell = cell.rstrip() if cell and (cell != last_cell): history.append(cell) - last_cell = cell + last_cell = cell - self._style = self._make_style_from_name_or_cls(self.highlighting_style) - self.style = DynamicStyle(lambda: self._style) + self._style = self._make_style_from_name_or_cls(self.highlighting_style) + self.style = DynamicStyle(lambda: self._style) editing_mode = getattr(EditingMode, self.editing_mode.upper()) - def patch_stdout(**kwargs): - return self.pt_cli.patch_stdout_context(**kwargs) - + def patch_stdout(**kwargs): + return self.pt_cli.patch_stdout_context(**kwargs) + self._pt_app = create_prompt_application( editing_mode=editing_mode, key_bindings_registry=kbmanager.registry, history=history, - completer=IPythonPTCompleter(shell=self, - patch_stdout=patch_stdout), + completer=IPythonPTCompleter(shell=self, + patch_stdout=patch_stdout), enable_history_search=True, - style=self.style, + style=self.style, mouse_support=self.mouse_support, **self._layout_options() ) @@ -275,14 +275,14 @@ class TerminalInteractiveShell(InteractiveShell): self._pt_app, eventloop=self._eventloop, output=create_output(true_color=self.true_color)) - def _make_style_from_name_or_cls(self, name_or_cls): + def _make_style_from_name_or_cls(self, name_or_cls): """ Small wrapper that make an IPython compatible style from a style name - We need that to add style for prompt ... etc. + We need that to add style for prompt ... etc. """ style_overrides = {} - if name_or_cls == 'legacy': + if name_or_cls == 'legacy': legacy = self.colors.lower() if legacy == 'linux': style_cls = get_style_by_name('monokai') @@ -307,26 +307,26 @@ class TerminalInteractiveShell(InteractiveShell): Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', }) - - # 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', - }) + + # 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', + }) elif legacy =='nocolor': style_cls=_NoStyle style_overrides = {} else : raise ValueError('Got unknown colors: ', legacy) else : - if isinstance(name_or_cls, string_types): - style_cls = get_style_by_name(name_or_cls) - else: - style_cls = name_or_cls + if isinstance(name_or_cls, string_types): + style_cls = get_style_by_name(name_or_cls) + else: + style_cls = name_or_cls style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', @@ -373,11 +373,11 @@ class TerminalInteractiveShell(InteractiveShell): return document.text def enable_win_unicode_console(self): - if sys.version_info >= (3, 6): - # Since PEP 528, Python uses the unicode APIs for the Windows - # console by default, so WUC shouldn't be needed. - return - + if sys.version_info >= (3, 6): + # Since PEP 528, Python uses the unicode APIs for the Windows + # console by default, so WUC shouldn't be needed. + return + import win_unicode_console if PY3: @@ -451,18 +451,18 @@ class TerminalInteractiveShell(InteractiveShell): def pre_prompt(self): if self.rl_next_input: - # We can't set the buffer here, because it will be reset just after - # this. Adding a callable to pre_run_callables does what we need - # after the buffer is reset. - s = cast_unicode_py2(self.rl_next_input) - def set_doc(): - self.pt_cli.application.buffer.document = Document(s) - if hasattr(self.pt_cli, 'pre_run_callables'): - self.pt_cli.pre_run_callables.append(set_doc) - else: - # Older version of prompt_toolkit; it's OK to set the document - # directly here. - set_doc() + # We can't set the buffer here, because it will be reset just after + # this. Adding a callable to pre_run_callables does what we need + # after the buffer is reset. + s = cast_unicode_py2(self.rl_next_input) + def set_doc(): + self.pt_cli.application.buffer.document = Document(s) + if hasattr(self.pt_cli, 'pre_run_callables'): + self.pt_cli.pre_run_callables.append(set_doc) + else: + # Older version of prompt_toolkit; it's OK to set the document + # directly here. + set_doc() self.rl_next_input = None def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED): @@ -494,28 +494,28 @@ class TerminalInteractiveShell(InteractiveShell): try: self.interact() break - except KeyboardInterrupt as e: - print("\n%s escaped interact()\n" % type(e).__name__) - finally: - # 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() + except KeyboardInterrupt as e: + print("\n%s escaped interact()\n" % type(e).__name__) + finally: + # 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() _inputhook = None def inputhook(self, context): if self._inputhook is not None: self._inputhook(context) - active_eventloop = None + active_eventloop = None def enable_gui(self, gui=None): if gui: - self.active_eventloop, self._inputhook =\ - get_inputhook_name_and_func(gui) + self.active_eventloop, self._inputhook =\ + get_inputhook_name_and_func(gui) else: - self.active_eventloop = self._inputhook = None + self.active_eventloop = self._inputhook = None # Run !system commands directly, not through pipes, so terminal programs # work correctly. diff --git a/contrib/python/ipython/py2/IPython/terminal/ipapp.py b/contrib/python/ipython/py2/IPython/terminal/ipapp.py index 6b25aaa3e36..5f6ba299626 100755 --- a/contrib/python/ipython/py2/IPython/terminal/ipapp.py +++ b/contrib/python/ipython/py2/IPython/terminal/ipapp.py @@ -35,7 +35,7 @@ from IPython.extensions.storemagic import StoreMagics from .interactiveshell import TerminalInteractiveShell from IPython.paths import get_ipython_dir from traitlets import ( - Bool, List, Dict, default, observe, Type + Bool, List, Dict, default, observe, Type ) #----------------------------------------------------------------------------- @@ -185,13 +185,13 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): flags = Dict(flags) aliases = Dict(aliases) classes = List() - - interactive_shell_class = Type( - klass=object, # use default_value otherwise which only allow subclasses. - default_value=TerminalInteractiveShell, - help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends" - ).tag(config=True) - + + interactive_shell_class = Type( + klass=object, # use default_value otherwise which only allow subclasses. + default_value=TerminalInteractiveShell, + help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends" + ).tag(config=True) + @default('classes') def _classes_default(self): """This has to be in a method, for TerminalIPythonApp to be available.""" @@ -327,7 +327,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): # shell.display_banner should always be False for the terminal # based app, because we call shell.show_banner() by hand below # so the banner shows *before* all extension loading stuff. - self.shell = self.interactive_shell_class.instance(parent=self, + self.shell = self.interactive_shell_class.instance(parent=self, profile_dir=self.profile_dir, ipython_dir=self.ipython_dir, user_ns=self.user_ns) self.shell.configurables.append(self) @@ -365,10 +365,10 @@ def load_default_config(ipython_dir=None): ipython_dir = get_ipython_dir() profile_dir = os.path.join(ipython_dir, 'profile_default') - app = TerminalIPythonApp() - app.config_file_paths.append(profile_dir) - app.load_config_file() - return app.config + app = TerminalIPythonApp() + app.config_file_paths.append(profile_dir) + app.load_config_file() + return app.config launch_new_instance = TerminalIPythonApp.launch_instance diff --git a/contrib/python/ipython/py2/IPython/terminal/magics.py b/contrib/python/ipython/py2/IPython/terminal/magics.py index 3a844a03970..c8b5ea5a352 100644 --- a/contrib/python/ipython/py2/IPython/terminal/magics.py +++ b/contrib/python/ipython/py2/IPython/terminal/magics.py @@ -82,9 +82,9 @@ class TerminalMagics(Magics): @line_magic def autoindent(self, parameter_s = ''): - """Toggle autoindent on/off (deprecated)""" - print("%autoindent is deprecated since IPython 5: you can now paste " - "multiple lines without turning autoindentation off.") + """Toggle autoindent on/off (deprecated)""" + print("%autoindent is deprecated since IPython 5: you can now paste " + "multiple lines without turning autoindentation off.") self.shell.set_autoindent() print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent]) diff --git a/contrib/python/ipython/py2/IPython/terminal/prompts.py b/contrib/python/ipython/py2/IPython/terminal/prompts.py index 43c21705033..d153289c439 100644 --- a/contrib/python/ipython/py2/IPython/terminal/prompts.py +++ b/contrib/python/ipython/py2/IPython/terminal/prompts.py @@ -63,18 +63,18 @@ class RichPromptDisplayHook(DisplayHook): """Subclass of base display hook using coloured prompt""" def write_output_prompt(self): sys.stdout.write(self.shell.separate_out) - # If we're not displaying a prompt, it effectively ends with a newline, - # because the output will be left-aligned. - self.prompt_end_newline = True - + # If we're not displaying a prompt, it effectively ends with a newline, + # because the output will be left-aligned. + self.prompt_end_newline = True + if self.do_full_cache: tokens = self.shell.prompts.out_prompt_tokens() - prompt_txt = ''.join(s for t, s in tokens) - if prompt_txt and not prompt_txt.endswith('\n'): - # Ask for a newline before multiline output - self.prompt_end_newline = False - + prompt_txt = ''.join(s for t, s in tokens) + if prompt_txt and not prompt_txt.endswith('\n'): + # Ask for a newline before multiline output + self.prompt_end_newline = False + if self.shell.pt_cli: self.shell.pt_cli.print_tokens(tokens) else: - sys.stdout.write(prompt_txt) + sys.stdout.write(prompt_txt) diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py index 3766973e826..3f45bc1cd13 100644 --- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py +++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py @@ -30,20 +30,20 @@ class UnknownBackend(KeyError): "Supported event loops are: {}").format(self.name, ', '.join(backends + sorted(registered))) -def get_inputhook_name_and_func(gui): +def get_inputhook_name_and_func(gui): if gui in registered: - return gui, registered[gui] + return gui, registered[gui] if gui not in backends: raise UnknownBackend(gui) if gui in aliases: - return get_inputhook_name_and_func(aliases[gui]) + return get_inputhook_name_and_func(aliases[gui]) - gui_mod = gui + gui_mod = gui if gui == 'qt5': os.environ['QT_API'] = 'pyqt5' - gui_mod = 'qt' + gui_mod = 'qt' - mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod) - return gui, mod.inputhook + mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod) + return gui, mod.inputhook diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py index 7395ac39ebe..536050e8cd1 100644 --- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py +++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py @@ -39,11 +39,11 @@ def inputhook(context): else: # On POSIX platforms, we can use a file descriptor to quit the event # loop when there is input ready to read. - notifier = QtCore.QSocketNotifier(context.fileno(), - QtCore.QSocketNotifier.Read) - # connect the callback we care about before we turn it on - notifier.activated.connect(event_loop.exit) + notifier = QtCore.QSocketNotifier(context.fileno(), + QtCore.QSocketNotifier.Read) + # connect the callback we care about before we turn it on + notifier.activated.connect(event_loop.exit) notifier.setEnabled(True) - # only start the event loop we are not already flipped - if not context.input_is_ready(): - event_loop.exec_() + # only start the event loop we are not already flipped + if not context.input_is_ready(): + event_loop.exec_() diff --git a/contrib/python/ipython/py2/IPython/terminal/ptutils.py b/contrib/python/ipython/py2/IPython/terminal/ptutils.py index c9ff705642d..03e33155b19 100644 --- a/contrib/python/ipython/py2/IPython/terminal/ptutils.py +++ b/contrib/python/ipython/py2/IPython/terminal/ptutils.py @@ -22,14 +22,14 @@ import pygments.lexers as pygments_lexers class IPythonPTCompleter(Completer): """Adaptor to provide IPython completions to prompt_toolkit""" - def __init__(self, ipy_completer=None, shell=None, patch_stdout=None): + def __init__(self, ipy_completer=None, shell=None, patch_stdout=None): if shell is None and ipy_completer is None: raise TypeError("Please pass shell=an InteractiveShell instance.") self._ipy_completer = ipy_completer self.shell = shell - if patch_stdout is None: - raise TypeError("Please pass patch_stdout") - self.patch_stdout = patch_stdout + if patch_stdout is None: + raise TypeError("Please pass patch_stdout") + self.patch_stdout = patch_stdout @property def ipy_completer(self): @@ -42,14 +42,14 @@ class IPythonPTCompleter(Completer): if not document.current_line.strip(): return - # Some bits of our completion system may print stuff (e.g. if a module - # is imported). This context manager ensures that doesn't interfere with - # the prompt. - with self.patch_stdout(): - used, matches = self.ipy_completer.complete( - line_buffer=document.current_line, - cursor_pos=document.cursor_position_col - ) + # Some bits of our completion system may print stuff (e.g. if a module + # is imported). This context manager ensures that doesn't interfere with + # the prompt. + with self.patch_stdout(): + used, matches = self.ipy_completer.complete( + line_buffer=document.current_line, + cursor_pos=document.cursor_position_col + ) start_pos = -len(used) for m in matches: if not m: diff --git a/contrib/python/ipython/py2/IPython/terminal/shortcuts.py b/contrib/python/ipython/py2/IPython/terminal/shortcuts.py index 8f0ae43e849..71ce01fe9c2 100644 --- a/contrib/python/ipython/py2/IPython/terminal/shortcuts.py +++ b/contrib/python/ipython/py2/IPython/terminal/shortcuts.py @@ -62,10 +62,10 @@ def register_ipython_shortcuts(registry, shell): filter=(HasFocus(DEFAULT_BUFFER) & EmacsInsertMode()))(newline_with_copy_margin) - registry.add_binding(Keys.F2, - filter=HasFocus(DEFAULT_BUFFER) - )(open_input_in_editor) - + registry.add_binding(Keys.F2, + filter=HasFocus(DEFAULT_BUFFER) + )(open_input_in_editor) + if shell.display_completions == 'readlinelike': registry.add_binding(Keys.ControlI, filter=(HasFocus(DEFAULT_BUFFER) @@ -96,18 +96,18 @@ def newline_or_execute_outer(shell): b.cancel_completion() return - # If there's only one line, treat it as if the cursor is at the end. - # See https://github.com/ipython/ipython/issues/10425 - if d.line_count == 1: - check_text = d.text - else: - check_text = d.text[:d.cursor_position] - status, indent = shell.input_splitter.check_complete(check_text + '\n') - - if not (d.on_last_line or - d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end() - ): - b.insert_text('\n' + (' ' * (indent or 0))) + # If there's only one line, treat it as if the cursor is at the end. + # See https://github.com/ipython/ipython/issues/10425 + if d.line_count == 1: + check_text = d.text + else: + check_text = d.text[:d.cursor_position] + status, indent = shell.input_splitter.check_complete(check_text + '\n') + + if not (d.on_last_line or + d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end() + ): + b.insert_text('\n' + (' ' * (indent or 0))) return if (status != 'incomplete') and b.accept_action.is_returnable: @@ -181,9 +181,9 @@ def newline_with_copy_margin(event): pos_diff = cursor_start_pos - cursor_end_pos b.cursor_right(count=pos_diff) -def open_input_in_editor(event): - event.cli.current_buffer.tempfile_suffix = ".py" - event.cli.current_buffer.open_in_editor(event.cli) +def open_input_in_editor(event): + event.cli.current_buffer.tempfile_suffix = ".py" + event.cli.current_buffer.open_in_editor(event.cli) if sys.platform == 'win32': |
