##// END OF EJS Templates
DOC: More autoreformatting of docstrings....
DOC: More autoreformatting of docstrings. Also add some configuration to ignore some files.

File last commit:

r26295:64598338
r26498:7c853204
Show More
shortcuts.py
372 lines | 11.7 KiB | text/x-python | PythonLexer
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334 """
Module to define and register Terminal IPython shortcuts with
Thomas Kluyver
Fix a couple of rst roles causing Sphinx warnings
r23428 :mod:`prompt_toolkit`
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334 """
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import warnings
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 import signal
import sys
Matthias Bussonnier
forgotten import
r26295 import re
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334 from typing import Callable
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 from prompt_toolkit.application.current import get_app
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 from prompt_toolkit.filters import (has_focus, has_selection, Condition,
vi_insert_mode, emacs_insert_mode, has_completions, vi_mode)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 from prompt_toolkit.key_binding import KeyBindings
Martin Skarzynski
add emacs keybindings to vi insert mode
r26067 from prompt_toolkit.key_binding.bindings import named_commands as nc
Martin Skarzynski
cursor shape changes with vi editing mode
r26113 from prompt_toolkit.key_binding.vi_state import InputMode, ViState
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Fernando Perez
Tag windows-only function so it doesn't get picked up on *nix doc builds.
r22670 from IPython.utils.decorators import undoc
Matthias Bussonnier
rst fixes
r23465 @undoc
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 @Condition
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 def cursor_in_leading_ws():
before = get_app().current_buffer.document.current_line_before_cursor
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 return (not before) or before.isspace()
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376
def create_ipython_shortcuts(shell):
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 """Set up the prompt_toolkit keyboard shortcuts for IPython"""
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376
kb = KeyBindings()
insert_mode = vi_insert_mode | emacs_insert_mode
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Thomas Kluyver
Allow configuring a function to handle return in the terminal...
r23580 if getattr(shell, 'handle_return', None):
return_handler = shell.handle_return(shell)
else:
return_handler = newline_or_execute_outer(shell)
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('enter', filter=(has_focus(DEFAULT_BUFFER)
& ~has_selection
& insert_mode
Thomas Kluyver
Allow configuring a function to handle return in the terminal...
r23580 ))(return_handler)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Matthias Bussonnier
some more work
r25142 def reformat_and_execute(event):
reformat_text_before_cursor(event.current_buffer, event.current_buffer.document, shell)
event.current_buffer.validate_and_handle()
kb.add('escape', 'enter', filter=(has_focus(DEFAULT_BUFFER)
& ~has_selection
& insert_mode
))(reformat_and_execute)
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('c-\\')(force_exit)
Matthias Bussonnier
Quit IPython on Ctrl-\ (SIGQUIT)...
r22739
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('c-p', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
)(previous_history_or_previous_completion)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('c-n', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
)(next_history_or_next_completion)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('c-g', filter=(has_focus(DEFAULT_BUFFER) & has_completions)
)(dismiss_completion)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('c-c', filter=has_focus(DEFAULT_BUFFER))(reset_buffer)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('c-c', filter=has_focus(SEARCH_BUFFER))(reset_search_buffer)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
# Ctrl+I == Tab
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
& ~has_selection
& insert_mode
& cursor_in_leading_ws
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 ))(indent_buffer)
Thomas Kluyver
Reformat for readability
r24408 kb.add('c-o', filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode)
)(newline_autoindent_outer(shell.input_transformer_manager))
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('f2', filter=has_focus(DEFAULT_BUFFER))(open_input_in_editor)
Carl Smith
Add shortcut to edit cell
r22851
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 if shell.display_completions == 'readlinelike':
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 kb.add('c-i', filter=(has_focus(DEFAULT_BUFFER)
& ~has_selection
& insert_mode
& ~cursor_in_leading_ws
))(display_completions_like_readline)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Matthias Bussonnier
reformat with darker
r26091 if sys.platform == "win32":
kb.add("c-v", filter=(has_focus(DEFAULT_BUFFER) & ~vi_mode))(win_paste)
Martin Skarzynski
add emacs keybindings to vi insert mode
r26067
@Condition
def ebivim():
return shell.emacs_bindings_in_vi_insert_mode
focused_insert = has_focus(DEFAULT_BUFFER) & vi_insert_mode
# Needed for to accept autosuggestions in vi insert mode
@kb.add("c-e", filter=focused_insert & ebivim)
def _(event):
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
else:
nc.end_of_line(event)
@kb.add("c-f", filter=focused_insert & ebivim)
def _(event):
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
else:
nc.forward_char(event)
@kb.add("escape", "f", filter=focused_insert & ebivim)
def _(event):
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
t = re.split(r"(\S+\s+)", suggestion.text)
b.insert_text(next((x for x in t if x), ""))
else:
nc.forward_word(event)
# Simple Control keybindings
key_cmd_dict = {
"c-a": nc.beginning_of_line,
"c-b": nc.backward_char,
"c-k": nc.kill_line,
"c-w": nc.backward_kill_word,
"c-y": nc.yank,
"c-_": nc.undo,
}
for key, cmd in key_cmd_dict.items():
kb.add(key, filter=focused_insert & ebivim)(cmd)
# Alt and Combo Control keybindings
keys_cmd_dict = {
# Control Combos
("c-x", "c-e"): nc.edit_and_execute,
("c-x", "e"): nc.edit_and_execute,
# Alt
("escape", "b"): nc.backward_word,
("escape", "c"): nc.capitalize_word,
("escape", "d"): nc.kill_word,
("escape", "h"): nc.backward_kill_word,
("escape", "l"): nc.downcase_word,
("escape", "u"): nc.uppercase_word,
("escape", "y"): nc.yank_pop,
("escape", "."): nc.yank_last_arg,
}
for keys, cmd in keys_cmd_dict.items():
kb.add(*keys, filter=focused_insert & ebivim)(cmd)
Martin Skarzynski
cursor shape changes with vi editing mode
r26113 def get_input_mode(self):
if sys.version_info[0] == 3:
app = get_app()
app.ttimeoutlen = shell.ttimeoutlen
app.timeoutlen = shell.timeoutlen
return self._input_mode
def set_input_mode(self, mode):
shape = {InputMode.NAVIGATION: 2, InputMode.REPLACE: 4}.get(mode, 6)
cursor = "\x1b[{} q".format(shape)
if hasattr(sys.stdout, "_cli"):
write = sys.stdout._cli.output.write_raw
else:
write = sys.stdout.write
write(cursor)
sys.stdout.flush()
self._input_mode = mode
if shell.editing_mode == "vi" and shell.modal_cursor:
ViState._input_mode = InputMode.INSERT
ViState.input_mode = property(get_input_mode, set_input_mode)
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 return kb
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Matthias Bussonnier
some more work
r25142 def reformat_text_before_cursor(buffer, document, shell):
text = buffer.delete_before_cursor(len(document.text[:document.cursor_position]))
try:
formatted_text = shell.reformat_handler(text)
buffer.insert_text(formatted_text)
except Exception as e:
buffer.insert_text(text)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 def newline_or_execute_outer(shell):
Matthias Bussonnier
autoformat with black
r25141
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 def newline_or_execute(event):
"""When the user presses return, insert a newline or execute the code."""
b = event.current_buffer
d = b.document
if b.complete_state:
cc = b.complete_state.current_completion
if cc:
b.apply_completion(cc)
else:
b.cancel_completion()
return
Thomas Kluyver
Prefer execution when there's only a single line entered...
r23577 # 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]
Thomas Kluyver
Add shell.check_complete() method...
r24180 status, indent = shell.check_complete(check_text)
Matthias Bussonnier
some more work
r25142
# if all we have after the cursor is whitespace: reformat current text
# before cursor
Matthias Bussonnier
update code to work with black more recent versions
r25242 after_cursor = d.text[d.cursor_position:]
Matthias Bussonnier
Fix auto formatting to be called only once....
r25753 reformatted = False
Matthias Bussonnier
update code to work with black more recent versions
r25242 if not after_cursor.strip():
Matthias Bussonnier
some more work
r25142 reformat_text_before_cursor(b, d, shell)
Matthias Bussonnier
Fix auto formatting to be called only once....
r25753 reformatted = True
Matthias Bussonnier
Indent on new line by looking at the text before the cursor....
r23323 if not (d.on_last_line or
d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
):
Matthias Bussonnier
Undeprecate autoindent...
r24498 if shell.autoindent:
Matthias Bussonnier
Merge remote-tracking branch 'origin/master' into inputtransformer2
r24502 b.insert_text('\n' + indent)
Matthias Bussonnier
Undeprecate autoindent...
r24498 else:
b.insert_text('\n')
Matthias Bussonnier
Indent on new line by looking at the text before the cursor....
r23323 return
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 if (status != 'incomplete') and b.accept_handler:
Matthias Bussonnier
Fix auto formatting to be called only once....
r25753 if not reformatted:
reformat_text_before_cursor(b, d, shell)
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 b.validate_and_handle()
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 else:
Matthias Bussonnier
Undeprecate autoindent...
r24498 if shell.autoindent:
Matthias Bussonnier
Merge remote-tracking branch 'origin/master' into inputtransformer2
r24502 b.insert_text('\n' + indent)
Matthias Bussonnier
Undeprecate autoindent...
r24498 else:
b.insert_text('\n')
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 return newline_or_execute
def previous_history_or_previous_completion(event):
"""
Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
If completer is open this still select previous completion.
"""
event.current_buffer.auto_up()
def next_history_or_next_completion(event):
"""
Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
If completer is open this still select next completion.
"""
event.current_buffer.auto_down()
def dismiss_completion(event):
b = event.current_buffer
if b.complete_state:
b.cancel_completion()
def reset_buffer(event):
b = event.current_buffer
if b.complete_state:
b.cancel_completion()
else:
b.reset()
def reset_search_buffer(event):
if event.current_buffer.document.text:
event.current_buffer.reset()
else:
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 event.app.layout.focus(DEFAULT_BUFFER)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
def suspend_to_bg(event):
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 event.app.suspend_to_background()
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Matthias Bussonnier
Quit IPython on Ctrl-\ (SIGQUIT)...
r22739 def force_exit(event):
"""
Force exit (with a non-zero return value)
"""
sys.exit("Quit")
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 def indent_buffer(event):
event.current_buffer.insert_text(' ' * 4)
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334 @undoc
Gil Forsyth
preserve margins when using Ctrl-O for newline...
r22695 def newline_with_copy_margin(event):
"""
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334 DEPRECATED since IPython 6.0
See :any:`newline_autoindent_outer` for a replacement.
Gil Forsyth
preserve margins when using Ctrl-O for newline...
r22695 Preserve margin and cursor position when using
Control-O to insert a newline in EMACS mode
"""
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334 warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. "
"see `newline_autoindent_outer(shell)(event)` for a replacement.",
DeprecationWarning, stacklevel=2)
Gil Forsyth
preserve margins when using Ctrl-O for newline...
r22695 b = event.current_buffer
cursor_start_pos = b.document.cursor_position_col
b.newline(copy_margin=True)
b.cursor_up(count=1)
cursor_end_pos = b.document.cursor_position_col
if cursor_start_pos != cursor_end_pos:
pos_diff = cursor_start_pos - cursor_end_pos
b.cursor_right(count=pos_diff)
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334 def newline_autoindent_outer(inputsplitter) -> Callable[..., None]:
"""
Return a function suitable for inserting a indented newline after the cursor.
Fancier version of deprecated ``newline_with_copy_margin`` which should
compute the correct indentation of the inserted line. That is to say, indent
by 4 extra space after a function definition, class definition, context
manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.
"""
def newline_autoindent(event):
"""insert a newline after the cursor indented appropriately."""
b = event.current_buffer
d = b.document
if b.complete_state:
b.cancel_completion()
text = d.text[:d.cursor_position] + '\n'
_, indent = inputsplitter.check_complete(text)
b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False)
return newline_autoindent
Carl Smith
Add shortcut to edit cell
r22851 def open_input_in_editor(event):
Jonathan Slenders
Upgrade to prompt_toolkit 2.0
r24376 event.app.current_buffer.open_in_editor()
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
if sys.platform == 'win32':
from IPython.core.error import TryNext
from IPython.lib.clipboard import (ClipboardEmpty,
win32_clipboard_get,
tkinter_clipboard_get)
Fernando Perez
Tag windows-only function so it doesn't get picked up on *nix doc builds.
r22670 @undoc
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 def win_paste(event):
try:
text = win32_clipboard_get()
except TryNext:
try:
text = tkinter_clipboard_get()
except (TryNext, ClipboardEmpty):
return
except ClipboardEmpty:
return
Martin Skarzynski
cursor shape changes with vi editing mode
r26113 event.current_buffer.insert_text(text.replace("\t", " " * 4))