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"
84 (defclass xref-location () ()
85 :documentation "A location represents a position in a file or buffer.")
87 (cl-defgeneric xref-location-marker (location)
88 "Return the marker for LOCATION.")
90 (cl-defgeneric xref-location-group (location)
91 "Return a string used to group a set of locations.
92 This is typically the filename.")
94 (cl-defgeneric xref-location-line (_location)
95 "Return the line number corresponding to the location."
98 (cl-defgeneric xref-match-length (_item)
99 "Return the length of the match."
102 ;;;; Commonly needed location classes are defined here:
104 ;; FIXME: might be useful to have an optional "hint" i.e. a string to
105 ;; search for in case the line number is sightly out of date.
106 (defclass xref-file-location (xref-location)
107 ((file :type string :initarg :file)
108 (line :type fixnum :initarg :line :reader xref-location-line)
109 (column :type fixnum :initarg :column :reader xref-file-location-column))
110 :documentation "A file location is a file/line/column triple.
111 Line numbers start from 1 and columns from 0.")
113 (defun xref-make-file-location (file line column)
114 "Create and return a new `xref-file-location'."
115 (make-instance 'xref-file-location :file file :line line :column column))
117 (cl-defmethod xref-location-marker ((l xref-file-location))
118 (with-slots (file line column) l
120 (or (get-file-buffer file)
121 (let ((find-file-suppress-same-file-warnings t))
122 (find-file-noselect file)))
126 (goto-char (point-min))
127 (beginning-of-line line)
128 (forward-char column)
131 (cl-defmethod xref-location-group ((l xref-file-location))
134 (defclass xref-buffer-location (xref-location)
135 ((buffer :type buffer :initarg :buffer)
136 (position :type fixnum :initarg :position)))
138 (defun xref-make-buffer-location (buffer position)
139 "Create and return a new `xref-buffer-location'."
140 (make-instance 'xref-buffer-location :buffer buffer :position position))
142 (cl-defmethod xref-location-marker ((l xref-buffer-location))
143 (with-slots (buffer position) l
144 (let ((m (make-marker)))
145 (move-marker m position buffer))))
147 (cl-defmethod xref-location-group ((l xref-buffer-location))
148 (with-slots (buffer) l
149 (or (buffer-file-name buffer)
150 (format "(buffer %s)" (buffer-name buffer)))))
152 (defclass xref-bogus-location (xref-location)
153 ((message :type string :initarg :message
154 :reader xref-bogus-location-message))
155 :documentation "Bogus locations are sometimes useful to
156 indicate errors, e.g. when we know that a function exists but the
157 actual location is not known.")
159 (defun xref-make-bogus-location (message)
160 "Create and return a new `xref-bogus-location'."
161 (make-instance 'xref-bogus-location :message message))
163 (cl-defmethod xref-location-marker ((l xref-bogus-location))
164 (user-error "%s" (oref l message)))
166 (cl-defmethod xref-location-group ((_ xref-bogus-location)) "(No location)")
171 (defclass xref-item ()
172 ((summary :type string :initarg :summary
173 :reader xref-item-summary
174 :documentation "One line which will be displayed for
175 this item in the output buffer.")
176 (location :initarg :location
177 :reader xref-item-location
178 :documentation "An object describing how to navigate
179 to the reference's target."))
180 :comment "An xref item describes a reference to a location
183 (defun xref-make (summary location)
184 "Create and return a new `xref-item'.
185 SUMMARY is a short string to describe the xref.
186 LOCATION is an `xref-location'."
187 (make-instance 'xref-item :summary summary :location location))
189 (defclass xref-match-item ()
190 ((summary :type string :initarg :summary
191 :reader xref-item-summary)
192 (location :initarg :location
193 :type xref-file-location
194 :reader xref-item-location)
195 (length :initarg :length :reader xref-match-length))
196 :comment "A match xref item describes a search result.")
198 (defun xref-make-match (summary location length)
199 "Create and return a new `xref-match-item'.
200 SUMMARY is a short string to describe the xref.
201 LOCATION is an `xref-location'.
202 LENGTH is the match length, in characters."
203 (make-instance 'xref-match-item :summary summary
204 :location location :length length))
209 (defvar xref-backend-functions nil
210 "Special hook to find the xref backend for the current context.
211 Each functions on this hook is called in turn with no arguments
212 and should return either nil to mean that it is not applicable,
213 or an xref backend, which is a value to be used to dispatch the
216 ;; We make the etags backend the default for now, until something
217 ;; better comes along. Use APPEND so that any `add-hook' calls made
218 ;; before this package is loaded put new items before this one.
219 (add-hook 'xref-backend-functions #'etags--xref-backend t)
222 (defun xref-find-backend ()
223 (run-hook-with-args-until-success 'xref-backend-functions))
225 (cl-defgeneric xref-backend-definitions (backend identifier)
226 "Find definitions of IDENTIFIER.
228 The result must be a list of xref objects. If IDENTIFIER
229 contains sufficient information to determine a unique definition,
230 return only that definition. If there are multiple possible
231 definitions, return all of them. If no definitions can be found,
234 IDENTIFIER can be any string returned by
235 `xref-backend-identifier-at-point', or from the table returned by
236 `xref-backend-identifier-completion-table'.
238 To create an xref object, call `xref-make'.")
240 (cl-defgeneric xref-backend-references (_backend identifier)
241 "Find references of IDENTIFIER.
242 The result must be a list of xref objects. If no references can
243 be found, return nil.
245 The default implementation uses `semantic-symref-tool-alist' to
246 find a search tool; by default, this uses \"find | grep\" in the
247 `project-current' roots."
250 (xref-collect-references identifier dir))
251 (let ((pr (project-current t)))
254 (project-external-roots pr)))))
256 (cl-defgeneric xref-backend-apropos (backend pattern)
257 "Find all symbols that match PATTERN.
258 PATTERN is a regexp")
260 (cl-defgeneric xref-backend-identifier-at-point (_backend)
261 "Return the relevant identifier at point.
263 The return value must be a string or nil. nil means no
264 identifier at point found.
266 If it's hard to determine the identifier precisely (e.g., because
267 it's a method call on unknown type), the implementation can
268 return a simple string (such as symbol at point) marked with a
269 special text property which e.g. `xref-backend-definitions' would
270 recognize and then delegate the work to an external process."
271 (let ((thing (thing-at-point 'symbol)))
272 (and thing (substring-no-properties thing))))
274 (cl-defgeneric xref-backend-identifier-completion-table (backend)
275 "Returns the completion table for identifiers.")
279 (defun xref--alistify (list key test)
280 "Partition the elements of LIST into an alist.
281 KEY extracts the key from an element and TEST is used to compare
285 (let* ((k (funcall key e))
286 (probe (cl-assoc k alist :test test)))
288 (setcdr probe (cons e (cdr probe)))
289 (push (cons k (list e)) alist))))
290 ;; Put them back in order.
291 (cl-loop for (key . value) in (reverse alist)
292 collect (cons key (reverse value)))))
294 (defun xref--insert-propertized (props &rest strings)
295 "Insert STRINGS with text properties PROPS."
296 (let ((start (point)))
297 (apply #'insert strings)
298 (add-text-properties start (point) props)))
300 (defun xref--search-property (property &optional backward)
301 "Search the next text range where text property PROPERTY is non-nil.
302 Return the value of PROPERTY. If BACKWARD is non-nil, search
304 (let ((next (if backward
305 #'previous-single-char-property-change
306 #'next-single-char-property-change))
310 (goto-char (funcall next (point) property))
311 (not (or (setq value (get-text-property (point) property))
315 (t (goto-char start) nil))))
318 ;;; Marker stack (M-. pushes, M-, pops)
320 (defcustom xref-marker-ring-length 16
321 "Length of the xref marker ring."
324 (defcustom xref-prompt-for-identifier '(not xref-find-definitions
325 xref-find-definitions-other-window
326 xref-find-definitions-other-frame)
327 "When t, always prompt for the identifier name.
329 When nil, prompt only when there's no value at point we can use,
330 or when the command has been called with the prefix argument.
332 Otherwise, it's a list of xref commands which will prompt
333 anyway (the value at point, if any, will be used as the default).
335 If the list starts with `not', the meaning of the rest of the
336 elements is negated."
337 :type '(choice (const :tag "always" t)
338 (const :tag "auto" nil)
339 (set :menu-tag "command specific" :tag "commands"
341 (const :tag "Except" not)
342 (repeat :inline t (symbol :tag "command")))))
344 (defcustom xref-after-jump-hook '(recenter
345 xref-pulse-momentarily)
346 "Functions called after jumping to an xref."
349 (defcustom xref-after-return-hook '(xref-pulse-momentarily)
350 "Functions called after returning to a pre-jump location."
353 (defvar xref--marker-ring (make-ring xref-marker-ring-length)
354 "Ring of markers to implement the marker stack.")
356 (defun xref-push-marker-stack (&optional m)
357 "Add point M (defaults to `point-marker') to the marker stack."
358 (ring-insert xref--marker-ring (or m (point-marker))))
361 (defun xref-pop-marker-stack ()
362 "Pop back to where \\[xref-find-definitions] was last invoked."
364 (let ((ring xref--marker-ring))
365 (when (ring-empty-p ring)
366 (user-error "Marker stack is empty"))
367 (let ((marker (ring-remove ring 0)))
368 (switch-to-buffer (or (marker-buffer marker)
369 (user-error "The marked buffer has been deleted")))
370 (goto-char (marker-position marker))
371 (set-marker marker nil nil)
372 (run-hooks 'xref-after-return-hook))))
374 (defvar xref--current-item nil)
376 (defun xref-pulse-momentarily ()
377 (pcase-let ((`(,beg . ,end)
380 (let ((length (xref-match-length xref--current-item)))
381 (and length (cons (point) (+ (point) length))))
382 (back-to-indentation)
384 (cons (line-beginning-position) (1+ (point)))
385 (cons (point) (line-end-position)))))))
386 (pulse-momentary-highlight-region beg end 'next-error)))
388 ;; etags.el needs this
389 (defun xref-clear-marker-stack ()
390 "Discard all markers from the marker stack."
391 (let ((ring xref--marker-ring))
392 (while (not (ring-empty-p ring))
393 (let ((marker (ring-remove ring)))
394 (set-marker marker nil nil)))))
397 (defun xref-marker-stack-empty-p ()
398 "Return t if the marker stack is empty; nil otherwise."
399 (ring-empty-p xref--marker-ring))
403 (defun xref--goto-char (pos)
405 ((and (<= (point-min) pos) (<= pos (point-max))))
406 (widen-automatically (widen))
407 (t (user-error "Position is outside accessible part of buffer")))
410 (defun xref--goto-location (location)
411 "Set buffer and point according to xref-location LOCATION."
412 (let ((marker (xref-location-marker location)))
413 (set-buffer (marker-buffer marker))
414 (xref--goto-char marker)))
416 (defun xref--pop-to-location (item &optional window)
417 "Go to the location of ITEM and display the buffer.
418 WINDOW controls how the buffer is displayed:
419 nil -- switch-to-buffer
420 `window' -- pop-to-buffer (other window)
421 `frame' -- pop-to-buffer (other frame)"
422 (let* ((marker (save-excursion
423 (xref-location-marker (xref-item-location item))))
424 (buf (marker-buffer marker)))
426 ((nil) (switch-to-buffer buf))
427 (window (pop-to-buffer buf t))
428 (frame (let ((pop-up-frames t)) (pop-to-buffer buf t))))
429 (xref--goto-char marker))
430 (let ((xref--current-item item))
431 (run-hooks 'xref-after-jump-hook)))
434 ;;; XREF buffer (part of the UI)
436 ;; The xref buffer is used to display a set of xrefs.
438 (defvar-local xref--display-history nil
439 "List of pairs (BUFFER . WINDOW), for temporarily displayed buffers.")
441 (defun xref--save-to-history (buf win)
442 (let ((restore (window-parameter win 'quit-restore)))
443 ;; Save the new entry if the window displayed another buffer
445 (when (and restore (not (eq (car restore) 'same)))
446 (push (cons buf win) xref--display-history))))
448 (defun xref--display-position (pos other-window buf)
449 ;; Show the location, but don't hijack focus.
450 (let ((xref-buf (current-buffer)))
451 (with-selected-window (display-buffer buf other-window)
452 (xref--goto-char pos)
453 (run-hooks 'xref-after-jump-hook)
454 (let ((buf (current-buffer))
455 (win (selected-window)))
456 (with-current-buffer xref-buf
457 (setq-local other-window-scroll-buffer buf)
458 (xref--save-to-history buf win))))))
460 (defun xref--show-location (location)
462 (let* ((marker (xref-location-marker location))
463 (buf (marker-buffer marker)))
464 (xref--display-position marker t buf))
465 (user-error (message (error-message-string err)))))
467 (defun xref-show-location-at-point ()
468 "Display the source of xref at point in the other window, if any."
470 (let* ((xref (xref--item-at-point))
471 (xref--current-item xref))
473 (xref--show-location (xref-item-location xref)))))
475 (defun xref-next-line ()
476 "Move to the next xref and display its source in the other window."
478 (xref--search-property 'xref-item)
479 (xref-show-location-at-point))
481 (defun xref-prev-line ()
482 "Move to the previous xref and display its source in the other window."
484 (xref--search-property 'xref-item t)
485 (xref-show-location-at-point))
487 (defun xref--item-at-point ()
489 (back-to-indentation)
490 (get-text-property (point) 'xref-item)))
492 (defvar-local xref--window nil
493 "ACTION argument to call `display-buffer' with.")
495 (defun xref-goto-xref ()
496 "Jump to the xref on the current line and bury the xref buffer."
498 (let ((xref (or (xref--item-at-point)
499 (user-error "No reference at point")))
500 (window xref--window))
502 (xref--pop-to-location xref window)))
504 (defun xref-query-replace (from to)
505 "Perform interactive replacement in all current matches."
507 (list (read-regexp "Query replace regexp in matches" ".*")
508 (read-regexp "Replace with: ")))
513 (goto-char (point-min))
514 (while (setq item (xref--search-property 'xref-item))
515 (when (xref-match-length item)
517 (let* ((loc (xref-item-location item))
518 (beg (xref-location-marker loc))
519 (end (move-marker (make-marker)
520 (+ beg (xref-match-length item))
521 (marker-buffer beg))))
522 ;; Perform sanity check first.
523 (xref--goto-location loc)
524 ;; FIXME: The check should probably be a generic
525 ;; function, instead of the assumption that all
526 ;; matches contain the full line as summary.
527 ;; TODO: Offer to re-scan otherwise.
528 (unless (equal (buffer-substring-no-properties
529 (line-beginning-position)
531 (xref-item-summary item))
532 (user-error "Search results out of date"))
533 (push (cons beg end) pairs)))))
534 (setq pairs (nreverse pairs)))
535 (unless pairs (user-error "No suitable matches here"))
536 (xref--query-replace-1 from to pairs))
538 (move-marker (car pair) nil)
539 (move-marker (cdr pair) nil)))))
541 ;; FIXME: Write a nicer UI.
542 (defun xref--query-replace-1 (from to pairs)
543 (let* ((query-replace-lazy-highlight nil)
544 current-beg current-end current-buf
545 ;; Counteract the "do the next match now" hack in
546 ;; `perform-replace'. And still, it'll report that those
547 ;; matches were "filtered out" at the end.
548 (isearch-filter-predicate
551 (eq (current-buffer) current-buf)
553 (<= end current-end))))
554 (replace-re-search-function
555 (lambda (from &optional _bound noerror)
557 (while (and (not found) pairs)
558 (setq pair (pop pairs)
559 current-beg (car pair)
560 current-end (cdr pair)
561 current-buf (marker-buffer current-beg))
562 (pop-to-buffer current-buf)
563 (goto-char current-beg)
564 (when (re-search-forward from current-end noerror)
567 ;; FIXME: Despite this being a multi-buffer replacement, `N'
568 ;; doesn't work, because we're not using
569 ;; `multi-query-replace-map', and it would expect the below
570 ;; function to be called once per buffer.
571 (perform-replace from to t t nil)))
573 (defvar xref--xref-buffer-mode-map
574 (let ((map (make-sparse-keymap)))
575 (define-key map [remap quit-window] #'xref-quit)
576 (define-key map (kbd "n") #'xref-next-line)
577 (define-key map (kbd "p") #'xref-prev-line)
578 (define-key map (kbd "r") #'xref-query-replace)
579 (define-key map (kbd "RET") #'xref-goto-xref)
580 (define-key map (kbd "C-o") #'xref-show-location-at-point)
581 ;; suggested by Johan Claesson "to further reduce finger movement":
582 (define-key map (kbd ".") #'xref-next-line)
583 (define-key map (kbd ",") #'xref-prev-line)
586 (define-derived-mode xref--xref-buffer-mode special-mode "XREF"
587 "Mode for displaying cross-references."
588 (setq buffer-read-only t)
589 (setq next-error-function #'xref--next-error-function)
590 (setq next-error-last-buffer (current-buffer)))
592 (defun xref--next-error-function (n reset?)
594 (goto-char (point-min)))
595 (let ((backward (< n 0))
599 (setq xref (xref--search-property 'xref-item backward)))
601 (xref--pop-to-location xref))
603 (error "No %s xref" (if backward "previous" "next"))))))
605 (defun xref-quit (&optional kill)
606 "Bury temporarily displayed buffers, then quit the current window.
608 If KILL is non-nil, also kill the current buffer.
610 The buffers that the user has otherwise interacted with in the
611 meantime are preserved."
613 (let ((window (selected-window))
614 (history xref--display-history))
615 (setq xref--display-history nil)
616 (pcase-dolist (`(,buf . ,win) history)
617 (when (and (window-live-p win)
618 (eq buf (window-buffer win)))
619 (quit-window nil win)))
620 (quit-window kill window)))
622 (defconst xref-buffer-name "*xref*"
623 "The name of the buffer to show xrefs.")
625 (defvar xref--button-map
626 (let ((map (make-sparse-keymap)))
627 (define-key map [(control ?m)] #'xref-goto-xref)
628 (define-key map [mouse-1] #'xref-goto-xref)
629 (define-key map [mouse-2] #'xref--mouse-2)
632 (defun xref--mouse-2 (event)
633 "Move point to the button and show the xref definition."
635 (mouse-set-point event)
637 (xref--search-property 'xref-item)
638 (xref-show-location-at-point))
640 (defun xref--insert-xrefs (xref-alist)
641 "Insert XREF-ALIST in the current-buffer.
642 XREF-ALIST is of the form ((GROUP . (XREF ...)) ...), where
643 GROUP is a string for decoration purposes and XREF is an
645 (require 'compile) ; For the compilation faces.
646 (cl-loop for ((group . xrefs) . more1) on xref-alist
648 (cl-loop for xref in xrefs
649 maximize (let ((line (xref-location-line
650 (oref xref location))))
651 (length (and line (format "%d" line)))))
652 for line-format = (and max-line-width
653 (format "%%%dd: " max-line-width))
655 (xref--insert-propertized '(face compilation-info) group "\n")
656 (cl-loop for (xref . more2) on xrefs do
657 (with-slots (summary location) xref
658 (let* ((line (xref-location-line location))
661 (propertize (format line-format line)
662 'face 'compilation-line-number)
664 (xref--insert-propertized
665 (list 'xref-item xref
666 ;; 'face 'font-lock-keyword-face
667 'mouse-face 'highlight
668 'keymap xref--button-map
670 (concat "mouse-2: display in another window, "
671 "RET or mouse-1: follow reference"))
675 (defun xref--analyze (xrefs)
676 "Find common filenames in XREFS.
677 Return an alist of the form ((FILENAME . (XREF ...)) ...)."
678 (xref--alistify xrefs
680 (xref-location-group (xref-item-location x)))
683 (defun xref--show-xref-buffer (xrefs alist)
684 (let ((xref-alist (xref--analyze xrefs)))
685 (with-current-buffer (get-buffer-create xref-buffer-name)
686 (let ((inhibit-read-only t))
688 (xref--insert-xrefs xref-alist)
689 (xref--xref-buffer-mode)
690 (pop-to-buffer (current-buffer))
691 (goto-char (point-min))
692 (setq xref--window (assoc-default 'window alist))
696 ;; This part of the UI seems fairly uncontroversial: it reads the
697 ;; identifier and deals with the single definition case.
698 ;; (FIXME: do we really want this case to be handled like that in
699 ;; "find references" and "find regexp searches"?)
701 ;; The controversial multiple definitions case is handed off to
702 ;; xref-show-xrefs-function.
704 (defvar xref-show-xrefs-function 'xref--show-xref-buffer
705 "Function to display a list of xrefs.")
707 (defvar xref--read-identifier-history nil)
709 (defvar xref--read-pattern-history nil)
711 (defun xref--show-xrefs (xrefs window)
714 (xref-push-marker-stack)
715 (xref--pop-to-location (car xrefs) window))
717 (xref-push-marker-stack)
718 (funcall xref-show-xrefs-function xrefs
719 `((window . ,window))))))
721 (defun xref--prompt-p (command)
722 (or (eq xref-prompt-for-identifier t)
723 (if (eq (car xref-prompt-for-identifier) 'not)
724 (not (memq command (cdr xref-prompt-for-identifier)))
725 (memq command xref-prompt-for-identifier))))
727 (defun xref--read-identifier (prompt)
728 "Return the identifier at point or read it from the minibuffer."
729 (let* ((backend (xref-find-backend))
730 (id (xref-backend-identifier-at-point backend)))
731 (cond ((or current-prefix-arg
733 (xref--prompt-p this-command))
734 (completing-read (if id
735 (format "%s (default %s): "
736 (substring prompt 0 (string-match
740 (xref-backend-identifier-completion-table backend)
742 'xref--read-identifier-history id))
748 (defun xref--find-xrefs (input kind arg window)
749 (let ((xrefs (funcall (intern (format "xref-backend-%s" kind))
753 (user-error "No %s found for: %s" (symbol-name kind) input))
754 (xref--show-xrefs xrefs window)))
756 (defun xref--find-definitions (id window)
757 (xref--find-xrefs id 'definitions id window))
760 (defun xref-find-definitions (identifier)
761 "Find the definition of the identifier at point.
762 With prefix argument or when there's no identifier at point,
765 If the backend has sufficient information to determine a unique
766 definition for IDENTIFIER, it returns only that definition. If
767 there are multiple possible definitions, it returns all of them.
769 If the backend returns one definition, jump to it; otherwise,
770 display the list in a buffer."
771 (interactive (list (xref--read-identifier "Find definitions of: ")))
772 (xref--find-definitions identifier nil))
775 (defun xref-find-definitions-other-window (identifier)
776 "Like `xref-find-definitions' but switch to the other window."
777 (interactive (list (xref--read-identifier "Find definitions of: ")))
778 (xref--find-definitions identifier 'window))
781 (defun xref-find-definitions-other-frame (identifier)
782 "Like `xref-find-definitions' but switch to the other frame."
783 (interactive (list (xref--read-identifier "Find definitions of: ")))
784 (xref--find-definitions identifier 'frame))
787 (defun xref-find-references (identifier)
788 "Find references to the identifier at point.
789 With prefix argument, prompt for the identifier."
790 (interactive (list (xref--read-identifier "Find references of: ")))
791 (xref--find-xrefs identifier 'references identifier nil))
793 (declare-function apropos-parse-pattern "apropos" (pattern))
796 (defun xref-find-apropos (pattern)
797 "Find all meaningful symbols that match PATTERN.
798 The argument has the same meaning as in `apropos'."
799 (interactive (list (read-string
800 "Search for pattern (word list or regexp): "
801 nil 'xref--read-pattern-history)))
803 (xref--find-xrefs pattern 'apropos
804 (apropos-parse-pattern
805 (if (string-equal (regexp-quote pattern) pattern)
807 (or (split-string pattern "[ \t]+" t)
808 (user-error "No word list given"))
815 ;;;###autoload (define-key esc-map "." #'xref-find-definitions)
816 ;;;###autoload (define-key esc-map "," #'xref-pop-marker-stack)
817 ;;;###autoload (define-key esc-map "?" #'xref-find-references)
818 ;;;###autoload (define-key esc-map [?\C-.] #'xref-find-apropos)
819 ;;;###autoload (define-key ctl-x-4-map "." #'xref-find-definitions-other-window)
820 ;;;###autoload (define-key ctl-x-5-map "." #'xref-find-definitions-other-frame)
825 (defvar xref-etags-mode--saved nil)
827 (define-minor-mode xref-etags-mode
828 "Minor mode to make xref use etags again.
830 Certain major modes install their own mechanisms for listing
831 identifiers and navigation. Turn this on to undo those settings
836 (setq xref-etags-mode--saved xref-backend-functions)
837 (kill-local-variable 'xref-backend-functions))
838 (setq-local xref-backend-functions xref-etags-mode--saved)))
840 (declare-function semantic-symref-find-references-by-name "semantic/symref")
841 (declare-function semantic-find-file-noselect "semantic/fw")
842 (declare-function grep-expand-template "grep")
844 (defun xref-collect-references (symbol dir)
845 "Collect references to SYMBOL inside DIR.
846 This function uses the Semantic Symbol Reference API, see
847 `semantic-symref-find-references-by-name' for details on which
848 tools are used, and when."
849 (cl-assert (directory-name-p dir))
850 (require 'semantic/symref)
851 (defvar semantic-symref-tool)
852 (let* ((default-directory dir)
853 (semantic-symref-tool 'detect)
854 (res (semantic-symref-find-references-by-name symbol 'subdirs))
855 (hits (and res (oref res hit-lines)))
856 (orig-buffers (buffer-list)))
858 (cl-mapcan (lambda (hit) (xref--collect-matches
859 hit (format "\\_<%s\\_>" (regexp-quote symbol))))
861 ;; TODO: Implement "lightweight" buffer visiting, so that we
862 ;; don't have to kill them.
864 (cl-set-difference (buffer-list) orig-buffers)))))
866 (defun xref-collect-matches (regexp files dir ignores)
867 "Collect matches for REGEXP inside FILES in DIR.
868 FILES is a string with glob patterns separated by spaces.
869 IGNORES is a list of glob patterns."
870 (cl-assert (directory-name-p dir))
871 (require 'semantic/fw)
872 (grep-compute-defaults)
873 (defvar grep-find-template)
874 (defvar grep-highlight-matches)
875 (let* ((grep-find-template (replace-regexp-in-string "-e " "-E "
876 grep-find-template t t))
877 (grep-highlight-matches nil)
878 (command (xref--rgrep-command (xref--regexp-to-extended regexp)
880 (orig-buffers (buffer-list))
881 (buf (get-buffer-create " *xref-grep*"))
882 (grep-re (caar grep-regexp-alist))
884 (with-current-buffer buf
886 (call-process-shell-command command nil t)
887 (goto-char (point-min))
888 (while (re-search-forward grep-re nil t)
889 (push (cons (string-to-number (match-string 2))
893 (cl-mapcan (lambda (hit) (xref--collect-matches hit regexp))
895 ;; TODO: Same as above.
897 (cl-set-difference (buffer-list) orig-buffers)))))
899 (defun xref--rgrep-command (regexp files dir ignores)
900 (require 'find-dired) ; for `find-name-arg'
901 (defvar grep-find-template)
902 (defvar find-name-arg)
903 (grep-expand-template
906 (concat (shell-quote-argument "(")
907 " " find-name-arg " "
909 #'shell-quote-argument
911 (concat " -o " find-name-arg " "))
913 (shell-quote-argument ")"))
916 (shell-quote-argument "(")
920 (when (string-match-p "/\\'" ignore)
921 (setq ignore (concat ignore "*")))
922 (if (string-match "\\`\\./" ignore)
923 (setq ignore (replace-match dir t t ignore))
924 (unless (string-prefix-p "*" ignore)
925 (setq ignore (concat "*/" ignore))))
926 (shell-quote-argument ignore))
930 (shell-quote-argument ")")
933 (defun xref--regexp-to-extended (str)
934 (replace-regexp-in-string
935 ;; FIXME: Add tests. Move to subr.el, make a public function.
936 ;; Maybe error on Emacs-only constructs.
937 "\\(?:\\\\\\\\\\)*\\(?:\\\\[][]\\)?\\(?:\\[.+?\\]\\|\\(\\\\?[(){}|]\\)\\)"
940 ((not (match-beginning 1))
942 ((eq (length (match-string 1 str)) 2)
943 (concat (substring str 0 (match-beginning 1))
944 (substring (match-string 1 str) 1 2)))
946 (concat (substring str 0 (match-beginning 1))
948 (match-string 1 str)))))
951 (defun xref--collect-matches (hit regexp)
952 (pcase-let* ((`(,line . ,file) hit)
953 (buf (or (find-buffer-visiting file)
954 (semantic-find-file-noselect file))))
955 (with-current-buffer buf
957 (goto-char (point-min))
958 (forward-line (1- line))
959 (let ((line-end (line-end-position))
960 (line-beg (line-beginning-position))
962 (syntax-propertize line-end)
963 ;; FIXME: This results in several lines with the same
964 ;; summary. Solve with composite pattern?
965 (while (re-search-forward regexp line-end t)
966 (let* ((beg-column (- (match-beginning 0) line-beg))
967 (end-column (- (match-end 0) line-beg))
968 (loc (xref-make-file-location file line beg-column))
969 (summary (buffer-substring line-beg line-end)))
970 (add-face-text-property beg-column end-column 'highlight
972 (push (xref-make-match summary loc (- end-column beg-column))
974 (nreverse matches))))))
978 ;;; xref.el ends here