elisp-completion-at-point: Prioritize being quoted over funpos
[emacs.git] / lisp / progmodes / elisp-mode.el
blob7c9a2d7c4227164ddaaeb48c04bb788d9d15bd5f
1 ;;; elisp-mode.el --- Emacs Lisp mode -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1986, 1999-2015 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: lisp, languages
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; The major mode for editing Emacs Lisp code.
27 ;; This mode is documented in the Emacs manual.
29 ;;; Code:
31 (require 'lisp-mode)
33 (define-abbrev-table 'emacs-lisp-mode-abbrev-table ()
34 "Abbrev table for Emacs Lisp mode.
35 It has `lisp-mode-abbrev-table' as its parent."
36 :parents (list lisp-mode-abbrev-table))
38 (defvar emacs-lisp-mode-syntax-table
39 (let ((table (make-syntax-table lisp--mode-syntax-table)))
40 (modify-syntax-entry ?\[ "(] " table)
41 (modify-syntax-entry ?\] ")[ " table)
42 table)
43 "Syntax table used in `emacs-lisp-mode'.")
45 (defvar emacs-lisp-mode-map
46 (let ((map (make-sparse-keymap "Emacs-Lisp"))
47 (menu-map (make-sparse-keymap "Emacs-Lisp"))
48 (lint-map (make-sparse-keymap))
49 (prof-map (make-sparse-keymap))
50 (tracing-map (make-sparse-keymap)))
51 (set-keymap-parent map lisp-mode-shared-map)
52 (define-key map "\e\t" 'completion-at-point)
53 (define-key map "\e\C-x" 'eval-defun)
54 (define-key map "\e\C-q" 'indent-pp-sexp)
55 (bindings--define-key map [menu-bar emacs-lisp]
56 (cons "Emacs-Lisp" menu-map))
57 (bindings--define-key menu-map [eldoc]
58 '(menu-item "Auto-Display Documentation Strings" eldoc-mode
59 :button (:toggle . (bound-and-true-p eldoc-mode))
60 :help "Display the documentation string for the item under cursor"))
61 (bindings--define-key menu-map [checkdoc]
62 '(menu-item "Check Documentation Strings" checkdoc
63 :help "Check documentation strings for style requirements"))
64 (bindings--define-key menu-map [re-builder]
65 '(menu-item "Construct Regexp" re-builder
66 :help "Construct a regexp interactively"))
67 (bindings--define-key menu-map [tracing] (cons "Tracing" tracing-map))
68 (bindings--define-key tracing-map [tr-a]
69 '(menu-item "Untrace All" untrace-all
70 :help "Untrace all currently traced functions"))
71 (bindings--define-key tracing-map [tr-uf]
72 '(menu-item "Untrace Function..." untrace-function
73 :help "Untrace function, and possibly activate all remaining advice"))
74 (bindings--define-key tracing-map [tr-sep] menu-bar-separator)
75 (bindings--define-key tracing-map [tr-q]
76 '(menu-item "Trace Function Quietly..." trace-function-background
77 :help "Trace the function with trace output going quietly to a buffer"))
78 (bindings--define-key tracing-map [tr-f]
79 '(menu-item "Trace Function..." trace-function
80 :help "Trace the function given as an argument"))
81 (bindings--define-key menu-map [profiling] (cons "Profiling" prof-map))
82 (bindings--define-key prof-map [prof-restall]
83 '(menu-item "Remove Instrumentation for All Functions" elp-restore-all
84 :help "Restore the original definitions of all functions being profiled"))
85 (bindings--define-key prof-map [prof-restfunc]
86 '(menu-item "Remove Instrumentation for Function..." elp-restore-function
87 :help "Restore an instrumented function to its original definition"))
89 (bindings--define-key prof-map [sep-rem] menu-bar-separator)
90 (bindings--define-key prof-map [prof-resall]
91 '(menu-item "Reset Counters for All Functions" elp-reset-all
92 :help "Reset the profiling information for all functions being profiled"))
93 (bindings--define-key prof-map [prof-resfunc]
94 '(menu-item "Reset Counters for Function..." elp-reset-function
95 :help "Reset the profiling information for a function"))
96 (bindings--define-key prof-map [prof-res]
97 '(menu-item "Show Profiling Results" elp-results
98 :help "Display current profiling results"))
99 (bindings--define-key prof-map [prof-pack]
100 '(menu-item "Instrument Package..." elp-instrument-package
101 :help "Instrument for profiling all function that start with a prefix"))
102 (bindings--define-key prof-map [prof-func]
103 '(menu-item "Instrument Function..." elp-instrument-function
104 :help "Instrument a function for profiling"))
105 ;; Maybe this should be in a separate submenu from the ELP stuff?
106 (bindings--define-key prof-map [sep-natprof] menu-bar-separator)
107 (bindings--define-key prof-map [prof-natprof-stop]
108 '(menu-item "Stop Native Profiler" profiler-stop
109 :help "Stop recording profiling information"
110 :enable (and (featurep 'profiler)
111 (profiler-running-p))))
112 (bindings--define-key prof-map [prof-natprof-report]
113 '(menu-item "Show Profiler Report" profiler-report
114 :help "Show the current profiler report"
115 :enable (and (featurep 'profiler)
116 (profiler-running-p))))
117 (bindings--define-key prof-map [prof-natprof-start]
118 '(menu-item "Start Native Profiler..." profiler-start
119 :help "Start recording profiling information"))
121 (bindings--define-key menu-map [lint] (cons "Linting" lint-map))
122 (bindings--define-key lint-map [lint-di]
123 '(menu-item "Lint Directory..." elint-directory
124 :help "Lint a directory"))
125 (bindings--define-key lint-map [lint-f]
126 '(menu-item "Lint File..." elint-file
127 :help "Lint a file"))
128 (bindings--define-key lint-map [lint-b]
129 '(menu-item "Lint Buffer" elint-current-buffer
130 :help "Lint the current buffer"))
131 (bindings--define-key lint-map [lint-d]
132 '(menu-item "Lint Defun" elint-defun
133 :help "Lint the function at point"))
134 (bindings--define-key menu-map [edebug-defun]
135 '(menu-item "Instrument Function for Debugging" edebug-defun
136 :help "Evaluate the top level form point is in, stepping through with Edebug"
137 :keys "C-u C-M-x"))
138 (bindings--define-key menu-map [separator-byte] menu-bar-separator)
139 (bindings--define-key menu-map [disas]
140 '(menu-item "Disassemble Byte Compiled Object..." disassemble
141 :help "Print disassembled code for OBJECT in a buffer"))
142 (bindings--define-key menu-map [byte-recompile]
143 '(menu-item "Byte-recompile Directory..." byte-recompile-directory
144 :help "Recompile every `.el' file in DIRECTORY that needs recompilation"))
145 (bindings--define-key menu-map [emacs-byte-compile-and-load]
146 '(menu-item "Byte-compile and Load" emacs-lisp-byte-compile-and-load
147 :help "Byte-compile the current file (if it has changed), then load compiled code"))
148 (bindings--define-key menu-map [byte-compile]
149 '(menu-item "Byte-compile This File" emacs-lisp-byte-compile
150 :help "Byte compile the file containing the current buffer"))
151 (bindings--define-key menu-map [separator-eval] menu-bar-separator)
152 (bindings--define-key menu-map [ielm]
153 '(menu-item "Interactive Expression Evaluation" ielm
154 :help "Interactively evaluate Emacs Lisp expressions"))
155 (bindings--define-key menu-map [eval-buffer]
156 '(menu-item "Evaluate Buffer" eval-buffer
157 :help "Execute the current buffer as Lisp code"))
158 (bindings--define-key menu-map [eval-region]
159 '(menu-item "Evaluate Region" eval-region
160 :help "Execute the region as Lisp code"
161 :enable mark-active))
162 (bindings--define-key menu-map [eval-sexp]
163 '(menu-item "Evaluate Last S-expression" eval-last-sexp
164 :help "Evaluate sexp before point; print value in echo area"))
165 (bindings--define-key menu-map [separator-format] menu-bar-separator)
166 (bindings--define-key menu-map [comment-region]
167 '(menu-item "Comment Out Region" comment-region
168 :help "Comment or uncomment each line in the region"
169 :enable mark-active))
170 (bindings--define-key menu-map [indent-region]
171 '(menu-item "Indent Region" indent-region
172 :help "Indent each nonblank line in the region"
173 :enable mark-active))
174 (bindings--define-key menu-map [indent-line]
175 '(menu-item "Indent Line" lisp-indent-line))
176 map)
177 "Keymap for Emacs Lisp mode.
178 All commands in `lisp-mode-shared-map' are inherited by this map.")
180 (defun emacs-lisp-byte-compile ()
181 "Byte compile the file containing the current buffer."
182 (interactive)
183 (if buffer-file-name
184 (byte-compile-file buffer-file-name)
185 (error "The buffer must be saved in a file first")))
187 (defun emacs-lisp-byte-compile-and-load ()
188 "Byte-compile the current file (if it has changed), then load compiled code."
189 (interactive)
190 (or buffer-file-name
191 (error "The buffer must be saved in a file first"))
192 (require 'bytecomp)
193 ;; Recompile if file or buffer has changed since last compilation.
194 (if (and (buffer-modified-p)
195 (y-or-n-p (format "Save buffer %s first? " (buffer-name))))
196 (save-buffer))
197 (byte-recompile-file buffer-file-name nil 0 t))
199 (defun emacs-lisp-macroexpand ()
200 "Macroexpand the form after point.
201 Comments in the form will be lost."
202 (interactive)
203 (let* ((start (point))
204 (exp (read (current-buffer)))
205 ;; Compute it before, since it may signal errors.
206 (new (macroexpand-1 exp)))
207 (if (equal exp new)
208 (message "Not a macro call, nothing to expand")
209 (delete-region start (point))
210 (pp new (current-buffer))
211 (if (bolp) (delete-char -1))
212 (indent-region start (point)))))
214 (defcustom emacs-lisp-mode-hook nil
215 "Hook run when entering Emacs Lisp mode."
216 :options '(eldoc-mode imenu-add-menubar-index checkdoc-minor-mode)
217 :type 'hook
218 :group 'lisp)
220 ;;;###autoload
221 (define-derived-mode emacs-lisp-mode prog-mode "Emacs-Lisp"
222 "Major mode for editing Lisp code to run in Emacs.
223 Commands:
224 Delete converts tabs to spaces as it moves back.
225 Blank lines separate paragraphs. Semicolons start comments.
227 \\{emacs-lisp-mode-map}"
228 :group 'lisp
229 (defvar xref-find-function)
230 (defvar xref-identifier-completion-table-function)
231 (lisp-mode-variables nil nil 'elisp)
232 (add-hook 'after-load-functions #'elisp--font-lock-flush-elisp-buffers)
233 (setq-local electric-pair-text-pairs
234 (cons '(?\` . ?\') electric-pair-text-pairs))
235 (setq imenu-case-fold-search nil)
236 (add-function :before-until (local 'eldoc-documentation-function)
237 #'elisp-eldoc-documentation-function)
238 (setq-local xref-find-function #'elisp-xref-find)
239 (setq-local xref-identifier-completion-table-function
240 #'elisp--xref-identifier-completion-table)
241 (add-hook 'completion-at-point-functions
242 #'elisp-completion-at-point nil 'local))
244 ;; Font-locking support.
246 (defun elisp--font-lock-flush-elisp-buffers (&optional file)
247 ;; FIXME: Aren't we only ever called from after-load-functions?
248 ;; Don't flush during load unless called from after-load-functions.
249 ;; In that case, FILE is non-nil. It's somehow strange that
250 ;; load-in-progress is t when an after-load-function is called since
251 ;; that should run *after* the load...
252 (when (or (not load-in-progress) file)
253 ;; FIXME: If the loaded file did not define any macros, there shouldn't
254 ;; be any need to font-lock-flush all the Elisp buffers.
255 (dolist (buf (buffer-list))
256 (with-current-buffer buf
257 (when (derived-mode-p 'emacs-lisp-mode)
258 ;; So as to take into account new macros that may have been defined
259 ;; by the just-loaded file.
260 (font-lock-flush))))))
262 ;;; Completion at point for Elisp
264 (defun elisp--local-variables-1 (vars sexp)
265 "Return the vars locally bound around the witness, or nil if not found."
266 (let (res)
267 (while
268 (unless
269 (setq res
270 (pcase sexp
271 (`(,(or `let `let*) ,bindings)
272 (let ((vars vars))
273 (when (eq 'let* (car sexp))
274 (dolist (binding (cdr (reverse bindings)))
275 (push (or (car-safe binding) binding) vars)))
276 (elisp--local-variables-1
277 vars (car (cdr-safe (car (last bindings)))))))
278 (`(,(or `let `let*) ,bindings . ,body)
279 (let ((vars vars))
280 (dolist (binding bindings)
281 (push (or (car-safe binding) binding) vars))
282 (elisp--local-variables-1 vars (car (last body)))))
283 (`(lambda ,_args)
284 ;; FIXME: Look for the witness inside `args'.
285 (setq sexp nil))
286 (`(lambda ,args . ,body)
287 (elisp--local-variables-1
288 (append (remq '&optional (remq '&rest args)) vars)
289 (car (last body))))
290 (`(condition-case ,_ ,e) (elisp--local-variables-1 vars e))
291 (`(condition-case ,v ,_ . ,catches)
292 (elisp--local-variables-1
293 (cons v vars) (cdr (car (last catches)))))
294 (`(quote . ,_)
295 ;; FIXME: Look for the witness inside sexp.
296 (setq sexp nil))
297 ;; FIXME: Handle `cond'.
298 (`(,_ . ,_)
299 (elisp--local-variables-1 vars (car (last sexp))))
300 (`elisp--witness--lisp (or vars '(nil)))
301 (_ nil)))
302 ;; We didn't find the witness in the last element so we try to
303 ;; backtrack to the last-but-one.
304 (setq sexp (ignore-errors (butlast sexp)))))
305 res))
307 (defun elisp--local-variables ()
308 "Return a list of locally let-bound variables at point."
309 (save-excursion
310 (skip-syntax-backward "w_")
311 (let* ((ppss (syntax-ppss))
312 (txt (buffer-substring-no-properties (or (car (nth 9 ppss)) (point))
313 (or (nth 8 ppss) (point))))
314 (closer ()))
315 (dolist (p (nth 9 ppss))
316 (push (cdr (syntax-after p)) closer))
317 (setq closer (apply #'string closer))
318 (let* ((sexp (condition-case nil
319 (car (read-from-string
320 (concat txt "elisp--witness--lisp" closer)))
321 ((invalid-read-syntax end-of-file) nil)))
322 (macroexpand-advice (lambda (expander form &rest args)
323 (condition-case nil
324 (apply expander form args)
325 (error form))))
326 (sexp
327 (unwind-protect
328 (progn
329 (advice-add 'macroexpand :around macroexpand-advice)
330 (macroexpand-all sexp))
331 (advice-remove 'macroexpand macroexpand-advice)))
332 (vars (elisp--local-variables-1 nil sexp)))
333 (delq nil
334 (mapcar (lambda (var)
335 (and (symbolp var)
336 (not (string-match (symbol-name var) "\\`[&_]"))
337 ;; Eliminate uninterned vars.
338 (intern-soft var)
339 var))
340 vars))))))
342 (defvar elisp--local-variables-completion-table
343 ;; Use `defvar' rather than `defconst' since defconst would purecopy this
344 ;; value, which would doubly fail: it would fail because purecopy can't
345 ;; handle the recursive bytecode object, and it would fail because it would
346 ;; move `lastpos' and `lastvars' to pure space where they'd be immutable!
347 (let ((lastpos nil) (lastvars nil))
348 (letrec ((hookfun (lambda ()
349 (setq lastpos nil)
350 (remove-hook 'post-command-hook hookfun))))
351 (completion-table-dynamic
352 (lambda (_string)
353 (save-excursion
354 (skip-syntax-backward "_w")
355 (let ((newpos (cons (point) (current-buffer))))
356 (unless (equal lastpos newpos)
357 (add-hook 'post-command-hook hookfun)
358 (setq lastpos newpos)
359 (setq lastvars
360 (mapcar #'symbol-name (elisp--local-variables))))))
361 lastvars)))))
363 (defun elisp--expect-function-p (pos)
364 "Return non-nil if the symbol at point is expected to be a function."
366 (and (eq (char-before pos) ?')
367 (eq (char-before (1- pos)) ?#))
368 (save-excursion
369 (let ((parent (nth 1 (syntax-ppss pos))))
370 (when parent
371 (goto-char parent)
372 (and
373 (looking-at (concat "(\\(cl-\\)?"
374 (regexp-opt '("declare-function"
375 "function" "defadvice"
376 "callf" "callf2"
377 "defsetf"))
378 "[ \t\r\n]+"))
379 (eq (match-end 0) pos)))))))
381 (defun elisp--form-quoted-p (pos)
382 "Return non-nil if the form at POS is not evaluated.
383 It can be quoted, or be inside a quoted form."
384 ;; FIXME: Do some macro expansion maybe.
385 (save-excursion
386 (let ((state (syntax-ppss pos)))
387 (or (nth 8 state) ; Code inside strings usually isn't evaluated.
388 ;; FIXME: The 9th element is undocumented.
389 (let ((nesting (cons (point) (reverse (nth 9 state))))
390 res)
391 (while (and nesting (not res))
392 (goto-char (pop nesting))
393 (cond
394 ((or (eq (char-after) ?\[)
395 (progn
396 (skip-chars-backward " ")
397 (memq (char-before) '(?' ?`))))
398 (setq res t))
399 ((eq (char-before) ?,)
400 (setq nesting nil))))
401 res)))))
403 ;; FIXME: Support for Company brings in features which straddle eldoc.
404 ;; We should consolidate this, so that major modes can provide all that
405 ;; data all at once:
406 ;; - a function to extract "the reference at point" (may be more complex
407 ;; than a mere string, to distinguish various namespaces).
408 ;; - a function to jump to such a reference.
409 ;; - a function to show the signature/interface of such a reference.
410 ;; - a function to build a help-buffer about that reference.
411 ;; FIXME: Those functions should also be used by the normal completion code in
412 ;; the *Completions* buffer.
414 (defun elisp--company-doc-buffer (str)
415 (let ((symbol (intern-soft str)))
416 ;; FIXME: we really don't want to "display-buffer and then undo it".
417 (save-window-excursion
418 ;; Make sure we don't display it in another frame, otherwise
419 ;; save-window-excursion won't be able to undo it.
420 (let ((display-buffer-overriding-action
421 '(nil . ((inhibit-switch-frame . t)))))
422 (ignore-errors
423 (cond
424 ((fboundp symbol) (describe-function symbol))
425 ((boundp symbol) (describe-variable symbol))
426 ((featurep symbol) (describe-package symbol))
427 ((facep symbol) (describe-face symbol))
428 (t (signal 'user-error nil)))
429 (help-buffer))))))
431 (defun elisp--company-doc-string (str)
432 (let* ((symbol (intern-soft str))
433 (doc (if (fboundp symbol)
434 (documentation symbol t)
435 (documentation-property symbol 'variable-documentation t))))
436 (and (stringp doc)
437 (string-match ".*$" doc)
438 (match-string 0 doc))))
440 (declare-function find-library-name "find-func" (library))
441 (declare-function find-function-library "find-func" (function &optional l-o v))
443 (defun elisp--company-location (str)
444 (let ((sym (intern-soft str)))
445 (cond
446 ((fboundp sym) (find-definition-noselect sym nil))
447 ((boundp sym) (find-definition-noselect sym 'defvar))
448 ((featurep sym)
449 (require 'find-func)
450 (cons (find-file-noselect (find-library-name
451 (symbol-name sym)))
453 ((facep sym) (find-definition-noselect sym 'defface)))))
455 (defun elisp-completion-at-point ()
456 "Function used for `completion-at-point-functions' in `emacs-lisp-mode'."
457 (with-syntax-table emacs-lisp-mode-syntax-table
458 (let* ((pos (point))
459 (beg (condition-case nil
460 (save-excursion
461 (backward-sexp 1)
462 (skip-syntax-forward "'")
463 (point))
464 (scan-error pos)))
465 (end
466 (unless (or (eq beg (point-max))
467 (member (char-syntax (char-after beg))
468 '(?\s ?\" ?\( ?\))))
469 (condition-case nil
470 (save-excursion
471 (goto-char beg)
472 (forward-sexp 1)
473 (skip-chars-backward "'")
474 (when (>= (point) pos)
475 (point)))
476 (scan-error pos))))
477 ;; t if in function position.
478 (funpos (eq (char-before beg) ?\())
479 (quoted (elisp--form-quoted-p beg)))
480 (when (and end (or (not (nth 8 (syntax-ppss)))
481 (eq (char-before beg) ?`)))
482 (let ((table-etc
483 (if (or (not funpos) quoted)
484 ;; FIXME: We could look at the first element of the list and
485 ;; use it to provide a more specific completion table in some
486 ;; cases. E.g. filter out keywords that are not understood by
487 ;; the macro/function being called.
488 (cond
489 ((elisp--expect-function-p beg)
490 (list nil obarray
491 :predicate #'fboundp
492 :company-doc-buffer #'elisp--company-doc-buffer
493 :company-docsig #'elisp--company-doc-string
494 :company-location #'elisp--company-location))
495 (quoted
496 (list nil obarray
497 ;; Don't include all symbols (bug#16646).
498 :predicate (lambda (sym)
499 (or (boundp sym)
500 (fboundp sym)
501 (featurep sym)
502 (symbol-plist sym)))
503 :annotation-function
504 (lambda (str) (if (fboundp (intern-soft str)) " <f>"))
505 :company-doc-buffer #'elisp--company-doc-buffer
506 :company-docsig #'elisp--company-doc-string
507 :company-location #'elisp--company-location))
509 (list nil (completion-table-merge
510 elisp--local-variables-completion-table
511 (apply-partially #'completion-table-with-predicate
512 obarray
513 #'boundp
514 'strict))
515 :company-doc-buffer #'elisp--company-doc-buffer
516 :company-docsig #'elisp--company-doc-string
517 :company-location #'elisp--company-location)))
518 ;; Looks like a funcall position. Let's double check.
519 (save-excursion
520 (goto-char (1- beg))
521 (let ((parent
522 (condition-case nil
523 (progn (up-list -1) (forward-char 1)
524 (let ((c (char-after)))
525 (if (eq c ?\() ?\(
526 (if (memq (char-syntax c) '(?w ?_))
527 (read (current-buffer))))))
528 (error nil))))
529 (pcase parent
530 ;; FIXME: Rather than hardcode special cases here,
531 ;; we should use something like a symbol-property.
532 (`declare
533 (list t (mapcar (lambda (x) (symbol-name (car x)))
534 (delete-dups
535 ;; FIXME: We should include some
536 ;; docstring with each entry.
537 (append
538 macro-declarations-alist
539 defun-declarations-alist)))))
540 ((and (or `condition-case `condition-case-unless-debug)
541 (guard (save-excursion
542 (ignore-errors
543 (forward-sexp 2)
544 (< (point) beg)))))
545 (list t obarray
546 :predicate (lambda (sym) (get sym 'error-conditions))))
547 ((and ?\(
548 (guard (save-excursion
549 (goto-char (1- beg))
550 (up-list -1)
551 (forward-symbol -1)
552 (looking-at "\\_<let\\*?\\_>"))))
553 (list t obarray
554 :predicate #'boundp
555 :company-doc-buffer #'elisp--company-doc-buffer
556 :company-docsig #'elisp--company-doc-string
557 :company-location #'elisp--company-location))
558 (_ (list nil obarray
559 :predicate #'fboundp
560 :company-doc-buffer #'elisp--company-doc-buffer
561 :company-docsig #'elisp--company-doc-string
562 :company-location #'elisp--company-location
563 ))))))))
564 (nconc (list beg end)
565 (if (null (car table-etc))
566 (cdr table-etc)
567 (cons
568 (if (memq (char-syntax (or (char-after end) ?\s))
569 '(?\s ?>))
570 (cadr table-etc)
571 (apply-partially 'completion-table-with-terminator
572 " " (cadr table-etc)))
573 (cddr table-etc)))))))))
575 (define-obsolete-function-alias
576 'lisp-completion-at-point 'elisp-completion-at-point "25.1")
578 ;;; Xref backend
580 (declare-function xref-make-elisp-location "xref" (symbol type file))
581 (declare-function xref-make-bogus-location "xref" (message))
582 (declare-function xref-make "xref" (description location))
584 (defun elisp-xref-find (action id)
585 (require 'find-func)
586 (pcase action
587 (`definitions
588 (let ((sym (intern-soft id)))
589 (when sym
590 (elisp--xref-find-definitions sym))))
591 (`references
592 (elisp--xref-find-references id))
593 (`apropos
594 (elisp--xref-find-apropos id))))
596 (defun elisp--xref-identifier-location (type sym)
597 (let ((file
598 (pcase type
599 (`defun (when (fboundp sym)
600 (let ((fun-lib
601 (find-function-library sym)))
602 (setq sym (car fun-lib))
603 (cdr fun-lib))))
604 (`defvar (and (boundp sym)
605 ;; Don't show minor modes twice.
606 ;; TODO: If TYPE ever becomes dependent on the
607 ;; context, move this check outside.
608 (not (fboundp sym))
609 (or (symbol-file sym 'defvar)
610 (help-C-file-name sym 'var))))
611 (`feature (and (featurep sym)
612 ;; Skip when a function with the same name
613 ;; is defined, because it's probably in the
614 ;; same file.
615 (not (fboundp sym))
616 (ignore-errors
617 (find-library-name (symbol-name sym)))))
618 (`defface (when (facep sym)
619 (symbol-file sym 'defface))))))
620 (when file
621 (when (string-match-p "\\.elc\\'" file)
622 (setq file (substring file 0 -1)))
623 (xref-make-elisp-location sym type file))))
625 (defun elisp--xref-find-definitions (symbol)
626 (save-excursion
627 (let (lst)
628 (dolist (type '(feature defface defvar defun))
629 (let ((loc
630 (condition-case err
631 (elisp--xref-identifier-location type symbol)
632 (error
633 (xref-make-bogus-location (error-message-string err))))))
634 (when loc
635 (push
636 (xref-make (format "(%s %s)" type symbol)
637 loc)
638 lst))))
639 lst)))
641 (defun elisp--xref-find-references (symbol)
642 (let* ((dirs (sort
643 (mapcar
644 (lambda (dir)
645 (file-name-as-directory (expand-file-name dir)))
646 (cons package-user-dir load-path))
647 #'string<))
648 (ref dirs))
649 ;; Delete subdirectories from the list.
650 (while (cdr ref)
651 (if (string-prefix-p (car ref) (cadr ref))
652 (setcdr ref (cddr ref))
653 (setq ref (cdr ref))))
654 (cl-mapcan
655 (lambda (dir)
656 (and (file-exists-p dir)
657 (xref-collect-references symbol dir)))
658 dirs)))
660 (defun elisp--xref-find-apropos (regexp)
661 (apply #'nconc
662 (let (lst)
663 (dolist (sym (apropos-internal regexp))
664 (push (elisp--xref-find-definitions sym) lst))
665 (nreverse lst))))
667 (defvar elisp--xref-identifier-completion-table
668 (apply-partially #'completion-table-with-predicate
669 obarray
670 (lambda (sym)
671 (or (boundp sym)
672 (fboundp sym)
673 (featurep sym)
674 (facep sym)))
675 'strict))
677 (defun elisp--xref-identifier-completion-table ()
678 elisp--xref-identifier-completion-table)
680 ;;; Elisp Interaction mode
682 (defvar lisp-interaction-mode-map
683 (let ((map (make-sparse-keymap))
684 (menu-map (make-sparse-keymap "Lisp-Interaction")))
685 (set-keymap-parent map lisp-mode-shared-map)
686 (define-key map "\e\C-x" 'eval-defun)
687 (define-key map "\e\C-q" 'indent-pp-sexp)
688 (define-key map "\e\t" 'completion-at-point)
689 (define-key map "\n" 'eval-print-last-sexp)
690 (bindings--define-key map [menu-bar lisp-interaction]
691 (cons "Lisp-Interaction" menu-map))
692 (bindings--define-key menu-map [eval-defun]
693 '(menu-item "Evaluate Defun" eval-defun
694 :help "Evaluate the top-level form containing point, or after point"))
695 (bindings--define-key menu-map [eval-print-last-sexp]
696 '(menu-item "Evaluate and Print" eval-print-last-sexp
697 :help "Evaluate sexp before point; print value into current buffer"))
698 (bindings--define-key menu-map [edebug-defun-lisp-interaction]
699 '(menu-item "Instrument Function for Debugging" edebug-defun
700 :help "Evaluate the top level form point is in, stepping through with Edebug"
701 :keys "C-u C-M-x"))
702 (bindings--define-key menu-map [indent-pp-sexp]
703 '(menu-item "Indent or Pretty-Print" indent-pp-sexp
704 :help "Indent each line of the list starting just after point, or prettyprint it"))
705 (bindings--define-key menu-map [complete-symbol]
706 '(menu-item "Complete Lisp Symbol" completion-at-point
707 :help "Perform completion on Lisp symbol preceding point"))
708 map)
709 "Keymap for Lisp Interaction mode.
710 All commands in `lisp-mode-shared-map' are inherited by this map.")
712 (define-derived-mode lisp-interaction-mode emacs-lisp-mode "Lisp Interaction"
713 "Major mode for typing and evaluating Lisp forms.
714 Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
715 before point, and prints its value into the buffer, advancing point.
716 Note that printing is controlled by `eval-expression-print-length'
717 and `eval-expression-print-level'.
719 Commands:
720 Delete converts tabs to spaces as it moves back.
721 Paragraphs are separated only by blank lines.
722 Semicolons start comments.
724 \\{lisp-interaction-mode-map}"
725 :abbrev-table nil)
727 ;;; Emacs Lisp Byte-Code mode
729 (eval-and-compile
730 (defconst emacs-list-byte-code-comment-re
731 (concat "\\(#\\)@\\([0-9]+\\) "
732 ;; Make sure it's a docstring and not a lazy-loaded byte-code.
733 "\\(?:[^(]\\|([^\"]\\)")))
735 (defun elisp--byte-code-comment (end &optional _point)
736 "Try to syntactically mark the #@NNN ....^_ docstrings in byte-code files."
737 (let ((ppss (syntax-ppss)))
738 (when (and (nth 4 ppss)
739 (eq (char-after (nth 8 ppss)) ?#))
740 (let* ((n (save-excursion
741 (goto-char (nth 8 ppss))
742 (when (looking-at emacs-list-byte-code-comment-re)
743 (string-to-number (match-string 2)))))
744 ;; `maxdiff' tries to make sure the loop below terminates.
745 (maxdiff n))
746 (when n
747 (let* ((bchar (match-end 2))
748 (b (position-bytes bchar)))
749 (goto-char (+ b n))
750 (while (let ((diff (- (position-bytes (point)) b n)))
751 (unless (zerop diff)
752 (when (> diff maxdiff) (setq diff maxdiff))
753 (forward-char (- diff))
754 (setq maxdiff (if (> diff 0) diff
755 (max (1- maxdiff) 1)))
756 t))))
757 (if (<= (point) end)
758 (put-text-property (1- (point)) (point)
759 'syntax-table
760 (string-to-syntax "> b"))
761 (goto-char end)))))))
763 (defun elisp-byte-code-syntax-propertize (start end)
764 (elisp--byte-code-comment end (point))
765 (funcall
766 (syntax-propertize-rules
767 (emacs-list-byte-code-comment-re
768 (1 (prog1 "< b" (elisp--byte-code-comment end (point))))))
769 start end))
771 ;;;###autoload
772 (add-to-list 'auto-mode-alist '("\\.elc\\'" . elisp-byte-code-mode))
773 ;;;###autoload
774 (define-derived-mode elisp-byte-code-mode emacs-lisp-mode
775 "Elisp-Byte-Code"
776 "Major mode for *.elc files."
777 ;; TODO: Add way to disassemble byte-code under point.
778 (setq-local open-paren-in-column-0-is-defun-start nil)
779 (setq-local syntax-propertize-function
780 #'elisp-byte-code-syntax-propertize))
783 ;;; Globally accessible functionality
785 (defun eval-print-last-sexp (&optional eval-last-sexp-arg-internal)
786 "Evaluate sexp before point; print value into current buffer.
788 Normally, this function truncates long output according to the value
789 of the variables `eval-expression-print-length' and
790 `eval-expression-print-level'. With a prefix argument of zero,
791 however, there is no such truncation. Such a prefix argument
792 also causes integers to be printed in several additional formats
793 \(octal, hexadecimal, and character).
795 If `eval-expression-debug-on-error' is non-nil, which is the default,
796 this command arranges for all errors to enter the debugger."
797 (interactive "P")
798 (let ((standard-output (current-buffer)))
799 (terpri)
800 (eval-last-sexp (or eval-last-sexp-arg-internal t))
801 (terpri)))
804 (defun last-sexp-setup-props (beg end value alt1 alt2)
805 "Set up text properties for the output of `elisp--eval-last-sexp'.
806 BEG and END are the start and end of the output in current-buffer.
807 VALUE is the Lisp value printed, ALT1 and ALT2 are strings for the
808 alternative printed representations that can be displayed."
809 (let ((map (make-sparse-keymap)))
810 (define-key map "\C-m" 'elisp-last-sexp-toggle-display)
811 (define-key map [down-mouse-2] 'mouse-set-point)
812 (define-key map [mouse-2] 'elisp-last-sexp-toggle-display)
813 (add-text-properties
814 beg end
815 `(printed-value (,value ,alt1 ,alt2)
816 mouse-face highlight
817 keymap ,map
818 help-echo "RET, mouse-2: toggle abbreviated display"
819 rear-nonsticky (mouse-face keymap help-echo
820 printed-value)))))
823 (defun elisp-last-sexp-toggle-display (&optional _arg)
824 "Toggle between abbreviated and unabbreviated printed representations."
825 (interactive "P")
826 (save-restriction
827 (widen)
828 (let ((value (get-text-property (point) 'printed-value)))
829 (when value
830 (let ((beg (or (previous-single-property-change (min (point-max) (1+ (point)))
831 'printed-value)
832 (point)))
833 (end (or (next-single-char-property-change (point) 'printed-value) (point)))
834 (standard-output (current-buffer))
835 (point (point)))
836 (delete-region beg end)
837 (insert (nth 1 value))
838 (or (= beg point)
839 (setq point (1- (point))))
840 (last-sexp-setup-props beg (point)
841 (nth 0 value)
842 (nth 2 value)
843 (nth 1 value))
844 (goto-char (min (point-max) point)))))))
846 (defun prin1-char (char) ;FIXME: Move it, e.g. to simple.el.
847 "Return a string representing CHAR as a character rather than as an integer.
848 If CHAR is not a character, return nil."
849 (and (integerp char)
850 (eventp char)
851 (let ((c (event-basic-type char))
852 (mods (event-modifiers char))
853 string)
854 ;; Prevent ?A from turning into ?\S-a.
855 (if (and (memq 'shift mods)
856 (zerop (logand char ?\S-\^@))
857 (not (let ((case-fold-search nil))
858 (char-equal c (upcase c)))))
859 (setq c (upcase c) mods nil))
860 ;; What string are we considering using?
861 (condition-case nil
862 (setq string
863 (concat
865 (mapconcat
866 (lambda (modif)
867 (cond ((eq modif 'super) "\\s-")
868 (t (string ?\\ (upcase (aref (symbol-name modif) 0)) ?-))))
869 mods "")
870 (cond
871 ((memq c '(?\; ?\( ?\) ?\{ ?\} ?\[ ?\] ?\" ?\' ?\\)) (string ?\\ c))
872 ((eq c 127) "\\C-?")
874 (string c)))))
875 (error nil))
876 ;; Verify the string reads a CHAR, not to some other character.
877 ;; If it doesn't, return nil instead.
878 (and string
879 (= (car (read-from-string string)) char)
880 string))))
882 (defun elisp--preceding-sexp ()
883 "Return sexp before the point."
884 (let ((opoint (point))
885 ignore-quotes
886 expr)
887 (save-excursion
888 (with-syntax-table emacs-lisp-mode-syntax-table
889 ;; If this sexp appears to be enclosed in `...'
890 ;; then ignore the surrounding quotes.
891 (setq ignore-quotes
892 (or (eq (following-char) ?\')
893 (eq (preceding-char) ?\')))
894 (forward-sexp -1)
895 ;; If we were after `?\e' (or similar case),
896 ;; use the whole thing, not just the `e'.
897 (when (eq (preceding-char) ?\\)
898 (forward-char -1)
899 (when (eq (preceding-char) ??)
900 (forward-char -1)))
902 ;; Skip over hash table read syntax.
903 (and (> (point) (1+ (point-min)))
904 (looking-back "#s" (- (point) 2))
905 (forward-char -2))
907 ;; Skip over `#N='s.
908 (when (eq (preceding-char) ?=)
909 (let (labeled-p)
910 (save-excursion
911 (skip-chars-backward "0-9#=")
912 (setq labeled-p (looking-at "\\(#[0-9]+=\\)+")))
913 (when labeled-p
914 (forward-sexp -1))))
916 (save-restriction
917 (if (and ignore-quotes (eq (following-char) ?`))
918 ;; vladimir@cs.ualberta.ca 30-Jul-1997: Skip ` in `variable' so
919 ;; that the value is returned, not the name.
920 (forward-char))
921 (when (looking-at ",@?") (goto-char (match-end 0)))
922 (narrow-to-region (point-min) opoint)
923 (setq expr (read (current-buffer)))
924 ;; If it's an (interactive ...) form, it's more useful to show how an
925 ;; interactive call would use it.
926 ;; FIXME: Is it really the right place for this?
927 (when (eq (car-safe expr) 'interactive)
928 (setq expr
929 `(call-interactively
930 (lambda (&rest args) ,expr args))))
931 expr)))))
932 (define-obsolete-function-alias 'preceding-sexp 'elisp--preceding-sexp "25.1")
934 (defun elisp--eval-last-sexp (eval-last-sexp-arg-internal)
935 "Evaluate sexp before point; print value in the echo area.
936 If EVAL-LAST-SEXP-ARG-INTERNAL is non-nil, print output into
937 current buffer. If EVAL-LAST-SEXP-ARG-INTERNAL is `0', print
938 output with no limit on the length and level of lists, and
939 include additional formats for integers \(octal, hexadecimal, and
940 character)."
941 (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t)))
942 ;; Setup the lexical environment if lexical-binding is enabled.
943 (elisp--eval-last-sexp-print-value
944 (eval (eval-sexp-add-defvars (elisp--preceding-sexp)) lexical-binding)
945 eval-last-sexp-arg-internal)))
948 (defun elisp--eval-last-sexp-print-value (value &optional eval-last-sexp-arg-internal)
949 (let ((unabbreviated (let ((print-length nil) (print-level nil))
950 (prin1-to-string value)))
951 (print-length (and (not (zerop (prefix-numeric-value
952 eval-last-sexp-arg-internal)))
953 eval-expression-print-length))
954 (print-level (and (not (zerop (prefix-numeric-value
955 eval-last-sexp-arg-internal)))
956 eval-expression-print-level))
957 (beg (point))
958 end)
959 (prog1
960 (prin1 value)
961 (let ((str (eval-expression-print-format value)))
962 (if str (princ str)))
963 (setq end (point))
964 (when (and (bufferp standard-output)
965 (or (not (null print-length))
966 (not (null print-level)))
967 (not (string= unabbreviated
968 (buffer-substring-no-properties beg end))))
969 (last-sexp-setup-props beg end value
970 unabbreviated
971 (buffer-substring-no-properties beg end))
972 ))))
975 (defvar elisp--eval-last-sexp-fake-value (make-symbol "t"))
977 (defun eval-sexp-add-defvars (exp &optional pos)
978 "Prepend EXP with all the `defvar's that precede it in the buffer.
979 POS specifies the starting position where EXP was found and defaults to point."
980 (setq exp (macroexpand-all exp)) ;Eager macro-expansion.
981 (if (not lexical-binding)
983 (save-excursion
984 (unless pos (setq pos (point)))
985 (let ((vars ()))
986 (goto-char (point-min))
987 (while (re-search-forward
988 "(def\\(?:var\\|const\\|custom\\)[ \t\n]+\\([^; '()\n\t]+\\)"
989 pos t)
990 (let ((var (intern (match-string 1))))
991 (and (not (special-variable-p var))
992 (save-excursion
993 (zerop (car (syntax-ppss (match-beginning 0)))))
994 (push var vars))))
995 `(progn ,@(mapcar (lambda (v) `(defvar ,v)) vars) ,exp)))))
997 (defun eval-last-sexp (eval-last-sexp-arg-internal)
998 "Evaluate sexp before point; print value in the echo area.
999 Interactively, with prefix argument, print output into current buffer.
1001 Normally, this function truncates long output according to the value
1002 of the variables `eval-expression-print-length' and
1003 `eval-expression-print-level'. With a prefix argument of zero,
1004 however, there is no such truncation. Such a prefix argument
1005 also causes integers to be printed in several additional formats
1006 \(octal, hexadecimal, and character).
1008 If `eval-expression-debug-on-error' is non-nil, which is the default,
1009 this command arranges for all errors to enter the debugger."
1010 (interactive "P")
1011 (if (null eval-expression-debug-on-error)
1012 (elisp--eval-last-sexp eval-last-sexp-arg-internal)
1013 (let ((value
1014 (let ((debug-on-error elisp--eval-last-sexp-fake-value))
1015 (cons (elisp--eval-last-sexp eval-last-sexp-arg-internal)
1016 debug-on-error))))
1017 (unless (eq (cdr value) elisp--eval-last-sexp-fake-value)
1018 (setq debug-on-error (cdr value)))
1019 (car value))))
1021 (defun elisp--eval-defun-1 (form)
1022 "Treat some expressions specially.
1023 Reset the `defvar' and `defcustom' variables to the initial value.
1024 \(For `defcustom', use the :set function if there is one.)
1025 Reinitialize the face according to the `defface' specification."
1026 ;; The code in edebug-defun should be consistent with this, but not
1027 ;; the same, since this gets a macroexpanded form.
1028 (cond ((not (listp form))
1029 form)
1030 ((and (eq (car form) 'defvar)
1031 (cdr-safe (cdr-safe form))
1032 (boundp (cadr form)))
1033 ;; Force variable to be re-set.
1034 `(progn (defvar ,(nth 1 form) nil ,@(nthcdr 3 form))
1035 (setq-default ,(nth 1 form) ,(nth 2 form))))
1036 ;; `defcustom' is now macroexpanded to
1037 ;; `custom-declare-variable' with a quoted value arg.
1038 ((and (eq (car form) 'custom-declare-variable)
1039 (default-boundp (eval (nth 1 form) lexical-binding)))
1040 ;; Force variable to be bound, using :set function if specified.
1041 (let ((setfunc (memq :set form)))
1042 (when setfunc
1043 (setq setfunc (car-safe (cdr-safe setfunc)))
1044 (or (functionp setfunc) (setq setfunc nil)))
1045 (funcall (or setfunc 'set-default)
1046 (eval (nth 1 form) lexical-binding)
1047 ;; The second arg is an expression that evaluates to
1048 ;; an expression. The second evaluation is the one
1049 ;; normally performed not by normal execution but by
1050 ;; custom-initialize-set (for example), which does not
1051 ;; use lexical-binding.
1052 (eval (eval (nth 2 form) lexical-binding))))
1053 form)
1054 ;; `defface' is macroexpanded to `custom-declare-face'.
1055 ((eq (car form) 'custom-declare-face)
1056 ;; Reset the face.
1057 (let ((face-symbol (eval (nth 1 form) lexical-binding)))
1058 (setq face-new-frame-defaults
1059 (assq-delete-all face-symbol face-new-frame-defaults))
1060 (put face-symbol 'face-defface-spec nil)
1061 (put face-symbol 'face-override-spec nil))
1062 form)
1063 ((eq (car form) 'progn)
1064 (cons 'progn (mapcar #'elisp--eval-defun-1 (cdr form))))
1065 (t form)))
1067 (defun elisp--eval-defun ()
1068 "Evaluate defun that point is in or before.
1069 The value is displayed in the echo area.
1070 If the current defun is actually a call to `defvar',
1071 then reset the variable using the initial value expression
1072 even if the variable already has some other value.
1073 \(Normally `defvar' does not change the variable's value
1074 if it already has a value.\)
1076 Return the result of evaluation."
1077 ;; FIXME: the print-length/level bindings should only be applied while
1078 ;; printing, not while evaluating.
1079 (let ((debug-on-error eval-expression-debug-on-error)
1080 (print-length eval-expression-print-length)
1081 (print-level eval-expression-print-level))
1082 (save-excursion
1083 ;; Arrange for eval-region to "read" the (possibly) altered form.
1084 ;; eval-region handles recording which file defines a function or
1085 ;; variable.
1086 (let ((standard-output t)
1087 beg end form)
1088 ;; Read the form from the buffer, and record where it ends.
1089 (save-excursion
1090 (end-of-defun)
1091 (beginning-of-defun)
1092 (setq beg (point))
1093 (setq form (read (current-buffer)))
1094 (setq end (point)))
1095 ;; Alter the form if necessary.
1096 (let ((form (eval-sexp-add-defvars
1097 (elisp--eval-defun-1 (macroexpand form)))))
1098 (eval-region beg end standard-output
1099 (lambda (_ignore)
1100 ;; Skipping to the end of the specified region
1101 ;; will make eval-region return.
1102 (goto-char end)
1103 form))))))
1104 (let ((str (eval-expression-print-format (car values))))
1105 (if str (princ str)))
1106 ;; The result of evaluation has been put onto VALUES. So return it.
1107 (car values))
1109 (defun eval-defun (edebug-it)
1110 "Evaluate the top-level form containing point, or after point.
1112 If the current defun is actually a call to `defvar' or `defcustom',
1113 evaluating it this way resets the variable using its initial value
1114 expression (using the defcustom's :set function if there is one), even
1115 if the variable already has some other value. \(Normally `defvar' and
1116 `defcustom' do not alter the value if there already is one.) In an
1117 analogous way, evaluating a `defface' overrides any customizations of
1118 the face, so that it becomes defined exactly as the `defface' expression
1119 says.
1121 If `eval-expression-debug-on-error' is non-nil, which is the default,
1122 this command arranges for all errors to enter the debugger.
1124 With a prefix argument, instrument the code for Edebug.
1126 If acting on a `defun' for FUNCTION, and the function was
1127 instrumented, `Edebug: FUNCTION' is printed in the echo area. If not
1128 instrumented, just FUNCTION is printed.
1130 If not acting on a `defun', the result of evaluation is displayed in
1131 the echo area. This display is controlled by the variables
1132 `eval-expression-print-length' and `eval-expression-print-level',
1133 which see."
1134 (interactive "P")
1135 (cond (edebug-it
1136 (require 'edebug)
1137 (eval-defun (not edebug-all-defs)))
1139 (if (null eval-expression-debug-on-error)
1140 (elisp--eval-defun)
1141 (let (new-value value)
1142 (let ((debug-on-error elisp--eval-last-sexp-fake-value))
1143 (setq value (elisp--eval-defun))
1144 (setq new-value debug-on-error))
1145 (unless (eq elisp--eval-last-sexp-fake-value new-value)
1146 (setq debug-on-error new-value))
1147 value)))))
1149 ;;; ElDoc Support
1151 (defvar elisp--eldoc-last-data (make-vector 3 nil)
1152 "Bookkeeping; elements are as follows:
1153 0 - contains the last symbol read from the buffer.
1154 1 - contains the string last displayed in the echo area for variables,
1155 or argument string for functions.
1156 2 - 'function if function args, 'variable if variable documentation.")
1158 (defun elisp-eldoc-documentation-function ()
1159 "`eldoc-documentation-function' (which see) for Emacs Lisp."
1160 (let ((current-symbol (elisp--current-symbol))
1161 (current-fnsym (elisp--fnsym-in-current-sexp)))
1162 (cond ((null current-fnsym)
1163 nil)
1164 ((eq current-symbol (car current-fnsym))
1165 (or (apply #'elisp--get-fnsym-args-string current-fnsym)
1166 (elisp--get-var-docstring current-symbol)))
1168 (or (elisp--get-var-docstring current-symbol)
1169 (apply #'elisp--get-fnsym-args-string current-fnsym))))))
1171 (defun elisp--get-fnsym-args-string (sym &optional index)
1172 "Return a string containing the parameter list of the function SYM.
1173 If SYM is a subr and no arglist is obtainable from the docstring
1174 or elsewhere, return a 1-line docstring."
1175 (let ((argstring
1176 (cond
1177 ((not (and sym (symbolp sym) (fboundp sym))) nil)
1178 ((and (eq sym (aref elisp--eldoc-last-data 0))
1179 (eq 'function (aref elisp--eldoc-last-data 2)))
1180 (aref elisp--eldoc-last-data 1))
1182 (let* ((advertised (gethash (indirect-function sym)
1183 advertised-signature-table t))
1185 (args
1186 (cond
1187 ((listp advertised) advertised)
1188 ((setq doc (help-split-fundoc
1189 (condition-case nil (documentation sym t)
1190 (invalid-function nil))
1191 sym))
1192 (car doc))
1193 (t (help-function-arglist sym)))))
1194 ;; Stringify, and store before highlighting, downcasing, etc.
1195 ;; FIXME should truncate before storing.
1196 (elisp--last-data-store sym (elisp--function-argstring args)
1197 'function))))))
1198 ;; Highlight, truncate.
1199 (if argstring
1200 (elisp--highlight-function-argument sym argstring index))))
1202 (defun elisp--highlight-function-argument (sym args index)
1203 "Highlight argument INDEX in ARGS list for function SYM.
1204 In the absence of INDEX, just call `elisp--docstring-format-sym-doc'."
1205 ;; FIXME: This should probably work on the list representation of `args'
1206 ;; rather than its string representation.
1207 ;; FIXME: This function is much too long, we need to split it up!
1208 (let ((start nil)
1209 (end 0)
1210 (argument-face 'eldoc-highlight-function-argument)
1211 (args-lst (mapcar (lambda (x)
1212 (replace-regexp-in-string
1213 "\\`[(]\\|[)]\\'" "" x))
1214 (split-string args))))
1215 ;; Find the current argument in the argument string. We need to
1216 ;; handle `&rest' and informal `...' properly.
1218 ;; FIXME: What to do with optional arguments, like in
1219 ;; (defun NAME ARGLIST [DOCSTRING] BODY...) case?
1220 ;; The problem is there is no robust way to determine if
1221 ;; the current argument is indeed a docstring.
1223 ;; When `&key' is used finding position based on `index'
1224 ;; would be wrong, so find the arg at point and determine
1225 ;; position in ARGS based on this current arg.
1226 (when (string-match "&key" args)
1227 (let* (case-fold-search
1228 key-have-value
1229 (sym-name (symbol-name sym))
1230 (cur-w (current-word))
1231 (args-lst-ak (cdr (member "&key" args-lst)))
1232 (limit (save-excursion
1233 (when (re-search-backward sym-name nil t)
1234 (match-end 0))))
1235 (cur-a (if (and cur-w (string-match ":\\([^ ()]*\\)" cur-w))
1236 (substring cur-w 1)
1237 (save-excursion
1238 (let (split)
1239 (when (re-search-backward ":\\([^()\n]*\\)" limit t)
1240 (setq split (split-string (match-string 1) " " t))
1241 (prog1 (car split)
1242 (when (cdr split)
1243 (setq key-have-value t))))))))
1244 ;; If `cur-a' is not one of `args-lst-ak'
1245 ;; assume user is entering an unknown key
1246 ;; referenced in last position in signature.
1247 (other-key-arg (and (stringp cur-a)
1248 args-lst-ak
1249 (not (member (upcase cur-a) args-lst-ak))
1250 (upcase (car (last args-lst-ak))))))
1251 (unless (string= cur-w sym-name)
1252 ;; The last keyword have already a value
1253 ;; i.e :foo a b and cursor is at b.
1254 ;; If signature have also `&rest'
1255 ;; (assume it is after the `&key' section)
1256 ;; go to the arg after `&rest'.
1257 (if (and key-have-value
1258 (save-excursion
1259 (not (re-search-forward ":.*" (point-at-eol) t)))
1260 (string-match "&rest \\([^ ()]*\\)" args))
1261 (setq index nil ; Skip next block based on positional args.
1262 start (match-beginning 1)
1263 end (match-end 1))
1264 ;; If `cur-a' is nil probably cursor is on a positional arg
1265 ;; before `&key', in this case, exit this block and determine
1266 ;; position with `index'.
1267 (when (and cur-a ; A keyword arg (dot removed) or nil.
1268 (or (string-match
1269 (concat "\\_<" (upcase cur-a) "\\_>") args)
1270 (string-match
1271 (concat "\\_<" other-key-arg "\\_>") args)))
1272 (setq index nil ; Skip next block based on positional args.
1273 start (match-beginning 0)
1274 end (match-end 0)))))))
1275 ;; Handle now positional arguments.
1276 (while (and index (>= index 1))
1277 (if (string-match "[^ ()]+" args end)
1278 (progn
1279 (setq start (match-beginning 0)
1280 end (match-end 0))
1281 (let ((argument (match-string 0 args)))
1282 (cond ((string= argument "&rest")
1283 ;; All the rest arguments are the same.
1284 (setq index 1))
1285 ((string= argument "&optional")) ; Skip.
1286 ((string= argument "&allow-other-keys")) ; Skip.
1287 ;; Back to index 0 in ARG1 ARG2 ARG2 ARG3 etc...
1288 ;; like in `setq'.
1289 ((or (and (string-match-p "\\.\\.\\.$" argument)
1290 (string= argument (car (last args-lst))))
1291 (and (string-match-p "\\.\\.\\.$"
1292 (substring args 1 (1- (length args))))
1293 (= (length (remove "..." args-lst)) 2)
1294 (> index 1) (eq (logand index 1) 1)))
1295 (setq index 0))
1297 (setq index (1- index))))))
1298 (setq end (length args)
1299 start (1- end)
1300 argument-face 'font-lock-warning-face
1301 index 0)))
1302 (let ((doc args))
1303 (when start
1304 (setq doc (copy-sequence args))
1305 (add-text-properties start end (list 'face argument-face) doc))
1306 (setq doc (elisp--docstring-format-sym-doc
1307 sym doc (if (functionp sym) 'font-lock-function-name-face
1308 'font-lock-keyword-face)))
1309 doc)))
1311 ;; Return a string containing a brief (one-line) documentation string for
1312 ;; the variable.
1313 (defun elisp--get-var-docstring (sym)
1314 (cond ((not sym) nil)
1315 ((and (eq sym (aref elisp--eldoc-last-data 0))
1316 (eq 'variable (aref elisp--eldoc-last-data 2)))
1317 (aref elisp--eldoc-last-data 1))
1319 (let ((doc (documentation-property sym 'variable-documentation t)))
1320 (when doc
1321 (let ((doc (elisp--docstring-format-sym-doc
1322 sym (elisp--docstring-first-line doc)
1323 'font-lock-variable-name-face)))
1324 (elisp--last-data-store sym doc 'variable)))))))
1326 (defun elisp--last-data-store (symbol doc type)
1327 (aset elisp--eldoc-last-data 0 symbol)
1328 (aset elisp--eldoc-last-data 1 doc)
1329 (aset elisp--eldoc-last-data 2 type)
1330 doc)
1332 ;; Note that any leading `*' in the docstring (which indicates the variable
1333 ;; is a user option) is removed.
1334 (defun elisp--docstring-first-line (doc)
1335 (and (stringp doc)
1336 (substitute-command-keys
1337 (save-match-data
1338 ;; Don't use "^" in the regexp below since it may match
1339 ;; anywhere in the doc-string.
1340 (let ((start (if (string-match "\\`\\*" doc) (match-end 0) 0)))
1341 (cond ((string-match "\n" doc)
1342 (substring doc start (match-beginning 0)))
1343 ((zerop start) doc)
1344 (t (substring doc start))))))))
1346 (defvar eldoc-echo-area-use-multiline-p)
1348 ;; If the entire line cannot fit in the echo area, the symbol name may be
1349 ;; truncated or eliminated entirely from the output to make room for the
1350 ;; description.
1351 (defun elisp--docstring-format-sym-doc (sym doc face)
1352 (save-match-data
1353 (let* ((name (symbol-name sym))
1354 (ea-multi eldoc-echo-area-use-multiline-p)
1355 ;; Subtract 1 from window width since emacs will not write
1356 ;; any chars to the last column, or in later versions, will
1357 ;; cause a wraparound and resize of the echo area.
1358 (ea-width (1- (window-width (minibuffer-window))))
1359 (strip (- (+ (length name) (length ": ") (length doc)) ea-width)))
1360 (cond ((or (<= strip 0)
1361 (eq ea-multi t)
1362 (and ea-multi (> (length doc) ea-width)))
1363 (format "%s: %s" (propertize name 'face face) doc))
1364 ((> (length doc) ea-width)
1365 (substring (format "%s" doc) 0 ea-width))
1366 ((>= strip (length name))
1367 (format "%s" doc))
1369 ;; Show the end of the partial symbol name, rather
1370 ;; than the beginning, since the former is more likely
1371 ;; to be unique given package namespace conventions.
1372 (setq name (substring name strip))
1373 (format "%s: %s" (propertize name 'face face) doc))))))
1376 ;; Return a list of current function name and argument index.
1377 (defun elisp--fnsym-in-current-sexp ()
1378 (save-excursion
1379 (let ((argument-index (1- (elisp--beginning-of-sexp))))
1380 ;; If we are at the beginning of function name, this will be -1.
1381 (when (< argument-index 0)
1382 (setq argument-index 0))
1383 ;; Don't do anything if current word is inside a string.
1384 (if (= (or (char-after (1- (point))) 0) ?\")
1386 (list (elisp--current-symbol) argument-index)))))
1388 ;; Move to the beginning of current sexp. Return the number of nested
1389 ;; sexp the point was over or after.
1390 (defun elisp--beginning-of-sexp ()
1391 (let ((parse-sexp-ignore-comments t)
1392 (num-skipped-sexps 0))
1393 (condition-case _
1394 (progn
1395 ;; First account for the case the point is directly over a
1396 ;; beginning of a nested sexp.
1397 (condition-case _
1398 (let ((p (point)))
1399 (forward-sexp -1)
1400 (forward-sexp 1)
1401 (when (< (point) p)
1402 (setq num-skipped-sexps 1)))
1403 (error))
1404 (while
1405 (let ((p (point)))
1406 (forward-sexp -1)
1407 (when (< (point) p)
1408 (setq num-skipped-sexps (1+ num-skipped-sexps))))))
1409 (error))
1410 num-skipped-sexps))
1412 ;; returns nil unless current word is an interned symbol.
1413 (defun elisp--current-symbol ()
1414 (let ((c (char-after (point))))
1415 (and c
1416 (memq (char-syntax c) '(?w ?_))
1417 (intern-soft (current-word)))))
1419 (defun elisp--function-argstring (arglist)
1420 "Return ARGLIST as a string enclosed by ().
1421 ARGLIST is either a string, or a list of strings or symbols."
1422 (let ((str (cond ((stringp arglist) arglist)
1423 ((not (listp arglist)) nil)
1424 (t (format "%S" (help-make-usage 'toto arglist))))))
1425 (if (and str (string-match "\\`([^ )]+ ?" str))
1426 (replace-match "(" t t str)
1427 str)))
1429 (provide 'elisp-mode)
1430 ;;; elisp-mode.el ends here