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 ;; We make the etags backend the default for now, until something
205 ;; better comes along.
206 (defvar xref-backend-functions (list #'xref--etags-backend)
207 "Special hook to find the xref backend for the current context.
208 Each functions on this hook is called in turn with no arguments
209 and should return either nil to mean that it is not applicable,
210 or an xref backend, which is a value to be used to dispatch the
214 (defun xref-find-backend ()
215 (run-hook-with-args-until-success 'xref-backend-functions))
217 (defun xref--etags-backend () 'etags)
219 (cl-defgeneric xref-backend-definitions (backend identifier)
220 "Find definitions of IDENTIFIER.
222 The result must be a list of xref objects. If IDENTIFIER
223 contains sufficient information to determine a unique definition,
224 return only that definition. If there are multiple possible
225 definitions, return all of them. If no definitions can be found,
228 IDENTIFIER can be any string returned by
229 `xref-backend-identifier-at-point', or from the table returned by
230 `xref-backend-identifier-completion-table'.
232 To create an xref object, call `xref-make'.")
234 (cl-defgeneric xref-backend-references (backend identifier)
235 "Find references of IDENTIFIER.
236 The result must be a list of xref objects. If no references can
237 be found, return nil.")
239 (cl-defgeneric xref-backend-apropos (backend pattern)
240 "Find all symbols that match PATTERN.
241 PATTERN is a regexp")
243 (cl-defgeneric xref-backend-identifier-at-point (_backend)
244 "Return the relevant identifier at point.
246 The return value must be a string or nil. nil means no
247 identifier at point found.
249 If it's hard to determine the identifier precisely (e.g., because
250 it's a method call on unknown type), the implementation can
251 return a simple string (such as symbol at point) marked with a
252 special text property which e.g. `xref-backend-definitions' would
253 recognize and then delegate the work to an external process."
254 (let ((thing (thing-at-point 'symbol)))
255 (and thing (substring-no-properties thing))))
257 (cl-defgeneric xref-backend-identifier-completion-table (backend)
258 "Returns the completion table for identifiers.")
262 (defun xref--alistify (list key test)
263 "Partition the elements of LIST into an alist.
264 KEY extracts the key from an element and TEST is used to compare
268 (let* ((k (funcall key e))
269 (probe (cl-assoc k alist :test test)))
271 (setcdr probe (cons e (cdr probe)))
272 (push (cons k (list e)) alist))))
273 ;; Put them back in order.
274 (cl-loop for (key . value) in (reverse alist)
275 collect (cons key (reverse value)))))
277 (defun xref--insert-propertized (props &rest strings)
278 "Insert STRINGS with text properties PROPS."
279 (let ((start (point)))
280 (apply #'insert strings)
281 (add-text-properties start (point) props)))
283 (defun xref--search-property (property &optional backward)
284 "Search the next text range where text property PROPERTY is non-nil.
285 Return the value of PROPERTY. If BACKWARD is non-nil, search
287 (let ((next (if backward
288 #'previous-single-char-property-change
289 #'next-single-char-property-change))
293 (goto-char (funcall next (point) property))
294 (not (or (setq value (get-text-property (point) property))
298 (t (goto-char start) nil))))
301 ;;; Marker stack (M-. pushes, M-, pops)
303 (defcustom xref-marker-ring-length 16
304 "Length of the xref marker ring."
307 (defcustom xref-prompt-for-identifier '(not xref-find-definitions
308 xref-find-definitions-other-window
309 xref-find-definitions-other-frame)
310 "When t, always prompt for the identifier name.
312 When nil, prompt only when there's no value at point we can use,
313 or when the command has been called with the prefix argument.
315 Otherwise, it's a list of xref commands which will prompt
316 anyway (the value at point, if any, will be used as the default).
318 If the list starts with `not', the meaning of the rest of the
319 elements is negated."
320 :type '(choice (const :tag "always" t)
321 (const :tag "auto" nil)
322 (set :menu-tag "command specific" :tag "commands"
324 (const :tag "Except" not)
325 (repeat :inline t (symbol :tag "command")))))
327 (defcustom xref-after-jump-hook '(recenter
328 xref-pulse-momentarily)
329 "Functions called after jumping to an xref."
332 (defcustom xref-after-return-hook '(xref-pulse-momentarily)
333 "Functions called after returning to a pre-jump location."
336 (defvar xref--marker-ring (make-ring xref-marker-ring-length)
337 "Ring of markers to implement the marker stack.")
339 (defun xref-push-marker-stack (&optional m)
340 "Add point M (defaults to `point-marker') to the marker stack."
341 (ring-insert xref--marker-ring (or m (point-marker))))
344 (defun xref-pop-marker-stack ()
345 "Pop back to where \\[xref-find-definitions] was last invoked."
347 (let ((ring xref--marker-ring))
348 (when (ring-empty-p ring)
349 (user-error "Marker stack is empty"))
350 (let ((marker (ring-remove ring 0)))
351 (switch-to-buffer (or (marker-buffer marker)
352 (user-error "The marked buffer has been deleted")))
353 (goto-char (marker-position marker))
354 (set-marker marker nil nil)
355 (run-hooks 'xref-after-return-hook))))
357 (defvar xref--current-item nil)
359 (defun xref-pulse-momentarily ()
360 (pcase-let ((`(,beg . ,end)
363 (let ((length (xref-match-length xref--current-item)))
364 (and length (cons (point) (+ (point) length))))
365 (back-to-indentation)
367 (cons (line-beginning-position) (1+ (point)))
368 (cons (point) (line-end-position)))))))
369 (pulse-momentary-highlight-region beg end 'next-error)))
371 ;; etags.el needs this
372 (defun xref-clear-marker-stack ()
373 "Discard all markers from the marker stack."
374 (let ((ring xref--marker-ring))
375 (while (not (ring-empty-p ring))
376 (let ((marker (ring-remove ring)))
377 (set-marker marker nil nil)))))
380 (defun xref-marker-stack-empty-p ()
381 "Return t if the marker stack is empty; nil otherwise."
382 (ring-empty-p xref--marker-ring))
386 (defun xref--goto-char (pos)
388 ((and (<= (point-min) pos) (<= pos (point-max))))
389 (widen-automatically (widen))
390 (t (user-error "Position is outside accessible part of buffer")))
393 (defun xref--goto-location (location)
394 "Set buffer and point according to xref-location LOCATION."
395 (let ((marker (xref-location-marker location)))
396 (set-buffer (marker-buffer marker))
397 (xref--goto-char marker)))
399 (defun xref--pop-to-location (item &optional window)
400 "Go to the location of ITEM and display the buffer.
401 WINDOW controls how the buffer is displayed:
402 nil -- switch-to-buffer
403 `window' -- pop-to-buffer (other window)
404 `frame' -- pop-to-buffer (other frame)"
405 (let* ((marker (save-excursion
406 (xref-location-marker (xref-item-location item))))
407 (buf (marker-buffer marker)))
409 ((nil) (switch-to-buffer buf))
410 (window (pop-to-buffer buf t))
411 (frame (let ((pop-up-frames t)) (pop-to-buffer buf t))))
412 (xref--goto-char marker))
413 (let ((xref--current-item item))
414 (run-hooks 'xref-after-jump-hook)))
417 ;;; XREF buffer (part of the UI)
419 ;; The xref buffer is used to display a set of xrefs.
421 (defvar-local xref--display-history nil
422 "List of pairs (BUFFER . WINDOW), for temporarily displayed buffers.")
424 (defun xref--save-to-history (buf win)
425 (let ((restore (window-parameter win 'quit-restore)))
426 ;; Save the new entry if the window displayed another buffer
428 (when (and restore (not (eq (car restore) 'same)))
429 (push (cons buf win) xref--display-history))))
431 (defun xref--display-position (pos other-window buf)
432 ;; Show the location, but don't hijack focus.
433 (let ((xref-buf (current-buffer)))
434 (with-selected-window (display-buffer buf other-window)
435 (xref--goto-char pos)
436 (run-hooks 'xref-after-jump-hook)
437 (let ((buf (current-buffer))
438 (win (selected-window)))
439 (with-current-buffer xref-buf
440 (setq-local other-window-scroll-buffer buf)
441 (xref--save-to-history buf win))))))
443 (defun xref--show-location (location)
445 (let* ((marker (xref-location-marker location))
446 (buf (marker-buffer marker)))
447 (xref--display-position marker t buf))
448 (user-error (message (error-message-string err)))))
450 (defun xref-show-location-at-point ()
451 "Display the source of xref at point in the other window, if any."
453 (let* ((xref (xref--item-at-point))
454 (xref--current-item xref))
456 (xref--show-location (xref-item-location xref)))))
458 (defun xref-next-line ()
459 "Move to the next xref and display its source in the other window."
461 (xref--search-property 'xref-item)
462 (xref-show-location-at-point))
464 (defun xref-prev-line ()
465 "Move to the previous xref and display its source in the other window."
467 (xref--search-property 'xref-item t)
468 (xref-show-location-at-point))
470 (defun xref--item-at-point ()
472 (back-to-indentation)
473 (get-text-property (point) 'xref-item)))
475 (defvar-local xref--window nil
476 "ACTION argument to call `display-buffer' with.")
478 (defun xref-goto-xref ()
479 "Jump to the xref on the current line and bury the xref buffer."
481 (let ((xref (or (xref--item-at-point)
482 (user-error "No reference at point")))
483 (window xref--window))
485 (xref--pop-to-location xref window)))
487 (defun xref-query-replace (from to)
488 "Perform interactive replacement in all current matches."
490 (list (read-regexp "Query replace regexp in matches" ".*")
491 (read-regexp "Replace with: ")))
496 (goto-char (point-min))
497 (while (setq item (xref--search-property 'xref-item))
498 (when (xref-match-length item)
500 (let* ((loc (xref-item-location item))
501 (beg (xref-location-marker loc))
502 (end (move-marker (make-marker)
503 (+ beg (xref-match-length item))
504 (marker-buffer beg))))
505 ;; Perform sanity check first.
506 (xref--goto-location loc)
507 ;; FIXME: The check should probably be a generic
508 ;; function, instead of the assumption that all
509 ;; matches contain the full line as summary.
510 ;; TODO: Offer to re-scan otherwise.
511 (unless (equal (buffer-substring-no-properties
512 (line-beginning-position)
514 (xref-item-summary item))
515 (user-error "Search results out of date"))
516 (push (cons beg end) pairs)))))
517 (setq pairs (nreverse pairs)))
518 (unless pairs (user-error "No suitable matches here"))
519 (xref--query-replace-1 from to pairs))
521 (move-marker (car pair) nil)
522 (move-marker (cdr pair) nil)))))
524 ;; FIXME: Write a nicer UI.
525 (defun xref--query-replace-1 (from to pairs)
526 (let* ((query-replace-lazy-highlight nil)
527 current-beg current-end current-buf
528 ;; Counteract the "do the next match now" hack in
529 ;; `perform-replace'. And still, it'll report that those
530 ;; matches were "filtered out" at the end.
531 (isearch-filter-predicate
534 (eq (current-buffer) current-buf)
536 (<= end current-end))))
537 (replace-re-search-function
538 (lambda (from &optional _bound noerror)
540 (while (and (not found) pairs)
541 (setq pair (pop pairs)
542 current-beg (car pair)
543 current-end (cdr pair)
544 current-buf (marker-buffer current-beg))
545 (pop-to-buffer current-buf)
546 (goto-char current-beg)
547 (when (re-search-forward from current-end noerror)
550 ;; FIXME: Despite this being a multi-buffer replacement, `N'
551 ;; doesn't work, because we're not using
552 ;; `multi-query-replace-map', and it would expect the below
553 ;; function to be called once per buffer.
554 (perform-replace from to t t nil)))
556 (defvar xref--xref-buffer-mode-map
557 (let ((map (make-sparse-keymap)))
558 (define-key map [remap quit-window] #'xref-quit)
559 (define-key map (kbd "n") #'xref-next-line)
560 (define-key map (kbd "p") #'xref-prev-line)
561 (define-key map (kbd "r") #'xref-query-replace)
562 (define-key map (kbd "RET") #'xref-goto-xref)
563 (define-key map (kbd "C-o") #'xref-show-location-at-point)
564 ;; suggested by Johan Claesson "to further reduce finger movement":
565 (define-key map (kbd ".") #'xref-next-line)
566 (define-key map (kbd ",") #'xref-prev-line)
569 (define-derived-mode xref--xref-buffer-mode special-mode "XREF"
570 "Mode for displaying cross-references."
571 (setq buffer-read-only t)
572 (setq next-error-function #'xref--next-error-function)
573 (setq next-error-last-buffer (current-buffer)))
575 (defun xref--next-error-function (n reset?)
577 (goto-char (point-min)))
578 (let ((backward (< n 0))
582 (setq xref (xref--search-property 'xref-item backward)))
584 (xref--pop-to-location xref))
586 (error "No %s xref" (if backward "previous" "next"))))))
588 (defun xref-quit (&optional kill)
589 "Bury temporarily displayed buffers, then quit the current window.
591 If KILL is non-nil, also kill the current buffer.
593 The buffers that the user has otherwise interacted with in the
594 meantime are preserved."
596 (let ((window (selected-window))
597 (history xref--display-history))
598 (setq xref--display-history nil)
599 (pcase-dolist (`(,buf . ,win) history)
600 (when (and (window-live-p win)
601 (eq buf (window-buffer win)))
602 (quit-window nil win)))
603 (quit-window kill window)))
605 (defconst xref-buffer-name "*xref*"
606 "The name of the buffer to show xrefs.")
608 (defvar xref--button-map
609 (let ((map (make-sparse-keymap)))
610 (define-key map [(control ?m)] #'xref-goto-xref)
611 (define-key map [mouse-1] #'xref-goto-xref)
612 (define-key map [mouse-2] #'xref--mouse-2)
615 (defun xref--mouse-2 (event)
616 "Move point to the button and show the xref definition."
618 (mouse-set-point event)
620 (xref--search-property 'xref-item)
621 (xref-show-location-at-point))
623 (defun xref--insert-xrefs (xref-alist)
624 "Insert XREF-ALIST in the current-buffer.
625 XREF-ALIST is of the form ((GROUP . (XREF ...)) ...), where
626 GROUP is a string for decoration purposes and XREF is an
628 (require 'compile) ; For the compilation faces.
629 (cl-loop for ((group . xrefs) . more1) on xref-alist
631 (cl-loop for xref in xrefs
632 maximize (let ((line (xref-location-line
633 (oref xref location))))
634 (length (and line (format "%d" line)))))
635 for line-format = (and max-line-width
636 (format "%%%dd: " max-line-width))
638 (xref--insert-propertized '(face compilation-info) group "\n")
639 (cl-loop for (xref . more2) on xrefs do
640 (with-slots (summary location) xref
641 (let* ((line (xref-location-line location))
644 (propertize (format line-format line)
645 'face 'compilation-line-number)
647 (xref--insert-propertized
648 (list 'xref-item xref
649 ;; 'face 'font-lock-keyword-face
650 'mouse-face 'highlight
651 'keymap xref--button-map
653 (concat "mouse-2: display in another window, "
654 "RET or mouse-1: follow reference"))
658 (defun xref--analyze (xrefs)
659 "Find common filenames in XREFS.
660 Return an alist of the form ((FILENAME . (XREF ...)) ...)."
661 (xref--alistify xrefs
663 (xref-location-group (xref-item-location x)))
666 (defun xref--show-xref-buffer (xrefs alist)
667 (let ((xref-alist (xref--analyze xrefs)))
668 (with-current-buffer (get-buffer-create xref-buffer-name)
669 (let ((inhibit-read-only t))
671 (xref--insert-xrefs xref-alist)
672 (xref--xref-buffer-mode)
673 (pop-to-buffer (current-buffer))
674 (goto-char (point-min))
675 (setq xref--window (assoc-default 'window alist))
679 ;; This part of the UI seems fairly uncontroversial: it reads the
680 ;; identifier and deals with the single definition case.
681 ;; (FIXME: do we really want this case to be handled like that in
682 ;; "find references" and "find regexp searches"?)
684 ;; The controversial multiple definitions case is handed off to
685 ;; xref-show-xrefs-function.
687 (defvar xref-show-xrefs-function 'xref--show-xref-buffer
688 "Function to display a list of xrefs.")
690 (defvar xref--read-identifier-history nil)
692 (defvar xref--read-pattern-history nil)
694 (defun xref--show-xrefs (xrefs window)
697 (xref-push-marker-stack)
698 (xref--pop-to-location (car xrefs) window))
700 (xref-push-marker-stack)
701 (funcall xref-show-xrefs-function xrefs
702 `((window . ,window))))))
704 (defun xref--prompt-p (command)
705 (or (eq xref-prompt-for-identifier t)
706 (if (eq (car xref-prompt-for-identifier) 'not)
707 (not (memq command (cdr xref-prompt-for-identifier)))
708 (memq command xref-prompt-for-identifier))))
710 (defun xref--read-identifier (prompt)
711 "Return the identifier at point or read it from the minibuffer."
712 (let* ((backend (xref-find-backend))
713 (id (xref-backend-identifier-at-point backend)))
714 (cond ((or current-prefix-arg
716 (xref--prompt-p this-command))
717 (completing-read (if id
718 (format "%s (default %s): "
719 (substring prompt 0 (string-match
723 (xref-backend-identifier-completion-table backend)
725 'xref--read-identifier-history id))
731 (defun xref--find-xrefs (input kind arg window)
732 (let ((xrefs (funcall (intern (format "xref-backend-%s" kind))
736 (user-error "No %s found for: %s" (symbol-name kind) input))
737 (xref--show-xrefs xrefs window)))
739 (defun xref--find-definitions (id window)
740 (xref--find-xrefs id 'definitions id window))
743 (defun xref-find-definitions (identifier)
744 "Find the definition of the identifier at point.
745 With prefix argument or when there's no identifier at point,
748 If the backend has sufficient information to determine a unique
749 definition for IDENTIFIER, it returns only that definition. If
750 there are multiple possible definitions, it returns all of them.
752 If the backend returns one definition, jump to it; otherwise,
753 display the list in a buffer."
754 (interactive (list (xref--read-identifier "Find definitions of: ")))
755 (xref--find-definitions identifier nil))
758 (defun xref-find-definitions-other-window (identifier)
759 "Like `xref-find-definitions' but switch to the other window."
760 (interactive (list (xref--read-identifier "Find definitions of: ")))
761 (xref--find-definitions identifier 'window))
764 (defun xref-find-definitions-other-frame (identifier)
765 "Like `xref-find-definitions' but switch to the other frame."
766 (interactive (list (xref--read-identifier "Find definitions of: ")))
767 (xref--find-definitions identifier 'frame))
770 (defun xref-find-references (identifier)
771 "Find references to the identifier at point.
772 With prefix argument, prompt for the identifier."
773 (interactive (list (xref--read-identifier "Find references of: ")))
774 (xref--find-xrefs identifier 'references identifier nil))
776 (declare-function apropos-parse-pattern "apropos" (pattern))
779 (defun xref-find-apropos (pattern)
780 "Find all meaningful symbols that match PATTERN.
781 The argument has the same meaning as in `apropos'."
782 (interactive (list (read-string
783 "Search for pattern (word list or regexp): "
784 nil 'xref--read-pattern-history)))
786 (xref--find-xrefs pattern 'apropos
787 (apropos-parse-pattern
788 (if (string-equal (regexp-quote pattern) pattern)
790 (or (split-string pattern "[ \t]+" t)
791 (user-error "No word list given"))
798 ;;;###autoload (define-key esc-map "." #'xref-find-definitions)
799 ;;;###autoload (define-key esc-map "," #'xref-pop-marker-stack)
800 ;;;###autoload (define-key esc-map "?" #'xref-find-references)
801 ;;;###autoload (define-key esc-map [?\C-.] #'xref-find-apropos)
802 ;;;###autoload (define-key ctl-x-4-map "." #'xref-find-definitions-other-window)
803 ;;;###autoload (define-key ctl-x-5-map "." #'xref-find-definitions-other-frame)
808 (defvar xref-etags-mode--saved nil)
810 (define-minor-mode xref-etags-mode
811 "Minor mode to make xref use etags again.
813 Certain major modes install their own mechanisms for listing
814 identifiers and navigation. Turn this on to undo those settings
819 (setq xref-etags-mode--saved xref-backend-functions)
820 (kill-local-variable 'xref-backend-functions))
821 (setq-local xref-backend-functions xref-etags-mode--saved)))
823 (declare-function semantic-symref-find-references-by-name "semantic/symref")
824 (declare-function semantic-find-file-noselect "semantic/fw")
825 (declare-function grep-expand-template "grep")
827 (defun xref-collect-references (symbol dir)
828 "Collect references to SYMBOL inside DIR.
829 This function uses the Semantic Symbol Reference API, see
830 `semantic-symref-find-references-by-name' for details on which
831 tools are used, and when."
832 (cl-assert (directory-name-p dir))
833 (require 'semantic/symref)
834 (defvar semantic-symref-tool)
835 (let* ((default-directory dir)
836 (semantic-symref-tool 'detect)
837 (res (semantic-symref-find-references-by-name symbol 'subdirs))
838 (hits (and res (oref res hit-lines)))
839 (orig-buffers (buffer-list)))
841 (cl-mapcan (lambda (hit) (xref--collect-matches
842 hit (format "\\_<%s\\_>" (regexp-quote symbol))))
844 ;; TODO: Implement "lightweight" buffer visiting, so that we
845 ;; don't have to kill them.
847 (cl-set-difference (buffer-list) orig-buffers)))))
849 (defun xref-collect-matches (regexp files dir ignores)
850 "Collect matches for REGEXP inside FILES in DIR.
851 FILES is a string with glob patterns separated by spaces.
852 IGNORES is a list of glob patterns."
853 (cl-assert (directory-name-p dir))
854 (require 'semantic/fw)
855 (grep-compute-defaults)
856 (defvar grep-find-template)
857 (defvar grep-highlight-matches)
858 (let* ((grep-find-template (replace-regexp-in-string "-e " "-E "
859 grep-find-template t t))
860 (grep-highlight-matches nil)
861 (command (xref--rgrep-command (xref--regexp-to-extended regexp)
863 (orig-buffers (buffer-list))
864 (buf (get-buffer-create " *xref-grep*"))
865 (grep-re (caar grep-regexp-alist))
867 (with-current-buffer buf
869 (call-process-shell-command command nil t)
870 (goto-char (point-min))
871 (while (re-search-forward grep-re nil t)
872 (push (cons (string-to-number (match-string 2))
876 (cl-mapcan (lambda (hit) (xref--collect-matches hit regexp))
878 ;; TODO: Same as above.
880 (cl-set-difference (buffer-list) orig-buffers)))))
882 (defun xref--rgrep-command (regexp files dir ignores)
883 (require 'find-dired) ; for `find-name-arg'
884 (defvar grep-find-template)
885 (defvar find-name-arg)
886 (grep-expand-template
889 (concat (shell-quote-argument "(")
890 " " find-name-arg " "
892 #'shell-quote-argument
894 (concat " -o " find-name-arg " "))
896 (shell-quote-argument ")"))
899 (shell-quote-argument "(")
903 (when (string-match-p "/\\'" ignore)
904 (setq ignore (concat ignore "*")))
905 (if (string-match "\\`\\./" ignore)
906 (setq ignore (replace-match dir t t ignore))
907 (unless (string-prefix-p "*" ignore)
908 (setq ignore (concat "*/" ignore))))
909 (shell-quote-argument ignore))
913 (shell-quote-argument ")")
916 (defun xref--regexp-to-extended (str)
917 (replace-regexp-in-string
918 ;; FIXME: Add tests. Move to subr.el, make a public function.
919 ;; Maybe error on Emacs-only constructs.
920 "\\(?:\\\\\\\\\\)*\\(?:\\\\[][]\\)?\\(?:\\[.+?\\]\\|\\(\\\\?[(){}|]\\)\\)"
923 ((not (match-beginning 1))
925 ((eq (length (match-string 1 str)) 2)
926 (concat (substring str 0 (match-beginning 1))
927 (substring (match-string 1 str) 1 2)))
929 (concat (substring str 0 (match-beginning 1))
931 (match-string 1 str)))))
934 (defun xref--collect-matches (hit regexp)
935 (pcase-let* ((`(,line . ,file) hit)
936 (buf (or (find-buffer-visiting file)
937 (semantic-find-file-noselect file))))
938 (with-current-buffer buf
940 (goto-char (point-min))
941 (forward-line (1- line))
942 (let ((line-end (line-end-position))
943 (line-beg (line-beginning-position))
945 (syntax-propertize line-end)
946 ;; FIXME: This results in several lines with the same
947 ;; summary. Solve with composite pattern?
948 (while (re-search-forward regexp line-end t)
949 (let* ((beg-column (- (match-beginning 0) line-beg))
950 (end-column (- (match-end 0) line-beg))
951 (loc (xref-make-file-location file line beg-column))
952 (summary (buffer-substring line-beg line-end)))
953 (add-face-text-property beg-column end-column 'highlight
955 (push (xref-make-match summary loc (- end-column beg-column))
957 (nreverse matches))))))
961 ;;; xref.el ends here