Subject: Re: bug#2544: 23.0.60; Could etags please try find a local tag first?

From: Dmitry Gutov <[email-masked]>
Date: Tue, 27 Jul 2021 02:15:30 +0300

On 21.07.2021 13:39, Lars Ingebrigtsen wrote:
> The problem is definitely much more noticeable in the etags backend, so
> if your judgement is that that's where the option (and sorting) should
> go, then please go ahead.:-)

Here's a rough patch.

Please test and send feedback (how well it works, variable naming, 
docstring, etc).
diff --git a/lisp/progmodes/etags.el b/lisp/progmodes/etags.el
index f0180ceeec..2af160be74 100644
--- a/lisp/progmodes/etags.el
+++ b/lisp/progmodes/etags.el
@@ -2059,6 +2059,10 @@ etags-xref-find-definitions-tag-order
 If you want `xref-find-definitions' to find the tagged files by their
 file name, add `tag-partial-file-name-match-p' to the list value.")
 
+(defcustom etags-xref-prioritize-same-file nil
+  "Non-nil to show the matches in the same file first."
+  :type 'boolean)
+
 ;;;###autoload
 (defun etags--xref-backend () 'etags)
 
@@ -2072,7 +2076,21 @@ xref-backend-identifier-completion-ignore-case
   (find-tag--completion-ignore-case))
 
 (cl-defmethod xref-backend-definitions ((_backend (eql etags)) symbol)
-  (etags--xref-find-definitions symbol))
+  (let ((file (and buffer-file-name (expand-file-name buffer-file-name)))
+        (definitions (etags--xref-find-definitions symbol))
+        same-file-definitions)
+    (when (and etags-xref-prioritize-same-file file)
+      (cl-delete-if
+       (lambda (definition)
+         (when (equal file
+                      (xref-location-group
+                       (xref-item-location definition)))
+           (push definition same-file-definitions)
+           t))
+       definitions)
+      (setq definitions (nconc (nreverse same-file-definitions)
+                               definitions)))
+    definitions))
 
 (cl-defmethod xref-backend-apropos ((_backend (eql etags)) pattern)
   (etags--xref-find-definitions (xref-apropos-regexp pattern) t))