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