1 ;;; electric.el --- window maker and Command loop for `electric' modes
3 ;; Copyright (C) 1985-1986, 1995, 2001-2013 Free Software Foundation,
6 ;; Author: K. Shane Hartman
8 ;; Keywords: extensions
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; "Electric" has been used in Emacs to refer to different things.
30 ;; - electric modes and buffers: modes that typically pop-up in a modal kind of
31 ;; way a transient buffer that automatically disappears as soon as the user
34 ;; - electric keys: self inserting keys which additionally perform some side
35 ;; operation which happens to be often convenient at that time. Examples of
36 ;; such side operations are: reindenting code, inserting a newline,
37 ;; ... auto-fill-mode and abbrev-mode can be considered as built-in forms of
38 ;; electric key behavior.
42 ;; This loop is the guts for non-standard modes which retain control
43 ;; until some event occurs. It is a `do-forever', the only way out is
44 ;; to throw. It assumes that you have set up the keymap, window, and
45 ;; everything else: all it does is read commands and execute them -
46 ;; providing error messages should one occur (if there is no loop
47 ;; function - which see). The required argument is a tag which should
48 ;; expect a value of nil if the user decides to punt. The second
49 ;; argument is the prompt to be used: if nil, use "->", if 'noprompt,
50 ;; don't use a prompt, if a string, use that string as prompt, and if
51 ;; a function of no variable, it will be evaluated in every iteration
52 ;; of the loop and its return value, which can be nil, 'noprompt or a
53 ;; string, will be used as prompt. Given third argument non-nil, it
54 ;; INHIBITS quitting unless the user types C-g at toplevel. This is
55 ;; so user can do things like C-u C-g and not get thrown out. Fourth
56 ;; argument, if non-nil, should be a function of two arguments which
57 ;; is called after every command is executed. The fifth argument, if
58 ;; provided, is the state variable for the function. If the
59 ;; loop-function gets an error, the loop will abort WITHOUT throwing
60 ;; (moral: use unwind-protect around call to this function for any
61 ;; critical stuff). The second argument for the loop function is the
62 ;; conditions for any error that occurred or nil if none.
64 (defun Electric-command-loop (return-tag
65 &optional prompt inhibit-quitting
66 loop-function loop-state
)
70 (inhibit-quit inhibit-quitting
)
71 (prompt-string prompt
))
73 (if (functionp prompt
)
74 (setq prompt-string
(funcall prompt
)))
75 (if (not (stringp prompt-string
))
76 (setq prompt-string
(unless (eq prompt-string
'noprompt
) "->")))
77 (setq cmd
(read-key-sequence prompt-string
))
78 (setq last-command-event
(aref cmd
(1- (length cmd
)))
79 this-command
(key-binding cmd t
)
81 (if (or (prog1 quit-flag
(setq quit-flag nil
))
82 (eq last-input-event ?\C-g
))
83 (progn (setq unread-command-events nil
85 ;; If it wasn't canceling a prefix character, then quit.
86 (if (or (= (length (this-command-keys)) 1)
87 (not inhibit-quit
)) ; safety
90 (throw return-tag nil
))
92 (setq current-prefix-arg prefix-arg
)
94 (condition-case conditions
95 (progn (command-execute cmd
)
96 (setq last-command this-command
)
97 (if (or (prog1 quit-flag
(setq quit-flag nil
))
98 (eq last-input-event ?\C-g
))
99 (progn (setq unread-command-events nil
)
100 (if (not inhibit-quit
)
103 (throw return-tag nil
))
105 (buffer-read-only (if loop-function
106 (setq err conditions
)
108 (message "Buffer is read-only")
110 (beginning-of-buffer (if loop-function
111 (setq err conditions
)
113 (message "Beginning of Buffer")
115 (end-of-buffer (if loop-function
116 (setq err conditions
)
118 (message "End of Buffer")
120 (error (if loop-function
121 (setq err conditions
)
124 (if (eq (car conditions
) 'error
)
125 (car (cdr conditions
))
126 (prin1-to-string conditions
)))
129 (if loop-function
(funcall loop-function loop-state err
))))
131 (throw return-tag nil
))
133 ;; This function is like pop-to-buffer, sort of.
135 ;; If there is a window displaying buffer
137 ;; Else if there is only one window
138 ;; Split it, selecting the window on the bottom with height being
139 ;; the lesser of max-height (if non-nil) and the number of lines in
140 ;; the buffer to be displayed subject to window-min-height constraint.
142 ;; Switch to buffer in the current window.
144 ;; Then if max-height is nil, and not all of the lines in the buffer
145 ;; are displayed, grab the whole frame.
147 ;; Returns selected window on buffer positioned at point-min.
149 (defun Electric-pop-up-window (buffer &optional max-height
)
150 (let* ((win (or (get-buffer-window buffer
) (selected-window)))
151 (buf (get-buffer buffer
))
152 (one-window (one-window-p t
))
156 (error "Buffer %s does not exist" buffer
)
157 (cond ((and (eq (window-buffer win
) buf
))
160 (pop-to-buffer buffer
)
161 (setq win
(selected-window)))
163 (switch-to-buffer buf
)))
164 ;; Don't shrink the window, but expand it if necessary.
165 (goto-char (point-min))
166 (unless (= (point-max) (window-end win t
))
167 (fit-window-to-buffer win max-height
))
172 (defgroup electricity
()
173 "Electric behavior for self inserting keys."
176 (defun electric--after-char-pos ()
177 "Return the position after the char we just inserted.
178 Returns nil when we can't find this char."
180 (when (or (eq (char-before) last-command-event
) ;; Sanity check.
182 (or (progn (skip-chars-backward " \t")
184 (eq (char-before) last-command-event
))
185 (progn (skip-chars-backward " \n\t")
187 (eq (char-before) last-command-event
)))))
190 (defun electric--sort-post-self-insertion-hook ()
191 "Ensure order of electric functions in `post-self-insertion-hook'.
193 Hooks in this variable interact in non-trivial ways, so a
194 relative order must be maintained within it."
195 (setq-default post-self-insert-hook
196 (sort (default-value 'post-self-insert-hook
)
198 (< (or (get fn1
'priority
) 0)
199 (or (get fn2
'priority
) 0))))))
201 ;;; Electric indentation.
203 ;; Autoloading variables is generally undesirable, but major modes
204 ;; should usually set this variable by adding elements to the default
205 ;; value, which only works well if the variable is preloaded.
207 (defvar electric-indent-chars
'(?
\n)
208 "Characters that should cause automatic reindentation.")
210 (defvar electric-indent-functions nil
211 "Special hook run to decide whether to auto-indent.
212 Each function is called with one argument (the inserted char), with
213 point right after that char, and it should return t to cause indentation,
214 `no-indent' to prevent indentation or nil to let other functions decide.")
216 (defvar-local electric-indent-inhibit nil
217 "If non-nil, reindentation is not appropriate for this buffer.
218 This should be set by major modes such as `python-mode' since
219 Python does not lend itself to fully automatic indentation.")
221 (defvar electric-indent-functions-without-reindent
222 '(indent-relative indent-to-left-margin indent-relative-maybe
223 py-indent-line coffee-indent-line org-indent-line
224 haskell-indentation-indent-line haskell-indent-cycle haskell-simple-indent
)
225 "List of indent functions that can't reindent.
226 If `line-indent-function' is one of those, then `electric-indent-mode' will
227 not try to reindent lines. It is normally better to make the major
228 mode set `electric-indent-inhibit', but this can be used as a workaround.")
230 (defun electric-indent-post-self-insert-function ()
231 ;; FIXME: This reindents the current line, but what we really want instead is
232 ;; to reindent the whole affected text. That's the current line for simple
233 ;; cases, but not all cases. We do take care of the newline case in an
234 ;; ad-hoc fashion, but there are still missing cases such as the case of
235 ;; electric-pair-mode wrapping a region with a pair of parens.
236 ;; There might be a way to get it working by analyzing buffer-undo-list, but
237 ;; it looks challenging.
241 ;; Don't reindent while inserting spaces at beginning of line.
242 (or (not (memq last-command-event
'(?\s ?
\t)))
243 (save-excursion (skip-chars-backward " \t") (not (bolp))))
244 (setq pos
(electric--after-char-pos))
247 (let ((act (or (run-hook-with-args-until-success
248 'electric-indent-functions
250 (memq last-command-event electric-indent-chars
))))
252 (or (memq act
'(nil no-indent
))
253 ;; In a string or comment.
254 (unless (eq act
'do-indent
) (nth 8 (syntax-ppss))))))))
255 ;; For newline, we want to reindent both lines and basically behave like
256 ;; reindent-then-newline-and-indent (whose code we hence copied).
257 (when (<= pos
(line-beginning-position))
258 (let ((before (copy-marker (1- pos
) t
)))
260 (unless (or (memq indent-line-function
261 electric-indent-functions-without-reindent
)
262 electric-indent-inhibit
)
263 ;; Don't reindent the previous line if the indentation function
264 ;; is not a real one.
266 (indent-according-to-mode))
267 ;; We are at EOL before the call to indent-according-to-mode, and
268 ;; after it we usually are as well, but not always. We tried to
269 ;; address it with `save-excursion' but that uses a normal marker
270 ;; whereas we need `move after insertion', so we do the
271 ;; save/restore by hand.
274 ;; Remove the trailing whitespace after indentation because
275 ;; indentation may (re)introduce the whitespace.
276 (delete-horizontal-space t
)))))
277 (unless (and electric-indent-inhibit
278 (> pos
(line-beginning-position)))
279 (indent-according-to-mode)))))
281 (put 'electric-indent-post-self-insert-function
'priority
60)
283 (defun electric-indent-just-newline (arg)
284 "Insert just a newline, without any auto-indentation."
286 (let ((electric-indent-mode nil
))
287 (newline arg
'interactive
)))
290 (define-minor-mode electric-indent-mode
291 "Toggle on-the-fly reindentation (Electric Indent mode).
292 With a prefix argument ARG, enable Electric Indent mode if ARG is
293 positive, and disable it otherwise. If called from Lisp, enable
294 the mode if ARG is omitted or nil.
296 This is a global minor mode. When enabled, it reindents whenever
297 the hook `electric-indent-functions' returns non-nil, or you
298 insert a character from `electric-indent-chars'."
299 :global t
:group
'electricity
300 :initialize
'custom-initialize-delay
302 (if (not electric-indent-mode
)
304 (when (eq (lookup-key global-map
[?\C-j
])
305 'electric-indent-just-newline
)
306 (define-key global-map
[?\C-j
] 'newline-and-indent
))
307 (remove-hook 'post-self-insert-hook
308 #'electric-indent-post-self-insert-function
))
309 (when (eq (lookup-key global-map
[?\C-j
]) 'newline-and-indent
)
310 (define-key global-map
[?\C-j
] 'electric-indent-just-newline
))
311 (add-hook 'post-self-insert-hook
312 #'electric-indent-post-self-insert-function
)
313 (electric--sort-post-self-insertion-hook)))
316 (define-minor-mode electric-indent-local-mode
317 "Toggle `electric-indent-mode' only in this buffer."
318 :variable
(buffer-local-value 'electric-indent-mode
(current-buffer))
320 ((eq electric-indent-mode
(default-value 'electric-indent-mode
))
321 (kill-local-variable 'electric-indent-mode
))
322 ((not (default-value 'electric-indent-mode
))
323 ;; Locally enabled, but globally disabled.
324 (electric-indent-mode 1) ; Setup the hooks.
325 (setq-default electric-indent-mode nil
) ; But keep it globally disabled.
328 ;;; Electric pairing.
330 (defcustom electric-pair-pairs
332 "Alist of pairs that should be used regardless of major mode.
334 Pairs of delimiters in this list are a fallback in case they have
335 no syntax relevant to `electric-pair-mode' in the mode's syntax
338 See also the variable `electric-pair-text-pairs'."
340 :type
'(repeat (cons character character
)))
342 (defcustom electric-pair-text-pairs
344 "Alist of pairs that should always be used in comments and strings.
346 Pairs of delimiters in this list are a fallback in case they have
347 no syntax relevant to `electric-pair-mode' in the syntax table
348 defined in `electric-pair-text-syntax-table'"
350 :type
'(repeat (cons character character
)))
352 (defcustom electric-pair-skip-self
#'electric-pair-default-skip-self
353 "If non-nil, skip char instead of inserting a second closing paren.
355 When inserting a closing paren character right before the same character,
356 just skip that character instead, so that hitting ( followed by ) results
357 in \"()\" rather than \"())\".
359 This can be convenient for people who find it easier to hit ) than C-f.
361 Can also be a function of one argument (the closer char just
362 inserted), in which case that function's return value is
366 (const :tag
"Never skip" nil
)
367 (const :tag
"Help balance" electric-pair-default-skip-self
)
368 (const :tag
"Always skip" t
)
371 (defcustom electric-pair-inhibit-predicate
372 #'electric-pair-default-inhibit
373 "Predicate to prevent insertion of a matching pair.
375 The function is called with a single char (the opening char just inserted).
376 If it returns non-nil, then `electric-pair-mode' will not insert a matching
380 (const :tag
"Conservative" electric-pair-conservative-inhibit
)
381 (const :tag
"Help balance" electric-pair-default-inhibit
)
382 (const :tag
"Always pair" ignore
)
385 (defcustom electric-pair-preserve-balance t
386 "Non-nil if default pairing and skipping should help balance parentheses.
388 The default values of `electric-pair-inhibit-predicate' and
389 `electric-pair-skip-self' check this variable before delegating to other
390 predicates reponsible for making decisions on whether to pair/skip some
391 characters based on the actual state of the buffer's parenthesis and
396 (defcustom electric-pair-delete-adjacent-pairs t
397 "If non-nil, backspacing an open paren also deletes adjacent closer.
399 Can also be a function of no arguments, in which case that function's
400 return value is considered instead."
404 (const :tag
"No" nil
)
407 (defcustom electric-pair-open-newline-between-pairs t
408 "If non-nil, a newline between adjacent parentheses opens an extra one.
410 Can also be a function of no arguments, in which case that function's
411 return value is considered instead."
415 (const :tag
"No" nil
)
418 (defcustom electric-pair-skip-whitespace t
419 "If non-nil skip whitespace when skipping over closing parens.
421 The specific kind of whitespace skipped is given by the variable
422 `electric-pair-skip-whitespace-chars'.
424 The symbol `chomp' specifies that the skipped-over whitespace
427 Can also be a function of no arguments, in which case that function's
428 return value is considered instead."
431 (const :tag
"Yes, jump over whitespace" t
)
432 (const :tag
"Yes, and delete whitespace" 'chomp
)
433 (const :tag
"No, no whitespace skipping" nil
)
436 (defcustom electric-pair-skip-whitespace-chars
(list ?
\t ?\s ?
\n)
437 "Whitespace characters considered by `electric-pair-skip-whitespace'."
439 :type
'(choice (set (const :tag
"Space" ?\s
)
440 (const :tag
"Tab" ?
\t)
441 (const :tag
"Newline" ?
\n))
444 (defun electric-pair--skip-whitespace ()
445 "Skip whitespace forward, not crossing comment or string boundaries."
446 (let ((saved (point))
447 (string-or-comment (nth 8 (syntax-ppss))))
448 (skip-chars-forward (apply #'string electric-pair-skip-whitespace-chars
))
449 (unless (eq string-or-comment
(nth 8 (syntax-ppss)))
452 (defvar electric-pair-text-syntax-table prog-mode-syntax-table
453 "Syntax table used when pairing inside comments and strings.
455 `electric-pair-mode' considers this syntax table only when point in inside
456 quotes or comments. If lookup fails here, `electric-pair-text-pairs' will
459 (defun electric-pair-backward-delete-char (n &optional killflag untabify
)
460 "Delete characters backward, and maybe also two adjacent paired delimiters.
462 Remaining behaviour is given by `backward-delete-char' or, if UNTABIFY is
463 non-nil, `backward-delete-char-untabify'."
464 (interactive "*p\nP")
465 (let* ((prev (char-before))
467 (syntax-info (electric-pair-syntax-info prev
))
468 (syntax (car syntax-info
))
469 (pair (cadr syntax-info
)))
470 (when (and (if (functionp electric-pair-delete-adjacent-pairs
)
471 (funcall electric-pair-delete-adjacent-pairs
)
472 electric-pair-delete-adjacent-pairs
)
474 (memq syntax
'(?\
( ?
\" ?\$
))
476 (delete-char 1 killflag
))
478 (backward-delete-char-untabify n killflag
)
479 (backward-delete-char n killflag
))))
481 (defun electric-pair-backward-delete-char-untabify (n &optional killflag
)
482 "Delete characters backward, and maybe also two adjacent paired delimiters.
484 Remaining behaviour is given by `backward-delete-char-untabify'."
485 (interactive "*p\nP")
486 (electric-pair-backward-delete-char n killflag t
))
488 (defun electric-pair-conservative-inhibit (char)
490 ;; I find it more often preferable not to pair when the
491 ;; same char is next.
492 (eq char
(char-after))
493 ;; Don't pair up when we insert the second of "" or of ((.
494 (and (eq char
(char-before))
495 (eq char
(char-before (1- (point)))))
496 ;; I also find it often preferable not to pair next to a word.
497 (eq (char-syntax (following-char)) ?w
)))
499 (defun electric-pair-syntax-info (command-event)
500 "Calculate a list (SYNTAX PAIR UNCONDITIONAL STRING-OR-COMMENT-START).
502 SYNTAX is COMMAND-EVENT's syntax character. PAIR is
503 COMMAND-EVENT's pair. UNCONDITIONAL indicates the variables
504 `electric-pair-pairs' or `electric-pair-text-pairs' were used to
505 lookup syntax. STRING-OR-COMMENT-START indicates that point is
506 inside a comment of string."
507 (let* ((pre-string-or-comment (nth 8 (save-excursion
508 (syntax-ppss (1- (point))))))
509 (post-string-or-comment (nth 8 (syntax-ppss (point))))
510 (string-or-comment (and post-string-or-comment
511 pre-string-or-comment
))
512 (table (if string-or-comment
513 electric-pair-text-syntax-table
515 (table-syntax-and-pair (with-syntax-table table
516 (list (char-syntax command-event
)
517 (or (matching-paren command-event
)
519 (fallback (if string-or-comment
520 (append electric-pair-text-pairs
522 electric-pair-pairs
))
523 (direct (assq command-event fallback
))
524 (reverse (rassq command-event fallback
)))
526 ((memq (car table-syntax-and-pair
)
528 (append table-syntax-and-pair
(list nil string-or-comment
)))
529 (direct (if (eq (car direct
) (cdr direct
))
530 (list ?
\" command-event t string-or-comment
)
531 (list ?\
( (cdr direct
) t string-or-comment
)))
532 (reverse (list ?\
) (car reverse
) t string-or-comment
)))))
534 (defun electric-pair--insert (char)
535 (let ((last-command-event char
)
536 (blink-matching-paren nil
)
537 (electric-pair-mode nil
))
538 (self-insert-command 1)))
540 (defun electric-pair--syntax-ppss (&optional pos where
)
541 "Like `syntax-ppss', but sometimes fallback to `parse-partial-sexp'.
543 WHERE is list defaulting to '(string comment) and indicates
544 when to fallback to `parse-partial-sexp'."
545 (let* ((pos (or pos
(point)))
546 (where (or where
'(string comment
)))
547 (quick-ppss (syntax-ppss))
548 (quick-ppss-at-pos (syntax-ppss pos
)))
549 (if (or (and (nth 3 quick-ppss
) (memq 'string where
))
550 (and (nth 4 quick-ppss
) (memq 'comment where
)))
551 (with-syntax-table electric-pair-text-syntax-table
552 (parse-partial-sexp (1+ (nth 8 quick-ppss
)) pos
))
553 ;; HACK! cc-mode apparently has some `syntax-ppss' bugs
554 (if (memq major-mode
'(c-mode c
++ mode
))
555 (parse-partial-sexp (point-min) pos
)
556 quick-ppss-at-pos
))))
558 ;; Balancing means controlling pairing and skipping of parentheses so
559 ;; that, if possible, the buffer ends up at least as balanced as
560 ;; before, if not more. The algorithm is slightly complex because some
561 ;; situations like "()))" need pairing to occur at the end but not at
562 ;; the beginning. Balancing should also happen independently for
563 ;; different types of parentheses, so that having your {}'s unbalanced
564 ;; doesn't keep `electric-pair-mode' from balancing your ()'s and your
566 (defun electric-pair--balance-info (direction string-or-comment
)
567 "Examine lists forward or backward according to DIRECTIONS's sign.
569 STRING-OR-COMMENT is info suitable for running `parse-partial-sexp'.
571 Return a cons of two descritions (MATCHED-P . PAIR) for the
572 innermost and outermost lists that enclose point. The outermost
573 list enclosing point is either the first top-level or first
574 mismatched list found by uplisting.
576 If the outermost list is matched, don't rely on its PAIR. If
577 point is not enclosed by any lists, return ((T) (T))."
580 (table (if string-or-comment
581 electric-pair-text-syntax-table
583 (at-top-level-or-equivalent-fn
584 ;; called when `scan-sexps' ran perfectly, when when it
585 ;; found a parenthesis pointing in the direction of
586 ;; travel. Also when travel started inside a comment and
589 (setq outermost
(list t
))
591 (setq innermost
(list t
)))))
592 (ended-prematurely-fn
593 ;; called when `scan-sexps' crashed against a parenthesis
594 ;; pointing opposite the direction of travel. After
595 ;; traversing that character, the idea is to travel one sexp
596 ;; in the opposite direction looking for a matching
602 (cond ((< direction
0)
605 (with-syntax-table table
608 (scan-sexps (point) 1)))))
611 ;; In this case, no need to use
612 ;; `scan-sexps', we can use some
613 ;; `electric-pair--syntax-ppss' in this
614 ;; case (which uses the quicker
615 ;; `syntax-ppss' in some cases)
616 (let* ((ppss (electric-pair--syntax-ppss
618 (start (car (last (nth 9 ppss
))))
619 (opener (char-after start
)))
621 (eq (char-before pos
)
622 (or (with-syntax-table table
623 (matching-paren opener
))
625 (actual-pair (if (> direction
0)
626 (char-before (point))
627 (char-after (point)))))
629 (setq innermost
(cons matched actual-pair
)))
631 (setq outermost
(cons matched actual-pair
)))))))
633 (while (not outermost
)
635 (with-syntax-table table
636 (scan-sexps (point) (if (> direction
0)
639 (funcall at-top-level-or-equivalent-fn
))
642 ;; some error happened and it is not of the "ended
643 ;; prematurely" kind"...
644 (not (string-match "ends prematurely" (nth 1 err
)))
645 ;; ... or we were in a comment and just came out of
647 (and string-or-comment
648 (not (nth 8 (syntax-ppss)))))
649 (funcall at-top-level-or-equivalent-fn
))
652 (goto-char (nth 3 err
))
653 (funcall ended-prematurely-fn
)))))))
654 (cons innermost outermost
)))
656 (defun electric-pair--looking-at-unterminated-string-p (char)
657 "Say if following string starts with CHAR and is unterminated."
660 (skip-chars-forward (format "^%c" char
))
661 (while (not (zerop (%
(save-excursion (skip-syntax-backward "\\")) 2)))
664 (skip-chars-forward (format "^%c" char
))))
667 (progn (forward-sexp) nil
)
670 (defun electric-pair--inside-string-p (char)
671 "Say if point is inside a string started by CHAR.
673 A comments text is parsed with `electric-pair-text-syntax-table'.
674 Also consider strings within comments, but not strings within
676 ;; FIXME: could also consider strings within strings by examining
678 (let* ((ppss (electric-pair--syntax-ppss (point) '(comment))))
679 (memq (nth 3 ppss
) (list t char
))))
681 (defun electric-pair-inhibit-if-helps-balance (char)
682 "Return non-nil if auto-pairing of CHAR would hurt parentheses' balance.
684 Works by first removing the character from the buffer, then doing
685 some list calculations, finally restoring the situation as if nothing
687 (pcase (electric-pair-syntax-info char
)
688 (`(,syntax
,pair
,_
,s-or-c
)
692 (cond ((eq ?\
( syntax
)
694 (electric-pair--balance-info 1 s-or-c
))
695 (innermost (car pair-data
))
696 (outermost (cdr pair-data
)))
697 (cond ((car outermost
)
700 (eq (cdr outermost
) pair
)))))
702 (electric-pair--looking-at-unterminated-string-p char
))))
703 (insert-char char
)))))
705 (defun electric-pair-skip-if-helps-balance (char)
706 "Return non-nil if skipping CHAR would benefit parentheses' balance.
708 Works by first removing the character from the buffer, then doing
709 some list calculations, finally restoring the situation as if nothing
711 (pcase (electric-pair-syntax-info char
)
712 (`(,syntax
,pair
,_
,s-or-c
)
716 (cond ((eq syntax ?\
))
718 (electric-pair--balance-info
720 (innermost (car pair-data
))
721 (outermost (cdr pair-data
)))
723 (cond ((car outermost
)
726 (not (eq (cdr outermost
) pair
)))))))
728 (electric-pair--inside-string-p char
))))
729 (insert-char char
)))))
731 (defun electric-pair-default-skip-self (char)
732 (if electric-pair-preserve-balance
733 (electric-pair-skip-if-helps-balance char
)
736 (defun electric-pair-default-inhibit (char)
737 (if electric-pair-preserve-balance
738 (electric-pair-inhibit-if-helps-balance char
)
739 (electric-pair-conservative-inhibit char
)))
741 (defun electric-pair-post-self-insert-function ()
742 (let* ((pos (and electric-pair-mode
(electric--after-char-pos)))
743 (skip-whitespace-info))
744 (pcase (electric-pair-syntax-info last-command-event
)
745 (`(,syntax
,pair
,unconditional
,_
)
748 ;; Wrap a pair around the active region.
750 ((and (memq syntax
'(?\
( ?\
) ?
\" ?\$
)) (use-region-p))
751 ;; FIXME: To do this right, we'd need a post-self-insert-function
752 ;; so we could add-function around it and insert the closer after
753 ;; all the rest of the hook has run.
754 (if (or (eq syntax ?
\")
757 (and (not (eq syntax ?\
)))
758 (>= (mark) (point))))
761 (electric-pair--insert pair
))
762 (delete-region pos
(1- pos
))
763 (electric-pair--insert pair
)
765 (electric-pair--insert last-command-event
)))
766 ;; Backslash-escaped: no pairing, no skipping.
769 (not (zerop (%
(skip-syntax-backward "\\") 2))))
772 ((and (memq syntax
'(?\
) ?
\" ?\$
))
773 (and (or unconditional
774 (if (functionp electric-pair-skip-self
)
775 (funcall electric-pair-skip-self last-command-event
)
776 electric-pair-skip-self
))
778 (when (setq skip-whitespace-info
779 (if (functionp electric-pair-skip-whitespace
)
780 (funcall electric-pair-skip-whitespace
)
781 electric-pair-skip-whitespace
))
782 (electric-pair--skip-whitespace))
783 (eq (char-after) last-command-event
))))
784 ;; This is too late: rather than insert&delete we'd want to only
785 ;; skip (or insert in overwrite mode). The difference is in what
786 ;; goes in the undo-log and in the intermediate state which might
787 ;; be visible to other post-self-insert-hook. We'll just have to
788 ;; live with it for now.
789 (when skip-whitespace-info
790 (electric-pair--skip-whitespace))
791 (delete-region (1- pos
) (if (eq skip-whitespace-info
'chomp
)
795 ;; Insert matching pair.
796 ((and (memq syntax
`(?\
( ?
\" ?\$
))
799 (not (funcall electric-pair-inhibit-predicate
800 last-command-event
))))
801 (save-excursion (electric-pair--insert pair
)))))
803 (when (and (if (functionp electric-pair-open-newline-between-pairs
)
804 (funcall electric-pair-open-newline-between-pairs
)
805 electric-pair-open-newline-between-pairs
)
806 (eq last-command-event ?
\n)
809 (skip-chars-backward "\t\s")
810 (char-before (1- (point))))
811 (matching-paren (char-after))))
812 (save-excursion (newline 1 t
)))))))
814 (put 'electric-pair-post-self-insert-function
'priority
20)
816 (defun electric-pair-will-use-region ()
818 (memq (car (electric-pair-syntax-info last-command-event
))
819 '(?\
( ?\
) ?
\" ?\$
))))
821 (defvar electric-pair-mode-map
822 (let ((map (make-sparse-keymap)))
823 (define-key map
[remap backward-delete-char-untabify
]
824 'electric-pair-backward-delete-char-untabify
)
825 (define-key map
[remap backward-delete-char
]
826 'electric-pair-backward-delete-char
)
827 (define-key map
[remap delete-backward-char
]
828 'electric-pair-backward-delete-char
)
830 "Keymap used by `electric-pair-mode'.")
833 (define-minor-mode electric-pair-mode
834 "Toggle automatic parens pairing (Electric Pair mode).
835 With a prefix argument ARG, enable Electric Pair mode if ARG is
836 positive, and disable it otherwise. If called from Lisp, enable
837 the mode if ARG is omitted or nil.
839 Electric Pair mode is a global minor mode. When enabled, typing
840 an open parenthesis automatically inserts the corresponding
841 closing parenthesis. \(Likewise for brackets, etc.)."
842 :global t
:group
'electricity
843 (if electric-pair-mode
845 (add-hook 'post-self-insert-hook
846 #'electric-pair-post-self-insert-function
)
847 (electric--sort-post-self-insertion-hook)
848 (add-hook 'self-insert-uses-region-functions
849 #'electric-pair-will-use-region
))
850 (remove-hook 'post-self-insert-hook
851 #'electric-pair-post-self-insert-function
)
852 (remove-hook 'self-insert-uses-region-functions
853 #'electric-pair-will-use-region
)))
855 ;;; Electric newlines after/before/around some chars.
857 (defvar electric-layout-rules nil
858 "List of rules saying where to automatically insert newlines.
860 Each rule has the form (CHAR . WHERE) where CHAR is the char that
861 was just inserted and WHERE specifies where to insert newlines
862 and can be: nil, `before', `after', `around', `after-stay', or a
863 function of no arguments that returns one of those symbols.
865 The symbols specify where in relation to CHAR the newline
866 character(s) should be inserted. `after-stay' means insert a
867 newline after CHAR but stay in the same place.")
869 (defun electric-layout-post-self-insert-function ()
870 (let* ((rule (cdr (assq last-command-event electric-layout-rules
)))
873 (setq pos
(electric--after-char-pos))
874 ;; Not in a string or comment.
875 (not (nth 8 (save-excursion (syntax-ppss pos
)))))
876 (let ((end (copy-marker (point)))
877 (sym (if (functionp rule
) (funcall rule
) rule
)))
878 (set-marker-insertion-type end
(not (eq sym
'after-stay
)))
881 ;; FIXME: we used `newline' down here which called
882 ;; self-insert-command and ran post-self-insert-hook recursively.
883 ;; It happened to make electric-indent-mode work automatically with
884 ;; electric-layout-mode (at the cost of re-indenting lines
885 ;; multiple times), but I'm not sure it's what we want.
887 ;; FIXME: check eolp before inserting \n?
888 (`before
(goto-char (1- pos
)) (skip-chars-backward " \t")
889 (unless (bolp) (insert "\n")))
890 (`after
(insert "\n"))
891 (`after-stay
(save-excursion
892 (let ((electric-layout-rules nil
))
894 (`around
(save-excursion
895 (goto-char (1- pos
)) (skip-chars-backward " \t")
896 (unless (bolp) (insert "\n")))
897 (insert "\n"))) ; FIXME: check eolp before inserting \n?
900 (put 'electric-layout-post-self-insert-function
'priority
40)
903 (define-minor-mode electric-layout-mode
904 "Automatically insert newlines around some chars.
905 With a prefix argument ARG, enable Electric Layout mode if ARG is
906 positive, and disable it otherwise. If called from Lisp, enable
907 the mode if ARG is omitted or nil.
908 The variable `electric-layout-rules' says when and how to insert newlines."
909 :global t
:group
'electricity
910 (cond (electric-layout-mode
911 (add-hook 'post-self-insert-hook
912 #'electric-layout-post-self-insert-function
)
913 (electric--sort-post-self-insertion-hook))
915 (remove-hook 'post-self-insert-hook
916 #'electric-layout-post-self-insert-function
))))
920 ;;; electric.el ends here