Repository: asottile/babi

Issue:
regex replace can break EOF invariant
for example, do a replace with `^` =>  `  ` and replace all and the end of the file will be forever broken-ish

Discussion:

Patch:
diff --git a/babi/file.py b/babi/file.py
index 57b707e..73182d3 100644
--- a/babi/file.py
+++ b/babi/file.py
@@ -195,7 +195,7 @@ class _SearchIter:
                 if match:
                     return self._stop_if_past_original(line_y, match)
         else:
-            for line_y in range(y + 1, len(self.file.buf)):
+            for line_y in range(y + 1, len(self.file.buf) - 1):
                 match = self.reg.search(self.file.buf[line_y])
                 if match:
                     return self._stop_if_past_original(line_y, match)


Test patch:
diff --git a/tests/features/replace_test.py b/tests/features/replace_test.py
index 83e489c..f864450 100644
--- a/tests/features/replace_test.py
+++ b/tests/features/replace_test.py
@@ -313,3 +313,18 @@ def test_replace_with_multiple_newline_characters(run, ten_lines):
 
         h.await_text_missing('line_1')
         h.await_text('li\nne\n1\n\nline_2')
+
+
+def test_replace_end_of_file(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('^')
+        h.await_text('replace with:')
+        h.press_and_enter('prefix:')
+        h.await_text('replace [yes, no, all]?')
+        h.press('a')
+
+        h.await_text('replaced 10 occurrences')
+        h.await_text('prefix:line_9')
+        h.assert_screen_line_equal(11, '')