From b7b2c9a9168290dd27025b2090d9daf3e5cbeff3 Mon Sep 17 00:00:00 2001 From: Noorhteen Raja NJ Date: Tue, 9 Mar 2021 19:37:53 +0530 Subject: [PATCH] fix: abbrevs with callback alters buffer text before expansion (#4156) * fix: abbrevs with callback alters buffer text before expansion fixes #3642 * docs: add news item --- news/fix-abbrevs-callback.rst | 23 +++++++++++++++++++++++ tests/xontribs/test_abbrevs.py | 8 +++++++- xontrib/abbrevs.py | 7 +++++-- 3 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 news/fix-abbrevs-callback.rst diff --git a/news/fix-abbrevs-callback.rst b/news/fix-abbrevs-callback.rst new file mode 100644 index 000000000..b2f22a92e --- /dev/null +++ b/news/fix-abbrevs-callback.rst @@ -0,0 +1,23 @@ +**Added:** + +* + +**Changed:** + +* + +**Deprecated:** + +* + +**Removed:** + +* + +**Fixed:** + +* now abbrevs callback will not remove word from ``buffer.text``. See https://github.com/xonsh/xonsh/issues/3642#issuecomment-793789741 + +**Security:** + +* diff --git a/tests/xontribs/test_abbrevs.py b/tests/xontribs/test_abbrevs.py index 33c04a9cc..e56c4663a 100644 --- a/tests/xontribs/test_abbrevs.py +++ b/tests/xontribs/test_abbrevs.py @@ -27,11 +27,17 @@ def abbrevs_xontrib(monkeypatch, source_path): del sys.modules[spec.name] +ps_special_expand = ( + lambda buffer, word: "procs" if buffer.text.startswith(word) else word +) + + @mark.parametrize( "abbr,val,expanded,cur", [ ("ps", "procs", "procs", None), - ("ps", lambda **kw: "callback", "callback", None), + ("ps", ps_special_expand, "procs", None), + ("docker ps", ps_special_expand, "docker ps", None), ("kill", "kill -9", "kill -9", 5), ("pt", "poetry", "poetry", 3), ], diff --git a/xontrib/abbrevs.py b/xontrib/abbrevs.py index 8111662ff..7ac9d5947 100644 --- a/xontrib/abbrevs.py +++ b/xontrib/abbrevs.py @@ -28,6 +28,7 @@ It is also possible to set the cursor position after expansion with, import builtins import typing as tp +from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import completion_is_selected, IsMultiline from prompt_toolkit.keys import Keys from xonsh.built_ins import DynamicAccessProxy @@ -60,7 +61,7 @@ def get_abbreviated(key: str, buffer) -> str: return text -def expand_abbrev(buffer) -> bool: +def expand_abbrev(buffer: Buffer) -> bool: """expand the given abbr text. Return true if cursor position changed.""" global last_expanded last_expanded = None @@ -74,9 +75,11 @@ def expand_abbrev(buffer) -> bool: startix, endix, quote = check_for_partial_string(partial) if startix is not None and endix is None: return False - buffer.delete_before_cursor(count=len(word)) text = get_abbreviated(word, buffer) + + buffer.delete_before_cursor(count=len(word)) buffer.insert_text(text) + last_expanded = _LastExpanded(word, text) if EDIT_SYMBOL in text: set_cursor_position(buffer, text)