Merge pull request #164 from AndrewLaneX/replace-errors

Handle errors when replacing
This commit is contained in:
Anthony Sottile
2021-10-03 15:53:22 -07:00
committed by GitHub
2 changed files with 17 additions and 1 deletions

View File

@@ -7,6 +7,7 @@ import hashlib
import os import os
import re import re
import signal import signal
import sre_parse
import sys import sys
from typing import Generator from typing import Generator
from typing import NamedTuple from typing import NamedTuple
@@ -419,7 +420,12 @@ class Screen:
'replace with', history='replace', allow_empty=True, 'replace with', history='replace', allow_empty=True,
) )
if response is not PromptResult.CANCELLED: 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: def command(self) -> EditResult | None:
response = self.prompt('', history='command') response = self.prompt('', history='command')

View File

@@ -22,6 +22,16 @@ def test_replace_invalid_regex(run):
h.await_text("invalid regex: '('") 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): def test_replace_cancel_at_replace_string(run):
with run() as h, and_exit(h): with run() as h, and_exit(h):
h.press('^\\') h.press('^\\')