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