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 (electric-pair-syntax-info prev
))
178 (syntax (car syntax-info
))
179 (pair (cadr syntax-info
)))
180 (when (and (if (functionp electric-pair-delete-adjacent-pairs
)
181 (funcall electric-pair-delete-adjacent-pairs
)
182 electric-pair-delete-adjacent-pairs
)
184 (memq syntax
'(?\
( ?
\" ?\$
))
186 (delete-char 1 killflag
))
188 (backward-delete-char-untabify n killflag
)
189 (backward-delete-char n killflag
))))
191 (defun electric-pair-backward-delete-char-untabify (n &optional killflag
)
192 "Delete characters backward, and maybe also two adjacent paired delimiters.
194 Remaining behavior is given by `backward-delete-char-untabify'."
195 (interactive "*p\nP")
196 (electric-pair-backward-delete-char n killflag t
))
198 (defun electric-pair-conservative-inhibit (char)
200 ;; I find it more often preferable not to pair when the
201 ;; same char is next.
202 (eq char
(char-after))
203 ;; Don't pair up when we insert the second of "" or of ((.
204 (and (eq char
(char-before))
205 (eq char
(char-before (1- (point)))))
206 ;; I also find it often preferable not to pair next to a word.
207 (eq (char-syntax (following-char)) ?w
)))
209 (defun electric-pair-syntax-info (command-event)
210 "Calculate a list (SYNTAX PAIR UNCONDITIONAL STRING-OR-COMMENT-START).
212 SYNTAX is COMMAND-EVENT's syntax character. PAIR is
213 COMMAND-EVENT's pair. UNCONDITIONAL indicates the variables
214 `electric-pair-pairs' or `electric-pair-text-pairs' were used to
215 lookup syntax. STRING-OR-COMMENT-START indicates that point is
216 inside a comment of string."
217 (let* ((pre-string-or-comment (nth 8 (save-excursion
218 (syntax-ppss (1- (point))))))
219 (post-string-or-comment (nth 8 (syntax-ppss (point))))
220 (string-or-comment (and post-string-or-comment
221 pre-string-or-comment
))
222 (table (if string-or-comment
223 electric-pair-text-syntax-table
225 (table-syntax-and-pair (with-syntax-table table
226 (list (char-syntax command-event
)
227 (or (matching-paren command-event
)
229 (fallback (if string-or-comment
230 (append electric-pair-text-pairs
232 electric-pair-pairs
))
233 (direct (assq command-event fallback
))
234 (reverse (rassq command-event fallback
)))
236 ((memq (car table-syntax-and-pair
)
238 (append table-syntax-and-pair
(list nil string-or-comment
)))
239 (direct (if (eq (car direct
) (cdr direct
))
240 (list ?
\" command-event t string-or-comment
)
241 (list ?\
( (cdr direct
) t string-or-comment
)))
242 (reverse (list ?\
) (car reverse
) t string-or-comment
)))))
244 (defun electric-pair--insert (char)
245 (let ((last-command-event char
)
246 (blink-matching-paren nil
)
247 (electric-pair-mode nil
))
248 (self-insert-command 1)))
250 (defun electric-pair--syntax-ppss (&optional pos where
)
251 "Like `syntax-ppss', but sometimes fallback to `parse-partial-sexp'.
253 WHERE is list defaulting to '(string comment) and indicates
254 when to fallback to `parse-partial-sexp'."
255 (let* ((pos (or pos
(point)))
256 (where (or where
'(string comment
)))
257 (quick-ppss (syntax-ppss))
258 (quick-ppss-at-pos (syntax-ppss pos
)))
259 (if (or (and (nth 3 quick-ppss
) (memq 'string where
))
260 (and (nth 4 quick-ppss
) (memq 'comment where
)))
261 (with-syntax-table electric-pair-text-syntax-table
262 (parse-partial-sexp (1+ (nth 8 quick-ppss
)) 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-at-pos
))))
268 ;; Balancing means controlling pairing and skipping of parentheses so
269 ;; that, if possible, the buffer ends up at least as balanced as
270 ;; before, if not more. The algorithm is slightly complex because some
271 ;; situations like "()))" need pairing to occur at the end but not at
272 ;; the beginning. Balancing should also happen independently for
273 ;; different types of parentheses, so that having your {}'s unbalanced
274 ;; doesn't keep `electric-pair-mode' from balancing your ()'s and your
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. If
287 point is not enclosed by any lists, return ((T) . (T))."
290 (table (if string-or-comment
291 electric-pair-text-syntax-table
293 (at-top-level-or-equivalent-fn
294 ;; called when `scan-sexps' ran perfectly, when when it
295 ;; found a parenthesis pointing in the direction of
296 ;; travel. Also when travel started inside a comment and
299 (setq outermost
(list t
))
301 (setq innermost
(list t
)))))
302 (ended-prematurely-fn
303 ;; called when `scan-sexps' crashed against a parenthesis
304 ;; pointing opposite the direction of travel. After
305 ;; traversing that character, the idea is to travel one sexp
306 ;; in the opposite direction looking for a matching
312 (cond ((< direction
0)
315 (with-syntax-table table
318 (scan-sexps (point) 1)))))
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
328 (start (car (last (nth 9 ppss
))))
329 (opener (char-after start
)))
331 (eq (char-before pos
)
332 (or (with-syntax-table table
333 (matching-paren opener
))
335 (actual-pair (if (> direction
0)
336 (char-before (point))
337 (char-after (point)))))
339 (setq innermost
(cons matched actual-pair
)))
341 (setq outermost
(cons matched actual-pair
)))))))
343 (while (not outermost
)
345 (with-syntax-table table
346 (scan-sexps (point) (if (> direction
0)
349 (funcall at-top-level-or-equivalent-fn
))
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
357 (and string-or-comment
358 (not (nth 8 (syntax-ppss)))))
359 (funcall at-top-level-or-equivalent-fn
))
362 (goto-char (nth 3 err
))
363 (funcall ended-prematurely-fn
)))))))
364 (cons innermost outermost
)))
366 (defun electric-pair--looking-at-unterminated-string-p (char)
367 "Say if following string starts with CHAR and is unterminated."
370 (skip-chars-forward (format "^%c" char
))
371 (while (not (zerop (%
(save-excursion (skip-syntax-backward "\\")) 2)))
374 (skip-chars-forward (format "^%c" char
))))
377 (progn (forward-sexp) nil
)
380 (defun electric-pair--inside-string-p (char)
381 "Say if point is inside a string started by CHAR.
383 A comments text is parsed with `electric-pair-text-syntax-table'.
384 Also consider strings within comments, but not strings within
386 ;; FIXME: could also consider strings within strings by examining
388 (let* ((ppss (electric-pair--syntax-ppss (point) '(comment))))
389 (memq (nth 3 ppss
) (list t char
))))
391 (defun electric-pair-inhibit-if-helps-balance (char)
392 "Return non-nil if auto-pairing of CHAR would hurt parentheses' balance.
394 Works by first removing the character from the buffer, then doing
395 some list calculations, finally restoring the situation as if nothing
397 (pcase (electric-pair-syntax-info char
)
398 (`(,syntax
,pair
,_
,s-or-c
)
402 (cond ((eq ?\
( syntax
)
404 (electric-pair--balance-info 1 s-or-c
))
405 (outermost (cdr pair-data
)))
406 (cond ((car outermost
)
409 (eq (cdr outermost
) pair
)))))
411 (electric-pair--looking-at-unterminated-string-p char
))))
412 (insert-char char
)))))
414 (defun electric-pair-skip-if-helps-balance (char)
415 "Return non-nil if skipping CHAR would benefit parentheses' balance.
417 Works by first removing the character from the buffer, then doing
418 some list calculations, finally restoring the situation as if nothing
420 (pcase (electric-pair-syntax-info char
)
421 (`(,syntax
,pair
,_
,s-or-c
)
425 (cond ((eq syntax ?\
))
427 (electric-pair--balance-info
429 (innermost (car pair-data
))
430 (outermost (cdr pair-data
)))
432 (cond ((car outermost
)
435 (not (eq (cdr outermost
) pair
)))))))
437 (electric-pair--inside-string-p char
))))
438 (insert-char char
)))))
440 (defun electric-pair-default-skip-self (char)
441 (if electric-pair-preserve-balance
442 (electric-pair-skip-if-helps-balance char
)
445 (defun electric-pair-default-inhibit (char)
446 (if electric-pair-preserve-balance
447 (electric-pair-inhibit-if-helps-balance char
)
448 (electric-pair-conservative-inhibit char
)))
450 (defun electric-pair-post-self-insert-function ()
451 (let* ((pos (and electric-pair-mode
(electric--after-char-pos)))
452 (skip-whitespace-info))
453 (pcase (electric-pair-syntax-info last-command-event
)
454 (`(,syntax
,pair
,unconditional
,_
)
457 ;; Wrap a pair around the active region.
459 ((and (memq syntax
'(?\
( ?\
) ?
\" ?\$
)) (use-region-p))
460 ;; FIXME: To do this right, we'd need a post-self-insert-function
461 ;; so we could add-function around it and insert the closer after
462 ;; all the rest of the hook has run.
463 (if (or (eq syntax ?
\")
466 (and (not (eq syntax ?\
)))
467 (>= (mark) (point))))
470 (electric-pair--insert pair
))
471 (delete-region pos
(1- pos
))
472 (electric-pair--insert pair
)
474 (electric-pair--insert last-command-event
)))
475 ;; Backslash-escaped: no pairing, no skipping.
478 (not (zerop (%
(skip-syntax-backward "\\") 2))))
481 ((and (memq syntax
'(?\
) ?
\" ?\$
))
482 (and (or unconditional
483 (if (functionp electric-pair-skip-self
)
484 (funcall electric-pair-skip-self last-command-event
)
485 electric-pair-skip-self
))
487 (when (setq skip-whitespace-info
488 (if (functionp electric-pair-skip-whitespace
)
489 (funcall electric-pair-skip-whitespace
)
490 electric-pair-skip-whitespace
))
491 (electric-pair--skip-whitespace))
492 (eq (char-after) last-command-event
))))
493 ;; This is too late: rather than insert&delete we'd want to only
494 ;; skip (or insert in overwrite mode). The difference is in what
495 ;; goes in the undo-log and in the intermediate state which might
496 ;; be visible to other post-self-insert-hook. We'll just have to
497 ;; live with it for now.
498 (when skip-whitespace-info
499 (electric-pair--skip-whitespace))
500 (delete-region (1- pos
) (if (eq skip-whitespace-info
'chomp
)
504 ;; Insert matching pair.
505 ((and (memq syntax
`(?\
( ?
\" ?\$
))
508 (not (funcall electric-pair-inhibit-predicate
509 last-command-event
))))
510 (save-excursion (electric-pair--insert pair
)))))
512 (when (and (if (functionp electric-pair-open-newline-between-pairs
)
513 (funcall electric-pair-open-newline-between-pairs
)
514 electric-pair-open-newline-between-pairs
)
515 (eq last-command-event ?
\n)
516 (< (1+ (point-min)) (point) (point-max))
518 (skip-chars-backward "\t\s")
519 (char-before (1- (point))))
520 (matching-paren (char-after))))
521 (save-excursion (newline 1 t
)))))))
523 (put 'electric-pair-post-self-insert-function
'priority
20)
525 (defun electric-pair-will-use-region ()
527 (memq (car (electric-pair-syntax-info last-command-event
))
528 '(?\
( ?\
) ?
\" ?\$
))))
530 (defvar electric-pair-mode-map
531 (let ((map (make-sparse-keymap)))
532 (define-key map
[remap backward-delete-char-untabify
]
533 'electric-pair-backward-delete-char-untabify
)
534 (define-key map
[remap backward-delete-char
]
535 'electric-pair-backward-delete-char
)
536 (define-key map
[remap delete-backward-char
]
537 'electric-pair-backward-delete-char
)
539 "Keymap used by `electric-pair-mode'.")
542 (define-minor-mode electric-pair-mode
543 "Toggle automatic parens pairing (Electric Pair mode).
544 With a prefix argument ARG, enable Electric Pair mode if ARG is
545 positive, and disable it otherwise. If called from Lisp, enable
546 the mode if ARG is omitted or nil.
548 Electric Pair mode is a global minor mode. When enabled, typing
549 an open parenthesis automatically inserts the corresponding
550 closing parenthesis. \(Likewise for brackets, etc.)."
551 :global t
:group
'electricity
552 (if electric-pair-mode
554 (add-hook 'post-self-insert-hook
555 #'electric-pair-post-self-insert-function
)
556 (electric--sort-post-self-insertion-hook)
557 (add-hook 'self-insert-uses-region-functions
558 #'electric-pair-will-use-region
))
559 (remove-hook 'post-self-insert-hook
560 #'electric-pair-post-self-insert-function
)
561 (remove-hook 'self-insert-uses-region-functions
562 #'electric-pair-will-use-region
)))
566 ;;; elec-pair.el ends here