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-conservative-inhibit (char)
171 ;; I find it more often preferable not to pair when the
172 ;; same char is next.
173 (eq char
(char-after))
174 ;; Don't pair up when we insert the second of "" or of ((.
175 (and (eq char
(char-before))
176 (eq char
(char-before (1- (point)))))
177 ;; I also find it often preferable not to pair next to a word.
178 (eq (char-syntax (following-char)) ?w
)))
180 (defun electric-pair-syntax-info (command-event)
181 "Calculate a list (SYNTAX PAIR UNCONDITIONAL STRING-OR-COMMENT-START).
183 SYNTAX is COMMAND-EVENT's syntax character. PAIR is
184 COMMAND-EVENT's pair. UNCONDITIONAL indicates the variables
185 `electric-pair-pairs' or `electric-pair-text-pairs' were used to
186 lookup syntax. STRING-OR-COMMENT-START indicates that point is
187 inside a comment or string."
188 (let* ((pre-string-or-comment (or (bobp)
189 (nth 8 (save-excursion
190 (syntax-ppss (1- (point)))))))
191 (post-string-or-comment (nth 8 (syntax-ppss (point))))
192 (string-or-comment (and post-string-or-comment
193 pre-string-or-comment
))
194 (table (if string-or-comment
195 electric-pair-text-syntax-table
197 (table-syntax-and-pair (with-syntax-table table
198 (list (char-syntax command-event
)
199 (or (matching-paren command-event
)
201 (fallback (if string-or-comment
202 (append electric-pair-text-pairs
204 electric-pair-pairs
))
205 (direct (assq command-event fallback
))
206 (reverse (rassq command-event fallback
)))
208 ((memq (car table-syntax-and-pair
)
210 (append table-syntax-and-pair
(list nil string-or-comment
)))
211 (direct (if (eq (car direct
) (cdr direct
))
212 (list ?
\" command-event t string-or-comment
)
213 (list ?\
( (cdr direct
) t string-or-comment
)))
214 (reverse (list ?\
) (car reverse
) t string-or-comment
)))))
216 (defun electric-pair--insert (char)
217 (let ((last-command-event char
)
218 (blink-matching-paren nil
)
219 (electric-pair-mode nil
))
220 (self-insert-command 1)))
222 (defun electric-pair--syntax-ppss (&optional pos where
)
223 "Like `syntax-ppss', but sometimes fallback to `parse-partial-sexp'.
225 WHERE is a list defaulting to '(string comment) and indicates
226 when to fallback to `parse-partial-sexp'."
227 (let* ((pos (or pos
(point)))
228 (where (or where
'(string comment
)))
229 (quick-ppss (syntax-ppss))
230 (quick-ppss-at-pos (syntax-ppss pos
))
231 (in-string (and (nth 3 quick-ppss-at-pos
) (memq 'string where
)))
232 (in-comment (and (nth 4 quick-ppss-at-pos
) (memq 'comment where
)))
233 (s-or-c-start (cond (in-string
234 (1+ (nth 8 quick-ppss
)))
236 (goto-char (nth 8 quick-ppss
))
237 (forward-comment (- (point-max)))
238 (skip-syntax-forward " >!")
241 (with-syntax-table electric-pair-text-syntax-table
242 (parse-partial-sexp s-or-c-start pos
))
243 ;; HACK! cc-mode apparently has some `syntax-ppss' bugs
244 (if (memq major-mode
'(c-mode c
++ mode
))
245 (parse-partial-sexp (point-min) pos
)
246 quick-ppss-at-pos
))))
248 ;; Balancing means controlling pairing and skipping of parentheses
249 ;; so that, if possible, the buffer ends up at least as balanced as
250 ;; before, if not more. The algorithm is slightly complex because
251 ;; some situations like "()))" need pairing to occur at the end but
252 ;; not at the beginning. Balancing should also happen independently
253 ;; for different types of parentheses, so that having your {}'s
254 ;; unbalanced doesn't keep `electric-pair-mode' from balancing your
255 ;; ()'s and your []'s.
256 (defun electric-pair--balance-info (direction string-or-comment
)
257 "Examine lists forward or backward according to DIRECTION's sign.
259 STRING-OR-COMMENT is info suitable for running `parse-partial-sexp'.
261 Return a cons of two descriptions (MATCHED-P . PAIR) for the
262 innermost and outermost lists that enclose point. The outermost
263 list enclosing point is either the first top-level or first
264 mismatched list found by listing up.
266 If the outermost list is matched, don't rely on its PAIR.
267 If point is not enclosed by any lists, return ((t) . (t))."
270 (table (if string-or-comment
271 electric-pair-text-syntax-table
273 (at-top-level-or-equivalent-fn
274 ;; called when `scan-sexps' ran perfectly, when it found
275 ;; a parenthesis pointing in the direction of travel.
276 ;; Also when travel started inside a comment and exited it.
278 (setq outermost
(list t
))
280 (setq innermost
(list t
)))))
281 (ended-prematurely-fn
282 ;; called when `scan-sexps' crashed against a parenthesis
283 ;; pointing opposite the direction of travel. After
284 ;; traversing that character, the idea is to travel one sexp
285 ;; in the opposite direction looking for a matching
291 (cond ((< direction
0)
294 (with-syntax-table table
297 (scan-sexps (point) 1)))))
300 ;; In this case, no need to use
301 ;; `scan-sexps', we can use some
302 ;; `electric-pair--syntax-ppss' in this
303 ;; case (which uses the quicker
304 ;; `syntax-ppss' in some cases)
305 (let* ((ppss (electric-pair--syntax-ppss
307 (start (car (last (nth 9 ppss
))))
308 (opener (char-after start
)))
310 (eq (char-before pos
)
311 (or (with-syntax-table table
312 (matching-paren opener
))
314 (actual-pair (if (> direction
0)
315 (char-before (point))
316 (char-after (point)))))
318 (setq innermost
(cons matched actual-pair
)))
320 (setq outermost
(cons matched actual-pair
)))))))
322 (while (not outermost
)
324 (with-syntax-table table
325 (scan-sexps (point) (if (> direction
0)
328 (funcall at-top-level-or-equivalent-fn
))
331 ;; some error happened and it is not of the "ended
332 ;; prematurely" kind...
333 (not (string-match "ends prematurely" (nth 1 err
)))
334 ;; ... or we were in a comment and just came out of
336 (and string-or-comment
337 (not (nth 8 (syntax-ppss)))))
338 (funcall at-top-level-or-equivalent-fn
))
341 (goto-char (nth 3 err
))
342 (funcall ended-prematurely-fn
)))))))
343 (cons innermost outermost
)))
345 (defvar electric-pair-string-bound-function
'point-max
346 "Next buffer position where strings are syntactically unexpected.
347 Value is a function called with no arguments and returning a
348 buffer position. Major modes should set this variable
349 buffer-locally if they experience slowness with
350 `electric-pair-mode' when pairing quotes.")
352 (defun electric-pair--unbalanced-strings-p (char)
353 "Return non-nil if there are unbalanced strings started by CHAR."
354 (let* ((selector-ppss (syntax-ppss))
355 (relevant-ppss (save-excursion
356 (if (nth 4 selector-ppss
) ; comment
357 (electric-pair--syntax-ppss
359 (goto-char (nth 8 selector-ppss
))
360 (forward-comment (point-max))
361 (skip-syntax-backward " >!")
364 (funcall electric-pair-string-bound-function
)))))
365 (string-delim (nth 3 relevant-ppss
)))
366 (or (eq t string-delim
)
367 (eq char string-delim
))))
369 (defun electric-pair--inside-string-p (char)
370 "Return non-nil if point is inside a string started by CHAR.
372 A comments text is parsed with `electric-pair-text-syntax-table'.
373 Also consider strings within comments, but not strings within
375 ;; FIXME: could also consider strings within strings by examining
377 (let ((ppss (electric-pair--syntax-ppss (point) '(comment))))
378 (memq (nth 3 ppss
) (list t char
))))
380 (defun electric-pair-inhibit-if-helps-balance (char)
381 "Return non-nil if auto-pairing of CHAR would hurt parentheses' balance.
383 Works by first removing the character from the buffer, then doing
384 some list calculations, finally restoring the situation as if nothing
386 (pcase (electric-pair-syntax-info char
)
387 (`(,syntax
,pair
,_
,s-or-c
)
391 (cond ((eq ?\
( syntax
)
393 (electric-pair--balance-info 1 s-or-c
))
394 (outermost (cdr pair-data
)))
395 (cond ((car outermost
)
398 (eq (cdr outermost
) pair
)))))
400 (electric-pair--unbalanced-strings-p char
))))
401 (insert-char char
)))))
403 (defun electric-pair-skip-if-helps-balance (char)
404 "Return non-nil if skipping CHAR would benefit parentheses' balance.
406 Works by first removing the character from the buffer, then doing
407 some list calculations, finally restoring the situation as if nothing
409 (pcase (electric-pair-syntax-info char
)
410 (`(,syntax
,pair
,_
,s-or-c
)
414 (cond ((eq syntax ?\
))
416 (electric-pair--balance-info
418 (innermost (car pair-data
))
419 (outermost (cdr pair-data
)))
421 (cond ((car outermost
)
424 (not (eq (cdr outermost
) pair
)))))))
426 (electric-pair--inside-string-p char
))))
427 (insert-char char
)))))
429 (defun electric-pair-default-skip-self (char)
430 (if electric-pair-preserve-balance
431 (electric-pair-skip-if-helps-balance char
)
434 (defun electric-pair-default-inhibit (char)
435 (if electric-pair-preserve-balance
436 (electric-pair-inhibit-if-helps-balance char
)
437 (electric-pair-conservative-inhibit char
)))
439 (defun electric-pair-post-self-insert-function ()
440 (let* ((pos (and electric-pair-mode
(electric--after-char-pos)))
441 (skip-whitespace-info))
442 (pcase (electric-pair-syntax-info last-command-event
)
443 (`(,syntax
,pair
,unconditional
,_
)
446 ;; Wrap a pair around the active region.
448 ((and (memq syntax
'(?\
( ?\
) ?
\" ?\$
)) (use-region-p))
449 ;; FIXME: To do this right, we'd need a post-self-insert-function
450 ;; so we could add-function around it and insert the closer after
451 ;; all the rest of the hook has run.
452 (if (or (eq syntax ?
\")
455 (and (not (eq syntax ?\
)))
456 (>= (mark) (point))))
459 (electric-pair--insert pair
))
460 (delete-region pos
(1- pos
))
461 (electric-pair--insert pair
)
463 (electric-pair--insert last-command-event
)))
464 ;; Backslash-escaped: no pairing, no skipping.
467 (not (zerop (%
(skip-syntax-backward "\\") 2))))
470 ((and (memq syntax
'(?\
) ?
\" ?\$
))
471 (and (or unconditional
472 (if (functionp electric-pair-skip-self
)
473 (funcall electric-pair-skip-self last-command-event
)
474 electric-pair-skip-self
))
476 (when (and (not (and unconditional
478 (setq skip-whitespace-info
479 (if (functionp electric-pair-skip-whitespace
)
480 (funcall electric-pair-skip-whitespace
)
481 electric-pair-skip-whitespace
)))
482 (electric-pair--skip-whitespace))
483 (eq (char-after) last-command-event
))))
484 ;; This is too late: rather than insert&delete we'd want to only
485 ;; skip (or insert in overwrite mode). The difference is in what
486 ;; goes in the undo-log and in the intermediate state which might
487 ;; be visible to other post-self-insert-hook. We'll just have to
488 ;; live with it for now.
489 (when skip-whitespace-info
490 (electric-pair--skip-whitespace))
491 (delete-region (1- pos
) (if (eq skip-whitespace-info
'chomp
)
495 ;; Insert matching pair.
496 ((and (memq syntax
`(?\
( ?
\" ?\$
))
499 (not (funcall electric-pair-inhibit-predicate
500 last-command-event
))))
501 (save-excursion (electric-pair--insert pair
)))))
503 (when (and (if (functionp electric-pair-open-newline-between-pairs
)
504 (funcall electric-pair-open-newline-between-pairs
)
505 electric-pair-open-newline-between-pairs
)
506 (eq last-command-event ?
\n)
507 (< (1+ (point-min)) (point) (point-max))
509 (skip-chars-backward "\t\s")
510 (char-before (1- (point))))
511 (matching-paren (char-after))))
512 (save-excursion (newline 1 t
)))))))
514 (put 'electric-pair-post-self-insert-function
'priority
20)
516 (defun electric-pair-will-use-region ()
518 (memq (car (electric-pair-syntax-info last-command-event
))
519 '(?\
( ?\
) ?
\" ?\$
))))
521 (defun electric-pair-delete-pair (arg &optional killp
)
522 "When between adjacent paired delimiters, delete both of them.
523 ARG and KILLP are passed directly to
524 `backward-delete-char-untabify', which see."
525 (interactive "*p\nP")
527 (backward-delete-char-untabify arg killp
))
529 (defvar electric-pair-mode-map
530 (let ((map (make-sparse-keymap)))
531 (define-key map
"\177"
533 "" electric-pair-delete-pair
536 (let* ((prev (char-before))
538 (syntax-info (and prev
539 (electric-pair-syntax-info prev
)))
540 (syntax (car syntax-info
))
541 (pair (cadr syntax-info
)))
543 (memq syntax
'(?\
( ?
\" ?\$
))
545 (if (functionp electric-pair-delete-adjacent-pairs
)
546 (funcall electric-pair-delete-adjacent-pairs
)
547 electric-pair-delete-adjacent-pairs
)
550 "Keymap used by `electric-pair-mode'.")
553 (define-minor-mode electric-pair-mode
554 "Toggle automatic parens pairing (Electric Pair mode).
555 With a prefix argument ARG, enable Electric Pair mode if ARG is
556 positive, and disable it otherwise. If called from Lisp, enable
557 the mode if ARG is omitted or nil.
559 Electric Pair mode is a global minor mode. When enabled, typing
560 an open parenthesis automatically inserts the corresponding
561 closing parenthesis. (Likewise for brackets, etc.)."
562 :global t
:group
'electricity
563 (if electric-pair-mode
565 (add-hook 'post-self-insert-hook
566 #'electric-pair-post-self-insert-function
)
567 (electric--sort-post-self-insertion-hook)
568 (add-hook 'self-insert-uses-region-functions
569 #'electric-pair-will-use-region
))
570 (remove-hook 'post-self-insert-hook
571 #'electric-pair-post-self-insert-function
)
572 (remove-hook 'self-insert-uses-region-functions
573 #'electric-pair-will-use-region
)))
577 ;;; elec-pair.el ends here