Subject: bug#50466: 28.0.50; isearch isearch-repeat-on-direction-change vs isearch-beginning-of-buffer

From: Lars Ingebrigtsen <[email-masked]>
Date: Wed, 08 Sep 2021 08:01:55 +0200

Ergus <[email-masked]> writes:

> (setq isearch-repeat-on-direction-change t)
> (define-key isearch-mode-map (kbd "M-<") #'isearch-beginning-of-buffer)
>
> If I have the cursor on the beginning of:
>
> 1abc
> 2abc
> 3abc
> 4abc
>
> and do
>
> C-s abc ;; cursor at the end of 1abc
> C-s     ;; cursor at the end of 2abc
> C-s     ;; cursor at the end of 3abc
> C-r     ;; cursor at the beginning of 2abc
> M-<     ;; cursor at the end of 3abc <- this is wrong
>
> The cursor goes to the end of 3abc (next candidate) instead of 1abc
> (first) as expected from isearch-beginning-of-buffer.

Simpler reproduction: Go to the end of the 3abc line and

C-r abc
M-<

That'll take you to the end of 4abc.  And it's because:

(defun isearch-beginning-of-buffer (&optional arg)
[...]
    (setq isearch-just-started t)
    (goto-char (point-min))
    (isearch-repeat 'forward arg)))

(defun isearch-repeat (direction &optional count)
[...]
    ;; C-s in reverse or C-r in forward, change direction.
    (if (and isearch-other-end isearch-repeat-on-direction-change)
        (goto-char isearch-other-end))

The following patch seems to fix the problem:

diff --git a/lisp/isearch.el b/lisp/isearch.el
index 1c776a06e1..6abd12700c 100644
--- a/lisp/isearch.el
+++ b/lisp/isearch.el
@@ -1898,7 +1898,8 @@ isearch-repeat
 	      (funcall isearch-wrap-function)
 	    (goto-char (if isearch-forward (point-min) (point-max))))))
     ;; C-s in reverse or C-r in forward, change direction.
-    (if (and isearch-other-end isearch-repeat-on-direction-change)
+    (if (and isearch-other-end isearch-repeat-on-direction-change
+             (not isearch-just-started))
         (goto-char isearch-other-end))
     (setq isearch-forward (not isearch-forward)
 	  isearch-success t))

But I'm not really very familiar with the isearch machinery, so I've
added Juri to the CCs; perhaps he has a comment here.

-- 
(domestic pets only, the antidote for overdose, milk.)
   bloggy blog: http://lars.ingebrigtsen.no