mirrored from git://git.sv.gnu.org/emacs.git
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
xref.el
2220 lines (1962 loc) · 85.6 KB
/
xref.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; xref.el --- Cross-referencing commands -*-lexical-binding:t-*-
;; Copyright (C) 2014-2024 Free Software Foundation, Inc.
;; Version: 1.7.0
;; Package-Requires: ((emacs "26.1"))
;; This is a GNU ELPA :core package. Avoid functionality that is not
;; compatible with the version of Emacs recorded above.
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This file provides a somewhat generic infrastructure for cross
;; referencing commands, in particular "find-definition".
;;
;; Some part of the functionality must be implemented in a language
;; dependent way and that's done by defining an xref backend.
;;
;; That consists of a constructor function, which should return a
;; backend value, and a set of implementations for the generic
;; functions:
;;
;; `xref-backend-identifier-at-point',
;; `xref-backend-identifier-completion-table',
;; `xref-backend-definitions', `xref-backend-references',
;; `xref-backend-apropos', which see.
;;
;; A major mode would normally use `add-hook' to add the backend
;; constructor to `xref-backend-functions'.
;;
;; The last three methods operate with "xref" and "location" values.
;;
;; One would usually call `xref-make' and `xref-make-file-location',
;; `xref-make-buffer-location' or `xref-make-bogus-location' to create
;; them. More generally, a location must be an instance of a type for
;; which methods `xref-location-group' and `xref-location-marker' are
;; implemented.
;;
;; There's a special kind of xrefs we call "match xrefs", which
;; correspond to search results. For these values,
;; `xref-match-length' must be defined, and `xref-location-marker'
;; must return the beginning of the match.
;;
;; Each identifier must be represented as a string. Implementers can
;; use string properties to store additional information about the
;; identifier, but they should keep in mind that values returned from
;; `xref-backend-identifier-completion-table' should still be
;; distinct, because the user can't see the properties when making the
;; choice.
;;
;; Older versions of Xref used EIEIO for implementation of the
;; built-in types, and included a class called `xref-location' which
;; was supposed to be inherited from. Neither is true anymore.
;;
;; See the etags and elisp-mode implementations for full examples.
;;; Code:
(require 'cl-lib)
(require 'ring)
(require 'project)
(eval-and-compile
(when (version< emacs-version "28.0.60")
;; etags.el in Emacs 26 and 27 uses EIEIO, and its location type
;; inherits from `xref-location'.
(require 'eieio)
;; Suppressing byte-compilation warnings (in Emacs 28+) about
;; `defclass' not being defined, which happens because the
;; `require' statement above is not evaluated either.
;; FIXME: Use `with-suppressed-warnings' when we stop supporting Emacs 26.
(with-no-warnings
(defclass xref-location () ()
:documentation "(Obsolete) location represents a position in a file or buffer."))))
(defgroup xref nil "Cross-referencing commands."
:version "25.1"
:group 'tools)
;;; Locations
(cl-defgeneric xref-location-marker (location)
"Return the marker for LOCATION.")
(cl-defgeneric xref-location-group (location)
"Return a string used to group a set of locations.
This is typically a file name, but can also be a package name, or
some other label.
When it is a file name, it should be the \"expanded\" version.")
(cl-defgeneric xref-location-line (_location)
"Return the line number corresponding to the location."
nil)
(cl-defgeneric xref-match-length (_item)
"Return the length of the match."
nil)
;;;; Commonly needed location types are defined here:
(defcustom xref-file-name-display 'project-relative
"Style of file name display in *xref* buffers.
If the value is the symbol `abs', show the file names in their
full absolute form.
If `nondirectory', show only the nondirectory (a.k.a. \"base name\")
part of the file name.
If `project-relative', the default, show only the file name
relative to the current project root. If there is no current
project, or if the file resides outside of its root, show that
particular file name in its full absolute form."
:type '(choice (const :tag "absolute file name" abs)
(const :tag "nondirectory file name" nondirectory)
(const :tag "relative to project root" project-relative))
:version "27.1")
;; FIXME: might be useful to have an optional "hint" i.e. a string to
;; search for in case the line number is slightly out of date.
(cl-defstruct (xref-file-location
(:constructor xref-make-file-location (file line column)))
"A file location is a file/line/column triple.
Line numbers start from 1 and columns from 0."
file line column)
(cl-defmethod xref-location-group ((l xref-file-location))
(xref-file-location-file l))
(cl-defmethod xref-location-line ((l xref-file-location))
(xref-file-location-line l))
(cl-defmethod xref-location-marker ((l xref-file-location))
(pcase-let (((cl-struct xref-file-location file line column) l))
(with-current-buffer
(let ((find-file-suppress-same-file-warnings t))
(find-file-noselect file))
(save-restriction
(widen)
(save-excursion
(goto-char (point-min))
(ignore-errors
;; The location shouldn't be be out of date, but we make
;; provision for that anyway; in case it's past the end of
;; the file, or it had been deleted. Then return an
;; approximation, the user will figure it out.
(beginning-of-line line)
(forward-char column))
(point-marker))))))
(cl-defstruct (xref-buffer-location
(:constructor xref-make-buffer-location (buffer position)))
buffer position)
(cl-defmethod xref-location-marker ((l xref-buffer-location))
(pcase-let (((cl-struct xref-buffer-location buffer position) l))
(let ((m (make-marker)))
(move-marker m position buffer))))
(cl-defmethod xref-location-group ((l xref-buffer-location))
(pcase-let (((cl-struct xref-buffer-location buffer) l))
(or (buffer-file-name buffer)
(format "(buffer %s)" (buffer-name buffer)))))
(cl-defstruct (xref-bogus-location
(:constructor xref-make-bogus-location (message)))
"Bogus locations are sometimes useful to indicate errors,
e.g. when we know that a function exists but the actual location
is not known."
message)
(cl-defmethod xref-location-marker ((l xref-bogus-location))
(user-error "%s" (xref-bogus-location-message l)))
(cl-defmethod xref-location-group ((_ xref-bogus-location)) "(No location)")
;;; Cross-reference
(defmacro xref--defstruct (name &rest fields)
(declare (indent 1))
`(cl-defstruct ,(if (>= emacs-major-version 27)
name
(remq (assq :noinline name) name))
,@fields))
(xref--defstruct (xref-item
(:constructor xref-make (summary location))
(:noinline t))
"An xref item describes a reference to a location somewhere."
(summary nil :documentation "String which describes the location.
When `xref-location-line' returns non-nil (a number), the summary
is implied to be the contents of a file or buffer line containing
the location. When multiple locations in a row report the same
line, in the same group (corresponding to the case of multiple
locations on one line), the summaries are concatenated in the
Xref output buffer. Consequently, any code that creates xref
values should take care to slice the summary values when several
locations point to the same line.
This behavior is new in Emacs 28.")
location)
(xref--defstruct (xref-match-item
(:include xref-item)
(:constructor xref-make-match (summary location length))
(:noinline t))
"A match xref item describes a search result."
length)
(cl-defmethod xref-match-length ((item xref-match-item))
"Return the length of the match."
(xref-match-item-length item))
;;; API
(defvar xref-backend-functions nil
"Special hook to find the xref backend for the current context.
Each function on this hook is called in turn with no arguments,
and should return either nil to mean that it is not applicable,
or an xref backend, which is a value to be used to dispatch the
generic functions.")
;; We make the etags backend the default for now, until something
;; better comes along. Use APPEND so that any `add-hook' calls made
;; before this package is loaded put new items before this one.
(add-hook 'xref-backend-functions #'etags--xref-backend t)
;;;###autoload
(defun xref-find-backend ()
(run-hook-with-args-until-success 'xref-backend-functions))
(cl-defgeneric xref-backend-definitions (backend identifier)
"Find definitions of IDENTIFIER.
The result must be a list of xref objects. If IDENTIFIER
contains sufficient information to determine a unique definition,
return only that definition. If there are multiple possible
definitions, return all of them. If no definitions can be found,
return nil.
IDENTIFIER can be any string returned by
`xref-backend-identifier-at-point', or from the table returned by
`xref-backend-identifier-completion-table'.
To create an xref object, call `xref-make'.")
(cl-defgeneric xref-backend-references (_backend identifier)
"Find references of IDENTIFIER.
The result must be a list of xref objects. If no references can
be found, return nil.
The default implementation uses `semantic-symref-tool-alist' to
find a search tool; by default, this uses \"find | grep\" in the
current project's main and external roots."
(mapcan
(lambda (dir)
(message "Searching %s..." dir)
(redisplay)
(prog1
(xref-references-in-directory identifier dir)
(message "Searching %s... done" dir)))
(let ((pr (project-current t)))
(project-combine-directories
(cons
(xref--project-root pr)
(project-external-roots pr))))))
(cl-defgeneric xref-backend-apropos (backend pattern)
"Find all symbols that match PATTERN string.
The second argument has the same meaning as in `apropos'.
If BACKEND is implemented in Lisp, it can use
`xref-apropos-regexp' to convert the pattern to regexp.")
(cl-defgeneric xref-backend-identifier-at-point (_backend)
"Return the relevant identifier at point.
The return value must be a string, or nil meaning no identifier
at point found.
If it's hard to determine the identifier precisely (e.g., because
it's a method call on unknown type), the implementation can
return a simple string (such as symbol at point) marked with a
special text property which e.g. `xref-backend-definitions' would
recognize and then delegate the work to an external process."
(let ((thing (thing-at-point 'symbol)))
(and thing (substring-no-properties thing))))
(cl-defgeneric xref-backend-identifier-completion-table (backend)
"Return the completion table for identifiers.")
(cl-defgeneric xref-backend-identifier-completion-ignore-case (_backend)
"Return t if case is not significant in identifier completion."
completion-ignore-case)
;;; misc utilities
(defun xref--alistify (list key)
"Partition the elements of LIST into an alist.
KEY extracts the key from an element."
(let ((table (make-hash-table :test #'equal)))
(dolist (e list)
(let* ((k (funcall key e))
(probe (gethash k table)))
(if probe
(puthash k (cons e probe) table)
(puthash k (list e) table))))
;; Put them back in order.
(cl-loop for key being hash-keys of table using (hash-values value)
collect (cons key (nreverse value)))))
(defun xref--insert-propertized (props &rest strings)
"Insert STRINGS with text properties PROPS."
(let ((start (point)))
(apply #'insert strings)
(add-text-properties start (point) props)))
(defun xref--search-property (property &optional backward)
"Search the next text range where text property PROPERTY is non-nil.
Return the value of PROPERTY. If BACKWARD is non-nil, search
backward."
(let ((next (if backward
#'previous-single-char-property-change
#'next-single-char-property-change))
(start (point))
(value nil))
(while (progn
(goto-char (funcall next (point) property))
(not (or (and
(memq (get-char-property (point) 'invisible) '(ellipsis nil))
(setq value (get-text-property (point) property)))
(eobp)
(bobp)))))
(cond (value)
(t (goto-char start) nil))))
(defvar xref-marker-ring-length 16
"Xref marker ring length.
This is a dummy variable retained for backward compatibility, and
otherwise unused.")
(make-obsolete-variable 'xref-marker-ring-length nil "29.1")
(defcustom xref-prompt-for-identifier '(not xref-find-definitions
xref-find-definitions-other-window
xref-find-definitions-other-frame)
"If non-nil, prompt for the identifier to find.
When t, always prompt for the identifier name.
When nil, prompt only when there's no value at point we can use,
or when the command has been called with the prefix argument.
Otherwise, it's a list of xref commands which will always prompt,
with the identifier at point, if any, used as the default.
If the list starts with `not', the meaning of the rest of the
elements is negated: these commands will NOT prompt."
:type '(choice (const :tag "Always prompt for identifier" t)
(const :tag "Prompt if no identifier at point" nil)
(set :menu-tag "Prompt according to command"
:tag "Prompt according to command"
:value (not)
(const :tag "Except for commands listed below" not)
(repeat :inline t (symbol :tag "command")))))
(defcustom xref-after-jump-hook '(recenter
xref-pulse-momentarily)
"Functions called after jumping to an xref.
Also see `xref-current-item'."
:type 'hook)
(defcustom xref-after-return-hook '(xref-pulse-momentarily)
"Functions called after returning to a pre-jump location."
:type 'hook)
(defcustom xref-after-update-hook nil
"Functions called after the xref buffer is updated."
:type 'hook
:version "28.1"
:package-version '(xref . "1.0.4"))
(defcustom xref-auto-jump-to-first-definition nil
"If t, `xref-find-definitions' always jumps to the first result.
`show' means to show the first result's location, but keep the
focus on the Xref buffer's window.
`move' means to only move point to the first result.
This variable also affects the variants of `xref-find-definitions',
such as `xref-find-definitions-other-window'."
:type '(choice (const :tag "Jump" t)
(const :tag "Show" show)
(const :tag "Move point only" move)
(const :tag "No auto-jump" nil))
:version "28.1"
:package-version '(xref . "1.2.0"))
(defcustom xref-auto-jump-to-first-xref nil
"If t, `xref-find-references' always jumps to the first result.
`show' means to show the first result's location, but keep the
focus on the Xref buffer's window.
`move' means to only move point to the first result.
This variable also affects commands similar to `xref-find-references',
such as `xref-find-references-at-mouse', `xref-find-apropos',
and `project-find-regexp'.
Please be careful when changing the value if you are using Emacs 27
or earlier: it can break `dired-do-find-regexp-and-replace'."
:type '(choice (const :tag "Jump" t)
(const :tag "Show" show)
(const :tag "Move point only" move)
(const :tag "No auto-jump" nil))
:version "28.1"
:package-version '(xref . "1.2.0"))
(defcustom xref-history-storage #'xref-global-history
"Function that returns xref history.
The following functions that can be used as this variable's value
are predefined:
- `xref-global-history'
Return a single, global history used across the entire Emacs
session. This is the default.
- `xref-window-local-history'
Return separate xref histories, one per window. Allows
independent navigation of code in each window. A new
xref history is created for every new window."
:type '(radio
(function-item :tag "Per-window history" xref-window-local-history)
(function-item :tag "Global history for Emacs session"
xref-global-history)
(function :tag "Other"))
:version "29.1"
:package-version '(xref . "1.6.0"))
(make-obsolete-variable 'xref--marker-ring 'xref--history "29.1")
(defun xref-set-marker-ring-length (_var _val)
(declare (obsolete
"this function has no effect: Xref marker ring is now unlimited in size"
"29.1"))
nil)
(defun xref--make-xref-history ()
"Return a new xref history."
(cons nil nil))
(defvar xref--history (xref--make-xref-history)
"(BACKWARD-STACK . FORWARD-STACK) of markers to visited Xref locations.")
(defun xref-global-history (&optional new-value)
"Return the xref history that is global for the current Emacs session.
Override existing value with NEW-VALUE if NEW-VALUE is set."
(if new-value
(setq xref--history new-value)
xref--history))
(defun xref-window-local-history (&optional new-value)
"Return window-local xref history for the selected window.
Override existing value with NEW-VALUE if NEW-VALUE is set."
(let ((w (selected-window)))
(if new-value
(set-window-parameter w 'xref--history new-value)
(or (window-parameter w 'xref--history)
(set-window-parameter w 'xref--history (xref--make-xref-history))))))
(defun xref--get-history ()
"Return xref history using `xref-history-storage'."
(funcall xref-history-storage))
(defun xref--push-backward (m)
"Push marker M onto the backward history stack."
(let ((history (xref--get-history)))
(unless (equal m (caar history))
(push m (car history)))))
(defun xref--push-forward (m)
"Push marker M onto the forward history stack."
(let ((history (xref--get-history)))
(unless (equal m (cadr history))
(push m (cdr history)))))
(defun xref-push-marker-stack (&optional m)
"Add point M (defaults to `point-marker') to the marker stack.
Erase the stack slots following this one."
(xref--push-backward (or m (point-marker)))
(let ((history (xref--get-history)))
(dolist (mk (cdr history))
(set-marker mk nil nil))
(setcdr history nil)))
;;;###autoload
(define-obsolete-function-alias 'xref-pop-marker-stack #'xref-go-back "29.1")
;;;###autoload
(defun xref-go-back ()
"Go back to the previous position in xref history.
To undo, use \\[xref-go-forward]."
(interactive)
(let ((history (xref--get-history)))
(if (null (car history))
(user-error "At start of xref history")
(let ((marker (pop (car history))))
(xref--push-forward (point-marker))
(switch-to-buffer (or (marker-buffer marker)
(user-error "The marked buffer has been deleted")))
(goto-char (marker-position marker))
(set-marker marker nil nil)
(run-hooks 'xref-after-return-hook)))))
;;;###autoload
(defun xref-go-forward ()
"Go to the point where a previous \\[xref-go-back] was invoked."
(interactive)
(let ((history (xref--get-history)))
(if (null (cdr history))
(user-error "At end of xref history")
(let ((marker (pop (cdr history))))
(xref--push-backward (point-marker))
(switch-to-buffer (or (marker-buffer marker)
(user-error "The marked buffer has been deleted")))
(goto-char (marker-position marker))
(set-marker marker nil nil)
(run-hooks 'xref-after-return-hook)))))
(define-obsolete-variable-alias
'xref--current-item
'xref-current-item
"29.1")
(defvar xref-current-item nil
"Dynamically bound to the current item being processed.
This can be used from `xref-after-jump-hook', for instance.")
(defun xref-pulse-momentarily ()
(pcase-let ((`(,beg . ,end)
(save-excursion
(or
(let ((length (xref-match-length xref-current-item)))
(and length (cons (point) (+ (point) length))))
(back-to-indentation)
(if (eolp)
(cons (line-beginning-position) (1+ (point)))
(cons (point) (line-end-position)))))))
(pulse-momentary-highlight-region beg end 'next-error)))
;; etags.el needs this
(defun xref-clear-marker-stack ()
"Discard all markers from the xref history."
(let ((history (xref--get-history)))
(dolist (l (list (car history) (cdr history)))
(dolist (m l)
(set-marker m nil nil)))
(setcar history nil)
(setcdr history nil))
nil)
;;;###autoload
(defun xref-marker-stack-empty-p ()
"Whether the xref back-history is empty."
(null (car (xref--get-history))))
;; FIXME: rename this to `xref-back-history-empty-p'.
;;;###autoload
(defun xref-forward-history-empty-p ()
"Whether the xref forward-history is empty."
(null (cdr (xref--get-history))))
(defun xref--goto-char (pos)
(cond
((and (<= (point-min) pos) (<= pos (point-max))))
(widen-automatically (widen))
(t (user-error "Position is outside accessible part of buffer")))
(goto-char pos))
(defun xref--goto-location (location)
"Set buffer and point according to `xref-location' LOCATION."
(let ((marker (xref-location-marker location)))
(set-buffer (marker-buffer marker))
(xref--goto-char marker)))
(defun xref-pop-to-location (item &optional action)
"Go to the location of ITEM and display the buffer.
ACTION controls how the buffer is displayed:
nil -- `switch-to-buffer'
`window' -- `pop-to-buffer' (other window)
`frame' -- `pop-to-buffer' (other frame)
If SELECT is non-nil, select the target window."
(let* ((marker (save-excursion
(xref-location-marker (xref-item-location item))))
(buf (marker-buffer marker)))
(cl-ecase action
((nil) (switch-to-buffer buf))
(window (pop-to-buffer buf t))
(frame (let ((pop-up-frames t)) (pop-to-buffer buf t))))
(xref--goto-char marker))
(let ((xref-current-item item))
(run-hooks 'xref-after-jump-hook)))
;;; XREF buffer (part of the UI)
;; The xref buffer is used to display a set of xrefs.
(defconst xref-buffer-name "*xref*"
"The name of the buffer to show xrefs.")
(defface xref-file-header '((t :inherit compilation-info))
"Face used to highlight file header in the xref buffer."
:version "27.1")
(defface xref-line-number '((t :inherit compilation-line-number))
"Face for displaying line numbers in the xref buffer."
:version "27.1")
(defface xref-match '((t :inherit match))
"Face used to highlight matches in the xref buffer."
:version "28.1")
(defvar-local xref-num-matches-found 0)
(defvar xref-num-matches-face 'compilation-info
"Face name to show the number of matches on the mode line.")
(defconst xref-mode-line-matches
`(" [" (:propertize (:eval (int-to-string xref-num-matches-found))
face ,xref-num-matches-face
help-echo "Number of matches so far")
"]"))
(put 'xref-mode-line-matches 'risky-local-variable t)
(defmacro xref--with-dedicated-window (&rest body)
`(let* ((xref-w (get-buffer-window xref-buffer-name))
(xref-w-dedicated (window-dedicated-p xref-w)))
(unwind-protect
(progn
(when xref-w
(set-window-dedicated-p xref-w 'soft))
,@body)
(when xref-w
(set-window-dedicated-p xref-w xref-w-dedicated)))))
(defvar-local xref--original-window-intent nil
"Original window-switching intent before xref buffer creation.")
(defvar-local xref--original-window nil
"The original window this xref buffer was created from.")
(defvar-local xref--fetcher nil
"The original function to call to fetch the list of xrefs.")
(defun xref--show-pos-in-buf (pos buf)
"Goto and display position POS of buffer BUF in a window.
Honor `xref--original-window-intent', run `xref-after-jump-hook'
and finally return the window."
(let* ((pop-up-frames
(or (eq xref--original-window-intent 'frame)
pop-up-frames))
(action
(cond ((eq xref--original-window-intent 'frame)
t)
((eq xref--original-window-intent 'window)
`((xref--display-buffer-in-other-window)
(window . ,xref--original-window)))
((and
(window-live-p xref--original-window)
(or (not (window-dedicated-p xref--original-window))
(eq (window-buffer xref--original-window) buf)))
`((xref--display-buffer-in-window)
(window . ,xref--original-window))))))
(with-selected-window (display-buffer buf action)
(xref--goto-char pos)
(run-hooks 'xref-after-jump-hook)
(selected-window))))
(defun xref--display-buffer-in-other-window (buffer alist)
(let ((window (assoc-default 'window alist)))
(cl-assert window)
(xref--with-dedicated-window
(with-selected-window window
(display-buffer buffer t)))))
(defun xref--display-buffer-in-window (buffer alist)
(let ((window (assoc-default 'window alist)))
(cl-assert window)
(with-selected-window window
(display-buffer buffer '(display-buffer-same-window)))))
(defun xref--show-location (location &optional select)
"Help `xref-show-xref' and `xref-goto-xref' do their job.
Go to LOCATION and if SELECT is non-nil select its window.
If SELECT is `quit', also quit the *xref* window."
(condition-case err
(let* ((marker (xref-location-marker location))
(buf (marker-buffer marker))
(xref-buffer (current-buffer)))
(cond (select
(if (eq select 'quit) (quit-window nil nil))
(let* ((old-frame (selected-frame))
(window (with-current-buffer xref-buffer
(xref--show-pos-in-buf marker buf)))
(frame (window-frame window)))
;; If we chose another frame, make sure it gets input
;; focus.
(unless (eq frame old-frame)
(select-frame-set-input-focus frame))
(select-window window)))
(t
(save-selected-window
(xref--with-dedicated-window
(xref--show-pos-in-buf marker buf))))))
(user-error (message (error-message-string err)))))
(defun xref--set-arrow ()
"Set the overlay arrow at the line at point."
(setq overlay-arrow-position
(set-marker (or overlay-arrow-position (make-marker))
(line-beginning-position))))
(defun xref-show-location-at-point ()
"Display the source of xref at point in the appropriate window, if any."
(interactive)
(let* ((xref (xref--item-at-point))
(xref-current-item xref))
(when xref
(xref--set-arrow)
(xref--show-location (xref-item-location xref)))))
(defun xref-next-line-no-show ()
"Move to the next xref but don't display its source."
(interactive)
(xref--search-property 'xref-item))
(defun xref-next-line ()
"Move to the next xref and display its source in the appropriate window."
(interactive)
(xref-next-line-no-show)
(xref-show-location-at-point))
(defun xref-prev-line-no-show ()
"Move to the previous xref but don't display its source."
(interactive)
(xref--search-property 'xref-item t))
(defun xref-prev-line ()
"Move to the previous xref and display its source in the appropriate window."
(interactive)
(xref-prev-line-no-show)
(xref-show-location-at-point))
(defun xref-next-group ()
"Move to the first item of the next xref group and display its source."
(interactive)
(xref--search-property 'xref-group)
(xref--search-property 'xref-item)
(xref-show-location-at-point))
(defun xref-prev-group ()
"Move to the first item of the previous xref group and display its source."
(interactive)
;; Search for the xref group of the current item, provided that the
;; point is not already in an xref group.
(unless (plist-member (text-properties-at (point)) 'xref-group)
(xref--search-property 'xref-group t))
;; Search for the previous xref group.
(xref--search-property 'xref-group t)
(xref--search-property 'xref-item)
(xref-show-location-at-point))
(defun xref--item-at-point ()
(get-text-property
(if (eolp) (1- (point)) (point))
'xref-item))
(defun xref-goto-xref (&optional quit)
"Jump to the xref on the current line and select its window.
If QUIT is non-nil (interactively, with prefix argument), also
quit the *xref* buffer."
(interactive "P")
(let* ((buffer (current-buffer))
(xref (or (xref--item-at-point)
(user-error "Choose a reference to visit")))
(xref-current-item xref))
(xref--set-arrow)
(xref--show-location (xref-item-location xref) (if quit 'quit t))
(if (fboundp 'next-error-found)
(next-error-found buffer (current-buffer))
;; Emacs < 27
(setq next-error-last-buffer buffer))))
(defun xref-quit-and-goto-xref ()
"Quit *xref* buffer, then jump to xref on current line."
(interactive)
(xref-goto-xref t))
(defun xref-quit-and-pop-marker-stack ()
"Quit *xref* buffer, then pop the xref marker stack."
(interactive)
(quit-window)
(xref-go-back))
(defun xref-query-replace-in-results (from to)
"Perform interactive replacement of FROM with TO in all displayed xrefs.
This function interactively replaces FROM with TO in the names of the
references displayed in the current *xref* buffer.
When called interactively, it uses '.*' as FROM, which means replace
the whole name, and prompts the user for TO.
If invoked with prefix argument, it prompts the user for both FROM and TO.
As each match is found, the user must type a character saying
what to do with it. Type SPC or `y' to replace the match,
DEL or `n' to skip and go to the next match. For more directions,
type \\[help-command] at that time.
Note that this function cannot be used in *xref* buffers that show
a partial list of all references, such as the *xref* buffer created
by \\[xref-find-definitions] and its variants, since those list only
some of the references to the identifiers."
(interactive
(let* ((fr
(if current-prefix-arg
(read-regexp "Query-replace (regexp)" ".*")
".*"))
(prompt (if current-prefix-arg
(format "Query-replace (regexp) %s with: " fr)
"Query-replace all matches with: ")))
(list fr (read-regexp prompt))))
(let* (item xrefs iter)
(save-excursion
(while (setq item (xref--search-property 'xref-item))
(when (xref-match-length item)
(push item xrefs))))
(unwind-protect
(progn
(goto-char (point-min))
(setq iter (xref--buf-pairs-iterator (nreverse xrefs)))
(xref--query-replace-1 from to iter))
(funcall iter :cleanup))))
(defun xref--buf-pairs-iterator (xrefs)
(let (chunk-done item next-pair file-buf pairs all-pairs)
(lambda (action)
(pcase action
(:next
(when (or xrefs next-pair)
(setq chunk-done nil)
(when next-pair
(setq file-buf (marker-buffer (car next-pair))
pairs (list next-pair)
next-pair nil))
(while (and (not chunk-done)
(setq item (pop xrefs)))
(save-excursion
(let* ((loc (xref-item-location item))
(beg (xref-location-marker loc))
(end (move-marker (make-marker)
(+ beg (xref-match-length item))
(marker-buffer beg))))
(let ((pair (cons beg end)))
(push pair all-pairs)
;; Perform sanity check first.
(xref--goto-location loc)
(if (xref--outdated-p item)
(message "Search result out of date, skipping")
(cond
((null file-buf)
(setq file-buf (marker-buffer beg))
(push pair pairs))
((equal file-buf (marker-buffer beg))
(push pair pairs))
(t
(setq chunk-done t
next-pair pair))))))))
(cons file-buf (nreverse pairs))))
(:cleanup
(dolist (pair all-pairs)
(move-marker (car pair) nil)
(move-marker (cdr pair) nil)))))))
(defun xref--outdated-p (item)
"Check that the match location at current position is up-to-date.
ITEM is an xref item which is expected to be produced by a search
command and have summary that matches buffer contents near point.
Depending on whether it's the first of the matches on the line,
the summary should either start from bol, or only match after
point."
;; FIXME: The check should most likely be a generic function instead
;; of the assumption that all matches' summaries relate to the
;; buffer text in a particular way.
(let* ((summary (xref-item-summary item))
;; Sometimes buffer contents include ^M, and sometimes Grep
;; output includes it, and they don't always match.
(strip (lambda (s) (if (string-match "\r\\'" s)
(substring-no-properties s 0 -1)
s)))
(stripped-summary (funcall strip summary))
(lendpos (line-end-position))
(check (lambda ()
(let ((comparison-end
(+ (point) (length stripped-summary))))
(and (>= lendpos comparison-end)
(equal stripped-summary
(buffer-substring-no-properties
(point) comparison-end)))))))
(not
(or
;; Either summary contains match text and after
;; (2nd+ match on the line)...
(funcall check)
;; ...or it starts at bol, includes the match and after.
(and (< (point) (+ (line-beginning-position)
(length stripped-summary)))
(save-excursion
(forward-line 0)
(funcall check)))))))
;; FIXME: Write a nicer UI.
(defun xref--query-replace-1 (from to iter)
(let* ((query-replace-lazy-highlight nil)
(continue t)
did-it-once buf-pairs pairs
current-beg current-end
;; Counteract the "do the next match now" hack in
;; `perform-replace'. And still, it'll report that those
;; matches were "filtered out" at the end.
(isearch-filter-predicate
(lambda (beg end)
(and current-beg
(>= beg current-beg)
(<= end current-end))))
(replace-re-search-function
(lambda (from &optional _bound noerror)
(let (found pair)
(while (and (not found) pairs)
(setq pair (pop pairs)
current-beg (car pair)
current-end (cdr pair))
(goto-char current-beg)
(when (re-search-forward from current-end noerror)
(setq found t)))
found))))
(while (and continue (setq buf-pairs (funcall iter :next)))
(if did-it-once
;; Reuse the same window for subsequent buffers.
(switch-to-buffer (car buf-pairs))
(xref--with-dedicated-window
(pop-to-buffer (car buf-pairs)))
(setq did-it-once t))
(setq pairs (cdr buf-pairs))
(setq continue
(perform-replace from to t t nil nil multi-query-replace-map)))
(unless did-it-once
(user-error
"Cannot perform global renaming of symbols using find-definition results"))
(when (and continue (not buf-pairs))
(message "All results processed"))))
(defvar xref--xref-buffer-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "n") #'xref-next-line)
(define-key map (kbd "p") #'xref-prev-line)
(define-key map (kbd "N") #'xref-next-group)
(define-key map (kbd "P") #'xref-prev-group)
(define-key map (kbd "r") #'xref-query-replace-in-results)
(define-key map (kbd "RET") #'xref-goto-xref)
(define-key map (kbd "TAB") #'xref-quit-and-goto-xref)
(define-key map (kbd "C-o") #'xref-show-location-at-point)
;; suggested by Johan Claesson "to further reduce finger movement":
(define-key map (kbd ".") #'xref-next-line)
(define-key map (kbd ",") #'xref-prev-line)
(define-key map (kbd "M-,") #'xref-quit-and-pop-marker-stack)
map))
(declare-function outline-search-text-property "outline"
(property &optional value bound move backward looking-at))