image-dired.el: use with-current-buffer
[emacs.git] / lisp / emacs-lisp / lisp.el
blobb37a811b8d57477a0a8b03f5dd827f33845c90ac
1 ;;; lisp.el --- Lisp editing commands for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1986, 1994, 2000-2013 Free Software Foundation,
4 ;; Inc.
6 ;; Maintainer: FSF
7 ;; Keywords: lisp, languages
8 ;; Package: emacs
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Lisp editing commands to go with Lisp major mode. More-or-less
28 ;; applicable in other modes too.
30 ;;; Code:
32 ;; Note that this variable is used by non-lisp modes too.
33 (defcustom defun-prompt-regexp nil
34 "If non-nil, a regexp to ignore before a defun.
35 This is only necessary if the opening paren or brace is not in column 0.
36 See function `beginning-of-defun'."
37 :type '(choice (const nil)
38 regexp)
39 :group 'lisp)
40 (make-variable-buffer-local 'defun-prompt-regexp)
42 (defcustom parens-require-spaces t
43 "If non-nil, add whitespace as needed when inserting parentheses.
44 This affects `insert-parentheses' and `insert-pair'."
45 :type 'boolean
46 :group 'lisp)
48 (defvar forward-sexp-function nil
49 ;; FIXME:
50 ;; - for some uses, we may want a "sexp-only" version, which only
51 ;; jumps over a well-formed sexp, rather than some dwimish thing
52 ;; like jumping from an "else" back up to its "if".
53 ;; - for up-list, we could use the "sexp-only" behavior as well
54 ;; to treat the dwimish halfsexp as a form of "up-list" step.
55 "If non-nil, `forward-sexp' delegates to this function.
56 Should take the same arguments and behave similarly to `forward-sexp'.")
58 (defun forward-sexp (&optional arg)
59 "Move forward across one balanced expression (sexp).
60 With ARG, do it that many times. Negative arg -N means
61 move backward across N balanced expressions.
62 This command assumes point is not in a string or comment.
63 Calls `forward-sexp-function' to do the work, if that is non-nil."
64 (interactive "^p")
65 (or arg (setq arg 1))
66 (if forward-sexp-function
67 (funcall forward-sexp-function arg)
68 (goto-char (or (scan-sexps (point) arg) (buffer-end arg)))
69 (if (< arg 0) (backward-prefix-chars))))
71 (defun backward-sexp (&optional arg)
72 "Move backward across one balanced expression (sexp).
73 With ARG, do it that many times. Negative arg -N means
74 move forward across N balanced expressions.
75 This command assumes point is not in a string or comment.
76 Uses `forward-sexp' to do the work."
77 (interactive "^p")
78 (or arg (setq arg 1))
79 (forward-sexp (- arg)))
81 (defun mark-sexp (&optional arg allow-extend)
82 "Set mark ARG sexps from point.
83 The place mark goes is the same place \\[forward-sexp] would
84 move to with the same argument.
85 Interactively, if this command is repeated
86 or (in Transient Mark mode) if the mark is active,
87 it marks the next ARG sexps after the ones already marked.
88 This command assumes point is not in a string or comment."
89 (interactive "P\np")
90 (cond ((and allow-extend
91 (or (and (eq last-command this-command) (mark t))
92 (and transient-mark-mode mark-active)))
93 (setq arg (if arg (prefix-numeric-value arg)
94 (if (< (mark) (point)) -1 1)))
95 (set-mark
96 (save-excursion
97 (goto-char (mark))
98 (forward-sexp arg)
99 (point))))
101 (push-mark
102 (save-excursion
103 (forward-sexp (prefix-numeric-value arg))
104 (point))
105 nil t))))
107 (defun forward-list (&optional arg)
108 "Move forward across one balanced group of parentheses.
109 With ARG, do it that many times.
110 Negative arg -N means move backward across N groups of parentheses.
111 This command assumes point is not in a string or comment."
112 (interactive "^p")
113 (or arg (setq arg 1))
114 (goto-char (or (scan-lists (point) arg 0) (buffer-end arg))))
116 (defun backward-list (&optional arg)
117 "Move backward across one balanced group of parentheses.
118 With ARG, do it that many times.
119 Negative arg -N means move forward across N groups of parentheses.
120 This command assumes point is not in a string or comment."
121 (interactive "^p")
122 (or arg (setq arg 1))
123 (forward-list (- arg)))
125 (defun down-list (&optional arg)
126 "Move forward down one level of parentheses.
127 With ARG, do this that many times.
128 A negative argument means move backward but still go down a level.
129 This command assumes point is not in a string or comment."
130 (interactive "^p")
131 (or arg (setq arg 1))
132 (let ((inc (if (> arg 0) 1 -1)))
133 (while (/= arg 0)
134 (goto-char (or (scan-lists (point) inc -1) (buffer-end arg)))
135 (setq arg (- arg inc)))))
137 (defun backward-up-list (&optional arg)
138 "Move backward out of one level of parentheses.
139 With ARG, do this that many times.
140 A negative argument means move forward but still to a less deep spot.
141 This command assumes point is not in a string or comment."
142 (interactive "^p")
143 (up-list (- (or arg 1))))
145 (defun up-list (&optional arg)
146 "Move forward out of one level of parentheses.
147 With ARG, do this that many times.
148 A negative argument means move backward but still to a less deep spot.
149 This command assumes point is not in a string or comment."
150 (interactive "^p")
151 (or arg (setq arg 1))
152 (let ((inc (if (> arg 0) 1 -1))
153 pos)
154 (while (/= arg 0)
155 (if (null forward-sexp-function)
156 (goto-char (or (scan-lists (point) inc 1) (buffer-end arg)))
157 (condition-case err
158 (while (progn (setq pos (point))
159 (forward-sexp inc)
160 (/= (point) pos)))
161 (scan-error (goto-char (nth (if (> arg 0) 3 2) err))))
162 (if (= (point) pos)
163 (signal 'scan-error
164 (list "Unbalanced parentheses" (point) (point)))))
165 (setq arg (- arg inc)))))
167 (defun kill-sexp (&optional arg)
168 "Kill the sexp (balanced expression) following point.
169 With ARG, kill that many sexps after point.
170 Negative arg -N means kill N sexps before point.
171 This command assumes point is not in a string or comment."
172 (interactive "p")
173 (let ((opoint (point)))
174 (forward-sexp (or arg 1))
175 (kill-region opoint (point))))
177 (defun backward-kill-sexp (&optional arg)
178 "Kill the sexp (balanced expression) preceding point.
179 With ARG, kill that many sexps before point.
180 Negative arg -N means kill N sexps after point.
181 This command assumes point is not in a string or comment."
182 (interactive "p")
183 (kill-sexp (- (or arg 1))))
185 ;; After Zmacs:
186 (defun kill-backward-up-list (&optional arg)
187 "Kill the form containing the current sexp, leaving the sexp itself.
188 A prefix argument ARG causes the relevant number of surrounding
189 forms to be removed.
190 This command assumes point is not in a string or comment."
191 (interactive "*p")
192 (let ((current-sexp (thing-at-point 'sexp)))
193 (if current-sexp
194 (save-excursion
195 (backward-up-list arg)
196 (kill-sexp)
197 (insert current-sexp))
198 (error "Not at a sexp"))))
200 (defvar beginning-of-defun-function nil
201 "If non-nil, function for `beginning-of-defun-raw' to call.
202 This is used to find the beginning of the defun instead of using the
203 normal recipe (see `beginning-of-defun'). Major modes can define this
204 if defining `defun-prompt-regexp' is not sufficient to handle the mode's
205 needs.
207 The function takes the same argument as `beginning-of-defun' and should
208 behave similarly, returning non-nil if it found the beginning of a defun.
209 Ideally it should move to a point right before an open-paren which encloses
210 the body of the defun.")
212 (defun beginning-of-defun (&optional arg)
213 "Move backward to the beginning of a defun.
214 With ARG, do it that many times. Negative ARG means move forward
215 to the ARGth following beginning of defun.
217 If search is successful, return t; point ends up at the beginning
218 of the line where the search succeeded. Otherwise, return nil.
220 When `open-paren-in-column-0-is-defun-start' is non-nil, a defun
221 is assumed to start where there is a char with open-parenthesis
222 syntax at the beginning of a line. If `defun-prompt-regexp' is
223 non-nil, then a string which matches that regexp may also precede
224 the open-parenthesis. If `defun-prompt-regexp' and
225 `open-paren-in-column-0-is-defun-start' are both nil, this
226 function instead finds an open-paren at the outermost level.
228 If the variable `beginning-of-defun-function' is non-nil, its
229 value is called as a function, with argument ARG, to find the
230 defun's beginning.
232 Regardless of the values of `defun-prompt-regexp' and
233 `beginning-of-defun-function', point always moves to the
234 beginning of the line whenever the search is successful."
235 (interactive "^p")
236 (or (not (eq this-command 'beginning-of-defun))
237 (eq last-command 'beginning-of-defun)
238 (and transient-mark-mode mark-active)
239 (push-mark))
240 (and (beginning-of-defun-raw arg)
241 (progn (beginning-of-line) t)))
243 (defun beginning-of-defun-raw (&optional arg)
244 "Move point to the character that starts a defun.
245 This is identical to function `beginning-of-defun', except that point
246 does not move to the beginning of the line when `defun-prompt-regexp'
247 is non-nil.
249 If variable `beginning-of-defun-function' is non-nil, its value
250 is called as a function to find the defun's beginning."
251 (interactive "^p") ; change this to "P", maybe, if we ever come to pass ARG
252 ; to beginning-of-defun-function.
253 (unless arg (setq arg 1))
254 (cond
255 (beginning-of-defun-function
256 (condition-case nil
257 (funcall beginning-of-defun-function arg)
258 ;; We used to define beginning-of-defun-function as taking no argument
259 ;; but that makes it impossible to implement correct forward motion:
260 ;; we used to use end-of-defun for that, but it's not supposed to do
261 ;; the same thing (it moves to the end of a defun not to the beginning
262 ;; of the next).
263 ;; In case the beginning-of-defun-function uses the old calling
264 ;; convention, fallback on the old implementation.
265 (wrong-number-of-arguments
266 (if (> arg 0)
267 (dotimes (_ arg)
268 (funcall beginning-of-defun-function))
269 (dotimes (_ (- arg))
270 (funcall end-of-defun-function))))))
272 ((or defun-prompt-regexp open-paren-in-column-0-is-defun-start)
273 (and (< arg 0) (not (eobp)) (forward-char 1))
274 (and (re-search-backward (if defun-prompt-regexp
275 (concat (if open-paren-in-column-0-is-defun-start
276 "^\\s(\\|" "")
277 "\\(?:" defun-prompt-regexp "\\)\\s(")
278 "^\\s(")
279 nil 'move arg)
280 (progn (goto-char (1- (match-end 0)))
281 t)))
283 ;; If open-paren-in-column-0-is-defun-start and defun-prompt-regexp
284 ;; are both nil, column 0 has no significance - so scan forward
285 ;; from BOB to see how nested point is, then carry on from there.
287 ;; It is generally not a good idea to land up here, because the
288 ;; call to scan-lists below can be extremely slow. This is because
289 ;; back_comment in syntax.c may have to scan from bob to find the
290 ;; beginning of each comment. Fixing this is not trivial -- cyd.
292 ((eq arg 0))
294 (let ((floor (point-min))
295 (ceiling (point-max))
296 (arg-+ve (> arg 0)))
297 (save-restriction
298 (widen)
299 (let ((ppss (let (syntax-begin-function
300 font-lock-beginning-of-syntax-function)
301 (syntax-ppss)))
302 ;; position of least enclosing paren, or nil.
303 encl-pos)
304 ;; Back out of any comment/string, so that encl-pos will always
305 ;; become nil if we're at top-level.
306 (when (nth 8 ppss)
307 (goto-char (nth 8 ppss))
308 (setq ppss (syntax-ppss))) ; should be fast, due to cache.
309 (setq encl-pos (syntax-ppss-toplevel-pos ppss))
310 (if encl-pos (goto-char encl-pos))
312 (and encl-pos arg-+ve (setq arg (1- arg)))
313 (and (not encl-pos) (not arg-+ve) (not (looking-at "\\s("))
314 (setq arg (1+ arg)))
316 (condition-case nil ; to catch crazy parens.
317 (progn
318 (goto-char (scan-lists (point) (- arg) 0))
319 (if arg-+ve
320 (if (>= (point) floor)
322 (goto-char floor)
323 nil)
324 ;; forward to next (, or trigger the c-c
325 (goto-char (1- (scan-lists (point) 1 -1)))
326 (if (<= (point) ceiling)
328 (goto-char ceiling)
329 nil)))
330 (error
331 (goto-char (if arg-+ve floor ceiling))
332 nil))))))))
334 (defvar end-of-defun-function
335 (lambda () (forward-sexp 1))
336 "Function for `end-of-defun' to call.
337 This is used to find the end of the defun at point.
338 It is called with no argument, right after calling `beginning-of-defun-raw'.
339 So the function can assume that point is at the beginning of the defun body.
340 It should move point to the first position after the defun.")
342 (defun buffer-end (arg)
343 "Return the \"far end\" position of the buffer, in direction ARG.
344 If ARG is positive, that's the end of the buffer.
345 Otherwise, that's the beginning of the buffer."
346 (if (> arg 0) (point-max) (point-min)))
348 (defun end-of-defun (&optional arg)
349 "Move forward to next end of defun.
350 With argument, do it that many times.
351 Negative argument -N means move back to Nth preceding end of defun.
353 An end of a defun occurs right after the close-parenthesis that
354 matches the open-parenthesis that starts a defun; see function
355 `beginning-of-defun'.
357 If variable `end-of-defun-function' is non-nil, its value
358 is called as a function to find the defun's end."
359 (interactive "^p")
360 (or (not (eq this-command 'end-of-defun))
361 (eq last-command 'end-of-defun)
362 (and transient-mark-mode mark-active)
363 (push-mark))
364 (if (or (null arg) (= arg 0)) (setq arg 1))
365 (let ((pos (point))
366 (beg (progn (end-of-line 1) (beginning-of-defun-raw 1) (point))))
367 (funcall end-of-defun-function)
368 ;; When comparing point against pos, we want to consider that if
369 ;; point was right after the end of the function, it's still
370 ;; considered as "in that function".
371 ;; E.g. `eval-defun' from right after the last close-paren.
372 (unless (bolp)
373 (skip-chars-forward " \t")
374 (if (looking-at "\\s<\\|\n")
375 (forward-line 1)))
376 (cond
377 ((> arg 0)
378 ;; Moving forward.
379 (if (> (point) pos)
380 ;; We already moved forward by one because we started from
381 ;; within a function.
382 (setq arg (1- arg))
383 ;; We started from after the end of the previous function.
384 (goto-char pos))
385 (unless (zerop arg)
386 (beginning-of-defun-raw (- arg))
387 (funcall end-of-defun-function)))
388 ((< arg 0)
389 ;; Moving backward.
390 (if (< (point) pos)
391 ;; We already moved backward because we started from between
392 ;; two functions.
393 (setq arg (1+ arg))
394 ;; We started from inside a function.
395 (goto-char beg))
396 (unless (zerop arg)
397 (beginning-of-defun-raw (- arg))
398 (funcall end-of-defun-function))))
399 (unless (bolp)
400 (skip-chars-forward " \t")
401 (if (looking-at "\\s<\\|\n")
402 (forward-line 1)))))
404 (defun mark-defun (&optional allow-extend)
405 "Put mark at end of this defun, point at beginning.
406 The defun marked is the one that contains point or follows point.
408 Interactively, if this command is repeated
409 or (in Transient Mark mode) if the mark is active,
410 it marks the next defun after the ones already marked."
411 (interactive "p")
412 (cond ((and allow-extend
413 (or (and (eq last-command this-command) (mark t))
414 (and transient-mark-mode mark-active)))
415 (set-mark
416 (save-excursion
417 (goto-char (mark))
418 (end-of-defun)
419 (point))))
421 (let ((opoint (point))
422 beg end)
423 (push-mark opoint)
424 ;; Try first in this order for the sake of languages with nested
425 ;; functions where several can end at the same place as with
426 ;; the offside rule, e.g. Python.
427 (beginning-of-defun)
428 (setq beg (point))
429 (end-of-defun)
430 (setq end (point))
431 (while (looking-at "^\n")
432 (forward-line 1))
433 (if (> (point) opoint)
434 (progn
435 ;; We got the right defun.
436 (push-mark beg nil t)
437 (goto-char end)
438 (exchange-point-and-mark))
439 ;; beginning-of-defun moved back one defun
440 ;; so we got the wrong one.
441 (goto-char opoint)
442 (end-of-defun)
443 (push-mark (point) nil t)
444 (beginning-of-defun))
445 (re-search-backward "^\n" (- (point) 1) t)))))
447 (defun narrow-to-defun (&optional _arg)
448 "Make text outside current defun invisible.
449 The defun visible is the one that contains point or follows point.
450 Optional ARG is ignored."
451 (interactive)
452 (save-excursion
453 (widen)
454 (let ((opoint (point))
455 beg end)
456 ;; Try first in this order for the sake of languages with nested
457 ;; functions where several can end at the same place as with
458 ;; the offside rule, e.g. Python.
460 ;; Finding the start of the function is a bit problematic since
461 ;; `beginning-of-defun' when we are on the first character of
462 ;; the function might go to the previous function.
464 ;; Therefore we first move one character forward and then call
465 ;; `beginning-of-defun'. However now we must check that we did
466 ;; not move into the next function.
467 (let ((here (point)))
468 (unless (eolp)
469 (forward-char))
470 (beginning-of-defun)
471 (when (< (point) here)
472 (goto-char here)
473 (beginning-of-defun)))
474 (setq beg (point))
475 (end-of-defun)
476 (setq end (point))
477 (while (looking-at "^\n")
478 (forward-line 1))
479 (unless (> (point) opoint)
480 ;; beginning-of-defun moved back one defun
481 ;; so we got the wrong one.
482 (goto-char opoint)
483 (end-of-defun)
484 (setq end (point))
485 (beginning-of-defun)
486 (setq beg (point)))
487 (goto-char end)
488 (re-search-backward "^\n" (- (point) 1) t)
489 (narrow-to-region beg end))))
491 (defvar insert-pair-alist
492 '((?\( ?\)) (?\[ ?\]) (?\{ ?\}) (?\< ?\>) (?\" ?\") (?\' ?\') (?\` ?\'))
493 "Alist of paired characters inserted by `insert-pair'.
494 Each element looks like (OPEN-CHAR CLOSE-CHAR) or (COMMAND-CHAR
495 OPEN-CHAR CLOSE-CHAR). The characters OPEN-CHAR and CLOSE-CHAR
496 of the pair whose key is equal to the last input character with
497 or without modifiers, are inserted by `insert-pair'.")
499 (defun insert-pair (&optional arg open close)
500 "Enclose following ARG sexps in a pair of OPEN and CLOSE characters.
501 Leave point after the first character.
502 A negative ARG encloses the preceding ARG sexps instead.
503 No argument is equivalent to zero: just insert characters
504 and leave point between.
505 If `parens-require-spaces' is non-nil, this command also inserts a space
506 before and after, depending on the surrounding characters.
507 If region is active, insert enclosing characters at region boundaries.
509 If arguments OPEN and CLOSE are nil, the character pair is found
510 from the variable `insert-pair-alist' according to the last input
511 character with or without modifiers. If no character pair is
512 found in the variable `insert-pair-alist', then the last input
513 character is inserted ARG times.
515 This command assumes point is not in a string or comment."
516 (interactive "P")
517 (if (not (and open close))
518 (let ((pair (or (assq last-command-event insert-pair-alist)
519 (assq (event-basic-type last-command-event)
520 insert-pair-alist))))
521 (if pair
522 (if (nth 2 pair)
523 (setq open (nth 1 pair) close (nth 2 pair))
524 (setq open (nth 0 pair) close (nth 1 pair))))))
525 (if (and open close)
526 (if (and transient-mark-mode mark-active)
527 (progn
528 (save-excursion (goto-char (region-end)) (insert close))
529 (save-excursion (goto-char (region-beginning)) (insert open)))
530 (if arg (setq arg (prefix-numeric-value arg))
531 (setq arg 0))
532 (cond ((> arg 0) (skip-chars-forward " \t"))
533 ((< arg 0) (forward-sexp arg) (setq arg (- arg))))
534 (and parens-require-spaces
535 (not (bobp))
536 (memq (char-syntax (preceding-char)) (list ?w ?_ (char-syntax close)))
537 (insert " "))
538 (insert open)
539 (save-excursion
540 (or (eq arg 0) (forward-sexp arg))
541 (insert close)
542 (and parens-require-spaces
543 (not (eobp))
544 (memq (char-syntax (following-char)) (list ?w ?_ (char-syntax open)))
545 (insert " "))))
546 (insert-char (event-basic-type last-command-event)
547 (prefix-numeric-value arg))))
549 (defun insert-parentheses (&optional arg)
550 "Enclose following ARG sexps in parentheses.
551 Leave point after open-paren.
552 A negative ARG encloses the preceding ARG sexps instead.
553 No argument is equivalent to zero: just insert `()' and leave point between.
554 If `parens-require-spaces' is non-nil, this command also inserts a space
555 before and after, depending on the surrounding characters.
556 If region is active, insert enclosing characters at region boundaries.
558 This command assumes point is not in a string or comment."
559 (interactive "P")
560 (insert-pair arg ?\( ?\)))
562 (defun delete-pair ()
563 "Delete a pair of characters enclosing the sexp that follows point."
564 (interactive)
565 (save-excursion (forward-sexp 1) (delete-char -1))
566 (delete-char 1))
568 (defun raise-sexp (&optional arg)
569 "Raise ARG sexps higher up the tree."
570 (interactive "p")
571 (let ((s (if (and transient-mark-mode mark-active)
572 (buffer-substring (region-beginning) (region-end))
573 (buffer-substring
574 (point)
575 (save-excursion (forward-sexp arg) (point))))))
576 (backward-up-list 1)
577 (delete-region (point) (save-excursion (forward-sexp 1) (point)))
578 (save-excursion (insert s))))
580 (defun move-past-close-and-reindent ()
581 "Move past next `)', delete indentation before it, then indent after it."
582 (interactive)
583 (up-list 1)
584 (forward-char -1)
585 (while (save-excursion ; this is my contribution
586 (let ((before-paren (point)))
587 (back-to-indentation)
588 (and (= (point) before-paren)
589 (progn
590 ;; Move to end of previous line.
591 (beginning-of-line)
592 (forward-char -1)
593 ;; Verify it doesn't end within a string or comment.
594 (let ((end (point))
595 state)
596 (beginning-of-line)
597 ;; Get state at start of line.
598 (setq state (list 0 nil nil
599 (null (calculate-lisp-indent))
600 nil nil nil nil
601 nil))
602 ;; Parse state across the line to get state at end.
603 (setq state (parse-partial-sexp (point) end nil nil
604 state))
605 ;; Check not in string or comment.
606 (and (not (elt state 3)) (not (elt state 4))))))))
607 (delete-indentation))
608 (forward-char 1)
609 (newline-and-indent))
611 (defun check-parens () ; lame name?
612 "Check for unbalanced parentheses in the current buffer.
613 More accurately, check the narrowed part of the buffer for unbalanced
614 expressions (\"sexps\") in general. This is done according to the
615 current syntax table and will find unbalanced brackets or quotes as
616 appropriate. (See Info node `(emacs)Parentheses'.) If imbalance is
617 found, an error is signaled and point is left at the first unbalanced
618 character."
619 (interactive)
620 (condition-case data
621 ;; Buffer can't have more than (point-max) sexps.
622 (scan-sexps (point-min) (point-max))
623 (scan-error (goto-char (nth 2 data))
624 ;; Could print (nth 1 data), which is either
625 ;; "Containing expression ends prematurely" or
626 ;; "Unbalanced parentheses", but those may not be so
627 ;; accurate/helpful, e.g. quotes may actually be
628 ;; mismatched.
629 (user-error "Unmatched bracket or quote"))))
631 (defun field-complete (table &optional predicate)
632 (declare (obsolete completion-in-region "24.4"))
633 (let ((minibuffer-completion-table table)
634 (minibuffer-completion-predicate predicate)
635 ;; This made sense for lisp-complete-symbol, but for
636 ;; field-complete, this is out of place. --Stef
637 ;; (completion-annotate-function
638 ;; (unless (eq predicate 'fboundp)
639 ;; (lambda (str)
640 ;; (if (fboundp (intern-soft str)) " <f>"))))
642 (call-interactively 'minibuffer-complete)))
644 (defun lisp-complete-symbol (&optional predicate)
645 "Perform completion on Lisp symbol preceding point.
646 Compare that symbol against the known Lisp symbols.
647 If no characters can be completed, display a list of possible completions.
648 Repeating the command at that point scrolls the list.
650 When called from a program, optional arg PREDICATE is a predicate
651 determining which symbols are considered, e.g. `commandp'.
652 If PREDICATE is nil, the context determines which symbols are
653 considered. If the symbol starts just after an open-parenthesis, only
654 symbols with function definitions are considered. Otherwise, all
655 symbols with function definitions, values or properties are
656 considered."
657 (declare (obsolete completion-at-point "24.4"))
658 (interactive)
659 (let* ((data (lisp-completion-at-point predicate))
660 (plist (nthcdr 3 data)))
661 (if (null data)
662 (minibuffer-message "Nothing to complete")
663 (let ((completion-extra-properties plist))
664 (completion-in-region (nth 0 data) (nth 1 data) (nth 2 data)
665 (plist-get plist :predicate))))))
667 (defun lisp--local-variables-1 (vars sexp)
668 "Return the vars locally bound around the witness, or nil if not found."
669 (let (res)
670 (while
671 (unless
672 (setq res
673 (pcase sexp
674 (`(,(or `let `let*) ,bindings)
675 (let ((vars vars))
676 (when (eq 'let* (car sexp))
677 (dolist (binding (cdr (reverse bindings)))
678 (push (or (car-safe binding) binding) vars)))
679 (lisp--local-variables-1
680 vars (car (cdr-safe (car (last bindings)))))))
681 (`(,(or `let `let*) ,bindings . ,body)
682 (let ((vars vars))
683 (dolist (binding bindings)
684 (push (or (car-safe binding) binding) vars))
685 (lisp--local-variables-1 vars (car (last body)))))
686 (`(lambda ,_) (setq sexp nil))
687 (`(lambda ,args . ,body)
688 (lisp--local-variables-1
689 (append args vars) (car (last body))))
690 (`(condition-case ,_ ,e) (lisp--local-variables-1 vars e))
691 (`(condition-case ,v ,_ . ,catches)
692 (lisp--local-variables-1
693 (cons v vars) (cdr (car (last catches)))))
694 (`(,_ . ,_)
695 (lisp--local-variables-1 vars (car (last sexp))))
696 (`lisp--witness--lisp (or vars '(nil)))
697 (_ nil)))
698 (setq sexp (ignore-errors (butlast sexp)))))
699 res))
701 (defun lisp--local-variables ()
702 "Return a list of locally let-bound variables at point."
703 (save-excursion
704 (skip-syntax-backward "w_")
705 (let* ((ppss (syntax-ppss))
706 (txt (buffer-substring-no-properties (or (car (nth 9 ppss)) (point))
707 (or (nth 8 ppss) (point))))
708 (closer ()))
709 (dolist (p (nth 9 ppss))
710 (push (cdr (syntax-after p)) closer))
711 (setq closer (apply #'string closer))
712 (let* ((sexp (car (read-from-string
713 (concat txt "lisp--witness--lisp" closer))))
714 (macroexpand-advice (lambda (expander form &rest args)
715 (condition-case nil
716 (apply expander form args)
717 (error form))))
718 (sexp
719 (unwind-protect
720 (progn
721 (advice-add 'macroexpand :around macroexpand-advice)
722 (macroexpand-all sexp))
723 (advice-remove 'macroexpand macroexpand-advice)))
724 (vars (lisp--local-variables-1 nil sexp)))
725 (delq nil
726 (mapcar (lambda (var)
727 (and (symbolp var)
728 (not (string-match (symbol-name var) "\\`[&_]"))
729 ;; Eliminate uninterned vars.
730 (intern-soft var)
731 var))
732 vars))))))
734 (defvar lisp--local-variables-completion-table
735 ;; Use `defvar' rather than `defconst' since defconst would purecopy this
736 ;; value, which would doubly fail: it would fail because purecopy can't
737 ;; handle the recursive bytecode object, and it would fail because it would
738 ;; move `lastpos' and `lastvars' to pure space where they'd be immutable!
739 (let ((lastpos nil) (lastvars nil))
740 (letrec ((hookfun (lambda ()
741 (setq lastpos nil)
742 (remove-hook 'post-command-hook hookfun))))
743 (completion-table-dynamic
744 (lambda (_string)
745 (save-excursion
746 (skip-syntax-backward "_w")
747 (let ((newpos (cons (point) (current-buffer))))
748 (unless (equal lastpos newpos)
749 (add-hook 'post-command-hook hookfun)
750 (setq lastpos newpos)
751 (setq lastvars
752 (mapcar #'symbol-name (lisp--local-variables))))))
753 lastvars)))))
755 (defun lisp-completion-at-point (&optional _predicate)
756 "Function used for `completion-at-point-functions' in `emacs-lisp-mode'."
757 (with-syntax-table emacs-lisp-mode-syntax-table
758 (let* ((pos (point))
759 (beg (condition-case nil
760 (save-excursion
761 (backward-sexp 1)
762 (skip-syntax-forward "'")
763 (point))
764 (scan-error pos)))
765 (end
766 (unless (or (eq beg (point-max))
767 (member (char-syntax (char-after beg)) '(?\" ?\( ?\))))
768 (condition-case nil
769 (save-excursion
770 (goto-char beg)
771 (forward-sexp 1)
772 (when (>= (point) pos)
773 (point)))
774 (scan-error pos))))
775 (funpos (eq (char-before beg) ?\()) ;t if in function position.
776 (table-etc
777 (if (not funpos)
778 ;; FIXME: We could look at the first element of the list and
779 ;; use it to provide a more specific completion table in some
780 ;; cases. E.g. filter out keywords that are not understood by
781 ;; the macro/function being called.
782 (list nil (completion-table-in-turn
783 lisp--local-variables-completion-table
784 obarray) ;Could be anything.
785 :annotation-function
786 (lambda (str) (if (fboundp (intern-soft str)) " <f>")))
787 ;; Looks like a funcall position. Let's double check.
788 (save-excursion
789 (goto-char (1- beg))
790 (let ((parent
791 (condition-case nil
792 (progn (up-list -1) (forward-char 1)
793 (let ((c (char-after)))
794 (if (eq c ?\() ?\(
795 (if (memq (char-syntax c) '(?w ?_))
796 (read (current-buffer))))))
797 (error nil))))
798 (pcase parent
799 ;; FIXME: Rather than hardcode special cases here,
800 ;; we should use something like a symbol-property.
801 (`declare
802 (list t (mapcar (lambda (x) (symbol-name (car x)))
803 (delete-dups
804 (append
805 macro-declarations-alist
806 defun-declarations-alist)))))
807 ((and (or `condition-case `condition-case-unless-debug)
808 (guard (save-excursion
809 (ignore-errors
810 (forward-sexp 2)
811 (< (point) beg)))))
812 (list t obarray
813 :predicate (lambda (sym) (get sym 'error-conditions))))
814 (_ (list nil obarray #'fboundp))))))))
815 (when end
816 (let ((tail (if (null (car table-etc))
817 (cdr table-etc)
818 (cons
819 (if (memq (char-syntax (or (char-after end) ?\s))
820 '(?\s ?>))
821 (cadr table-etc)
822 (apply-partially 'completion-table-with-terminator
823 " " (cadr table-etc)))
824 (cddr table-etc)))))
825 `(,beg ,end ,@tail))))))
827 ;;; lisp.el ends here