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