Improve documentation of 'electric-pair-mode'
[emacs.git] / lisp / elec-pair.el
blob97049a7d9d964a3a935c0f8ca0556e6b63610097
1 ;;; elec-pair.el --- Automatic parenthesis pairing -*- lexical-binding:t -*-
3 ;; Copyright (C) 2013-2018 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 <https://www.gnu.org/licenses/>.
22 ;;; Commentary:
24 ;;; Code:
26 (require 'electric)
27 (eval-when-compile (require 'cl-lib))
29 ;;; Electric pairing.
31 (defcustom electric-pair-pairs
32 `((?\" . ?\")
33 (,(nth 0 electric-quote-chars) . ,(nth 1 electric-quote-chars))
34 (,(nth 2 electric-quote-chars) . ,(nth 3 electric-quote-chars)))
35 "Alist of pairs that should be used regardless of major mode.
37 Pairs of delimiters in this list are a fallback in case they have
38 no syntax relevant to `electric-pair-mode' in the mode's syntax
39 table.
41 See also the variable `electric-pair-text-pairs'."
42 :version "24.1"
43 :group 'electricity
44 :type '(repeat (cons character character)))
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 (cl-defmacro electric-pair--with-uncached-syntax ((table &optional start) &rest body)
227 "Like `with-syntax-table', but flush the syntax-ppss cache afterwards.
228 Use this instead of (with-syntax-table TABLE BODY) when BODY
229 contains code which may update the syntax-ppss cache. This
230 includes calling `parse-partial-sexp' and any sexp-based movement
231 functions when `parse-sexp-lookup-properties' is non-nil. The
232 cache is flushed from position START, defaulting to point."
233 (declare (debug ((form &optional form) body)) (indent 1))
234 (let ((start-var (make-symbol "start")))
235 `(let ((syntax-propertize-function nil)
236 (,start-var ,(or start '(point))))
237 (unwind-protect
238 (with-syntax-table ,table
239 ,@body)
240 (syntax-ppss-flush-cache ,start-var)))))
242 (defun electric-pair--syntax-ppss (&optional pos where)
243 "Like `syntax-ppss', but sometimes fallback to `parse-partial-sexp'.
245 WHERE is a list defaulting to '(string comment) and indicates
246 when to fallback to `parse-partial-sexp'."
247 (let* ((pos (or pos (point)))
248 (where (or where '(string comment)))
249 (quick-ppss (syntax-ppss pos))
250 (in-string (and (nth 3 quick-ppss) (memq 'string where)))
251 (in-comment (and (nth 4 quick-ppss) (memq 'comment where)))
252 (s-or-c-start (cond (in-string
253 (1+ (nth 8 quick-ppss)))
254 (in-comment
255 (goto-char (nth 8 quick-ppss))
256 (forward-comment (- (point-max)))
257 (skip-syntax-forward " >!")
258 (point)))))
259 (if s-or-c-start
260 (electric-pair--with-uncached-syntax (electric-pair-text-syntax-table
261 s-or-c-start)
262 (parse-partial-sexp s-or-c-start pos))
263 ;; HACK! cc-mode apparently has some `syntax-ppss' bugs
264 (if (memq major-mode '(c-mode c++ mode))
265 (parse-partial-sexp (point-min) pos)
266 quick-ppss))))
268 ;; Balancing means controlling pairing and skipping of parentheses
269 ;; so that, if possible, the buffer ends up at least as balanced as
270 ;; before, if not more. The algorithm is slightly complex because
271 ;; some situations like "()))" need pairing to occur at the end but
272 ;; not at the beginning. Balancing should also happen independently
273 ;; for different types of parentheses, so that having your {}'s
274 ;; unbalanced doesn't keep `electric-pair-mode' from balancing your
275 ;; ()'s and your []'s.
276 (defun electric-pair--balance-info (direction string-or-comment)
277 "Examine lists forward or backward according to DIRECTION's sign.
279 STRING-OR-COMMENT is info suitable for running `parse-partial-sexp'.
281 Return a cons of two descriptions (MATCHED-P . PAIR) for the
282 innermost and outermost lists that enclose point. The outermost
283 list enclosing point is either the first top-level or first
284 mismatched list found by listing up.
286 If the outermost list is matched, don't rely on its PAIR.
287 If point is not enclosed by any lists, return ((t) . (t))."
288 (let* (innermost
289 outermost
290 (table (if string-or-comment
291 electric-pair-text-syntax-table
292 (syntax-table)))
293 (at-top-level-or-equivalent-fn
294 ;; called when `scan-sexps' ran perfectly, when it found
295 ;; a parenthesis pointing in the direction of travel.
296 ;; Also when travel started inside a comment and exited it.
297 #'(lambda ()
298 (setq outermost (list t))
299 (unless innermost
300 (setq innermost (list t)))))
301 (ended-prematurely-fn
302 ;; called when `scan-sexps' crashed against a parenthesis
303 ;; pointing opposite the direction of travel. After
304 ;; traversing that character, the idea is to travel one sexp
305 ;; in the opposite direction looking for a matching
306 ;; delimiter.
307 #'(lambda ()
308 (let* ((pos (point))
309 (matched
310 (save-excursion
311 (cond ((< direction 0)
312 (condition-case nil
313 (eq (char-after pos)
314 (electric-pair--with-uncached-syntax
315 (table)
316 (matching-paren
317 (char-before
318 (scan-sexps (point) 1)))))
319 (scan-error nil)))
321 ;; In this case, no need to use
322 ;; `scan-sexps', we can use some
323 ;; `electric-pair--syntax-ppss' in this
324 ;; case (which uses the quicker
325 ;; `syntax-ppss' in some cases)
326 (let* ((ppss (electric-pair--syntax-ppss
327 (1- (point))))
328 (start (car (last (nth 9 ppss))))
329 (opener (char-after start)))
330 (and start
331 (eq (char-before pos)
332 (or (with-syntax-table table
333 (matching-paren opener))
334 opener))))))))
335 (actual-pair (if (> direction 0)
336 (char-before (point))
337 (char-after (point)))))
338 (unless innermost
339 (setq innermost (cons matched actual-pair)))
340 (unless matched
341 (setq outermost (cons matched actual-pair)))))))
342 (save-excursion
343 (while (not outermost)
344 (condition-case err
345 (electric-pair--with-uncached-syntax (table)
346 (scan-sexps (point) (if (> direction 0)
347 (point-max)
348 (- (point-max))))
349 (funcall at-top-level-or-equivalent-fn))
350 (scan-error
351 (cond ((or
352 ;; some error happened and it is not of the "ended
353 ;; prematurely" kind...
354 (not (string-match "ends prematurely" (nth 1 err)))
355 ;; ... or we were in a comment and just came out of
356 ;; it.
357 (and string-or-comment
358 (not (nth 8 (syntax-ppss)))))
359 (funcall at-top-level-or-equivalent-fn))
361 ;; exit the sexp
362 (goto-char (nth 3 err))
363 (funcall ended-prematurely-fn)))))))
364 (cons innermost outermost)))
366 (defvar electric-pair-string-bound-function 'point-max
367 "Next buffer position where strings are syntactically unexpected.
368 Value is a function called with no arguments and returning a
369 buffer position. Major modes should set this variable
370 buffer-locally if they experience slowness with
371 `electric-pair-mode' when pairing quotes.")
373 (defun electric-pair--unbalanced-strings-p (char)
374 "Return non-nil if there are unbalanced strings started by CHAR."
375 (let* ((selector-ppss (syntax-ppss))
376 (relevant-ppss (save-excursion
377 (if (nth 4 selector-ppss) ; comment
378 (electric-pair--syntax-ppss
379 (progn
380 (goto-char (nth 8 selector-ppss))
381 (forward-comment (point-max))
382 (skip-syntax-backward " >!")
383 (point)))
384 (syntax-ppss
385 (funcall electric-pair-string-bound-function)))))
386 (string-delim (nth 3 relevant-ppss)))
387 (or (eq t string-delim)
388 (eq char string-delim))))
390 (defun electric-pair--inside-string-p (char)
391 "Return non-nil if point is inside a string started by CHAR.
393 A comments text is parsed with `electric-pair-text-syntax-table'.
394 Also consider strings within comments, but not strings within
395 strings."
396 ;; FIXME: could also consider strings within strings by examining
397 ;; delimiters.
398 (let ((ppss (electric-pair--syntax-ppss (point) '(comment))))
399 (memq (nth 3 ppss) (list t char))))
401 (defun electric-pair-inhibit-if-helps-balance (char)
402 "Return non-nil if auto-pairing of CHAR would hurt parentheses' balance.
404 Works by first removing the character from the buffer, then doing
405 some list calculations, finally restoring the situation as if nothing
406 happened."
407 (pcase (electric-pair-syntax-info char)
408 (`(,syntax ,pair ,_ ,s-or-c)
409 (unwind-protect
410 (progn
411 (delete-char -1)
412 (cond ((eq ?\( syntax)
413 (let* ((pair-data
414 (electric-pair--balance-info 1 s-or-c))
415 (outermost (cdr pair-data)))
416 (cond ((car outermost)
417 nil)
419 (eq (cdr outermost) pair)))))
420 ((eq syntax ?\")
421 (electric-pair--unbalanced-strings-p char))))
422 (insert-char char)))))
424 (defun electric-pair-skip-if-helps-balance (char)
425 "Return non-nil if skipping CHAR would benefit parentheses' balance.
427 Works by first removing the character from the buffer, then doing
428 some list calculations, finally restoring the situation as if nothing
429 happened."
430 (pcase (electric-pair-syntax-info char)
431 (`(,syntax ,pair ,_ ,s-or-c)
432 (unwind-protect
433 (progn
434 (delete-char -1)
435 (cond ((eq syntax ?\))
436 (let* ((pair-data
437 (electric-pair--balance-info
438 -1 s-or-c))
439 (innermost (car pair-data))
440 (outermost (cdr pair-data)))
441 (and
442 (cond ((car outermost)
443 (car innermost))
444 ((car innermost)
445 (not (eq (cdr outermost) pair)))))))
446 ((eq syntax ?\")
447 (electric-pair--inside-string-p char))))
448 (insert-char char)))))
450 (defun electric-pair-default-skip-self (char)
451 (if electric-pair-preserve-balance
452 (electric-pair-skip-if-helps-balance char)
455 (defun electric-pair-default-inhibit (char)
456 (if electric-pair-preserve-balance
457 (electric-pair-inhibit-if-helps-balance char)
458 (electric-pair-conservative-inhibit char)))
460 (defun electric-pair-post-self-insert-function ()
461 (let* ((pos (and electric-pair-mode (electric--after-char-pos)))
462 (skip-whitespace-info))
463 (pcase (electric-pair-syntax-info last-command-event)
464 (`(,syntax ,pair ,unconditional ,_)
465 (cond
466 ((null pos) nil)
467 ;; Wrap a pair around the active region.
469 ((and (memq syntax '(?\( ?\) ?\" ?\$)) (use-region-p))
470 ;; FIXME: To do this right, we'd need a post-self-insert-function
471 ;; so we could add-function around it and insert the closer after
472 ;; all the rest of the hook has run.
473 (if (or (eq syntax ?\")
474 (and (eq syntax ?\))
475 (>= (point) (mark)))
476 (and (not (eq syntax ?\)))
477 (>= (mark) (point))))
478 (save-excursion
479 (goto-char (mark))
480 (electric-pair--insert pair))
481 (delete-region pos (1- pos))
482 (electric-pair--insert pair)
483 (goto-char (mark))
484 (electric-pair--insert last-command-event)))
485 ;; Backslash-escaped: no pairing, no skipping.
486 ((save-excursion
487 (goto-char (1- pos))
488 (not (zerop (% (skip-syntax-backward "\\") 2))))
489 nil)
490 ;; Skip self.
491 ((and (memq syntax '(?\) ?\" ?\$))
492 (and (or unconditional
493 (if (functionp electric-pair-skip-self)
494 (funcall electric-pair-skip-self last-command-event)
495 electric-pair-skip-self))
496 (save-excursion
497 (when (and (not (and unconditional
498 (eq syntax ?\")))
499 (setq skip-whitespace-info
500 (if (and (not (eq electric-pair-skip-whitespace 'chomp))
501 (functionp electric-pair-skip-whitespace))
502 (funcall electric-pair-skip-whitespace)
503 electric-pair-skip-whitespace)))
504 (electric-pair--skip-whitespace))
505 (eq (char-after) last-command-event))))
506 ;; This is too late: rather than insert&delete we'd want to only
507 ;; skip (or insert in overwrite mode). The difference is in what
508 ;; goes in the undo-log and in the intermediate state which might
509 ;; be visible to other post-self-insert-hook. We'll just have to
510 ;; live with it for now.
511 (when skip-whitespace-info
512 (electric-pair--skip-whitespace))
513 (delete-region (1- pos) (if (eq skip-whitespace-info 'chomp)
514 (point)
515 pos))
516 (forward-char))
517 ;; Insert matching pair.
518 ((and (memq syntax `(?\( ?\" ?\$))
519 (not overwrite-mode)
520 (or unconditional
521 (not (funcall electric-pair-inhibit-predicate
522 last-command-event))))
523 (save-excursion (electric-pair--insert pair)))))
525 (when (and (if (functionp electric-pair-open-newline-between-pairs)
526 (funcall electric-pair-open-newline-between-pairs)
527 electric-pair-open-newline-between-pairs)
528 (eq last-command-event ?\n)
529 (< (1+ (point-min)) (point) (point-max))
530 (eq (save-excursion
531 (skip-chars-backward "\t\s")
532 (char-before (1- (point))))
533 (matching-paren (char-after))))
534 (save-excursion (newline 1 t)))))))
536 (put 'electric-pair-post-self-insert-function 'priority 20)
538 (defun electric-pair-will-use-region ()
539 (and (use-region-p)
540 (memq (car (electric-pair-syntax-info last-command-event))
541 '(?\( ?\) ?\" ?\$))))
543 (defun electric-pair-delete-pair (arg &optional killp)
544 "When between adjacent paired delimiters, delete both of them.
545 ARG and KILLP are passed directly to
546 `backward-delete-char-untabify', which see."
547 (interactive "*p\nP")
548 (delete-char 1)
549 (backward-delete-char-untabify arg killp))
551 (defvar electric-pair-mode-map
552 (let ((map (make-sparse-keymap)))
553 (define-key map "\177"
554 `(menu-item
555 "" electric-pair-delete-pair
556 :filter
557 ,(lambda (cmd)
558 (let* ((prev (char-before))
559 (next (char-after))
560 (syntax-info (and prev
561 (electric-pair-syntax-info prev)))
562 (syntax (car syntax-info))
563 (pair (cadr syntax-info)))
564 (and next pair
565 (memq syntax '(?\( ?\" ?\$))
566 (eq pair next)
567 (if (functionp electric-pair-delete-adjacent-pairs)
568 (funcall electric-pair-delete-adjacent-pairs)
569 electric-pair-delete-adjacent-pairs)
570 cmd)))))
571 map)
572 "Keymap used by `electric-pair-mode'.")
574 ;;;###autoload
575 (define-minor-mode electric-pair-mode
576 "Toggle automatic parens pairing (Electric Pair mode).
577 With a prefix argument ARG, enable Electric Pair mode if ARG is
578 positive, and disable it otherwise. If called from Lisp, enable
579 the mode if ARG is omitted or nil.
581 Electric Pair mode is a global minor mode. When enabled, typing
582 an open parenthesis automatically inserts the corresponding
583 closing parenthesis, and vice versa. (Likewise for brackets, etc.).
584 If the region is active, the parentheses (brackets, etc.) are
585 inserted around the region instead.
587 To toggle the mode in a single buffer, use `electric-pair-local-mode'."
588 :global t :group 'electricity
589 (if electric-pair-mode
590 (progn
591 (add-hook 'post-self-insert-hook
592 #'electric-pair-post-self-insert-function)
593 (electric--sort-post-self-insertion-hook)
594 (add-hook 'self-insert-uses-region-functions
595 #'electric-pair-will-use-region))
596 (remove-hook 'post-self-insert-hook
597 #'electric-pair-post-self-insert-function)
598 (remove-hook 'self-insert-uses-region-functions
599 #'electric-pair-will-use-region)))
601 ;;;###autoload
602 (define-minor-mode electric-pair-local-mode
603 "Toggle `electric-pair-mode' only in this buffer."
604 :variable (buffer-local-value 'electric-pair-mode (current-buffer))
605 (cond
606 ((eq electric-pair-mode (default-value 'electric-pair-mode))
607 (kill-local-variable 'electric-pair-mode))
608 ((not (default-value 'electric-pair-mode))
609 ;; Locally enabled, but globally disabled.
610 (electric-pair-mode 1) ; Setup the hooks.
611 (setq-default electric-pair-mode nil) ; But keep it globally disabled.
614 (provide 'elec-pair)
616 ;;; elec-pair.el ends here