Merge branch 'master' into comment-cache
[emacs.git] / lisp / elec-pair.el
blob87e82e24fb19bb42bdb43bc96b3e36cc51d8fb9b
1 ;;; elec-pair.el --- Automatic parenthesis pairing -*- lexical-binding:t -*-
3 ;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
5 ;; Author: João Távora <joaotavora@gmail.com>
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22 ;;; Commentary:
24 ;;; Code:
26 (require 'electric)
28 ;;; Electric pairing.
30 (defcustom electric-pair-pairs
31 '((?\" . ?\")
32 ((nth 0 electric-quote-chars) . (nth 1 electric-quote-chars))
33 ((nth 2 electric-quote-chars) . (nth 3 electric-quote-chars)))
34 "Alist of pairs that should be used regardless of major mode.
36 Pairs of delimiters in this list are a fallback in case they have
37 no syntax relevant to `electric-pair-mode' in the mode's syntax
38 table.
40 See also the variable `electric-pair-text-pairs'."
41 :version "24.1"
42 :group 'electricity
43 :type '(repeat (cons character character)))
45 ;;;###autoload
46 (defcustom electric-pair-text-pairs
47 '((?\" . ?\" )
48 ((nth 0 electric-quote-chars) . (nth 1 electric-quote-chars))
49 ((nth 2 electric-quote-chars) . (nth 3 electric-quote-chars)))
50 "Alist of pairs that should always be used in comments and strings.
52 Pairs of delimiters in this list are a fallback in case they have
53 no syntax relevant to `electric-pair-mode' in the syntax table
54 defined in `electric-pair-text-syntax-table'"
55 :version "24.4"
56 :group 'electricity
57 :type '(repeat (cons character character)))
59 (defcustom electric-pair-skip-self #'electric-pair-default-skip-self
60 "If non-nil, skip char instead of inserting a second closing paren.
62 When inserting a closing paren character right before the same character,
63 just skip that character instead, so that hitting ( followed by ) results
64 in \"()\" rather than \"())\".
66 This can be convenient for people who find it easier to hit ) than C-f.
68 Can also be a function of one argument (the closer char just
69 inserted), in which case that function's return value is
70 considered instead."
71 :version "24.1"
72 :group 'electricity
73 :type '(choice
74 (const :tag "Never skip" nil)
75 (const :tag "Help balance" electric-pair-default-skip-self)
76 (const :tag "Always skip" t)
77 function))
79 (defcustom electric-pair-inhibit-predicate
80 #'electric-pair-default-inhibit
81 "Predicate to prevent insertion of a matching pair.
83 The function is called with a single char (the opening char just inserted).
84 If it returns non-nil, then `electric-pair-mode' will not insert a matching
85 closer."
86 :version "24.4"
87 :group 'electricity
88 :type '(choice
89 (const :tag "Conservative" electric-pair-conservative-inhibit)
90 (const :tag "Help balance" electric-pair-default-inhibit)
91 (const :tag "Always pair" ignore)
92 function))
94 (defcustom electric-pair-preserve-balance t
95 "Non-nil if default pairing and skipping should help balance parentheses.
97 The default values of `electric-pair-inhibit-predicate' and
98 `electric-pair-skip-self' check this variable before delegating to other
99 predicates responsible for making decisions on whether to pair/skip some
100 characters based on the actual state of the buffer's parentheses and
101 quotes."
102 :version "24.4"
103 :group 'electricity
104 :type 'boolean)
106 (defcustom electric-pair-delete-adjacent-pairs t
107 "If non-nil, backspacing an open paren also deletes adjacent closer.
109 Can also be a function of no arguments, in which case that function's
110 return value is considered instead."
111 :version "24.4"
112 :group 'electricity
113 :type '(choice
114 (const :tag "Yes" t)
115 (const :tag "No" nil)
116 function))
118 (defcustom electric-pair-open-newline-between-pairs t
119 "If non-nil, a newline between adjacent parentheses opens an extra one.
121 Can also be a function of no arguments, in which case that function's
122 return value is considered instead."
123 :version "24.4"
124 :group 'electricity
125 :type '(choice
126 (const :tag "Yes" t)
127 (const :tag "No" nil)
128 function))
130 (defcustom electric-pair-skip-whitespace t
131 "If non-nil skip whitespace when skipping over closing parens.
133 The specific kind of whitespace skipped is given by the variable
134 `electric-pair-skip-whitespace-chars'.
136 The symbol `chomp' specifies that the skipped-over whitespace
137 should be deleted.
139 Can also be a function of no arguments, in which case that function's
140 return value is considered instead."
141 :version "24.4"
142 :group 'electricity
143 :type '(choice
144 (const :tag "Yes, jump over whitespace" t)
145 (const :tag "Yes, and delete whitespace" chomp)
146 (const :tag "No, no whitespace skipping" nil)
147 function))
149 (defcustom electric-pair-skip-whitespace-chars (list ?\t ?\s ?\n)
150 "Whitespace characters considered by `electric-pair-skip-whitespace'."
151 :version "24.4"
152 :group 'electricity
153 :type '(choice (set (const :tag "Space" ?\s)
154 (const :tag "Tab" ?\t)
155 (const :tag "Newline" ?\n))
156 (list character)))
158 (defun electric-pair--skip-whitespace ()
159 "Skip whitespace forward, not crossing comment or string boundaries."
160 (let ((saved (point))
161 (string-or-comment (nth 8 (syntax-ppss))))
162 (skip-chars-forward (apply #'string electric-pair-skip-whitespace-chars))
163 (unless (eq string-or-comment (nth 8 (syntax-ppss)))
164 (goto-char saved))))
166 (defvar electric-pair-text-syntax-table prog-mode-syntax-table
167 "Syntax table used when pairing inside comments and strings.
169 `electric-pair-mode' considers this syntax table only when point in inside
170 quotes or comments. If lookup fails here, `electric-pair-text-pairs' will
171 be considered.")
173 (defun electric-pair-conservative-inhibit (char)
175 ;; I find it more often preferable not to pair when the
176 ;; same char is next.
177 (eq char (char-after))
178 ;; Don't pair up when we insert the second of "" or of ((.
179 (and (eq char (char-before))
180 (eq char (char-before (1- (point)))))
181 ;; I also find it often preferable not to pair next to a word.
182 (eq (char-syntax (following-char)) ?w)))
184 (defun electric-pair-syntax-info (command-event)
185 "Calculate a list (SYNTAX PAIR UNCONDITIONAL STRING-OR-COMMENT-START).
187 SYNTAX is COMMAND-EVENT's syntax character. PAIR is
188 COMMAND-EVENT's pair. UNCONDITIONAL indicates the variables
189 `electric-pair-pairs' or `electric-pair-text-pairs' were used to
190 lookup syntax. STRING-OR-COMMENT-START indicates that point is
191 inside a comment or string."
192 (let* ((pre-string-or-comment (or (bobp)
193 (nth 8 (save-excursion
194 (syntax-ppss (1- (point)))))))
195 (post-string-or-comment (nth 8 (syntax-ppss (point))))
196 (string-or-comment (and post-string-or-comment
197 pre-string-or-comment))
198 (table (if string-or-comment
199 electric-pair-text-syntax-table
200 (syntax-table)))
201 (table-syntax-and-pair (with-syntax-table table
202 (list (char-syntax command-event)
203 (or (matching-paren command-event)
204 command-event))))
205 (fallback (if string-or-comment
206 (append electric-pair-text-pairs
207 electric-pair-pairs)
208 electric-pair-pairs))
209 (direct (assq command-event fallback))
210 (reverse (rassq command-event fallback)))
211 (cond
212 ((memq (car table-syntax-and-pair)
213 '(?\" ?\( ?\) ?\$))
214 (append table-syntax-and-pair (list nil string-or-comment)))
215 (direct (if (eq (car direct) (cdr direct))
216 (list ?\" command-event t string-or-comment)
217 (list ?\( (cdr direct) t string-or-comment)))
218 (reverse (list ?\) (car reverse) t string-or-comment)))))
220 (defun electric-pair--insert (char)
221 (let ((last-command-event char)
222 (blink-matching-paren nil)
223 (electric-pair-mode nil))
224 (self-insert-command 1)))
226 (defun electric-pair--syntax-ppss (&optional pos where)
227 "Like `syntax-ppss', but sometimes fallback to `parse-partial-sexp'.
229 WHERE is a list defaulting to '(string comment) and indicates
230 when to fallback to `parse-partial-sexp'."
231 (let* ((pos (or pos (point)))
232 (where (or where '(string comment)))
233 (quick-ppss (syntax-ppss pos))
234 (in-string (and (nth 3 quick-ppss) (memq 'string where)))
235 (in-comment (and (nth 4 quick-ppss) (memq 'comment where)))
236 (s-or-c-start (cond (in-string
237 (1+ (nth 8 quick-ppss)))
238 (in-comment
239 (goto-char (nth 8 quick-ppss))
240 (forward-comment (- (point-max)))
241 (skip-syntax-forward " >!")
242 (point)))))
243 (if s-or-c-start
244 (with-syntax-table electric-pair-text-syntax-table
245 (parse-partial-sexp s-or-c-start pos))
246 ;; HACK! cc-mode apparently has some `syntax-ppss' bugs
247 (if (memq major-mode '(c-mode c++ mode))
248 (parse-partial-sexp (point-min) pos)
249 quick-ppss))))
251 ;; Balancing means controlling pairing and skipping of parentheses
252 ;; so that, if possible, the buffer ends up at least as balanced as
253 ;; before, if not more. The algorithm is slightly complex because
254 ;; some situations like "()))" need pairing to occur at the end but
255 ;; not at the beginning. Balancing should also happen independently
256 ;; for different types of parentheses, so that having your {}'s
257 ;; unbalanced doesn't keep `electric-pair-mode' from balancing your
258 ;; ()'s and your []'s.
259 (defun electric-pair--balance-info (direction string-or-comment)
260 "Examine lists forward or backward according to DIRECTION's sign.
262 STRING-OR-COMMENT is info suitable for running `parse-partial-sexp'.
264 Return a cons of two descriptions (MATCHED-P . PAIR) for the
265 innermost and outermost lists that enclose point. The outermost
266 list enclosing point is either the first top-level or first
267 mismatched list found by listing up.
269 If the outermost list is matched, don't rely on its PAIR.
270 If point is not enclosed by any lists, return ((t) . (t))."
271 (let* (innermost
272 outermost
273 (table (if string-or-comment
274 electric-pair-text-syntax-table
275 (syntax-table)))
276 (at-top-level-or-equivalent-fn
277 ;; called when `scan-sexps' ran perfectly, when it found
278 ;; a parenthesis pointing in the direction of travel.
279 ;; Also when travel started inside a comment and exited it.
280 #'(lambda ()
281 (setq outermost (list t))
282 (unless innermost
283 (setq innermost (list t)))))
284 (ended-prematurely-fn
285 ;; called when `scan-sexps' crashed against a parenthesis
286 ;; pointing opposite the direction of travel. After
287 ;; traversing that character, the idea is to travel one sexp
288 ;; in the opposite direction looking for a matching
289 ;; delimiter.
290 #'(lambda ()
291 (let* ((pos (point))
292 (matched
293 (save-excursion
294 (cond ((< direction 0)
295 (condition-case nil
296 (eq (char-after pos)
297 (with-syntax-table table
298 (matching-paren
299 (char-before
300 (scan-sexps (point) 1)))))
301 (scan-error nil)))
303 ;; In this case, no need to use
304 ;; `scan-sexps', we can use some
305 ;; `electric-pair--syntax-ppss' in this
306 ;; case (which uses the quicker
307 ;; `syntax-ppss' in some cases)
308 (let* ((ppss (electric-pair--syntax-ppss
309 (1- (point))))
310 (start (car (last (nth 9 ppss))))
311 (opener (char-after start)))
312 (and start
313 (eq (char-before pos)
314 (or (with-syntax-table table
315 (matching-paren opener))
316 opener))))))))
317 (actual-pair (if (> direction 0)
318 (char-before (point))
319 (char-after (point)))))
320 (unless innermost
321 (setq innermost (cons matched actual-pair)))
322 (unless matched
323 (setq outermost (cons matched actual-pair)))))))
324 (save-excursion
325 (while (not outermost)
326 (condition-case err
327 (with-syntax-table table
328 (scan-sexps (point) (if (> direction 0)
329 (point-max)
330 (- (point-max))))
331 (funcall at-top-level-or-equivalent-fn))
332 (scan-error
333 (cond ((or
334 ;; some error happened and it is not of the "ended
335 ;; prematurely" kind...
336 (not (string-match "ends prematurely" (nth 1 err)))
337 ;; ... or we were in a comment and just came out of
338 ;; it.
339 (and string-or-comment
340 (not (nth 8 (syntax-ppss)))))
341 (funcall at-top-level-or-equivalent-fn))
343 ;; exit the sexp
344 (goto-char (nth 3 err))
345 (funcall ended-prematurely-fn)))))))
346 (cons innermost outermost)))
348 (defvar electric-pair-string-bound-function 'point-max
349 "Next buffer position where strings are syntactically unexpected.
350 Value is a function called with no arguments and returning a
351 buffer position. Major modes should set this variable
352 buffer-locally if they experience slowness with
353 `electric-pair-mode' when pairing quotes.")
355 (defun electric-pair--unbalanced-strings-p (char)
356 "Return non-nil if there are unbalanced strings started by CHAR."
357 (let* ((selector-ppss (syntax-ppss))
358 (relevant-ppss (save-excursion
359 (if (nth 4 selector-ppss) ; comment
360 (electric-pair--syntax-ppss
361 (progn
362 (goto-char (nth 8 selector-ppss))
363 (forward-comment (point-max))
364 (skip-syntax-backward " >!")
365 (point)))
366 (syntax-ppss
367 (funcall electric-pair-string-bound-function)))))
368 (string-delim (nth 3 relevant-ppss)))
369 (or (eq t string-delim)
370 (eq char string-delim))))
372 (defun electric-pair--inside-string-p (char)
373 "Return non-nil if point is inside a string started by CHAR.
375 A comments text is parsed with `electric-pair-text-syntax-table'.
376 Also consider strings within comments, but not strings within
377 strings."
378 ;; FIXME: could also consider strings within strings by examining
379 ;; delimiters.
380 (let ((ppss (electric-pair--syntax-ppss (point) '(comment))))
381 (memq (nth 3 ppss) (list t char))))
383 (defun electric-pair-inhibit-if-helps-balance (char)
384 "Return non-nil if auto-pairing of CHAR would hurt parentheses' balance.
386 Works by first removing the character from the buffer, then doing
387 some list calculations, finally restoring the situation as if nothing
388 happened."
389 (pcase (electric-pair-syntax-info char)
390 (`(,syntax ,pair ,_ ,s-or-c)
391 (unwind-protect
392 (progn
393 (delete-char -1)
394 (cond ((eq ?\( syntax)
395 (let* ((pair-data
396 (electric-pair--balance-info 1 s-or-c))
397 (outermost (cdr pair-data)))
398 (cond ((car outermost)
399 nil)
401 (eq (cdr outermost) pair)))))
402 ((eq syntax ?\")
403 (electric-pair--unbalanced-strings-p char))))
404 (insert-char char)))))
406 (defun electric-pair-skip-if-helps-balance (char)
407 "Return non-nil if skipping CHAR would benefit parentheses' balance.
409 Works by first removing the character from the buffer, then doing
410 some list calculations, finally restoring the situation as if nothing
411 happened."
412 (pcase (electric-pair-syntax-info char)
413 (`(,syntax ,pair ,_ ,s-or-c)
414 (unwind-protect
415 (progn
416 (delete-char -1)
417 (cond ((eq syntax ?\))
418 (let* ((pair-data
419 (electric-pair--balance-info
420 -1 s-or-c))
421 (innermost (car pair-data))
422 (outermost (cdr pair-data)))
423 (and
424 (cond ((car outermost)
425 (car innermost))
426 ((car innermost)
427 (not (eq (cdr outermost) pair)))))))
428 ((eq syntax ?\")
429 (electric-pair--inside-string-p char))))
430 (insert-char char)))))
432 (defun electric-pair-default-skip-self (char)
433 (if electric-pair-preserve-balance
434 (electric-pair-skip-if-helps-balance char)
437 (defun electric-pair-default-inhibit (char)
438 (if electric-pair-preserve-balance
439 (electric-pair-inhibit-if-helps-balance char)
440 (electric-pair-conservative-inhibit char)))
442 (defun electric-pair-post-self-insert-function ()
443 (let* ((pos (and electric-pair-mode (electric--after-char-pos)))
444 (skip-whitespace-info))
445 (pcase (electric-pair-syntax-info last-command-event)
446 (`(,syntax ,pair ,unconditional ,_)
447 (cond
448 ((null pos) nil)
449 ;; Wrap a pair around the active region.
451 ((and (memq syntax '(?\( ?\) ?\" ?\$)) (use-region-p))
452 ;; FIXME: To do this right, we'd need a post-self-insert-function
453 ;; so we could add-function around it and insert the closer after
454 ;; all the rest of the hook has run.
455 (if (or (eq syntax ?\")
456 (and (eq syntax ?\))
457 (>= (point) (mark)))
458 (and (not (eq syntax ?\)))
459 (>= (mark) (point))))
460 (save-excursion
461 (goto-char (mark))
462 (electric-pair--insert pair))
463 (delete-region pos (1- pos))
464 (electric-pair--insert pair)
465 (goto-char (mark))
466 (electric-pair--insert last-command-event)))
467 ;; Backslash-escaped: no pairing, no skipping.
468 ((save-excursion
469 (goto-char (1- pos))
470 (not (zerop (% (skip-syntax-backward "\\") 2))))
471 nil)
472 ;; Skip self.
473 ((and (memq syntax '(?\) ?\" ?\$))
474 (and (or unconditional
475 (if (functionp electric-pair-skip-self)
476 (funcall electric-pair-skip-self last-command-event)
477 electric-pair-skip-self))
478 (save-excursion
479 (when (and (not (and unconditional
480 (eq syntax ?\")))
481 (setq skip-whitespace-info
482 (if (and (not (eq electric-pair-skip-whitespace 'chomp))
483 (functionp electric-pair-skip-whitespace))
484 (funcall electric-pair-skip-whitespace)
485 electric-pair-skip-whitespace)))
486 (electric-pair--skip-whitespace))
487 (eq (char-after) last-command-event))))
488 ;; This is too late: rather than insert&delete we'd want to only
489 ;; skip (or insert in overwrite mode). The difference is in what
490 ;; goes in the undo-log and in the intermediate state which might
491 ;; be visible to other post-self-insert-hook. We'll just have to
492 ;; live with it for now.
493 (when skip-whitespace-info
494 (electric-pair--skip-whitespace))
495 (delete-region (1- pos) (if (eq skip-whitespace-info 'chomp)
496 (point)
497 pos))
498 (forward-char))
499 ;; Insert matching pair.
500 ((and (memq syntax `(?\( ?\" ?\$))
501 (not overwrite-mode)
502 (or unconditional
503 (not (funcall electric-pair-inhibit-predicate
504 last-command-event))))
505 (save-excursion (electric-pair--insert pair)))))
507 (when (and (if (functionp electric-pair-open-newline-between-pairs)
508 (funcall electric-pair-open-newline-between-pairs)
509 electric-pair-open-newline-between-pairs)
510 (eq last-command-event ?\n)
511 (< (1+ (point-min)) (point) (point-max))
512 (eq (save-excursion
513 (skip-chars-backward "\t\s")
514 (char-before (1- (point))))
515 (matching-paren (char-after))))
516 (save-excursion (newline 1 t)))))))
518 (put 'electric-pair-post-self-insert-function 'priority 20)
520 (defun electric-pair-will-use-region ()
521 (and (use-region-p)
522 (memq (car (electric-pair-syntax-info last-command-event))
523 '(?\( ?\) ?\" ?\$))))
525 (defun electric-pair-delete-pair (arg &optional killp)
526 "When between adjacent paired delimiters, delete both of them.
527 ARG and KILLP are passed directly to
528 `backward-delete-char-untabify', which see."
529 (interactive "*p\nP")
530 (delete-char 1)
531 (backward-delete-char-untabify arg killp))
533 (defvar electric-pair-mode-map
534 (let ((map (make-sparse-keymap)))
535 (define-key map "\177"
536 `(menu-item
537 "" electric-pair-delete-pair
538 :filter
539 ,(lambda (cmd)
540 (let* ((prev (char-before))
541 (next (char-after))
542 (syntax-info (and prev
543 (electric-pair-syntax-info prev)))
544 (syntax (car syntax-info))
545 (pair (cadr syntax-info)))
546 (and next pair
547 (memq syntax '(?\( ?\" ?\$))
548 (eq pair next)
549 (if (functionp electric-pair-delete-adjacent-pairs)
550 (funcall electric-pair-delete-adjacent-pairs)
551 electric-pair-delete-adjacent-pairs)
552 cmd)))))
553 map)
554 "Keymap used by `electric-pair-mode'.")
556 ;;;###autoload
557 (define-minor-mode electric-pair-mode
558 "Toggle automatic parens pairing (Electric Pair mode).
559 With a prefix argument ARG, enable Electric Pair mode if ARG is
560 positive, and disable it otherwise. If called from Lisp, enable
561 the mode if ARG is omitted or nil.
563 Electric Pair mode is a global minor mode. When enabled, typing
564 an open parenthesis automatically inserts the corresponding
565 closing parenthesis. (Likewise for brackets, etc.). To toggle
566 the mode in a single buffer, use `electric-pair-local-mode'."
567 :global t :group 'electricity
568 (if electric-pair-mode
569 (progn
570 (add-hook 'post-self-insert-hook
571 #'electric-pair-post-self-insert-function)
572 (electric--sort-post-self-insertion-hook)
573 (add-hook 'self-insert-uses-region-functions
574 #'electric-pair-will-use-region))
575 (remove-hook 'post-self-insert-hook
576 #'electric-pair-post-self-insert-function)
577 (remove-hook 'self-insert-uses-region-functions
578 #'electric-pair-will-use-region)))
580 ;;;###autoload
581 (define-minor-mode electric-pair-local-mode
582 "Toggle `electric-pair-mode' only in this buffer."
583 :variable (buffer-local-value 'electric-pair-mode (current-buffer))
584 (cond
585 ((eq electric-pair-mode (default-value 'electric-pair-mode))
586 (kill-local-variable 'electric-pair-mode))
587 ((not (default-value 'electric-pair-mode))
588 ;; Locally enabled, but globally disabled.
589 (electric-pair-mode 1) ; Setup the hooks.
590 (setq-default electric-pair-mode nil) ; But keep it globally disabled.
593 (provide 'elec-pair)
595 ;;; elec-pair.el ends here