]> code.delx.au - gnu-emacs/blob - lisp/progmodes/elisp-mode.el
Add xref-find-regexp
[gnu-emacs] / lisp / progmodes / elisp-mode.el
1 ;;; elisp-mode.el --- Emacs Lisp mode -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 1985-1986, 1999-2015 Free Software Foundation, Inc.
4
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: lisp, languages
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
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.
15
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.
20
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/>.
23
24 ;;; Commentary:
25
26 ;; The major mode for editing Emacs Lisp code.
27 ;; This mode is documented in the Emacs manual.
28
29 ;;; Code:
30
31 (require 'lisp-mode)
32
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))
37
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'.")
44
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"))
88
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"))
120
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.")
179
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")))
186
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))
198
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)))))
213
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)
219
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.
226
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))
243
244 ;; Font-locking support.
245
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))))))
261
262 ;;; Completion at point for Elisp
263
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))
306
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))))))
341
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)))))
362
363 (defun elisp--expect-function-p (pos)
364 "Return non-nil if the symbol at point is expected to be a function."
365 (or
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)))))))
380
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)))))
402
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.
413
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))))))
430
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))))
439
440 (declare-function find-library-name "find-func" (library))
441 (declare-function find-function-library "find-func" (function &optional l-o v))
442
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)))
452 0))
453 ((facep sym) (find-definition-noselect sym 'defface)))))
454
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))
508 (t
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 (or ?\( `let `let*)
548 (guard (save-excursion
549 (goto-char (1- beg))
550 (when (eq parent ?\()
551 (up-list -1))
552 (forward-symbol -1)
553 (looking-at "\\_<let\\*?\\_>"))))
554 (list t obarray
555 :predicate #'boundp
556 :company-doc-buffer #'elisp--company-doc-buffer
557 :company-docsig #'elisp--company-doc-string
558 :company-location #'elisp--company-location))
559 (_ (list nil obarray
560 :predicate #'fboundp
561 :company-doc-buffer #'elisp--company-doc-buffer
562 :company-docsig #'elisp--company-doc-string
563 :company-location #'elisp--company-location
564 ))))))))
565 (nconc (list beg end)
566 (if (null (car table-etc))
567 (cdr table-etc)
568 (cons
569 (if (memq (char-syntax (or (char-after end) ?\s))
570 '(?\s ?>))
571 (cadr table-etc)
572 (apply-partially 'completion-table-with-terminator
573 " " (cadr table-etc)))
574 (cddr table-etc)))))))))
575
576 (define-obsolete-function-alias
577 'lisp-completion-at-point 'elisp-completion-at-point "25.1")
578
579 ;;; Xref backend
580
581 (declare-function xref-make-elisp-location "xref" (symbol type file))
582 (declare-function xref-make-bogus-location "xref" (message))
583 (declare-function xref-make "xref" (description location))
584 (declare-function xref-collect-matches "xref" (input dir &optional kind))
585
586 (defun elisp-xref-find (action id)
587 (require 'find-func)
588 (pcase action
589 (`definitions
590 (let ((sym (intern-soft id)))
591 (when sym
592 (elisp--xref-find-definitions sym))))
593 (`references
594 (elisp--xref-find-matches id 'symbol))
595 (`matches
596 (elisp--xref-find-matches id 'regexp))
597 (`apropos
598 (elisp--xref-find-apropos id))))
599
600 (defun elisp--xref-identifier-location (type sym)
601 (let ((file
602 (pcase type
603 (`defun (when (fboundp sym)
604 (let ((fun-lib
605 (find-function-library sym)))
606 (setq sym (car fun-lib))
607 (cdr fun-lib))))
608 (`defvar (and (boundp sym)
609 (let ((el-file (symbol-file sym 'defvar)))
610 (if el-file
611 (and
612 ;; Don't show minor modes twice.
613 ;; TODO: If TYPE ever becomes dependent on the
614 ;; context, move this check outside.
615 (not (and (fboundp sym)
616 (memq sym minor-mode-list)))
617 el-file)
618 (help-C-file-name sym 'var)))))
619 (`feature (and (featurep sym)
620 ;; Skip when a function with the same name
621 ;; is defined, because it's probably in the
622 ;; same file.
623 (not (fboundp sym))
624 (ignore-errors
625 (find-library-name (symbol-name sym)))))
626 (`defface (when (facep sym)
627 (symbol-file sym 'defface))))))
628 (when file
629 (when (string-match-p "\\.elc\\'" file)
630 (setq file (substring file 0 -1)))
631 (xref-make-elisp-location sym type file))))
632
633 (defvar elisp--xref-format
634 (let ((str "(%s %s)"))
635 (put-text-property 1 3 'face 'font-lock-keyword-face str)
636 (put-text-property 4 6 'face 'font-lock-function-name-face str)
637 str))
638
639 (defun elisp--xref-find-definitions (symbol)
640 (save-excursion
641 (let (lst)
642 (dolist (type '(feature defface defvar defun))
643 (let ((loc
644 (condition-case err
645 (elisp--xref-identifier-location type symbol)
646 (error
647 (xref-make-bogus-location (error-message-string err))))))
648 (when loc
649 (push
650 (xref-make (format elisp--xref-format type symbol)
651 loc)
652 lst))))
653 lst)))
654
655 (defvar package-user-dir)
656
657 (defun elisp--xref-find-matches (symbol kind)
658 (let* ((dirs (sort
659 (mapcar
660 (lambda (dir)
661 (file-name-as-directory (expand-file-name dir)))
662 ;; It's one level above a number of `load-path'
663 ;; elements (one for each installed package).
664 ;; Save us some process calls.
665 (cons package-user-dir load-path))
666 #'string<))
667 (ref dirs))
668 ;; Delete subdirectories from the list.
669 (while (cdr ref)
670 (if (string-prefix-p (car ref) (cadr ref))
671 (setcdr ref (cddr ref))
672 (setq ref (cdr ref))))
673 (cl-mapcan
674 (lambda (dir)
675 (and (file-exists-p dir)
676 (xref-collect-matches symbol dir kind)))
677 dirs)))
678
679 (defun elisp--xref-find-apropos (regexp)
680 (apply #'nconc
681 (let (lst)
682 (dolist (sym (apropos-internal regexp))
683 (push (elisp--xref-find-definitions sym) lst))
684 (nreverse lst))))
685
686 (defvar elisp--xref-identifier-completion-table
687 (apply-partially #'completion-table-with-predicate
688 obarray
689 (lambda (sym)
690 (or (boundp sym)
691 (fboundp sym)
692 (featurep sym)
693 (facep sym)))
694 'strict))
695
696 (defun elisp--xref-identifier-completion-table ()
697 elisp--xref-identifier-completion-table)
698
699 ;;; Elisp Interaction mode
700
701 (defvar lisp-interaction-mode-map
702 (let ((map (make-sparse-keymap))
703 (menu-map (make-sparse-keymap "Lisp-Interaction")))
704 (set-keymap-parent map lisp-mode-shared-map)
705 (define-key map "\e\C-x" 'eval-defun)
706 (define-key map "\e\C-q" 'indent-pp-sexp)
707 (define-key map "\e\t" 'completion-at-point)
708 (define-key map "\n" 'eval-print-last-sexp)
709 (bindings--define-key map [menu-bar lisp-interaction]
710 (cons "Lisp-Interaction" menu-map))
711 (bindings--define-key menu-map [eval-defun]
712 '(menu-item "Evaluate Defun" eval-defun
713 :help "Evaluate the top-level form containing point, or after point"))
714 (bindings--define-key menu-map [eval-print-last-sexp]
715 '(menu-item "Evaluate and Print" eval-print-last-sexp
716 :help "Evaluate sexp before point; print value into current buffer"))
717 (bindings--define-key menu-map [edebug-defun-lisp-interaction]
718 '(menu-item "Instrument Function for Debugging" edebug-defun
719 :help "Evaluate the top level form point is in, stepping through with Edebug"
720 :keys "C-u C-M-x"))
721 (bindings--define-key menu-map [indent-pp-sexp]
722 '(menu-item "Indent or Pretty-Print" indent-pp-sexp
723 :help "Indent each line of the list starting just after point, or prettyprint it"))
724 (bindings--define-key menu-map [complete-symbol]
725 '(menu-item "Complete Lisp Symbol" completion-at-point
726 :help "Perform completion on Lisp symbol preceding point"))
727 map)
728 "Keymap for Lisp Interaction mode.
729 All commands in `lisp-mode-shared-map' are inherited by this map.")
730
731 (define-derived-mode lisp-interaction-mode emacs-lisp-mode "Lisp Interaction"
732 "Major mode for typing and evaluating Lisp forms.
733 Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
734 before point, and prints its value into the buffer, advancing point.
735 Note that printing is controlled by `eval-expression-print-length'
736 and `eval-expression-print-level'.
737
738 Commands:
739 Delete converts tabs to spaces as it moves back.
740 Paragraphs are separated only by blank lines.
741 Semicolons start comments.
742
743 \\{lisp-interaction-mode-map}"
744 :abbrev-table nil)
745
746 ;;; Emacs Lisp Byte-Code mode
747
748 (eval-and-compile
749 (defconst emacs-list-byte-code-comment-re
750 (concat "\\(#\\)@\\([0-9]+\\) "
751 ;; Make sure it's a docstring and not a lazy-loaded byte-code.
752 "\\(?:[^(]\\|([^\"]\\)")))
753
754 (defun elisp--byte-code-comment (end &optional _point)
755 "Try to syntactically mark the #@NNN ....^_ docstrings in byte-code files."
756 (let ((ppss (syntax-ppss)))
757 (when (and (nth 4 ppss)
758 (eq (char-after (nth 8 ppss)) ?#))
759 (let* ((n (save-excursion
760 (goto-char (nth 8 ppss))
761 (when (looking-at emacs-list-byte-code-comment-re)
762 (string-to-number (match-string 2)))))
763 ;; `maxdiff' tries to make sure the loop below terminates.
764 (maxdiff n))
765 (when n
766 (let* ((bchar (match-end 2))
767 (b (position-bytes bchar)))
768 (goto-char (+ b n))
769 (while (let ((diff (- (position-bytes (point)) b n)))
770 (unless (zerop diff)
771 (when (> diff maxdiff) (setq diff maxdiff))
772 (forward-char (- diff))
773 (setq maxdiff (if (> diff 0) diff
774 (max (1- maxdiff) 1)))
775 t))))
776 (if (<= (point) end)
777 (put-text-property (1- (point)) (point)
778 'syntax-table
779 (string-to-syntax "> b"))
780 (goto-char end)))))))
781
782 (defun elisp-byte-code-syntax-propertize (start end)
783 (elisp--byte-code-comment end (point))
784 (funcall
785 (syntax-propertize-rules
786 (emacs-list-byte-code-comment-re
787 (1 (prog1 "< b" (elisp--byte-code-comment end (point))))))
788 start end))
789
790 ;;;###autoload
791 (add-to-list 'auto-mode-alist '("\\.elc\\'" . elisp-byte-code-mode))
792 ;;;###autoload
793 (define-derived-mode elisp-byte-code-mode emacs-lisp-mode
794 "Elisp-Byte-Code"
795 "Major mode for *.elc files."
796 ;; TODO: Add way to disassemble byte-code under point.
797 (setq-local open-paren-in-column-0-is-defun-start nil)
798 (setq-local syntax-propertize-function
799 #'elisp-byte-code-syntax-propertize))
800
801
802 ;;; Globally accessible functionality
803
804 (defun eval-print-last-sexp (&optional eval-last-sexp-arg-internal)
805 "Evaluate sexp before point; print value into current buffer.
806
807 Normally, this function truncates long output according to the value
808 of the variables `eval-expression-print-length' and
809 `eval-expression-print-level'. With a prefix argument of zero,
810 however, there is no such truncation. Such a prefix argument
811 also causes integers to be printed in several additional formats
812 \(octal, hexadecimal, and character).
813
814 If `eval-expression-debug-on-error' is non-nil, which is the default,
815 this command arranges for all errors to enter the debugger."
816 (interactive "P")
817 (let ((standard-output (current-buffer)))
818 (terpri)
819 (eval-last-sexp (or eval-last-sexp-arg-internal t))
820 (terpri)))
821
822
823 (defun last-sexp-setup-props (beg end value alt1 alt2)
824 "Set up text properties for the output of `elisp--eval-last-sexp'.
825 BEG and END are the start and end of the output in current-buffer.
826 VALUE is the Lisp value printed, ALT1 and ALT2 are strings for the
827 alternative printed representations that can be displayed."
828 (let ((map (make-sparse-keymap)))
829 (define-key map "\C-m" 'elisp-last-sexp-toggle-display)
830 (define-key map [down-mouse-2] 'mouse-set-point)
831 (define-key map [mouse-2] 'elisp-last-sexp-toggle-display)
832 (add-text-properties
833 beg end
834 `(printed-value (,value ,alt1 ,alt2)
835 mouse-face highlight
836 keymap ,map
837 help-echo "RET, mouse-2: toggle abbreviated display"
838 rear-nonsticky (mouse-face keymap help-echo
839 printed-value)))))
840
841
842 (defun elisp-last-sexp-toggle-display (&optional _arg)
843 "Toggle between abbreviated and unabbreviated printed representations."
844 (interactive "P")
845 (save-restriction
846 (widen)
847 (let ((value (get-text-property (point) 'printed-value)))
848 (when value
849 (let ((beg (or (previous-single-property-change (min (point-max) (1+ (point)))
850 'printed-value)
851 (point)))
852 (end (or (next-single-char-property-change (point) 'printed-value) (point)))
853 (standard-output (current-buffer))
854 (point (point)))
855 (delete-region beg end)
856 (insert (nth 1 value))
857 (or (= beg point)
858 (setq point (1- (point))))
859 (last-sexp-setup-props beg (point)
860 (nth 0 value)
861 (nth 2 value)
862 (nth 1 value))
863 (goto-char (min (point-max) point)))))))
864
865 (defun prin1-char (char) ;FIXME: Move it, e.g. to simple.el.
866 "Return a string representing CHAR as a character rather than as an integer.
867 If CHAR is not a character, return nil."
868 (and (integerp char)
869 (eventp char)
870 (let ((c (event-basic-type char))
871 (mods (event-modifiers char))
872 string)
873 ;; Prevent ?A from turning into ?\S-a.
874 (if (and (memq 'shift mods)
875 (zerop (logand char ?\S-\^@))
876 (not (let ((case-fold-search nil))
877 (char-equal c (upcase c)))))
878 (setq c (upcase c) mods nil))
879 ;; What string are we considering using?
880 (condition-case nil
881 (setq string
882 (concat
883 "?"
884 (mapconcat
885 (lambda (modif)
886 (cond ((eq modif 'super) "\\s-")
887 (t (string ?\\ (upcase (aref (symbol-name modif) 0)) ?-))))
888 mods "")
889 (cond
890 ((memq c '(?\; ?\( ?\) ?\{ ?\} ?\[ ?\] ?\" ?\' ?\\)) (string ?\\ c))
891 ((eq c 127) "\\C-?")
892 (t
893 (string c)))))
894 (error nil))
895 ;; Verify the string reads a CHAR, not to some other character.
896 ;; If it doesn't, return nil instead.
897 (and string
898 (= (car (read-from-string string)) char)
899 string))))
900
901 (defun elisp--preceding-sexp ()
902 "Return sexp before the point."
903 (let ((opoint (point))
904 ignore-quotes
905 expr)
906 (save-excursion
907 (with-syntax-table emacs-lisp-mode-syntax-table
908 ;; If this sexp appears to be enclosed in `...'
909 ;; then ignore the surrounding quotes.
910 (setq ignore-quotes
911 (or (eq (following-char) ?\')
912 (eq (preceding-char) ?\')))
913 (forward-sexp -1)
914 ;; If we were after `?\e' (or similar case),
915 ;; use the whole thing, not just the `e'.
916 (when (eq (preceding-char) ?\\)
917 (forward-char -1)
918 (when (eq (preceding-char) ??)
919 (forward-char -1)))
920
921 ;; Skip over hash table read syntax.
922 (and (> (point) (1+ (point-min)))
923 (looking-back "#s" (- (point) 2))
924 (forward-char -2))
925
926 ;; Skip over `#N='s.
927 (when (eq (preceding-char) ?=)
928 (let (labeled-p)
929 (save-excursion
930 (skip-chars-backward "0-9#=")
931 (setq labeled-p (looking-at "\\(#[0-9]+=\\)+")))
932 (when labeled-p
933 (forward-sexp -1))))
934
935 (save-restriction
936 (if (and ignore-quotes (eq (following-char) ?`))
937 ;; vladimir@cs.ualberta.ca 30-Jul-1997: Skip ` in `variable' so
938 ;; that the value is returned, not the name.
939 (forward-char))
940 (when (looking-at ",@?") (goto-char (match-end 0)))
941 (narrow-to-region (point-min) opoint)
942 (setq expr (read (current-buffer)))
943 ;; If it's an (interactive ...) form, it's more useful to show how an
944 ;; interactive call would use it.
945 ;; FIXME: Is it really the right place for this?
946 (when (eq (car-safe expr) 'interactive)
947 (setq expr
948 `(call-interactively
949 (lambda (&rest args) ,expr args))))
950 expr)))))
951 (define-obsolete-function-alias 'preceding-sexp 'elisp--preceding-sexp "25.1")
952
953 (defun elisp--eval-last-sexp (eval-last-sexp-arg-internal)
954 "Evaluate sexp before point; print value in the echo area.
955 If EVAL-LAST-SEXP-ARG-INTERNAL is non-nil, print output into
956 current buffer. If EVAL-LAST-SEXP-ARG-INTERNAL is `0', print
957 output with no limit on the length and level of lists, and
958 include additional formats for integers \(octal, hexadecimal, and
959 character)."
960 (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t)))
961 ;; Setup the lexical environment if lexical-binding is enabled.
962 (elisp--eval-last-sexp-print-value
963 (eval (eval-sexp-add-defvars (elisp--preceding-sexp)) lexical-binding)
964 eval-last-sexp-arg-internal)))
965
966
967 (defun elisp--eval-last-sexp-print-value (value &optional eval-last-sexp-arg-internal)
968 (let ((unabbreviated (let ((print-length nil) (print-level nil))
969 (prin1-to-string value)))
970 (print-length (and (not (zerop (prefix-numeric-value
971 eval-last-sexp-arg-internal)))
972 eval-expression-print-length))
973 (print-level (and (not (zerop (prefix-numeric-value
974 eval-last-sexp-arg-internal)))
975 eval-expression-print-level))
976 (beg (point))
977 end)
978 (prog1
979 (prin1 value)
980 (let ((str (eval-expression-print-format value)))
981 (if str (princ str)))
982 (setq end (point))
983 (when (and (bufferp standard-output)
984 (or (not (null print-length))
985 (not (null print-level)))
986 (not (string= unabbreviated
987 (buffer-substring-no-properties beg end))))
988 (last-sexp-setup-props beg end value
989 unabbreviated
990 (buffer-substring-no-properties beg end))
991 ))))
992
993
994 (defvar elisp--eval-last-sexp-fake-value (make-symbol "t"))
995
996 (defun eval-sexp-add-defvars (exp &optional pos)
997 "Prepend EXP with all the `defvar's that precede it in the buffer.
998 POS specifies the starting position where EXP was found and defaults to point."
999 (setq exp (macroexpand-all exp)) ;Eager macro-expansion.
1000 (if (not lexical-binding)
1001 exp
1002 (save-excursion
1003 (unless pos (setq pos (point)))
1004 (let ((vars ()))
1005 (goto-char (point-min))
1006 (while (re-search-forward
1007 "(def\\(?:var\\|const\\|custom\\)[ \t\n]+\\([^; '()\n\t]+\\)"
1008 pos t)
1009 (let ((var (intern (match-string 1))))
1010 (and (not (special-variable-p var))
1011 (save-excursion
1012 (zerop (car (syntax-ppss (match-beginning 0)))))
1013 (push var vars))))
1014 `(progn ,@(mapcar (lambda (v) `(defvar ,v)) vars) ,exp)))))
1015
1016 (defun eval-last-sexp (eval-last-sexp-arg-internal)
1017 "Evaluate sexp before point; print value in the echo area.
1018 Interactively, with prefix argument, print output into current buffer.
1019
1020 Normally, this function truncates long output according to the value
1021 of the variables `eval-expression-print-length' and
1022 `eval-expression-print-level'. With a prefix argument of zero,
1023 however, there is no such truncation. Such a prefix argument
1024 also causes integers to be printed in several additional formats
1025 \(octal, hexadecimal, and character).
1026
1027 If `eval-expression-debug-on-error' is non-nil, which is the default,
1028 this command arranges for all errors to enter the debugger."
1029 (interactive "P")
1030 (if (null eval-expression-debug-on-error)
1031 (elisp--eval-last-sexp eval-last-sexp-arg-internal)
1032 (let ((value
1033 (let ((debug-on-error elisp--eval-last-sexp-fake-value))
1034 (cons (elisp--eval-last-sexp eval-last-sexp-arg-internal)
1035 debug-on-error))))
1036 (unless (eq (cdr value) elisp--eval-last-sexp-fake-value)
1037 (setq debug-on-error (cdr value)))
1038 (car value))))
1039
1040 (defun elisp--eval-defun-1 (form)
1041 "Treat some expressions specially.
1042 Reset the `defvar' and `defcustom' variables to the initial value.
1043 \(For `defcustom', use the :set function if there is one.)
1044 Reinitialize the face according to the `defface' specification."
1045 ;; The code in edebug-defun should be consistent with this, but not
1046 ;; the same, since this gets a macroexpanded form.
1047 (cond ((not (listp form))
1048 form)
1049 ((and (eq (car form) 'defvar)
1050 (cdr-safe (cdr-safe form))
1051 (boundp (cadr form)))
1052 ;; Force variable to be re-set.
1053 `(progn (defvar ,(nth 1 form) nil ,@(nthcdr 3 form))
1054 (setq-default ,(nth 1 form) ,(nth 2 form))))
1055 ;; `defcustom' is now macroexpanded to
1056 ;; `custom-declare-variable' with a quoted value arg.
1057 ((and (eq (car form) 'custom-declare-variable)
1058 (default-boundp (eval (nth 1 form) lexical-binding)))
1059 ;; Force variable to be bound, using :set function if specified.
1060 (let ((setfunc (memq :set form)))
1061 (when setfunc
1062 (setq setfunc (car-safe (cdr-safe setfunc)))
1063 (or (functionp setfunc) (setq setfunc nil)))
1064 (funcall (or setfunc 'set-default)
1065 (eval (nth 1 form) lexical-binding)
1066 ;; The second arg is an expression that evaluates to
1067 ;; an expression. The second evaluation is the one
1068 ;; normally performed not by normal execution but by
1069 ;; custom-initialize-set (for example), which does not
1070 ;; use lexical-binding.
1071 (eval (eval (nth 2 form) lexical-binding))))
1072 form)
1073 ;; `defface' is macroexpanded to `custom-declare-face'.
1074 ((eq (car form) 'custom-declare-face)
1075 ;; Reset the face.
1076 (let ((face-symbol (eval (nth 1 form) lexical-binding)))
1077 (setq face-new-frame-defaults
1078 (assq-delete-all face-symbol face-new-frame-defaults))
1079 (put face-symbol 'face-defface-spec nil)
1080 (put face-symbol 'face-override-spec nil))
1081 form)
1082 ((eq (car form) 'progn)
1083 (cons 'progn (mapcar #'elisp--eval-defun-1 (cdr form))))
1084 (t form)))
1085
1086 (defun elisp--eval-defun ()
1087 "Evaluate defun that point is in or before.
1088 The value is displayed in the echo area.
1089 If the current defun is actually a call to `defvar',
1090 then reset the variable using the initial value expression
1091 even if the variable already has some other value.
1092 \(Normally `defvar' does not change the variable's value
1093 if it already has a value.\)
1094
1095 Return the result of evaluation."
1096 ;; FIXME: the print-length/level bindings should only be applied while
1097 ;; printing, not while evaluating.
1098 (let ((debug-on-error eval-expression-debug-on-error)
1099 (print-length eval-expression-print-length)
1100 (print-level eval-expression-print-level))
1101 (save-excursion
1102 ;; Arrange for eval-region to "read" the (possibly) altered form.
1103 ;; eval-region handles recording which file defines a function or
1104 ;; variable.
1105 (let ((standard-output t)
1106 beg end form)
1107 ;; Read the form from the buffer, and record where it ends.
1108 (save-excursion
1109 (end-of-defun)
1110 (beginning-of-defun)
1111 (setq beg (point))
1112 (setq form (read (current-buffer)))
1113 (setq end (point)))
1114 ;; Alter the form if necessary.
1115 (let ((form (eval-sexp-add-defvars
1116 (elisp--eval-defun-1 (macroexpand form)))))
1117 (eval-region beg end standard-output
1118 (lambda (_ignore)
1119 ;; Skipping to the end of the specified region
1120 ;; will make eval-region return.
1121 (goto-char end)
1122 form))))))
1123 (let ((str (eval-expression-print-format (car values))))
1124 (if str (princ str)))
1125 ;; The result of evaluation has been put onto VALUES. So return it.
1126 (car values))
1127
1128 (defun eval-defun (edebug-it)
1129 "Evaluate the top-level form containing point, or after point.
1130
1131 If the current defun is actually a call to `defvar' or `defcustom',
1132 evaluating it this way resets the variable using its initial value
1133 expression (using the defcustom's :set function if there is one), even
1134 if the variable already has some other value. \(Normally `defvar' and
1135 `defcustom' do not alter the value if there already is one.) In an
1136 analogous way, evaluating a `defface' overrides any customizations of
1137 the face, so that it becomes defined exactly as the `defface' expression
1138 says.
1139
1140 If `eval-expression-debug-on-error' is non-nil, which is the default,
1141 this command arranges for all errors to enter the debugger.
1142
1143 With a prefix argument, instrument the code for Edebug.
1144
1145 If acting on a `defun' for FUNCTION, and the function was
1146 instrumented, `Edebug: FUNCTION' is printed in the echo area. If not
1147 instrumented, just FUNCTION is printed.
1148
1149 If not acting on a `defun', the result of evaluation is displayed in
1150 the echo area. This display is controlled by the variables
1151 `eval-expression-print-length' and `eval-expression-print-level',
1152 which see."
1153 (interactive "P")
1154 (cond (edebug-it
1155 (require 'edebug)
1156 (eval-defun (not edebug-all-defs)))
1157 (t
1158 (if (null eval-expression-debug-on-error)
1159 (elisp--eval-defun)
1160 (let (new-value value)
1161 (let ((debug-on-error elisp--eval-last-sexp-fake-value))
1162 (setq value (elisp--eval-defun))
1163 (setq new-value debug-on-error))
1164 (unless (eq elisp--eval-last-sexp-fake-value new-value)
1165 (setq debug-on-error new-value))
1166 value)))))
1167
1168 ;;; ElDoc Support
1169
1170 (defvar elisp--eldoc-last-data (make-vector 3 nil)
1171 "Bookkeeping; elements are as follows:
1172 0 - contains the last symbol read from the buffer.
1173 1 - contains the string last displayed in the echo area for variables,
1174 or argument string for functions.
1175 2 - 'function if function args, 'variable if variable documentation.")
1176
1177 (defun elisp-eldoc-documentation-function ()
1178 "`eldoc-documentation-function' (which see) for Emacs Lisp."
1179 (let ((current-symbol (elisp--current-symbol))
1180 (current-fnsym (elisp--fnsym-in-current-sexp)))
1181 (cond ((null current-fnsym)
1182 nil)
1183 ((eq current-symbol (car current-fnsym))
1184 (or (apply #'elisp-get-fnsym-args-string current-fnsym)
1185 (elisp-get-var-docstring current-symbol)))
1186 (t
1187 (or (elisp-get-var-docstring current-symbol)
1188 (apply #'elisp-get-fnsym-args-string current-fnsym))))))
1189
1190 (defun elisp-get-fnsym-args-string (sym &optional index prefix)
1191 "Return a string containing the parameter list of the function SYM.
1192 If SYM is a subr and no arglist is obtainable from the docstring
1193 or elsewhere, return a 1-line docstring."
1194 (let ((argstring
1195 (cond
1196 ((not (and sym (symbolp sym) (fboundp sym))) nil)
1197 ((and (eq sym (aref elisp--eldoc-last-data 0))
1198 (eq 'function (aref elisp--eldoc-last-data 2)))
1199 (aref elisp--eldoc-last-data 1))
1200 (t
1201 (let* ((advertised (gethash (indirect-function sym)
1202 advertised-signature-table t))
1203 doc
1204 (args
1205 (cond
1206 ((listp advertised) advertised)
1207 ((setq doc (help-split-fundoc
1208 (condition-case nil (documentation sym t)
1209 (invalid-function nil))
1210 sym))
1211 (car doc))
1212 (t (help-function-arglist sym)))))
1213 ;; Stringify, and store before highlighting, downcasing, etc.
1214 (elisp--last-data-store sym (elisp-function-argstring args)
1215 'function))))))
1216 ;; Highlight, truncate.
1217 (if argstring
1218 (elisp--highlight-function-argument
1219 sym argstring index
1220 (or prefix
1221 (concat (propertize (symbol-name sym) 'face
1222 (if (functionp sym)
1223 'font-lock-function-name-face
1224 'font-lock-keyword-face))
1225 ": "))))))
1226
1227 (defun elisp--highlight-function-argument (sym args index prefix)
1228 "Highlight argument INDEX in ARGS list for function SYM.
1229 In the absence of INDEX, just call `eldoc-docstring-format-sym-doc'."
1230 ;; FIXME: This should probably work on the list representation of `args'
1231 ;; rather than its string representation.
1232 ;; FIXME: This function is much too long, we need to split it up!
1233 (let ((start nil)
1234 (end 0)
1235 (argument-face 'eldoc-highlight-function-argument)
1236 (args-lst (mapcar (lambda (x)
1237 (replace-regexp-in-string
1238 "\\`[(]\\|[)]\\'" "" x))
1239 (split-string args))))
1240 ;; Find the current argument in the argument string. We need to
1241 ;; handle `&rest' and informal `...' properly.
1242 ;;
1243 ;; FIXME: What to do with optional arguments, like in
1244 ;; (defun NAME ARGLIST [DOCSTRING] BODY...) case?
1245 ;; The problem is there is no robust way to determine if
1246 ;; the current argument is indeed a docstring.
1247
1248 ;; When `&key' is used finding position based on `index'
1249 ;; would be wrong, so find the arg at point and determine
1250 ;; position in ARGS based on this current arg.
1251 (when (string-match "&key" args)
1252 (let* (case-fold-search
1253 key-have-value
1254 (sym-name (symbol-name sym))
1255 (cur-w (current-word))
1256 (args-lst-ak (cdr (member "&key" args-lst)))
1257 (limit (save-excursion
1258 (when (re-search-backward sym-name nil t)
1259 (match-end 0))))
1260 (cur-a (if (and cur-w (string-match ":\\([^ ()]*\\)" cur-w))
1261 (substring cur-w 1)
1262 (save-excursion
1263 (let (split)
1264 (when (re-search-backward ":\\([^()\n]*\\)" limit t)
1265 (setq split (split-string (match-string 1) " " t))
1266 (prog1 (car split)
1267 (when (cdr split)
1268 (setq key-have-value t))))))))
1269 ;; If `cur-a' is not one of `args-lst-ak'
1270 ;; assume user is entering an unknown key
1271 ;; referenced in last position in signature.
1272 (other-key-arg (and (stringp cur-a)
1273 args-lst-ak
1274 (not (member (upcase cur-a) args-lst-ak))
1275 (upcase (car (last args-lst-ak))))))
1276 (unless (string= cur-w sym-name)
1277 ;; The last keyword have already a value
1278 ;; i.e :foo a b and cursor is at b.
1279 ;; If signature have also `&rest'
1280 ;; (assume it is after the `&key' section)
1281 ;; go to the arg after `&rest'.
1282 (if (and key-have-value
1283 (save-excursion
1284 (not (re-search-forward ":.*" (point-at-eol) t)))
1285 (string-match "&rest \\([^ ()]*\\)" args))
1286 (setq index nil ; Skip next block based on positional args.
1287 start (match-beginning 1)
1288 end (match-end 1))
1289 ;; If `cur-a' is nil probably cursor is on a positional arg
1290 ;; before `&key', in this case, exit this block and determine
1291 ;; position with `index'.
1292 (when (and cur-a ; A keyword arg (dot removed) or nil.
1293 (or (string-match
1294 (concat "\\_<" (upcase cur-a) "\\_>") args)
1295 (string-match
1296 (concat "\\_<" other-key-arg "\\_>") args)))
1297 (setq index nil ; Skip next block based on positional args.
1298 start (match-beginning 0)
1299 end (match-end 0)))))))
1300 ;; Handle now positional arguments.
1301 (while (and index (>= index 1))
1302 (if (string-match "[^ ()]+" args end)
1303 (progn
1304 (setq start (match-beginning 0)
1305 end (match-end 0))
1306 (let ((argument (match-string 0 args)))
1307 (cond ((string= argument "&rest")
1308 ;; All the rest arguments are the same.
1309 (setq index 1))
1310 ((string= argument "&optional")) ; Skip.
1311 ((string= argument "&allow-other-keys")) ; Skip.
1312 ;; Back to index 0 in ARG1 ARG2 ARG2 ARG3 etc...
1313 ;; like in `setq'.
1314 ((or (and (string-match-p "\\.\\.\\.\\'" argument)
1315 (string= argument (car (last args-lst))))
1316 (and (string-match-p "\\.\\.\\.\\'"
1317 (substring args 1 (1- (length args))))
1318 (= (length (remove "..." args-lst)) 2)
1319 (> index 1) (eq (logand index 1) 1)))
1320 (setq index 0))
1321 (t
1322 (setq index (1- index))))))
1323 (setq end (length args)
1324 start (1- end)
1325 argument-face 'font-lock-warning-face
1326 index 0)))
1327 (let ((doc args))
1328 (when start
1329 (setq doc (copy-sequence args))
1330 (add-text-properties start end (list 'face argument-face) doc))
1331 (setq doc (eldoc-docstring-format-sym-doc prefix doc))
1332 doc)))
1333
1334 ;; Return a string containing a brief (one-line) documentation string for
1335 ;; the variable.
1336 (defun elisp-get-var-docstring (sym)
1337 (cond ((not sym) nil)
1338 ((and (eq sym (aref elisp--eldoc-last-data 0))
1339 (eq 'variable (aref elisp--eldoc-last-data 2)))
1340 (aref elisp--eldoc-last-data 1))
1341 (t
1342 (let ((doc (documentation-property sym 'variable-documentation t)))
1343 (when doc
1344 (let ((doc (eldoc-docstring-format-sym-doc
1345 sym (elisp--docstring-first-line doc)
1346 'font-lock-variable-name-face)))
1347 (elisp--last-data-store sym doc 'variable)))))))
1348
1349 (defun elisp--last-data-store (symbol doc type)
1350 (aset elisp--eldoc-last-data 0 symbol)
1351 (aset elisp--eldoc-last-data 1 doc)
1352 (aset elisp--eldoc-last-data 2 type)
1353 doc)
1354
1355 ;; Note that any leading `*' in the docstring (which indicates the variable
1356 ;; is a user option) is removed.
1357 (defun elisp--docstring-first-line (doc)
1358 (and (stringp doc)
1359 (substitute-command-keys
1360 (save-match-data
1361 ;; Don't use "^" in the regexp below since it may match
1362 ;; anywhere in the doc-string.
1363 (let ((start (if (string-match "\\`\\*" doc) (match-end 0) 0)))
1364 (cond ((string-match "\n" doc)
1365 (substring doc start (match-beginning 0)))
1366 ((zerop start) doc)
1367 (t (substring doc start))))))))
1368 \f
1369 ;; Return a list of current function name and argument index.
1370 (defun elisp--fnsym-in-current-sexp ()
1371 (save-excursion
1372 (let ((argument-index (1- (elisp--beginning-of-sexp))))
1373 ;; If we are at the beginning of function name, this will be -1.
1374 (when (< argument-index 0)
1375 (setq argument-index 0))
1376 ;; Don't do anything if current word is inside a string.
1377 (if (= (or (char-after (1- (point))) 0) ?\")
1378 nil
1379 (list (elisp--current-symbol) argument-index)))))
1380
1381 ;; Move to the beginning of current sexp. Return the number of nested
1382 ;; sexp the point was over or after.
1383 (defun elisp--beginning-of-sexp ()
1384 (let ((parse-sexp-ignore-comments t)
1385 (num-skipped-sexps 0))
1386 (condition-case _
1387 (progn
1388 ;; First account for the case the point is directly over a
1389 ;; beginning of a nested sexp.
1390 (condition-case _
1391 (let ((p (point)))
1392 (forward-sexp -1)
1393 (forward-sexp 1)
1394 (when (< (point) p)
1395 (setq num-skipped-sexps 1)))
1396 (error))
1397 (while
1398 (let ((p (point)))
1399 (forward-sexp -1)
1400 (when (< (point) p)
1401 (setq num-skipped-sexps (1+ num-skipped-sexps))))))
1402 (error))
1403 num-skipped-sexps))
1404
1405 ;; returns nil unless current word is an interned symbol.
1406 (defun elisp--current-symbol ()
1407 (let ((c (char-after (point))))
1408 (and c
1409 (memq (char-syntax c) '(?w ?_))
1410 (intern-soft (current-word)))))
1411
1412 (defun elisp-function-argstring (arglist)
1413 "Return ARGLIST as a string enclosed by ().
1414 ARGLIST is either a string, or a list of strings or symbols."
1415 (let ((str (cond ((stringp arglist) arglist)
1416 ((not (listp arglist)) nil)
1417 (t (format "%S" (help-make-usage 'toto arglist))))))
1418 (if (and str (string-match "\\`([^ )]+ ?" str))
1419 (replace-match "(" t t str)
1420 str)))
1421
1422 (provide 'elisp-mode)
1423 ;;; elisp-mode.el ends here