Subject: Re: bug#36967: 27.0.50; Duplicate lines in xref output

From: Juri Linkov <[email-masked]>
Date: Wed, 02 Dec 2020 23:30:18 +0200

>> I tried to use project-find-regexp more often than rgrep,
>> but unfortunately xref still has a fundamental flaw:
>> 0. emacs -Q
>> 1. M-x project-find-regexp RET regexp RET
>> 2. The output buffer *xref* contains duplicate lines
>>     when regexp is found on the same line several times,
>>     each duplicate output line has separate highlighting
>>     for every regexp occurrence.
>
> I don't know how "fundamental" it is, but indeed, it's somewhat of
> a drawback. Suggestions for improving it (API change and/or implementation
> change) are welcome.

Here is the patch that makes the broken project-find-regexp usable:

diff --git a/lisp/progmodes/xref.el b/lisp/progmodes/xref.el
index 3b19debb79..1f5e45f20d 100644
--- a/lisp/progmodes/xref.el
+++ b/lisp/progmodes/xref.el
@@ -1461,11 +1461,10 @@ xref--collect-matches
                                  syntax-needed)))))
 
 (defun xref--collect-matches-1 (regexp file line line-beg line-end syntax-needed)
-  (let (matches)
+  (let ((summary (buffer-substring line-beg line-end))
+        matches)
     (when syntax-needed
       (syntax-propertize line-end))
-    ;; FIXME: This results in several lines with the same
-    ;; summary. Solve with composite pattern?
     (while (and
             ;; REGEXP might match an empty string.  Or line.
             (or (null matches)
@@ -1473,12 +1472,12 @@ xref--collect-matches-1
             (re-search-forward regexp line-end t))
       (let* ((beg-column (- (match-beginning 0) line-beg))
              (end-column (- (match-end 0) line-beg))
-             (loc (xref-make-file-location file line beg-column))
-             (summary (buffer-substring line-beg line-end)))
+             (loc (xref-make-file-location file line beg-column)))
         (add-face-text-property beg-column end-column 'xref-match
                                 t summary)
-        (push (xref-make-match summary loc (- end-column beg-column))
-              matches)))
+        (unless matches
+          (push (xref-make-match summary loc (- end-column beg-column))
+                matches))))
     (nreverse matches)))
 
 (defun xref--find-file-buffer (file)