]> code.delx.au - gnu-emacs/blob - lisp/progmodes/xref.el
00f348929ef636bf33f14d06f660f7eda14f7678
[gnu-emacs] / lisp / progmodes / xref.el
1 ;; xref.el --- Cross-referencing commands -*-lexical-binding:t-*-
2
3 ;; Copyright (C) 2014-2015 Free Software Foundation, Inc.
4
5 ;; This file is part of GNU Emacs.
6
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.
11
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.
16
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/>.
19
20 ;;; Commentary:
21
22 ;; This file provides a somewhat generic infrastructure for cross
23 ;; referencing commands, in particular "find-definition".
24 ;;
25 ;; Some part of the functionality must be implemented in a language
26 ;; dependent way and that's done by defining an xref backend.
27 ;;
28 ;; That consists of a constructor function, which should return a
29 ;; backend value, and a set of implementations for the generic
30 ;; functions:
31 ;;
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.
36 ;;
37 ;; A major mode would normally use `add-hook' to add the backend
38 ;; constructor to `xref-backend-functions'.
39 ;;
40 ;; The last three methods operate with "xref" and "location" values.
41 ;;
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'.
47 ;;
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.
52 ;;
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
58 ;; choice.
59 ;;
60 ;; See the etags and elisp-mode implementations for full examples.
61
62 ;;; Code:
63
64 (require 'cl-lib)
65 (require 'eieio)
66 (require 'ring)
67 (require 'pcase)
68 (require 'project)
69
70 (eval-when-compile
71 (require 'semantic/symref)) ;; for hit-lines slot
72
73 (defgroup xref nil "Cross-referencing commands"
74 :group 'tools)
75
76 \f
77 ;;; Locations
78
79 (defclass xref-location () ()
80 :documentation "A location represents a position in a file or buffer.")
81
82 (cl-defgeneric xref-location-marker (location)
83 "Return the marker for LOCATION.")
84
85 (cl-defgeneric xref-location-group (location)
86 "Return a string used to group a set of locations.
87 This is typically the filename.")
88
89 (cl-defgeneric xref-location-line (_location)
90 "Return the line number corresponding to the location."
91 nil)
92
93 (cl-defgeneric xref-match-length (_item)
94 "Return the length of the match."
95 nil)
96
97 ;;;; Commonly needed location classes are defined here:
98
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.")
107
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))
111
112 (cl-defmethod xref-location-marker ((l xref-file-location))
113 (with-slots (file line column) l
114 (with-current-buffer
115 (or (get-file-buffer file)
116 (let ((find-file-suppress-same-file-warnings t))
117 (find-file-noselect file)))
118 (save-restriction
119 (widen)
120 (save-excursion
121 (goto-char (point-min))
122 (beginning-of-line line)
123 (forward-char column)
124 (point-marker))))))
125
126 (cl-defmethod xref-location-group ((l xref-file-location))
127 (oref l file))
128
129 (defclass xref-buffer-location (xref-location)
130 ((buffer :type buffer :initarg :buffer)
131 (position :type fixnum :initarg :position)))
132
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))
136
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))))
141
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)))))
146
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.")
153
154 (defun xref-make-bogus-location (message)
155 "Create and return a new `xref-bogus-location'."
156 (make-instance 'xref-bogus-location :message message))
157
158 (cl-defmethod xref-location-marker ((l xref-bogus-location))
159 (user-error "%s" (oref l message)))
160
161 (cl-defmethod xref-location-group ((_ xref-bogus-location)) "(No location)")
162
163 \f
164 ;;; Cross-reference
165
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
176 somewhere.")
177
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))
183
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.")
192
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))
200
201 \f
202 ;;; API
203
204 (defvar xref-backend-functions nil
205 "Special hook to find the xref backend for the current context.
206 Each functions on this hook is called in turn with no arguments
207 and should return either nil to mean that it is not applicable,
208 or an xref backend, which is a value to be used to dispatch the
209 generic functions.")
210
211 ;; We make the etags backend the default for now, until something
212 ;; better comes along. Use APPEND so that any `add-hook' calls made
213 ;; before this package is loaded put new items before this one.
214 (add-hook 'xref-backend-functions #'etags--xref-backend t)
215
216 ;;;###autoload
217 (defun xref-find-backend ()
218 (run-hook-with-args-until-success 'xref-backend-functions))
219
220 (cl-defgeneric xref-backend-definitions (backend identifier)
221 "Find definitions of IDENTIFIER.
222
223 The result must be a list of xref objects. If IDENTIFIER
224 contains sufficient information to determine a unique definition,
225 return only that definition. If there are multiple possible
226 definitions, return all of them. If no definitions can be found,
227 return nil.
228
229 IDENTIFIER can be any string returned by
230 `xref-backend-identifier-at-point', or from the table returned by
231 `xref-backend-identifier-completion-table'.
232
233 To create an xref object, call `xref-make'.")
234
235 (cl-defgeneric xref-backend-references (_backend identifier)
236 "Find references of IDENTIFIER.
237 The result must be a list of xref objects. If no references can
238 be found, return nil.
239
240 The default implementation uses `semantic-symref-tool-alist' to
241 find a search tool; by default, this uses \"find | grep\" in the
242 `project-current' roots."
243 (cl-mapcan
244 (lambda (dir)
245 (xref-collect-references identifier dir))
246 (let ((pr (project-current t)))
247 (append
248 (project-roots pr)
249 (project-external-roots pr)))))
250
251 (cl-defgeneric xref-backend-apropos (backend pattern)
252 "Find all symbols that match PATTERN.
253 PATTERN is a regexp")
254
255 (cl-defgeneric xref-backend-identifier-at-point (_backend)
256 "Return the relevant identifier at point.
257
258 The return value must be a string or nil. nil means no
259 identifier at point found.
260
261 If it's hard to determine the identifier precisely (e.g., because
262 it's a method call on unknown type), the implementation can
263 return a simple string (such as symbol at point) marked with a
264 special text property which e.g. `xref-backend-definitions' would
265 recognize and then delegate the work to an external process."
266 (let ((thing (thing-at-point 'symbol)))
267 (and thing (substring-no-properties thing))))
268
269 (cl-defgeneric xref-backend-identifier-completion-table (backend)
270 "Returns the completion table for identifiers.")
271
272 \f
273 ;;; misc utilities
274 (defun xref--alistify (list key test)
275 "Partition the elements of LIST into an alist.
276 KEY extracts the key from an element and TEST is used to compare
277 keys."
278 (let ((alist '()))
279 (dolist (e list)
280 (let* ((k (funcall key e))
281 (probe (cl-assoc k alist :test test)))
282 (if probe
283 (setcdr probe (cons e (cdr probe)))
284 (push (cons k (list e)) alist))))
285 ;; Put them back in order.
286 (cl-loop for (key . value) in (reverse alist)
287 collect (cons key (reverse value)))))
288
289 (defun xref--insert-propertized (props &rest strings)
290 "Insert STRINGS with text properties PROPS."
291 (let ((start (point)))
292 (apply #'insert strings)
293 (add-text-properties start (point) props)))
294
295 (defun xref--search-property (property &optional backward)
296 "Search the next text range where text property PROPERTY is non-nil.
297 Return the value of PROPERTY. If BACKWARD is non-nil, search
298 backward."
299 (let ((next (if backward
300 #'previous-single-char-property-change
301 #'next-single-char-property-change))
302 (start (point))
303 (value nil))
304 (while (progn
305 (goto-char (funcall next (point) property))
306 (not (or (setq value (get-text-property (point) property))
307 (eobp)
308 (bobp)))))
309 (cond (value)
310 (t (goto-char start) nil))))
311
312 \f
313 ;;; Marker stack (M-. pushes, M-, pops)
314
315 (defcustom xref-marker-ring-length 16
316 "Length of the xref marker ring."
317 :type 'integer)
318
319 (defcustom xref-prompt-for-identifier '(not xref-find-definitions
320 xref-find-definitions-other-window
321 xref-find-definitions-other-frame)
322 "When t, always prompt for the identifier name.
323
324 When nil, prompt only when there's no value at point we can use,
325 or when the command has been called with the prefix argument.
326
327 Otherwise, it's a list of xref commands which will prompt
328 anyway (the value at point, if any, will be used as the default).
329
330 If the list starts with `not', the meaning of the rest of the
331 elements is negated."
332 :type '(choice (const :tag "always" t)
333 (const :tag "auto" nil)
334 (set :menu-tag "command specific" :tag "commands"
335 :value (not)
336 (const :tag "Except" not)
337 (repeat :inline t (symbol :tag "command")))))
338
339 (defcustom xref-after-jump-hook '(recenter
340 xref-pulse-momentarily)
341 "Functions called after jumping to an xref."
342 :type 'hook)
343
344 (defcustom xref-after-return-hook '(xref-pulse-momentarily)
345 "Functions called after returning to a pre-jump location."
346 :type 'hook)
347
348 (defvar xref--marker-ring (make-ring xref-marker-ring-length)
349 "Ring of markers to implement the marker stack.")
350
351 (defun xref-push-marker-stack (&optional m)
352 "Add point M (defaults to `point-marker') to the marker stack."
353 (ring-insert xref--marker-ring (or m (point-marker))))
354
355 ;;;###autoload
356 (defun xref-pop-marker-stack ()
357 "Pop back to where \\[xref-find-definitions] was last invoked."
358 (interactive)
359 (let ((ring xref--marker-ring))
360 (when (ring-empty-p ring)
361 (user-error "Marker stack is empty"))
362 (let ((marker (ring-remove ring 0)))
363 (switch-to-buffer (or (marker-buffer marker)
364 (user-error "The marked buffer has been deleted")))
365 (goto-char (marker-position marker))
366 (set-marker marker nil nil)
367 (run-hooks 'xref-after-return-hook))))
368
369 (defvar xref--current-item nil)
370
371 (defun xref-pulse-momentarily ()
372 (pcase-let ((`(,beg . ,end)
373 (save-excursion
374 (or
375 (let ((length (xref-match-length xref--current-item)))
376 (and length (cons (point) (+ (point) length))))
377 (back-to-indentation)
378 (if (eolp)
379 (cons (line-beginning-position) (1+ (point)))
380 (cons (point) (line-end-position)))))))
381 (pulse-momentary-highlight-region beg end 'next-error)))
382
383 ;; etags.el needs this
384 (defun xref-clear-marker-stack ()
385 "Discard all markers from the marker stack."
386 (let ((ring xref--marker-ring))
387 (while (not (ring-empty-p ring))
388 (let ((marker (ring-remove ring)))
389 (set-marker marker nil nil)))))
390
391 ;;;###autoload
392 (defun xref-marker-stack-empty-p ()
393 "Return t if the marker stack is empty; nil otherwise."
394 (ring-empty-p xref--marker-ring))
395
396 \f
397
398 (defun xref--goto-char (pos)
399 (cond
400 ((and (<= (point-min) pos) (<= pos (point-max))))
401 (widen-automatically (widen))
402 (t (user-error "Position is outside accessible part of buffer")))
403 (goto-char pos))
404
405 (defun xref--goto-location (location)
406 "Set buffer and point according to xref-location LOCATION."
407 (let ((marker (xref-location-marker location)))
408 (set-buffer (marker-buffer marker))
409 (xref--goto-char marker)))
410
411 (defun xref--pop-to-location (item &optional window)
412 "Go to the location of ITEM and display the buffer.
413 WINDOW controls how the buffer is displayed:
414 nil -- switch-to-buffer
415 `window' -- pop-to-buffer (other window)
416 `frame' -- pop-to-buffer (other frame)"
417 (let* ((marker (save-excursion
418 (xref-location-marker (xref-item-location item))))
419 (buf (marker-buffer marker)))
420 (cl-ecase window
421 ((nil) (switch-to-buffer buf))
422 (window (pop-to-buffer buf t))
423 (frame (let ((pop-up-frames t)) (pop-to-buffer buf t))))
424 (xref--goto-char marker))
425 (let ((xref--current-item item))
426 (run-hooks 'xref-after-jump-hook)))
427
428 \f
429 ;;; XREF buffer (part of the UI)
430
431 ;; The xref buffer is used to display a set of xrefs.
432
433 (defvar-local xref--display-history nil
434 "List of pairs (BUFFER . WINDOW), for temporarily displayed buffers.")
435
436 (defun xref--save-to-history (buf win)
437 (let ((restore (window-parameter win 'quit-restore)))
438 ;; Save the new entry if the window displayed another buffer
439 ;; previously.
440 (when (and restore (not (eq (car restore) 'same)))
441 (push (cons buf win) xref--display-history))))
442
443 (defun xref--display-position (pos other-window buf)
444 ;; Show the location, but don't hijack focus.
445 (let ((xref-buf (current-buffer)))
446 (with-selected-window (display-buffer buf other-window)
447 (xref--goto-char pos)
448 (run-hooks 'xref-after-jump-hook)
449 (let ((buf (current-buffer))
450 (win (selected-window)))
451 (with-current-buffer xref-buf
452 (setq-local other-window-scroll-buffer buf)
453 (xref--save-to-history buf win))))))
454
455 (defun xref--show-location (location)
456 (condition-case err
457 (let* ((marker (xref-location-marker location))
458 (buf (marker-buffer marker)))
459 (xref--display-position marker t buf))
460 (user-error (message (error-message-string err)))))
461
462 (defun xref-show-location-at-point ()
463 "Display the source of xref at point in the other window, if any."
464 (interactive)
465 (let* ((xref (xref--item-at-point))
466 (xref--current-item xref))
467 (when xref
468 (xref--show-location (xref-item-location xref)))))
469
470 (defun xref-next-line ()
471 "Move to the next xref and display its source in the other window."
472 (interactive)
473 (xref--search-property 'xref-item)
474 (xref-show-location-at-point))
475
476 (defun xref-prev-line ()
477 "Move to the previous xref and display its source in the other window."
478 (interactive)
479 (xref--search-property 'xref-item t)
480 (xref-show-location-at-point))
481
482 (defun xref--item-at-point ()
483 (save-excursion
484 (back-to-indentation)
485 (get-text-property (point) 'xref-item)))
486
487 (defvar-local xref--window nil
488 "ACTION argument to call `display-buffer' with.")
489
490 (defun xref-goto-xref ()
491 "Jump to the xref on the current line and bury the xref buffer."
492 (interactive)
493 (let ((xref (or (xref--item-at-point)
494 (user-error "No reference at point")))
495 (window xref--window))
496 (xref-quit)
497 (xref--pop-to-location xref window)))
498
499 (defun xref-query-replace (from to)
500 "Perform interactive replacement in all current matches."
501 (interactive
502 (list (read-regexp "Query replace regexp in matches" ".*")
503 (read-regexp "Replace with: ")))
504 (let (pairs item)
505 (unwind-protect
506 (progn
507 (save-excursion
508 (goto-char (point-min))
509 (while (setq item (xref--search-property 'xref-item))
510 (when (xref-match-length item)
511 (save-excursion
512 (let* ((loc (xref-item-location item))
513 (beg (xref-location-marker loc))
514 (end (move-marker (make-marker)
515 (+ beg (xref-match-length item))
516 (marker-buffer beg))))
517 ;; Perform sanity check first.
518 (xref--goto-location loc)
519 ;; FIXME: The check should probably be a generic
520 ;; function, instead of the assumption that all
521 ;; matches contain the full line as summary.
522 ;; TODO: Offer to re-scan otherwise.
523 (unless (equal (buffer-substring-no-properties
524 (line-beginning-position)
525 (line-end-position))
526 (xref-item-summary item))
527 (user-error "Search results out of date"))
528 (push (cons beg end) pairs)))))
529 (setq pairs (nreverse pairs)))
530 (unless pairs (user-error "No suitable matches here"))
531 (xref--query-replace-1 from to pairs))
532 (dolist (pair pairs)
533 (move-marker (car pair) nil)
534 (move-marker (cdr pair) nil)))))
535
536 ;; FIXME: Write a nicer UI.
537 (defun xref--query-replace-1 (from to pairs)
538 (let* ((query-replace-lazy-highlight nil)
539 current-beg current-end current-buf
540 ;; Counteract the "do the next match now" hack in
541 ;; `perform-replace'. And still, it'll report that those
542 ;; matches were "filtered out" at the end.
543 (isearch-filter-predicate
544 (lambda (beg end)
545 (and current-beg
546 (eq (current-buffer) current-buf)
547 (>= beg current-beg)
548 (<= end current-end))))
549 (replace-re-search-function
550 (lambda (from &optional _bound noerror)
551 (let (found pair)
552 (while (and (not found) pairs)
553 (setq pair (pop pairs)
554 current-beg (car pair)
555 current-end (cdr pair)
556 current-buf (marker-buffer current-beg))
557 (pop-to-buffer current-buf)
558 (goto-char current-beg)
559 (when (re-search-forward from current-end noerror)
560 (setq found t)))
561 found))))
562 ;; FIXME: Despite this being a multi-buffer replacement, `N'
563 ;; doesn't work, because we're not using
564 ;; `multi-query-replace-map', and it would expect the below
565 ;; function to be called once per buffer.
566 (perform-replace from to t t nil)))
567
568 (defvar xref--xref-buffer-mode-map
569 (let ((map (make-sparse-keymap)))
570 (define-key map [remap quit-window] #'xref-quit)
571 (define-key map (kbd "n") #'xref-next-line)
572 (define-key map (kbd "p") #'xref-prev-line)
573 (define-key map (kbd "r") #'xref-query-replace)
574 (define-key map (kbd "RET") #'xref-goto-xref)
575 (define-key map (kbd "C-o") #'xref-show-location-at-point)
576 ;; suggested by Johan Claesson "to further reduce finger movement":
577 (define-key map (kbd ".") #'xref-next-line)
578 (define-key map (kbd ",") #'xref-prev-line)
579 map))
580
581 (define-derived-mode xref--xref-buffer-mode special-mode "XREF"
582 "Mode for displaying cross-references."
583 (setq buffer-read-only t)
584 (setq next-error-function #'xref--next-error-function)
585 (setq next-error-last-buffer (current-buffer)))
586
587 (defun xref--next-error-function (n reset?)
588 (when reset?
589 (goto-char (point-min)))
590 (let ((backward (< n 0))
591 (n (abs n))
592 (xref nil))
593 (dotimes (_ n)
594 (setq xref (xref--search-property 'xref-item backward)))
595 (cond (xref
596 (xref--pop-to-location xref))
597 (t
598 (error "No %s xref" (if backward "previous" "next"))))))
599
600 (defun xref-quit (&optional kill)
601 "Bury temporarily displayed buffers, then quit the current window.
602
603 If KILL is non-nil, also kill the current buffer.
604
605 The buffers that the user has otherwise interacted with in the
606 meantime are preserved."
607 (interactive "P")
608 (let ((window (selected-window))
609 (history xref--display-history))
610 (setq xref--display-history nil)
611 (pcase-dolist (`(,buf . ,win) history)
612 (when (and (window-live-p win)
613 (eq buf (window-buffer win)))
614 (quit-window nil win)))
615 (quit-window kill window)))
616
617 (defconst xref-buffer-name "*xref*"
618 "The name of the buffer to show xrefs.")
619
620 (defvar xref--button-map
621 (let ((map (make-sparse-keymap)))
622 (define-key map [(control ?m)] #'xref-goto-xref)
623 (define-key map [mouse-1] #'xref-goto-xref)
624 (define-key map [mouse-2] #'xref--mouse-2)
625 map))
626
627 (defun xref--mouse-2 (event)
628 "Move point to the button and show the xref definition."
629 (interactive "e")
630 (mouse-set-point event)
631 (forward-line 0)
632 (xref--search-property 'xref-item)
633 (xref-show-location-at-point))
634
635 (defun xref--insert-xrefs (xref-alist)
636 "Insert XREF-ALIST in the current-buffer.
637 XREF-ALIST is of the form ((GROUP . (XREF ...)) ...), where
638 GROUP is a string for decoration purposes and XREF is an
639 `xref-item' object."
640 (require 'compile) ; For the compilation faces.
641 (cl-loop for ((group . xrefs) . more1) on xref-alist
642 for max-line-width =
643 (cl-loop for xref in xrefs
644 maximize (let ((line (xref-location-line
645 (oref xref location))))
646 (length (and line (format "%d" line)))))
647 for line-format = (and max-line-width
648 (format "%%%dd: " max-line-width))
649 do
650 (xref--insert-propertized '(face compilation-info) group "\n")
651 (cl-loop for (xref . more2) on xrefs do
652 (with-slots (summary location) xref
653 (let* ((line (xref-location-line location))
654 (prefix
655 (if line
656 (propertize (format line-format line)
657 'face 'compilation-line-number)
658 " ")))
659 (xref--insert-propertized
660 (list 'xref-item xref
661 ;; 'face 'font-lock-keyword-face
662 'mouse-face 'highlight
663 'keymap xref--button-map
664 'help-echo
665 (concat "mouse-2: display in another window, "
666 "RET or mouse-1: follow reference"))
667 prefix summary)))
668 (insert "\n"))))
669
670 (defun xref--analyze (xrefs)
671 "Find common filenames in XREFS.
672 Return an alist of the form ((FILENAME . (XREF ...)) ...)."
673 (xref--alistify xrefs
674 (lambda (x)
675 (xref-location-group (xref-item-location x)))
676 #'equal))
677
678 (defun xref--show-xref-buffer (xrefs alist)
679 (let ((xref-alist (xref--analyze xrefs)))
680 (with-current-buffer (get-buffer-create xref-buffer-name)
681 (let ((inhibit-read-only t))
682 (erase-buffer)
683 (xref--insert-xrefs xref-alist)
684 (xref--xref-buffer-mode)
685 (pop-to-buffer (current-buffer))
686 (goto-char (point-min))
687 (setq xref--window (assoc-default 'window alist))
688 (current-buffer)))))
689
690 \f
691 ;; This part of the UI seems fairly uncontroversial: it reads the
692 ;; identifier and deals with the single definition case.
693 ;; (FIXME: do we really want this case to be handled like that in
694 ;; "find references" and "find regexp searches"?)
695 ;;
696 ;; The controversial multiple definitions case is handed off to
697 ;; xref-show-xrefs-function.
698
699 (defvar xref-show-xrefs-function 'xref--show-xref-buffer
700 "Function to display a list of xrefs.")
701
702 (defvar xref--read-identifier-history nil)
703
704 (defvar xref--read-pattern-history nil)
705
706 (defun xref--show-xrefs (xrefs window)
707 (cond
708 ((not (cdr xrefs))
709 (xref-push-marker-stack)
710 (xref--pop-to-location (car xrefs) window))
711 (t
712 (xref-push-marker-stack)
713 (funcall xref-show-xrefs-function xrefs
714 `((window . ,window))))))
715
716 (defun xref--prompt-p (command)
717 (or (eq xref-prompt-for-identifier t)
718 (if (eq (car xref-prompt-for-identifier) 'not)
719 (not (memq command (cdr xref-prompt-for-identifier)))
720 (memq command xref-prompt-for-identifier))))
721
722 (defun xref--read-identifier (prompt)
723 "Return the identifier at point or read it from the minibuffer."
724 (let* ((backend (xref-find-backend))
725 (id (xref-backend-identifier-at-point backend)))
726 (cond ((or current-prefix-arg
727 (not id)
728 (xref--prompt-p this-command))
729 (completing-read (if id
730 (format "%s (default %s): "
731 (substring prompt 0 (string-match
732 "[ :]+\\'" prompt))
733 id)
734 prompt)
735 (xref-backend-identifier-completion-table backend)
736 nil nil nil
737 'xref--read-identifier-history id))
738 (t id))))
739
740 \f
741 ;;; Commands
742
743 (defun xref--find-xrefs (input kind arg window)
744 (let ((xrefs (funcall (intern (format "xref-backend-%s" kind))
745 (xref-find-backend)
746 arg)))
747 (unless xrefs
748 (user-error "No %s found for: %s" (symbol-name kind) input))
749 (xref--show-xrefs xrefs window)))
750
751 (defun xref--find-definitions (id window)
752 (xref--find-xrefs id 'definitions id window))
753
754 ;;;###autoload
755 (defun xref-find-definitions (identifier)
756 "Find the definition of the identifier at point.
757 With prefix argument or when there's no identifier at point,
758 prompt for it.
759
760 If the backend has sufficient information to determine a unique
761 definition for IDENTIFIER, it returns only that definition. If
762 there are multiple possible definitions, it returns all of them.
763
764 If the backend returns one definition, jump to it; otherwise,
765 display the list in a buffer."
766 (interactive (list (xref--read-identifier "Find definitions of: ")))
767 (xref--find-definitions identifier nil))
768
769 ;;;###autoload
770 (defun xref-find-definitions-other-window (identifier)
771 "Like `xref-find-definitions' but switch to the other window."
772 (interactive (list (xref--read-identifier "Find definitions of: ")))
773 (xref--find-definitions identifier 'window))
774
775 ;;;###autoload
776 (defun xref-find-definitions-other-frame (identifier)
777 "Like `xref-find-definitions' but switch to the other frame."
778 (interactive (list (xref--read-identifier "Find definitions of: ")))
779 (xref--find-definitions identifier 'frame))
780
781 ;;;###autoload
782 (defun xref-find-references (identifier)
783 "Find references to the identifier at point.
784 With prefix argument, prompt for the identifier."
785 (interactive (list (xref--read-identifier "Find references of: ")))
786 (xref--find-xrefs identifier 'references identifier nil))
787
788 (declare-function apropos-parse-pattern "apropos" (pattern))
789
790 ;;;###autoload
791 (defun xref-find-apropos (pattern)
792 "Find all meaningful symbols that match PATTERN.
793 The argument has the same meaning as in `apropos'."
794 (interactive (list (read-string
795 "Search for pattern (word list or regexp): "
796 nil 'xref--read-pattern-history)))
797 (require 'apropos)
798 (xref--find-xrefs pattern 'apropos
799 (apropos-parse-pattern
800 (if (string-equal (regexp-quote pattern) pattern)
801 ;; Split into words
802 (or (split-string pattern "[ \t]+" t)
803 (user-error "No word list given"))
804 pattern))
805 nil))
806
807 \f
808 ;;; Key bindings
809
810 ;;;###autoload (define-key esc-map "." #'xref-find-definitions)
811 ;;;###autoload (define-key esc-map "," #'xref-pop-marker-stack)
812 ;;;###autoload (define-key esc-map "?" #'xref-find-references)
813 ;;;###autoload (define-key esc-map [?\C-.] #'xref-find-apropos)
814 ;;;###autoload (define-key ctl-x-4-map "." #'xref-find-definitions-other-window)
815 ;;;###autoload (define-key ctl-x-5-map "." #'xref-find-definitions-other-frame)
816
817 \f
818 ;;; Helper functions
819
820 (defvar xref-etags-mode--saved nil)
821
822 (define-minor-mode xref-etags-mode
823 "Minor mode to make xref use etags again.
824
825 Certain major modes install their own mechanisms for listing
826 identifiers and navigation. Turn this on to undo those settings
827 and just use etags."
828 :lighter ""
829 (if xref-etags-mode
830 (progn
831 (setq xref-etags-mode--saved xref-backend-functions)
832 (kill-local-variable 'xref-backend-functions))
833 (setq-local xref-backend-functions xref-etags-mode--saved)))
834
835 (declare-function semantic-symref-find-references-by-name "semantic/symref")
836 (declare-function semantic-find-file-noselect "semantic/fw")
837 (declare-function grep-expand-template "grep")
838
839 (defun xref-collect-references (symbol dir)
840 "Collect references to SYMBOL inside DIR.
841 This function uses the Semantic Symbol Reference API, see
842 `semantic-symref-find-references-by-name' for details on which
843 tools are used, and when."
844 (cl-assert (directory-name-p dir))
845 (require 'semantic/symref)
846 (defvar semantic-symref-tool)
847 (let* ((default-directory dir)
848 (semantic-symref-tool 'detect)
849 (res (semantic-symref-find-references-by-name symbol 'subdirs))
850 (hits (and res (oref res hit-lines)))
851 (orig-buffers (buffer-list)))
852 (unwind-protect
853 (cl-mapcan (lambda (hit) (xref--collect-matches
854 hit (format "\\_<%s\\_>" (regexp-quote symbol))))
855 hits)
856 ;; TODO: Implement "lightweight" buffer visiting, so that we
857 ;; don't have to kill them.
858 (mapc #'kill-buffer
859 (cl-set-difference (buffer-list) orig-buffers)))))
860
861 (defun xref-collect-matches (regexp files dir ignores)
862 "Collect matches for REGEXP inside FILES in DIR.
863 FILES is a string with glob patterns separated by spaces.
864 IGNORES is a list of glob patterns."
865 (cl-assert (directory-name-p dir))
866 (require 'semantic/fw)
867 (grep-compute-defaults)
868 (defvar grep-find-template)
869 (defvar grep-highlight-matches)
870 (let* ((grep-find-template (replace-regexp-in-string "-e " "-E "
871 grep-find-template t t))
872 (grep-highlight-matches nil)
873 (command (xref--rgrep-command (xref--regexp-to-extended regexp)
874 files dir ignores))
875 (orig-buffers (buffer-list))
876 (buf (get-buffer-create " *xref-grep*"))
877 (grep-re (caar grep-regexp-alist))
878 hits)
879 (with-current-buffer buf
880 (erase-buffer)
881 (call-process-shell-command command nil t)
882 (goto-char (point-min))
883 (while (re-search-forward grep-re nil t)
884 (push (cons (string-to-number (match-string 2))
885 (match-string 1))
886 hits)))
887 (unwind-protect
888 (cl-mapcan (lambda (hit) (xref--collect-matches hit regexp))
889 (nreverse hits))
890 ;; TODO: Same as above.
891 (mapc #'kill-buffer
892 (cl-set-difference (buffer-list) orig-buffers)))))
893
894 (defun xref--rgrep-command (regexp files dir ignores)
895 (require 'find-dired) ; for `find-name-arg'
896 (defvar grep-find-template)
897 (defvar find-name-arg)
898 (grep-expand-template
899 grep-find-template
900 regexp
901 (concat (shell-quote-argument "(")
902 " " find-name-arg " "
903 (mapconcat
904 #'shell-quote-argument
905 (split-string files)
906 (concat " -o " find-name-arg " "))
907 " "
908 (shell-quote-argument ")"))
909 dir
910 (concat
911 (shell-quote-argument "(")
912 " -path "
913 (mapconcat
914 (lambda (ignore)
915 (when (string-match-p "/\\'" ignore)
916 (setq ignore (concat ignore "*")))
917 (if (string-match "\\`\\./" ignore)
918 (setq ignore (replace-match dir t t ignore))
919 (unless (string-prefix-p "*" ignore)
920 (setq ignore (concat "*/" ignore))))
921 (shell-quote-argument ignore))
922 ignores
923 " -o -path ")
924 " "
925 (shell-quote-argument ")")
926 " -prune -o ")))
927
928 (defun xref--regexp-to-extended (str)
929 (replace-regexp-in-string
930 ;; FIXME: Add tests. Move to subr.el, make a public function.
931 ;; Maybe error on Emacs-only constructs.
932 "\\(?:\\\\\\\\\\)*\\(?:\\\\[][]\\)?\\(?:\\[.+?\\]\\|\\(\\\\?[(){}|]\\)\\)"
933 (lambda (str)
934 (cond
935 ((not (match-beginning 1))
936 str)
937 ((eq (length (match-string 1 str)) 2)
938 (concat (substring str 0 (match-beginning 1))
939 (substring (match-string 1 str) 1 2)))
940 (t
941 (concat (substring str 0 (match-beginning 1))
942 "\\"
943 (match-string 1 str)))))
944 str t t))
945
946 (defun xref--collect-matches (hit regexp)
947 (pcase-let* ((`(,line . ,file) hit)
948 (buf (or (find-buffer-visiting file)
949 (semantic-find-file-noselect file))))
950 (with-current-buffer buf
951 (save-excursion
952 (goto-char (point-min))
953 (forward-line (1- line))
954 (let ((line-end (line-end-position))
955 (line-beg (line-beginning-position))
956 matches)
957 (syntax-propertize line-end)
958 ;; FIXME: This results in several lines with the same
959 ;; summary. Solve with composite pattern?
960 (while (re-search-forward regexp line-end t)
961 (let* ((beg-column (- (match-beginning 0) line-beg))
962 (end-column (- (match-end 0) line-beg))
963 (loc (xref-make-file-location file line beg-column))
964 (summary (buffer-substring line-beg line-end)))
965 (add-face-text-property beg-column end-column 'highlight
966 t summary)
967 (push (xref-make-match summary loc (- end-column beg-column))
968 matches)))
969 (nreverse matches))))))
970
971 (provide 'xref)
972
973 ;;; xref.el ends here