From 84015d3ac4d585e48a7c4275cf55b2c2ffaef2d5 Mon Sep 17 00:00:00 2001 From: Andrew Lane Date: Fri, 1 Oct 2021 12:34:36 +0300 Subject: [PATCH] Handle errors when replacing --- babi/screen.py | 8 +++++++- tests/features/replace_test.py | 10 ++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/babi/screen.py b/babi/screen.py index 9d725d4..c86bc71 100644 --- a/babi/screen.py +++ b/babi/screen.py @@ -7,6 +7,7 @@ import hashlib import os import re import signal +import sre_parse import sys from typing import Generator from typing import NamedTuple @@ -419,7 +420,12 @@ class Screen: 'replace with', history='replace', allow_empty=True, ) if response is not PromptResult.CANCELLED: - self.file.replace(self, search_response, response) + try: + sre_parse.parse_template(response, search_response) + except re.error: + self.status.update('invalid replacement string') + else: + self.file.replace(self, search_response, response) def command(self) -> EditResult | None: response = self.prompt('', history='command') diff --git a/tests/features/replace_test.py b/tests/features/replace_test.py index f42cf10..83e489c 100644 --- a/tests/features/replace_test.py +++ b/tests/features/replace_test.py @@ -22,6 +22,16 @@ def test_replace_invalid_regex(run): h.await_text("invalid regex: '('") +def test_replace_invalid_replacement(run, ten_lines): + with run(str(ten_lines)) as h, and_exit(h): + h.press('^\\') + h.await_text('search (to replace):') + h.press_and_enter('line_0') + h.await_text('replace with:') + h.press_and_enter('\\') + h.await_text('invalid replacement string') + + def test_replace_cancel_at_replace_string(run): with run() as h, and_exit(h): h.press('^\\')