xref.el 34 KB

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