1 ;;; electric.el --- window maker and Command loop for `electric' modes
3 ;; Copyright (C) 1985-1986, 1995, 2001-2011 Free Software Foundation, Inc.
5 ;; Author: K. Shane Hartman
7 ;; Keywords: extensions
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; "Electric" has been used in Emacs to refer to different things.
29 ;; - electric modes and buffers: modes that typically pop-up in a modal kind of
30 ;; way a transient buffer that automatically disappears as soon as the user
33 ;; - electric keys: self inserting keys which additionally perform some side
34 ;; operation which happens to be often convenient at that time. Examples of
35 ;; such side operations are: reindenting code, inserting a newline,
36 ;; ... auto-fill-mode and abbrev-mode can be considered as built-in forms of
37 ;; electric key behavior.
41 (eval-when-compile (require 'cl
))
43 ;; This loop is the guts for non-standard modes which retain control
44 ;; until some event occurs. It is a `do-forever', the only way out is
45 ;; to throw. It assumes that you have set up the keymap, window, and
46 ;; everything else: all it does is read commands and execute them -
47 ;; providing error messages should one occur (if there is no loop
48 ;; function - which see). The required argument is a tag which should
49 ;; expect a value of nil if the user decides to punt. The second
50 ;; argument is the prompt to be used: if nil, use "->", if 'noprompt,
51 ;; don't use a prompt, if a string, use that string as prompt, and if
52 ;; a function of no variable, it will be evaluated in every iteration
53 ;; of the loop and its return value, which can be nil, 'noprompt or a
54 ;; string, will be used as prompt. Given third argument non-nil, it
55 ;; INHIBITS quitting unless the user types C-g at toplevel. This is
56 ;; so user can do things like C-u C-g and not get thrown out. Fourth
57 ;; argument, if non-nil, should be a function of two arguments which
58 ;; is called after every command is executed. The fifth argument, if
59 ;; provided, is the state variable for the function. If the
60 ;; loop-function gets an error, the loop will abort WITHOUT throwing
61 ;; (moral: use unwind-protect around call to this function for any
62 ;; critical stuff). The second argument for the loop function is the
63 ;; conditions for any error that occurred or nil if none.
65 (defun Electric-command-loop (return-tag
66 &optional prompt inhibit-quitting
67 loop-function loop-state
)
71 (inhibit-quit inhibit-quitting
)
72 (prompt-string prompt
))
74 (if (functionp prompt
)
75 (setq prompt-string
(funcall prompt
)))
76 (if (not (stringp prompt-string
))
77 (setq prompt-string
(unless (eq prompt-string
'noprompt
) "->")))
78 (setq cmd
(read-key-sequence prompt-string
))
79 (setq last-command-event
(aref cmd
(1- (length cmd
)))
80 this-command
(key-binding cmd t
)
82 ;; This makes universal-argument-other-key work.
83 (setq universal-argument-num-events
0)
84 (if (or (prog1 quit-flag
(setq quit-flag nil
))
85 (eq last-input-event ?\C-g
))
86 (progn (setq unread-command-events nil
88 ;; If it wasn't cancelling a prefix character, then quit.
89 (if (or (= (length (this-command-keys)) 1)
90 (not inhibit-quit
)) ; safety
93 (throw return-tag nil
))
95 (setq current-prefix-arg prefix-arg
)
97 (condition-case conditions
98 (progn (command-execute cmd
)
99 (setq last-command this-command
)
100 (if (or (prog1 quit-flag
(setq quit-flag nil
))
101 (eq last-input-event ?\C-g
))
102 (progn (setq unread-command-events nil
)
103 (if (not inhibit-quit
)
106 (throw return-tag nil
))
108 (buffer-read-only (if loop-function
109 (setq err conditions
)
111 (message "Buffer is read-only")
113 (beginning-of-buffer (if loop-function
114 (setq err conditions
)
116 (message "Beginning of Buffer")
118 (end-of-buffer (if loop-function
119 (setq err conditions
)
121 (message "End of Buffer")
123 (error (if loop-function
124 (setq err conditions
)
127 (if (eq (car conditions
) 'error
)
128 (car (cdr conditions
))
129 (prin1-to-string conditions
)))
132 (if loop-function
(funcall loop-function loop-state err
))))
134 (throw return-tag nil
))
136 ;; This function is like pop-to-buffer, sort of.
138 ;; If there is a window displaying buffer
140 ;; Else if there is only one window
141 ;; Split it, selecting the window on the bottom with height being
142 ;; the lesser of max-height (if non-nil) and the number of lines in
143 ;; the buffer to be displayed subject to window-min-height constraint.
145 ;; Switch to buffer in the current window.
147 ;; Then if max-height is nil, and not all of the lines in the buffer
148 ;; are displayed, grab the whole frame.
150 ;; Returns selected window on buffer positioned at point-min.
152 (defun Electric-pop-up-window (buffer &optional max-height
)
153 (let* ((win (or (get-buffer-window buffer
) (selected-window)))
154 (buf (get-buffer buffer
))
155 (one-window (one-window-p t
))
159 (error "Buffer %s does not exist" buffer
)
160 (cond ((and (eq (window-buffer win
) buf
))
163 (pop-to-buffer buffer
)
164 (setq win
(selected-window)))
166 (switch-to-buffer buf
)))
167 ;; Don't shrink the window, but expand it if necessary.
168 (goto-char (point-min))
169 (unless (= (point-max) (window-end win t
))
170 (fit-window-to-buffer win max-height
))
175 (defgroup electricity
()
176 "Electric behavior for self inserting keys."
179 (defun electric--after-char-pos ()
180 "Return the position after the char we just inserted.
181 Returns nil when we can't find this char."
183 (when (or (eq (char-before) last-command-event
) ;; Sanity check.
185 (or (progn (skip-chars-backward " \t")
187 (eq (char-before) last-command-event
))
188 (progn (skip-chars-backward " \n\t")
190 (eq (char-before) last-command-event
)))))
193 ;; Electric indentation.
195 ;; Autoloading variables is generally undesirable, but major modes
196 ;; should usually set this variable by adding elements to the default
197 ;; value, which only works well if the variable is preloaded.
199 (defvar electric-indent-chars
'(?
\n)
200 "Characters that should cause automatic reindentation.
201 Each entry of the list can be either a character or a cons of the
202 form (CHAR . PREDICATE) which means that CHAR should cause reindentation
203 only if PREDICATE returns non-nil. PREDICATE is called with no arguments
204 and with point before the inserted char.")
206 (defun electric-indent-post-self-insert-function ()
207 ;; FIXME: This reindents the current line, but what we really want instead is
208 ;; to reindent the whole affected text. That's the current line for simple
209 ;; cases, but not all cases. We do take care of the newline case in an
210 ;; ad-hoc fashion, but there are still missing cases such as the case of
211 ;; electric-pair-mode wrapping a region with a pair of parens.
212 ;; There might be a way to get it working by analyzing buffer-undo-list, but
213 ;; it looks challenging.
215 (when (and (or (memq last-command-event electric-indent-chars
)
216 (let ((cp (assq last-command-event electric-indent-chars
)))
217 (and cp
(setq pos
(electric--after-char-pos))
220 (funcall (cdr cp
))))))
221 ;; Don't reindent while inserting spaces at beginning of line.
222 (or (not (memq last-command-event
'(?\s ?
\t)))
223 (save-excursion (skip-chars-backward " \t") (not (bolp))))
224 (setq pos
(electric--after-char-pos))
225 ;; Not in a string or comment.
226 (not (nth 8 (save-excursion (syntax-ppss pos
)))))
227 ;; For newline, we want to reindent both lines and basically behave like
228 ;; reindent-then-newline-and-indent (whose code we hence copied).
229 (when (< (1- pos
) (line-beginning-position))
230 (let ((before (copy-marker (1- pos
) t
)))
232 (unless (memq indent-line-function
233 '(indent-relative indent-to-left-margin
234 indent-relative-maybe
))
235 ;; Don't reindent the previous line if the indentation function
236 ;; is not a real one.
238 (indent-according-to-mode))
239 ;; We are at EOL before the call to indent-according-to-mode, and
240 ;; after it we usually are as well, but not always. We tried to
241 ;; address it with `save-excursion' but that uses a normal marker
242 ;; whereas we need `move after insertion', so we do the
243 ;; save/restore by hand.
245 ;; Remove the trailing whitespace after indentation because
246 ;; indentation may (re)introduce the whitespace.
247 (delete-horizontal-space t
))))
248 (unless (memq indent-line-function
'(indent-to-left-margin))
249 (indent-according-to-mode)))))
252 (define-minor-mode electric-indent-mode
253 "Toggle on-the-fly reindentation (Electric Indent mode).
254 With a prefix argument ARG, enable Electric Indent mode if ARG is
255 positive, and disable it otherwise. If called from Lisp, enable
256 the mode if ARG is omitted or nil.
258 Electric Indent mode is a global minor mode. When enabled,
259 reindentation is triggered whenever you insert a character listed
260 in `electric-indent-chars'."
263 (if electric-indent-mode
264 (add-hook 'post-self-insert-hook
265 #'electric-indent-post-self-insert-function
266 ;; post-self-insert-hooks interact in non-trivial ways.
267 ;; It turns out that electric-indent-mode generally works
270 (remove-hook 'post-self-insert-hook
271 #'electric-indent-post-self-insert-function
)))
275 (defcustom electric-pair-pairs
277 "Alist of pairs that should be used regardless of major mode."
278 :type
'(repeat (cons character character
)))
280 (defcustom electric-pair-skip-self t
281 "If non-nil, skip char instead of inserting a second closing paren.
282 When inserting a closing paren character right before the same character,
283 just skip that character instead, so that hitting ( followed by ) results
284 in \"()\" rather than \"())\".
285 This can be convenient for people who find it easier to hit ) than C-f."
288 (defun electric-pair-post-self-insert-function ()
289 (let* ((syntax (and (eq (char-before) last-command-event
) ; Sanity check.
291 (let ((x (assq last-command-event electric-pair-pairs
)))
293 (x (if (eq (car x
) (cdr x
)) ?
\" ?\
())
294 ((rassq last-command-event electric-pair-pairs
) ?\
))
295 (t (char-syntax last-command-event
))))))
296 ;; FIXME: when inserting the closer, we should maybe use
297 ;; self-insert-command, although it may prove tricky running
298 ;; post-self-insert-hook recursively, and we wouldn't want to trigger
299 ;; blink-matching-open.
300 (closer (if (eq syntax ?\
()
301 (cdr (or (assq last-command-event electric-pair-pairs
)
302 (aref (syntax-table) last-command-event
)))
303 last-command-event
)))
305 ;; Wrap a pair around the active region.
306 ((and (memq syntax
'(?\
( ?
\" ?\$
)) (use-region-p))
307 (if (> (mark) (point))
309 ;; We already inserted the open-paren but at the end of the region,
310 ;; so we have to remove it and start over.
314 (insert last-command-event
)))
316 ;; Backslash-escaped: no pairing, no skipping.
318 (goto-char (1- (point)))
319 (not (zerop (%
(skip-syntax-backward "\\") 2))))
322 ((and (memq syntax
'(?\
) ?
\" ?\$
))
323 electric-pair-skip-self
324 (eq (char-after) last-command-event
))
325 ;; This is too late: rather than insert&delete we'd want to only skip (or
326 ;; insert in overwrite mode). The difference is in what goes in the
327 ;; undo-log and in the intermediate state which might be visible to other
328 ;; post-self-insert-hook. We'll just have to live with it for now.
330 ;; Insert matching pair.
331 ((not (or (not (memq syntax
`(?\
( ?
\" ?\$
)))
333 ;; I find it more often preferable not to pair when the
334 ;; same char is next.
335 (eq last-command-event
(char-after))
336 (eq last-command-event
(char-before (1- (point))))
337 ;; I also find it often preferable not to pair next to a word.
338 (eq (char-syntax (following-char)) ?w
)))
339 (save-excursion (insert closer
))))))
342 (define-minor-mode electric-pair-mode
343 "Toggle automatic parens pairing (Electric Pair mode).
344 With a prefix argument ARG, enable Electric Pair mode if ARG is
345 positive, and disable it otherwise. If called from Lisp, enable
346 the mode if ARG is omitted or nil.
348 Electric Pair mode is a global minor mode. When enabled, typing
349 an open parenthesis automatically inserts the corresponding
350 closing parenthesis. \(Likewise for brackets, etc.)"
353 (if electric-pair-mode
354 (add-hook 'post-self-insert-hook
355 #'electric-pair-post-self-insert-function
)
356 (remove-hook 'post-self-insert-hook
357 #'electric-pair-post-self-insert-function
)))
359 ;; Automatically add newlines after/before/around some chars.
361 (defvar electric-layout-rules
'()
362 "List of rules saying where to automatically insert newlines.
363 Each rule has the form (CHAR . WHERE) where CHAR is the char
364 that was just inserted and WHERE specifies where to insert newlines
365 and can be: nil, `before', `after', `around', or a function that returns
366 one of those symbols.")
368 (defun electric-layout-post-self-insert-function ()
369 (let* ((rule (cdr (assq last-command-event electric-layout-rules
)))
372 (setq pos
(electric--after-char-pos))
373 ;; Not in a string or comment.
374 (not (nth 8 (save-excursion (syntax-ppss pos
)))))
375 (let ((end (copy-marker (point) t
)))
377 (case (if (functionp rule
) (funcall rule
) rule
)
378 ;; FIXME: we used `newline' down here which called
379 ;; self-insert-command and ran post-self-insert-hook recursively.
380 ;; It happened to make electric-indent-mode work automatically with
381 ;; electric-layout-mode (at the cost of re-indenting lines
382 ;; multiple times), but I'm not sure it's what we want.
383 (before (goto-char (1- pos
)) (skip-chars-backward " \t")
384 (unless (bolp) (insert "\n")))
385 (after (insert "\n")) ; FIXME: check eolp before inserting \n?
386 (around (save-excursion
387 (goto-char (1- pos
)) (skip-chars-backward " \t")
388 (unless (bolp) (insert "\n")))
389 (insert "\n"))) ; FIXME: check eolp before inserting \n?
393 (define-minor-mode electric-layout-mode
394 "Automatically insert newlines around some chars."
397 (if electric-layout-mode
398 (add-hook 'post-self-insert-hook
399 #'electric-layout-post-self-insert-function
)
400 (remove-hook 'post-self-insert-hook
401 #'electric-layout-post-self-insert-function
)))
405 ;;; electric.el ends here