1 ;;; find-func.el --- find the definition of the Emacs Lisp function near point -*- lexical-binding:t -*-
3 ;; Copyright (C) 1997, 1999, 2001-2016 Free Software Foundation, Inc.
5 ;; Author: Jens Petersen <petersen@kurims.kyoto-u.ac.jp>
6 ;; Maintainer: petersen@kurims.kyoto-u.ac.jp
7 ;; Keywords: emacs-lisp, functions, variables
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; The funniest thing about this is that I can't imagine why a package
28 ;; so obviously useful as this hasn't been written before!!
30 ;; (find-function-setup-keys)
36 ;; if you don't like the given keybindings and away you go! It does
37 ;; pretty much what you would expect, putting the cursor at the
38 ;; definition of the function or variable at point.
40 ;; The code started out from `describe-function', `describe-key'
41 ;; ("help.el") and `fff-find-loaded-emacs-lisp-function' (Noah Friedman's
48 (defgroup find-function nil
49 "Finds the definition of the Emacs Lisp symbol near point."
50 ;; :prefix "find-function"
53 (defconst find-function-space-re "\\(?:\\s-\\|\n\\|;.*\n\\)+")
55 (defcustom find-function-regexp
56 ;; Match things like (defun foo ...), (defmacro foo ...),
57 ;; (define-skeleton foo ...), (define-generic-mode 'foo ...),
58 ;; (define-derived-mode foo ...), (define-minor-mode foo)
60 "^\\s-*(\\(def\\(ine-skeleton\\|ine-generic-mode\\|ine-derived-mode\\|\
61 ine\\(?:-global\\)?-minor-mode\\|ine-compilation-mode\\|un-cvs-mode\\|\
62 foo\\|\\(?:[^icfgv]\\|g[^r]\\)\\(\\w\\|\\s_\\)+\\*?\\)\\|easy-mmode-define-[a-z-]+\\|easy-menu-define\\|\
63 menu-bar-make-toggle\\)"
64 find-function-space-re
65 "\\('\\|(quote \\)?%s\\(\\s-\\|$\\|[()]\\)")
66 "The regexp used by `find-function' to search for a function definition.
67 Note it must contain a `%s' at the place where `format'
68 should insert the function name. The default value avoids `defconst',
69 `defgroup', `defvar', `defface'.
71 Please send improvements and fixes to the maintainer."
76 (defcustom find-variable-regexp
78 "^\\s-*(\\(def[^fumag]\\(\\w\\|\\s_\\)+\\*?\\|\
79 easy-mmode-def\\(map\\|syntax\\)\\|easy-menu-define\\)"
80 find-function-space-re
82 "The regexp used by `find-variable' to search for a variable definition.
83 Note it must contain a `%s' at the place where `format'
84 should insert the variable name. The default value
85 avoids `defun', `defmacro', `defalias', `defadvice', `defgroup', `defface'.
87 Please send improvements and fixes to the maintainer."
92 (defcustom find-face-regexp
93 (concat"^\\s-*(defface" find-function-space-re "%s\\(\\s-\\|$\\)")
94 "The regexp used by `find-face' to search for a face definition.
95 Note it must contain a `%s' at the place where `format'
96 should insert the face name.
98 Please send improvements and fixes to the maintainer."
100 :group 'find-function
103 (defcustom find-feature-regexp
105 "The regexp used by `xref-find-definitions' when searching for a feature definition.
106 Note it must contain a `%s' at the place where `format'
107 should insert the feature name."
108 ;; We search for ";;; Code" rather than (feature '%s) because the
109 ;; former is near the start of the code, and the latter is very
110 ;; uninteresting. If the regexp is not found, just goes to
111 ;; (point-min), which is acceptable in this case.
116 (defcustom find-alias-regexp
118 "The regexp used by `xref-find-definitions' to search for an alias definition.
119 Note it must contain a `%s' at the place where `format'
120 should insert the feature name."
125 (defvar find-function-regexp-alist
126 '((nil . find-function-regexp)
127 (defvar . find-variable-regexp)
128 (defface . find-face-regexp)
129 (feature . find-feature-regexp)
130 (defalias . find-alias-regexp))
131 "Alist mapping definition types into regexp variables.
132 Each regexp variable's value should actually be a format string
133 to be used to substitute the desired symbol name into the regexp.
134 Instead of regexp variable, types can be mapped to functions as well,
135 in which case the function is called with one argument (the object
136 we're looking for) and it should search for it.")
137 (put 'find-function-regexp-alist 'risky-local-variable t)
139 (defcustom find-function-source-path nil
140 "The default list of directories where `find-function' searches.
142 If this variable is nil then `find-function' searches `load-path' by
144 :type '(repeat directory)
145 :group 'find-function)
147 (defcustom find-function-recenter-line 1
148 "The window line-number from which to start displaying a symbol definition.
149 A value of nil implies center the beginning of the definition.
150 See `find-function' and `find-variable'."
151 :type '(choice (const :tag "Center" nil)
153 :group 'find-function
156 (defcustom find-function-after-hook nil
157 "Hook run after finding symbol definition.
159 See the functions `find-function' and `find-variable'."
161 :group 'find-function
166 (defun find-library-suffixes ()
167 (let ((suffixes nil))
168 (dolist (suffix (get-load-suffixes) (nreverse suffixes))
169 (unless (string-match "elc" suffix) (push suffix suffixes)))))
171 (defun find-library--load-name (library)
172 (let ((name library))
173 (dolist (dir load-path)
174 (let ((rel (file-relative-name library dir)))
175 (if (and (not (string-match "\\`\\.\\./" rel))
176 (< (length rel) (length name)))
178 (unless (equal name library) name)))
180 (defun find-library-name (library)
181 "Return the absolute file name of the Emacs Lisp source of LIBRARY.
182 LIBRARY should be a string (the name of the library)."
183 ;; If the library is byte-compiled, try to find a source library by
185 (when (string-match "\\.el\\(c\\(\\..*\\)?\\)\\'" library)
186 (setq library (replace-match "" t t library)))
189 (or find-function-source-path load-path)
190 (find-library-suffixes))
192 (or find-function-source-path load-path)
193 load-file-rep-suffixes)
194 (when (file-name-absolute-p library)
195 (let ((rel (find-library--load-name library)))
199 (or find-function-source-path load-path)
200 (find-library-suffixes))
202 (or find-function-source-path load-path)
203 load-file-rep-suffixes)))))
204 (find-library--from-load-path library)
205 (error "Can't find library %s" library)))
207 (defun find-library--from-load-path (library)
208 ;; In `load-history', the file may be ".elc", ".el", ".el.gz", and
209 ;; LIBRARY may be "foo.el" or "foo", so make sure that we get all
210 ;; potential matches, and then see whether any of them lead us to an
211 ;; ".el" or an ".el.gz" file.
212 (let* ((elc-regexp "\\.el\\(c\\(\\..*\\)?\\)\\'")
215 (mapconcat 'regexp-quote (find-library-suffixes) "\\'\\|")
216 "\\|" elc-regexp "\\)\\'"))
220 (if (string-match suffix-regexp (car entry))
221 (replace-match "" t t (car entry))
228 (replace-regexp-in-string suffix-regexp "" library))
230 (file-name-nondirectory (car entry))))
233 (dolist (file potentials)
234 (dolist (suffix (find-library-suffixes))
236 (cond ((file-exists-p file)
238 ((file-exists-p (concat file suffix))
239 (setq result (concat file suffix)))))))
242 (defvar find-function-C-source-directory
243 (let ((dir (expand-file-name "src" source-directory)))
244 (if (file-accessible-directory-p dir) dir))
245 "Directory where the C source files of Emacs can be found.
246 If nil, do not try to find the source code of functions and variables
249 (declare-function ad-get-advice-info "advice" (function))
251 (defun find-function-advised-original (func)
252 "Return the original function definition of an advised function FUNC.
253 If FUNC is not a symbol, return it. Else, if it's not advised,
254 return the symbol's function definition."
255 (or (and (symbolp func)
257 (let ((ofunc (advice--symbol-function func)))
258 (if (advice--p ofunc)
263 (defun find-function-C-source (fun-or-var file type)
264 "Find the source location where FUN-OR-VAR is defined in FILE.
265 TYPE should be nil to find a function, or `defvar' to find a variable."
266 (let ((dir (or find-function-C-source-directory
267 (read-directory-name "Emacs C source dir: " nil nil t))))
268 (setq file (expand-file-name file dir))
269 (if (file-readable-p file)
270 (if (null find-function-C-source-directory)
271 (setq find-function-C-source-directory dir))
272 (error "The C source file %s is not available"
273 (file-name-nondirectory file))))
275 ;; Either or both an alias and its target might be advised.
276 (setq fun-or-var (find-function-advised-original
278 (find-function-advised-original fun-or-var)))))
279 (with-current-buffer (find-file-noselect file)
280 (goto-char (point-min))
281 (unless (re-search-forward
283 (concat "DEFVAR[A-Z_]*[ \t\n]*([ \t\n]*\""
284 (regexp-quote (symbol-name fun-or-var))
286 (concat "DEFUN[ \t\n]*([ \t\n]*\""
287 (regexp-quote (subr-name (advice--cd*r fun-or-var)))
290 (error "Can't find source for %s" fun-or-var))
291 (cons (current-buffer) (match-beginning 0))))
294 (defun find-library (library &optional other-window)
295 "Find the Emacs Lisp source of LIBRARY.
296 LIBRARY should be a string (the name of the library). If the
297 optional OTHER-WINDOW argument (i.e., the command argument) is
298 specified, pop to a different window before displaying the
301 (let* ((dirs (or find-function-source-path load-path))
302 (suffixes (find-library-suffixes))
303 (table (apply-partially 'locate-file-completion-table
305 (def (if (eq (function-called-at-point) 'require)
306 ;; `function-called-at-point' may return 'require
307 ;; with `point' anywhere on this line. So wrap the
308 ;; `save-excursion' below in a `condition-case' to
309 ;; avoid reporting a scan-error here.
315 (thing-at-point 'symbol))
317 (thing-at-point 'symbol))))
318 (when (and def (not (test-completion def table)))
321 (completing-read (if def
322 (format "Library name (default %s): " def)
324 table nil nil nil nil def)
325 current-prefix-arg)))
327 (funcall (if other-window
329 'pop-to-buffer-same-window)
330 (find-file-noselect (find-library-name library)))
331 (run-hooks 'find-function-after-hook)))
334 (defun find-function-search-for-symbol (symbol type library)
335 "Search for SYMBOL's definition of type TYPE in LIBRARY.
336 Visit the library in a buffer, and return a cons cell (BUFFER . POSITION),
337 or just (BUFFER . nil) if the definition can't be found in the file.
339 If TYPE is nil, look for a function definition.
340 Otherwise, TYPE specifies the kind of definition,
341 and it is interpreted via `find-function-regexp-alist'.
342 The search is done in the source for library LIBRARY."
344 (error "Don't know where `%s' is defined" symbol))
345 ;; Some functions are defined as part of the construct
346 ;; that defines something else.
347 (while (and (symbolp symbol) (get symbol 'definition-name))
348 (setq symbol (get symbol 'definition-name)))
349 (if (string-match "\\`src/\\(.*\\.\\(c\\|m\\)\\)\\'" library)
350 (find-function-C-source symbol (match-string 1 library) type)
351 (when (string-match "\\.el\\(c\\)\\'" library)
352 (setq library (substring library 0 (match-beginning 1))))
353 ;; Strip extension from .emacs.el to make sure symbol is searched in
355 (when (string-match "\\.emacs\\(.el\\)" library)
356 (setq library (substring library 0 (match-beginning 1))))
357 (let* ((filename (find-library-name library))
358 (regexp-symbol (cdr (assq type find-function-regexp-alist))))
359 (with-current-buffer (find-file-noselect filename)
360 (let ((regexp (if (functionp regexp-symbol) regexp-symbol
361 (format (symbol-value regexp-symbol)
362 ;; Entry for ` (backquote) macro in loaddefs.el,
363 ;; (defalias (quote \`)..., has a \ but
364 ;; (symbol-name symbol) doesn't. Add an
365 ;; optional \ to catch this.
367 (regexp-quote (symbol-name symbol))))))
369 (with-syntax-table emacs-lisp-mode-syntax-table
370 (goto-char (point-min))
371 (if (if (functionp regexp)
372 (funcall regexp symbol)
373 (or (re-search-forward regexp nil t)
374 ;; `regexp' matches definitions using known forms like
375 ;; `defun', or `defvar'. But some functions/variables
376 ;; are defined using special macros (or functions), so
377 ;; if `regexp' can't find the definition, we look for
378 ;; something of the form "(SOMETHING <symbol> ...)".
379 ;; This fails to distinguish function definitions from
380 ;; variable declarations (or even uses thereof), but is
381 ;; a good pragmatic fallback.
383 (concat "^([^ ]+" find-function-space-re "['(]?"
384 (regexp-quote (symbol-name symbol))
389 (cons (current-buffer) (point)))
390 (cons (current-buffer) nil))))))))
392 (defun find-function-library (function &optional lisp-only verbose)
393 "Return the pair (ORIG-FUNCTION . LIBRARY) for FUNCTION.
395 ORIG-FUNCTION is the original name, after removing all advice and
396 resolving aliases. LIBRARY is an absolute file name, a relative
397 file name inside the C sources directory, or a name of an
400 If ORIG-FUNCTION is a built-in function and LISP-ONLY is non-nil,
403 If VERBOSE is non-nil, and FUNCTION is an alias, display a
404 message about the whole chain of aliases."
405 (let ((def (if (symbolp function)
406 (find-function-advised-original function)))
408 ;; FIXME for completeness, it might be nice to print something like:
409 ;; foo (which is advised), which is an alias for bar (which is advised).
410 (while (and def (symbolp def))
411 (or (eq def function)
413 (setq aliases (if aliases
416 ", which is an alias for `%s'"
418 (format-message "`%s' is an alias for `%s'"
419 function (symbol-name def)))))
420 (setq function (find-function-advised-original function)
421 def (find-function-advised-original function)))
423 (message "%s" aliases))
426 ((autoloadp def) (nth 1 def))
429 (error "%s is a built-in function" function))
430 (help-C-file-name def 'subr))
431 ((symbol-file function 'defun))))))
434 (defun find-function-noselect (function &optional lisp-only)
435 "Return a pair (BUFFER . POINT) pointing to the definition of FUNCTION.
437 Finds the source file containing the definition of FUNCTION
438 in a buffer and the point of the definition. The buffer is
439 not selected. If the function definition can't be found in
440 the buffer, returns (BUFFER).
442 If FUNCTION is a built-in function, this function normally
443 attempts to find it in the Emacs C sources; however, if LISP-ONLY
444 is non-nil, signal an error instead.
446 If the file where FUNCTION is defined is not known, then it is
447 searched for in `find-function-source-path' if non-nil, otherwise
450 (error "You didn't specify a function"))
451 (let ((func-lib (find-function-library function lisp-only t)))
452 (find-function-search-for-symbol (car func-lib) nil (cdr func-lib))))
454 (defun find-function-read (&optional type)
455 "Read and return an interned symbol, defaulting to the one near point.
457 If TYPE is nil, insist on a symbol with a function definition.
458 Otherwise TYPE should be `defvar' or `defface'.
459 If TYPE is nil, defaults using `function-called-at-point',
460 otherwise uses `variable-at-point'."
461 (let* ((symb1 (cond ((null type) (function-called-at-point))
462 ((eq type 'defvar) (variable-at-point))
463 (t (variable-at-point t))))
464 (symb (unless (eq symb1 0) symb1))
465 (predicate (cdr (assq type '((nil . fboundp)
467 (defface . facep)))))
468 (prompt-type (cdr (assq type '((nil . "function")
469 (defvar . "variable")
470 (defface . "face")))))
471 (prompt (concat "Find " prompt-type
472 (and symb (format " (default %s)" symb))
474 (enable-recursive-minibuffers t))
475 (list (intern (completing-read
476 prompt obarray predicate
477 t nil nil (and symb (symbol-name symb)))))))
479 (defun find-function-do-it (symbol type switch-fn)
480 "Find Emacs Lisp SYMBOL in a buffer and display it.
481 TYPE is nil to search for a function definition,
482 or else `defvar' or `defface'.
484 The variable `find-function-recenter-line' controls how
485 to recenter the display. SWITCH-FN is the function to call
486 to display and select the buffer.
487 See also `find-function-after-hook'.
489 Set mark before moving, if the buffer already existed."
490 (let* ((orig-point (point))
491 (orig-buffers (buffer-list))
492 (buffer-point (save-excursion
493 (find-definition-noselect symbol type)))
494 (new-buf (car buffer-point))
495 (new-point (cdr buffer-point)))
497 (when (memq new-buf orig-buffers)
498 (push-mark orig-point))
499 (funcall switch-fn new-buf)
500 (when new-point (goto-char new-point))
501 (recenter find-function-recenter-line)
502 (run-hooks 'find-function-after-hook))))
505 (defun find-function (function)
506 "Find the definition of the FUNCTION near point.
508 Finds the source file containing the definition of the function
509 near point (selected by `function-called-at-point') in a buffer and
510 places point before the definition.
511 Set mark before moving, if the buffer already existed.
513 The library where FUNCTION is defined is searched for in
514 `find-function-source-path', if non-nil, otherwise in `load-path'.
515 See also `find-function-recenter-line' and `find-function-after-hook'."
516 (interactive (find-function-read))
517 (find-function-do-it function nil 'switch-to-buffer))
520 (defun find-function-other-window (function)
521 "Find, in another window, the definition of FUNCTION near point.
523 See `find-function' for more details."
524 (interactive (find-function-read))
525 (find-function-do-it function nil 'switch-to-buffer-other-window))
528 (defun find-function-other-frame (function)
529 "Find, in another frame, the definition of FUNCTION near point.
531 See `find-function' for more details."
532 (interactive (find-function-read))
533 (find-function-do-it function nil 'switch-to-buffer-other-frame))
536 (defun find-variable-noselect (variable &optional file)
537 "Return a pair `(BUFFER . POINT)' pointing to the definition of VARIABLE.
539 Finds the library containing the definition of VARIABLE in a buffer and
540 the point of the definition. The buffer is not selected.
541 If the variable's definition can't be found in the buffer, return (BUFFER).
543 The library where VARIABLE is defined is searched for in FILE or
544 `find-function-source-path', if non-nil, otherwise in `load-path'."
546 (error "You didn't specify a variable")
547 (let ((library (or file
548 (symbol-file variable 'defvar)
549 (help-C-file-name variable 'var))))
550 (find-function-search-for-symbol variable 'defvar library))))
553 (defun find-variable (variable)
554 "Find the definition of the VARIABLE at or before point.
556 Finds the library containing the definition of the variable
557 near point (selected by `variable-at-point') in a buffer and
558 places point before the definition.
560 Set mark before moving, if the buffer already existed.
562 The library where VARIABLE is defined is searched for in
563 `find-function-source-path', if non-nil, otherwise in `load-path'.
564 See also `find-function-recenter-line' and `find-function-after-hook'."
565 (interactive (find-function-read 'defvar))
566 (find-function-do-it variable 'defvar 'switch-to-buffer))
569 (defun find-variable-other-window (variable)
570 "Find, in another window, the definition of VARIABLE near point.
572 See `find-variable' for more details."
573 (interactive (find-function-read 'defvar))
574 (find-function-do-it variable 'defvar 'switch-to-buffer-other-window))
577 (defun find-variable-other-frame (variable)
578 "Find, in another frame, the definition of VARIABLE near point.
580 See `find-variable' for more details."
581 (interactive (find-function-read 'defvar))
582 (find-function-do-it variable 'defvar 'switch-to-buffer-other-frame))
585 (defun find-definition-noselect (symbol type &optional file)
586 "Return a pair `(BUFFER . POINT)' pointing to the definition of SYMBOL.
587 If the definition can't be found in the buffer, return (BUFFER).
588 TYPE says what type of definition: nil for a function, `defvar' for a
589 variable, `defface' for a face. This function does not switch to the
590 buffer nor display it.
592 The library where SYMBOL is defined is searched for in FILE or
593 `find-function-source-path', if non-nil, otherwise in `load-path'."
596 (error "You didn't specify a symbol"))
598 (find-function-noselect symbol))
600 (find-variable-noselect symbol file))
602 (let ((library (or file (symbol-file symbol type))))
603 (find-function-search-for-symbol symbol type library)))))
605 ;; For symmetry, this should be called find-face; but some programs
606 ;; assume that, if that name is defined, it means something else.
608 (defun find-face-definition (face)
609 "Find the definition of FACE. FACE defaults to the name near point.
611 Finds the Emacs Lisp library containing the definition of the face
612 near point (selected by `variable-at-point') in a buffer and
613 places point before the definition.
615 Set mark before moving, if the buffer already existed.
617 The library where FACE is defined is searched for in
618 `find-function-source-path', if non-nil, otherwise in `load-path'.
619 See also `find-function-recenter-line' and `find-function-after-hook'."
620 (interactive (find-function-read 'defface))
621 (find-function-do-it face 'defface 'switch-to-buffer))
623 (defun find-function-on-key-do-it (key find-fn)
624 "Find the function that KEY invokes. KEY is a string.
625 Set mark before moving, if the buffer already existed.
627 FIND-FN is the function to call to navigate to the function."
630 (let* ((event (and (eventp key) (aref key 0))) ; Null event OK below.
631 (start (event-start event))
632 (modifiers (event-modifiers event))
633 (window (and (or (memq 'click modifiers) (memq 'down modifiers)
634 (memq 'drag modifiers))
635 (posn-window start))))
636 ;; For a mouse button event, go to the button it applies to
637 ;; to get the right key bindings. And go to the right place
638 ;; in case the keymap depends on where you clicked.
639 (when (windowp window)
640 (set-buffer (window-buffer window))
641 (goto-char (posn-point start)))
642 (setq defn (key-binding key))))
643 (let ((key-desc (key-description key)))
644 (if (or (null defn) (integerp defn))
645 (message "%s is unbound" key-desc)
647 (message "%s runs %s" key-desc (prin1-to-string defn))
648 (funcall find-fn defn))))))
651 (defun find-function-on-key (key)
652 "Find the function that KEY invokes. KEY is a string.
653 Set mark before moving, if the buffer already existed."
654 (interactive "kFind function on key: ")
655 (find-function-on-key-do-it key #'find-function))
658 (defun find-function-on-key-other-window (key)
659 "Find, in the other window, the function that KEY invokes.
660 See `find-function-on-key'."
661 (interactive "kFind function on key: ")
662 (find-function-on-key-do-it key #'find-function-other-window))
665 (defun find-function-on-key-other-frame (key)
666 "Find, in the other frame, the function that KEY invokes.
667 See `find-function-on-key'."
668 (interactive "kFind function on key: ")
669 (find-function-on-key-do-it key #'find-function-other-frame))
672 (defun find-function-at-point ()
673 "Find directly the function at point in the other window."
675 (let ((symb (function-called-at-point)))
677 (find-function-other-window symb))))
680 (defun find-variable-at-point ()
681 "Find directly the variable at point in the other window."
683 (let ((symb (variable-at-point)))
684 (when (and symb (not (equal symb 0)))
685 (find-variable-other-window symb))))
688 (defun find-function-setup-keys ()
689 "Define some key bindings for the find-function family of functions."
690 (define-key ctl-x-map "F" 'find-function)
691 (define-key ctl-x-4-map "F" 'find-function-other-window)
692 (define-key ctl-x-5-map "F" 'find-function-other-frame)
693 (define-key ctl-x-map "K" 'find-function-on-key)
694 (define-key ctl-x-4-map "K" 'find-function-on-key-other-window)
695 (define-key ctl-x-5-map "K" 'find-function-on-key-other-frame)
696 (define-key ctl-x-map "V" 'find-variable)
697 (define-key ctl-x-4-map "V" 'find-variable-other-window)
698 (define-key ctl-x-5-map "V" 'find-variable-other-frame))
702 ;;; find-func.el ends here