Output alists with dotted pair notation in .dir-locals.el
[emacs.git] / lisp / elec-pair.el
blob7df70982957050882a9b6cbcbf129ba8ac12a703
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 (defvar-local electric-pair-skip-whitespace-function
159 #'electric-pair--skip-whitespace
160 "Function to use to skip whitespace forward.
161 Before attempting a skip, if `electric-pair-skip-whitespace' is
162 non-nil, this function is called. It move point to a new buffer
163 position, presumably skipping only whitespace in between.")
165 (defun electric-pair--skip-whitespace ()
166 "Skip whitespace forward, not crossing comment or string boundaries."
167 (let ((saved (point))
168 (string-or-comment (nth 8 (syntax-ppss))))
169 (skip-chars-forward (apply #'string electric-pair-skip-whitespace-chars))
170 (unless (eq string-or-comment (nth 8 (syntax-ppss)))
171 (goto-char saved))))
173 (defvar electric-pair-text-syntax-table prog-mode-syntax-table
174 "Syntax table used when pairing inside comments and strings.
176 `electric-pair-mode' considers this syntax table only when point in inside
177 quotes or comments. If lookup fails here, `electric-pair-text-pairs' will
178 be considered.")
180 (defun electric-pair-conservative-inhibit (char)
182 ;; I find it more often preferable not to pair when the
183 ;; same char is next.
184 (eq char (char-after))
185 ;; Don't pair up when we insert the second of "" or of ((.
186 (and (eq char (char-before))
187 (eq char (char-before (1- (point)))))
188 ;; I also find it often preferable not to pair next to a word.
189 (eq (char-syntax (following-char)) ?w)))
191 (defun electric-pair-syntax-info (command-event)
192 "Calculate a list (SYNTAX PAIR UNCONDITIONAL STRING-OR-COMMENT-START).
194 SYNTAX is COMMAND-EVENT's syntax character. PAIR is
195 COMMAND-EVENT's pair. UNCONDITIONAL indicates the variables
196 `electric-pair-pairs' or `electric-pair-text-pairs' were used to
197 lookup syntax. STRING-OR-COMMENT-START indicates that point is
198 inside a comment or string."
199 (let* ((pre-string-or-comment (or (bobp)
200 (nth 8 (save-excursion
201 (syntax-ppss (1- (point)))))))
202 (post-string-or-comment (nth 8 (syntax-ppss (point))))
203 (string-or-comment (and post-string-or-comment
204 pre-string-or-comment))
205 (table (if string-or-comment
206 electric-pair-text-syntax-table
207 (syntax-table)))
208 (table-syntax-and-pair (with-syntax-table table
209 (list (char-syntax command-event)
210 (or (matching-paren command-event)
211 command-event))))
212 (fallback (if string-or-comment
213 (append electric-pair-text-pairs
214 electric-pair-pairs)
215 electric-pair-pairs))
216 (direct (assq command-event fallback))
217 (reverse (rassq command-event fallback)))
218 (cond
219 ((memq (car table-syntax-and-pair)
220 '(?\" ?\( ?\) ?\$))
221 (append table-syntax-and-pair (list nil string-or-comment)))
222 (direct (if (eq (car direct) (cdr direct))
223 (list ?\" command-event t string-or-comment)
224 (list ?\( (cdr direct) t string-or-comment)))
225 (reverse (list ?\) (car reverse) t string-or-comment)))))
227 (defun electric-pair--insert (char)
228 (let ((last-command-event char)
229 (blink-matching-paren nil)
230 (electric-pair-mode nil))
231 (self-insert-command 1)))
233 (cl-defmacro electric-pair--with-uncached-syntax ((table &optional start) &rest body)
234 "Like `with-syntax-table', but flush the syntax-ppss cache afterwards.
235 Use this instead of (with-syntax-table TABLE BODY) when BODY
236 contains code which may update the syntax-ppss cache. This
237 includes calling `parse-partial-sexp' and any sexp-based movement
238 functions when `parse-sexp-lookup-properties' is non-nil. The
239 cache is flushed from position START, defaulting to point."
240 (declare (debug ((form &optional form) body)) (indent 1))
241 (let ((start-var (make-symbol "start")))
242 `(let ((syntax-propertize-function nil)
243 (,start-var ,(or start '(point))))
244 (unwind-protect
245 (with-syntax-table ,table
246 ,@body)
247 (syntax-ppss-flush-cache ,start-var)))))
249 (defun electric-pair--syntax-ppss (&optional pos where)
250 "Like `syntax-ppss', but sometimes fallback to `parse-partial-sexp'.
252 WHERE is a list defaulting to '(string comment) and indicates
253 when to fallback to `parse-partial-sexp'."
254 (let* ((pos (or pos (point)))
255 (where (or where '(string comment)))
256 (quick-ppss (syntax-ppss pos))
257 (in-string (and (nth 3 quick-ppss) (memq 'string where)))
258 (in-comment (and (nth 4 quick-ppss) (memq 'comment where)))
259 (s-or-c-start (cond (in-string
260 (1+ (nth 8 quick-ppss)))
261 (in-comment
262 (goto-char (nth 8 quick-ppss))
263 (forward-comment (- (point-max)))
264 (skip-syntax-forward " >!")
265 (point)))))
266 (if s-or-c-start
267 (electric-pair--with-uncached-syntax (electric-pair-text-syntax-table
268 s-or-c-start)
269 (parse-partial-sexp s-or-c-start pos))
270 ;; HACK! cc-mode apparently has some `syntax-ppss' bugs
271 (if (memq major-mode '(c-mode c++ mode))
272 (parse-partial-sexp (point-min) pos)
273 quick-ppss))))
275 ;; Balancing means controlling pairing and skipping of parentheses
276 ;; so that, if possible, the buffer ends up at least as balanced as
277 ;; before, if not more. The algorithm is slightly complex because
278 ;; some situations like "()))" need pairing to occur at the end but
279 ;; not at the beginning. Balancing should also happen independently
280 ;; for different types of parentheses, so that having your {}'s
281 ;; unbalanced doesn't keep `electric-pair-mode' from balancing your
282 ;; ()'s and your []'s.
283 (defun electric-pair--balance-info (direction string-or-comment)
284 "Examine lists forward or backward according to DIRECTION's sign.
286 STRING-OR-COMMENT is info suitable for running `parse-partial-sexp'.
288 Return a cons of two descriptions (MATCHED-P . PAIR) for the
289 innermost and outermost lists that enclose point. The outermost
290 list enclosing point is either the first top-level or first
291 mismatched list found by listing up.
293 If the outermost list is matched, don't rely on its PAIR.
294 If point is not enclosed by any lists, return ((t) . (t))."
295 (let* (innermost
296 outermost
297 (table (if string-or-comment
298 electric-pair-text-syntax-table
299 (syntax-table)))
300 (at-top-level-or-equivalent-fn
301 ;; called when `scan-sexps' ran perfectly, when it found
302 ;; a parenthesis pointing in the direction of travel.
303 ;; Also when travel started inside a comment and exited it.
304 #'(lambda ()
305 (setq outermost (list t))
306 (unless innermost
307 (setq innermost (list t)))))
308 (ended-prematurely-fn
309 ;; called when `scan-sexps' crashed against a parenthesis
310 ;; pointing opposite the direction of travel. After
311 ;; traversing that character, the idea is to travel one sexp
312 ;; in the opposite direction looking for a matching
313 ;; delimiter.
314 #'(lambda ()
315 (let* ((pos (point))
316 (matched
317 (save-excursion
318 (cond ((< direction 0)
319 (condition-case nil
320 (eq (char-after pos)
321 (electric-pair--with-uncached-syntax
322 (table)
323 (matching-paren
324 (char-before
325 (scan-sexps (point) 1)))))
326 (scan-error nil)))
328 ;; In this case, no need to use
329 ;; `scan-sexps', we can use some
330 ;; `electric-pair--syntax-ppss' in this
331 ;; case (which uses the quicker
332 ;; `syntax-ppss' in some cases)
333 (let* ((ppss (electric-pair--syntax-ppss
334 (1- (point))))
335 (start (car (last (nth 9 ppss))))
336 (opener (char-after start)))
337 (and start
338 (eq (char-before pos)
339 (or (with-syntax-table table
340 (matching-paren opener))
341 opener))))))))
342 (actual-pair (if (> direction 0)
343 (char-before (point))
344 (char-after (point)))))
345 (unless innermost
346 (setq innermost (cons matched actual-pair)))
347 (unless matched
348 (setq outermost (cons matched actual-pair)))))))
349 (save-excursion
350 (while (not outermost)
351 (condition-case err
352 (electric-pair--with-uncached-syntax (table)
353 (scan-sexps (point) (if (> direction 0)
354 (point-max)
355 (- (point-max))))
356 (funcall at-top-level-or-equivalent-fn))
357 (scan-error
358 (cond ((or
359 ;; some error happened and it is not of the "ended
360 ;; prematurely" kind...
361 (not (string-match "ends prematurely" (nth 1 err)))
362 ;; ... or we were in a comment and just came out of
363 ;; it.
364 (and string-or-comment
365 (not (nth 8 (syntax-ppss)))))
366 (funcall at-top-level-or-equivalent-fn))
368 ;; exit the sexp
369 (goto-char (nth 3 err))
370 (funcall ended-prematurely-fn)))))))
371 (cons innermost outermost)))
373 (defvar electric-pair-string-bound-function 'point-max
374 "Next buffer position where strings are syntactically unexpected.
375 Value is a function called with no arguments and returning a
376 buffer position. Major modes should set this variable
377 buffer-locally if they experience slowness with
378 `electric-pair-mode' when pairing quotes.")
380 (defun electric-pair--unbalanced-strings-p (char)
381 "Return non-nil if there are unbalanced strings started by CHAR."
382 (let* ((selector-ppss (syntax-ppss))
383 (relevant-ppss (save-excursion
384 (if (nth 4 selector-ppss) ; comment
385 (electric-pair--syntax-ppss
386 (progn
387 (goto-char (nth 8 selector-ppss))
388 (forward-comment (point-max))
389 (skip-syntax-backward " >!")
390 (point)))
391 (syntax-ppss
392 (funcall electric-pair-string-bound-function)))))
393 (string-delim (nth 3 relevant-ppss)))
394 (or (eq t string-delim)
395 (eq char string-delim))))
397 (defun electric-pair--inside-string-p (char)
398 "Return non-nil if point is inside a string started by CHAR.
400 A comments text is parsed with `electric-pair-text-syntax-table'.
401 Also consider strings within comments, but not strings within
402 strings."
403 ;; FIXME: could also consider strings within strings by examining
404 ;; delimiters.
405 (let ((ppss (electric-pair--syntax-ppss (point) '(comment))))
406 (memq (nth 3 ppss) (list t char))))
408 (defun electric-pair-inhibit-if-helps-balance (char)
409 "Return non-nil if auto-pairing of CHAR would hurt parentheses' balance.
411 Works by first removing the character from the buffer, then doing
412 some list calculations, finally restoring the situation as if nothing
413 happened."
414 (pcase (electric-pair-syntax-info char)
415 (`(,syntax ,pair ,_ ,s-or-c)
416 (unwind-protect
417 (progn
418 (delete-char -1)
419 (cond ((eq ?\( syntax)
420 (let* ((pair-data
421 (electric-pair--balance-info 1 s-or-c))
422 (outermost (cdr pair-data)))
423 (cond ((car outermost)
424 nil)
426 (eq (cdr outermost) pair)))))
427 ((eq syntax ?\")
428 (electric-pair--unbalanced-strings-p char))))
429 (insert-char char)))))
431 (defun electric-pair-skip-if-helps-balance (char)
432 "Return non-nil if skipping CHAR would benefit parentheses' balance.
434 Works by first removing the character from the buffer, then doing
435 some list calculations, finally restoring the situation as if nothing
436 happened."
437 (pcase (electric-pair-syntax-info char)
438 (`(,syntax ,pair ,_ ,s-or-c)
439 (unwind-protect
440 (progn
441 (delete-char -1)
442 (cond ((eq syntax ?\))
443 (let* ((pair-data
444 (electric-pair--balance-info
445 -1 s-or-c))
446 (innermost (car pair-data))
447 (outermost (cdr pair-data)))
448 (and
449 (cond ((car outermost)
450 (car innermost))
451 ((car innermost)
452 (not (eq (cdr outermost) pair)))))))
453 ((eq syntax ?\")
454 (electric-pair--inside-string-p char))))
455 (insert-char char)))))
457 (defun electric-pair-default-skip-self (char)
458 (if electric-pair-preserve-balance
459 (electric-pair-skip-if-helps-balance char)
462 (defun electric-pair-default-inhibit (char)
463 (if electric-pair-preserve-balance
464 (electric-pair-inhibit-if-helps-balance char)
465 (electric-pair-conservative-inhibit char)))
467 (defun electric-pair-post-self-insert-function ()
468 (let* ((pos (and electric-pair-mode (electric--after-char-pos)))
469 (skip-whitespace-info))
470 (pcase (electric-pair-syntax-info last-command-event)
471 (`(,syntax ,pair ,unconditional ,_)
472 (cond
473 ((null pos) nil)
474 ;; Wrap a pair around the active region.
476 ((and (memq syntax '(?\( ?\) ?\" ?\$)) (use-region-p))
477 ;; FIXME: To do this right, we'd need a post-self-insert-function
478 ;; so we could add-function around it and insert the closer after
479 ;; all the rest of the hook has run.
480 (if (or (eq syntax ?\")
481 (and (eq syntax ?\))
482 (>= (point) (mark)))
483 (and (not (eq syntax ?\)))
484 (>= (mark) (point))))
485 (save-excursion
486 (goto-char (mark))
487 (electric-pair--insert pair))
488 (delete-region pos (1- pos))
489 (electric-pair--insert pair)
490 (goto-char (mark))
491 (electric-pair--insert last-command-event)))
492 ;; Backslash-escaped: no pairing, no skipping.
493 ((save-excursion
494 (goto-char (1- pos))
495 (not (zerop (% (skip-syntax-backward "\\") 2))))
496 nil)
497 ;; Skip self.
498 ((and (memq syntax '(?\) ?\" ?\$))
499 (and (or unconditional
500 (if (functionp electric-pair-skip-self)
501 (funcall electric-pair-skip-self last-command-event)
502 electric-pair-skip-self))
503 (save-excursion
504 (when (and (not (and unconditional
505 (eq syntax ?\")))
506 (setq skip-whitespace-info
507 (if (and (not (eq electric-pair-skip-whitespace 'chomp))
508 (functionp electric-pair-skip-whitespace))
509 (funcall electric-pair-skip-whitespace)
510 electric-pair-skip-whitespace)))
511 (funcall electric-pair-skip-whitespace-function))
512 (eq (char-after) last-command-event))))
513 ;; This is too late: rather than insert&delete we'd want to only
514 ;; skip (or insert in overwrite mode). The difference is in what
515 ;; goes in the undo-log and in the intermediate state which might
516 ;; be visible to other post-self-insert-hook. We'll just have to
517 ;; live with it for now.
518 (when skip-whitespace-info
519 (funcall electric-pair-skip-whitespace-function))
520 (delete-region (1- pos) (if (eq skip-whitespace-info 'chomp)
521 (point)
522 pos))
523 (forward-char))
524 ;; Insert matching pair.
525 ((and (memq syntax `(?\( ?\" ?\$))
526 (not overwrite-mode)
527 (or unconditional
528 (not (funcall electric-pair-inhibit-predicate
529 last-command-event))))
530 (save-excursion (electric-pair--insert pair)))))
532 (when (and (if (functionp electric-pair-open-newline-between-pairs)
533 (funcall electric-pair-open-newline-between-pairs)
534 electric-pair-open-newline-between-pairs)
535 (eq last-command-event ?\n)
536 (< (1+ (point-min)) (point) (point-max))
537 (eq (save-excursion
538 (skip-chars-backward "\t\s")
539 (char-before (1- (point))))
540 (matching-paren (char-after))))
541 (save-excursion (newline 1 t)))))))
543 (put 'electric-pair-post-self-insert-function 'priority 20)
545 (defun electric-pair-will-use-region ()
546 (and (use-region-p)
547 (memq (car (electric-pair-syntax-info last-command-event))
548 '(?\( ?\) ?\" ?\$))))
550 (defun electric-pair-delete-pair (arg &optional killp)
551 "When between adjacent paired delimiters, delete both of them.
552 ARG and KILLP are passed directly to
553 `backward-delete-char-untabify', which see."
554 (interactive "*p\nP")
555 (delete-char 1)
556 (backward-delete-char-untabify arg killp))
558 (defvar electric-pair-mode-map
559 (let ((map (make-sparse-keymap)))
560 (define-key map "\177"
561 `(menu-item
562 "" electric-pair-delete-pair
563 :filter
564 ,(lambda (cmd)
565 (let* ((prev (char-before))
566 (next (char-after))
567 (syntax-info (and prev
568 (electric-pair-syntax-info prev)))
569 (syntax (car syntax-info))
570 (pair (cadr syntax-info)))
571 (and next pair
572 (memq syntax '(?\( ?\" ?\$))
573 (eq pair next)
574 (if (functionp electric-pair-delete-adjacent-pairs)
575 (funcall electric-pair-delete-adjacent-pairs)
576 electric-pair-delete-adjacent-pairs)
577 cmd)))))
578 map)
579 "Keymap used by `electric-pair-mode'.")
581 ;;;###autoload
582 (define-minor-mode electric-pair-mode
583 "Toggle automatic parens pairing (Electric Pair mode).
585 Electric Pair mode is a global minor mode. When enabled, typing
586 an open parenthesis automatically inserts the corresponding
587 closing parenthesis, and vice versa. (Likewise for brackets, etc.).
588 If the region is active, the parentheses (brackets, etc.) are
589 inserted around the region instead.
591 To toggle the mode in a single buffer, use `electric-pair-local-mode'."
592 :global t :group 'electricity
593 (if electric-pair-mode
594 (progn
595 (add-hook 'post-self-insert-hook
596 #'electric-pair-post-self-insert-function)
597 (electric--sort-post-self-insertion-hook)
598 (add-hook 'self-insert-uses-region-functions
599 #'electric-pair-will-use-region))
600 (remove-hook 'post-self-insert-hook
601 #'electric-pair-post-self-insert-function)
602 (remove-hook 'self-insert-uses-region-functions
603 #'electric-pair-will-use-region)))
605 ;;;###autoload
606 (define-minor-mode electric-pair-local-mode
607 "Toggle `electric-pair-mode' only in this buffer."
608 :variable (buffer-local-value 'electric-pair-mode (current-buffer))
609 (cond
610 ((eq electric-pair-mode (default-value 'electric-pair-mode))
611 (kill-local-variable 'electric-pair-mode))
612 ((not (default-value 'electric-pair-mode))
613 ;; Locally enabled, but globally disabled.
614 (electric-pair-mode 1) ; Setup the hooks.
615 (setq-default electric-pair-mode nil) ; But keep it globally disabled.
618 (provide 'elec-pair)
620 ;;; elec-pair.el ends here