1 ;; xref.el --- Cross-referencing commands -*-lexical-binding:t-*-
3 ;; Copyright (C) 2014-2015 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 ;; This file provides a somewhat generic infrastructure for cross
23 ;; referencing commands, in particular "find-definition".
25 ;; Some part of the functionality must be implemented in a language
26 ;; dependent way and that's done by defining an xref backend.
28 ;; That consists of a constructor function, which should return a
29 ;; backend value, and a set of implementations for the generic
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.
37 ;; A major mode would normally use `add-hook' to add the backend
38 ;; constructor to `xref-backend-functions'.
40 ;; The last three methods operate with "xref" and "location" values.
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'.
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.
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
60 ;; See the etags and elisp-mode implementations for full examples.
71 (require 'semantic/symref)) ;; for hit-lines slot
73 (defgroup xref nil "Cross-referencing commands"
79 (defclass xref-location () ()
80 :documentation "A location represents a position in a file or buffer.")
82 (cl-defgeneric xref-location-marker (location)
83 "Return the marker for LOCATION.")
85 (cl-defgeneric xref-location-group (location)
86 "Return a string used to group a set of locations.
87 This is typically the filename.")
89 (cl-defgeneric xref-location-line (_location)
90 "Return the line number corresponding to the location."
93 (cl-defgeneric xref-match-length (_item)
94 "Return the length of the match."
97 ;;;; Commonly needed location classes are defined here:
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.")
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))
112 (cl-defmethod xref-location-marker ((l xref-file-location))
113 (with-slots (file line column) l
115 (or (get-file-buffer file)
116 (let ((find-file-suppress-same-file-warnings t))
117 (find-file-noselect file)))
121 (goto-char (point-min))
122 (beginning-of-line line)
123 (forward-char column)
126 (cl-defmethod xref-location-group ((l xref-file-location))
129 (defclass xref-buffer-location (xref-location)
130 ((buffer :type buffer :initarg :buffer)
131 (position :type fixnum :initarg :position)))
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))
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))))
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)))))
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.")
154 (defun xref-make-bogus-location (message)
155 "Create and return a new `xref-bogus-location'."
156 (make-instance 'xref-bogus-location :message message))
158 (cl-defmethod xref-location-marker ((l xref-bogus-location))
159 (user-error "%s" (oref l message)))
161 (cl-defmethod xref-location-group ((_ xref-bogus-location)) "(No location)")
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
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))
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.")
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))
204 (defvar xref-backend-functions nil
205 "Special hook to find the xref backend for the current context.
206 Each functions on this hook is called in turn with no arguments
207 and should return either nil to mean that it is not applicable,
208 or an xref backend, which is a value to be used to dispatch the
211 ;; We make the etags backend the default for now, until something
212 ;; better comes along. Use APPEND so that any `add-hook' calls made
213 ;; before this package is loaded put new items before this one.
214 (add-hook 'xref-backend-functions #'etags--xref-backend t)
217 (defun xref-find-backend ()
218 (run-hook-with-args-until-success 'xref-backend-functions))
220 (cl-defgeneric xref-backend-definitions (backend identifier)
221 "Find definitions of IDENTIFIER.
223 The result must be a list of xref objects. If IDENTIFIER
224 contains sufficient information to determine a unique definition,
225 return only that definition. If there are multiple possible
226 definitions, return all of them. If no definitions can be found,
229 IDENTIFIER can be any string returned by
230 `xref-backend-identifier-at-point', or from the table returned by
231 `xref-backend-identifier-completion-table'.
233 To create an xref object, call `xref-make'.")
235 (cl-defgeneric xref-backend-references (_backend identifier)
236 "Find references of IDENTIFIER.
237 The result must be a list of xref objects. If no references can
238 be found, return nil.
240 The default implementation uses `semantic-symref-tool-alist' to
241 find a search tool; by default, this uses \"find | grep\" in the
242 `project-current' roots."
245 (xref-collect-references identifier dir))
246 (let ((pr (project-current t)))
249 (project-external-roots pr)))))
251 (cl-defgeneric xref-backend-apropos (backend pattern)
252 "Find all symbols that match PATTERN.
253 PATTERN is a regexp")
255 (cl-defgeneric xref-backend-identifier-at-point (_backend)
256 "Return the relevant identifier at point.
258 The return value must be a string or nil. nil means no
259 identifier at point found.
261 If it's hard to determine the identifier precisely (e.g., because
262 it's a method call on unknown type), the implementation can
263 return a simple string (such as symbol at point) marked with a
264 special text property which e.g. `xref-backend-definitions' would
265 recognize and then delegate the work to an external process."
266 (let ((thing (thing-at-point 'symbol)))
267 (and thing (substring-no-properties thing))))
269 (cl-defgeneric xref-backend-identifier-completion-table (backend)
270 "Returns the completion table for identifiers.")
274 (defun xref--alistify (list key test)
275 "Partition the elements of LIST into an alist.
276 KEY extracts the key from an element and TEST is used to compare
280 (let* ((k (funcall key e))
281 (probe (cl-assoc k alist :test test)))
283 (setcdr probe (cons e (cdr probe)))
284 (push (cons k (list e)) alist))))
285 ;; Put them back in order.
286 (cl-loop for (key . value) in (reverse alist)
287 collect (cons key (reverse value)))))
289 (defun xref--insert-propertized (props &rest strings)
290 "Insert STRINGS with text properties PROPS."
291 (let ((start (point)))
292 (apply #'insert strings)
293 (add-text-properties start (point) props)))
295 (defun xref--search-property (property &optional backward)
296 "Search the next text range where text property PROPERTY is non-nil.
297 Return the value of PROPERTY. If BACKWARD is non-nil, search
299 (let ((next (if backward
300 #'previous-single-char-property-change
301 #'next-single-char-property-change))
305 (goto-char (funcall next (point) property))
306 (not (or (setq value (get-text-property (point) property))
310 (t (goto-char start) nil))))
313 ;;; Marker stack (M-. pushes, M-, pops)
315 (defcustom xref-marker-ring-length 16
316 "Length of the xref marker ring."
319 (defcustom xref-prompt-for-identifier '(not xref-find-definitions
320 xref-find-definitions-other-window
321 xref-find-definitions-other-frame)
322 "When t, always prompt for the identifier name.
324 When nil, prompt only when there's no value at point we can use,
325 or when the command has been called with the prefix argument.
327 Otherwise, it's a list of xref commands which will prompt
328 anyway (the value at point, if any, will be used as the default).
330 If the list starts with `not', the meaning of the rest of the
331 elements is negated."
332 :type '(choice (const :tag "always" t)
333 (const :tag "auto" nil)
334 (set :menu-tag "command specific" :tag "commands"
336 (const :tag "Except" not)
337 (repeat :inline t (symbol :tag "command")))))
339 (defcustom xref-after-jump-hook '(recenter
340 xref-pulse-momentarily)
341 "Functions called after jumping to an xref."
344 (defcustom xref-after-return-hook '(xref-pulse-momentarily)
345 "Functions called after returning to a pre-jump location."
348 (defvar xref--marker-ring (make-ring xref-marker-ring-length)
349 "Ring of markers to implement the marker stack.")
351 (defun xref-push-marker-stack (&optional m)
352 "Add point M (defaults to `point-marker') to the marker stack."
353 (ring-insert xref--marker-ring (or m (point-marker))))
356 (defun xref-pop-marker-stack ()
357 "Pop back to where \\[xref-find-definitions] was last invoked."
359 (let ((ring xref--marker-ring))
360 (when (ring-empty-p ring)
361 (user-error "Marker stack is empty"))
362 (let ((marker (ring-remove ring 0)))
363 (switch-to-buffer (or (marker-buffer marker)
364 (user-error "The marked buffer has been deleted")))
365 (goto-char (marker-position marker))
366 (set-marker marker nil nil)
367 (run-hooks 'xref-after-return-hook))))
369 (defvar xref--current-item nil)
371 (defun xref-pulse-momentarily ()
372 (pcase-let ((`(,beg . ,end)
375 (let ((length (xref-match-length xref--current-item)))
376 (and length (cons (point) (+ (point) length))))
377 (back-to-indentation)
379 (cons (line-beginning-position) (1+ (point)))
380 (cons (point) (line-end-position)))))))
381 (pulse-momentary-highlight-region beg end 'next-error)))
383 ;; etags.el needs this
384 (defun xref-clear-marker-stack ()
385 "Discard all markers from the marker stack."
386 (let ((ring xref--marker-ring))
387 (while (not (ring-empty-p ring))
388 (let ((marker (ring-remove ring)))
389 (set-marker marker nil nil)))))
392 (defun xref-marker-stack-empty-p ()
393 "Return t if the marker stack is empty; nil otherwise."
394 (ring-empty-p xref--marker-ring))
398 (defun xref--goto-char (pos)
400 ((and (<= (point-min) pos) (<= pos (point-max))))
401 (widen-automatically (widen))
402 (t (user-error "Position is outside accessible part of buffer")))
405 (defun xref--goto-location (location)
406 "Set buffer and point according to xref-location LOCATION."
407 (let ((marker (xref-location-marker location)))
408 (set-buffer (marker-buffer marker))
409 (xref--goto-char marker)))
411 (defun xref--pop-to-location (item &optional window)
412 "Go to the location of ITEM and display the buffer.
413 WINDOW controls how the buffer is displayed:
414 nil -- switch-to-buffer
415 `window' -- pop-to-buffer (other window)
416 `frame' -- pop-to-buffer (other frame)"
417 (let* ((marker (save-excursion
418 (xref-location-marker (xref-item-location item))))
419 (buf (marker-buffer marker)))
421 ((nil) (switch-to-buffer buf))
422 (window (pop-to-buffer buf t))
423 (frame (let ((pop-up-frames t)) (pop-to-buffer buf t))))
424 (xref--goto-char marker))
425 (let ((xref--current-item item))
426 (run-hooks 'xref-after-jump-hook)))
429 ;;; XREF buffer (part of the UI)
431 ;; The xref buffer is used to display a set of xrefs.
433 (defvar-local xref--display-history nil
434 "List of pairs (BUFFER . WINDOW), for temporarily displayed buffers.")
436 (defun xref--save-to-history (buf win)
437 (let ((restore (window-parameter win 'quit-restore)))
438 ;; Save the new entry if the window displayed another buffer
440 (when (and restore (not (eq (car restore) 'same)))
441 (push (cons buf win) xref--display-history))))
443 (defun xref--display-position (pos other-window buf)
444 ;; Show the location, but don't hijack focus.
445 (let ((xref-buf (current-buffer)))
446 (with-selected-window (display-buffer buf other-window)
447 (xref--goto-char pos)
448 (run-hooks 'xref-after-jump-hook)
449 (let ((buf (current-buffer))
450 (win (selected-window)))
451 (with-current-buffer xref-buf
452 (setq-local other-window-scroll-buffer buf)
453 (xref--save-to-history buf win))))))
455 (defun xref--show-location (location)
457 (let* ((marker (xref-location-marker location))
458 (buf (marker-buffer marker)))
459 (xref--display-position marker t buf))
460 (user-error (message (error-message-string err)))))
462 (defun xref-show-location-at-point ()
463 "Display the source of xref at point in the other window, if any."
465 (let* ((xref (xref--item-at-point))
466 (xref--current-item xref))
468 (xref--show-location (xref-item-location xref)))))
470 (defun xref-next-line ()
471 "Move to the next xref and display its source in the other window."
473 (xref--search-property 'xref-item)
474 (xref-show-location-at-point))
476 (defun xref-prev-line ()
477 "Move to the previous xref and display its source in the other window."
479 (xref--search-property 'xref-item t)
480 (xref-show-location-at-point))
482 (defun xref--item-at-point ()
484 (back-to-indentation)
485 (get-text-property (point) 'xref-item)))
487 (defvar-local xref--window nil
488 "ACTION argument to call `display-buffer' with.")
490 (defun xref-goto-xref ()
491 "Jump to the xref on the current line and bury the xref buffer."
493 (let ((xref (or (xref--item-at-point)
494 (user-error "No reference at point")))
495 (window xref--window))
497 (xref--pop-to-location xref window)))
499 (defun xref-query-replace (from to)
500 "Perform interactive replacement in all current matches."
502 (list (read-regexp "Query replace regexp in matches" ".*")
503 (read-regexp "Replace with: ")))
508 (goto-char (point-min))
509 (while (setq item (xref--search-property 'xref-item))
510 (when (xref-match-length item)
512 (let* ((loc (xref-item-location item))
513 (beg (xref-location-marker loc))
514 (end (move-marker (make-marker)
515 (+ beg (xref-match-length item))
516 (marker-buffer beg))))
517 ;; Perform sanity check first.
518 (xref--goto-location loc)
519 ;; FIXME: The check should probably be a generic
520 ;; function, instead of the assumption that all
521 ;; matches contain the full line as summary.
522 ;; TODO: Offer to re-scan otherwise.
523 (unless (equal (buffer-substring-no-properties
524 (line-beginning-position)
526 (xref-item-summary item))
527 (user-error "Search results out of date"))
528 (push (cons beg end) pairs)))))
529 (setq pairs (nreverse pairs)))
530 (unless pairs (user-error "No suitable matches here"))
531 (xref--query-replace-1 from to pairs))
533 (move-marker (car pair) nil)
534 (move-marker (cdr pair) nil)))))
536 ;; FIXME: Write a nicer UI.
537 (defun xref--query-replace-1 (from to pairs)
538 (let* ((query-replace-lazy-highlight nil)
539 current-beg current-end current-buf
540 ;; Counteract the "do the next match now" hack in
541 ;; `perform-replace'. And still, it'll report that those
542 ;; matches were "filtered out" at the end.
543 (isearch-filter-predicate
546 (eq (current-buffer) current-buf)
548 (<= end current-end))))
549 (replace-re-search-function
550 (lambda (from &optional _bound noerror)
552 (while (and (not found) pairs)
553 (setq pair (pop pairs)
554 current-beg (car pair)
555 current-end (cdr pair)
556 current-buf (marker-buffer current-beg))
557 (pop-to-buffer current-buf)
558 (goto-char current-beg)
559 (when (re-search-forward from current-end noerror)
562 ;; FIXME: Despite this being a multi-buffer replacement, `N'
563 ;; doesn't work, because we're not using
564 ;; `multi-query-replace-map', and it would expect the below
565 ;; function to be called once per buffer.
566 (perform-replace from to t t nil)))
568 (defvar xref--xref-buffer-mode-map
569 (let ((map (make-sparse-keymap)))
570 (define-key map [remap quit-window] #'xref-quit)
571 (define-key map (kbd "n") #'xref-next-line)
572 (define-key map (kbd "p") #'xref-prev-line)
573 (define-key map (kbd "r") #'xref-query-replace)
574 (define-key map (kbd "RET") #'xref-goto-xref)
575 (define-key map (kbd "C-o") #'xref-show-location-at-point)
576 ;; suggested by Johan Claesson "to further reduce finger movement":
577 (define-key map (kbd ".") #'xref-next-line)
578 (define-key map (kbd ",") #'xref-prev-line)
581 (define-derived-mode xref--xref-buffer-mode special-mode "XREF"
582 "Mode for displaying cross-references."
583 (setq buffer-read-only t)
584 (setq next-error-function #'xref--next-error-function)
585 (setq next-error-last-buffer (current-buffer)))
587 (defun xref--next-error-function (n reset?)
589 (goto-char (point-min)))
590 (let ((backward (< n 0))
594 (setq xref (xref--search-property 'xref-item backward)))
596 (xref--pop-to-location xref))
598 (error "No %s xref" (if backward "previous" "next"))))))
600 (defun xref-quit (&optional kill)
601 "Bury temporarily displayed buffers, then quit the current window.
603 If KILL is non-nil, also kill the current buffer.
605 The buffers that the user has otherwise interacted with in the
606 meantime are preserved."
608 (let ((window (selected-window))
609 (history xref--display-history))
610 (setq xref--display-history nil)
611 (pcase-dolist (`(,buf . ,win) history)
612 (when (and (window-live-p win)
613 (eq buf (window-buffer win)))
614 (quit-window nil win)))
615 (quit-window kill window)))
617 (defconst xref-buffer-name "*xref*"
618 "The name of the buffer to show xrefs.")
620 (defvar xref--button-map
621 (let ((map (make-sparse-keymap)))
622 (define-key map [(control ?m)] #'xref-goto-xref)
623 (define-key map [mouse-1] #'xref-goto-xref)
624 (define-key map [mouse-2] #'xref--mouse-2)
627 (defun xref--mouse-2 (event)
628 "Move point to the button and show the xref definition."
630 (mouse-set-point event)
632 (xref--search-property 'xref-item)
633 (xref-show-location-at-point))
635 (defun xref--insert-xrefs (xref-alist)
636 "Insert XREF-ALIST in the current-buffer.
637 XREF-ALIST is of the form ((GROUP . (XREF ...)) ...), where
638 GROUP is a string for decoration purposes and XREF is an
640 (require 'compile) ; For the compilation faces.
641 (cl-loop for ((group . xrefs) . more1) on xref-alist
643 (cl-loop for xref in xrefs
644 maximize (let ((line (xref-location-line
645 (oref xref location))))
646 (length (and line (format "%d" line)))))
647 for line-format = (and max-line-width
648 (format "%%%dd: " max-line-width))
650 (xref--insert-propertized '(face compilation-info) group "\n")
651 (cl-loop for (xref . more2) on xrefs do
652 (with-slots (summary location) xref
653 (let* ((line (xref-location-line location))
656 (propertize (format line-format line)
657 'face 'compilation-line-number)
659 (xref--insert-propertized
660 (list 'xref-item xref
661 ;; 'face 'font-lock-keyword-face
662 'mouse-face 'highlight
663 'keymap xref--button-map
665 (concat "mouse-2: display in another window, "
666 "RET or mouse-1: follow reference"))
670 (defun xref--analyze (xrefs)
671 "Find common filenames in XREFS.
672 Return an alist of the form ((FILENAME . (XREF ...)) ...)."
673 (xref--alistify xrefs
675 (xref-location-group (xref-item-location x)))
678 (defun xref--show-xref-buffer (xrefs alist)
679 (let ((xref-alist (xref--analyze xrefs)))
680 (with-current-buffer (get-buffer-create xref-buffer-name)
681 (let ((inhibit-read-only t))
683 (xref--insert-xrefs xref-alist)
684 (xref--xref-buffer-mode)
685 (pop-to-buffer (current-buffer))
686 (goto-char (point-min))
687 (setq xref--window (assoc-default 'window alist))
691 ;; This part of the UI seems fairly uncontroversial: it reads the
692 ;; identifier and deals with the single definition case.
693 ;; (FIXME: do we really want this case to be handled like that in
694 ;; "find references" and "find regexp searches"?)
696 ;; The controversial multiple definitions case is handed off to
697 ;; xref-show-xrefs-function.
699 (defvar xref-show-xrefs-function 'xref--show-xref-buffer
700 "Function to display a list of xrefs.")
702 (defvar xref--read-identifier-history nil)
704 (defvar xref--read-pattern-history nil)
706 (defun xref--show-xrefs (xrefs window)
709 (xref-push-marker-stack)
710 (xref--pop-to-location (car xrefs) window))
712 (xref-push-marker-stack)
713 (funcall xref-show-xrefs-function xrefs
714 `((window . ,window))))))
716 (defun xref--prompt-p (command)
717 (or (eq xref-prompt-for-identifier t)
718 (if (eq (car xref-prompt-for-identifier) 'not)
719 (not (memq command (cdr xref-prompt-for-identifier)))
720 (memq command xref-prompt-for-identifier))))
722 (defun xref--read-identifier (prompt)
723 "Return the identifier at point or read it from the minibuffer."
724 (let* ((backend (xref-find-backend))
725 (id (xref-backend-identifier-at-point backend)))
726 (cond ((or current-prefix-arg
728 (xref--prompt-p this-command))
729 (completing-read (if id
730 (format "%s (default %s): "
731 (substring prompt 0 (string-match
735 (xref-backend-identifier-completion-table backend)
737 'xref--read-identifier-history id))
743 (defun xref--find-xrefs (input kind arg window)
744 (let ((xrefs (funcall (intern (format "xref-backend-%s" kind))
748 (user-error "No %s found for: %s" (symbol-name kind) input))
749 (xref--show-xrefs xrefs window)))
751 (defun xref--find-definitions (id window)
752 (xref--find-xrefs id 'definitions id window))
755 (defun xref-find-definitions (identifier)
756 "Find the definition of the identifier at point.
757 With prefix argument or when there's no identifier at point,
760 If the backend has sufficient information to determine a unique
761 definition for IDENTIFIER, it returns only that definition. If
762 there are multiple possible definitions, it returns all of them.
764 If the backend returns one definition, jump to it; otherwise,
765 display the list in a buffer."
766 (interactive (list (xref--read-identifier "Find definitions of: ")))
767 (xref--find-definitions identifier nil))
770 (defun xref-find-definitions-other-window (identifier)
771 "Like `xref-find-definitions' but switch to the other window."
772 (interactive (list (xref--read-identifier "Find definitions of: ")))
773 (xref--find-definitions identifier 'window))
776 (defun xref-find-definitions-other-frame (identifier)
777 "Like `xref-find-definitions' but switch to the other frame."
778 (interactive (list (xref--read-identifier "Find definitions of: ")))
779 (xref--find-definitions identifier 'frame))
782 (defun xref-find-references (identifier)
783 "Find references to the identifier at point.
784 With prefix argument, prompt for the identifier."
785 (interactive (list (xref--read-identifier "Find references of: ")))
786 (xref--find-xrefs identifier 'references identifier nil))
788 (declare-function apropos-parse-pattern "apropos" (pattern))
791 (defun xref-find-apropos (pattern)
792 "Find all meaningful symbols that match PATTERN.
793 The argument has the same meaning as in `apropos'."
794 (interactive (list (read-string
795 "Search for pattern (word list or regexp): "
796 nil 'xref--read-pattern-history)))
798 (xref--find-xrefs pattern 'apropos
799 (apropos-parse-pattern
800 (if (string-equal (regexp-quote pattern) pattern)
802 (or (split-string pattern "[ \t]+" t)
803 (user-error "No word list given"))
810 ;;;###autoload (define-key esc-map "." #'xref-find-definitions)
811 ;;;###autoload (define-key esc-map "," #'xref-pop-marker-stack)
812 ;;;###autoload (define-key esc-map "?" #'xref-find-references)
813 ;;;###autoload (define-key esc-map [?\C-.] #'xref-find-apropos)
814 ;;;###autoload (define-key ctl-x-4-map "." #'xref-find-definitions-other-window)
815 ;;;###autoload (define-key ctl-x-5-map "." #'xref-find-definitions-other-frame)
820 (defvar xref-etags-mode--saved nil)
822 (define-minor-mode xref-etags-mode
823 "Minor mode to make xref use etags again.
825 Certain major modes install their own mechanisms for listing
826 identifiers and navigation. Turn this on to undo those settings
831 (setq xref-etags-mode--saved xref-backend-functions)
832 (kill-local-variable 'xref-backend-functions))
833 (setq-local xref-backend-functions xref-etags-mode--saved)))
835 (declare-function semantic-symref-find-references-by-name "semantic/symref")
836 (declare-function semantic-find-file-noselect "semantic/fw")
837 (declare-function grep-expand-template "grep")
839 (defun xref-collect-references (symbol dir)
840 "Collect references to SYMBOL inside DIR.
841 This function uses the Semantic Symbol Reference API, see
842 `semantic-symref-find-references-by-name' for details on which
843 tools are used, and when."
844 (cl-assert (directory-name-p dir))
845 (require 'semantic/symref)
846 (defvar semantic-symref-tool)
847 (let* ((default-directory dir)
848 (semantic-symref-tool 'detect)
849 (res (semantic-symref-find-references-by-name symbol 'subdirs))
850 (hits (and res (oref res hit-lines)))
851 (orig-buffers (buffer-list)))
853 (cl-mapcan (lambda (hit) (xref--collect-matches
854 hit (format "\\_<%s\\_>" (regexp-quote symbol))))
856 ;; TODO: Implement "lightweight" buffer visiting, so that we
857 ;; don't have to kill them.
859 (cl-set-difference (buffer-list) orig-buffers)))))
861 (defun xref-collect-matches (regexp files dir ignores)
862 "Collect matches for REGEXP inside FILES in DIR.
863 FILES is a string with glob patterns separated by spaces.
864 IGNORES is a list of glob patterns."
865 (cl-assert (directory-name-p dir))
866 (require 'semantic/fw)
867 (grep-compute-defaults)
868 (defvar grep-find-template)
869 (defvar grep-highlight-matches)
870 (let* ((grep-find-template (replace-regexp-in-string "-e " "-E "
871 grep-find-template t t))
872 (grep-highlight-matches nil)
873 (command (xref--rgrep-command (xref--regexp-to-extended regexp)
875 (orig-buffers (buffer-list))
876 (buf (get-buffer-create " *xref-grep*"))
877 (grep-re (caar grep-regexp-alist))
879 (with-current-buffer buf
881 (call-process-shell-command command nil t)
882 (goto-char (point-min))
883 (while (re-search-forward grep-re nil t)
884 (push (cons (string-to-number (match-string 2))
888 (cl-mapcan (lambda (hit) (xref--collect-matches hit regexp))
890 ;; TODO: Same as above.
892 (cl-set-difference (buffer-list) orig-buffers)))))
894 (defun xref--rgrep-command (regexp files dir ignores)
895 (require 'find-dired) ; for `find-name-arg'
896 (defvar grep-find-template)
897 (defvar find-name-arg)
898 (grep-expand-template
901 (concat (shell-quote-argument "(")
902 " " find-name-arg " "
904 #'shell-quote-argument
906 (concat " -o " find-name-arg " "))
908 (shell-quote-argument ")"))
911 (shell-quote-argument "(")
915 (when (string-match-p "/\\'" ignore)
916 (setq ignore (concat ignore "*")))
917 (if (string-match "\\`\\./" ignore)
918 (setq ignore (replace-match dir t t ignore))
919 (unless (string-prefix-p "*" ignore)
920 (setq ignore (concat "*/" ignore))))
921 (shell-quote-argument ignore))
925 (shell-quote-argument ")")
928 (defun xref--regexp-to-extended (str)
929 (replace-regexp-in-string
930 ;; FIXME: Add tests. Move to subr.el, make a public function.
931 ;; Maybe error on Emacs-only constructs.
932 "\\(?:\\\\\\\\\\)*\\(?:\\\\[][]\\)?\\(?:\\[.+?\\]\\|\\(\\\\?[(){}|]\\)\\)"
935 ((not (match-beginning 1))
937 ((eq (length (match-string 1 str)) 2)
938 (concat (substring str 0 (match-beginning 1))
939 (substring (match-string 1 str) 1 2)))
941 (concat (substring str 0 (match-beginning 1))
943 (match-string 1 str)))))
946 (defun xref--collect-matches (hit regexp)
947 (pcase-let* ((`(,line . ,file) hit)
948 (buf (or (find-buffer-visiting file)
949 (semantic-find-file-noselect file))))
950 (with-current-buffer buf
952 (goto-char (point-min))
953 (forward-line (1- line))
954 (let ((line-end (line-end-position))
955 (line-beg (line-beginning-position))
957 (syntax-propertize line-end)
958 ;; FIXME: This results in several lines with the same
959 ;; summary. Solve with composite pattern?
960 (while (re-search-forward regexp line-end t)
961 (let* ((beg-column (- (match-beginning 0) line-beg))
962 (end-column (- (match-end 0) line-beg))
963 (loc (xref-make-file-location file line beg-column))
964 (summary (buffer-substring line-beg line-end)))
965 (add-face-text-property beg-column end-column 'highlight
967 (push (xref-make-match summary loc (- end-column beg-column))
969 (nreverse matches))))))
973 ;;; xref.el ends here