From cf104a46e325d3a782eb54bfe56c1aa2a55e3dc2 Mon Sep 17 00:00:00 2001
From: Eshel Yaron <me@eshelyaron.com>
Date: Thu, 8 Dec 2022 22:10:04 +0200
Subject: [PATCH] FIXED: stale predicate locations in loaded modified buffers

* sweep.pl (sweep_predicate_location_/2,3): prefer xref over loaded
predicate properties.
* sweeprolog.el (sweeprolog-predicate-location): first analyze buffer
if modified to update xref data.
---
 sweep.pl      | 23 +++++++++--------------
 sweeprolog.el |  1 +
 2 files changed, 10 insertions(+), 14 deletions(-)

diff --git a/sweep.pl b/sweep.pl
index 4c0c12e..95f1f2d 100644
--- a/sweep.pl
+++ b/sweep.pl
@@ -353,23 +353,15 @@ sweep_predicate_apropos(Query0, Matches) :-
             Tail).
 
 sweep_predicate_location_(H, Path, Line) :-
-    predicate_property(H, file(Path0)),
-    predicate_property(H, line_count(Line)),
+    xref_defined(Path0, H, How),
+    xref_definition_line(How, Line),
     !,
     atom_string(Path0, Path).
 sweep_predicate_location_(H, Path, Line) :-
-    (   xref_defined(Path0, H, How),
-        xref_definition_line(How, Line)
-    ->  true
-    ;   xref_defined(Path0, H, _), Line = []
-    ),
+    predicate_property(H, file(Path0)),
+    predicate_property(H, line_count(Line)),
     atom_string(Path0, Path).
 
-sweep_predicate_location_(M, H, Path, Line) :-
-    predicate_property(M:H, file(Path0)),
-    predicate_property(M:H, line_count(Line)),
-    !,
-    atom_string(Path0, Path).
 sweep_predicate_location_(M, H, Path, Line) :-
     (   xref_defined(Path0, M:H, How),
         xref_definition_line(How, Line)
@@ -377,9 +369,12 @@ sweep_predicate_location_(M, H, Path, Line) :-
     ;   xref_defined(Path0, H, How),
         xref_definition_line(How, Line),
         xref_module(Path0, M)
-    ->  true
-    ;   xref_defined(Path0, M:H, _), Line = []
     ),
+    !,
+    atom_string(Path0, Path).
+sweep_predicate_location_(M, H, Path, Line) :-
+    predicate_property(M:H, file(Path0)),
+    predicate_property(M:H, line_count(Line)),
     atom_string(Path0, Path).
 
 
diff --git a/sweeprolog.el b/sweeprolog.el
index 3fd1765..742b42a 100644
--- a/sweeprolog.el
+++ b/sweeprolog.el
@@ -853,6 +853,7 @@ PROJECT (only on Emacs 28 or later)."
 For native built-in predicates, the behavior of this function
 depends on the value of the user option
 `sweeprolog-swipl-sources', which see."
+  (sweeprolog-analyze-buffer)
   (or (sweeprolog--query-once "sweep" "sweep_predicate_location" mfn)
       (sweeprolog-native-predicate-location mfn)))
 
-- 
2.39.5