Subject: bug#53626: 28.0.91; project-find-regexp (C-x p g) twice results in searching different projects

From: Dmitry Gutov <[email-masked]>
Date: Mon, 21 Feb 2022 03:55:54 +0200

On 07.02.2022 05:12, Dmitry Gutov wrote:
>> Maybe we could rename the old buffer to a temp name, then create and
>> fill the new one, then set the old buffer's window's buffer to the new
>> one, and finally kill the old one.  But this is not nice at all.
> 
> Right.

We can also try a lighter-weight hack like below. WDYT?

diff --git a/lisp/progmodes/xref.el b/lisp/progmodes/xref.el
index 784c745477..082d64aaeb 100644
--- a/lisp/progmodes/xref.el
+++ b/lisp/progmodes/xref.el
@@ -1107,6 +1107,13 @@ xref--analyze
               (cdr pair)))
       alist)))

+(defun xref--ensure-default-directory (dd buffer)
+  ;; We might be in a let-binding which will restore the current value
+  ;; to a previous one (bug#53626).  So do this later.
+  (run-with-timer
+   0 nil
+   (lambda () (with-current-buffer buffer (setq default-directory dd)))))
+
  (defun xref--show-xref-buffer (fetcher alist)
    (cl-assert (functionp fetcher))
    (let* ((xrefs
@@ -1117,7 +1124,7 @@ xref--show-xref-buffer
           (dd default-directory)
           buf)
      (with-current-buffer (get-buffer-create xref-buffer-name)
-      (setq default-directory dd)
+      (xref--ensure-default-directory dd (current-buffer))
        (xref--xref-buffer-mode)
        (xref--show-common-initialize xref-alist fetcher alist)
        (pop-to-buffer (current-buffer))
@@ -1216,7 +1223,7 @@ xref-show-definitions-buffer-at-bottom
                              (assoc-default 'display-action alist)))
       (t
        (with-current-buffer (get-buffer-create xref-buffer-name)
-        (setq default-directory dd)
+        (xref--ensure-default-directory dd (current-buffer))
          (xref--transient-buffer-mode)
          (xref--show-common-initialize (xref--analyze xrefs) fetcher alist)
          (pop-to-buffer (current-buffer)