1 ;; xref.el --- Cross-referencing commands -*-lexical-binding:t-*-
3 ;; Copyright (C) 2014-2016 Free Software Foundation, Inc.
5 ;; This file is part of GNU Emacs.
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.
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.
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/>.
22 ;; NOTE: The xref API is still experimental and can change in major,
23 ;; backward-incompatible ways. Everyone is encouraged to try it, and
24 ;; report to us any problems or use cases we hadn't anticipated, by
25 ;; sending an email to emacs-devel, or `M-x report-emacs-bug'.
27 ;; This file provides a somewhat generic infrastructure for cross
28 ;; referencing commands, in particular "find-definition".
30 ;; Some part of the functionality must be implemented in a language
31 ;; dependent way and that's done by defining an xref backend.
33 ;; That consists of a constructor function, which should return a
34 ;; backend value, and a set of implementations for the generic
37 ;; `xref-backend-identifier-at-point',
38 ;; `xref-backend-identifier-completion-table',
39 ;; `xref-backend-definitions', `xref-backend-references',
40 ;; `xref-backend-apropos', which see.
42 ;; A major mode would normally use `add-hook' to add the backend
43 ;; constructor to `xref-backend-functions'.
45 ;; The last three methods operate with "xref" and "location" values.
47 ;; One would usually call `make-xref' and `xref-make-file-location',
48 ;; `xref-make-buffer-location' or `xref-make-bogus-location' to create
49 ;; them. More generally, a location must be an instance of an EIEIO
50 ;; class inheriting from `xref-location' and implementing
51 ;; `xref-location-group' and `xref-location-marker'.
53 ;; There's a special kind of xrefs we call "match xrefs", which
54 ;; correspond to search results. For these values,
55 ;; `xref-match-length' must be defined, and `xref-location-marker'
56 ;; must return the beginning of the match.
58 ;; Each identifier must be represented as a string. Implementers can
59 ;; use string properties to store additional information about the
60 ;; identifier, but they should keep in mind that values returned from
61 ;; `xref-backend-identifier-completion-table' should still be
62 ;; distinct, because the user can't see the properties when making the
65 ;; See the etags and elisp-mode implementations for full examples.
76 (require 'semantic/symref)) ;; for hit-lines slot
78 (defgroup xref nil "Cross-referencing commands"
85 (defclass xref-location () ()
86 :documentation "A location represents a position in a file or buffer.")
88 (cl-defgeneric xref-location-marker (location)
89 "Return the marker for LOCATION.")
91 (cl-defgeneric xref-location-group (location)
92 "Return a string used to group a set of locations.
93 This is typically the filename.")
95 (cl-defgeneric xref-location-line (_location)
96 "Return the line number corresponding to the location."
99 (cl-defgeneric xref-match-length (_item)
100 "Return the length of the match."
103 ;;;; Commonly needed location classes are defined here:
105 ;; FIXME: might be useful to have an optional "hint" i.e. a string to
106 ;; search for in case the line number is sightly out of date.
107 (defclass xref-file-location (xref-location)
108 ((file :type string :initarg :file)
109 (line :type fixnum :initarg :line :reader xref-location-line)
110 (column :type fixnum :initarg :column :reader xref-file-location-column))
111 :documentation "A file location is a file/line/column triple.
112 Line numbers start from 1 and columns from 0.")
114 (defun xref-make-file-location (file line column)
115 "Create and return a new `xref-file-location'."
116 (make-instance 'xref-file-location :file file :line line :column column))
118 (cl-defmethod xref-location-marker ((l xref-file-location))
119 (with-slots (file line column) l
121 (or (get-file-buffer file)
122 (let ((find-file-suppress-same-file-warnings t))
123 (find-file-noselect file)))
127 (goto-char (point-min))
128 (beginning-of-line line)
129 (forward-char column)
132 (cl-defmethod xref-location-group ((l xref-file-location))
135 (defclass xref-buffer-location (xref-location)
136 ((buffer :type buffer :initarg :buffer)
137 (position :type fixnum :initarg :position)))
139 (defun xref-make-buffer-location (buffer position)
140 "Create and return a new `xref-buffer-location'."
141 (make-instance 'xref-buffer-location :buffer buffer :position position))
143 (cl-defmethod xref-location-marker ((l xref-buffer-location))
144 (with-slots (buffer position) l
145 (let ((m (make-marker)))
146 (move-marker m position buffer))))
148 (cl-defmethod xref-location-group ((l xref-buffer-location))
149 (with-slots (buffer) l
150 (or (buffer-file-name buffer)
151 (format "(buffer %s)" (buffer-name buffer)))))
153 (defclass xref-bogus-location (xref-location)
154 ((message :type string :initarg :message
155 :reader xref-bogus-location-message))
156 :documentation "Bogus locations are sometimes useful to
157 indicate errors, e.g. when we know that a function exists but the
158 actual location is not known.")
160 (defun xref-make-bogus-location (message)
161 "Create and return a new `xref-bogus-location'."
162 (make-instance 'xref-bogus-location :message message))
164 (cl-defmethod xref-location-marker ((l xref-bogus-location))
165 (user-error "%s" (oref l message)))
167 (cl-defmethod xref-location-group ((_ xref-bogus-location)) "(No location)")
172 (defclass xref-item ()
173 ((summary :type string :initarg :summary
174 :reader xref-item-summary
175 :documentation "One line which will be displayed for
176 this item in the output buffer.")
177 (location :initarg :location
178 :reader xref-item-location
179 :documentation "An object describing how to navigate
180 to the reference's target."))
181 :comment "An xref item describes a reference to a location
184 (defun xref-make (summary location)
185 "Create and return a new `xref-item'.
186 SUMMARY is a short string to describe the xref.
187 LOCATION is an `xref-location'."
188 (make-instance 'xref-item :summary summary :location location))
190 (defclass xref-match-item ()
191 ((summary :type string :initarg :summary
192 :reader xref-item-summary)
193 (location :initarg :location
194 :type xref-file-location
195 :reader xref-item-location)
196 (length :initarg :length :reader xref-match-length))
197 :comment "A match xref item describes a search result.")
199 (defun xref-make-match (summary location length)
200 "Create and return a new `xref-match-item'.
201 SUMMARY is a short string to describe the xref.
202 LOCATION is an `xref-location'.
203 LENGTH is the match length, in characters."
204 (make-instance 'xref-match-item :summary summary
205 :location location :length length))
210 (defvar xref-backend-functions nil
211 "Special hook to find the xref backend for the current context.
212 Each function on this hook is called in turn with no arguments,
213 and should return either nil to mean that it is not applicable,
214 or an xref backend, which is a value to be used to dispatch the
217 ;; We make the etags backend the default for now, until something
218 ;; better comes along. Use APPEND so that any `add-hook' calls made
219 ;; before this package is loaded put new items before this one.
220 (add-hook 'xref-backend-functions #'etags--xref-backend t)
223 (defun xref-find-backend ()
224 (run-hook-with-args-until-success 'xref-backend-functions))
226 (cl-defgeneric xref-backend-definitions (backend identifier)
227 "Find definitions of IDENTIFIER.
229 The result must be a list of xref objects. If IDENTIFIER
230 contains sufficient information to determine a unique definition,
231 return only that definition. If there are multiple possible
232 definitions, return all of them. If no definitions can be found,
235 IDENTIFIER can be any string returned by
236 `xref-backend-identifier-at-point', or from the table returned by
237 `xref-backend-identifier-completion-table'.
239 To create an xref object, call `xref-make'.")
241 (cl-defgeneric xref-backend-references (_backend identifier)
242 "Find references of IDENTIFIER.
243 The result must be a list of xref objects. If no references can
244 be found, return nil.
246 The default implementation uses `semantic-symref-tool-alist' to
247 find a search tool; by default, this uses \"find | grep\" in the
248 `project-current' roots."
251 (xref-collect-references identifier dir))
252 (let ((pr (project-current t)))
255 (project-external-roots pr)))))
257 (cl-defgeneric xref-backend-apropos (backend pattern)
258 "Find all symbols that match PATTERN.
259 PATTERN is a regexp")
261 (cl-defgeneric xref-backend-identifier-at-point (_backend)
262 "Return the relevant identifier at point.
264 The return value must be a string or nil. nil means no
265 identifier at point found.
267 If it's hard to determine the identifier precisely (e.g., because
268 it's a method call on unknown type), the implementation can
269 return a simple string (such as symbol at point) marked with a
270 special text property which e.g. `xref-backend-definitions' would
271 recognize and then delegate the work to an external process."
272 (let ((thing (thing-at-point 'symbol)))
273 (and thing (substring-no-properties thing))))
275 (cl-defgeneric xref-backend-identifier-completion-table (backend)
276 "Returns the completion table for identifiers.")
280 (defun xref--alistify (list key test)
281 "Partition the elements of LIST into an alist.
282 KEY extracts the key from an element and TEST is used to compare
286 (let* ((k (funcall key e))
287 (probe (cl-assoc k alist :test test)))
289 (setcdr probe (cons e (cdr probe)))
290 (push (cons k (list e)) alist))))
291 ;; Put them back in order.
292 (cl-loop for (key . value) in (reverse alist)
293 collect (cons key (reverse value)))))
295 (defun xref--insert-propertized (props &rest strings)
296 "Insert STRINGS with text properties PROPS."
297 (let ((start (point)))
298 (apply #'insert strings)
299 (add-text-properties start (point) props)))
301 (defun xref--search-property (property &optional backward)
302 "Search the next text range where text property PROPERTY is non-nil.
303 Return the value of PROPERTY. If BACKWARD is non-nil, search
305 (let ((next (if backward
306 #'previous-single-char-property-change
307 #'next-single-char-property-change))
311 (goto-char (funcall next (point) property))
312 (not (or (setq value (get-text-property (point) property))
316 (t (goto-char start) nil))))
319 ;;; Marker stack (M-. pushes, M-, pops)
321 (defcustom xref-marker-ring-length 16
322 "Length of the xref marker ring."
325 (defcustom xref-prompt-for-identifier '(not xref-find-definitions
326 xref-find-definitions-other-window
327 xref-find-definitions-other-frame)
328 "When t, always prompt for the identifier name.
330 When nil, prompt only when there's no value at point we can use,
331 or when the command has been called with the prefix argument.
333 Otherwise, it's a list of xref commands which will prompt
334 anyway (the value at point, if any, will be used as the default).
336 If the list starts with `not', the meaning of the rest of the
337 elements is negated."
338 :type '(choice (const :tag "always" t)
339 (const :tag "auto" nil)
340 (set :menu-tag "command specific" :tag "commands"
342 (const :tag "Except" not)
343 (repeat :inline t (symbol :tag "command")))))
345 (defcustom xref-after-jump-hook '(recenter
346 xref-pulse-momentarily)
347 "Functions called after jumping to an xref."
350 (defcustom xref-after-return-hook '(xref-pulse-momentarily)
351 "Functions called after returning to a pre-jump location."
354 (defvar xref--marker-ring (make-ring xref-marker-ring-length)
355 "Ring of markers to implement the marker stack.")
357 (defun xref-push-marker-stack (&optional m)
358 "Add point M (defaults to `point-marker') to the marker stack."
359 (ring-insert xref--marker-ring (or m (point-marker))))
362 (defun xref-pop-marker-stack ()
363 "Pop back to where \\[xref-find-definitions] was last invoked."
365 (let ((ring xref--marker-ring))
366 (when (ring-empty-p ring)
367 (user-error "Marker stack is empty"))
368 (let ((marker (ring-remove ring 0)))
369 (switch-to-buffer (or (marker-buffer marker)
370 (user-error "The marked buffer has been deleted")))
371 (goto-char (marker-position marker))
372 (set-marker marker nil nil)
373 (run-hooks 'xref-after-return-hook))))
375 (defvar xref--current-item nil)
377 (defun xref-pulse-momentarily ()
378 (pcase-let ((`(,beg . ,end)
381 (let ((length (xref-match-length xref--current-item)))
382 (and length (cons (point) (+ (point) length))))
383 (back-to-indentation)
385 (cons (line-beginning-position) (1+ (point)))
386 (cons (point) (line-end-position)))))))
387 (pulse-momentary-highlight-region beg end 'next-error)))
389 ;; etags.el needs this
390 (defun xref-clear-marker-stack ()
391 "Discard all markers from the marker stack."
392 (let ((ring xref--marker-ring))
393 (while (not (ring-empty-p ring))
394 (let ((marker (ring-remove ring)))
395 (set-marker marker nil nil)))))
398 (defun xref-marker-stack-empty-p ()
399 "Return t if the marker stack is empty; nil otherwise."
400 (ring-empty-p xref--marker-ring))
404 (defun xref--goto-char (pos)
406 ((and (<= (point-min) pos) (<= pos (point-max))))
407 (widen-automatically (widen))
408 (t (user-error "Position is outside accessible part of buffer")))
411 (defun xref--goto-location (location)
412 "Set buffer and point according to xref-location LOCATION."
413 (let ((marker (xref-location-marker location)))
414 (set-buffer (marker-buffer marker))
415 (xref--goto-char marker)))
417 (defun xref--pop-to-location (item &optional window)
418 "Go to the location of ITEM and display the buffer.
419 WINDOW controls how the buffer is displayed:
420 nil -- switch-to-buffer
421 `window' -- pop-to-buffer (other window)
422 `frame' -- pop-to-buffer (other frame)"
423 (let* ((marker (save-excursion
424 (xref-location-marker (xref-item-location item))))
425 (buf (marker-buffer marker)))
427 ((nil) (switch-to-buffer buf))
428 (window (pop-to-buffer buf t))
429 (frame (let ((pop-up-frames t)) (pop-to-buffer buf t))))
430 (xref--goto-char marker))
431 (let ((xref--current-item item))
432 (run-hooks 'xref-after-jump-hook)))
435 ;;; XREF buffer (part of the UI)
437 ;; The xref buffer is used to display a set of xrefs.
439 (defvar-local xref--display-history nil
440 "List of pairs (BUFFER . WINDOW), for temporarily displayed buffers.")
442 (defun xref--save-to-history (buf win)
443 (let ((restore (window-parameter win 'quit-restore)))
444 ;; Save the new entry if the window displayed another buffer
446 (when (and restore (not (eq (car restore) 'same)))
447 (push (cons buf win) xref--display-history))))
449 (defun xref--display-position (pos other-window buf)
450 ;; Show the location, but don't hijack focus.
451 (let ((xref-buf (current-buffer)))
452 (with-selected-window (display-buffer buf other-window)
453 (xref--goto-char pos)
454 (run-hooks 'xref-after-jump-hook)
455 (let ((buf (current-buffer))
456 (win (selected-window)))
457 (with-current-buffer xref-buf
458 (setq-local other-window-scroll-buffer buf)
459 (xref--save-to-history buf win))))))
461 (defun xref--show-location (location)
463 (let* ((marker (xref-location-marker location))
464 (buf (marker-buffer marker)))
465 (xref--display-position marker t buf))
466 (user-error (message (error-message-string err)))))
468 (defun xref-show-location-at-point ()
469 "Display the source of xref at point in the other window, if any."
471 (let* ((xref (xref--item-at-point))
472 (xref--current-item xref))
474 (xref--show-location (xref-item-location xref)))))
476 (defun xref-next-line ()
477 "Move to the next xref and display its source in the other window."
479 (xref--search-property 'xref-item)
480 (xref-show-location-at-point))
482 (defun xref-prev-line ()
483 "Move to the previous xref and display its source in the other window."
485 (xref--search-property 'xref-item t)
486 (xref-show-location-at-point))
488 (defun xref--item-at-point ()
490 (back-to-indentation)
491 (get-text-property (point) 'xref-item)))
493 (defvar-local xref--window nil
494 "ACTION argument to call `display-buffer' with.")
496 (defun xref-goto-xref ()
497 "Jump to the xref on the current line and bury the xref buffer."
499 (let ((xref (or (xref--item-at-point)
500 (user-error "No reference at point")))
501 (window xref--window))
503 (xref--pop-to-location xref window)))
505 (defun xref-query-replace-in-results (from to)
506 "Perform interactive replacement of FROM with TO in all displayed xrefs.
508 This command interactively replaces FROM with TO in the names of the
509 references displayed in the current *xref* buffer."
511 (let ((fr (read-regexp "Xref query-replace (regexp)" ".*")))
513 (read-regexp (format "Xref query-replace (regexp) %s with: " fr)))))
514 (let ((reporter (make-progress-reporter (format "Saving search results...")
515 0 (line-number-at-pos (point-max))))
521 (goto-char (point-min))
522 ;; TODO: This list should be computed on-demand instead.
523 ;; As long as the UI just iterates through matches one by
524 ;; one, there's no need to compute them all in advance.
525 ;; Then we can throw away the reporter.
526 (while (setq item (xref--search-property 'xref-item))
527 (when (xref-match-length item)
529 (let* ((loc (xref-item-location item))
530 (beg (xref-location-marker loc))
531 (end (move-marker (make-marker)
532 (+ beg (xref-match-length item))
533 (marker-buffer beg))))
534 ;; Perform sanity check first.
535 (xref--goto-location loc)
536 ;; FIXME: The check should probably be a generic
537 ;; function, instead of the assumption that all
538 ;; matches contain the full line as summary.
539 ;; TODO: Offer to re-scan otherwise.
540 (unless (equal (buffer-substring-no-properties
541 (line-beginning-position)
543 (xref-item-summary item))
544 (user-error "Search results out of date"))
545 (progress-reporter-update reporter (cl-incf counter))
546 (push (cons beg end) pairs)))))
547 (setq pairs (nreverse pairs)))
548 (unless pairs (user-error "No suitable matches here"))
549 (progress-reporter-done reporter)
550 (xref--query-replace-1 from to pairs))
552 (move-marker (car pair) nil)
553 (move-marker (cdr pair) nil)))))
555 ;; FIXME: Write a nicer UI.
556 (defun xref--query-replace-1 (from to pairs)
557 (let* ((query-replace-lazy-highlight nil)
558 current-beg current-end current-buf
559 ;; Counteract the "do the next match now" hack in
560 ;; `perform-replace'. And still, it'll report that those
561 ;; matches were "filtered out" at the end.
562 (isearch-filter-predicate
565 (eq (current-buffer) current-buf)
567 (<= end current-end))))
568 (replace-re-search-function
569 (lambda (from &optional _bound noerror)
571 (while (and (not found) pairs)
572 (setq pair (pop pairs)
573 current-beg (car pair)
574 current-end (cdr pair)
575 current-buf (marker-buffer current-beg))
576 (pop-to-buffer current-buf)
577 (goto-char current-beg)
578 (when (re-search-forward from current-end noerror)
581 ;; FIXME: Despite this being a multi-buffer replacement, `N'
582 ;; doesn't work, because we're not using
583 ;; `multi-query-replace-map', and it would expect the below
584 ;; function to be called once per buffer.
585 (perform-replace from to t t nil)))
587 (defvar xref--xref-buffer-mode-map
588 (let ((map (make-sparse-keymap)))
589 (define-key map [remap quit-window] #'xref-quit)
590 (define-key map (kbd "n") #'xref-next-line)
591 (define-key map (kbd "p") #'xref-prev-line)
592 (define-key map (kbd "r") #'xref-query-replace-in-results)
593 (define-key map (kbd "RET") #'xref-goto-xref)
594 (define-key map (kbd "C-o") #'xref-show-location-at-point)
595 ;; suggested by Johan Claesson "to further reduce finger movement":
596 (define-key map (kbd ".") #'xref-next-line)
597 (define-key map (kbd ",") #'xref-prev-line)
600 (define-derived-mode xref--xref-buffer-mode special-mode "XREF"
601 "Mode for displaying cross-references."
602 (setq buffer-read-only t)
603 ;; FIXME: http://debbugs.gnu.org/20489
604 ;; (setq next-error-function #'xref--next-error-function)
605 ;; (setq next-error-last-buffer (current-buffer))
608 (defun xref--next-error-function (n reset?)
610 (goto-char (point-min)))
611 (let ((backward (< n 0))
615 (setq xref (xref--search-property 'xref-item backward)))
617 (xref--pop-to-location xref))
619 (error "No %s xref" (if backward "previous" "next"))))))
621 (defun xref-quit (&optional kill)
622 "Bury temporarily displayed buffers, then quit the current window.
624 If KILL is non-nil, also kill the current buffer.
626 The buffers that the user has otherwise interacted with in the
627 meantime are preserved."
629 (let ((window (selected-window))
630 (history xref--display-history))
631 (setq xref--display-history nil)
632 (pcase-dolist (`(,buf . ,win) history)
633 (when (and (window-live-p win)
634 (eq buf (window-buffer win)))
635 (quit-window nil win)))
636 (quit-window kill window)))
638 (defconst xref-buffer-name "*xref*"
639 "The name of the buffer to show xrefs.")
641 (defvar xref--button-map
642 (let ((map (make-sparse-keymap)))
643 (define-key map [(control ?m)] #'xref-goto-xref)
644 (define-key map [mouse-1] #'xref-goto-xref)
645 (define-key map [mouse-2] #'xref--mouse-2)
648 (defun xref--mouse-2 (event)
649 "Move point to the button and show the xref definition."
651 (mouse-set-point event)
653 (xref--search-property 'xref-item)
654 (xref-show-location-at-point))
656 (defun xref--insert-xrefs (xref-alist)
657 "Insert XREF-ALIST in the current-buffer.
658 XREF-ALIST is of the form ((GROUP . (XREF ...)) ...), where
659 GROUP is a string for decoration purposes and XREF is an
661 (require 'compile) ; For the compilation faces.
662 (cl-loop for ((group . xrefs) . more1) on xref-alist
664 (cl-loop for xref in xrefs
665 maximize (let ((line (xref-location-line
666 (oref xref location))))
667 (length (and line (format "%d" line)))))
668 for line-format = (and max-line-width
669 (format "%%%dd: " max-line-width))
671 (xref--insert-propertized '(face compilation-info) group "\n")
672 (cl-loop for (xref . more2) on xrefs do
673 (with-slots (summary location) xref
674 (let* ((line (xref-location-line location))
677 (propertize (format line-format line)
678 'face 'compilation-line-number)
680 (xref--insert-propertized
681 (list 'xref-item xref
682 ;; 'face 'font-lock-keyword-face
683 'mouse-face 'highlight
684 'keymap xref--button-map
686 (concat "mouse-2: display in another window, "
687 "RET or mouse-1: follow reference"))
691 (defun xref--analyze (xrefs)
692 "Find common filenames in XREFS.
693 Return an alist of the form ((FILENAME . (XREF ...)) ...)."
694 (xref--alistify xrefs
696 (xref-location-group (xref-item-location x)))
699 (defun xref--show-xref-buffer (xrefs alist)
700 (let ((xref-alist (xref--analyze xrefs)))
701 (with-current-buffer (get-buffer-create xref-buffer-name)
702 (let ((inhibit-read-only t))
704 (xref--insert-xrefs xref-alist)
705 (xref--xref-buffer-mode)
706 (pop-to-buffer (current-buffer))
707 (goto-char (point-min))
708 (setq xref--window (assoc-default 'window alist))
712 ;; This part of the UI seems fairly uncontroversial: it reads the
713 ;; identifier and deals with the single definition case.
714 ;; (FIXME: do we really want this case to be handled like that in
715 ;; "find references" and "find regexp searches"?)
717 ;; The controversial multiple definitions case is handed off to
718 ;; xref-show-xrefs-function.
720 (defvar xref-show-xrefs-function 'xref--show-xref-buffer
721 "Function to display a list of xrefs.")
723 (defvar xref--read-identifier-history nil)
725 (defvar xref--read-pattern-history nil)
727 (defun xref--show-xrefs (xrefs window &optional always-show-list)
729 ((and (not (cdr xrefs)) (not always-show-list))
730 (xref-push-marker-stack)
731 (xref--pop-to-location (car xrefs) window))
733 (xref-push-marker-stack)
734 (funcall xref-show-xrefs-function xrefs
735 `((window . ,window))))))
737 (defun xref--prompt-p (command)
738 (or (eq xref-prompt-for-identifier t)
739 (if (eq (car xref-prompt-for-identifier) 'not)
740 (not (memq command (cdr xref-prompt-for-identifier)))
741 (memq command xref-prompt-for-identifier))))
743 (defun xref--read-identifier (prompt)
744 "Return the identifier at point or read it from the minibuffer."
745 (let* ((backend (xref-find-backend))
746 (id (xref-backend-identifier-at-point backend)))
747 (cond ((or current-prefix-arg
749 (xref--prompt-p this-command))
750 (completing-read (if id
751 (format "%s (default %s): "
752 (substring prompt 0 (string-match
756 (xref-backend-identifier-completion-table backend)
758 'xref--read-identifier-history id))
764 (defun xref--find-xrefs (input kind arg window)
765 (let ((xrefs (funcall (intern (format "xref-backend-%s" kind))
769 (user-error "No %s found for: %s" (symbol-name kind) input))
770 (xref--show-xrefs xrefs window)))
772 (defun xref--find-definitions (id window)
773 (xref--find-xrefs id 'definitions id window))
776 (defun xref-find-definitions (identifier)
777 "Find the definition of the identifier at point.
778 With prefix argument or when there's no identifier at point,
781 If sufficient information is available to determine a unique
782 definition for IDENTIFIER, display it in the selected window.
783 Otherwise, display the list of the possible definitions in a
784 buffer where the user can select from the list."
785 (interactive (list (xref--read-identifier "Find definitions of: ")))
786 (xref--find-definitions identifier nil))
789 (defun xref-find-definitions-other-window (identifier)
790 "Like `xref-find-definitions' but switch to the other window."
791 (interactive (list (xref--read-identifier "Find definitions of: ")))
792 (xref--find-definitions identifier 'window))
795 (defun xref-find-definitions-other-frame (identifier)
796 "Like `xref-find-definitions' but switch to the other frame."
797 (interactive (list (xref--read-identifier "Find definitions of: ")))
798 (xref--find-definitions identifier 'frame))
801 (defun xref-find-references (identifier)
802 "Find references to the identifier at point.
803 With prefix argument, prompt for the identifier."
804 (interactive (list (xref--read-identifier "Find references of: ")))
805 (xref--find-xrefs identifier 'references identifier nil))
807 (declare-function apropos-parse-pattern "apropos" (pattern))
810 (defun xref-find-apropos (pattern)
811 "Find all meaningful symbols that match PATTERN.
812 The argument has the same meaning as in `apropos'."
813 (interactive (list (read-string
814 "Search for pattern (word list or regexp): "
815 nil 'xref--read-pattern-history)))
817 (xref--find-xrefs pattern 'apropos
818 (apropos-parse-pattern
819 (if (string-equal (regexp-quote pattern) pattern)
821 (or (split-string pattern "[ \t]+" t)
822 (user-error "No word list given"))
829 ;;;###autoload (define-key esc-map "." #'xref-find-definitions)
830 ;;;###autoload (define-key esc-map "," #'xref-pop-marker-stack)
831 ;;;###autoload (define-key esc-map "?" #'xref-find-references)
832 ;;;###autoload (define-key esc-map [?\C-.] #'xref-find-apropos)
833 ;;;###autoload (define-key ctl-x-4-map "." #'xref-find-definitions-other-window)
834 ;;;###autoload (define-key ctl-x-5-map "." #'xref-find-definitions-other-frame)
839 (defvar xref-etags-mode--saved nil)
841 (define-minor-mode xref-etags-mode
842 "Minor mode to make xref use etags again.
844 Certain major modes install their own mechanisms for listing
845 identifiers and navigation. Turn this on to undo those settings
850 (setq xref-etags-mode--saved xref-backend-functions)
851 (kill-local-variable 'xref-backend-functions))
852 (setq-local xref-backend-functions xref-etags-mode--saved)))
854 (declare-function semantic-symref-find-references-by-name "semantic/symref")
855 (declare-function semantic-find-file-noselect "semantic/fw")
856 (declare-function grep-expand-template "grep")
858 (defun xref-collect-references (symbol dir)
859 "Collect references to SYMBOL inside DIR.
860 This function uses the Semantic Symbol Reference API, see
861 `semantic-symref-find-references-by-name' for details on which
862 tools are used, and when."
863 (cl-assert (directory-name-p dir))
864 (require 'semantic/symref)
865 (defvar semantic-symref-tool)
867 ;; Some symref backends use `ede-project-root-directory' as the root
868 ;; directory for the search, rather than `default-directory'. Since
869 ;; the caller has specified `dir', we bind `ede-minor-mode' to nil
870 ;; to force the backend to use `default-directory'.
871 (let* ((ede-minor-mode nil)
872 (default-directory dir)
873 (semantic-symref-tool 'detect)
874 (res (semantic-symref-find-references-by-name symbol 'subdirs))
875 (hits (and res (oref res hit-lines)))
876 (orig-buffers (buffer-list)))
878 (cl-mapcan (lambda (hit) (xref--collect-matches
879 hit (format "\\_<%s\\_>" (regexp-quote symbol))))
881 ;; TODO: Implement "lightweight" buffer visiting, so that we
882 ;; don't have to kill them.
884 (cl-set-difference (buffer-list) orig-buffers)))))
887 (defun xref-collect-matches (regexp files dir ignores)
888 "Collect matches for REGEXP inside FILES in DIR.
889 FILES is a string with glob patterns separated by spaces.
890 IGNORES is a list of glob patterns."
891 ;; DIR can also be a regular file for now; let's not advertise that.
892 (require 'semantic/fw)
893 (grep-compute-defaults)
894 (defvar grep-find-template)
895 (defvar grep-highlight-matches)
896 (let* ((grep-find-template (replace-regexp-in-string "-e " "-E "
897 grep-find-template t t))
898 (grep-highlight-matches nil)
899 (command (xref--rgrep-command (xref--regexp-to-extended regexp)
901 (expand-file-name dir)
903 (orig-buffers (buffer-list))
904 (buf (get-buffer-create " *xref-grep*"))
905 (grep-re (caar grep-regexp-alist))
909 (with-current-buffer buf
911 (call-process-shell-command command nil t)
912 (goto-char (point-min))
913 (while (re-search-forward grep-re nil t)
914 (push (cons (string-to-number (match-string 2))
917 (setq reporter (make-progress-reporter
918 (format "Collecting search results...")
921 (cl-mapcan (lambda (hit)
923 (progress-reporter-update reporter counter)
925 (xref--collect-matches hit regexp))
927 (progress-reporter-done reporter)
928 ;; TODO: Same as above.
930 (cl-set-difference (buffer-list) orig-buffers)))))
932 (defun xref--rgrep-command (regexp files dir ignores)
933 (require 'find-dired) ; for `find-name-arg'
934 (defvar grep-find-template)
935 (defvar find-name-arg)
936 (grep-expand-template
939 (concat (shell-quote-argument "(")
940 " " find-name-arg " "
942 #'shell-quote-argument
944 (concat " -o " find-name-arg " "))
946 (shell-quote-argument ")"))
948 (xref--find-ignores-arguments ignores dir)))
950 (defun xref--find-ignores-arguments (ignores dir)
951 ;; `shell-quote-argument' quotes the tilde as well.
952 (cl-assert (not (string-match-p "\\`~" dir)))
955 (shell-quote-argument "(")
959 (when (string-match-p "/\\'" ignore)
960 (setq ignore (concat ignore "*")))
961 (if (string-match "\\`\\./" ignore)
962 (setq ignore (replace-match dir t t ignore))
963 (unless (string-prefix-p "*" ignore)
964 (setq ignore (concat "*/" ignore))))
965 (shell-quote-argument ignore))
969 (shell-quote-argument ")")
972 (defun xref--regexp-to-extended (str)
973 (replace-regexp-in-string
974 ;; FIXME: Add tests. Move to subr.el, make a public function.
975 ;; Maybe error on Emacs-only constructs.
976 "\\(?:\\\\\\\\\\)*\\(?:\\\\[][]\\)?\\(?:\\[.+?\\]\\|\\(\\\\?[(){}|]\\)\\)"
979 ((not (match-beginning 1))
981 ((eq (length (match-string 1 str)) 2)
982 (concat (substring str 0 (match-beginning 1))
983 (substring (match-string 1 str) 1 2)))
985 (concat (substring str 0 (match-beginning 1))
987 (match-string 1 str)))))
990 (defun xref--collect-matches (hit regexp)
991 (pcase-let* ((`(,line . ,file) hit)
992 (buf (or (find-buffer-visiting file)
993 (semantic-find-file-noselect file))))
994 (with-current-buffer buf
996 (goto-char (point-min))
997 (forward-line (1- line))
998 (let ((line-end (line-end-position))
999 (line-beg (line-beginning-position))
1001 (syntax-propertize line-end)
1002 ;; FIXME: This results in several lines with the same
1003 ;; summary. Solve with composite pattern?
1004 (while (re-search-forward regexp line-end t)
1005 (let* ((beg-column (- (match-beginning 0) line-beg))
1006 (end-column (- (match-end 0) line-beg))
1007 (loc (xref-make-file-location file line beg-column))
1008 (summary (buffer-substring line-beg line-end)))
1009 (add-face-text-property beg-column end-column 'highlight
1011 (push (xref-make-match summary loc (- end-column beg-column))
1013 (nreverse matches))))))
1017 ;;; xref.el ends here