xref.el 37 KB

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