]> code.delx.au - gnu-emacs/blob - lisp/progmodes/elisp-mode.el
Consolidate cross-referencing commands
[gnu-emacs] / lisp / progmodes / elisp-mode.el
1 ;;; elisp-mode.el --- Emacs Lisp mode -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 1985-1986, 1999-2014 Free Software Foundation, Inc.
4
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: lisp, languages
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; The major mode for editing Emacs Lisp code.
27 ;; This mode is documented in the Emacs manual.
28
29 ;;; Code:
30
31 (require 'lisp-mode)
32
33 (defvar emacs-lisp-mode-abbrev-table nil)
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 (lisp-mode-variables nil nil 'elisp)
233 (setq imenu-case-fold-search nil)
234 (setq-local eldoc-documentation-function
235 #'elisp-eldoc-documentation-function)
236 (setq-local xref-find-function #'elisp-xref-find)
237 (setq-local xref-identifier-completion-table-function
238 #'elisp--xref-identifier-completion-table)
239 (add-hook 'completion-at-point-functions
240 #'elisp-completion-at-point nil 'local))
241
242 ;;; Completion at point for Elisp
243
244 (defun elisp--local-variables-1 (vars sexp)
245 "Return the vars locally bound around the witness, or nil if not found."
246 (let (res)
247 (while
248 (unless
249 (setq res
250 (pcase sexp
251 (`(,(or `let `let*) ,bindings)
252 (let ((vars vars))
253 (when (eq 'let* (car sexp))
254 (dolist (binding (cdr (reverse bindings)))
255 (push (or (car-safe binding) binding) vars)))
256 (elisp--local-variables-1
257 vars (car (cdr-safe (car (last bindings)))))))
258 (`(,(or `let `let*) ,bindings . ,body)
259 (let ((vars vars))
260 (dolist (binding bindings)
261 (push (or (car-safe binding) binding) vars))
262 (elisp--local-variables-1 vars (car (last body)))))
263 (`(lambda ,_args)
264 ;; FIXME: Look for the witness inside `args'.
265 (setq sexp nil))
266 (`(lambda ,args . ,body)
267 (elisp--local-variables-1
268 (append (remq '&optional (remq '&rest args)) vars)
269 (car (last body))))
270 (`(condition-case ,_ ,e) (elisp--local-variables-1 vars e))
271 (`(condition-case ,v ,_ . ,catches)
272 (elisp--local-variables-1
273 (cons v vars) (cdr (car (last catches)))))
274 (`(quote . ,_)
275 ;; FIXME: Look for the witness inside sexp.
276 (setq sexp nil))
277 ;; FIXME: Handle `cond'.
278 (`(,_ . ,_)
279 (elisp--local-variables-1 vars (car (last sexp))))
280 (`elisp--witness--lisp (or vars '(nil)))
281 (_ nil)))
282 ;; We didn't find the witness in the last element so we try to
283 ;; backtrack to the last-but-one.
284 (setq sexp (ignore-errors (butlast sexp)))))
285 res))
286
287 (defun elisp--local-variables ()
288 "Return a list of locally let-bound variables at point."
289 (save-excursion
290 (skip-syntax-backward "w_")
291 (let* ((ppss (syntax-ppss))
292 (txt (buffer-substring-no-properties (or (car (nth 9 ppss)) (point))
293 (or (nth 8 ppss) (point))))
294 (closer ()))
295 (dolist (p (nth 9 ppss))
296 (push (cdr (syntax-after p)) closer))
297 (setq closer (apply #'string closer))
298 (let* ((sexp (condition-case nil
299 (car (read-from-string
300 (concat txt "elisp--witness--lisp" closer)))
301 ((invalid-read-syntax end-of-file) nil)))
302 (macroexpand-advice (lambda (expander form &rest args)
303 (condition-case nil
304 (apply expander form args)
305 (error form))))
306 (sexp
307 (unwind-protect
308 (progn
309 (advice-add 'macroexpand :around macroexpand-advice)
310 (macroexpand-all sexp))
311 (advice-remove 'macroexpand macroexpand-advice)))
312 (vars (elisp--local-variables-1 nil sexp)))
313 (delq nil
314 (mapcar (lambda (var)
315 (and (symbolp var)
316 (not (string-match (symbol-name var) "\\`[&_]"))
317 ;; Eliminate uninterned vars.
318 (intern-soft var)
319 var))
320 vars))))))
321
322 (defvar elisp--local-variables-completion-table
323 ;; Use `defvar' rather than `defconst' since defconst would purecopy this
324 ;; value, which would doubly fail: it would fail because purecopy can't
325 ;; handle the recursive bytecode object, and it would fail because it would
326 ;; move `lastpos' and `lastvars' to pure space where they'd be immutable!
327 (let ((lastpos nil) (lastvars nil))
328 (letrec ((hookfun (lambda ()
329 (setq lastpos nil)
330 (remove-hook 'post-command-hook hookfun))))
331 (completion-table-dynamic
332 (lambda (_string)
333 (save-excursion
334 (skip-syntax-backward "_w")
335 (let ((newpos (cons (point) (current-buffer))))
336 (unless (equal lastpos newpos)
337 (add-hook 'post-command-hook hookfun)
338 (setq lastpos newpos)
339 (setq lastvars
340 (mapcar #'symbol-name (elisp--local-variables))))))
341 lastvars)))))
342
343 (defun elisp--expect-function-p (pos)
344 "Return non-nil if the symbol at point is expected to be a function."
345 (or
346 (and (eq (char-before pos) ?')
347 (eq (char-before (1- pos)) ?#))
348 (save-excursion
349 (let ((parent (nth 1 (syntax-ppss pos))))
350 (when parent
351 (goto-char parent)
352 (and
353 (looking-at (concat "(\\(cl-\\)?"
354 (regexp-opt '("declare-function"
355 "function" "defadvice"
356 "callf" "callf2"
357 "defsetf"))
358 "[ \t\r\n]+"))
359 (eq (match-end 0) pos)))))))
360
361 (defun elisp--form-quoted-p (pos)
362 "Return non-nil if the form at POS is not evaluated.
363 It can be quoted, or be inside a quoted form."
364 ;; FIXME: Do some macro expansion maybe.
365 (save-excursion
366 (let ((state (syntax-ppss pos)))
367 (or (nth 8 state) ; Code inside strings usually isn't evaluated.
368 ;; FIXME: The 9th element is undocumented.
369 (let ((nesting (cons (point) (reverse (nth 9 state))))
370 res)
371 (while (and nesting (not res))
372 (goto-char (pop nesting))
373 (cond
374 ((or (eq (char-after) ?\[)
375 (progn
376 (skip-chars-backward " ")
377 (memq (char-before) '(?' ?`))))
378 (setq res t))
379 ((eq (char-before) ?,)
380 (setq nesting nil))))
381 res)))))
382
383 ;; FIXME: Support for Company brings in features which straddle eldoc.
384 ;; We should consolidate this, so that major modes can provide all that
385 ;; data all at once:
386 ;; - a function to extract "the reference at point" (may be more complex
387 ;; than a mere string, to distinguish various namespaces).
388 ;; - a function to jump to such a reference.
389 ;; - a function to show the signature/interface of such a reference.
390 ;; - a function to build a help-buffer about that reference.
391 ;; FIXME: Those functions should also be used by the normal completion code in
392 ;; the *Completions* buffer.
393
394 (defun elisp--company-doc-buffer (str)
395 (let ((symbol (intern-soft str)))
396 ;; FIXME: we really don't want to "display-buffer and then undo it".
397 (save-window-excursion
398 ;; Make sure we don't display it in another frame, otherwise
399 ;; save-window-excursion won't be able to undo it.
400 (let ((display-buffer-overriding-action
401 '(nil . ((inhibit-switch-frame . t)))))
402 (ignore-errors
403 (cond
404 ((fboundp symbol) (describe-function symbol))
405 ((boundp symbol) (describe-variable symbol))
406 ((featurep symbol) (describe-package symbol))
407 ((facep symbol) (describe-face symbol))
408 (t (signal 'user-error nil)))
409 (help-buffer))))))
410
411 (defun elisp--company-doc-string (str)
412 (let* ((symbol (intern-soft str))
413 (doc (if (fboundp symbol)
414 (documentation symbol t)
415 (documentation-property symbol 'variable-documentation t))))
416 (and (stringp doc)
417 (string-match ".*$" doc)
418 (match-string 0 doc))))
419
420 (declare-function find-library-name "find-func" (library))
421
422 (defvar elisp--identifier-types '(defun defvar feature defface))
423
424 (defun elisp--identifier-location (type sym)
425 (pcase (cons type sym)
426 (`(defun . ,(pred fboundp))
427 (find-definition-noselect sym nil))
428 (`(defvar . ,(pred boundp))
429 (find-definition-noselect sym 'defvar))
430 (`(defface . ,(pred facep))
431 (find-definition-noselect sym 'defface))
432 (`(feature . ,(pred featurep))
433 (require 'find-func)
434 (cons (find-file-noselect (find-library-name
435 (symbol-name sym)))
436 1))))
437
438 (defun elisp--company-location (str)
439 (catch 'res
440 (let ((sym (intern-soft str)))
441 (when sym
442 (dolist (type elisp--identifier-types)
443 (let ((loc (elisp--identifier-location type sym)))
444 (and loc (throw 'res loc))))))))
445
446 (defvar elisp--identifier-completion-table
447 (apply-partially #'completion-table-with-predicate
448 obarray
449 (lambda (sym)
450 (or (boundp sym)
451 (fboundp sym)
452 (featurep sym)
453 (symbol-plist sym)))
454 'strict))
455
456 (defun elisp-completion-at-point ()
457 "Function used for `completion-at-point-functions' in `emacs-lisp-mode'."
458 (with-syntax-table emacs-lisp-mode-syntax-table
459 (let* ((pos (point))
460 (beg (condition-case nil
461 (save-excursion
462 (backward-sexp 1)
463 (skip-syntax-forward "'")
464 (point))
465 (scan-error pos)))
466 (end
467 (unless (or (eq beg (point-max))
468 (member (char-syntax (char-after beg))
469 '(?\s ?\" ?\( ?\))))
470 (condition-case nil
471 (save-excursion
472 (goto-char beg)
473 (forward-sexp 1)
474 (skip-chars-backward "'")
475 (when (>= (point) pos)
476 (point)))
477 (scan-error pos))))
478 ;; t if in function position.
479 (funpos (eq (char-before beg) ?\()))
480 (when (and end (or (not (nth 8 (syntax-ppss)))
481 (eq (char-before beg) ?`)))
482 (let ((table-etc
483 (if (not funpos)
484 ;; FIXME: We could look at the first element of the list and
485 ;; use it to provide a more specific completion table in some
486 ;; cases. E.g. filter out keywords that are not understood by
487 ;; the macro/function being called.
488 (cond
489 ((elisp--expect-function-p beg)
490 (list nil obarray
491 :predicate #'fboundp
492 :company-doc-buffer #'elisp--company-doc-buffer
493 :company-docsig #'elisp--company-doc-string
494 :company-location #'elisp--company-location))
495 ((elisp--form-quoted-p beg)
496 ;; Don't include all symbols (bug#16646).
497 (list nil elisp--identifier-completion-table
498 :annotation-function
499 (lambda (str) (if (fboundp (intern-soft str)) " <f>"))
500 :company-doc-buffer #'elisp--company-doc-buffer
501 :company-docsig #'elisp--company-doc-string
502 :company-location #'elisp--company-location))
503 (t
504 (list nil (completion-table-merge
505 elisp--local-variables-completion-table
506 (apply-partially #'completion-table-with-predicate
507 obarray
508 #'boundp
509 'strict))
510 :company-doc-buffer #'elisp--company-doc-buffer
511 :company-docsig #'elisp--company-doc-string
512 :company-location #'elisp--company-location)))
513 ;; Looks like a funcall position. Let's double check.
514 (save-excursion
515 (goto-char (1- beg))
516 (let ((parent
517 (condition-case nil
518 (progn (up-list -1) (forward-char 1)
519 (let ((c (char-after)))
520 (if (eq c ?\() ?\(
521 (if (memq (char-syntax c) '(?w ?_))
522 (read (current-buffer))))))
523 (error nil))))
524 (pcase parent
525 ;; FIXME: Rather than hardcode special cases here,
526 ;; we should use something like a symbol-property.
527 (`declare
528 (list t (mapcar (lambda (x) (symbol-name (car x)))
529 (delete-dups
530 ;; FIXME: We should include some
531 ;; docstring with each entry.
532 (append
533 macro-declarations-alist
534 defun-declarations-alist)))))
535 ((and (or `condition-case `condition-case-unless-debug)
536 (guard (save-excursion
537 (ignore-errors
538 (forward-sexp 2)
539 (< (point) beg)))))
540 (list t obarray
541 :predicate (lambda (sym) (get sym 'error-conditions))))
542 ((and ?\(
543 (guard (save-excursion
544 (goto-char (1- beg))
545 (up-list -1)
546 (forward-symbol -1)
547 (looking-at "\\_<let\\*?\\_>"))))
548 (list t obarray
549 :predicate #'boundp
550 :company-doc-buffer #'elisp--company-doc-buffer
551 :company-docsig #'elisp--company-doc-string
552 :company-location #'elisp--company-location))
553 (_ (list nil obarray
554 :predicate #'fboundp
555 :company-doc-buffer #'elisp--company-doc-buffer
556 :company-docsig #'elisp--company-doc-string
557 :company-location #'elisp--company-location
558 ))))))))
559 (nconc (list beg end)
560 (if (null (car table-etc))
561 (cdr table-etc)
562 (cons
563 (if (memq (char-syntax (or (char-after end) ?\s))
564 '(?\s ?>))
565 (cadr table-etc)
566 (apply-partially 'completion-table-with-terminator
567 " " (cadr table-etc)))
568 (cddr table-etc)))))))))
569
570 (define-obsolete-function-alias
571 'lisp-completion-at-point 'elisp-completion-at-point "25.1")
572
573 ;;; Xref backend
574
575 (declare-function xref-make-buffer-location "xref" (buffer position))
576 (declare-function xref-make-bogus-location "xref" (message))
577 (declare-function xref-make "xref" (description location))
578
579 (defun elisp-xref-find (action id)
580 (when (eq action 'definitions)
581 (let ((sym (intern-soft id)))
582 (when sym
583 (remove nil (elisp--xref-find-definitions sym))))))
584
585 (defun elisp--xref-find-definitions (symbol)
586 (save-excursion
587 (mapcar
588 (lambda (type)
589 (let ((loc
590 (condition-case err
591 (let ((buf-pos (elisp--identifier-location type symbol)))
592 (when buf-pos
593 (xref-make-buffer-location (car buf-pos)
594 (or (cdr buf-pos) 1))))
595 (error
596 (xref-make-bogus-location (error-message-string err))))))
597 (when loc
598 (xref-make (format "(%s %s)" type symbol)
599 loc))))
600 elisp--identifier-types)))
601
602 (defun elisp--xref-identifier-completion-table ()
603 elisp--identifier-completion-table)
604
605 ;;; Elisp Interaction mode
606
607 (defvar lisp-interaction-mode-map
608 (let ((map (make-sparse-keymap))
609 (menu-map (make-sparse-keymap "Lisp-Interaction")))
610 (set-keymap-parent map lisp-mode-shared-map)
611 (define-key map "\e\C-x" 'eval-defun)
612 (define-key map "\e\C-q" 'indent-pp-sexp)
613 (define-key map "\e\t" 'completion-at-point)
614 (define-key map "\n" 'eval-print-last-sexp)
615 (bindings--define-key map [menu-bar lisp-interaction]
616 (cons "Lisp-Interaction" menu-map))
617 (bindings--define-key menu-map [eval-defun]
618 '(menu-item "Evaluate Defun" eval-defun
619 :help "Evaluate the top-level form containing point, or after point"))
620 (bindings--define-key menu-map [eval-print-last-sexp]
621 '(menu-item "Evaluate and Print" eval-print-last-sexp
622 :help "Evaluate sexp before point; print value into current buffer"))
623 (bindings--define-key menu-map [edebug-defun-lisp-interaction]
624 '(menu-item "Instrument Function for Debugging" edebug-defun
625 :help "Evaluate the top level form point is in, stepping through with Edebug"
626 :keys "C-u C-M-x"))
627 (bindings--define-key menu-map [indent-pp-sexp]
628 '(menu-item "Indent or Pretty-Print" indent-pp-sexp
629 :help "Indent each line of the list starting just after point, or prettyprint it"))
630 (bindings--define-key menu-map [complete-symbol]
631 '(menu-item "Complete Lisp Symbol" completion-at-point
632 :help "Perform completion on Lisp symbol preceding point"))
633 map)
634 "Keymap for Lisp Interaction mode.
635 All commands in `lisp-mode-shared-map' are inherited by this map.")
636
637 (define-derived-mode lisp-interaction-mode emacs-lisp-mode "Lisp Interaction"
638 "Major mode for typing and evaluating Lisp forms.
639 Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
640 before point, and prints its value into the buffer, advancing point.
641 Note that printing is controlled by `eval-expression-print-length'
642 and `eval-expression-print-level'.
643
644 Commands:
645 Delete converts tabs to spaces as it moves back.
646 Paragraphs are separated only by blank lines.
647 Semicolons start comments.
648
649 \\{lisp-interaction-mode-map}"
650 :abbrev-table nil)
651
652 ;;; Emacs Lisp Byte-Code mode
653
654 (eval-and-compile
655 (defconst emacs-list-byte-code-comment-re
656 (concat "\\(#\\)@\\([0-9]+\\) "
657 ;; Make sure it's a docstring and not a lazy-loaded byte-code.
658 "\\(?:[^(]\\|([^\"]\\)")))
659
660 (defun elisp--byte-code-comment (end &optional _point)
661 "Try to syntactically mark the #@NNN ....^_ docstrings in byte-code files."
662 (let ((ppss (syntax-ppss)))
663 (when (and (nth 4 ppss)
664 (eq (char-after (nth 8 ppss)) ?#))
665 (let* ((n (save-excursion
666 (goto-char (nth 8 ppss))
667 (when (looking-at emacs-list-byte-code-comment-re)
668 (string-to-number (match-string 2)))))
669 ;; `maxdiff' tries to make sure the loop below terminates.
670 (maxdiff n))
671 (when n
672 (let* ((bchar (match-end 2))
673 (b (position-bytes bchar)))
674 (goto-char (+ b n))
675 (while (let ((diff (- (position-bytes (point)) b n)))
676 (unless (zerop diff)
677 (when (> diff maxdiff) (setq diff maxdiff))
678 (forward-char (- diff))
679 (setq maxdiff (if (> diff 0) diff
680 (max (1- maxdiff) 1)))
681 t))))
682 (if (<= (point) end)
683 (put-text-property (1- (point)) (point)
684 'syntax-table
685 (string-to-syntax "> b"))
686 (goto-char end)))))))
687
688 (defun elisp-byte-code-syntax-propertize (start end)
689 (elisp--byte-code-comment end (point))
690 (funcall
691 (syntax-propertize-rules
692 (emacs-list-byte-code-comment-re
693 (1 (prog1 "< b" (elisp--byte-code-comment end (point))))))
694 start end))
695
696 ;;;###autoload
697 (add-to-list 'auto-mode-alist '("\\.elc\\'" . elisp-byte-code-mode))
698 ;;;###autoload
699 (define-derived-mode elisp-byte-code-mode emacs-lisp-mode
700 "Elisp-Byte-Code"
701 "Major mode for *.elc files."
702 ;; TODO: Add way to disassemble byte-code under point.
703 (setq-local open-paren-in-column-0-is-defun-start nil)
704 (setq-local syntax-propertize-function
705 #'elisp-byte-code-syntax-propertize))
706
707
708 ;;; Globally accessible functionality
709
710 (defun eval-print-last-sexp (&optional eval-last-sexp-arg-internal)
711 "Evaluate sexp before point; print value into current buffer.
712
713 Normally, this function truncates long output according to the value
714 of the variables `eval-expression-print-length' and
715 `eval-expression-print-level'. With a prefix argument of zero,
716 however, there is no such truncation. Such a prefix argument
717 also causes integers to be printed in several additional formats
718 \(octal, hexadecimal, and character).
719
720 If `eval-expression-debug-on-error' is non-nil, which is the default,
721 this command arranges for all errors to enter the debugger."
722 (interactive "P")
723 (let ((standard-output (current-buffer)))
724 (terpri)
725 (eval-last-sexp (or eval-last-sexp-arg-internal t))
726 (terpri)))
727
728
729 (defun last-sexp-setup-props (beg end value alt1 alt2)
730 "Set up text properties for the output of `elisp--eval-last-sexp'.
731 BEG and END are the start and end of the output in current-buffer.
732 VALUE is the Lisp value printed, ALT1 and ALT2 are strings for the
733 alternative printed representations that can be displayed."
734 (let ((map (make-sparse-keymap)))
735 (define-key map "\C-m" 'elisp-last-sexp-toggle-display)
736 (define-key map [down-mouse-2] 'mouse-set-point)
737 (define-key map [mouse-2] 'elisp-last-sexp-toggle-display)
738 (add-text-properties
739 beg end
740 `(printed-value (,value ,alt1 ,alt2)
741 mouse-face highlight
742 keymap ,map
743 help-echo "RET, mouse-2: toggle abbreviated display"
744 rear-nonsticky (mouse-face keymap help-echo
745 printed-value)))))
746
747
748 (defun elisp-last-sexp-toggle-display (&optional _arg)
749 "Toggle between abbreviated and unabbreviated printed representations."
750 (interactive "P")
751 (save-restriction
752 (widen)
753 (let ((value (get-text-property (point) 'printed-value)))
754 (when value
755 (let ((beg (or (previous-single-property-change (min (point-max) (1+ (point)))
756 'printed-value)
757 (point)))
758 (end (or (next-single-char-property-change (point) 'printed-value) (point)))
759 (standard-output (current-buffer))
760 (point (point)))
761 (delete-region beg end)
762 (insert (nth 1 value))
763 (or (= beg point)
764 (setq point (1- (point))))
765 (last-sexp-setup-props beg (point)
766 (nth 0 value)
767 (nth 2 value)
768 (nth 1 value))
769 (goto-char (min (point-max) point)))))))
770
771 (defun prin1-char (char) ;FIXME: Move it, e.g. to simple.el.
772 "Return a string representing CHAR as a character rather than as an integer.
773 If CHAR is not a character, return nil."
774 (and (integerp char)
775 (eventp char)
776 (let ((c (event-basic-type char))
777 (mods (event-modifiers char))
778 string)
779 ;; Prevent ?A from turning into ?\S-a.
780 (if (and (memq 'shift mods)
781 (zerop (logand char ?\S-\^@))
782 (not (let ((case-fold-search nil))
783 (char-equal c (upcase c)))))
784 (setq c (upcase c) mods nil))
785 ;; What string are we considering using?
786 (condition-case nil
787 (setq string
788 (concat
789 "?"
790 (mapconcat
791 (lambda (modif)
792 (cond ((eq modif 'super) "\\s-")
793 (t (string ?\\ (upcase (aref (symbol-name modif) 0)) ?-))))
794 mods "")
795 (cond
796 ((memq c '(?\; ?\( ?\) ?\{ ?\} ?\[ ?\] ?\" ?\' ?\\)) (string ?\\ c))
797 ((eq c 127) "\\C-?")
798 (t
799 (string c)))))
800 (error nil))
801 ;; Verify the string reads a CHAR, not to some other character.
802 ;; If it doesn't, return nil instead.
803 (and string
804 (= (car (read-from-string string)) char)
805 string))))
806
807 (defun elisp--preceding-sexp ()
808 "Return sexp before the point."
809 (let ((opoint (point))
810 ignore-quotes
811 expr)
812 (save-excursion
813 (with-syntax-table emacs-lisp-mode-syntax-table
814 ;; If this sexp appears to be enclosed in `...'
815 ;; then ignore the surrounding quotes.
816 (setq ignore-quotes
817 (or (eq (following-char) ?\')
818 (eq (preceding-char) ?\')))
819 (forward-sexp -1)
820 ;; If we were after `?\e' (or similar case),
821 ;; use the whole thing, not just the `e'.
822 (when (eq (preceding-char) ?\\)
823 (forward-char -1)
824 (when (eq (preceding-char) ??)
825 (forward-char -1)))
826
827 ;; Skip over hash table read syntax.
828 (and (> (point) (1+ (point-min)))
829 (looking-back "#s" (- (point) 2))
830 (forward-char -2))
831
832 ;; Skip over `#N='s.
833 (when (eq (preceding-char) ?=)
834 (let (labeled-p)
835 (save-excursion
836 (skip-chars-backward "0-9#=")
837 (setq labeled-p (looking-at "\\(#[0-9]+=\\)+")))
838 (when labeled-p
839 (forward-sexp -1))))
840
841 (save-restriction
842 (if (and ignore-quotes (eq (following-char) ?`))
843 ;; vladimir@cs.ualberta.ca 30-Jul-1997: Skip ` in `variable' so
844 ;; that the value is returned, not the name.
845 (forward-char))
846 (when (looking-at ",@?") (goto-char (match-end 0)))
847 (narrow-to-region (point-min) opoint)
848 (setq expr (read (current-buffer)))
849 ;; If it's an (interactive ...) form, it's more useful to show how an
850 ;; interactive call would use it.
851 ;; FIXME: Is it really the right place for this?
852 (when (eq (car-safe expr) 'interactive)
853 (setq expr
854 `(call-interactively
855 (lambda (&rest args) ,expr args))))
856 expr)))))
857 (define-obsolete-function-alias 'preceding-sexp 'elisp--preceding-sexp "25.1")
858
859 (defun elisp--eval-last-sexp (eval-last-sexp-arg-internal)
860 "Evaluate sexp before point; print value in the echo area.
861 With argument, print output into current buffer.
862 With a zero prefix arg, print output with no limit on the length
863 and level of lists, and include additional formats for integers
864 \(octal, hexadecimal, and character)."
865 (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t)))
866 ;; Setup the lexical environment if lexical-binding is enabled.
867 (elisp--eval-last-sexp-print-value
868 (eval (eval-sexp-add-defvars (elisp--preceding-sexp)) lexical-binding)
869 eval-last-sexp-arg-internal)))
870
871
872 (defun elisp--eval-last-sexp-print-value (value &optional eval-last-sexp-arg-internal)
873 (let ((unabbreviated (let ((print-length nil) (print-level nil))
874 (prin1-to-string value)))
875 (print-length (and (not (zerop (prefix-numeric-value
876 eval-last-sexp-arg-internal)))
877 eval-expression-print-length))
878 (print-level (and (not (zerop (prefix-numeric-value
879 eval-last-sexp-arg-internal)))
880 eval-expression-print-level))
881 (beg (point))
882 end)
883 (prog1
884 (prin1 value)
885 (let ((str (eval-expression-print-format value)))
886 (if str (princ str)))
887 (setq end (point))
888 (when (and (bufferp standard-output)
889 (or (not (null print-length))
890 (not (null print-level)))
891 (not (string= unabbreviated
892 (buffer-substring-no-properties beg end))))
893 (last-sexp-setup-props beg end value
894 unabbreviated
895 (buffer-substring-no-properties beg end))
896 ))))
897
898
899 (defvar elisp--eval-last-sexp-fake-value (make-symbol "t"))
900
901 (defun eval-sexp-add-defvars (exp &optional pos)
902 "Prepend EXP with all the `defvar's that precede it in the buffer.
903 POS specifies the starting position where EXP was found and defaults to point."
904 (setq exp (macroexpand-all exp)) ;Eager macro-expansion.
905 (if (not lexical-binding)
906 exp
907 (save-excursion
908 (unless pos (setq pos (point)))
909 (let ((vars ()))
910 (goto-char (point-min))
911 (while (re-search-forward
912 "(def\\(?:var\\|const\\|custom\\)[ \t\n]+\\([^; '()\n\t]+\\)"
913 pos t)
914 (let ((var (intern (match-string 1))))
915 (and (not (special-variable-p var))
916 (save-excursion
917 (zerop (car (syntax-ppss (match-beginning 0)))))
918 (push var vars))))
919 `(progn ,@(mapcar (lambda (v) `(defvar ,v)) vars) ,exp)))))
920
921 (defun eval-last-sexp (eval-last-sexp-arg-internal)
922 "Evaluate sexp before point; print value in the echo area.
923 Interactively, with prefix argument, print output into current buffer.
924
925 Normally, this function truncates long output according to the value
926 of the variables `eval-expression-print-length' and
927 `eval-expression-print-level'. With a prefix argument of zero,
928 however, there is no such truncation. Such a prefix argument
929 also causes integers to be printed in several additional formats
930 \(octal, hexadecimal, and character).
931
932 If `eval-expression-debug-on-error' is non-nil, which is the default,
933 this command arranges for all errors to enter the debugger."
934 (interactive "P")
935 (if (null eval-expression-debug-on-error)
936 (elisp--eval-last-sexp eval-last-sexp-arg-internal)
937 (let ((value
938 (let ((debug-on-error elisp--eval-last-sexp-fake-value))
939 (cons (elisp--eval-last-sexp eval-last-sexp-arg-internal)
940 debug-on-error))))
941 (unless (eq (cdr value) elisp--eval-last-sexp-fake-value)
942 (setq debug-on-error (cdr value)))
943 (car value))))
944
945 (defun elisp--eval-defun-1 (form)
946 "Treat some expressions specially.
947 Reset the `defvar' and `defcustom' variables to the initial value.
948 \(For `defcustom', use the :set function if there is one.)
949 Reinitialize the face according to the `defface' specification."
950 ;; The code in edebug-defun should be consistent with this, but not
951 ;; the same, since this gets a macroexpanded form.
952 (cond ((not (listp form))
953 form)
954 ((and (eq (car form) 'defvar)
955 (cdr-safe (cdr-safe form))
956 (boundp (cadr form)))
957 ;; Force variable to be re-set.
958 `(progn (defvar ,(nth 1 form) nil ,@(nthcdr 3 form))
959 (setq-default ,(nth 1 form) ,(nth 2 form))))
960 ;; `defcustom' is now macroexpanded to
961 ;; `custom-declare-variable' with a quoted value arg.
962 ((and (eq (car form) 'custom-declare-variable)
963 (default-boundp (eval (nth 1 form) lexical-binding)))
964 ;; Force variable to be bound, using :set function if specified.
965 (let ((setfunc (memq :set form)))
966 (when setfunc
967 (setq setfunc (car-safe (cdr-safe setfunc)))
968 (or (functionp setfunc) (setq setfunc nil)))
969 (funcall (or setfunc 'set-default)
970 (eval (nth 1 form) lexical-binding)
971 ;; The second arg is an expression that evaluates to
972 ;; an expression. The second evaluation is the one
973 ;; normally performed not by normal execution but by
974 ;; custom-initialize-set (for example), which does not
975 ;; use lexical-binding.
976 (eval (eval (nth 2 form) lexical-binding))))
977 form)
978 ;; `defface' is macroexpanded to `custom-declare-face'.
979 ((eq (car form) 'custom-declare-face)
980 ;; Reset the face.
981 (let ((face-symbol (eval (nth 1 form) lexical-binding)))
982 (setq face-new-frame-defaults
983 (assq-delete-all face-symbol face-new-frame-defaults))
984 (put face-symbol 'face-defface-spec nil)
985 (put face-symbol 'face-override-spec nil))
986 form)
987 ((eq (car form) 'progn)
988 (cons 'progn (mapcar #'elisp--eval-defun-1 (cdr form))))
989 (t form)))
990
991 (defun elisp--eval-defun ()
992 "Evaluate defun that point is in or before.
993 The value is displayed in the echo area.
994 If the current defun is actually a call to `defvar',
995 then reset the variable using the initial value expression
996 even if the variable already has some other value.
997 \(Normally `defvar' does not change the variable's value
998 if it already has a value.\)
999
1000 Return the result of evaluation."
1001 ;; FIXME: the print-length/level bindings should only be applied while
1002 ;; printing, not while evaluating.
1003 (let ((debug-on-error eval-expression-debug-on-error)
1004 (print-length eval-expression-print-length)
1005 (print-level eval-expression-print-level))
1006 (save-excursion
1007 ;; Arrange for eval-region to "read" the (possibly) altered form.
1008 ;; eval-region handles recording which file defines a function or
1009 ;; variable.
1010 (let ((standard-output t)
1011 beg end form)
1012 ;; Read the form from the buffer, and record where it ends.
1013 (save-excursion
1014 (end-of-defun)
1015 (beginning-of-defun)
1016 (setq beg (point))
1017 (setq form (read (current-buffer)))
1018 (setq end (point)))
1019 ;; Alter the form if necessary.
1020 (let ((form (eval-sexp-add-defvars
1021 (elisp--eval-defun-1 (macroexpand form)))))
1022 (eval-region beg end standard-output
1023 (lambda (_ignore)
1024 ;; Skipping to the end of the specified region
1025 ;; will make eval-region return.
1026 (goto-char end)
1027 form))))))
1028 (let ((str (eval-expression-print-format (car values))))
1029 (if str (princ str)))
1030 ;; The result of evaluation has been put onto VALUES. So return it.
1031 (car values))
1032
1033 (defun eval-defun (edebug-it)
1034 "Evaluate the top-level form containing point, or after point.
1035
1036 If the current defun is actually a call to `defvar' or `defcustom',
1037 evaluating it this way resets the variable using its initial value
1038 expression (using the defcustom's :set function if there is one), even
1039 if the variable already has some other value. \(Normally `defvar' and
1040 `defcustom' do not alter the value if there already is one.) In an
1041 analogous way, evaluating a `defface' overrides any customizations of
1042 the face, so that it becomes defined exactly as the `defface' expression
1043 says.
1044
1045 If `eval-expression-debug-on-error' is non-nil, which is the default,
1046 this command arranges for all errors to enter the debugger.
1047
1048 With a prefix argument, instrument the code for Edebug.
1049
1050 If acting on a `defun' for FUNCTION, and the function was
1051 instrumented, `Edebug: FUNCTION' is printed in the echo area. If not
1052 instrumented, just FUNCTION is printed.
1053
1054 If not acting on a `defun', the result of evaluation is displayed in
1055 the echo area. This display is controlled by the variables
1056 `eval-expression-print-length' and `eval-expression-print-level',
1057 which see."
1058 (interactive "P")
1059 (cond (edebug-it
1060 (require 'edebug)
1061 (eval-defun (not edebug-all-defs)))
1062 (t
1063 (if (null eval-expression-debug-on-error)
1064 (elisp--eval-defun)
1065 (let (new-value value)
1066 (let ((debug-on-error elisp--eval-last-sexp-fake-value))
1067 (setq value (elisp--eval-defun))
1068 (setq new-value debug-on-error))
1069 (unless (eq elisp--eval-last-sexp-fake-value new-value)
1070 (setq debug-on-error new-value))
1071 value)))))
1072
1073 ;;; ElDoc Support
1074
1075 (defvar elisp--eldoc-last-data (make-vector 3 nil)
1076 "Bookkeeping; elements are as follows:
1077 0 - contains the last symbol read from the buffer.
1078 1 - contains the string last displayed in the echo area for variables,
1079 or argument string for functions.
1080 2 - 'function if function args, 'variable if variable documentation.")
1081
1082 (defun elisp-eldoc-documentation-function ()
1083 "`eldoc-documentation-function' (which see) for Emacs Lisp."
1084 (let ((current-symbol (elisp--current-symbol))
1085 (current-fnsym (elisp--fnsym-in-current-sexp)))
1086 (cond ((null current-fnsym)
1087 nil)
1088 ((eq current-symbol (car current-fnsym))
1089 (or (apply #'elisp--get-fnsym-args-string current-fnsym)
1090 (elisp--get-var-docstring current-symbol)))
1091 (t
1092 (or (elisp--get-var-docstring current-symbol)
1093 (apply #'elisp--get-fnsym-args-string current-fnsym))))))
1094
1095 (defun elisp--get-fnsym-args-string (sym &optional index)
1096 "Return a string containing the parameter list of the function SYM.
1097 If SYM is a subr and no arglist is obtainable from the docstring
1098 or elsewhere, return a 1-line docstring."
1099 (let ((argstring
1100 (cond
1101 ((not (and sym (symbolp sym) (fboundp sym))) nil)
1102 ((and (eq sym (aref elisp--eldoc-last-data 0))
1103 (eq 'function (aref elisp--eldoc-last-data 2)))
1104 (aref elisp--eldoc-last-data 1))
1105 (t
1106 (let* ((advertised (gethash (indirect-function sym)
1107 advertised-signature-table t))
1108 doc
1109 (args
1110 (cond
1111 ((listp advertised) advertised)
1112 ((setq doc (help-split-fundoc (documentation sym t) sym))
1113 (car doc))
1114 (t (help-function-arglist sym)))))
1115 ;; Stringify, and store before highlighting, downcasing, etc.
1116 ;; FIXME should truncate before storing.
1117 (elisp--last-data-store sym (elisp--function-argstring args)
1118 'function))))))
1119 ;; Highlight, truncate.
1120 (if argstring
1121 (elisp--highlight-function-argument sym argstring index))))
1122
1123 (defun elisp--highlight-function-argument (sym args index)
1124 "Highlight argument INDEX in ARGS list for function SYM.
1125 In the absence of INDEX, just call `elisp--docstring-format-sym-doc'."
1126 ;; FIXME: This should probably work on the list representation of `args'
1127 ;; rather than its string representation.
1128 ;; FIXME: This function is much too long, we need to split it up!
1129 (let ((start nil)
1130 (end 0)
1131 (argument-face 'eldoc-highlight-function-argument)
1132 (args-lst (mapcar (lambda (x)
1133 (replace-regexp-in-string
1134 "\\`[(]\\|[)]\\'" "" x))
1135 (split-string args))))
1136 ;; Find the current argument in the argument string. We need to
1137 ;; handle `&rest' and informal `...' properly.
1138 ;;
1139 ;; FIXME: What to do with optional arguments, like in
1140 ;; (defun NAME ARGLIST [DOCSTRING] BODY...) case?
1141 ;; The problem is there is no robust way to determine if
1142 ;; the current argument is indeed a docstring.
1143
1144 ;; When `&key' is used finding position based on `index'
1145 ;; would be wrong, so find the arg at point and determine
1146 ;; position in ARGS based on this current arg.
1147 (when (string-match "&key" args)
1148 (let* (case-fold-search
1149 key-have-value
1150 (sym-name (symbol-name sym))
1151 (cur-w (current-word))
1152 (args-lst-ak (cdr (member "&key" args-lst)))
1153 (limit (save-excursion
1154 (when (re-search-backward sym-name nil t)
1155 (match-end 0))))
1156 (cur-a (if (and cur-w (string-match ":\\([^ ()]*\\)" cur-w))
1157 (substring cur-w 1)
1158 (save-excursion
1159 (let (split)
1160 (when (re-search-backward ":\\([^()\n]*\\)" limit t)
1161 (setq split (split-string (match-string 1) " " t))
1162 (prog1 (car split)
1163 (when (cdr split)
1164 (setq key-have-value t))))))))
1165 ;; If `cur-a' is not one of `args-lst-ak'
1166 ;; assume user is entering an unknown key
1167 ;; referenced in last position in signature.
1168 (other-key-arg (and (stringp cur-a)
1169 args-lst-ak
1170 (not (member (upcase cur-a) args-lst-ak))
1171 (upcase (car (last args-lst-ak))))))
1172 (unless (string= cur-w sym-name)
1173 ;; The last keyword have already a value
1174 ;; i.e :foo a b and cursor is at b.
1175 ;; If signature have also `&rest'
1176 ;; (assume it is after the `&key' section)
1177 ;; go to the arg after `&rest'.
1178 (if (and key-have-value
1179 (save-excursion
1180 (not (re-search-forward ":.*" (point-at-eol) t)))
1181 (string-match "&rest \\([^ ()]*\\)" args))
1182 (setq index nil ; Skip next block based on positional args.
1183 start (match-beginning 1)
1184 end (match-end 1))
1185 ;; If `cur-a' is nil probably cursor is on a positional arg
1186 ;; before `&key', in this case, exit this block and determine
1187 ;; position with `index'.
1188 (when (and cur-a ; A keyword arg (dot removed) or nil.
1189 (or (string-match
1190 (concat "\\_<" (upcase cur-a) "\\_>") args)
1191 (string-match
1192 (concat "\\_<" other-key-arg "\\_>") args)))
1193 (setq index nil ; Skip next block based on positional args.
1194 start (match-beginning 0)
1195 end (match-end 0)))))))
1196 ;; Handle now positional arguments.
1197 (while (and index (>= index 1))
1198 (if (string-match "[^ ()]+" args end)
1199 (progn
1200 (setq start (match-beginning 0)
1201 end (match-end 0))
1202 (let ((argument (match-string 0 args)))
1203 (cond ((string= argument "&rest")
1204 ;; All the rest arguments are the same.
1205 (setq index 1))
1206 ((string= argument "&optional")) ; Skip.
1207 ((string= argument "&allow-other-keys")) ; Skip.
1208 ;; Back to index 0 in ARG1 ARG2 ARG2 ARG3 etc...
1209 ;; like in `setq'.
1210 ((or (and (string-match-p "\\.\\.\\.$" argument)
1211 (string= argument (car (last args-lst))))
1212 (and (string-match-p "\\.\\.\\.$"
1213 (substring args 1 (1- (length args))))
1214 (= (length (remove "..." args-lst)) 2)
1215 (> index 1) (eq (logand index 1) 1)))
1216 (setq index 0))
1217 (t
1218 (setq index (1- index))))))
1219 (setq end (length args)
1220 start (1- end)
1221 argument-face 'font-lock-warning-face
1222 index 0)))
1223 (let ((doc args))
1224 (when start
1225 (setq doc (copy-sequence args))
1226 (add-text-properties start end (list 'face argument-face) doc))
1227 (setq doc (elisp--docstring-format-sym-doc
1228 sym doc (if (functionp sym) 'font-lock-function-name-face
1229 'font-lock-keyword-face)))
1230 doc)))
1231
1232 ;; Return a string containing a brief (one-line) documentation string for
1233 ;; the variable.
1234 (defun elisp--get-var-docstring (sym)
1235 (cond ((not sym) nil)
1236 ((and (eq sym (aref elisp--eldoc-last-data 0))
1237 (eq 'variable (aref elisp--eldoc-last-data 2)))
1238 (aref elisp--eldoc-last-data 1))
1239 (t
1240 (let ((doc (documentation-property sym 'variable-documentation t)))
1241 (when doc
1242 (let ((doc (elisp--docstring-format-sym-doc
1243 sym (elisp--docstring-first-line doc)
1244 'font-lock-variable-name-face)))
1245 (elisp--last-data-store sym doc 'variable)))))))
1246
1247 (defun elisp--last-data-store (symbol doc type)
1248 (aset elisp--eldoc-last-data 0 symbol)
1249 (aset elisp--eldoc-last-data 1 doc)
1250 (aset elisp--eldoc-last-data 2 type)
1251 doc)
1252
1253 ;; Note that any leading `*' in the docstring (which indicates the variable
1254 ;; is a user option) is removed.
1255 (defun elisp--docstring-first-line (doc)
1256 (and (stringp doc)
1257 (substitute-command-keys
1258 (save-match-data
1259 ;; Don't use "^" in the regexp below since it may match
1260 ;; anywhere in the doc-string.
1261 (let ((start (if (string-match "\\`\\*" doc) (match-end 0) 0)))
1262 (cond ((string-match "\n" doc)
1263 (substring doc start (match-beginning 0)))
1264 ((zerop start) doc)
1265 (t (substring doc start))))))))
1266
1267 (defvar eldoc-echo-area-use-multiline-p)
1268
1269 ;; If the entire line cannot fit in the echo area, the symbol name may be
1270 ;; truncated or eliminated entirely from the output to make room for the
1271 ;; description.
1272 (defun elisp--docstring-format-sym-doc (sym doc face)
1273 (save-match-data
1274 (let* ((name (symbol-name sym))
1275 (ea-multi eldoc-echo-area-use-multiline-p)
1276 ;; Subtract 1 from window width since emacs will not write
1277 ;; any chars to the last column, or in later versions, will
1278 ;; cause a wraparound and resize of the echo area.
1279 (ea-width (1- (window-width (minibuffer-window))))
1280 (strip (- (+ (length name) (length ": ") (length doc)) ea-width)))
1281 (cond ((or (<= strip 0)
1282 (eq ea-multi t)
1283 (and ea-multi (> (length doc) ea-width)))
1284 (format "%s: %s" (propertize name 'face face) doc))
1285 ((> (length doc) ea-width)
1286 (substring (format "%s" doc) 0 ea-width))
1287 ((>= strip (length name))
1288 (format "%s" doc))
1289 (t
1290 ;; Show the end of the partial symbol name, rather
1291 ;; than the beginning, since the former is more likely
1292 ;; to be unique given package namespace conventions.
1293 (setq name (substring name strip))
1294 (format "%s: %s" (propertize name 'face face) doc))))))
1295
1296 \f
1297 ;; Return a list of current function name and argument index.
1298 (defun elisp--fnsym-in-current-sexp ()
1299 (save-excursion
1300 (let ((argument-index (1- (elisp--beginning-of-sexp))))
1301 ;; If we are at the beginning of function name, this will be -1.
1302 (when (< argument-index 0)
1303 (setq argument-index 0))
1304 ;; Don't do anything if current word is inside a string.
1305 (if (= (or (char-after (1- (point))) 0) ?\")
1306 nil
1307 (list (elisp--current-symbol) argument-index)))))
1308
1309 ;; Move to the beginning of current sexp. Return the number of nested
1310 ;; sexp the point was over or after.
1311 (defun elisp--beginning-of-sexp ()
1312 (let ((parse-sexp-ignore-comments t)
1313 (num-skipped-sexps 0))
1314 (condition-case _
1315 (progn
1316 ;; First account for the case the point is directly over a
1317 ;; beginning of a nested sexp.
1318 (condition-case _
1319 (let ((p (point)))
1320 (forward-sexp -1)
1321 (forward-sexp 1)
1322 (when (< (point) p)
1323 (setq num-skipped-sexps 1)))
1324 (error))
1325 (while
1326 (let ((p (point)))
1327 (forward-sexp -1)
1328 (when (< (point) p)
1329 (setq num-skipped-sexps (1+ num-skipped-sexps))))))
1330 (error))
1331 num-skipped-sexps))
1332
1333 ;; returns nil unless current word is an interned symbol.
1334 (defun elisp--current-symbol ()
1335 (let ((c (char-after (point))))
1336 (and c
1337 (memq (char-syntax c) '(?w ?_))
1338 (intern-soft (current-word)))))
1339
1340 (defun elisp--function-argstring (arglist)
1341 "Return ARGLIST as a string enclosed by ().
1342 ARGLIST is either a string, or a list of strings or symbols."
1343 (let ((str (cond ((stringp arglist) arglist)
1344 ((not (listp arglist)) nil)
1345 (t (format "%S" (help-make-usage 'toto arglist))))))
1346 (if (and str (string-match "\\`([^ )]+ ?" str))
1347 (replace-match "(" t t str)
1348 str)))
1349
1350 (provide 'elisp-mode)
1351 ;;; elisp-mode.el ends here