* emacs-lisp/lisp.el (up-list): Doc fix.
[bpt/emacs.git] / lisp / emacs-lisp / lisp.el
CommitLineData
bbcc4d97 1;;; lisp.el --- Lisp editing commands for Emacs -*- lexical-binding:t -*-
6594deb0 2
ba318903 3;; Copyright (C) 1985-1986, 1994, 2000-2014 Free Software Foundation,
ab422c4d 4;; Inc.
9750e079 5
34dc21db 6;; Maintainer: emacs-devel@gnu.org
e9571d2a 7;; Keywords: lisp, languages
bd78fa1d 8;; Package: emacs
e5167999 9
b73b9811 10;; This file is part of GNU Emacs.
11
d6cba7ae 12;; GNU Emacs is free software: you can redistribute it and/or modify
b73b9811 13;; it under the terms of the GNU General Public License as published by
d6cba7ae
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
b73b9811 16
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.
21
22;; You should have received a copy of the GNU General Public License
d6cba7ae 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
b73b9811 24
e41b2db1
ER
25;;; Commentary:
26
e50c4203
DL
27;; Lisp editing commands to go with Lisp major mode. More-or-less
28;; applicable in other modes too.
e41b2db1 29
e5167999 30;;; Code:
b73b9811 31
7fe78b07 32;; Note that this variable is used by non-lisp modes too.
30e19aee 33(defcustom defun-prompt-regexp nil
cb711556 34 "If non-nil, a regexp to ignore before a defun.
7fe78b07 35This is only necessary if the opening paren or brace is not in column 0.
a64dc1a4 36See function `beginning-of-defun'."
ba6b3a2a
RS
37 :type '(choice (const nil)
38 regexp)
30e19aee 39 :group 'lisp)
24ff5498 40(make-variable-buffer-local 'defun-prompt-regexp)
b73b9811 41
30e19aee 42(defcustom parens-require-spaces t
becc6788
CY
43 "If non-nil, add whitespace as needed when inserting parentheses.
44This affects `insert-parentheses' and `insert-pair'."
30e19aee
RS
45 :type 'boolean
46 :group 'lisp)
44a53673 47
11ae6c5d 48(defvar forward-sexp-function nil
dd8791e9
SM
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.
11ae6c5d
SM
55 "If non-nil, `forward-sexp' delegates to this function.
56Should take the same arguments and behave similarly to `forward-sexp'.")
57
b73b9811 58(defun forward-sexp (&optional arg)
59 "Move forward across one balanced expression (sexp).
c6eeec65 60With ARG, do it that many times. Negative arg -N means
8fc2ac41 61move backward across N balanced expressions.
ba947bc4
GM
62This command assumes point is not in a string or comment.
63Calls `forward-sexp-function' to do the work, if that is non-nil."
61eee794 64 (interactive "^p")
b73b9811 65 (or arg (setq arg 1))
11ae6c5d
SM
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))))
b73b9811 70
71(defun backward-sexp (&optional arg)
72 "Move backward across one balanced expression (sexp).
c6eeec65 73With ARG, do it that many times. Negative arg -N means
8fc2ac41 74move forward across N balanced expressions.
ba947bc4
GM
75This command assumes point is not in a string or comment.
76Uses `forward-sexp' to do the work."
61eee794 77 (interactive "^p")
b73b9811 78 (or arg (setq arg 1))
79 (forward-sexp (- arg)))
80
afb62fdd 81(defun mark-sexp (&optional arg allow-extend)
b73b9811 82 "Set mark ARG sexps from point.
e3f99b91 83The place mark goes is the same place \\[forward-sexp] would
f07493e7 84move to with the same argument.
afb62fdd 85Interactively, if this command is repeated
a64dc1a4 86or (in Transient Mark mode) if the mark is active,
8fc2ac41
AM
87it marks the next ARG sexps after the ones already marked.
88This command assumes point is not in a string or comment."
afb62fdd
RS
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)))
3610d3c9 93 (setq arg (if arg (prefix-numeric-value arg)
967e1a52 94 (if (< (mark) (point)) -1 1)))
cad113ae
KG
95 (set-mark
96 (save-excursion
967e1a52
JL
97 (goto-char (mark))
98 (forward-sexp arg)
99 (point))))
cad113ae
KG
100 (t
101 (push-mark
102 (save-excursion
3610d3c9 103 (forward-sexp (prefix-numeric-value arg))
cad113ae
KG
104 (point))
105 nil t))))
b73b9811 106
107(defun forward-list (&optional arg)
108 "Move forward across one balanced group of parentheses.
3bd1d8a8
LI
109This command will also work on other parentheses-like expressions
110defined by the current language mode.
c6eeec65 111With ARG, do it that many times.
8fc2ac41
AM
112Negative arg -N means move backward across N groups of parentheses.
113This command assumes point is not in a string or comment."
61eee794 114 (interactive "^p")
b73b9811 115 (or arg (setq arg 1))
116 (goto-char (or (scan-lists (point) arg 0) (buffer-end arg))))
117
118(defun backward-list (&optional arg)
119 "Move backward across one balanced group of parentheses.
3bd1d8a8
LI
120This command will also work on other parentheses-like expressions
121defined by the current language mode.
c6eeec65 122With ARG, do it that many times.
8fc2ac41
AM
123Negative arg -N means move forward across N groups of parentheses.
124This command assumes point is not in a string or comment."
61eee794 125 (interactive "^p")
b73b9811 126 (or arg (setq arg 1))
127 (forward-list (- arg)))
128
e50c4203 129(defun down-list (&optional arg)
b73b9811 130 "Move forward down one level of parentheses.
3bd1d8a8
LI
131This command will also work on other parentheses-like expressions
132defined by the current language mode.
c6eeec65 133With ARG, do this that many times.
8fc2ac41
AM
134A negative argument means move backward but still go down a level.
135This command assumes point is not in a string or comment."
61eee794 136 (interactive "^p")
e50c4203 137 (or arg (setq arg 1))
b73b9811 138 (let ((inc (if (> arg 0) 1 -1)))
139 (while (/= arg 0)
140 (goto-char (or (scan-lists (point) inc -1) (buffer-end arg)))
141 (setq arg (- arg inc)))))
142
e50c4203 143(defun backward-up-list (&optional arg)
b73b9811 144 "Move backward out of one level of parentheses.
3bd1d8a8
LI
145This command will also work on other parentheses-like expressions
146defined by the current language mode.
c6eeec65 147With ARG, do this that many times.
8fc2ac41
AM
148A negative argument means move forward but still to a less deep spot.
149This command assumes point is not in a string or comment."
61eee794 150 (interactive "^p")
e50c4203 151 (up-list (- (or arg 1))))
b73b9811 152
e50c4203 153(defun up-list (&optional arg)
b73b9811 154 "Move forward out of one level of parentheses.
3bd1d8a8
LI
155This command will also work on other parentheses-like expressions
156defined by the current language mode.
c6eeec65 157With ARG, do this that many times.
8fc2ac41
AM
158A negative argument means move backward but still to a less deep spot.
159This command assumes point is not in a string or comment."
61eee794 160 (interactive "^p")
e50c4203 161 (or arg (setq arg 1))
984edd22
SM
162 (let ((inc (if (> arg 0) 1 -1))
163 pos)
b73b9811 164 (while (/= arg 0)
984edd22
SM
165 (if (null forward-sexp-function)
166 (goto-char (or (scan-lists (point) inc 1) (buffer-end arg)))
e44e373d
SM
167 (condition-case err
168 (while (progn (setq pos (point))
169 (forward-sexp inc)
170 (/= (point) pos)))
171 (scan-error (goto-char (nth (if (> arg 0) 3 2) err))))
172 (if (= (point) pos)
984edd22
SM
173 (signal 'scan-error
174 (list "Unbalanced parentheses" (point) (point)))))
b73b9811 175 (setq arg (- arg inc)))))
176
e50c4203 177(defun kill-sexp (&optional arg)
dd60a465
RS
178 "Kill the sexp (balanced expression) following point.
179With ARG, kill that many sexps after point.
8fc2ac41
AM
180Negative arg -N means kill N sexps before point.
181This command assumes point is not in a string or comment."
b73b9811 182 (interactive "p")
183 (let ((opoint (point)))
e50c4203 184 (forward-sexp (or arg 1))
b73b9811 185 (kill-region opoint (point))))
186
e50c4203 187(defun backward-kill-sexp (&optional arg)
dd60a465
RS
188 "Kill the sexp (balanced expression) preceding point.
189With ARG, kill that many sexps before point.
8fc2ac41
AM
190Negative arg -N means kill N sexps after point.
191This command assumes point is not in a string or comment."
b73b9811 192 (interactive "p")
e50c4203 193 (kill-sexp (- (or arg 1))))
de6d64b2
EZ
194
195;; After Zmacs:
196(defun kill-backward-up-list (&optional arg)
197 "Kill the form containing the current sexp, leaving the sexp itself.
198A prefix argument ARG causes the relevant number of surrounding
8fc2ac41
AM
199forms to be removed.
200This command assumes point is not in a string or comment."
de6d64b2
EZ
201 (interactive "*p")
202 (let ((current-sexp (thing-at-point 'sexp)))
203 (if current-sexp
204 (save-excursion
205 (backward-up-list arg)
206 (kill-sexp)
207 (insert current-sexp))
208 (error "Not at a sexp"))))
b73b9811 209\f
ab22ee53 210(defvar beginning-of-defun-function nil
c6eeec65
DL
211 "If non-nil, function for `beginning-of-defun-raw' to call.
212This is used to find the beginning of the defun instead of using the
ab22ee53
RS
213normal recipe (see `beginning-of-defun'). Major modes can define this
214if defining `defun-prompt-regexp' is not sufficient to handle the mode's
215needs.
c6eeec65 216
50bfa18a
SM
217The function takes the same argument as `beginning-of-defun' and should
218behave similarly, returning non-nil if it found the beginning of a defun.
219Ideally it should move to a point right before an open-paren which encloses
220the body of the defun.")
c6eeec65 221
b73b9811 222(defun beginning-of-defun (&optional arg)
223 "Move backward to the beginning of a defun.
6957495d
CY
224With ARG, do it that many times. Negative ARG means move forward
225to the ARGth following beginning of defun.
226
227If search is successful, return t; point ends up at the beginning
228of the line where the search succeeded. Otherwise, return nil.
229
230When `open-paren-in-column-0-is-defun-start' is non-nil, a defun
231is assumed to start where there is a char with open-parenthesis
232syntax at the beginning of a line. If `defun-prompt-regexp' is
233non-nil, then a string which matches that regexp may also precede
234the open-parenthesis. If `defun-prompt-regexp' and
235`open-paren-in-column-0-is-defun-start' are both nil, this
236function instead finds an open-paren at the outermost level.
237
238If the variable `beginning-of-defun-function' is non-nil, its
239value is called as a function, with argument ARG, to find the
240defun's beginning.
241
242Regardless of the values of `defun-prompt-regexp' and
243`beginning-of-defun-function', point always moves to the
244beginning of the line whenever the search is successful."
61eee794 245 (interactive "^p")
90c08845 246 (or (not (eq this-command 'beginning-of-defun))
967e1a52
JL
247 (eq last-command 'beginning-of-defun)
248 (and transient-mark-mode mark-active)
249 (push-mark))
afa995e1
KH
250 (and (beginning-of-defun-raw arg)
251 (progn (beginning-of-line) t)))
252
253(defun beginning-of-defun-raw (&optional arg)
254 "Move point to the character that starts a defun.
c6eeec65
DL
255This is identical to function `beginning-of-defun', except that point
256does not move to the beginning of the line when `defun-prompt-regexp'
257is non-nil.
258
ab22ee53
RS
259If variable `beginning-of-defun-function' is non-nil, its value
260is called as a function to find the defun's beginning."
61eee794 261 (interactive "^p") ; change this to "P", maybe, if we ever come to pass ARG
4df5698c
CY
262 ; to beginning-of-defun-function.
263 (unless arg (setq arg 1))
6cb54822
AM
264 (cond
265 (beginning-of-defun-function
50bfa18a
SM
266 (condition-case nil
267 (funcall beginning-of-defun-function arg)
268 ;; We used to define beginning-of-defun-function as taking no argument
269 ;; but that makes it impossible to implement correct forward motion:
270 ;; we used to use end-of-defun for that, but it's not supposed to do
271 ;; the same thing (it moves to the end of a defun not to the beginning
272 ;; of the next).
273 ;; In case the beginning-of-defun-function uses the old calling
274 ;; convention, fallback on the old implementation.
275 (wrong-number-of-arguments
276 (if (> arg 0)
bbcc4d97 277 (dotimes (_ arg)
50bfa18a 278 (funcall beginning-of-defun-function))
bbcc4d97 279 (dotimes (_ (- arg))
8e911f6f 280 (funcall end-of-defun-function))))))
6cb54822
AM
281
282 ((or defun-prompt-regexp open-paren-in-column-0-is-defun-start)
283 (and (< arg 0) (not (eobp)) (forward-char 1))
c6eeec65 284 (and (re-search-backward (if defun-prompt-regexp
418d645c
GM
285 (concat (if open-paren-in-column-0-is-defun-start
286 "^\\s(\\|" "")
b5ed9def 287 "\\(?:" defun-prompt-regexp "\\)\\s(")
c6eeec65 288 "^\\s(")
6cb54822 289 nil 'move arg)
4114bc49
SM
290 (progn (goto-char (1- (match-end 0)))
291 t)))
6cb54822 292
4df5698c
CY
293 ;; If open-paren-in-column-0-is-defun-start and defun-prompt-regexp
294 ;; are both nil, column 0 has no significance - so scan forward
295 ;; from BOB to see how nested point is, then carry on from there.
296 ;;
297 ;; It is generally not a good idea to land up here, because the
298 ;; call to scan-lists below can be extremely slow. This is because
299 ;; back_comment in syntax.c may have to scan from bob to find the
300 ;; beginning of each comment. Fixing this is not trivial -- cyd.
301
302 ((eq arg 0))
6cb54822 303 (t
4df5698c
CY
304 (let ((floor (point-min))
305 (ceiling (point-max))
306 (arg-+ve (> arg 0)))
6cb54822
AM
307 (save-restriction
308 (widen)
4df5698c
CY
309 (let ((ppss (let (syntax-begin-function
310 font-lock-beginning-of-syntax-function)
311 (syntax-ppss)))
312 ;; position of least enclosing paren, or nil.
313 encl-pos)
314 ;; Back out of any comment/string, so that encl-pos will always
315 ;; become nil if we're at top-level.
316 (when (nth 8 ppss)
317 (goto-char (nth 8 ppss))
318 (setq ppss (syntax-ppss))) ; should be fast, due to cache.
319 (setq encl-pos (syntax-ppss-toplevel-pos ppss))
320 (if encl-pos (goto-char encl-pos))
321
322 (and encl-pos arg-+ve (setq arg (1- arg)))
323 (and (not encl-pos) (not arg-+ve) (not (looking-at "\\s("))
324 (setq arg (1+ arg)))
325
326 (condition-case nil ; to catch crazy parens.
327 (progn
328 (goto-char (scan-lists (point) (- arg) 0))
329 (if arg-+ve
330 (if (>= (point) floor)
331 t
332 (goto-char floor)
333 nil)
334 ;; forward to next (, or trigger the c-c
335 (goto-char (1- (scan-lists (point) 1 -1)))
336 (if (<= (point) ceiling)
337 t
338 (goto-char ceiling)
339 nil)))
340 (error
341 (goto-char (if arg-+ve floor ceiling))
342 nil))))))))
c6eeec65 343
7bbab3e0
SM
344(defvar end-of-defun-function
345 (lambda () (forward-sexp 1))
61e21607 346 "Function for `end-of-defun' to call.
6d3e4d22 347This is used to find the end of the defun at point.
61e21607 348It is called with no argument, right after calling `beginning-of-defun-raw'.
6d3e4d22
SM
349So the function can assume that point is at the beginning of the defun body.
350It should move point to the first position after the defun.")
b73b9811 351
352(defun buffer-end (arg)
a64dc1a4 353 "Return the \"far end\" position of the buffer, in direction ARG.
03deb635
RS
354If ARG is positive, that's the end of the buffer.
355Otherwise, that's the beginning of the buffer."
b73b9811 356 (if (> arg 0) (point-max) (point-min)))
357
358(defun end-of-defun (&optional arg)
a64dc1a4
LT
359 "Move forward to next end of defun.
360With argument, do it that many times.
b73b9811 361Negative argument -N means move back to Nth preceding end of defun.
362
c6eeec65
DL
363An end of a defun occurs right after the close-parenthesis that
364matches the open-parenthesis that starts a defun; see function
ab22ee53
RS
365`beginning-of-defun'.
366
367If variable `end-of-defun-function' is non-nil, its value
368is called as a function to find the defun's end."
61eee794 369 (interactive "^p")
90c08845 370 (or (not (eq this-command 'end-of-defun))
967e1a52
JL
371 (eq last-command 'end-of-defun)
372 (and transient-mark-mode mark-active)
373 (push-mark))
44b254cc 374 (if (or (null arg) (= arg 0)) (setq arg 1))
f9f34ece
SM
375 (let ((pos (point))
376 (beg (progn (end-of-line 1) (beginning-of-defun-raw 1) (point))))
377 (funcall end-of-defun-function)
f2a8252a
SM
378 ;; When comparing point against pos, we want to consider that if
379 ;; point was right after the end of the function, it's still
380 ;; considered as "in that function".
381 ;; E.g. `eval-defun' from right after the last close-paren.
382 (unless (bolp)
383 (skip-chars-forward " \t")
384 (if (looking-at "\\s<\\|\n")
385 (forward-line 1)))
f9f34ece
SM
386 (cond
387 ((> arg 0)
388 ;; Moving forward.
389 (if (> (point) pos)
390 ;; We already moved forward by one because we started from
391 ;; within a function.
392 (setq arg (1- arg))
393 ;; We started from after the end of the previous function.
394 (goto-char pos))
395 (unless (zerop arg)
396 (beginning-of-defun-raw (- arg))
397 (funcall end-of-defun-function)))
398 ((< arg 0)
399 ;; Moving backward.
400 (if (< (point) pos)
401 ;; We already moved backward because we started from between
402 ;; two functions.
403 (setq arg (1+ arg))
404 ;; We started from inside a function.
405 (goto-char beg))
406 (unless (zerop arg)
407 (beginning-of-defun-raw (- arg))
408 (funcall end-of-defun-function))))
409 (unless (bolp)
410 (skip-chars-forward " \t")
411 (if (looking-at "\\s<\\|\n")
412 (forward-line 1)))))
b73b9811 413
afb62fdd 414(defun mark-defun (&optional allow-extend)
b73b9811 415 "Put mark at end of this defun, point at beginning.
cad113ae 416The defun marked is the one that contains point or follows point.
afb62fdd
RS
417
418Interactively, if this command is repeated
a64dc1a4 419or (in Transient Mark mode) if the mark is active,
afb62fdd
RS
420it marks the next defun after the ones already marked."
421 (interactive "p")
422 (cond ((and allow-extend
423 (or (and (eq last-command this-command) (mark t))
424 (and transient-mark-mode mark-active)))
be0d25b6
KG
425 (set-mark
426 (save-excursion
427 (goto-char (mark))
428 (end-of-defun)
429 (point))))
430 (t
d3d6bc9b
RS
431 (let ((opoint (point))
432 beg end)
433 (push-mark opoint)
434 ;; Try first in this order for the sake of languages with nested
435 ;; functions where several can end at the same place as with
436 ;; the offside rule, e.g. Python.
437 (beginning-of-defun)
438 (setq beg (point))
439 (end-of-defun)
440 (setq end (point))
441 (while (looking-at "^\n")
442 (forward-line 1))
443 (if (> (point) opoint)
444 (progn
445 ;; We got the right defun.
446 (push-mark beg nil t)
447 (goto-char end)
448 (exchange-point-and-mark))
449 ;; beginning-of-defun moved back one defun
450 ;; so we got the wrong one.
451 (goto-char opoint)
452 (end-of-defun)
453 (push-mark (point) nil t)
454 (beginning-of-defun))
455 (re-search-backward "^\n" (- (point) 1) t)))))
b73b9811 456
bbcc4d97 457(defun narrow-to-defun (&optional _arg)
3f7e952d 458 "Make text outside current defun invisible.
c6eeec65
DL
459The defun visible is the one that contains point or follows point.
460Optional ARG is ignored."
3f7e952d
RS
461 (interactive)
462 (save-excursion
463 (widen)
d3d6bc9b
RS
464 (let ((opoint (point))
465 beg end)
466 ;; Try first in this order for the sake of languages with nested
467 ;; functions where several can end at the same place as with
468 ;; the offside rule, e.g. Python.
050cc68b
LB
469
470 ;; Finding the start of the function is a bit problematic since
471 ;; `beginning-of-defun' when we are on the first character of
472 ;; the function might go to the previous function.
473 ;;
474 ;; Therefore we first move one character forward and then call
475 ;; `beginning-of-defun'. However now we must check that we did
476 ;; not move into the next function.
477 (let ((here (point)))
478 (unless (eolp)
479 (forward-char))
480 (beginning-of-defun)
481 (when (< (point) here)
482 (goto-char here)
483 (beginning-of-defun)))
d3d6bc9b 484 (setq beg (point))
750e563f 485 (end-of-defun)
d3d6bc9b
RS
486 (setq end (point))
487 (while (looking-at "^\n")
488 (forward-line 1))
489 (unless (> (point) opoint)
490 ;; beginning-of-defun moved back one defun
491 ;; so we got the wrong one.
492 (goto-char opoint)
493 (end-of-defun)
494 (setq end (point))
495 (beginning-of-defun)
496 (setq beg (point)))
497 (goto-char end)
498 (re-search-backward "^\n" (- (point) 1) t)
499 (narrow-to-region beg end))))
3f7e952d 500
d97c8198
JL
501(defvar insert-pair-alist
502 '((?\( ?\)) (?\[ ?\]) (?\{ ?\}) (?\< ?\>) (?\" ?\") (?\' ?\') (?\` ?\'))
503 "Alist of paired characters inserted by `insert-pair'.
504Each element looks like (OPEN-CHAR CLOSE-CHAR) or (COMMAND-CHAR
505OPEN-CHAR CLOSE-CHAR). The characters OPEN-CHAR and CLOSE-CHAR
506of the pair whose key is equal to the last input character with
507or without modifiers, are inserted by `insert-pair'.")
508
509(defun insert-pair (&optional arg open close)
5891bf24
JL
510 "Enclose following ARG sexps in a pair of OPEN and CLOSE characters.
511Leave point after the first character.
e3ac26cb 512A negative ARG encloses the preceding ARG sexps instead.
5891bf24
JL
513No argument is equivalent to zero: just insert characters
514and leave point between.
d5bfe076 515If `parens-require-spaces' is non-nil, this command also inserts a space
5891bf24 516before and after, depending on the surrounding characters.
d97c8198
JL
517If region is active, insert enclosing characters at region boundaries.
518
519If arguments OPEN and CLOSE are nil, the character pair is found
520from the variable `insert-pair-alist' according to the last input
521character with or without modifiers. If no character pair is
522found in the variable `insert-pair-alist', then the last input
8fc2ac41
AM
523character is inserted ARG times.
524
525This command assumes point is not in a string or comment."
b73b9811 526 (interactive "P")
d97c8198 527 (if (not (and open close))
61a846fb 528 (let ((pair (or (assq last-command-event insert-pair-alist)
d97c8198
JL
529 (assq (event-basic-type last-command-event)
530 insert-pair-alist))))
531 (if pair
532 (if (nth 2 pair)
533 (setq open (nth 1 pair) close (nth 2 pair))
534 (setq open (nth 0 pair) close (nth 1 pair))))))
535 (if (and open close)
536 (if (and transient-mark-mode mark-active)
537 (progn
538 (save-excursion (goto-char (region-end)) (insert close))
539 (save-excursion (goto-char (region-beginning)) (insert open)))
540 (if arg (setq arg (prefix-numeric-value arg))
541 (setq arg 0))
542 (cond ((> arg 0) (skip-chars-forward " \t"))
543 ((< arg 0) (forward-sexp arg) (setq arg (- arg))))
544 (and parens-require-spaces
545 (not (bobp))
546 (memq (char-syntax (preceding-char)) (list ?w ?_ (char-syntax close)))
547 (insert " "))
548 (insert open)
549 (save-excursion
550 (or (eq arg 0) (forward-sexp arg))
551 (insert close)
552 (and parens-require-spaces
553 (not (eobp))
554 (memq (char-syntax (following-char)) (list ?w ?_ (char-syntax open)))
555 (insert " "))))
556 (insert-char (event-basic-type last-command-event)
557 (prefix-numeric-value arg))))
558
559(defun insert-parentheses (&optional arg)
a64dc1a4
LT
560 "Enclose following ARG sexps in parentheses.
561Leave point after open-paren.
5891bf24
JL
562A negative ARG encloses the preceding ARG sexps instead.
563No argument is equivalent to zero: just insert `()' and leave point between.
564If `parens-require-spaces' is non-nil, this command also inserts a space
565before and after, depending on the surrounding characters.
8fc2ac41
AM
566If region is active, insert enclosing characters at region boundaries.
567
568This command assumes point is not in a string or comment."
5891bf24
JL
569 (interactive "P")
570 (insert-pair arg ?\( ?\)))
b73b9811 571
d97c8198
JL
572(defun delete-pair ()
573 "Delete a pair of characters enclosing the sexp that follows point."
574 (interactive)
575 (save-excursion (forward-sexp 1) (delete-char -1))
576 (delete-char 1))
577
578(defun raise-sexp (&optional arg)
579 "Raise ARG sexps higher up the tree."
580 (interactive "p")
581 (let ((s (if (and transient-mark-mode mark-active)
582 (buffer-substring (region-beginning) (region-end))
583 (buffer-substring
584 (point)
585 (save-excursion (forward-sexp arg) (point))))))
586 (backward-up-list 1)
587 (delete-region (point) (save-excursion (forward-sexp 1) (point)))
588 (save-excursion (insert s))))
589
b73b9811 590(defun move-past-close-and-reindent ()
591 "Move past next `)', delete indentation before it, then indent after it."
592 (interactive)
593 (up-list 1)
594 (forward-char -1)
595 (while (save-excursion ; this is my contribution
596 (let ((before-paren (point)))
597 (back-to-indentation)
adce3b5f
RS
598 (and (= (point) before-paren)
599 (progn
600 ;; Move to end of previous line.
601 (beginning-of-line)
602 (forward-char -1)
603 ;; Verify it doesn't end within a string or comment.
604 (let ((end (point))
605 state)
606 (beginning-of-line)
607 ;; Get state at start of line.
c6eeec65 608 (setq state (list 0 nil nil
adce3b5f
RS
609 (null (calculate-lisp-indent))
610 nil nil nil nil
611 nil))
612 ;; Parse state across the line to get state at end.
613 (setq state (parse-partial-sexp (point) end nil nil
614 state))
615 ;; Check not in string or comment.
616 (and (not (elt state 3)) (not (elt state 4))))))))
b73b9811 617 (delete-indentation))
618 (forward-char 1)
619 (newline-and-indent))
c6eeec65
DL
620
621(defun check-parens () ; lame name?
622 "Check for unbalanced parentheses in the current buffer.
623More accurately, check the narrowed part of the buffer for unbalanced
624expressions (\"sexps\") in general. This is done according to the
625current syntax table and will find unbalanced brackets or quotes as
7bc10886 626appropriate. (See Info node `(emacs)Parentheses'.) If imbalance is
8ad8cfa5 627found, an error is signaled and point is left at the first unbalanced
7bc10886 628character."
c6eeec65
DL
629 (interactive)
630 (condition-case data
631 ;; Buffer can't have more than (point-max) sexps.
632 (scan-sexps (point-min) (point-max))
633 (scan-error (goto-char (nth 2 data))
634 ;; Could print (nth 1 data), which is either
635 ;; "Containing expression ends prematurely" or
636 ;; "Unbalanced parentheses", but those may not be so
637 ;; accurate/helpful, e.g. quotes may actually be
638 ;; mismatched.
dd8791e9 639 (user-error "Unmatched bracket or quote"))))
b73b9811 640\f
61e21607 641(defun field-complete (table &optional predicate)
dd8791e9 642 (declare (obsolete completion-in-region "24.4"))
73ebf88f
SM
643 (let ((minibuffer-completion-table table)
644 (minibuffer-completion-predicate predicate)
645 ;; This made sense for lisp-complete-symbol, but for
646 ;; field-complete, this is out of place. --Stef
647 ;; (completion-annotate-function
648 ;; (unless (eq predicate 'fboundp)
649 ;; (lambda (str)
650 ;; (if (fboundp (intern-soft str)) " <f>"))))
651 )
652 (call-interactively 'minibuffer-complete)))
61e21607 653
e50c4203 654(defun lisp-complete-symbol (&optional predicate)
2eb9adab
RS
655 "Perform completion on Lisp symbol preceding point.
656Compare that symbol against the known Lisp symbols.
1fa1cb1b
RS
657If no characters can be completed, display a list of possible completions.
658Repeating the command at that point scrolls the list.
2eb9adab 659
e50c4203
DL
660When called from a program, optional arg PREDICATE is a predicate
661determining which symbols are considered, e.g. `commandp'.
662If PREDICATE is nil, the context determines which symbols are
663considered. If the symbol starts just after an open-parenthesis, only
664symbols with function definitions are considered. Otherwise, all
665symbols with function definitions, values or properties are
666considered."
dd8791e9 667 (declare (obsolete completion-at-point "24.4"))
b73b9811 668 (interactive)
51ef56c4
SM
669 (let* ((data (lisp-completion-at-point predicate))
670 (plist (nthcdr 3 data)))
ccaa4765
SM
671 (if (null data)
672 (minibuffer-message "Nothing to complete")
2403c841
SM
673 (let ((completion-extra-properties plist))
674 (completion-in-region (nth 0 data) (nth 1 data) (nth 2 data)
ccaa4765 675 (plist-get plist :predicate))))))
0ca12598 676
bbcc4d97
SM
677(defun lisp--local-variables-1 (vars sexp)
678 "Return the vars locally bound around the witness, or nil if not found."
679 (let (res)
680 (while
681 (unless
682 (setq res
683 (pcase sexp
684 (`(,(or `let `let*) ,bindings)
685 (let ((vars vars))
686 (when (eq 'let* (car sexp))
687 (dolist (binding (cdr (reverse bindings)))
688 (push (or (car-safe binding) binding) vars)))
689 (lisp--local-variables-1
690 vars (car (cdr-safe (car (last bindings)))))))
691 (`(,(or `let `let*) ,bindings . ,body)
692 (let ((vars vars))
693 (dolist (binding bindings)
694 (push (or (car-safe binding) binding) vars))
695 (lisp--local-variables-1 vars (car (last body)))))
696 (`(lambda ,_) (setq sexp nil))
697 (`(lambda ,args . ,body)
698 (lisp--local-variables-1
699 (append args vars) (car (last body))))
700 (`(condition-case ,_ ,e) (lisp--local-variables-1 vars e))
701 (`(condition-case ,v ,_ . ,catches)
702 (lisp--local-variables-1
703 (cons v vars) (cdr (car (last catches)))))
704 (`(,_ . ,_)
705 (lisp--local-variables-1 vars (car (last sexp))))
706 (`lisp--witness--lisp (or vars '(nil)))
707 (_ nil)))
708 (setq sexp (ignore-errors (butlast sexp)))))
709 res))
710
711(defun lisp--local-variables ()
712 "Return a list of locally let-bound variables at point."
713 (save-excursion
714 (skip-syntax-backward "w_")
715 (let* ((ppss (syntax-ppss))
716 (txt (buffer-substring-no-properties (or (car (nth 9 ppss)) (point))
717 (or (nth 8 ppss) (point))))
718 (closer ()))
719 (dolist (p (nth 9 ppss))
720 (push (cdr (syntax-after p)) closer))
721 (setq closer (apply #'string closer))
722 (let* ((sexp (car (read-from-string
723 (concat txt "lisp--witness--lisp" closer))))
724 (macroexpand-advice (lambda (expander form &rest args)
725 (condition-case nil
726 (apply expander form args)
727 (error form))))
728 (sexp
729 (unwind-protect
730 (progn
731 (advice-add 'macroexpand :around macroexpand-advice)
732 (macroexpand-all sexp))
733 (advice-remove 'macroexpand macroexpand-advice)))
734 (vars (lisp--local-variables-1 nil sexp)))
735 (delq nil
736 (mapcar (lambda (var)
737 (and (symbolp var)
738 (not (string-match (symbol-name var) "\\`[&_]"))
739 ;; Eliminate uninterned vars.
740 (intern-soft var)
741 var))
742 vars))))))
743
744(defvar lisp--local-variables-completion-table
745 ;; Use `defvar' rather than `defconst' since defconst would purecopy this
746 ;; value, which would doubly fail: it would fail because purecopy can't
747 ;; handle the recursive bytecode object, and it would fail because it would
748 ;; move `lastpos' and `lastvars' to pure space where they'd be immutable!
749 (let ((lastpos nil) (lastvars nil))
750 (letrec ((hookfun (lambda ()
751 (setq lastpos nil)
752 (remove-hook 'post-command-hook hookfun))))
753 (completion-table-dynamic
754 (lambda (_string)
755 (save-excursion
756 (skip-syntax-backward "_w")
757 (let ((newpos (cons (point) (current-buffer))))
758 (unless (equal lastpos newpos)
759 (add-hook 'post-command-hook hookfun)
760 (setq lastpos newpos)
761 (setq lastvars
762 (mapcar #'symbol-name (lisp--local-variables))))))
763 lastvars)))))
764
2da4c3ab
SM
765;; FIXME: Support for Company brings in features which straddle eldoc.
766;; We should consolidate this, so that major modes can provide all that
767;; data all at once:
768;; - a function to extract "the reference at point" (may be more complex
769;; than a mere string, to distinguish various namespaces).
770;; - a function to jump to such a reference.
771;; - a function to show the signature/interface of such a reference.
772;; - a function to build a help-buffer about that reference.
773;; FIXME: Those functions should also be used by the normal completion code in
774;; the *Completions* buffer.
775
776(defun lisp--company-doc-buffer (str)
777 (let ((symbol (intern-soft str)))
778 ;; FIXME: we really don't want to "display-buffer and then undo it".
779 (save-window-excursion
780 ;; Make sure we don't display it in another frame, otherwise
781 ;; save-window-excursion won't be able to undo it.
782 (let ((display-buffer-overriding-action
783 '(nil . ((inhibit-switch-frame . t)))))
784 (ignore-errors
785 (cond
786 ((fboundp symbol) (describe-function symbol))
787 ((boundp symbol) (describe-variable symbol))
788 ((featurep symbol) (describe-package symbol))
789 ((facep symbol) (describe-face symbol))
790 (t (signal 'user-error nil)))
791 (help-buffer))))))
792
793(defun lisp--company-doc-string (str)
794 (let* ((symbol (intern-soft str))
795 (doc (if (fboundp symbol)
796 (documentation symbol t)
797 (documentation-property symbol 'variable-documentation t))))
798 (and (stringp doc)
799 (string-match ".*$" doc)
800 (match-string 0 doc))))
801
802(declare-function find-library-name "find-func" (library))
803
804(defun lisp--company-location (str)
805 (let ((sym (intern-soft str)))
806 (cond
807 ((fboundp sym) (find-definition-noselect sym nil))
808 ((boundp sym) (find-definition-noselect sym 'defvar))
809 ((featurep sym)
810 (require 'find-func)
811 (cons (find-file-noselect (find-library-name
812 (symbol-name sym)))
813 0))
814 ((facep sym) (find-definition-noselect sym 'defface)))))
815
bbcc4d97 816(defun lisp-completion-at-point (&optional _predicate)
0ca12598 817 "Function used for `completion-at-point-functions' in `emacs-lisp-mode'."
4c528197 818 (with-syntax-table emacs-lisp-mode-syntax-table
4c14013d
JB
819 (let* ((pos (point))
820 (beg (condition-case nil
821 (save-excursion
822 (backward-sexp 1)
823 (skip-syntax-forward "'")
824 (point))
825 (scan-error pos)))
4c14013d
JB
826 (end
827 (unless (or (eq beg (point-max))
29127376
SM
828 (member (char-syntax (char-after beg))
829 '(?\s ?\" ?\( ?\))))
4c14013d
JB
830 (condition-case nil
831 (save-excursion
832 (goto-char beg)
833 (forward-sexp 1)
834 (when (>= (point) pos)
835 (point)))
dd8791e9
SM
836 (scan-error pos))))
837 (funpos (eq (char-before beg) ?\()) ;t if in function position.
838 (table-etc
839 (if (not funpos)
840 ;; FIXME: We could look at the first element of the list and
841 ;; use it to provide a more specific completion table in some
842 ;; cases. E.g. filter out keywords that are not understood by
843 ;; the macro/function being called.
a333e4d2 844 (list nil (completion-table-merge
bbcc4d97 845 lisp--local-variables-completion-table
29127376
SM
846 (apply-partially #'completion-table-with-predicate
847 obarray
848 ;; Don't include all symbols
849 ;; (bug#16646).
850 (lambda (sym)
851 (or (boundp sym)
852 (fboundp sym)
853 (symbol-plist sym)))
854 'strict))
dd8791e9 855 :annotation-function
2da4c3ab
SM
856 (lambda (str) (if (fboundp (intern-soft str)) " <f>"))
857 :company-doc-buffer #'lisp--company-doc-buffer
858 :company-docsig #'lisp--company-doc-string
859 :company-location #'lisp--company-location)
dd8791e9
SM
860 ;; Looks like a funcall position. Let's double check.
861 (save-excursion
862 (goto-char (1- beg))
863 (let ((parent
864 (condition-case nil
865 (progn (up-list -1) (forward-char 1)
866 (let ((c (char-after)))
867 (if (eq c ?\() ?\(
868 (if (memq (char-syntax c) '(?w ?_))
869 (read (current-buffer))))))
870 (error nil))))
871 (pcase parent
872 ;; FIXME: Rather than hardcode special cases here,
873 ;; we should use something like a symbol-property.
874 (`declare
875 (list t (mapcar (lambda (x) (symbol-name (car x)))
2da4c3ab
SM
876 (delete-dups
877 ;; FIXME: We should include some
878 ;; docstring with each entry.
879 (append
880 macro-declarations-alist
881 defun-declarations-alist)))))
c9023370
SM
882 ((and (or `condition-case `condition-case-unless-debug)
883 (guard (save-excursion
884 (ignore-errors
885 (forward-sexp 2)
886 (< (point) beg)))))
dd8791e9
SM
887 (list t obarray
888 :predicate (lambda (sym) (get sym 'error-conditions))))
e333fb10
SM
889 ((and ?\(
890 (guard (save-excursion
891 (goto-char (1- beg))
892 (up-list -1)
893 (forward-symbol -1)
894 (looking-at "\\_<let\\*?\\_>"))))
895 (list t obarray
896 :predicate #'boundp
897 :company-doc-buffer #'lisp--company-doc-buffer
898 :company-docsig #'lisp--company-doc-string
899 :company-location #'lisp--company-location))
2da4c3ab
SM
900 (_ (list nil obarray
901 :predicate #'fboundp
902 :company-doc-buffer #'lisp--company-doc-buffer
903 :company-docsig #'lisp--company-doc-string
904 :company-location #'lisp--company-location
905 ))))))))
4c14013d 906 (when end
dd8791e9
SM
907 (let ((tail (if (null (car table-etc))
908 (cdr table-etc)
909 (cons
df76dacb 910 (if (memq (char-syntax (or (char-after end) ?\s))
dd8791e9
SM
911 '(?\s ?>))
912 (cadr table-etc)
913 (apply-partially 'completion-table-with-terminator
914 " " (cadr table-etc)))
915 (cddr table-etc)))))
916 `(,beg ,end ,@tail))))))
6594deb0
ER
917
918;;; lisp.el ends here