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