; * etc/NEWS: Fix last change.
[emacs.git] / lisp / progmodes / xref.el
blobdb025d40aa325c3ac02aa0df49cec203be1edb3c
1 ;; xref.el --- Cross-referencing commands -*-lexical-binding:t-*-
3 ;; Copyright (C) 2014-2017 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 <https://www.gnu.org/licenses/>.
20 ;;; Commentary:
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
35 ;; functions:
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
63 ;; choice.
65 ;; See the etags and elisp-mode implementations for full examples.
67 ;;; Code:
69 (require 'cl-lib)
70 (require 'eieio)
71 (require 'ring)
72 (require 'project)
74 (eval-when-compile
75 (require 'semantic/symref)) ;; for hit-lines slot
77 (defgroup xref nil "Cross-referencing commands"
78 :version "25.1"
79 :group 'tools)
82 ;;; Locations
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."
96 nil)
98 (cl-defgeneric xref-match-length (_item)
99 "Return the length of the match."
100 nil)
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 slightly 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
119 (with-current-buffer
120 (or (get-file-buffer file)
121 (let ((find-file-suppress-same-file-warnings t))
122 (find-file-noselect file)))
123 (save-restriction
124 (widen)
125 (save-excursion
126 (goto-char (point-min))
127 (beginning-of-line line)
128 (forward-char column)
129 (point-marker))))))
131 (cl-defmethod xref-location-group ((l xref-file-location))
132 (oref l file))
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)")
169 ;;; Cross-reference
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
181 somewhere.")
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))
207 ;;; API
209 (defvar xref-backend-functions nil
210 "Special hook to find the xref backend for the current context.
211 Each function 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
214 generic functions.")
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)
221 ;;;###autoload
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,
232 return nil.
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."
248 (cl-mapcan
249 (lambda (dir)
250 (xref-collect-references identifier dir))
251 (let ((pr (project-current t)))
252 (append
253 (project-roots pr)
254 (project-external-roots pr)))))
256 (cl-defgeneric xref-backend-apropos (backend pattern)
257 "Find all symbols that match regexp PATTERN.")
259 (cl-defgeneric xref-backend-identifier-at-point (_backend)
260 "Return the relevant identifier at point.
262 The return value must be a string or nil. nil means no
263 identifier at point found.
265 If it's hard to determine the identifier precisely (e.g., because
266 it's a method call on unknown type), the implementation can
267 return a simple string (such as symbol at point) marked with a
268 special text property which e.g. `xref-backend-definitions' would
269 recognize and then delegate the work to an external process."
270 (let ((thing (thing-at-point 'symbol)))
271 (and thing (substring-no-properties thing))))
273 (cl-defgeneric xref-backend-identifier-completion-table (backend)
274 "Returns the completion table for identifiers.")
277 ;;; misc utilities
278 (defun xref--alistify (list key test)
279 "Partition the elements of LIST into an alist.
280 KEY extracts the key from an element and TEST is used to compare
281 keys."
282 (let ((alist '()))
283 (dolist (e list)
284 (let* ((k (funcall key e))
285 (probe (cl-assoc k alist :test test)))
286 (if probe
287 (setcdr probe (cons e (cdr probe)))
288 (push (cons k (list e)) alist))))
289 ;; Put them back in order.
290 (cl-loop for (key . value) in (reverse alist)
291 collect (cons key (reverse value)))))
293 (defun xref--insert-propertized (props &rest strings)
294 "Insert STRINGS with text properties PROPS."
295 (let ((start (point)))
296 (apply #'insert strings)
297 (add-text-properties start (point) props)))
299 (defun xref--search-property (property &optional backward)
300 "Search the next text range where text property PROPERTY is non-nil.
301 Return the value of PROPERTY. If BACKWARD is non-nil, search
302 backward."
303 (let ((next (if backward
304 #'previous-single-char-property-change
305 #'next-single-char-property-change))
306 (start (point))
307 (value nil))
308 (while (progn
309 (goto-char (funcall next (point) property))
310 (not (or (setq value (get-text-property (point) property))
311 (eobp)
312 (bobp)))))
313 (cond (value)
314 (t (goto-char start) nil))))
317 ;;; Marker stack (M-. pushes, M-, pops)
319 (defcustom xref-marker-ring-length 16
320 "Length of the xref marker ring."
321 :type 'integer)
323 (defcustom xref-prompt-for-identifier '(not xref-find-definitions
324 xref-find-definitions-other-window
325 xref-find-definitions-other-frame)
326 "When t, always prompt for the identifier name.
328 When nil, prompt only when there's no value at point we can use,
329 or when the command has been called with the prefix argument.
331 Otherwise, it's a list of xref commands which will prompt
332 anyway (the value at point, if any, will be used as the default).
334 If the list starts with `not', the meaning of the rest of the
335 elements is negated."
336 :type '(choice (const :tag "always" t)
337 (const :tag "auto" nil)
338 (set :menu-tag "command specific" :tag "commands"
339 :value (not)
340 (const :tag "Except" not)
341 (repeat :inline t (symbol :tag "command")))))
343 (defcustom xref-after-jump-hook '(recenter
344 xref-pulse-momentarily)
345 "Functions called after jumping to an xref."
346 :type 'hook)
348 (defcustom xref-after-return-hook '(xref-pulse-momentarily)
349 "Functions called after returning to a pre-jump location."
350 :type 'hook)
352 (defvar xref--marker-ring (make-ring xref-marker-ring-length)
353 "Ring of markers to implement the marker stack.")
355 (defun xref-push-marker-stack (&optional m)
356 "Add point M (defaults to `point-marker') to the marker stack."
357 (ring-insert xref--marker-ring (or m (point-marker))))
359 ;;;###autoload
360 (defun xref-pop-marker-stack ()
361 "Pop back to where \\[xref-find-definitions] was last invoked."
362 (interactive)
363 (let ((ring xref--marker-ring))
364 (when (ring-empty-p ring)
365 (user-error "Marker stack is empty"))
366 (let ((marker (ring-remove ring 0)))
367 (switch-to-buffer (or (marker-buffer marker)
368 (user-error "The marked buffer has been deleted")))
369 (goto-char (marker-position marker))
370 (set-marker marker nil nil)
371 (run-hooks 'xref-after-return-hook))))
373 (defvar xref--current-item nil)
375 (defun xref-pulse-momentarily ()
376 (pcase-let ((`(,beg . ,end)
377 (save-excursion
379 (let ((length (xref-match-length xref--current-item)))
380 (and length (cons (point) (+ (point) length))))
381 (back-to-indentation)
382 (if (eolp)
383 (cons (line-beginning-position) (1+ (point)))
384 (cons (point) (line-end-position)))))))
385 (pulse-momentary-highlight-region beg end 'next-error)))
387 ;; etags.el needs this
388 (defun xref-clear-marker-stack ()
389 "Discard all markers from the marker stack."
390 (let ((ring xref--marker-ring))
391 (while (not (ring-empty-p ring))
392 (let ((marker (ring-remove ring)))
393 (set-marker marker nil nil)))))
395 ;;;###autoload
396 (defun xref-marker-stack-empty-p ()
397 "Return t if the marker stack is empty; nil otherwise."
398 (ring-empty-p xref--marker-ring))
402 (defun xref--goto-char (pos)
403 (cond
404 ((and (<= (point-min) pos) (<= pos (point-max))))
405 (widen-automatically (widen))
406 (t (user-error "Position is outside accessible part of buffer")))
407 (goto-char pos))
409 (defun xref--goto-location (location)
410 "Set buffer and point according to xref-location LOCATION."
411 (let ((marker (xref-location-marker location)))
412 (set-buffer (marker-buffer marker))
413 (xref--goto-char marker)))
415 (defun xref--pop-to-location (item &optional action)
416 "Go to the location of ITEM and display the buffer.
417 ACTION controls how the buffer is displayed:
418 nil -- switch-to-buffer
419 `window' -- pop-to-buffer (other window)
420 `frame' -- pop-to-buffer (other frame)
421 If SELECT is non-nil, select the target window."
422 (let* ((marker (save-excursion
423 (xref-location-marker (xref-item-location item))))
424 (buf (marker-buffer marker)))
425 (cl-ecase action
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.
437 (defconst xref-buffer-name "*xref*"
438 "The name of the buffer to show xrefs.")
440 (defmacro xref--with-dedicated-window (&rest body)
441 `(let* ((xref-w (get-buffer-window xref-buffer-name))
442 (xref-w-dedicated (window-dedicated-p xref-w)))
443 (unwind-protect
444 (progn
445 (when xref-w
446 (set-window-dedicated-p xref-w 'soft))
447 ,@body)
448 (when xref-w
449 (set-window-dedicated-p xref-w xref-w-dedicated)))))
451 (defvar-local xref--original-window-intent nil
452 "Original window-switching intent before xref buffer creation.")
454 (defvar-local xref--original-window nil
455 "The original window this xref buffer was created from.")
457 (defun xref--show-pos-in-buf (pos buf)
458 "Goto and display position POS of buffer BUF in a window.
459 Honor `xref--original-window-intent', run `xref-after-jump-hook'
460 and finally return the window."
461 (let* ((xref-buf (current-buffer))
462 (pop-up-frames
463 (or (eq xref--original-window-intent 'frame)
464 pop-up-frames))
465 (action
466 (cond ((memq
467 xref--original-window-intent
468 '(window frame))
470 ((and
471 (window-live-p xref--original-window)
472 (or (not (window-dedicated-p xref--original-window))
473 (eq (window-buffer xref--original-window) buf)))
474 `(,(lambda (buf _alist)
475 (set-window-buffer xref--original-window buf)
476 xref--original-window))))))
477 (with-selected-window
478 (with-selected-window
479 ;; Just before `display-buffer', place ourselves in the
480 ;; original window to suggest preserving it. Of course, if
481 ;; user has deleted the original window, all bets are off,
482 ;; just use the selected one.
483 (or (and (window-live-p xref--original-window)
484 xref--original-window)
485 (selected-window))
486 (display-buffer buf action))
487 (xref--goto-char pos)
488 (run-hooks 'xref-after-jump-hook)
489 (let ((buf (current-buffer)))
490 (with-current-buffer xref-buf
491 (setq-local other-window-scroll-buffer buf)))
492 (selected-window))))
494 (defun xref--show-location (location &optional select)
495 "Help `xref-show-xref' and `xref-goto-xref' do their job.
496 Go to LOCATION and if SELECT is non-nil select its window. If
497 SELECT is `quit', also quit the *xref* window."
498 (condition-case err
499 (let* ((marker (xref-location-marker location))
500 (buf (marker-buffer marker))
501 (xref-buffer (current-buffer)))
502 (cond (select
503 (if (eq select 'quit) (quit-window nil nil))
504 (with-current-buffer xref-buffer
505 (select-window (xref--show-pos-in-buf marker buf))))
507 (save-selected-window
508 (xref--with-dedicated-window
509 (xref--show-pos-in-buf marker buf))))))
510 (user-error (message (error-message-string err)))))
512 (defun xref-show-location-at-point ()
513 "Display the source of xref at point in the appropriate window, if any."
514 (interactive)
515 (let* ((xref (xref--item-at-point))
516 (xref--current-item xref))
517 (when xref
518 (xref--show-location (xref-item-location xref)))))
520 (defun xref-next-line ()
521 "Move to the next xref and display its source in the appropriate window."
522 (interactive)
523 (xref--search-property 'xref-item)
524 (xref-show-location-at-point))
526 (defun xref-prev-line ()
527 "Move to the previous xref and display its source in the appropriate window."
528 (interactive)
529 (xref--search-property 'xref-item t)
530 (xref-show-location-at-point))
532 (defun xref--item-at-point ()
533 (save-excursion
534 (back-to-indentation)
535 (get-text-property (point) 'xref-item)))
537 (defun xref-goto-xref (&optional quit)
538 "Jump to the xref on the current line and select its window.
539 Non-interactively, non-nil QUIT means to first quit the *xref*
540 buffer."
541 (interactive)
542 (let ((xref (or (xref--item-at-point)
543 (user-error "No reference at point"))))
544 (xref--show-location (xref-item-location xref) (if quit 'quit t))))
546 (defun xref-quit-and-goto-xref ()
547 "Quit *xref* buffer, then jump to xref on current line."
548 (interactive)
549 (xref-goto-xref t))
551 (defun xref-query-replace-in-results (from to)
552 "Perform interactive replacement of FROM with TO in all displayed xrefs.
554 This command interactively replaces FROM with TO in the names of the
555 references displayed in the current *xref* buffer."
556 (interactive
557 (let ((fr (read-regexp "Xref query-replace (regexp)" ".*")))
558 (list fr
559 (read-regexp (format "Xref query-replace (regexp) %s with: " fr)))))
560 (let* (item xrefs iter)
561 (save-excursion
562 (while (setq item (xref--search-property 'xref-item))
563 (when (xref-match-length item)
564 (push item xrefs))))
565 (unwind-protect
566 (progn
567 (goto-char (point-min))
568 (setq iter (xref--buf-pairs-iterator (nreverse xrefs)))
569 (xref--query-replace-1 from to iter))
570 (funcall iter :cleanup))))
572 (defun xref--buf-pairs-iterator (xrefs)
573 (let (chunk-done item next-pair file-buf pairs all-pairs)
574 (lambda (action)
575 (pcase action
576 (:next
577 (when (or xrefs next-pair)
578 (setq chunk-done nil)
579 (when next-pair
580 (setq file-buf (marker-buffer (car next-pair))
581 pairs (list next-pair)
582 next-pair nil))
583 (while (and (not chunk-done)
584 (setq item (pop xrefs)))
585 (save-excursion
586 (let* ((loc (xref-item-location item))
587 (beg (xref-location-marker loc))
588 (end (move-marker (make-marker)
589 (+ beg (xref-match-length item))
590 (marker-buffer beg))))
591 (let ((pair (cons beg end)))
592 (push pair all-pairs)
593 ;; Perform sanity check first.
594 (xref--goto-location loc)
595 (if (xref--outdated-p item
596 (buffer-substring-no-properties
597 (line-beginning-position)
598 (line-end-position)))
599 (message "Search result out of date, skipping")
600 (cond
601 ((null file-buf)
602 (setq file-buf (marker-buffer beg))
603 (push pair pairs))
604 ((equal file-buf (marker-buffer beg))
605 (push pair pairs))
607 (setq chunk-done t
608 next-pair pair))))))))
609 (cons file-buf (nreverse pairs))))
610 (:cleanup
611 (dolist (pair all-pairs)
612 (move-marker (car pair) nil)
613 (move-marker (cdr pair) nil)))))))
615 (defun xref--outdated-p (item line-text)
616 ;; FIXME: The check should probably be a generic function instead of
617 ;; the assumption that all matches contain the full line as summary.
618 (let ((summary (xref-item-summary item))
619 (strip (lambda (s) (if (string-match "\r\\'" s)
620 (substring-no-properties s 0 -1)
621 s))))
622 (not
623 ;; Sometimes buffer contents include ^M, and sometimes Grep
624 ;; output includes it, and they don't always match.
625 (equal (funcall strip line-text)
626 (funcall strip summary)))))
628 ;; FIXME: Write a nicer UI.
629 (defun xref--query-replace-1 (from to iter)
630 (let* ((query-replace-lazy-highlight nil)
631 (continue t)
632 did-it-once buf-pairs pairs
633 current-beg current-end
634 ;; Counteract the "do the next match now" hack in
635 ;; `perform-replace'. And still, it'll report that those
636 ;; matches were "filtered out" at the end.
637 (isearch-filter-predicate
638 (lambda (beg end)
639 (and current-beg
640 (>= beg current-beg)
641 (<= end current-end))))
642 (replace-re-search-function
643 (lambda (from &optional _bound noerror)
644 (let (found pair)
645 (while (and (not found) pairs)
646 (setq pair (pop pairs)
647 current-beg (car pair)
648 current-end (cdr pair))
649 (goto-char current-beg)
650 (when (re-search-forward from current-end noerror)
651 (setq found t)))
652 found))))
653 (while (and continue (setq buf-pairs (funcall iter :next)))
654 (if did-it-once
655 ;; Reuse the same window for subsequent buffers.
656 (switch-to-buffer (car buf-pairs))
657 (xref--with-dedicated-window
658 (pop-to-buffer (car buf-pairs)))
659 (setq did-it-once t))
660 (setq pairs (cdr buf-pairs))
661 (setq continue
662 (perform-replace from to t t nil nil multi-query-replace-map)))
663 (unless did-it-once (user-error "No suitable matches here"))
664 (when (and continue (not buf-pairs))
665 (message "All results processed"))))
667 (defvar xref--xref-buffer-mode-map
668 (let ((map (make-sparse-keymap)))
669 (define-key map (kbd "n") #'xref-next-line)
670 (define-key map (kbd "p") #'xref-prev-line)
671 (define-key map (kbd "r") #'xref-query-replace-in-results)
672 (define-key map (kbd "RET") #'xref-goto-xref)
673 (define-key map (kbd "TAB") #'xref-quit-and-goto-xref)
674 (define-key map (kbd "C-o") #'xref-show-location-at-point)
675 ;; suggested by Johan Claesson "to further reduce finger movement":
676 (define-key map (kbd ".") #'xref-next-line)
677 (define-key map (kbd ",") #'xref-prev-line)
678 map))
680 (define-derived-mode xref--xref-buffer-mode special-mode "XREF"
681 "Mode for displaying cross-references."
682 (setq buffer-read-only t)
683 (setq next-error-function #'xref--next-error-function)
684 (setq next-error-last-buffer (current-buffer)))
686 (defun xref--next-error-function (n reset?)
687 (when reset?
688 (goto-char (point-min)))
689 (let ((backward (< n 0))
690 (n (abs n))
691 (xref nil))
692 (dotimes (_ n)
693 (setq xref (xref--search-property 'xref-item backward)))
694 (cond (xref
695 (xref--show-location (xref-item-location xref) t))
697 (error "No %s xref" (if backward "previous" "next"))))))
699 (defvar xref--button-map
700 (let ((map (make-sparse-keymap)))
701 (define-key map [(control ?m)] #'xref-goto-xref)
702 (define-key map [mouse-1] #'xref-goto-xref)
703 (define-key map [mouse-2] #'xref--mouse-2)
704 map))
706 (defun xref--mouse-2 (event)
707 "Move point to the button and show the xref definition."
708 (interactive "e")
709 (mouse-set-point event)
710 (forward-line 0)
711 (xref--search-property 'xref-item)
712 (xref-show-location-at-point))
714 (defun xref--insert-xrefs (xref-alist)
715 "Insert XREF-ALIST in the current-buffer.
716 XREF-ALIST is of the form ((GROUP . (XREF ...)) ...), where
717 GROUP is a string for decoration purposes and XREF is an
718 `xref-item' object."
719 (require 'compile) ; For the compilation faces.
720 (cl-loop for ((group . xrefs) . more1) on xref-alist
721 for max-line-width =
722 (cl-loop for xref in xrefs
723 maximize (let ((line (xref-location-line
724 (oref xref location))))
725 (length (and line (format "%d" line)))))
726 for line-format = (and max-line-width
727 (format "%%%dd: " max-line-width))
729 (xref--insert-propertized '(face compilation-info) group "\n")
730 (cl-loop for (xref . more2) on xrefs do
731 (with-slots (summary location) xref
732 (let* ((line (xref-location-line location))
733 (prefix
734 (if line
735 (propertize (format line-format line)
736 'face 'compilation-line-number)
737 " ")))
738 (xref--insert-propertized
739 (list 'xref-item xref
740 ;; 'face 'font-lock-keyword-face
741 'mouse-face 'highlight
742 'keymap xref--button-map
743 'help-echo
744 (concat "mouse-2: display in another window, "
745 "RET or mouse-1: follow reference"))
746 prefix summary)))
747 (insert "\n"))))
749 (defun xref--analyze (xrefs)
750 "Find common filenames in XREFS.
751 Return an alist of the form ((FILENAME . (XREF ...)) ...)."
752 (xref--alistify xrefs
753 (lambda (x)
754 (xref-location-group (xref-item-location x)))
755 #'equal))
757 (defun xref--show-xref-buffer (xrefs alist)
758 (let ((xref-alist (xref--analyze xrefs)))
759 (with-current-buffer (get-buffer-create xref-buffer-name)
760 (setq buffer-undo-list nil)
761 (let ((inhibit-read-only t)
762 (buffer-undo-list t))
763 (erase-buffer)
764 (xref--insert-xrefs xref-alist)
765 (xref--xref-buffer-mode)
766 (pop-to-buffer (current-buffer))
767 (goto-char (point-min))
768 (setq xref--original-window (assoc-default 'window alist)
769 xref--original-window-intent (assoc-default 'display-action alist))
770 (current-buffer)))))
773 ;; This part of the UI seems fairly uncontroversial: it reads the
774 ;; identifier and deals with the single definition case.
775 ;; (FIXME: do we really want this case to be handled like that in
776 ;; "find references" and "find regexp searches"?)
778 ;; The controversial multiple definitions case is handed off to
779 ;; xref-show-xrefs-function.
781 (defvar xref-show-xrefs-function 'xref--show-xref-buffer
782 "Function to display a list of xrefs.")
784 (defvar xref--read-identifier-history nil)
786 (defvar xref--read-pattern-history nil)
788 (defun xref--show-xrefs (xrefs display-action &optional always-show-list)
789 (cond
790 ((and (not (cdr xrefs)) (not always-show-list))
791 (xref-push-marker-stack)
792 (xref--pop-to-location (car xrefs) display-action))
794 (xref-push-marker-stack)
795 (funcall xref-show-xrefs-function xrefs
796 `((window . ,(selected-window))
797 (display-action . ,display-action))))))
799 (defun xref--prompt-p (command)
800 (or (eq xref-prompt-for-identifier t)
801 (if (eq (car xref-prompt-for-identifier) 'not)
802 (not (memq command (cdr xref-prompt-for-identifier)))
803 (memq command xref-prompt-for-identifier))))
805 (defun xref--read-identifier (prompt)
806 "Return the identifier at point or read it from the minibuffer."
807 (let* ((backend (xref-find-backend))
808 (id (xref-backend-identifier-at-point backend)))
809 (cond ((or current-prefix-arg
810 (not id)
811 (xref--prompt-p this-command))
812 (completing-read (if id
813 (format "%s (default %s): "
814 (substring prompt 0 (string-match
815 "[ :]+\\'" prompt))
817 prompt)
818 (xref-backend-identifier-completion-table backend)
819 nil nil nil
820 'xref--read-identifier-history id))
821 (t id))))
824 ;;; Commands
826 (defun xref--find-xrefs (input kind arg display-action)
827 (let ((xrefs (funcall (intern (format "xref-backend-%s" kind))
828 (xref-find-backend)
829 arg)))
830 (unless xrefs
831 (user-error "No %s found for: %s" (symbol-name kind) input))
832 (xref--show-xrefs xrefs display-action)))
834 (defun xref--find-definitions (id display-action)
835 (xref--find-xrefs id 'definitions id display-action))
837 ;;;###autoload
838 (defun xref-find-definitions (identifier)
839 "Find the definition of the identifier at point.
840 With prefix argument or when there's no identifier at point,
841 prompt for it.
843 If sufficient information is available to determine a unique
844 definition for IDENTIFIER, display it in the selected window.
845 Otherwise, display the list of the possible definitions in a
846 buffer where the user can select from the list."
847 (interactive (list (xref--read-identifier "Find definitions of: ")))
848 (xref--find-definitions identifier nil))
850 ;;;###autoload
851 (defun xref-find-definitions-other-window (identifier)
852 "Like `xref-find-definitions' but switch to the other window."
853 (interactive (list (xref--read-identifier "Find definitions of: ")))
854 (xref--find-definitions identifier 'window))
856 ;;;###autoload
857 (defun xref-find-definitions-other-frame (identifier)
858 "Like `xref-find-definitions' but switch to the other frame."
859 (interactive (list (xref--read-identifier "Find definitions of: ")))
860 (xref--find-definitions identifier 'frame))
862 ;;;###autoload
863 (defun xref-find-references (identifier)
864 "Find references to the identifier at point.
865 With prefix argument, prompt for the identifier."
866 (interactive (list (xref--read-identifier "Find references of: ")))
867 (xref--find-xrefs identifier 'references identifier nil))
869 (declare-function apropos-parse-pattern "apropos" (pattern))
871 ;;;###autoload
872 (defun xref-find-apropos (pattern)
873 "Find all meaningful symbols that match PATTERN.
874 The argument has the same meaning as in `apropos'."
875 (interactive (list (read-string
876 "Search for pattern (word list or regexp): "
877 nil 'xref--read-pattern-history)))
878 (require 'apropos)
879 (xref--find-xrefs pattern 'apropos
880 (apropos-parse-pattern
881 (if (string-equal (regexp-quote pattern) pattern)
882 ;; Split into words
883 (or (split-string pattern "[ \t]+" t)
884 (user-error "No word list given"))
885 pattern))
886 nil))
889 ;;; Key bindings
891 ;;;###autoload (define-key esc-map "." #'xref-find-definitions)
892 ;;;###autoload (define-key esc-map "," #'xref-pop-marker-stack)
893 ;;;###autoload (define-key esc-map "?" #'xref-find-references)
894 ;;;###autoload (define-key esc-map [?\C-.] #'xref-find-apropos)
895 ;;;###autoload (define-key ctl-x-4-map "." #'xref-find-definitions-other-window)
896 ;;;###autoload (define-key ctl-x-5-map "." #'xref-find-definitions-other-frame)
899 ;;; Helper functions
901 (defvar xref-etags-mode--saved nil)
903 (define-minor-mode xref-etags-mode
904 "Minor mode to make xref use etags again.
906 Certain major modes install their own mechanisms for listing
907 identifiers and navigation. Turn this on to undo those settings
908 and just use etags."
909 :lighter ""
910 (if xref-etags-mode
911 (progn
912 (setq xref-etags-mode--saved xref-backend-functions)
913 (kill-local-variable 'xref-backend-functions))
914 (setq-local xref-backend-functions xref-etags-mode--saved)))
916 (declare-function semantic-symref-instantiate "semantic/symref")
917 (declare-function semantic-symref-perform-search "semantic/symref")
918 (declare-function grep-expand-template "grep")
919 (defvar ede-minor-mode) ;; ede.el
921 (defun xref-collect-references (symbol dir)
922 "Collect references to SYMBOL inside DIR.
923 This function uses the Semantic Symbol Reference API, see
924 `semantic-symref-tool-alist' for details on which tools are used,
925 and when."
926 (cl-assert (directory-name-p dir))
927 (require 'semantic/symref)
928 (defvar semantic-symref-tool)
930 ;; Some symref backends use `ede-project-root-directory' as the root
931 ;; directory for the search, rather than `default-directory'. Since
932 ;; the caller has specified `dir', we bind `ede-minor-mode' to nil
933 ;; to force the backend to use `default-directory'.
934 (let* ((ede-minor-mode nil)
935 (default-directory dir)
936 ;; FIXME: Remove CScope and Global from the recognized tools?
937 ;; The current implementations interpret the symbol search as
938 ;; "find all calls to the given function", but not function
939 ;; definition. And they return nothing when passed a variable
940 ;; name, even a global one.
941 (semantic-symref-tool 'detect)
942 (case-fold-search nil)
943 (inst (semantic-symref-instantiate :searchfor symbol
944 :searchtype 'symbol
945 :searchscope 'subdirs
946 :resulttype 'line-and-text)))
947 (xref--convert-hits (semantic-symref-perform-search inst)
948 (format "\\_<%s\\_>" (regexp-quote symbol)))))
950 ;;;###autoload
951 (defun xref-collect-matches (regexp files dir ignores)
952 "Collect matches for REGEXP inside FILES in DIR.
953 FILES is a string with glob patterns separated by spaces.
954 IGNORES is a list of glob patterns."
955 ;; DIR can also be a regular file for now; let's not advertise that.
956 (require 'semantic/fw)
957 (grep-compute-defaults)
958 (defvar grep-find-template)
959 (defvar grep-highlight-matches)
960 (pcase-let*
961 ((grep-find-template (replace-regexp-in-string "<C>" "<C> -E"
962 grep-find-template t t))
963 (grep-highlight-matches nil)
964 ;; TODO: Sanitize the regexp to remove Emacs-specific terms,
965 ;; so that Grep can search for the "relaxed" version. Can we
966 ;; do that reliably enough, without creating false negatives?
967 (command (xref--rgrep-command (xref--regexp-to-extended regexp)
968 files
969 (expand-file-name dir)
970 ignores))
971 (def default-directory)
972 (buf (get-buffer-create " *xref-grep*"))
973 (`(,grep-re ,file-group ,line-group . ,_) (car grep-regexp-alist))
974 (status nil)
975 (hits nil))
976 (with-current-buffer buf
977 (erase-buffer)
978 (setq default-directory def)
979 (setq status
980 (call-process-shell-command command nil t))
981 (goto-char (point-min))
982 ;; Can't use the exit status: Grep exits with 1 to mean "no
983 ;; matches found". Find exits with 1 if any of the invocations
984 ;; exit with non-zero. "No matches" and "Grep program not found"
985 ;; are all the same to it.
986 (when (and (/= (point-min) (point-max))
987 (not (looking-at grep-re)))
988 (user-error "Search failed with status %d: %s" status (buffer-string)))
989 (while (re-search-forward grep-re nil t)
990 (push (list (string-to-number (match-string line-group))
991 (match-string file-group)
992 (buffer-substring-no-properties (point) (line-end-position)))
993 hits)))
994 (xref--convert-hits (nreverse hits) regexp)))
996 (defun xref--rgrep-command (regexp files dir ignores)
997 (require 'find-dired) ; for `find-name-arg'
998 (defvar grep-find-template)
999 (defvar find-name-arg)
1000 ;; `shell-quote-argument' quotes the tilde as well.
1001 (cl-assert (not (string-match-p "\\`~" dir)))
1002 (grep-expand-template
1003 grep-find-template
1004 regexp
1005 (concat (shell-quote-argument "(")
1006 " " find-name-arg " "
1007 (mapconcat
1008 #'shell-quote-argument
1009 (split-string files)
1010 (concat " -o " find-name-arg " "))
1012 (shell-quote-argument ")"))
1013 (shell-quote-argument dir)
1014 (xref--find-ignores-arguments ignores dir)))
1016 (defun xref--find-ignores-arguments (ignores dir)
1017 "Convert IGNORES and DIR to a list of arguments for 'find'.
1018 IGNORES is a list of glob patterns. DIR is an absolute
1019 directory, used as the root of the ignore globs."
1020 (cl-assert (not (string-match-p "\\`~" dir)))
1021 (when ignores
1022 (concat
1023 (shell-quote-argument "(")
1024 " -path "
1025 (mapconcat
1026 (lambda (ignore)
1027 (when (string-match-p "/\\'" ignore)
1028 (setq ignore (concat ignore "*")))
1029 (if (string-match "\\`\\./" ignore)
1030 (setq ignore (replace-match dir t t ignore))
1031 (unless (string-prefix-p "*" ignore)
1032 (setq ignore (concat "*/" ignore))))
1033 (shell-quote-argument ignore))
1034 ignores
1035 " -o -path ")
1037 (shell-quote-argument ")")
1038 " -prune -o ")))
1040 (defun xref--regexp-to-extended (str)
1041 (replace-regexp-in-string
1042 ;; FIXME: Add tests. Move to subr.el, make a public function.
1043 ;; Maybe error on Emacs-only constructs.
1044 "\\(?:\\\\\\\\\\)*\\(?:\\\\[][]\\)?\\(?:\\[.+?\\]\\|\\(\\\\?[(){}|]\\)\\)"
1045 (lambda (str)
1046 (cond
1047 ((not (match-beginning 1))
1048 str)
1049 ((eq (length (match-string 1 str)) 2)
1050 (concat (substring str 0 (match-beginning 1))
1051 (substring (match-string 1 str) 1 2)))
1053 (concat (substring str 0 (match-beginning 1))
1054 "\\"
1055 (match-string 1 str)))))
1056 str t t))
1058 (defun xref--regexp-syntax-dependent-p (str)
1059 "Return non-nil when STR depends on the buffer's syntax.
1060 Such as the current syntax table and the applied syntax properties."
1061 (let ((case-fold-search nil))
1062 (string-match-p (rx
1063 (or string-start (not (in ?\\)))
1064 (0+ (= 2 ?\\))
1066 (in ?b ?B ?< ?> ?w ?W ?_ ?s ?S))
1067 str)))
1069 (defvar xref--last-visiting-buffer nil)
1070 (defvar xref--temp-buffer-file-name nil)
1072 (defun xref--convert-hits (hits regexp)
1073 (let (xref--last-visiting-buffer
1074 (tmp-buffer (generate-new-buffer " *xref-temp*")))
1075 (unwind-protect
1076 (cl-mapcan (lambda (hit) (xref--collect-matches hit regexp tmp-buffer))
1077 hits)
1078 (kill-buffer tmp-buffer))))
1080 (defun xref--collect-matches (hit regexp tmp-buffer)
1081 (pcase-let* ((`(,line ,file ,text) hit)
1082 (buf (xref--find-buffer-visiting file))
1083 (syntax-needed (xref--regexp-syntax-dependent-p regexp)))
1084 (if buf
1085 (with-current-buffer buf
1086 (save-excursion
1087 (goto-char (point-min))
1088 (forward-line (1- line))
1089 (xref--collect-matches-1 regexp file line
1090 (line-beginning-position)
1091 (line-end-position)
1092 syntax-needed)))
1093 ;; Using the temporary buffer is both a performance and a buffer
1094 ;; management optimization.
1095 (with-current-buffer tmp-buffer
1096 (erase-buffer)
1097 (when (and syntax-needed
1098 (not (equal file xref--temp-buffer-file-name)))
1099 (insert-file-contents file nil 0 200)
1100 ;; Can't (setq-local delay-mode-hooks t) because of
1101 ;; bug#23272, but the performance penalty seems minimal.
1102 (let ((buffer-file-name file)
1103 (inhibit-message t)
1104 message-log-max)
1105 (ignore-errors
1106 (set-auto-mode t)))
1107 (setq-local xref--temp-buffer-file-name file)
1108 (setq-local inhibit-read-only t)
1109 (erase-buffer))
1110 (insert text)
1111 (goto-char (point-min))
1112 (xref--collect-matches-1 regexp file line
1113 (point)
1114 (point-max)
1115 syntax-needed)))))
1117 (defun xref--collect-matches-1 (regexp file line line-beg line-end syntax-needed)
1118 (let (matches)
1119 (when syntax-needed
1120 (syntax-propertize line-end))
1121 ;; FIXME: This results in several lines with the same
1122 ;; summary. Solve with composite pattern?
1123 (while (and
1124 ;; REGEXP might match an empty string. Or line.
1125 (or (null matches)
1126 (> (point) line-beg))
1127 (re-search-forward regexp line-end t))
1128 (let* ((beg-column (- (match-beginning 0) line-beg))
1129 (end-column (- (match-end 0) line-beg))
1130 (loc (xref-make-file-location file line beg-column))
1131 (summary (buffer-substring line-beg line-end)))
1132 (add-face-text-property beg-column end-column 'highlight
1133 t summary)
1134 (push (xref-make-match summary loc (- end-column beg-column))
1135 matches)))
1136 (nreverse matches)))
1138 (defun xref--find-buffer-visiting (file)
1139 (unless (equal (car xref--last-visiting-buffer) file)
1140 (setq xref--last-visiting-buffer
1141 (cons file (find-buffer-visiting file))))
1142 (cdr xref--last-visiting-buffer))
1144 (provide 'xref)
1146 ;;; xref.el ends here