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