* doc/lispref/variables.texi (Scope): Mention the availability of lexbind.
[emacs.git] / lisp / emacs-lisp / eldoc.el
blobcd9b779bee96360295db4c0b8e5fc65aa3599429
1 ;;; eldoc.el --- show function arglist or variable docstring in echo area
3 ;; Copyright (C) 1996-2011 Free Software Foundation, Inc.
5 ;; Author: Noah Friedman <friedman@splode.com>
6 ;; Maintainer: friedman@splode.com
7 ;; Keywords: extensions
8 ;; Created: 1995-10-06
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/>.
25 ;;; Commentary:
27 ;; This program was inspired by the behavior of the "mouse documentation
28 ;; window" on many Lisp Machine systems; as you type a function's symbol
29 ;; name as part of a sexp, it will print the argument list for that
30 ;; function. Behavior is not identical; for example, you need not actually
31 ;; type the function name, you need only move point around in a sexp that
32 ;; calls it. Also, if point is over a documented variable, it will print
33 ;; the one-line documentation for that variable instead, to remind you of
34 ;; that variable's meaning.
36 ;; One useful way to enable this minor mode is to put the following in your
37 ;; .emacs:
39 ;; (add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)
40 ;; (add-hook 'lisp-interaction-mode-hook 'turn-on-eldoc-mode)
41 ;; (add-hook 'ielm-mode-hook 'turn-on-eldoc-mode)
43 ;; Major modes for other languages may use ElDoc by defining an
44 ;; appropriate function as the buffer-local value of
45 ;; `eldoc-documentation-function'.
47 ;;; Code:
49 (require 'help-fns) ;For fundoc-usage handling functions.
51 (defgroup eldoc nil
52 "Show function arglist or variable docstring in echo area."
53 :group 'lisp
54 :group 'extensions)
56 (defcustom eldoc-idle-delay 0.50
57 "Number of seconds of idle time to wait before printing.
58 If user input arrives before this interval of time has elapsed after the
59 last input, no documentation will be printed.
61 If this variable is set to 0, no idle time is required."
62 :type 'number
63 :group 'eldoc)
65 ;;;###autoload
66 (defcustom eldoc-minor-mode-string (purecopy " ElDoc")
67 "String to display in mode line when ElDoc Mode is enabled; nil for none."
68 :type '(choice string (const :tag "None" nil))
69 :group 'eldoc)
71 (defcustom eldoc-argument-case 'upcase
72 "Case to display argument names of functions, as a symbol.
73 This has two preferred values: `upcase' or `downcase'.
74 Actually, any name of a function which takes a string as an argument and
75 returns another string is acceptable.
77 Note that if `eldoc-documentation-function' is non-nil, this variable
78 has no effect, unless the function handles it explicitly."
79 :type '(radio (function-item upcase)
80 (function-item downcase)
81 function)
82 :group 'eldoc)
84 (defcustom eldoc-echo-area-use-multiline-p 'truncate-sym-name-if-fit
85 "Allow long ElDoc messages to resize echo area display.
86 If value is t, never attempt to truncate messages; complete symbol name
87 and function arglist or 1-line variable documentation will be displayed
88 even if echo area must be resized to fit.
90 If value is any non-nil value other than t, symbol name may be truncated
91 if it will enable the function arglist or documentation string to fit on a
92 single line without resizing window. Otherwise, behavior is just like
93 former case.
95 If value is nil, messages are always truncated to fit in a single line of
96 display in the echo area. Function or variable symbol name may be
97 truncated to make more of the arglist or documentation string visible.
99 Note that if `eldoc-documentation-function' is non-nil, this variable
100 has no effect, unless the function handles it explicitly."
101 :type '(radio (const :tag "Always" t)
102 (const :tag "Never" nil)
103 (const :tag "Yes, but truncate symbol names if it will\
104 enable argument list to fit on one line" truncate-sym-name-if-fit))
105 :group 'eldoc)
107 (defface eldoc-highlight-function-argument
108 '((t (:inherit bold)))
109 "Face used for the argument at point in a function's argument list.
110 Note that if `eldoc-documentation-function' is non-nil, this face
111 has no effect, unless the function handles it explicitly."
112 :group 'eldoc)
114 ;;; No user options below here.
116 (defvar eldoc-message-commands-table-size 31
117 "Used by `eldoc-add-command' to initialize `eldoc-message-commands' obarray.
118 It should probably never be necessary to do so, but if you
119 choose to increase the number of buckets, you must do so before loading
120 this file since the obarray is initialized at load time.
121 Remember to keep it a prime number to improve hash performance.")
123 (defconst eldoc-message-commands
124 (make-vector eldoc-message-commands-table-size 0)
125 "Commands after which it is appropriate to print in the echo area.
126 ElDoc does not try to print function arglists, etc., after just any command,
127 because some commands print their own messages in the echo area and these
128 functions would instantly overwrite them. But `self-insert-command' as well
129 as most motion commands are good candidates.
130 This variable contains an obarray of symbols; do not manipulate it
131 directly. Instead, use `eldoc-add-command' and `eldoc-remove-command'.")
133 ;; Not a constant.
134 (defconst eldoc-last-data (make-vector 3 nil)
135 "Bookkeeping; elements are as follows:
136 0 - contains the last symbol read from the buffer.
137 1 - contains the string last displayed in the echo area for variables,
138 or argument string for functions.
139 2 - 'function if function args, 'variable if variable documentation.")
141 (defvar eldoc-last-message nil)
143 (defvar eldoc-timer nil "ElDoc's timer object.")
145 (defvar eldoc-current-idle-delay eldoc-idle-delay
146 "Idle time delay currently in use by timer.
147 This is used to determine if `eldoc-idle-delay' is changed by the user.")
150 ;;;###autoload
151 (define-minor-mode eldoc-mode
152 "Toggle ElDoc mode on or off.
153 In ElDoc mode, the echo area displays information about a
154 function or variable in the text where point is. If point is
155 on a documented variable, it displays the first line of that
156 variable's doc string. Otherwise it displays the argument list
157 of the function called in the expression point is on.
159 With prefix ARG, turn ElDoc mode on if and only if ARG is positive."
160 :group 'eldoc :lighter eldoc-minor-mode-string
161 (setq eldoc-last-message nil)
162 (if eldoc-mode
163 (progn
164 (add-hook 'post-command-hook 'eldoc-schedule-timer nil t)
165 (add-hook 'pre-command-hook 'eldoc-pre-command-refresh-echo-area t))
166 (remove-hook 'post-command-hook 'eldoc-schedule-timer)
167 (remove-hook 'pre-command-hook 'eldoc-pre-command-refresh-echo-area)))
169 ;;;###autoload
170 (defun turn-on-eldoc-mode ()
171 "Unequivocally turn on ElDoc mode (see command `eldoc-mode')."
172 (interactive)
173 (eldoc-mode 1))
176 (defun eldoc-schedule-timer ()
177 (or (and eldoc-timer
178 (memq eldoc-timer timer-idle-list))
179 (setq eldoc-timer
180 (run-with-idle-timer eldoc-idle-delay t
181 'eldoc-print-current-symbol-info)))
183 ;; If user has changed the idle delay, update the timer.
184 (cond ((not (= eldoc-idle-delay eldoc-current-idle-delay))
185 (setq eldoc-current-idle-delay eldoc-idle-delay)
186 (timer-set-idle-time eldoc-timer eldoc-idle-delay t))))
188 (defun eldoc-message (&rest args)
189 (let ((omessage eldoc-last-message))
190 (setq eldoc-last-message
191 (cond ((eq (car args) eldoc-last-message) eldoc-last-message)
192 ((null (car args)) nil)
193 ;; If only one arg, no formatting to do, so put it in
194 ;; eldoc-last-message so eq test above might succeed on
195 ;; subsequent calls.
196 ((null (cdr args)) (car args))
197 (t (apply 'format args))))
198 ;; In emacs 19.29 and later, and XEmacs 19.13 and later, all messages
199 ;; are recorded in a log. Do not put eldoc messages in that log since
200 ;; they are Legion.
201 ;; Emacs way of preventing log messages.
202 (let ((message-log-max nil))
203 (cond (eldoc-last-message (message "%s" eldoc-last-message))
204 (omessage (message nil)))))
205 eldoc-last-message)
207 ;; This function goes on pre-command-hook for XEmacs or when using idle
208 ;; timers in Emacs. Motion commands clear the echo area for some reason,
209 ;; which make eldoc messages flicker or disappear just before motion
210 ;; begins. This function reprints the last eldoc message immediately
211 ;; before the next command executes, which does away with the flicker.
212 ;; This doesn't seem to be required for Emacs 19.28 and earlier.
213 (defun eldoc-pre-command-refresh-echo-area ()
214 (and eldoc-last-message
215 (if (eldoc-display-message-no-interference-p)
216 (eldoc-message eldoc-last-message)
217 (setq eldoc-last-message nil))))
219 ;; Decide whether now is a good time to display a message.
220 (defun eldoc-display-message-p ()
221 (and (eldoc-display-message-no-interference-p)
222 ;; If this-command is non-nil while running via an idle
223 ;; timer, we're still in the middle of executing a command,
224 ;; e.g. a query-replace where it would be annoying to
225 ;; overwrite the echo area.
226 (and (not this-command)
227 (symbolp last-command)
228 (intern-soft (symbol-name last-command)
229 eldoc-message-commands))))
231 ;; Check various conditions about the current environment that might make
232 ;; it undesirable to print eldoc messages right this instant.
233 (defun eldoc-display-message-no-interference-p ()
234 (and eldoc-mode
235 (not executing-kbd-macro)
236 (not (and (boundp 'edebug-active) edebug-active))
237 ;; Having this mode operate in an active minibuffer/echo area causes
238 ;; interference with what's going on there.
239 (not cursor-in-echo-area)
240 (not (eq (selected-window) (minibuffer-window)))))
243 ;;;###autoload
244 (defvar eldoc-documentation-function nil
245 "If non-nil, function to call to return doc string.
246 The function of no args should return a one-line string for displaying
247 doc about a function etc. appropriate to the context around point.
248 It should return nil if there's no doc appropriate for the context.
249 Typically doc is returned if point is on a function-like name or in its
250 arg list.
252 The result is used as is, so the function must explicitly handle
253 the variables `eldoc-argument-case' and `eldoc-echo-area-use-multiline-p',
254 and the face `eldoc-highlight-function-argument', if they are to have any
255 effect.
257 This variable is expected to be made buffer-local by modes (other than
258 Emacs Lisp mode) that support ElDoc.")
260 (defun eldoc-print-current-symbol-info ()
261 (condition-case err
262 (and (eldoc-display-message-p)
263 (if eldoc-documentation-function
264 (eldoc-message (funcall eldoc-documentation-function))
265 (let* ((current-symbol (eldoc-current-symbol))
266 (current-fnsym (eldoc-fnsym-in-current-sexp))
267 (doc (cond
268 ((null current-fnsym)
269 nil)
270 ((eq current-symbol (car current-fnsym))
271 (or (apply 'eldoc-get-fnsym-args-string
272 current-fnsym)
273 (eldoc-get-var-docstring current-symbol)))
275 (or (eldoc-get-var-docstring current-symbol)
276 (apply 'eldoc-get-fnsym-args-string
277 current-fnsym))))))
278 (eldoc-message doc))))
279 ;; This is run from post-command-hook or some idle timer thing,
280 ;; so we need to be careful that errors aren't ignored.
281 (error (message "eldoc error: %s" err))))
283 (defun eldoc-get-fnsym-args-string (sym &optional index)
284 "Return a string containing the parameter list of the function SYM.
285 If SYM is a subr and no arglist is obtainable from the docstring
286 or elsewhere, return a 1-line docstring. Calls the functions
287 `eldoc-function-argstring-format' and
288 `eldoc-highlight-function-argument' to format the result. The
289 former calls `eldoc-argument-case'; the latter gives the
290 function name `font-lock-function-name-face', and optionally
291 highlights argument number INDEX."
292 (let (args doc advertised)
293 (cond ((not (and sym (symbolp sym) (fboundp sym))))
294 ((and (eq sym (aref eldoc-last-data 0))
295 (eq 'function (aref eldoc-last-data 2)))
296 (setq doc (aref eldoc-last-data 1)))
297 ((listp (setq advertised (gethash (indirect-function sym)
298 advertised-signature-table t)))
299 (setq args advertised))
300 ((setq doc (help-split-fundoc (documentation sym t) sym))
301 (setq args (car doc))
302 ;; Remove any enclosing (), since e-function-argstring adds them.
303 (string-match "\\`[^ )]* ?" args)
304 (setq args (substring args (match-end 0)))
305 (if (string-match-p ")\\'" args)
306 (setq args (substring args 0 -1))))
308 (setq args (help-function-arglist sym))))
309 (if args
310 ;; Stringify, and store before highlighting, downcasing, etc.
311 ;; FIXME should truncate before storing.
312 (eldoc-last-data-store sym (setq args (eldoc-function-argstring args))
313 'function)
314 (setq args doc)) ; use stored value
315 ;; Change case, highlight, truncate.
316 (if args
317 (eldoc-highlight-function-argument
318 sym (eldoc-function-argstring-format args) index))))
320 (defun eldoc-highlight-function-argument (sym args index)
321 "Highlight argument INDEX in ARGS list for function SYM.
322 In the absence of INDEX, just call `eldoc-docstring-format-sym-doc'."
323 (let ((start nil)
324 (end 0)
325 (argument-face 'eldoc-highlight-function-argument))
326 ;; Find the current argument in the argument string. We need to
327 ;; handle `&rest' and informal `...' properly.
329 ;; FIXME: What to do with optional arguments, like in
330 ;; (defun NAME ARGLIST [DOCSTRING] BODY...) case?
331 ;; The problem is there is no robust way to determine if
332 ;; the current argument is indeed a docstring.
333 (while (and index (>= index 1))
334 (if (string-match "[^ ()]+" args end)
335 (progn
336 (setq start (match-beginning 0)
337 end (match-end 0))
338 (let ((argument (match-string 0 args)))
339 (cond ((string= argument "&rest")
340 ;; All the rest arguments are the same.
341 (setq index 1))
342 ((string= argument "&optional"))
343 ((string-match-p "\\.\\.\\.$" argument)
344 (setq index 0))
346 (setq index (1- index))))))
347 (setq end (length args)
348 start (1- end)
349 argument-face 'font-lock-warning-face
350 index 0)))
351 (let ((doc args))
352 (when start
353 (setq doc (copy-sequence args))
354 (add-text-properties start end (list 'face argument-face) doc))
355 (setq doc (eldoc-docstring-format-sym-doc
356 sym doc 'font-lock-function-name-face))
357 doc)))
359 ;; Return a string containing a brief (one-line) documentation string for
360 ;; the variable.
361 (defun eldoc-get-var-docstring (sym)
362 (when sym
363 (cond ((and (eq sym (aref eldoc-last-data 0))
364 (eq 'variable (aref eldoc-last-data 2)))
365 (aref eldoc-last-data 1))
367 (let ((doc (documentation-property sym 'variable-documentation t)))
368 (cond (doc
369 (setq doc (eldoc-docstring-format-sym-doc
370 sym (eldoc-docstring-first-line doc)
371 'font-lock-variable-name-face))
372 (eldoc-last-data-store sym doc 'variable)))
373 doc)))))
375 (defun eldoc-last-data-store (symbol doc type)
376 (aset eldoc-last-data 0 symbol)
377 (aset eldoc-last-data 1 doc)
378 (aset eldoc-last-data 2 type))
380 ;; Note that any leading `*' in the docstring (which indicates the variable
381 ;; is a user option) is removed.
382 (defun eldoc-docstring-first-line (doc)
383 (and (stringp doc)
384 (substitute-command-keys
385 (save-match-data
386 ;; Don't use "^" in the regexp below since it may match
387 ;; anywhere in the doc-string.
388 (let ((start (if (string-match "\\`\\*" doc) (match-end 0) 0)))
389 (cond ((string-match "\n" doc)
390 (substring doc start (match-beginning 0)))
391 ((zerop start) doc)
392 (t (substring doc start))))))))
394 ;; If the entire line cannot fit in the echo area, the symbol name may be
395 ;; truncated or eliminated entirely from the output to make room for the
396 ;; description.
397 (defun eldoc-docstring-format-sym-doc (sym doc face)
398 (save-match-data
399 (let* ((name (symbol-name sym))
400 (ea-multi eldoc-echo-area-use-multiline-p)
401 ;; Subtract 1 from window width since emacs will not write
402 ;; any chars to the last column, or in later versions, will
403 ;; cause a wraparound and resize of the echo area.
404 (ea-width (1- (window-width (minibuffer-window))))
405 (strip (- (+ (length name) (length ": ") (length doc)) ea-width)))
406 (cond ((or (<= strip 0)
407 (eq ea-multi t)
408 (and ea-multi (> (length doc) ea-width)))
409 (format "%s: %s" (propertize name 'face face) doc))
410 ((> (length doc) ea-width)
411 (substring (format "%s" doc) 0 ea-width))
412 ((>= strip (length name))
413 (format "%s" doc))
415 ;; Show the end of the partial symbol name, rather
416 ;; than the beginning, since the former is more likely
417 ;; to be unique given package namespace conventions.
418 (setq name (substring name strip))
419 (format "%s: %s" (propertize name 'face face) doc))))))
422 ;; Return a list of current function name and argument index.
423 (defun eldoc-fnsym-in-current-sexp ()
424 (save-excursion
425 (let ((argument-index (1- (eldoc-beginning-of-sexp))))
426 ;; If we are at the beginning of function name, this will be -1.
427 (when (< argument-index 0)
428 (setq argument-index 0))
429 ;; Don't do anything if current word is inside a string.
430 (if (= (or (char-after (1- (point))) 0) ?\")
432 (list (eldoc-current-symbol) argument-index)))))
434 ;; Move to the beginnig of current sexp. Return the number of nested
435 ;; sexp the point was over or after.
436 (defun eldoc-beginning-of-sexp ()
437 (let ((parse-sexp-ignore-comments t)
438 (num-skipped-sexps 0))
439 (condition-case err
440 (progn
441 ;; First account for the case the point is directly over a
442 ;; beginning of a nested sexp.
443 (condition-case err
444 (let ((p (point)))
445 (forward-sexp -1)
446 (forward-sexp 1)
447 (when (< (point) p)
448 (setq num-skipped-sexps 1)))
449 (error))
450 (while
451 (let ((p (point)))
452 (forward-sexp -1)
453 (when (< (point) p)
454 (setq num-skipped-sexps (1+ num-skipped-sexps))))))
455 (error))
456 num-skipped-sexps))
458 ;; returns nil unless current word is an interned symbol.
459 (defun eldoc-current-symbol ()
460 (let ((c (char-after (point))))
461 (and c
462 (memq (char-syntax c) '(?w ?_))
463 (intern-soft (current-word)))))
465 ;; Do indirect function resolution if possible.
466 (defun eldoc-symbol-function (fsym)
467 (let ((defn (and (fboundp fsym)
468 (symbol-function fsym))))
469 (and (symbolp defn)
470 (condition-case err
471 (setq defn (indirect-function fsym))
472 (error (setq defn nil))))
473 defn))
475 (defun eldoc-function-argstring (arglist)
476 "Return ARGLIST as a string enclosed by ().
477 ARGLIST is either a string, or a list of strings or symbols."
478 (cond ((stringp arglist))
479 ((not (listp arglist))
480 (setq arglist nil))
481 ((symbolp (car arglist))
482 (setq arglist
483 (mapconcat (lambda (s) (symbol-name s))
484 arglist " ")))
485 ((stringp (car arglist))
486 (setq arglist
487 (mapconcat (lambda (s) s)
488 arglist " "))))
489 (if arglist
490 (format "(%s)" arglist)))
492 (defun eldoc-function-argstring-format (argstring)
493 "Apply `eldoc-argument-case' to each word in ARGSTRING.
494 The words \"&rest\", \"&optional\" are returned unchanged."
495 (mapconcat (lambda (s)
496 (if (string-match-p "\\`(?&\\(?:optional\\|rest\\))?\\'" s)
498 (funcall eldoc-argument-case s)))
499 (split-string argstring) " "))
502 ;; When point is in a sexp, the function args are not reprinted in the echo
503 ;; area after every possible interactive command because some of them print
504 ;; their own messages in the echo area; the eldoc functions would instantly
505 ;; overwrite them unless it is more restrained.
506 ;; These functions do display-command table management.
508 (defun eldoc-add-command (&rest cmds)
509 (dolist (name cmds)
510 (and (symbolp name)
511 (setq name (symbol-name name)))
512 (set (intern name eldoc-message-commands) t)))
514 (defun eldoc-add-command-completions (&rest names)
515 (dolist (name names)
516 (apply 'eldoc-add-command (all-completions name obarray 'commandp))))
518 (defun eldoc-remove-command (&rest cmds)
519 (dolist (name cmds)
520 (and (symbolp name)
521 (setq name (symbol-name name)))
522 (unintern name eldoc-message-commands)))
524 (defun eldoc-remove-command-completions (&rest names)
525 (dolist (name names)
526 (apply 'eldoc-remove-command
527 (all-completions name eldoc-message-commands))))
530 ;; Prime the command list.
531 (eldoc-add-command-completions
532 "backward-" "beginning-of-" "delete-other-windows" "delete-window"
533 "down-list" "end-of-" "exchange-point-and-mark" "forward-" "goto-"
534 "handle-select-window" "indent-for-tab-command" "left-" "mark-page"
535 "mark-paragraph" "mouse-set-point" "move-" "move-beginning-of-"
536 "move-end-of-" "next-" "other-window" "pop-global-mark" "previous-"
537 "recenter" "right-" "scroll-" "self-insert-command" "split-window-"
538 "up-list")
540 (provide 'eldoc)
542 ;;; eldoc.el ends here