]> code.delx.au - gnu-emacs/blob - lisp/progmodes/xref.el
Unify the absolutely equal xref-backend-references implementations
[gnu-emacs] / lisp / progmodes / xref.el
1 ;; xref.el --- Cross-referencing commands -*-lexical-binding:t-*-
2
3 ;; Copyright (C) 2014-2015 Free Software Foundation, Inc.
4
5 ;; This file is part of GNU Emacs.
6
7 ;; GNU Emacs is free software: you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
11
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
16
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
19
20 ;;; Commentary:
21
22 ;; This file provides a somewhat generic infrastructure for cross
23 ;; referencing commands, in particular "find-definition".
24 ;;
25 ;; Some part of the functionality must be implemented in a language
26 ;; dependent way and that's done by defining an xref backend.
27 ;;
28 ;; That consists of a constructor function, which should return a
29 ;; backend value, and a set of implementations for the generic
30 ;; functions:
31 ;;
32 ;; `xref-backend-identifier-at-point',
33 ;; `xref-backend-identifier-completion-table',
34 ;; `xref-backend-definitions', `xref-backend-references',
35 ;; `xref-backend-apropos', which see.
36 ;;
37 ;; A major mode would normally use `add-hook' to add the backend
38 ;; constructor to `xref-backend-functions'.
39 ;;
40 ;; The last three methods operate with "xref" and "location" values.
41 ;;
42 ;; One would usually call `make-xref' and `xref-make-file-location',
43 ;; `xref-make-buffer-location' or `xref-make-bogus-location' to create
44 ;; them. More generally, a location must be an instance of an EIEIO
45 ;; class inheriting from `xref-location' and implementing
46 ;; `xref-location-group' and `xref-location-marker'.
47 ;;
48 ;; There's a special kind of xrefs we call "match xrefs", which
49 ;; correspond to search results. For these values,
50 ;; `xref-match-length' must be defined, and `xref-location-marker'
51 ;; must return the beginning of the match.
52 ;;
53 ;; Each identifier must be represented as a string. Implementers can
54 ;; use string properties to store additional information about the
55 ;; identifier, but they should keep in mind that values returned from
56 ;; `xref-backend-identifier-completion-table' should still be
57 ;; distinct, because the user can't see the properties when making the
58 ;; choice.
59 ;;
60 ;; See the etags and elisp-mode implementations for full examples.
61
62 ;;; Code:
63
64 (require 'cl-lib)
65 (require 'eieio)
66 (require 'ring)
67 (require 'pcase)
68 (require 'project)
69
70 (eval-when-compile
71 (require 'semantic/symref)) ;; for hit-lines slot
72
73 (defgroup xref nil "Cross-referencing commands"
74 :group 'tools)
75
76 \f
77 ;;; Locations
78
79 (defclass xref-location () ()
80 :documentation "A location represents a position in a file or buffer.")
81
82 (cl-defgeneric xref-location-marker (location)
83 "Return the marker for LOCATION.")
84
85 (cl-defgeneric xref-location-group (location)
86 "Return a string used to group a set of locations.
87 This is typically the filename.")
88
89 (cl-defgeneric xref-location-line (_location)
90 "Return the line number corresponding to the location."
91 nil)
92
93 (cl-defgeneric xref-match-length (_item)
94 "Return the length of the match."
95 nil)
96
97 ;;;; Commonly needed location classes are defined here:
98
99 ;; FIXME: might be useful to have an optional "hint" i.e. a string to
100 ;; search for in case the line number is sightly out of date.
101 (defclass xref-file-location (xref-location)
102 ((file :type string :initarg :file)
103 (line :type fixnum :initarg :line :reader xref-location-line)
104 (column :type fixnum :initarg :column :reader xref-file-location-column))
105 :documentation "A file location is a file/line/column triple.
106 Line numbers start from 1 and columns from 0.")
107
108 (defun xref-make-file-location (file line column)
109 "Create and return a new `xref-file-location'."
110 (make-instance 'xref-file-location :file file :line line :column column))
111
112 (cl-defmethod xref-location-marker ((l xref-file-location))
113 (with-slots (file line column) l
114 (with-current-buffer
115 (or (get-file-buffer file)
116 (let ((find-file-suppress-same-file-warnings t))
117 (find-file-noselect file)))
118 (save-restriction
119 (widen)
120 (save-excursion
121 (goto-char (point-min))
122 (beginning-of-line line)
123 (forward-char column)
124 (point-marker))))))
125
126 (cl-defmethod xref-location-group ((l xref-file-location))
127 (oref l file))
128
129 (defclass xref-buffer-location (xref-location)
130 ((buffer :type buffer :initarg :buffer)
131 (position :type fixnum :initarg :position)))
132
133 (defun xref-make-buffer-location (buffer position)
134 "Create and return a new `xref-buffer-location'."
135 (make-instance 'xref-buffer-location :buffer buffer :position position))
136
137 (cl-defmethod xref-location-marker ((l xref-buffer-location))
138 (with-slots (buffer position) l
139 (let ((m (make-marker)))
140 (move-marker m position buffer))))
141
142 (cl-defmethod xref-location-group ((l xref-buffer-location))
143 (with-slots (buffer) l
144 (or (buffer-file-name buffer)
145 (format "(buffer %s)" (buffer-name buffer)))))
146
147 (defclass xref-bogus-location (xref-location)
148 ((message :type string :initarg :message
149 :reader xref-bogus-location-message))
150 :documentation "Bogus locations are sometimes useful to
151 indicate errors, e.g. when we know that a function exists but the
152 actual location is not known.")
153
154 (defun xref-make-bogus-location (message)
155 "Create and return a new `xref-bogus-location'."
156 (make-instance 'xref-bogus-location :message message))
157
158 (cl-defmethod xref-location-marker ((l xref-bogus-location))
159 (user-error "%s" (oref l message)))
160
161 (cl-defmethod xref-location-group ((_ xref-bogus-location)) "(No location)")
162
163 \f
164 ;;; Cross-reference
165
166 (defclass xref-item ()
167 ((summary :type string :initarg :summary
168 :reader xref-item-summary
169 :documentation "One line which will be displayed for
170 this item in the output buffer.")
171 (location :initarg :location
172 :reader xref-item-location
173 :documentation "An object describing how to navigate
174 to the reference's target."))
175 :comment "An xref item describes a reference to a location
176 somewhere.")
177
178 (defun xref-make (summary location)
179 "Create and return a new `xref-item'.
180 SUMMARY is a short string to describe the xref.
181 LOCATION is an `xref-location'."
182 (make-instance 'xref-item :summary summary :location location))
183
184 (defclass xref-match-item ()
185 ((summary :type string :initarg :summary
186 :reader xref-item-summary)
187 (location :initarg :location
188 :type xref-file-location
189 :reader xref-item-location)
190 (length :initarg :length :reader xref-match-length))
191 :comment "A match xref item describes a search result.")
192
193 (defun xref-make-match (summary location length)
194 "Create and return a new `xref-match-item'.
195 SUMMARY is a short string to describe the xref.
196 LOCATION is an `xref-location'.
197 LENGTH is the match length, in characters."
198 (make-instance 'xref-match-item :summary summary
199 :location location :length length))
200
201 \f
202 ;;; API
203
204 ;; We make the etags backend the default for now, until something
205 ;; better comes along.
206 (defvar xref-backend-functions (list #'xref--etags-backend)
207 "Special hook to find the xref backend for the current context.
208 Each functions on this hook is called in turn with no arguments
209 and should return either nil to mean that it is not applicable,
210 or an xref backend, which is a value to be used to dispatch the
211 generic functions.")
212
213 ;;;###autoload
214 (defun xref-find-backend ()
215 (run-hook-with-args-until-success 'xref-backend-functions))
216
217 (defun xref--etags-backend () 'etags)
218
219 (cl-defgeneric xref-backend-definitions (backend identifier)
220 "Find definitions of IDENTIFIER.
221
222 The result must be a list of xref objects. If IDENTIFIER
223 contains sufficient information to determine a unique definition,
224 return only that definition. If there are multiple possible
225 definitions, return all of them. If no definitions can be found,
226 return nil.
227
228 IDENTIFIER can be any string returned by
229 `xref-backend-identifier-at-point', or from the table returned by
230 `xref-backend-identifier-completion-table'.
231
232 To create an xref object, call `xref-make'.")
233
234 (cl-defgeneric xref-backend-references (_backend identifier)
235 "Find references of IDENTIFIER.
236 The result must be a list of xref objects. If no references can
237 be found, return nil.
238
239 The default implementation performs a Grep symbol-search inside
240 the current project."
241 (cl-mapcan
242 (lambda (dir)
243 (xref-collect-references identifier dir))
244 (let ((pr (project-current t)))
245 (append
246 (project-roots pr)
247 (project-library-roots pr)))))
248
249 (cl-defgeneric xref-backend-apropos (backend pattern)
250 "Find all symbols that match PATTERN.
251 PATTERN is a regexp")
252
253 (cl-defgeneric xref-backend-identifier-at-point (_backend)
254 "Return the relevant identifier at point.
255
256 The return value must be a string or nil. nil means no
257 identifier at point found.
258
259 If it's hard to determine the identifier precisely (e.g., because
260 it's a method call on unknown type), the implementation can
261 return a simple string (such as symbol at point) marked with a
262 special text property which e.g. `xref-backend-definitions' would
263 recognize and then delegate the work to an external process."
264 (let ((thing (thing-at-point 'symbol)))
265 (and thing (substring-no-properties thing))))
266
267 (cl-defgeneric xref-backend-identifier-completion-table (backend)
268 "Returns the completion table for identifiers.")
269
270 \f
271 ;;; misc utilities
272 (defun xref--alistify (list key test)
273 "Partition the elements of LIST into an alist.
274 KEY extracts the key from an element and TEST is used to compare
275 keys."
276 (let ((alist '()))
277 (dolist (e list)
278 (let* ((k (funcall key e))
279 (probe (cl-assoc k alist :test test)))
280 (if probe
281 (setcdr probe (cons e (cdr probe)))
282 (push (cons k (list e)) alist))))
283 ;; Put them back in order.
284 (cl-loop for (key . value) in (reverse alist)
285 collect (cons key (reverse value)))))
286
287 (defun xref--insert-propertized (props &rest strings)
288 "Insert STRINGS with text properties PROPS."
289 (let ((start (point)))
290 (apply #'insert strings)
291 (add-text-properties start (point) props)))
292
293 (defun xref--search-property (property &optional backward)
294 "Search the next text range where text property PROPERTY is non-nil.
295 Return the value of PROPERTY. If BACKWARD is non-nil, search
296 backward."
297 (let ((next (if backward
298 #'previous-single-char-property-change
299 #'next-single-char-property-change))
300 (start (point))
301 (value nil))
302 (while (progn
303 (goto-char (funcall next (point) property))
304 (not (or (setq value (get-text-property (point) property))
305 (eobp)
306 (bobp)))))
307 (cond (value)
308 (t (goto-char start) nil))))
309
310 \f
311 ;;; Marker stack (M-. pushes, M-, pops)
312
313 (defcustom xref-marker-ring-length 16
314 "Length of the xref marker ring."
315 :type 'integer)
316
317 (defcustom xref-prompt-for-identifier '(not xref-find-definitions
318 xref-find-definitions-other-window
319 xref-find-definitions-other-frame)
320 "When t, always prompt for the identifier name.
321
322 When nil, prompt only when there's no value at point we can use,
323 or when the command has been called with the prefix argument.
324
325 Otherwise, it's a list of xref commands which will prompt
326 anyway (the value at point, if any, will be used as the default).
327
328 If the list starts with `not', the meaning of the rest of the
329 elements is negated."
330 :type '(choice (const :tag "always" t)
331 (const :tag "auto" nil)
332 (set :menu-tag "command specific" :tag "commands"
333 :value (not)
334 (const :tag "Except" not)
335 (repeat :inline t (symbol :tag "command")))))
336
337 (defcustom xref-after-jump-hook '(recenter
338 xref-pulse-momentarily)
339 "Functions called after jumping to an xref."
340 :type 'hook)
341
342 (defcustom xref-after-return-hook '(xref-pulse-momentarily)
343 "Functions called after returning to a pre-jump location."
344 :type 'hook)
345
346 (defvar xref--marker-ring (make-ring xref-marker-ring-length)
347 "Ring of markers to implement the marker stack.")
348
349 (defun xref-push-marker-stack (&optional m)
350 "Add point M (defaults to `point-marker') to the marker stack."
351 (ring-insert xref--marker-ring (or m (point-marker))))
352
353 ;;;###autoload
354 (defun xref-pop-marker-stack ()
355 "Pop back to where \\[xref-find-definitions] was last invoked."
356 (interactive)
357 (let ((ring xref--marker-ring))
358 (when (ring-empty-p ring)
359 (user-error "Marker stack is empty"))
360 (let ((marker (ring-remove ring 0)))
361 (switch-to-buffer (or (marker-buffer marker)
362 (user-error "The marked buffer has been deleted")))
363 (goto-char (marker-position marker))
364 (set-marker marker nil nil)
365 (run-hooks 'xref-after-return-hook))))
366
367 (defvar xref--current-item nil)
368
369 (defun xref-pulse-momentarily ()
370 (pcase-let ((`(,beg . ,end)
371 (save-excursion
372 (or
373 (let ((length (xref-match-length xref--current-item)))
374 (and length (cons (point) (+ (point) length))))
375 (back-to-indentation)
376 (if (eolp)
377 (cons (line-beginning-position) (1+ (point)))
378 (cons (point) (line-end-position)))))))
379 (pulse-momentary-highlight-region beg end 'next-error)))
380
381 ;; etags.el needs this
382 (defun xref-clear-marker-stack ()
383 "Discard all markers from the marker stack."
384 (let ((ring xref--marker-ring))
385 (while (not (ring-empty-p ring))
386 (let ((marker (ring-remove ring)))
387 (set-marker marker nil nil)))))
388
389 ;;;###autoload
390 (defun xref-marker-stack-empty-p ()
391 "Return t if the marker stack is empty; nil otherwise."
392 (ring-empty-p xref--marker-ring))
393
394 \f
395
396 (defun xref--goto-char (pos)
397 (cond
398 ((and (<= (point-min) pos) (<= pos (point-max))))
399 (widen-automatically (widen))
400 (t (user-error "Position is outside accessible part of buffer")))
401 (goto-char pos))
402
403 (defun xref--goto-location (location)
404 "Set buffer and point according to xref-location LOCATION."
405 (let ((marker (xref-location-marker location)))
406 (set-buffer (marker-buffer marker))
407 (xref--goto-char marker)))
408
409 (defun xref--pop-to-location (item &optional window)
410 "Go to the location of ITEM and display the buffer.
411 WINDOW controls how the buffer is displayed:
412 nil -- switch-to-buffer
413 `window' -- pop-to-buffer (other window)
414 `frame' -- pop-to-buffer (other frame)"
415 (let* ((marker (save-excursion
416 (xref-location-marker (xref-item-location item))))
417 (buf (marker-buffer marker)))
418 (cl-ecase window
419 ((nil) (switch-to-buffer buf))
420 (window (pop-to-buffer buf t))
421 (frame (let ((pop-up-frames t)) (pop-to-buffer buf t))))
422 (xref--goto-char marker))
423 (let ((xref--current-item item))
424 (run-hooks 'xref-after-jump-hook)))
425
426 \f
427 ;;; XREF buffer (part of the UI)
428
429 ;; The xref buffer is used to display a set of xrefs.
430
431 (defvar-local xref--display-history nil
432 "List of pairs (BUFFER . WINDOW), for temporarily displayed buffers.")
433
434 (defun xref--save-to-history (buf win)
435 (let ((restore (window-parameter win 'quit-restore)))
436 ;; Save the new entry if the window displayed another buffer
437 ;; previously.
438 (when (and restore (not (eq (car restore) 'same)))
439 (push (cons buf win) xref--display-history))))
440
441 (defun xref--display-position (pos other-window buf)
442 ;; Show the location, but don't hijack focus.
443 (let ((xref-buf (current-buffer)))
444 (with-selected-window (display-buffer buf other-window)
445 (xref--goto-char pos)
446 (run-hooks 'xref-after-jump-hook)
447 (let ((buf (current-buffer))
448 (win (selected-window)))
449 (with-current-buffer xref-buf
450 (setq-local other-window-scroll-buffer buf)
451 (xref--save-to-history buf win))))))
452
453 (defun xref--show-location (location)
454 (condition-case err
455 (let* ((marker (xref-location-marker location))
456 (buf (marker-buffer marker)))
457 (xref--display-position marker t buf))
458 (user-error (message (error-message-string err)))))
459
460 (defun xref-show-location-at-point ()
461 "Display the source of xref at point in the other window, if any."
462 (interactive)
463 (let* ((xref (xref--item-at-point))
464 (xref--current-item xref))
465 (when xref
466 (xref--show-location (xref-item-location xref)))))
467
468 (defun xref-next-line ()
469 "Move to the next xref and display its source in the other window."
470 (interactive)
471 (xref--search-property 'xref-item)
472 (xref-show-location-at-point))
473
474 (defun xref-prev-line ()
475 "Move to the previous xref and display its source in the other window."
476 (interactive)
477 (xref--search-property 'xref-item t)
478 (xref-show-location-at-point))
479
480 (defun xref--item-at-point ()
481 (save-excursion
482 (back-to-indentation)
483 (get-text-property (point) 'xref-item)))
484
485 (defvar-local xref--window nil
486 "ACTION argument to call `display-buffer' with.")
487
488 (defun xref-goto-xref ()
489 "Jump to the xref on the current line and bury the xref buffer."
490 (interactive)
491 (let ((xref (or (xref--item-at-point)
492 (user-error "No reference at point")))
493 (window xref--window))
494 (xref-quit)
495 (xref--pop-to-location xref window)))
496
497 (defun xref-query-replace (from to)
498 "Perform interactive replacement in all current matches."
499 (interactive
500 (list (read-regexp "Query replace regexp in matches" ".*")
501 (read-regexp "Replace with: ")))
502 (let (pairs item)
503 (unwind-protect
504 (progn
505 (save-excursion
506 (goto-char (point-min))
507 (while (setq item (xref--search-property 'xref-item))
508 (when (xref-match-length item)
509 (save-excursion
510 (let* ((loc (xref-item-location item))
511 (beg (xref-location-marker loc))
512 (end (move-marker (make-marker)
513 (+ beg (xref-match-length item))
514 (marker-buffer beg))))
515 ;; Perform sanity check first.
516 (xref--goto-location loc)
517 ;; FIXME: The check should probably be a generic
518 ;; function, instead of the assumption that all
519 ;; matches contain the full line as summary.
520 ;; TODO: Offer to re-scan otherwise.
521 (unless (equal (buffer-substring-no-properties
522 (line-beginning-position)
523 (line-end-position))
524 (xref-item-summary item))
525 (user-error "Search results out of date"))
526 (push (cons beg end) pairs)))))
527 (setq pairs (nreverse pairs)))
528 (unless pairs (user-error "No suitable matches here"))
529 (xref--query-replace-1 from to pairs))
530 (dolist (pair pairs)
531 (move-marker (car pair) nil)
532 (move-marker (cdr pair) nil)))))
533
534 ;; FIXME: Write a nicer UI.
535 (defun xref--query-replace-1 (from to pairs)
536 (let* ((query-replace-lazy-highlight nil)
537 current-beg current-end current-buf
538 ;; Counteract the "do the next match now" hack in
539 ;; `perform-replace'. And still, it'll report that those
540 ;; matches were "filtered out" at the end.
541 (isearch-filter-predicate
542 (lambda (beg end)
543 (and current-beg
544 (eq (current-buffer) current-buf)
545 (>= beg current-beg)
546 (<= end current-end))))
547 (replace-re-search-function
548 (lambda (from &optional _bound noerror)
549 (let (found pair)
550 (while (and (not found) pairs)
551 (setq pair (pop pairs)
552 current-beg (car pair)
553 current-end (cdr pair)
554 current-buf (marker-buffer current-beg))
555 (pop-to-buffer current-buf)
556 (goto-char current-beg)
557 (when (re-search-forward from current-end noerror)
558 (setq found t)))
559 found))))
560 ;; FIXME: Despite this being a multi-buffer replacement, `N'
561 ;; doesn't work, because we're not using
562 ;; `multi-query-replace-map', and it would expect the below
563 ;; function to be called once per buffer.
564 (perform-replace from to t t nil)))
565
566 (defvar xref--xref-buffer-mode-map
567 (let ((map (make-sparse-keymap)))
568 (define-key map [remap quit-window] #'xref-quit)
569 (define-key map (kbd "n") #'xref-next-line)
570 (define-key map (kbd "p") #'xref-prev-line)
571 (define-key map (kbd "r") #'xref-query-replace)
572 (define-key map (kbd "RET") #'xref-goto-xref)
573 (define-key map (kbd "C-o") #'xref-show-location-at-point)
574 ;; suggested by Johan Claesson "to further reduce finger movement":
575 (define-key map (kbd ".") #'xref-next-line)
576 (define-key map (kbd ",") #'xref-prev-line)
577 map))
578
579 (define-derived-mode xref--xref-buffer-mode special-mode "XREF"
580 "Mode for displaying cross-references."
581 (setq buffer-read-only t)
582 (setq next-error-function #'xref--next-error-function)
583 (setq next-error-last-buffer (current-buffer)))
584
585 (defun xref--next-error-function (n reset?)
586 (when reset?
587 (goto-char (point-min)))
588 (let ((backward (< n 0))
589 (n (abs n))
590 (xref nil))
591 (dotimes (_ n)
592 (setq xref (xref--search-property 'xref-item backward)))
593 (cond (xref
594 (xref--pop-to-location xref))
595 (t
596 (error "No %s xref" (if backward "previous" "next"))))))
597
598 (defun xref-quit (&optional kill)
599 "Bury temporarily displayed buffers, then quit the current window.
600
601 If KILL is non-nil, also kill the current buffer.
602
603 The buffers that the user has otherwise interacted with in the
604 meantime are preserved."
605 (interactive "P")
606 (let ((window (selected-window))
607 (history xref--display-history))
608 (setq xref--display-history nil)
609 (pcase-dolist (`(,buf . ,win) history)
610 (when (and (window-live-p win)
611 (eq buf (window-buffer win)))
612 (quit-window nil win)))
613 (quit-window kill window)))
614
615 (defconst xref-buffer-name "*xref*"
616 "The name of the buffer to show xrefs.")
617
618 (defvar xref--button-map
619 (let ((map (make-sparse-keymap)))
620 (define-key map [(control ?m)] #'xref-goto-xref)
621 (define-key map [mouse-1] #'xref-goto-xref)
622 (define-key map [mouse-2] #'xref--mouse-2)
623 map))
624
625 (defun xref--mouse-2 (event)
626 "Move point to the button and show the xref definition."
627 (interactive "e")
628 (mouse-set-point event)
629 (forward-line 0)
630 (xref--search-property 'xref-item)
631 (xref-show-location-at-point))
632
633 (defun xref--insert-xrefs (xref-alist)
634 "Insert XREF-ALIST in the current-buffer.
635 XREF-ALIST is of the form ((GROUP . (XREF ...)) ...), where
636 GROUP is a string for decoration purposes and XREF is an
637 `xref-item' object."
638 (require 'compile) ; For the compilation faces.
639 (cl-loop for ((group . xrefs) . more1) on xref-alist
640 for max-line-width =
641 (cl-loop for xref in xrefs
642 maximize (let ((line (xref-location-line
643 (oref xref location))))
644 (length (and line (format "%d" line)))))
645 for line-format = (and max-line-width
646 (format "%%%dd: " max-line-width))
647 do
648 (xref--insert-propertized '(face compilation-info) group "\n")
649 (cl-loop for (xref . more2) on xrefs do
650 (with-slots (summary location) xref
651 (let* ((line (xref-location-line location))
652 (prefix
653 (if line
654 (propertize (format line-format line)
655 'face 'compilation-line-number)
656 " ")))
657 (xref--insert-propertized
658 (list 'xref-item xref
659 ;; 'face 'font-lock-keyword-face
660 'mouse-face 'highlight
661 'keymap xref--button-map
662 'help-echo
663 (concat "mouse-2: display in another window, "
664 "RET or mouse-1: follow reference"))
665 prefix summary)))
666 (insert "\n"))))
667
668 (defun xref--analyze (xrefs)
669 "Find common filenames in XREFS.
670 Return an alist of the form ((FILENAME . (XREF ...)) ...)."
671 (xref--alistify xrefs
672 (lambda (x)
673 (xref-location-group (xref-item-location x)))
674 #'equal))
675
676 (defun xref--show-xref-buffer (xrefs alist)
677 (let ((xref-alist (xref--analyze xrefs)))
678 (with-current-buffer (get-buffer-create xref-buffer-name)
679 (let ((inhibit-read-only t))
680 (erase-buffer)
681 (xref--insert-xrefs xref-alist)
682 (xref--xref-buffer-mode)
683 (pop-to-buffer (current-buffer))
684 (goto-char (point-min))
685 (setq xref--window (assoc-default 'window alist))
686 (current-buffer)))))
687
688 \f
689 ;; This part of the UI seems fairly uncontroversial: it reads the
690 ;; identifier and deals with the single definition case.
691 ;; (FIXME: do we really want this case to be handled like that in
692 ;; "find references" and "find regexp searches"?)
693 ;;
694 ;; The controversial multiple definitions case is handed off to
695 ;; xref-show-xrefs-function.
696
697 (defvar xref-show-xrefs-function 'xref--show-xref-buffer
698 "Function to display a list of xrefs.")
699
700 (defvar xref--read-identifier-history nil)
701
702 (defvar xref--read-pattern-history nil)
703
704 (defun xref--show-xrefs (xrefs window)
705 (cond
706 ((not (cdr xrefs))
707 (xref-push-marker-stack)
708 (xref--pop-to-location (car xrefs) window))
709 (t
710 (xref-push-marker-stack)
711 (funcall xref-show-xrefs-function xrefs
712 `((window . ,window))))))
713
714 (defun xref--prompt-p (command)
715 (or (eq xref-prompt-for-identifier t)
716 (if (eq (car xref-prompt-for-identifier) 'not)
717 (not (memq command (cdr xref-prompt-for-identifier)))
718 (memq command xref-prompt-for-identifier))))
719
720 (defun xref--read-identifier (prompt)
721 "Return the identifier at point or read it from the minibuffer."
722 (let* ((backend (xref-find-backend))
723 (id (xref-backend-identifier-at-point backend)))
724 (cond ((or current-prefix-arg
725 (not id)
726 (xref--prompt-p this-command))
727 (completing-read (if id
728 (format "%s (default %s): "
729 (substring prompt 0 (string-match
730 "[ :]+\\'" prompt))
731 id)
732 prompt)
733 (xref-backend-identifier-completion-table backend)
734 nil nil nil
735 'xref--read-identifier-history id))
736 (t id))))
737
738 \f
739 ;;; Commands
740
741 (defun xref--find-xrefs (input kind arg window)
742 (let ((xrefs (funcall (intern (format "xref-backend-%s" kind))
743 (xref-find-backend)
744 arg)))
745 (unless xrefs
746 (user-error "No %s found for: %s" (symbol-name kind) input))
747 (xref--show-xrefs xrefs window)))
748
749 (defun xref--find-definitions (id window)
750 (xref--find-xrefs id 'definitions id window))
751
752 ;;;###autoload
753 (defun xref-find-definitions (identifier)
754 "Find the definition of the identifier at point.
755 With prefix argument or when there's no identifier at point,
756 prompt for it.
757
758 If the backend has sufficient information to determine a unique
759 definition for IDENTIFIER, it returns only that definition. If
760 there are multiple possible definitions, it returns all of them.
761
762 If the backend returns one definition, jump to it; otherwise,
763 display the list in a buffer."
764 (interactive (list (xref--read-identifier "Find definitions of: ")))
765 (xref--find-definitions identifier nil))
766
767 ;;;###autoload
768 (defun xref-find-definitions-other-window (identifier)
769 "Like `xref-find-definitions' but switch to the other window."
770 (interactive (list (xref--read-identifier "Find definitions of: ")))
771 (xref--find-definitions identifier 'window))
772
773 ;;;###autoload
774 (defun xref-find-definitions-other-frame (identifier)
775 "Like `xref-find-definitions' but switch to the other frame."
776 (interactive (list (xref--read-identifier "Find definitions of: ")))
777 (xref--find-definitions identifier 'frame))
778
779 ;;;###autoload
780 (defun xref-find-references (identifier)
781 "Find references to the identifier at point.
782 With prefix argument, prompt for the identifier."
783 (interactive (list (xref--read-identifier "Find references of: ")))
784 (xref--find-xrefs identifier 'references identifier nil))
785
786 (declare-function apropos-parse-pattern "apropos" (pattern))
787
788 ;;;###autoload
789 (defun xref-find-apropos (pattern)
790 "Find all meaningful symbols that match PATTERN.
791 The argument has the same meaning as in `apropos'."
792 (interactive (list (read-string
793 "Search for pattern (word list or regexp): "
794 nil 'xref--read-pattern-history)))
795 (require 'apropos)
796 (xref--find-xrefs pattern 'apropos
797 (apropos-parse-pattern
798 (if (string-equal (regexp-quote pattern) pattern)
799 ;; Split into words
800 (or (split-string pattern "[ \t]+" t)
801 (user-error "No word list given"))
802 pattern))
803 nil))
804
805 \f
806 ;;; Key bindings
807
808 ;;;###autoload (define-key esc-map "." #'xref-find-definitions)
809 ;;;###autoload (define-key esc-map "," #'xref-pop-marker-stack)
810 ;;;###autoload (define-key esc-map "?" #'xref-find-references)
811 ;;;###autoload (define-key esc-map [?\C-.] #'xref-find-apropos)
812 ;;;###autoload (define-key ctl-x-4-map "." #'xref-find-definitions-other-window)
813 ;;;###autoload (define-key ctl-x-5-map "." #'xref-find-definitions-other-frame)
814
815 \f
816 ;;; Helper functions
817
818 (defvar xref-etags-mode--saved nil)
819
820 (define-minor-mode xref-etags-mode
821 "Minor mode to make xref use etags again.
822
823 Certain major modes install their own mechanisms for listing
824 identifiers and navigation. Turn this on to undo those settings
825 and just use etags."
826 :lighter ""
827 (if xref-etags-mode
828 (progn
829 (setq xref-etags-mode--saved xref-backend-functions)
830 (kill-local-variable 'xref-backend-functions))
831 (setq-local xref-backend-functions xref-etags-mode--saved)))
832
833 (declare-function semantic-symref-find-references-by-name "semantic/symref")
834 (declare-function semantic-find-file-noselect "semantic/fw")
835 (declare-function grep-expand-template "grep")
836
837 (defun xref-collect-references (symbol dir)
838 "Collect references to SYMBOL inside DIR.
839 This function uses the Semantic Symbol Reference API, see
840 `semantic-symref-find-references-by-name' for details on which
841 tools are used, and when."
842 (cl-assert (directory-name-p dir))
843 (require 'semantic/symref)
844 (defvar semantic-symref-tool)
845 (let* ((default-directory dir)
846 (semantic-symref-tool 'detect)
847 (res (semantic-symref-find-references-by-name symbol 'subdirs))
848 (hits (and res (oref res hit-lines)))
849 (orig-buffers (buffer-list)))
850 (unwind-protect
851 (cl-mapcan (lambda (hit) (xref--collect-matches
852 hit (format "\\_<%s\\_>" (regexp-quote symbol))))
853 hits)
854 ;; TODO: Implement "lightweight" buffer visiting, so that we
855 ;; don't have to kill them.
856 (mapc #'kill-buffer
857 (cl-set-difference (buffer-list) orig-buffers)))))
858
859 (defun xref-collect-matches (regexp files dir ignores)
860 "Collect matches for REGEXP inside FILES in DIR.
861 FILES is a string with glob patterns separated by spaces.
862 IGNORES is a list of glob patterns."
863 (cl-assert (directory-name-p dir))
864 (require 'semantic/fw)
865 (grep-compute-defaults)
866 (defvar grep-find-template)
867 (defvar grep-highlight-matches)
868 (let* ((grep-find-template (replace-regexp-in-string "-e " "-E "
869 grep-find-template t t))
870 (grep-highlight-matches nil)
871 (command (xref--rgrep-command (xref--regexp-to-extended regexp)
872 files dir ignores))
873 (orig-buffers (buffer-list))
874 (buf (get-buffer-create " *xref-grep*"))
875 (grep-re (caar grep-regexp-alist))
876 hits)
877 (with-current-buffer buf
878 (erase-buffer)
879 (call-process-shell-command command nil t)
880 (goto-char (point-min))
881 (while (re-search-forward grep-re nil t)
882 (push (cons (string-to-number (match-string 2))
883 (match-string 1))
884 hits)))
885 (unwind-protect
886 (cl-mapcan (lambda (hit) (xref--collect-matches hit regexp))
887 (nreverse hits))
888 ;; TODO: Same as above.
889 (mapc #'kill-buffer
890 (cl-set-difference (buffer-list) orig-buffers)))))
891
892 (defun xref--rgrep-command (regexp files dir ignores)
893 (require 'find-dired) ; for `find-name-arg'
894 (defvar grep-find-template)
895 (defvar find-name-arg)
896 (grep-expand-template
897 grep-find-template
898 regexp
899 (concat (shell-quote-argument "(")
900 " " find-name-arg " "
901 (mapconcat
902 #'shell-quote-argument
903 (split-string files)
904 (concat " -o " find-name-arg " "))
905 " "
906 (shell-quote-argument ")"))
907 dir
908 (concat
909 (shell-quote-argument "(")
910 " -path "
911 (mapconcat
912 (lambda (ignore)
913 (when (string-match-p "/\\'" ignore)
914 (setq ignore (concat ignore "*")))
915 (if (string-match "\\`\\./" ignore)
916 (setq ignore (replace-match dir t t ignore))
917 (unless (string-prefix-p "*" ignore)
918 (setq ignore (concat "*/" ignore))))
919 (shell-quote-argument ignore))
920 ignores
921 " -o -path ")
922 " "
923 (shell-quote-argument ")")
924 " -prune -o ")))
925
926 (defun xref--regexp-to-extended (str)
927 (replace-regexp-in-string
928 ;; FIXME: Add tests. Move to subr.el, make a public function.
929 ;; Maybe error on Emacs-only constructs.
930 "\\(?:\\\\\\\\\\)*\\(?:\\\\[][]\\)?\\(?:\\[.+?\\]\\|\\(\\\\?[(){}|]\\)\\)"
931 (lambda (str)
932 (cond
933 ((not (match-beginning 1))
934 str)
935 ((eq (length (match-string 1 str)) 2)
936 (concat (substring str 0 (match-beginning 1))
937 (substring (match-string 1 str) 1 2)))
938 (t
939 (concat (substring str 0 (match-beginning 1))
940 "\\"
941 (match-string 1 str)))))
942 str t t))
943
944 (defun xref--collect-matches (hit regexp)
945 (pcase-let* ((`(,line . ,file) hit)
946 (buf (or (find-buffer-visiting file)
947 (semantic-find-file-noselect file))))
948 (with-current-buffer buf
949 (save-excursion
950 (goto-char (point-min))
951 (forward-line (1- line))
952 (let ((line-end (line-end-position))
953 (line-beg (line-beginning-position))
954 matches)
955 (syntax-propertize line-end)
956 ;; FIXME: This results in several lines with the same
957 ;; summary. Solve with composite pattern?
958 (while (re-search-forward regexp line-end t)
959 (let* ((beg-column (- (match-beginning 0) line-beg))
960 (end-column (- (match-end 0) line-beg))
961 (loc (xref-make-file-location file line beg-column))
962 (summary (buffer-substring line-beg line-end)))
963 (add-face-text-property beg-column end-column 'highlight
964 t summary)
965 (push (xref-make-match summary loc (- end-column beg-column))
966 matches)))
967 (nreverse matches))))))
968
969 (provide 'xref)
970
971 ;;; xref.el ends here