xonsh/xontrib/abbrevs.py

64 lines
2 KiB
Python
Raw Normal View History

2020-03-25 20:12:30 +01:00
"""
Command abbreviations.
This expands input words from `abbrevs` disctionary as you type.
"""
2020-03-20 21:46:35 +01:00
import builtins
2020-03-25 17:30:28 +01:00
from prompt_toolkit.filters import IsMultiline
from prompt_toolkit.keys import Keys
2020-03-20 21:46:35 +01:00
from xonsh.platform import ptk_shell_type
2020-03-25 18:29:05 +01:00
from xonsh.tools import check_for_partial_string
2020-03-20 21:46:35 +01:00
__all__ = ()
if "abbrevs" not in builtins.__xonsh__.ctx.keys():
builtins.__xonsh__.ctx["abbrevs"] = dict()
2020-03-20 21:46:35 +01:00
def expand_abbrev(buffer):
if "abbrevs" not in builtins.__xonsh__.ctx.keys():
return
2020-03-25 18:29:05 +01:00
document = buffer.document
word = document.get_word_before_cursor()
2020-03-20 21:46:35 +01:00
abbrevs = builtins.__xonsh__.ctx["abbrevs"]
if word in abbrevs.keys():
2020-03-25 18:29:05 +01:00
partial = document.text[: document.cursor_position]
startix, endix, quote = check_for_partial_string(partial)
if startix is not None and endix is None:
return
2020-03-20 21:46:35 +01:00
buffer.delete_before_cursor(count=len(word))
buffer.insert_text(abbrevs[word])
@events.on_ptk_create
def custom_keybindings(bindings, **kw):
if ptk_shell_type() == "prompt_toolkit2":
2020-03-25 17:30:28 +01:00
from xonsh.ptk2.key_bindings import carriage_return
from prompt_toolkit.filters import EmacsInsertMode, ViInsertMode
2020-03-20 21:46:35 +01:00
handler = bindings.add
2020-03-25 17:30:28 +01:00
insert_mode = ViInsertMode() | EmacsInsertMode()
2020-03-20 21:46:35 +01:00
else:
2020-03-25 17:30:28 +01:00
from xonsh.ptk.key_bindings import carriage_return
2020-03-25 20:46:41 +01:00
from prompt_toolkit.filters import to_filter
2020-03-25 17:30:28 +01:00
2020-03-20 21:46:35 +01:00
handler = bindings.registry.add_binding
2020-03-25 20:46:41 +01:00
insert_mode = to_filter(True)
2020-03-20 21:46:35 +01:00
2020-03-25 17:30:28 +01:00
@handler(" ", filter=IsMultiline() & insert_mode)
def handle_space(event):
2020-03-20 21:46:35 +01:00
buffer = event.app.current_buffer
expand_abbrev(buffer)
buffer.insert_text(" ")
2020-03-25 17:30:28 +01:00
@handler(Keys.ControlJ, filter=IsMultiline() & insert_mode)
@handler(Keys.ControlM, filter=IsMultiline() & insert_mode)
def multiline_carriage_return(event):
buffer = event.app.current_buffer
current_char = buffer.document.current_char
if not current_char or current_char.isspace():
expand_abbrev(buffer)
2020-03-25 17:30:28 +01:00
carriage_return(buffer, event.cli)