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