1 ;;; elec-pair.el --- Automatic parenthesis pairing -*- lexical-binding:t -*-
3 ;; Copyright (C) 2013-2014 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/>.
30 (defcustom electric-pair-pairs
32 "Alist of pairs that should be used regardless of major mode.
34 Pairs of delimiters in this list are a fallback in case they have
35 no syntax relevant to `electric-pair-mode' in the mode's syntax
38 See also the variable `electric-pair-text-pairs'."
41 :type '(repeat (cons character character)))
44 (defcustom electric-pair-text-pairs
46 "Alist of pairs that should always be used in comments and strings.
48 Pairs of delimiters in this list are a fallback in case they have
49 no syntax relevant to `electric-pair-mode' in the syntax table
50 defined in `electric-pair-text-syntax-table'"
53 :type '(repeat (cons character character)))
55 (defcustom electric-pair-skip-self #'electric-pair-default-skip-self
56 "If non-nil, skip char instead of inserting a second closing paren.
58 When inserting a closing paren character right before the same character,
59 just skip that character instead, so that hitting ( followed by ) results
60 in \"()\" rather than \"())\".
62 This can be convenient for people who find it easier to hit ) than C-f.
64 Can also be a function of one argument (the closer char just
65 inserted), in which case that function's return value is
70 (const :tag "Never skip" nil)
71 (const :tag "Help balance" electric-pair-default-skip-self)
72 (const :tag "Always skip" t)
75 (defcustom electric-pair-inhibit-predicate
76 #'electric-pair-default-inhibit
77 "Predicate to prevent insertion of a matching pair.
79 The function is called with a single char (the opening char just inserted).
80 If it returns non-nil, then `electric-pair-mode' will not insert a matching
85 (const :tag "Conservative" electric-pair-conservative-inhibit)
86 (const :tag "Help balance" electric-pair-default-inhibit)
87 (const :tag "Always pair" ignore)
90 (defcustom electric-pair-preserve-balance t
91 "Non-nil if default pairing and skipping should help balance parentheses.
93 The default values of `electric-pair-inhibit-predicate' and
94 `electric-pair-skip-self' check this variable before delegating to other
95 predicates responsible for making decisions on whether to pair/skip some
96 characters based on the actual state of the buffer's parentheses and
102 (defcustom electric-pair-delete-adjacent-pairs t
103 "If non-nil, backspacing an open paren also deletes adjacent closer.
105 Can also be a function of no arguments, in which case that function's
106 return value is considered instead."
111 (const :tag "No" nil)
114 (defcustom electric-pair-open-newline-between-pairs t
115 "If non-nil, a newline between adjacent parentheses opens an extra one.
117 Can also be a function of no arguments, in which case that function's
118 return value is considered instead."
123 (const :tag "No" nil)
126 (defcustom electric-pair-skip-whitespace t
127 "If non-nil skip whitespace when skipping over closing parens.
129 The specific kind of whitespace skipped is given by the variable
130 `electric-pair-skip-whitespace-chars'.
132 The symbol `chomp' specifies that the skipped-over whitespace
135 Can also be a function of no arguments, in which case that function's
136 return value is considered instead."
140 (const :tag "Yes, jump over whitespace" t)
141 (const :tag "Yes, and delete whitespace" chomp)
142 (const :tag "No, no whitespace skipping" nil)
145 (defcustom electric-pair-skip-whitespace-chars (list ?\t ?\s ?\n)
146 "Whitespace characters considered by `electric-pair-skip-whitespace'."
149 :type '(choice (set (const :tag "Space" ?\s)
150 (const :tag "Tab" ?\t)
151 (const :tag "Newline" ?\n))
154 (defun electric-pair--skip-whitespace ()
155 "Skip whitespace forward, not crossing comment or string boundaries."
156 (let ((saved (point))
157 (string-or-comment (nth 8 (syntax-ppss))))
158 (skip-chars-forward (apply #'string electric-pair-skip-whitespace-chars))
159 (unless (eq string-or-comment (nth 8 (syntax-ppss)))
162 (defvar electric-pair-text-syntax-table prog-mode-syntax-table
163 "Syntax table used when pairing inside comments and strings.
165 `electric-pair-mode' considers this syntax table only when point in inside
166 quotes or comments. If lookup fails here, `electric-pair-text-pairs' will
169 (defun electric-pair-backward-delete-char (n &optional killflag untabify)
170 "Delete characters backward, and maybe also two adjacent paired delimiters.
172 Remaining behavior is given by `backward-delete-char' or, if UNTABIFY is
173 non-nil, `backward-delete-char-untabify'."
174 (interactive "*p\nP")
175 (let* ((prev (char-before))
177 (syntax-info (and prev
178 (electric-pair-syntax-info prev)))
179 (syntax (car syntax-info))
180 (pair (cadr syntax-info)))
182 (if (functionp electric-pair-delete-adjacent-pairs)
183 (funcall electric-pair-delete-adjacent-pairs)
184 electric-pair-delete-adjacent-pairs)
185 (memq syntax '(?\( ?\" ?\$))
187 (delete-char 1 killflag))
189 (backward-delete-char-untabify n killflag)
190 (backward-delete-char n killflag))))
192 (defun electric-pair-backward-delete-char-untabify (n &optional killflag)
193 "Delete characters backward, and maybe also two adjacent paired delimiters.
195 Remaining behavior is given by `backward-delete-char-untabify'."
196 (interactive "*p\nP")
197 (electric-pair-backward-delete-char n killflag t))
199 (defun electric-pair-conservative-inhibit (char)
201 ;; I find it more often preferable not to pair when the
202 ;; same char is next.
203 (eq char (char-after))
204 ;; Don't pair up when we insert the second of "" or of ((.
205 (and (eq char (char-before))
206 (eq char (char-before (1- (point)))))
207 ;; I also find it often preferable not to pair next to a word.
208 (eq (char-syntax (following-char)) ?w)))
210 (defun electric-pair-syntax-info (command-event)
211 "Calculate a list (SYNTAX PAIR UNCONDITIONAL STRING-OR-COMMENT-START).
213 SYNTAX is COMMAND-EVENT's syntax character. PAIR is
214 COMMAND-EVENT's pair. UNCONDITIONAL indicates the variables
215 `electric-pair-pairs' or `electric-pair-text-pairs' were used to
216 lookup syntax. STRING-OR-COMMENT-START indicates that point is
217 inside a comment or string."
218 (let* ((pre-string-or-comment (or (bobp)
219 (nth 8 (save-excursion
220 (syntax-ppss (1- (point)))))))
221 (post-string-or-comment (nth 8 (syntax-ppss (point))))
222 (string-or-comment (and post-string-or-comment
223 pre-string-or-comment))
224 (table (if string-or-comment
225 electric-pair-text-syntax-table
227 (table-syntax-and-pair (with-syntax-table table
228 (list (char-syntax command-event)
229 (or (matching-paren command-event)
231 (fallback (if string-or-comment
232 (append electric-pair-text-pairs
234 electric-pair-pairs))
235 (direct (assq command-event fallback))
236 (reverse (rassq command-event fallback)))
238 ((memq (car table-syntax-and-pair)
240 (append table-syntax-and-pair (list nil string-or-comment)))
241 (direct (if (eq (car direct) (cdr direct))
242 (list ?\" command-event t string-or-comment)
243 (list ?\( (cdr direct) t string-or-comment)))
244 (reverse (list ?\) (car reverse) t string-or-comment)))))
246 (defun electric-pair--insert (char)
247 (let ((last-command-event char)
248 (blink-matching-paren nil)
249 (electric-pair-mode nil))
250 (self-insert-command 1)))
252 (defun electric-pair--syntax-ppss (&optional pos where)
253 "Like `syntax-ppss', but sometimes fallback to `parse-partial-sexp'.
255 WHERE is a list defaulting to '(string comment) and indicates
256 when to fallback to `parse-partial-sexp'."
257 (let* ((pos (or pos (point)))
258 (where (or where '(string comment)))
259 (quick-ppss (syntax-ppss))
260 (quick-ppss-at-pos (syntax-ppss pos))
261 (in-string (and (nth 3 quick-ppss-at-pos) (memq 'string where)))
262 (in-comment (and (nth 4 quick-ppss-at-pos) (memq 'comment where)))
263 (s-or-c-start (cond (in-string
264 (1+ (nth 8 quick-ppss)))
266 (goto-char (nth 8 quick-ppss))
267 (forward-comment (- (point-max)))
268 (skip-syntax-forward " >!")
271 (with-syntax-table electric-pair-text-syntax-table
272 (parse-partial-sexp s-or-c-start pos))
273 ;; HACK! cc-mode apparently has some `syntax-ppss' bugs
274 (if (memq major-mode '(c-mode c++ mode))
275 (parse-partial-sexp (point-min) pos)
276 quick-ppss-at-pos))))
278 ;; Balancing means controlling pairing and skipping of parentheses
279 ;; so that, if possible, the buffer ends up at least as balanced as
280 ;; before, if not more. The algorithm is slightly complex because
281 ;; some situations like "()))" need pairing to occur at the end but
282 ;; not at the beginning. Balancing should also happen independently
283 ;; for different types of parentheses, so that having your {}'s
284 ;; unbalanced doesn't keep `electric-pair-mode' from balancing your
285 ;; ()'s and your []'s.
286 (defun electric-pair--balance-info (direction string-or-comment)
287 "Examine lists forward or backward according to DIRECTION's sign.
289 STRING-OR-COMMENT is info suitable for running `parse-partial-sexp'.
291 Return a cons of two descriptions (MATCHED-P . PAIR) for the
292 innermost and outermost lists that enclose point. The outermost
293 list enclosing point is either the first top-level or first
294 mismatched list found by listing up.
296 If the outermost list is matched, don't rely on its PAIR.
297 If point is not enclosed by any lists, return ((t) . (t))."
300 (table (if string-or-comment
301 electric-pair-text-syntax-table
303 (at-top-level-or-equivalent-fn
304 ;; called when `scan-sexps' ran perfectly, when it found
305 ;; a parenthesis pointing in the direction of travel.
306 ;; Also when travel started inside a comment and exited it.
308 (setq outermost (list t))
310 (setq innermost (list t)))))
311 (ended-prematurely-fn
312 ;; called when `scan-sexps' crashed against a parenthesis
313 ;; pointing opposite the direction of travel. After
314 ;; traversing that character, the idea is to travel one sexp
315 ;; in the opposite direction looking for a matching
321 (cond ((< direction 0)
324 (with-syntax-table table
327 (scan-sexps (point) 1)))))
330 ;; In this case, no need to use
331 ;; `scan-sexps', we can use some
332 ;; `electric-pair--syntax-ppss' in this
333 ;; case (which uses the quicker
334 ;; `syntax-ppss' in some cases)
335 (let* ((ppss (electric-pair--syntax-ppss
337 (start (car (last (nth 9 ppss))))
338 (opener (char-after start)))
340 (eq (char-before pos)
341 (or (with-syntax-table table
342 (matching-paren opener))
344 (actual-pair (if (> direction 0)
345 (char-before (point))
346 (char-after (point)))))
348 (setq innermost (cons matched actual-pair)))
350 (setq outermost (cons matched actual-pair)))))))
352 (while (not outermost)
354 (with-syntax-table table
355 (scan-sexps (point) (if (> direction 0)
358 (funcall at-top-level-or-equivalent-fn))
361 ;; some error happened and it is not of the "ended
362 ;; prematurely" kind...
363 (not (string-match "ends prematurely" (nth 1 err)))
364 ;; ... or we were in a comment and just came out of
366 (and string-or-comment
367 (not (nth 8 (syntax-ppss)))))
368 (funcall at-top-level-or-equivalent-fn))
371 (goto-char (nth 3 err))
372 (funcall ended-prematurely-fn)))))))
373 (cons innermost outermost)))
375 (defvar electric-pair-string-bound-function 'point-max
376 "Next buffer position where strings are syntatically unexpected.
377 Value is a function called with no arguments and returning a
378 buffer position. Major modes should set this variable
379 buffer-locally if they experience slowness with
380 `electric-pair-mode' when pairing quotes.")
382 (defun electric-pair--unbalanced-strings-p (char)
383 "Return non-nil if there are unbalanced strings started by CHAR."
384 (let* ((selector-ppss (syntax-ppss))
385 (relevant-ppss (save-excursion
386 (if (nth 4 selector-ppss) ; comment
387 (electric-pair--syntax-ppss
389 (goto-char (nth 8 selector-ppss))
390 (forward-comment (point-max))
391 (skip-syntax-backward " >!")
394 (funcall electric-pair-string-bound-function)))))
395 (string-delim (nth 3 relevant-ppss)))
396 (or (eq t string-delim)
397 (eq char string-delim))))
399 (defun electric-pair--inside-string-p (char)
400 "Return non-nil if point is inside a string started by CHAR.
402 A comments text is parsed with `electric-pair-text-syntax-table'.
403 Also consider strings within comments, but not strings within
405 ;; FIXME: could also consider strings within strings by examining
407 (let ((ppss (electric-pair--syntax-ppss (point) '(comment))))
408 (memq (nth 3 ppss) (list t char))))
410 (defun electric-pair-inhibit-if-helps-balance (char)
411 "Return non-nil if auto-pairing of CHAR would hurt parentheses' balance.
413 Works by first removing the character from the buffer, then doing
414 some list calculations, finally restoring the situation as if nothing
416 (pcase (electric-pair-syntax-info char)
417 (`(,syntax ,pair ,_ ,s-or-c)
421 (cond ((eq ?\( syntax)
423 (electric-pair--balance-info 1 s-or-c))
424 (outermost (cdr pair-data)))
425 (cond ((car outermost)
428 (eq (cdr outermost) pair)))))
430 (electric-pair--unbalanced-strings-p char))))
431 (insert-char char)))))
433 (defun electric-pair-skip-if-helps-balance (char)
434 "Return non-nil if skipping CHAR would benefit parentheses' balance.
436 Works by first removing the character from the buffer, then doing
437 some list calculations, finally restoring the situation as if nothing
439 (pcase (electric-pair-syntax-info char)
440 (`(,syntax ,pair ,_ ,s-or-c)
444 (cond ((eq syntax ?\))
446 (electric-pair--balance-info
448 (innermost (car pair-data))
449 (outermost (cdr pair-data)))
451 (cond ((car outermost)
454 (not (eq (cdr outermost) pair)))))))
456 (electric-pair--inside-string-p char))))
457 (insert-char char)))))
459 (defun electric-pair-default-skip-self (char)
460 (if electric-pair-preserve-balance
461 (electric-pair-skip-if-helps-balance char)
464 (defun electric-pair-default-inhibit (char)
465 (if electric-pair-preserve-balance
466 (electric-pair-inhibit-if-helps-balance char)
467 (electric-pair-conservative-inhibit char)))
469 (defun electric-pair-post-self-insert-function ()
470 (let* ((pos (and electric-pair-mode (electric--after-char-pos)))
471 (skip-whitespace-info))
472 (pcase (electric-pair-syntax-info last-command-event)
473 (`(,syntax ,pair ,unconditional ,_)
476 ;; Wrap a pair around the active region.
478 ((and (memq syntax '(?\( ?\) ?\" ?\$)) (use-region-p))
479 ;; FIXME: To do this right, we'd need a post-self-insert-function
480 ;; so we could add-function around it and insert the closer after
481 ;; all the rest of the hook has run.
482 (if (or (eq syntax ?\")
485 (and (not (eq syntax ?\)))
486 (>= (mark) (point))))
489 (electric-pair--insert pair))
490 (delete-region pos (1- pos))
491 (electric-pair--insert pair)
493 (electric-pair--insert last-command-event)))
494 ;; Backslash-escaped: no pairing, no skipping.
497 (not (zerop (% (skip-syntax-backward "\\") 2))))
500 ((and (memq syntax '(?\) ?\" ?\$))
501 (and (or unconditional
502 (if (functionp electric-pair-skip-self)
503 (funcall electric-pair-skip-self last-command-event)
504 electric-pair-skip-self))
506 (when (setq skip-whitespace-info
507 (if (functionp electric-pair-skip-whitespace)
508 (funcall electric-pair-skip-whitespace)
509 electric-pair-skip-whitespace))
510 (electric-pair--skip-whitespace))
511 (eq (char-after) last-command-event))))
512 ;; This is too late: rather than insert&delete we'd want to only
513 ;; skip (or insert in overwrite mode). The difference is in what
514 ;; goes in the undo-log and in the intermediate state which might
515 ;; be visible to other post-self-insert-hook. We'll just have to
516 ;; live with it for now.
517 (when skip-whitespace-info
518 (electric-pair--skip-whitespace))
519 (delete-region (1- pos) (if (eq skip-whitespace-info 'chomp)
523 ;; Insert matching pair.
524 ((and (memq syntax `(?\( ?\" ?\$))
527 (not (funcall electric-pair-inhibit-predicate
528 last-command-event))))
529 (save-excursion (electric-pair--insert pair)))))
531 (when (and (if (functionp electric-pair-open-newline-between-pairs)
532 (funcall electric-pair-open-newline-between-pairs)
533 electric-pair-open-newline-between-pairs)
534 (eq last-command-event ?\n)
535 (< (1+ (point-min)) (point) (point-max))
537 (skip-chars-backward "\t\s")
538 (char-before (1- (point))))
539 (matching-paren (char-after))))
540 (save-excursion (newline 1 t)))))))
542 (put 'electric-pair-post-self-insert-function 'priority 20)
544 (defun electric-pair-will-use-region ()
546 (memq (car (electric-pair-syntax-info last-command-event))
547 '(?\( ?\) ?\" ?\$))))
549 (defvar electric-pair-mode-map
550 (let ((map (make-sparse-keymap)))
551 (define-key map [remap backward-delete-char-untabify]
552 'electric-pair-backward-delete-char-untabify)
553 (define-key map [remap backward-delete-char]
554 'electric-pair-backward-delete-char)
555 (define-key map [remap delete-backward-char]
556 'electric-pair-backward-delete-char)
558 "Keymap used by `electric-pair-mode'.")
561 (define-minor-mode electric-pair-mode
562 "Toggle automatic parens pairing (Electric Pair mode).
563 With a prefix argument ARG, enable Electric Pair mode if ARG is
564 positive, and disable it otherwise. If called from Lisp, enable
565 the mode if ARG is omitted or nil.
567 Electric Pair mode is a global minor mode. When enabled, typing
568 an open parenthesis automatically inserts the corresponding
569 closing parenthesis. (Likewise for brackets, etc.)."
570 :global t :group 'electricity
571 (if electric-pair-mode
573 (add-hook 'post-self-insert-hook
574 #'electric-pair-post-self-insert-function)
575 (electric--sort-post-self-insertion-hook)
576 (add-hook 'self-insert-uses-region-functions
577 #'electric-pair-will-use-region))
578 (remove-hook 'post-self-insert-hook
579 #'electric-pair-post-self-insert-function)
580 (remove-hook 'self-insert-uses-region-functions
581 #'electric-pair-will-use-region)))
585 ;;; elec-pair.el ends here