##// END OF EJS Templates
MAINT: fix typing mypy 1.0
MAINT: fix typing mypy 1.0

File last commit:

r28050:a885b478
r28091:33fde841
Show More
__init__.py
670 lines | 20.0 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.
Matthias Bussonnier
Misc review cleanup....
r28029 import os
import re
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 import signal
import sys
Matthias Bussonnier
Misc review cleanup....
r28029 import warnings
krassowski
Fix mypy job, fix issues detected by mypy
r28011 from typing import Callable, Dict, Union
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334
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
Matthias Bussonnier
Misc review cleanup....
r28029 from prompt_toolkit.filters import Condition, emacs_insert_mode, has_completions
from prompt_toolkit.filters import has_focus as has_focus_impl
krassowski
Restore shortcuts in documentation, define identifiers
r28010 from prompt_toolkit.filters import (
has_selection,
Matthias Bussonnier
Misc review cleanup....
r28029 has_suggestion,
krassowski
Restore shortcuts in documentation, define identifiers
r28010 vi_insert_mode,
vi_mode,
)
Matthias Bussonnier
Misc review cleanup....
r28029 from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.key_binding.bindings import named_commands as nc
krassowski
Restore shortcuts in documentation, define identifiers
r28010 from prompt_toolkit.key_binding.bindings.completion import (
display_completions_like_readline,
)
Martin Skarzynski
cursor shape changes with vi editing mode
r26113 from prompt_toolkit.key_binding.vi_state import InputMode, ViState
krassowski
Restore shortcuts in documentation, define identifiers
r28010 from prompt_toolkit.layout.layout import FocusableElement
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
Matthias Bussonnier
Misc review cleanup....
r28029 from IPython.terminal.shortcuts import auto_match as match
from IPython.terminal.shortcuts import auto_suggest
Fernando Perez
Tag windows-only function so it doesn't get picked up on *nix doc builds.
r22670 from IPython.utils.decorators import undoc
krassowski
Restore shortcuts in documentation, define identifiers
r28010
__all__ = ["create_ipython_shortcuts"]
Fernando Perez
Tag windows-only function so it doesn't get picked up on *nix doc builds.
r22670
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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 def has_focus(value: FocusableElement):
"""Wrapper around has_focus adding a nice `__name__` to tester function"""
tester = has_focus_impl(value).func
tester.__name__ = f"is_focused({value})"
return Condition(tester)
Matthias Bussonnier
Apply autosuggestion only at EOL....
r27713
krassowski
Restore shortcuts in documentation, define identifiers
r28010
krassowski
Add missing line_below/line_above conditions
r28042 @undoc
krassowski
Autosuggest: only navigate on edges of doc, show in multi-line doc
r28041 @Condition
def has_line_below() -> bool:
document = get_app().current_buffer.document
return document.cursor_position_row < len(document.lines) - 1
krassowski
Add missing line_below/line_above conditions
r28042 @undoc
krassowski
Autosuggest: only navigate on edges of doc, show in multi-line doc
r28041 @Condition
def has_line_above() -> bool:
document = get_app().current_buffer.document
return document.cursor_position_row != 0
Matthias Bussonnier
Misc review cleanup....
r28029 def create_ipython_shortcuts(shell, for_all_platforms: bool = False) -> KeyBindings:
"""Set up the prompt_toolkit keyboard shortcuts for IPython.
Parameters
----------
shell: InteractiveShell
The current IPython shell Instance
for_all_platforms: bool (default false)
This parameter is mostly used in generating the documentation
to create the shortcut binding for all the platforms, and export
them.
Returns
-------
KeyBindings
the keybinding instance for prompt toolkit.
"""
krassowski
Restore shortcuts in documentation, define identifiers
r28010 # Warning: if possible, do NOT define handler functions in the locals
# scope of this function, instead define functions in the global
# scope, or a separate module, and include a user-friendly docstring
# describing the action.
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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 if getattr(shell, "handle_return", None):
Thomas Kluyver
Allow configuring a function to handle return in the terminal...
r23580 return_handler = shell.handle_return(shell)
else:
return_handler = newline_or_execute_outer(shell)
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add("enter", filter=(has_focus(DEFAULT_BUFFER) & ~has_selection & insert_mode))(
return_handler
)
Matthias Bussonnier
some more work
r25142
Jake Herrmann
Fix vi mode escape delay
r27981 @Condition
def ebivim():
return shell.emacs_bindings_in_vi_insert_mode
krassowski
Restore shortcuts in documentation, define identifiers
r28010 @kb.add(
Matthias Bussonnier
please formatter
r27982 "escape",
"enter",
filter=(has_focus(DEFAULT_BUFFER) & ~has_selection & insert_mode & ebivim),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )
def reformat_and_execute(event):
"""Reformat code and execute it"""
reformat_text_before_cursor(
event.current_buffer, event.current_buffer.document, shell
)
event.current_buffer.validate_and_handle()
Matthias Bussonnier
some more work
r25142
Maor Kleinberger
Fix ctrl-\ behavior...
r27599 kb.add("c-\\")(quit)
Matthias Bussonnier
Quit IPython on Ctrl-\ (SIGQUIT)...
r22739
krassowski
Restore shortcuts in documentation, define identifiers
r28010 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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add("c-g", filter=(has_focus(DEFAULT_BUFFER) & has_completions))(
dismiss_completion
)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add("c-c", filter=has_focus(DEFAULT_BUFFER))(reset_buffer)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add("c-c", filter=has_focus(SEARCH_BUFFER))(reset_search_buffer)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
krassowski
Restore shortcuts in documentation, define identifiers
r28010 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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add(
"tab",
filter=(
has_focus(DEFAULT_BUFFER)
& ~has_selection
& insert_mode
& cursor_in_leading_ws
),
)(indent_buffer)
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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add("f2", filter=has_focus(DEFAULT_BUFFER))(open_input_in_editor)
Carl Smith
Add shortcut to edit cell
r22851
Martin Skarzynski
Add setting to toggle auto_match feature
r27375 @Condition
def auto_match():
return shell.auto_match
satoru
Fix #13654, improve performance of auto match for quotes...
r27762 def all_quotes_paired(quote, buf):
paired = True
i = 0
while i < len(buf):
c = buf[i]
if c == quote:
paired = not paired
satoru
Fix format
r27763 elif c == "\\":
satoru
Fix #13654, improve performance of auto match for quotes...
r27762 i += 1
i += 1
return paired
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373 focused_insert = (vi_insert_mode | emacs_insert_mode) & has_focus(DEFAULT_BUFFER)
krassowski
Fix mypy job, fix issues detected by mypy
r28011 _preceding_text_cache: Dict[Union[str, Callable], Condition] = {}
_following_text_cache: Dict[Union[str, Callable], Condition] = {}
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373
krassowski
Fix mypy job, fix issues detected by mypy
r28011 def preceding_text(pattern: Union[str, Callable]):
satoru
Fix #13654, improve performance of auto match for quotes...
r27762 if pattern in _preceding_text_cache:
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373 return _preceding_text_cache[pattern]
satoru
Fix #13654, improve performance of auto match for quotes...
r27762 if callable(pattern):
Matthias Bussonnier
Reformat and move some mapping to global location.
r28032
satoru
Fix #13654, improve performance of auto match for quotes...
r27762 def _preceding_text():
app = get_app()
before_cursor = app.current_buffer.document.current_line_before_cursor
Matthias Bussonnier
MISC docs, cleanup and typing (in progress).
r28028 # mypy can't infer if(callable): https://github.com/python/mypy/issues/3603
return bool(pattern(before_cursor)) # type: ignore[operator]
satoru
Fix format
r27763
satoru
Fix #13654, improve performance of auto match for quotes...
r27762 else:
m = re.compile(pattern)
def _preceding_text():
app = get_app()
satoru
Fix format
r27763 before_cursor = app.current_buffer.document.current_line_before_cursor
return bool(m.match(before_cursor))
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373
krassowski
Restore shortcuts in documentation, define identifiers
r28010 _preceding_text.__name__ = f"preceding_text({pattern!r})"
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373 condition = Condition(_preceding_text)
_preceding_text_cache[pattern] = condition
return condition
def following_text(pattern):
try:
return _following_text_cache[pattern]
except KeyError:
pass
m = re.compile(pattern)
def _following_text():
app = get_app()
return bool(m.match(app.current_buffer.document.current_line_after_cursor))
krassowski
Restore shortcuts in documentation, define identifiers
r28010 _following_text.__name__ = f"following_text({pattern!r})"
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373 condition = Condition(_following_text)
_following_text_cache[pattern] = condition
return condition
Lucy McPhail
Improve auto_match for triple quotes and escaped quotes
r27737 @Condition
def not_inside_unclosed_string():
app = get_app()
s = app.current_buffer.document.text_before_cursor
# remove escaped quotes
s = s.replace('\\"', "").replace("\\'", "")
# remove triple-quoted string literals
s = re.sub(r"(?:\"\"\"[\s\S]*\"\"\"|'''[\s\S]*''')", "", s)
# remove single-quoted string literals
s = re.sub(r"""(?:"[^"]*["\n]|'[^']*['\n])""", "", s)
return not ('"' in s or "'" in s)
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373 # auto match
Matthias Bussonnier
Reformat and move some mapping to global location.
r28032 for key, cmd in match.auto_match_parens.items():
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add(key, filter=focused_insert & auto_match & following_text(r"[,)}\]]|$"))(
cmd
)
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373
Matthias Bussonnier
Reformat and move some mapping to global location.
r28032 # raw string
for key, cmd in match.auto_match_parens_raw_string.items():
kb.add(
key,
filter=focused_insert & auto_match & preceding_text(r".*(r|R)[\"'](-*)$"),
)(cmd)
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add(
Lucy McPhail
Improve auto_match for quotes...
r27530 '"',
filter=focused_insert
& auto_match
Lucy McPhail
Improve auto_match for triple quotes and escaped quotes
r27737 & not_inside_unclosed_string
satoru
Fix #13654, improve performance of auto match for quotes...
r27762 & preceding_text(lambda line: all_quotes_paired('"', line))
Lucy McPhail
Improve auto_match for quotes...
r27530 & following_text(r"[,)}\]]|$"),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )(match.double_quote)
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add(
Lucy McPhail
Improve auto_match for quotes...
r27530 "'",
filter=focused_insert
& auto_match
Lucy McPhail
Improve auto_match for triple quotes and escaped quotes
r27737 & not_inside_unclosed_string
satoru
Fix #13654, improve performance of auto match for quotes...
r27762 & preceding_text(lambda line: all_quotes_paired("'", line))
Lucy McPhail
Improve auto_match for quotes...
r27530 & following_text(r"[,)}\]]|$"),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )(match.single_quote)
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add(
Lucy McPhail
Improve auto_match for triple quotes and escaped quotes
r27737 '"',
filter=focused_insert
& auto_match
& not_inside_unclosed_string
& preceding_text(r'^.*""$'),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )(match.docstring_double_quotes)
Lucy McPhail
Improve auto_match for triple quotes and escaped quotes
r27737
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add(
Lucy McPhail
Improve auto_match for triple quotes and escaped quotes
r27737 "'",
filter=focused_insert
& auto_match
& not_inside_unclosed_string
& preceding_text(r"^.*''$"),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )(match.docstring_single_quotes)
Lucy McPhail
Improve auto_match for triple quotes and escaped quotes
r27737
krassowski
Restore shortcuts in documentation, define identifiers
r28010 # just move cursor
kb.add(")", filter=focused_insert & auto_match & following_text(r"^\)"))(
match.skip_over
Gal B
Add missing auto_match flag in shortcuts.py...
r27477 )
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add("]", filter=focused_insert & auto_match & following_text(r"^\]"))(
match.skip_over
)
kb.add("}", filter=focused_insert & auto_match & following_text(r"^\}"))(
match.skip_over
)
kb.add('"', filter=focused_insert & auto_match & following_text('^"'))(
match.skip_over
)
kb.add("'", filter=focused_insert & auto_match & following_text("^'"))(
match.skip_over
Gal B
Add missing auto_match flag in shortcuts.py...
r27477 )
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add(
Matthias Bussonnier
autoreformat
r27374 "backspace",
Martin Skarzynski
Add setting to toggle auto_match feature
r27375 filter=focused_insert
& preceding_text(r".*\($")
& auto_match
& following_text(r"^\)"),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )(match.delete_pair)
kb.add(
Matthias Bussonnier
autoreformat
r27374 "backspace",
Martin Skarzynski
Add setting to toggle auto_match feature
r27375 filter=focused_insert
& preceding_text(r".*\[$")
& auto_match
& following_text(r"^\]"),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )(match.delete_pair)
kb.add(
Matthias Bussonnier
autoreformat
r27374 "backspace",
Martin Skarzynski
Add setting to toggle auto_match feature
r27375 filter=focused_insert
& preceding_text(r".*\{$")
& auto_match
& following_text(r"^\}"),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )(match.delete_pair)
kb.add(
Matthias Bussonnier
autoreformat
r27374 "backspace",
Martin Skarzynski
Add setting to toggle auto_match feature
r27375 filter=focused_insert
& preceding_text('.*"$')
& auto_match
& following_text('^"'),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )(match.delete_pair)
kb.add(
Matthias Bussonnier
autoreformat
r27374 "backspace",
Martin Skarzynski
Add setting to toggle auto_match feature
r27375 filter=focused_insert
& preceding_text(r".*'$")
& auto_match
& following_text(r"^'"),
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )(match.delete_pair)
Martin Skarzynski
implement auto_match brackets and quotes based on randy3k/radian/
r27373
Matthias Bussonnier
autoreformat
r27374 if shell.display_completions == "readlinelike":
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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 if sys.platform == "win32" or for_all_platforms:
Matthias Bussonnier
reformat with darker
r26091 kb.add("c-v", filter=(has_focus(DEFAULT_BUFFER) & ~vi_mode))(win_paste)
Martin Skarzynski
add emacs keybindings to vi insert mode
r26067
Matthias Bussonnier
more updates to WN
r27305 focused_insert_vi = has_focus(DEFAULT_BUFFER) & vi_insert_mode
Martin Skarzynski
add emacs keybindings to vi insert mode
r26067
krassowski
Restore shortcuts in documentation, define identifiers
r28010 # autosuggestions
krassowski
Autosuggest: only navigate on edges of doc, show in multi-line doc
r28041 @Condition
def navigable_suggestions():
return isinstance(
shell.auto_suggest, auto_suggest.NavigableAutoSuggestFromHistory
)
krassowski
Restore shortcuts in documentation, define identifiers
r28010 kb.add("end", filter=has_focus(DEFAULT_BUFFER) & (ebivim | ~vi_insert_mode))(
krassowski
Implement traversal of autosuggestions and by-character fill
r28014 auto_suggest.accept_in_vi_insert_mode
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )
kb.add("c-e", filter=focused_insert_vi & ebivim)(
krassowski
Implement traversal of autosuggestions and by-character fill
r28014 auto_suggest.accept_in_vi_insert_mode
)
kb.add("c-f", filter=focused_insert_vi)(auto_suggest.accept)
kb.add("escape", "f", filter=focused_insert_vi & ebivim)(auto_suggest.accept_word)
kb.add("c-right", filter=has_suggestion & has_focus(DEFAULT_BUFFER))(
auto_suggest.accept_token
)
Matthias Bussonnier
FIX: Update vi bindings to work with nav auttosuggestion....
r28050 kb.add(
"escape", filter=has_suggestion & has_focus(DEFAULT_BUFFER) & emacs_insert_mode
)(auto_suggest.discard)
krassowski
Autosuggest: only navigate on edges of doc, show in multi-line doc
r28041 kb.add(
"up",
filter=navigable_suggestions
& ~has_line_above
& has_suggestion
& has_focus(DEFAULT_BUFFER),
)(auto_suggest.swap_autosuggestion_up(shell.auto_suggest))
kb.add(
"down",
filter=navigable_suggestions
& ~has_line_below
& has_suggestion
& has_focus(DEFAULT_BUFFER),
)(auto_suggest.swap_autosuggestion_down(shell.auto_suggest))
krassowski
Add missing line_below/line_above conditions
r28042 kb.add(
"up", filter=has_line_above & navigable_suggestions & has_focus(DEFAULT_BUFFER)
)(auto_suggest.up_and_update_hint)
kb.add(
"down",
filter=has_line_below & navigable_suggestions & has_focus(DEFAULT_BUFFER),
)(auto_suggest.down_and_update_hint)
krassowski
Implement traversal of autosuggestions and by-character fill
r28014 kb.add("right", filter=has_suggestion & has_focus(DEFAULT_BUFFER))(
auto_suggest.accept_character
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )
krassowski
Autosuggest: only navigate on edges of doc, show in multi-line doc
r28041 kb.add("c-left", filter=has_suggestion & has_focus(DEFAULT_BUFFER))(
krassowski
Accept with cursor in place with ctrl + down, move left after accepting
r28016 auto_suggest.accept_and_move_cursor_left
)
kb.add("c-down", filter=has_suggestion & has_focus(DEFAULT_BUFFER))(
krassowski
Accepting suggestions with cursor in place and resume on backspace
r28015 auto_suggest.accept_and_keep_cursor
)
kb.add("backspace", filter=has_suggestion & has_focus(DEFAULT_BUFFER))(
auto_suggest.backspace_and_resume_hint
)
Martin Skarzynski
add emacs keybindings to vi insert mode
r26067
# 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():
Matthias Bussonnier
more updates to WN
r27305 kb.add(key, filter=focused_insert_vi & ebivim)(cmd)
Martin Skarzynski
add emacs keybindings to vi insert mode
r26067
# 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():
Matthias Bussonnier
more updates to WN
r27305 kb.add(*keys, filter=focused_insert_vi & ebivim)(cmd)
Martin Skarzynski
add emacs keybindings to vi insert mode
r26067
Martin Skarzynski
cursor shape changes with vi editing mode
r26113 def get_input_mode(self):
Matthias Bussonnier
remove last bits of pre-38 codepath....
r27154 app = get_app()
app.ttimeoutlen = shell.ttimeoutlen
app.timeoutlen = shell.timeoutlen
Martin Skarzynski
cursor shape changes with vi editing mode
r26113
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)
ltrujello
Fixes #13472 by restoring user's terminal cursor
r27508 sys.stdout.write(cursor)
Martin Skarzynski
cursor shape changes with vi editing mode
r26113 sys.stdout.flush()
self._input_mode = mode
if shell.editing_mode == "vi" and shell.modal_cursor:
krassowski
Fix mypy job, fix issues detected by mypy
r28011 ViState._input_mode = InputMode.INSERT # type: ignore
ViState.input_mode = property(get_input_mode, set_input_mode) # type: ignore
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):
krassowski
Restore shortcuts in documentation, define identifiers
r28010 text = buffer.delete_before_cursor(len(document.text[: document.cursor_position]))
Matthias Bussonnier
some more work
r25142 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):
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:
krassowski
Restore shortcuts in documentation, define identifiers
r28010 check_text = d.text[: d.cursor_position]
Thomas Kluyver
Add shell.check_complete() method...
r24180 status, indent = shell.check_complete(check_text)
krassowski
Restore shortcuts in documentation, define identifiers
r28010
Matthias Bussonnier
some more work
r25142 # if all we have after the cursor is whitespace: reformat current text
# before cursor
krassowski
Restore shortcuts in documentation, define identifiers
r28010 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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 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:
krassowski
Restore shortcuts in documentation, define identifiers
r28010 b.insert_text("\n" + indent)
Matthias Bussonnier
Undeprecate autoindent...
r24498 else:
krassowski
Restore shortcuts in documentation, define identifiers
r28010 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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 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:
krassowski
Restore shortcuts in documentation, define identifiers
r28010 b.insert_text("\n" + indent)
Matthias Bussonnier
Undeprecate autoindent...
r24498 else:
krassowski
Restore shortcuts in documentation, define identifiers
r28010 b.insert_text("\n")
newline_or_execute.__qualname__ = "newline_or_execute"
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):
krassowski
Restore shortcuts in documentation, define identifiers
r28010 """Dismiss completion"""
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 b = event.current_buffer
if b.complete_state:
b.cancel_completion()
def reset_buffer(event):
krassowski
Restore shortcuts in documentation, define identifiers
r28010 """Reset buffer"""
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 b = event.current_buffer
if b.complete_state:
b.cancel_completion()
else:
b.reset()
def reset_search_buffer(event):
krassowski
Restore shortcuts in documentation, define identifiers
r28010 """Reset search buffer"""
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 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
krassowski
Restore shortcuts in documentation, define identifiers
r28010
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 def suspend_to_bg(event):
krassowski
Restore shortcuts in documentation, define identifiers
r28010 """Suspend to background"""
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
krassowski
Restore shortcuts in documentation, define identifiers
r28010
Maor Kleinberger
Fix ctrl-\ behavior...
r27599 def quit(event):
Matthias Bussonnier
Quit IPython on Ctrl-\ (SIGQUIT)...
r22739 """
krassowski
Restore shortcuts in documentation, define identifiers
r28010 Quit application with ``SIGQUIT`` if supported or ``sys.exit`` otherwise.
Maor Kleinberger
Fix ctrl-\ behavior...
r27599 On platforms that support SIGQUIT, send SIGQUIT to the current process.
On other platforms, just exit the process with a message.
Matthias Bussonnier
Quit IPython on Ctrl-\ (SIGQUIT)...
r22739 """
Maor Kleinberger
Fix ctrl-\ behavior...
r27599 sigquit = getattr(signal, "SIGQUIT", None)
if sigquit is not None:
os.kill(0, signal.SIGQUIT)
else:
sys.exit("Quit")
Matthias Bussonnier
Quit IPython on Ctrl-\ (SIGQUIT)...
r22739
krassowski
Restore shortcuts in documentation, define identifiers
r28010
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 def indent_buffer(event):
krassowski
Restore shortcuts in documentation, define identifiers
r28010 """Indent buffer"""
event.current_buffer.insert_text(" " * 4)
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642
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
"""
krassowski
Restore shortcuts in documentation, define identifiers
r28010 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,
)
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334
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)
krassowski
Restore shortcuts in documentation, define identifiers
r28010
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):
krassowski
Restore shortcuts in documentation, define identifiers
r28010 """Insert a newline after the cursor indented appropriately."""
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334 b = event.current_buffer
d = b.document
if b.complete_state:
b.cancel_completion()
krassowski
Restore shortcuts in documentation, define identifiers
r28010 text = d.text[: d.cursor_position] + "\n"
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334 _, indent = inputsplitter.check_complete(text)
krassowski
Restore shortcuts in documentation, define identifiers
r28010 b.insert_text("\n" + (" " * (indent or 0)), move_cursor=False)
newline_autoindent.__qualname__ = "newline_autoindent"
Matthias Bussonnier
Improve indentation of next line when using CTRL-o in terminal....
r23334
return newline_autoindent
Carl Smith
Add shortcut to edit cell
r22851 def open_input_in_editor(event):
krassowski
Restore shortcuts in documentation, define identifiers
r28010 """Open code from input in external editor"""
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
krassowski
Restore shortcuts in documentation, define identifiers
r28010 if sys.platform == "win32":
Thomas Kluyver
Pull shortcut definitions out to a separate module
r22642 from IPython.core.error import TryNext
krassowski
Restore shortcuts in documentation, define identifiers
r28010 from IPython.lib.clipboard import (
ClipboardEmpty,
tkinter_clipboard_get,
Matthias Bussonnier
Misc review cleanup....
r28029 win32_clipboard_get,
krassowski
Restore shortcuts in documentation, define identifiers
r28010 )
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 @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))
krassowski
Restore shortcuts in documentation, define identifiers
r28010
else:
@undoc
def win_paste(event):
"""Stub used when auto-generating shortcuts for documentation"""
pass