From 9f1a44d9e3aaac48ea884b0a4b7901a3d2528432 Mon Sep 17 00:00:00 2001
From: Benno Schulenberg <bensberg@justemail.net>
Date: Sun, 1 May 2016 12:35:47 +0200
Subject: [PATCH] replacing: properly detect when we've rereached the starting
 position

Commit 8704dde mistakenly removed this part of code -- it is not dead,
it is just that it will only fire when the user answered No at some of
the replacement prompts.  So... when we've rereached the starting line,
a found occurrence is invalid when it is beyond the starting x (either
after or before it, dependending on the direction of search).

This fixes https://savannah.gnu.org/bugs/?47816.
---
 src/search.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)

diff --git a/src/search.c b/src/search.c
index dd0c1b27..ed03c743 100644
--- a/src/search.c
+++ b/src/search.c
@@ -266,6 +266,8 @@ int findnextstr(
 	/* When bigger than zero, show and wipe the "Searching..." message. */
     filestruct *fileptr = openfile->current;
     const char *rev_start = fileptr->data, *found = NULL;
+    size_t found_x;
+	/* The x coordinate of a found occurrence. */
     time_t lastkbcheck = time(NULL);
 
     /* rev_start might end up 1 character before the start or after the
@@ -380,11 +382,28 @@ int findnextstr(
 #endif
     }
 
+    found_x = found - fileptr->data;
+
+    /* Ensure that the found occurrence is not beyond the starting x. */
+    if (search_last_line &&
+#ifndef NANO_TINY
+		((!ISSET(BACKWARDS_SEARCH) && found_x > begin_x) ||
+		(ISSET(BACKWARDS_SEARCH) && found_x < begin_x))
+#else
+		found_x > begin_x
+#endif
+		) {
+	not_found_msg(needle);
+	disable_nodelay();
+	return 0;
+    }
+
+
     disable_nodelay();
 
     /* Set the current position to point at what we found. */
     openfile->current = fileptr;
-    openfile->current_x = found - fileptr->data;
+    openfile->current_x = found_x;
     openfile->current_y = fileptr->lineno - openfile->edittop->lineno;
 
     /* When requested, pass back the length of the match. */
-- 
GitLab