Signal error if find-grep returns a nonzero status
[emacs.git] / lisp / progmodes / xref.el
blobc43f3a4ca838040b614fb6f80c3848205ef378b1
1 ;; xref.el --- Cross-referencing commands -*-lexical-binding:t-*-
3 ;; Copyright (C) 2014-2017 Free Software Foundation, Inc.
5 ;; This file is part of GNU Emacs.
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.
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.
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/>.
20 ;;; Commentary:
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'.
27 ;; This file provides a somewhat generic infrastructure for cross
28 ;; referencing commands, in particular "find-definition".
30 ;; Some part of the functionality must be implemented in a language
31 ;; dependent way and that's done by defining an xref backend.
33 ;; That consists of a constructor function, which should return a
34 ;; backend value, and a set of implementations for the generic
35 ;; functions:
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.
42 ;; A major mode would normally use `add-hook' to add the backend
43 ;; constructor to `xref-backend-functions'.
45 ;; The last three methods operate with "xref" and "location" values.
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'.
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.
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.
65 ;; See the etags and elisp-mode implementations for full examples.
67 ;;; Code:
69 (require 'cl-lib)
70 (require 'eieio)
71 (require 'ring)
72 (require 'project)
74 (eval-when-compile
75 (require 'semantic/symref)) ;; for hit-lines slot
77 (defgroup xref nil "Cross-referencing commands"
78 :version "25.1"
79 :group 'tools)
82 ;;; Locations
84 (defclass xref-location () ()
85 :documentation "A location represents a position in a file or buffer.")
87 (cl-defgeneric xref-location-marker (location)
88 "Return the marker for LOCATION.")
90 (cl-defgeneric xref-location-group (location)
91 "Return a string used to group a set of locations.
92 This is typically the filename.")
94 (cl-defgeneric xref-location-line (_location)
95 "Return the line number corresponding to the location."
96 nil)
98 (cl-defgeneric xref-match-length (_item)
99 "Return the length of the match."
100 nil)
102 ;;;; Commonly needed location classes are defined here:
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.")
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))
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))))))
131 (cl-defmethod xref-location-group ((l xref-file-location))
132 (oref l file))
134 (defclass xref-buffer-location (xref-location)
135 ((buffer :type buffer :initarg :buffer)
136 (position :type fixnum :initarg :position)))
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))
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))))
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)))))
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.")
159 (defun xref-make-bogus-location (message)
160 "Create and return a new `xref-bogus-location'."
161 (make-instance 'xref-bogus-location :message message))
163 (cl-defmethod xref-location-marker ((l xref-bogus-location))
164 (user-error "%s" (oref l message)))
166 (cl-defmethod xref-location-group ((_ xref-bogus-location)) "(No location)")
169 ;;; Cross-reference
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.")
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))
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.")
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))
207 ;;; API
209 (defvar xref-backend-functions nil
210 "Special hook to find the xref backend for the current context.
211 Each function 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.")
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)
221 ;;;###autoload
222 (defun xref-find-backend ()
223 (run-hook-with-args-until-success 'xref-backend-functions))
225 (cl-defgeneric xref-backend-definitions (backend identifier)
226 "Find definitions of IDENTIFIER.
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.
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'.
238 To create an xref object, call `xref-make'.")
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.
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)))))
256 (cl-defgeneric xref-backend-apropos (backend pattern)
257 "Find all symbols that match PATTERN.
258 PATTERN is a regexp")
260 (cl-defgeneric xref-backend-identifier-at-point (_backend)
261 "Return the relevant identifier at point.
263 The return value must be a string or nil. nil means no
264 identifier at point found.
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))))
274 (cl-defgeneric xref-backend-identifier-completion-table (backend)
275 "Returns the completion table for identifiers.")
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)))))
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)))
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))))
318 ;;; Marker stack (M-. pushes, M-, pops)
320 (defcustom xref-marker-ring-length 16
321 "Length of the xref marker ring."
322 :type 'integer)
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.
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.
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).
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")))))
344 (defcustom xref-after-jump-hook '(recenter
345 xref-pulse-momentarily)
346 "Functions called after jumping to an xref."
347 :type 'hook)
349 (defcustom xref-after-return-hook '(xref-pulse-momentarily)
350 "Functions called after returning to a pre-jump location."
351 :type 'hook)
353 (defvar xref--marker-ring (make-ring xref-marker-ring-length)
354 "Ring of markers to implement the marker stack.")
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))))
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))))
374 (defvar xref--current-item nil)
376 (defun xref-pulse-momentarily ()
377 (pcase-let ((`(,beg . ,end)
378 (save-excursion
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)))
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)))))
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))
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))
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)))
416 (defun xref--pop-to-location (item &optional action)
417 "Go to the location of ITEM and display the buffer.
418 ACTION 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 If SELECT is non-nil, select the target window."
423 (let* ((marker (save-excursion
424 (xref-location-marker (xref-item-location item))))
425 (buf (marker-buffer marker)))
426 (cl-ecase action
427 ((nil) (switch-to-buffer buf))
428 (window (pop-to-buffer buf t))
429 (frame (let ((pop-up-frames t)) (pop-to-buffer buf t))))
430 (xref--goto-char marker))
431 (let ((xref--current-item item))
432 (run-hooks 'xref-after-jump-hook)))
435 ;;; XREF buffer (part of the UI)
437 ;; The xref buffer is used to display a set of xrefs.
438 (defconst xref-buffer-name "*xref*"
439 "The name of the buffer to show xrefs.")
441 (defmacro xref--with-dedicated-window (&rest body)
442 `(let* ((xref-w (get-buffer-window xref-buffer-name))
443 (xref-w-dedicated (window-dedicated-p xref-w)))
444 (unwind-protect
445 (progn
446 (when xref-w
447 (set-window-dedicated-p xref-w 'soft))
448 ,@body)
449 (when xref-w
450 (set-window-dedicated-p xref-w xref-w-dedicated)))))
452 (defun xref--show-pos-in-buf (pos buf select)
453 (let ((xref-buf (current-buffer))
454 win)
455 (with-selected-window
456 (xref--with-dedicated-window
457 (display-buffer buf))
458 (xref--goto-char pos)
459 (run-hooks 'xref-after-jump-hook)
460 (let ((buf (current-buffer)))
461 (setq win (selected-window))
462 (with-current-buffer xref-buf
463 (setq-local other-window-scroll-buffer buf))))
464 (when select
465 (select-window win))))
467 (defun xref--show-location (location &optional select)
468 (condition-case err
469 (let* ((marker (xref-location-marker location))
470 (buf (marker-buffer marker)))
471 (xref--show-pos-in-buf marker buf select))
472 (user-error (message (error-message-string err)))))
474 (defvar-local xref--window nil
475 "The original window this xref buffer was created from.")
477 (defun xref-show-location-at-point ()
478 "Display the source of xref at point in the appropriate window, if any."
479 (interactive)
480 (let* ((xref (xref--item-at-point))
481 (xref--current-item xref))
482 (when xref
483 ;; Try to avoid the window the current xref buffer was
484 ;; originally created from.
485 (if (window-live-p xref--window)
486 (with-selected-window xref--window
487 (xref--show-location (xref-item-location xref)))
488 (xref--show-location (xref-item-location xref))))))
490 (defun xref-next-line ()
491 "Move to the next xref and display its source in the appropriate window."
492 (interactive)
493 (xref--search-property 'xref-item)
494 (xref-show-location-at-point))
496 (defun xref-prev-line ()
497 "Move to the previous xref and display its source in the appropriate window."
498 (interactive)
499 (xref--search-property 'xref-item t)
500 (xref-show-location-at-point))
502 (defun xref--item-at-point ()
503 (save-excursion
504 (back-to-indentation)
505 (get-text-property (point) 'xref-item)))
507 (defun xref-goto-xref ()
508 "Jump to the xref on the current line and select its window."
509 (interactive)
510 (let ((xref (or (xref--item-at-point)
511 (user-error "No reference at point"))))
512 (xref--show-location (xref-item-location xref) t)))
514 (defun xref-query-replace-in-results (from to)
515 "Perform interactive replacement of FROM with TO in all displayed xrefs.
517 This command interactively replaces FROM with TO in the names of the
518 references displayed in the current *xref* buffer."
519 (interactive
520 (let ((fr (read-regexp "Xref query-replace (regexp)" ".*")))
521 (list fr
522 (read-regexp (format "Xref query-replace (regexp) %s with: " fr)))))
523 (let* (item xrefs iter)
524 (save-excursion
525 (while (setq item (xref--search-property 'xref-item))
526 (when (xref-match-length item)
527 (push item xrefs))))
528 (unwind-protect
529 (progn
530 (goto-char (point-min))
531 (setq iter (xref--buf-pairs-iterator (nreverse xrefs)))
532 (xref--query-replace-1 from to iter))
533 (funcall iter :cleanup))))
535 (defun xref--buf-pairs-iterator (xrefs)
536 (let (chunk-done item next-pair file-buf pairs all-pairs)
537 (lambda (action)
538 (pcase action
539 (:next
540 (when (or xrefs next-pair)
541 (setq chunk-done nil)
542 (when next-pair
543 (setq file-buf (marker-buffer (car next-pair))
544 pairs (list next-pair)
545 next-pair nil))
546 (while (and (not chunk-done)
547 (setq item (pop xrefs)))
548 (save-excursion
549 (let* ((loc (xref-item-location item))
550 (beg (xref-location-marker loc))
551 (end (move-marker (make-marker)
552 (+ beg (xref-match-length item))
553 (marker-buffer beg))))
554 (let ((pair (cons beg end)))
555 (push pair all-pairs)
556 ;; Perform sanity check first.
557 (xref--goto-location loc)
558 (if (xref--outdated-p item
559 (buffer-substring-no-properties
560 (line-beginning-position)
561 (line-end-position)))
562 (message "Search result out of date, skipping")
563 (cond
564 ((null file-buf)
565 (setq file-buf (marker-buffer beg))
566 (push pair pairs))
567 ((equal file-buf (marker-buffer beg))
568 (push pair pairs))
570 (setq chunk-done t
571 next-pair pair))))))))
572 (cons file-buf (nreverse pairs))))
573 (:cleanup
574 (dolist (pair all-pairs)
575 (move-marker (car pair) nil)
576 (move-marker (cdr pair) nil)))))))
578 (defun xref--outdated-p (item line-text)
579 ;; FIXME: The check should probably be a generic function instead of
580 ;; the assumption that all matches contain the full line as summary.
581 (let ((summary (xref-item-summary item))
582 (strip (lambda (s) (if (string-match "\r\\'" s)
583 (substring-no-properties s 0 -1)
584 s))))
585 (not
586 ;; Sometimes buffer contents include ^M, and sometimes Grep
587 ;; output includes it, and they don't always match.
588 (equal (funcall strip line-text)
589 (funcall strip summary)))))
591 ;; FIXME: Write a nicer UI.
592 (defun xref--query-replace-1 (from to iter)
593 (let* ((query-replace-lazy-highlight nil)
594 (continue t)
595 did-it-once buf-pairs pairs
596 current-beg current-end
597 ;; Counteract the "do the next match now" hack in
598 ;; `perform-replace'. And still, it'll report that those
599 ;; matches were "filtered out" at the end.
600 (isearch-filter-predicate
601 (lambda (beg end)
602 (and current-beg
603 (>= beg current-beg)
604 (<= end current-end))))
605 (replace-re-search-function
606 (lambda (from &optional _bound noerror)
607 (let (found pair)
608 (while (and (not found) pairs)
609 (setq pair (pop pairs)
610 current-beg (car pair)
611 current-end (cdr pair))
612 (goto-char current-beg)
613 (when (re-search-forward from current-end noerror)
614 (setq found t)))
615 found))))
616 (while (and continue (setq buf-pairs (funcall iter :next)))
617 (if did-it-once
618 ;; Reuse the same window for subsequent buffers.
619 (switch-to-buffer (car buf-pairs))
620 (xref--with-dedicated-window
621 (pop-to-buffer (car buf-pairs)))
622 (setq did-it-once t))
623 (setq pairs (cdr buf-pairs))
624 (setq continue
625 (perform-replace from to t t nil nil multi-query-replace-map)))
626 (unless did-it-once (user-error "No suitable matches here"))
627 (when (and continue (not buf-pairs))
628 (message "All results processed"))))
630 (defvar xref--xref-buffer-mode-map
631 (let ((map (make-sparse-keymap)))
632 (define-key map (kbd "n") #'xref-next-line)
633 (define-key map (kbd "p") #'xref-prev-line)
634 (define-key map (kbd "r") #'xref-query-replace-in-results)
635 (define-key map (kbd "RET") #'xref-goto-xref)
636 (define-key map (kbd "C-o") #'xref-show-location-at-point)
637 ;; suggested by Johan Claesson "to further reduce finger movement":
638 (define-key map (kbd ".") #'xref-next-line)
639 (define-key map (kbd ",") #'xref-prev-line)
640 map))
642 (define-derived-mode xref--xref-buffer-mode special-mode "XREF"
643 "Mode for displaying cross-references."
644 (setq buffer-read-only t)
645 (setq next-error-function #'xref--next-error-function)
646 (setq next-error-last-buffer (current-buffer)))
648 (defun xref--next-error-function (n reset?)
649 (when reset?
650 (goto-char (point-min)))
651 (let ((backward (< n 0))
652 (n (abs n))
653 (xref nil))
654 (dotimes (_ n)
655 (setq xref (xref--search-property 'xref-item backward)))
656 (cond (xref
657 (xref--show-location (xref-item-location xref) t))
659 (error "No %s xref" (if backward "previous" "next"))))))
661 (defvar xref--button-map
662 (let ((map (make-sparse-keymap)))
663 (define-key map [(control ?m)] #'xref-goto-xref)
664 (define-key map [mouse-1] #'xref-goto-xref)
665 (define-key map [mouse-2] #'xref--mouse-2)
666 map))
668 (defun xref--mouse-2 (event)
669 "Move point to the button and show the xref definition."
670 (interactive "e")
671 (mouse-set-point event)
672 (forward-line 0)
673 (xref--search-property 'xref-item)
674 (xref-show-location-at-point))
676 (defun xref--insert-xrefs (xref-alist)
677 "Insert XREF-ALIST in the current-buffer.
678 XREF-ALIST is of the form ((GROUP . (XREF ...)) ...), where
679 GROUP is a string for decoration purposes and XREF is an
680 `xref-item' object."
681 (require 'compile) ; For the compilation faces.
682 (cl-loop for ((group . xrefs) . more1) on xref-alist
683 for max-line-width =
684 (cl-loop for xref in xrefs
685 maximize (let ((line (xref-location-line
686 (oref xref location))))
687 (length (and line (format "%d" line)))))
688 for line-format = (and max-line-width
689 (format "%%%dd: " max-line-width))
691 (xref--insert-propertized '(face compilation-info) group "\n")
692 (cl-loop for (xref . more2) on xrefs do
693 (with-slots (summary location) xref
694 (let* ((line (xref-location-line location))
695 (prefix
696 (if line
697 (propertize (format line-format line)
698 'face 'compilation-line-number)
699 " ")))
700 (xref--insert-propertized
701 (list 'xref-item xref
702 ;; 'face 'font-lock-keyword-face
703 'mouse-face 'highlight
704 'keymap xref--button-map
705 'help-echo
706 (concat "mouse-2: display in another window, "
707 "RET or mouse-1: follow reference"))
708 prefix summary)))
709 (insert "\n"))))
711 (defun xref--analyze (xrefs)
712 "Find common filenames in XREFS.
713 Return an alist of the form ((FILENAME . (XREF ...)) ...)."
714 (xref--alistify xrefs
715 (lambda (x)
716 (xref-location-group (xref-item-location x)))
717 #'equal))
719 (defun xref--show-xref-buffer (xrefs alist)
720 (let ((xref-alist (xref--analyze xrefs)))
721 (with-current-buffer (get-buffer-create xref-buffer-name)
722 (setq buffer-undo-list nil)
723 (let ((inhibit-read-only t)
724 (buffer-undo-list t))
725 (erase-buffer)
726 (xref--insert-xrefs xref-alist)
727 (xref--xref-buffer-mode)
728 (pop-to-buffer (current-buffer))
729 (goto-char (point-min))
730 (setq xref--window (assoc-default 'window alist))
731 (current-buffer)))))
734 ;; This part of the UI seems fairly uncontroversial: it reads the
735 ;; identifier and deals with the single definition case.
736 ;; (FIXME: do we really want this case to be handled like that in
737 ;; "find references" and "find regexp searches"?)
739 ;; The controversial multiple definitions case is handed off to
740 ;; xref-show-xrefs-function.
742 (defvar xref-show-xrefs-function 'xref--show-xref-buffer
743 "Function to display a list of xrefs.")
745 (defvar xref--read-identifier-history nil)
747 (defvar xref--read-pattern-history nil)
749 (defun xref--show-xrefs (xrefs display-action &optional always-show-list)
750 (cond
751 ((and (not (cdr xrefs)) (not always-show-list))
752 (xref-push-marker-stack)
753 (xref--pop-to-location (car xrefs) display-action))
755 (xref-push-marker-stack)
756 (funcall xref-show-xrefs-function xrefs
757 `((window . ,(selected-window)))))))
759 (defun xref--prompt-p (command)
760 (or (eq xref-prompt-for-identifier t)
761 (if (eq (car xref-prompt-for-identifier) 'not)
762 (not (memq command (cdr xref-prompt-for-identifier)))
763 (memq command xref-prompt-for-identifier))))
765 (defun xref--read-identifier (prompt)
766 "Return the identifier at point or read it from the minibuffer."
767 (let* ((backend (xref-find-backend))
768 (id (xref-backend-identifier-at-point backend)))
769 (cond ((or current-prefix-arg
770 (not id)
771 (xref--prompt-p this-command))
772 (completing-read (if id
773 (format "%s (default %s): "
774 (substring prompt 0 (string-match
775 "[ :]+\\'" prompt))
777 prompt)
778 (xref-backend-identifier-completion-table backend)
779 nil nil nil
780 'xref--read-identifier-history id))
781 (t id))))
784 ;;; Commands
786 (defun xref--find-xrefs (input kind arg display-action)
787 (let ((xrefs (funcall (intern (format "xref-backend-%s" kind))
788 (xref-find-backend)
789 arg)))
790 (unless xrefs
791 (user-error "No %s found for: %s" (symbol-name kind) input))
792 (xref--show-xrefs xrefs display-action)))
794 (defun xref--find-definitions (id display-action)
795 (xref--find-xrefs id 'definitions id display-action))
797 ;;;###autoload
798 (defun xref-find-definitions (identifier)
799 "Find the definition of the identifier at point.
800 With prefix argument or when there's no identifier at point,
801 prompt for it.
803 If sufficient information is available to determine a unique
804 definition for IDENTIFIER, display it in the selected window.
805 Otherwise, display the list of the possible definitions in a
806 buffer where the user can select from the list."
807 (interactive (list (xref--read-identifier "Find definitions of: ")))
808 (xref--find-definitions identifier nil))
810 ;;;###autoload
811 (defun xref-find-definitions-other-window (identifier)
812 "Like `xref-find-definitions' but switch to the other window."
813 (interactive (list (xref--read-identifier "Find definitions of: ")))
814 (xref--find-definitions identifier 'window))
816 ;;;###autoload
817 (defun xref-find-definitions-other-frame (identifier)
818 "Like `xref-find-definitions' but switch to the other frame."
819 (interactive (list (xref--read-identifier "Find definitions of: ")))
820 (xref--find-definitions identifier 'frame))
822 ;;;###autoload
823 (defun xref-find-references (identifier)
824 "Find references to the identifier at point.
825 With prefix argument, prompt for the identifier."
826 (interactive (list (xref--read-identifier "Find references of: ")))
827 (xref--find-xrefs identifier 'references identifier nil))
829 (declare-function apropos-parse-pattern "apropos" (pattern))
831 ;;;###autoload
832 (defun xref-find-apropos (pattern)
833 "Find all meaningful symbols that match PATTERN.
834 The argument has the same meaning as in `apropos'."
835 (interactive (list (read-string
836 "Search for pattern (word list or regexp): "
837 nil 'xref--read-pattern-history)))
838 (require 'apropos)
839 (xref--find-xrefs pattern 'apropos
840 (apropos-parse-pattern
841 (if (string-equal (regexp-quote pattern) pattern)
842 ;; Split into words
843 (or (split-string pattern "[ \t]+" t)
844 (user-error "No word list given"))
845 pattern))
846 nil))
849 ;;; Key bindings
851 ;;;###autoload (define-key esc-map "." #'xref-find-definitions)
852 ;;;###autoload (define-key esc-map "," #'xref-pop-marker-stack)
853 ;;;###autoload (define-key esc-map "?" #'xref-find-references)
854 ;;;###autoload (define-key esc-map [?\C-.] #'xref-find-apropos)
855 ;;;###autoload (define-key ctl-x-4-map "." #'xref-find-definitions-other-window)
856 ;;;###autoload (define-key ctl-x-5-map "." #'xref-find-definitions-other-frame)
859 ;;; Helper functions
861 (defvar xref-etags-mode--saved nil)
863 (define-minor-mode xref-etags-mode
864 "Minor mode to make xref use etags again.
866 Certain major modes install their own mechanisms for listing
867 identifiers and navigation. Turn this on to undo those settings
868 and just use etags."
869 :lighter ""
870 (if xref-etags-mode
871 (progn
872 (setq xref-etags-mode--saved xref-backend-functions)
873 (kill-local-variable 'xref-backend-functions))
874 (setq-local xref-backend-functions xref-etags-mode--saved)))
876 (declare-function semantic-symref-instantiate "semantic/symref")
877 (declare-function semantic-symref-perform-search "semantic/symref")
878 (declare-function grep-expand-template "grep")
879 (defvar ede-minor-mode) ;; ede.el
881 (defun xref-collect-references (symbol dir)
882 "Collect references to SYMBOL inside DIR.
883 This function uses the Semantic Symbol Reference API, see
884 `semantic-symref-tool-alist' for details on which tools are used,
885 and when."
886 (cl-assert (directory-name-p dir))
887 (require 'semantic/symref)
888 (defvar semantic-symref-tool)
890 ;; Some symref backends use `ede-project-root-directory' as the root
891 ;; directory for the search, rather than `default-directory'. Since
892 ;; the caller has specified `dir', we bind `ede-minor-mode' to nil
893 ;; to force the backend to use `default-directory'.
894 (let* ((ede-minor-mode nil)
895 (default-directory dir)
896 ;; FIXME: Remove CScope and Global from the recognized tools?
897 ;; The current implementations interpret the symbol search as
898 ;; "find all calls to the given function", but not function
899 ;; definition. And they return nothing when passed a variable
900 ;; name, even a global one.
901 (semantic-symref-tool 'detect)
902 (case-fold-search nil)
903 (inst (semantic-symref-instantiate :searchfor symbol
904 :searchtype 'symbol
905 :searchscope 'subdirs
906 :resulttype 'line-and-text)))
907 (xref--convert-hits (semantic-symref-perform-search inst)
908 (format "\\_<%s\\_>" (regexp-quote symbol)))))
910 ;;;###autoload
911 (defun xref-collect-matches (regexp files dir ignores)
912 "Collect matches for REGEXP inside FILES in DIR.
913 FILES is a string with glob patterns separated by spaces.
914 IGNORES is a list of glob patterns."
915 ;; DIR can also be a regular file for now; let's not advertise that.
916 (require 'semantic/fw)
917 (grep-compute-defaults)
918 (defvar grep-find-template)
919 (defvar grep-highlight-matches)
920 (let* ((grep-find-template (replace-regexp-in-string "<C>" "<C> -E"
921 grep-find-template t t))
922 (grep-highlight-matches nil)
923 ;; TODO: Sanitize the regexp to remove Emacs-specific terms,
924 ;; so that Grep can search for the "relaxed" version. Can we
925 ;; do that reliably enough, without creating false negatives?
926 (command (xref--rgrep-command (xref--regexp-to-extended regexp)
927 files
928 (expand-file-name dir)
929 ignores))
930 (buf (get-buffer-create " *xref-grep*"))
931 (grep-re (caar grep-regexp-alist))
932 status
933 hits)
934 (with-current-buffer buf
935 (erase-buffer)
936 (setq status
937 (call-process-shell-command command nil t))
938 (when (and (not (zerop status))
939 ;; Nonzero status can mean "no matches found".
940 (/= (point-min) (point-max)))
941 (user-error "Search failed with status %d: %s" status (buffer-string)))
942 (goto-char (point-min))
943 (while (re-search-forward grep-re nil t)
944 (push (list (string-to-number (match-string 2))
945 (match-string 1)
946 (buffer-substring-no-properties (point) (line-end-position)))
947 hits)))
948 (xref--convert-hits (nreverse hits) regexp)))
950 (defun xref--rgrep-command (regexp files dir ignores)
951 (require 'find-dired) ; for `find-name-arg'
952 (defvar grep-find-template)
953 (defvar find-name-arg)
954 ;; `shell-quote-argument' quotes the tilde as well.
955 (cl-assert (not (string-match-p "\\`~" dir)))
956 (grep-expand-template
957 grep-find-template
958 regexp
959 (concat (shell-quote-argument "(")
960 " " find-name-arg " "
961 (mapconcat
962 #'shell-quote-argument
963 (split-string files)
964 (concat " -o " find-name-arg " "))
966 (shell-quote-argument ")"))
967 (shell-quote-argument dir)
968 (xref--find-ignores-arguments ignores dir)))
970 (defun xref--find-ignores-arguments (ignores dir)
971 "Convert IGNORES and DIR to a list of arguments for 'find'.
972 IGNORES is a list of glob patterns. DIR is an absolute
973 directory, used as the root of the ignore globs."
974 (cl-assert (not (string-match-p "\\`~" dir)))
975 (when ignores
976 (concat
977 (shell-quote-argument "(")
978 " -path "
979 (mapconcat
980 (lambda (ignore)
981 (when (string-match-p "/\\'" ignore)
982 (setq ignore (concat ignore "*")))
983 (if (string-match "\\`\\./" ignore)
984 (setq ignore (replace-match dir t t ignore))
985 (unless (string-prefix-p "*" ignore)
986 (setq ignore (concat "*/" ignore))))
987 (shell-quote-argument ignore))
988 ignores
989 " -o -path ")
991 (shell-quote-argument ")")
992 " -prune -o ")))
994 (defun xref--regexp-to-extended (str)
995 (replace-regexp-in-string
996 ;; FIXME: Add tests. Move to subr.el, make a public function.
997 ;; Maybe error on Emacs-only constructs.
998 "\\(?:\\\\\\\\\\)*\\(?:\\\\[][]\\)?\\(?:\\[.+?\\]\\|\\(\\\\?[(){}|]\\)\\)"
999 (lambda (str)
1000 (cond
1001 ((not (match-beginning 1))
1002 str)
1003 ((eq (length (match-string 1 str)) 2)
1004 (concat (substring str 0 (match-beginning 1))
1005 (substring (match-string 1 str) 1 2)))
1007 (concat (substring str 0 (match-beginning 1))
1008 "\\"
1009 (match-string 1 str)))))
1010 str t t))
1012 (defun xref--regexp-syntax-dependent-p (str)
1013 "Return non-nil when STR depends on the buffer's syntax.
1014 Such as the current syntax table and the applied syntax properties."
1015 (let ((case-fold-search nil))
1016 (string-match-p (rx
1017 (or string-start (not (in ?\\)))
1018 (0+ (= 2 ?\\))
1020 (in ?b ?B ?< ?> ?w ?W ?_ ?s ?S))
1021 str)))
1023 (defvar xref--last-visiting-buffer nil)
1024 (defvar xref--temp-buffer-file-name nil)
1026 (defun xref--convert-hits (hits regexp)
1027 (let (xref--last-visiting-buffer
1028 (tmp-buffer (generate-new-buffer " *xref-temp*")))
1029 (unwind-protect
1030 (cl-mapcan (lambda (hit) (xref--collect-matches hit regexp tmp-buffer))
1031 hits)
1032 (kill-buffer tmp-buffer))))
1034 (defun xref--collect-matches (hit regexp tmp-buffer)
1035 (pcase-let* ((`(,line ,file ,text) hit)
1036 (buf (xref--find-buffer-visiting file))
1037 (syntax-needed (xref--regexp-syntax-dependent-p regexp)))
1038 (if buf
1039 (with-current-buffer buf
1040 (save-excursion
1041 (goto-char (point-min))
1042 (forward-line (1- line))
1043 (xref--collect-matches-1 regexp file line
1044 (line-beginning-position)
1045 (line-end-position)
1046 syntax-needed)))
1047 ;; Using the temporary buffer is both a performance and a buffer
1048 ;; management optimization.
1049 (with-current-buffer tmp-buffer
1050 (erase-buffer)
1051 (when (and syntax-needed
1052 (not (equal file xref--temp-buffer-file-name)))
1053 (insert-file-contents file nil 0 200)
1054 ;; Can't (setq-local delay-mode-hooks t) because of
1055 ;; bug#23272, but the performance penalty seems minimal.
1056 (let ((buffer-file-name file)
1057 (inhibit-message t)
1058 message-log-max)
1059 (ignore-errors
1060 (set-auto-mode t)))
1061 (setq-local xref--temp-buffer-file-name file)
1062 (setq-local inhibit-read-only t)
1063 (erase-buffer))
1064 (insert text)
1065 (goto-char (point-min))
1066 (xref--collect-matches-1 regexp file line
1067 (point)
1068 (point-max)
1069 syntax-needed)))))
1071 (defun xref--collect-matches-1 (regexp file line line-beg line-end syntax-needed)
1072 (let (matches)
1073 (when syntax-needed
1074 (syntax-propertize line-end))
1075 ;; FIXME: This results in several lines with the same
1076 ;; summary. Solve with composite pattern?
1077 (while (and
1078 ;; REGEXP might match an empty string. Or line.
1079 (or (null matches)
1080 (> (point) line-beg))
1081 (re-search-forward regexp line-end t))
1082 (let* ((beg-column (- (match-beginning 0) line-beg))
1083 (end-column (- (match-end 0) line-beg))
1084 (loc (xref-make-file-location file line beg-column))
1085 (summary (buffer-substring line-beg line-end)))
1086 (add-face-text-property beg-column end-column 'highlight
1087 t summary)
1088 (push (xref-make-match summary loc (- end-column beg-column))
1089 matches)))
1090 (nreverse matches)))
1092 (defun xref--find-buffer-visiting (file)
1093 (unless (equal (car xref--last-visiting-buffer) file)
1094 (setq xref--last-visiting-buffer
1095 (cons file (find-buffer-visiting file))))
1096 (cdr xref--last-visiting-buffer))
1098 (provide 'xref)
1100 ;;; xref.el ends here