lisp/imenu.el (imenu-progress-message): Restore.
[bpt/emacs.git] / lisp / electric.el
CommitLineData
55535639 1;;; electric.el --- window maker and Command loop for `electric' modes
c0274f38 2
acaf905b 3;; Copyright (C) 1985-1986, 1995, 2001-2012 Free Software Foundation, Inc.
9750e079 4
e5167999
ER
5;; Author: K. Shane Hartman
6;; Maintainer: FSF
fd7fa35a 7;; Keywords: extensions
e5167999 8
0d20f9a0
JB
9;; This file is part of GNU Emacs.
10
eb3fa2cf 11;; GNU Emacs is free software: you can redistribute it and/or modify
0d20f9a0 12;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
0d20f9a0
JB
15
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.
20
21;; You should have received a copy of the GNU General Public License
eb3fa2cf 22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
0d20f9a0 23
c8472948 24;;; Commentary:
0d20f9a0 25
3b843809
SM
26;; "Electric" has been used in Emacs to refer to different things.
27;; Among them:
28;;
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
31;; is done with it.
32;;
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.
0d20f9a0 38
c8472948
ER
39;;; Code:
40
3b843809
SM
41(eval-when-compile (require 'cl))
42
0d20f9a0 43;; This loop is the guts for non-standard modes which retain control
f135afd3
RS
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
0d20f9a0
JB
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
f135afd3
RS
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
0d20f9a0
JB
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.
64
65(defun Electric-command-loop (return-tag
06b60517 66 &optional prompt inhibit-quitting
0d20f9a0 67 loop-function loop-state)
f135afd3 68
71296446
JB
69 (let (cmd
70 (err nil)
06b60517 71 (inhibit-quit inhibit-quitting)
f135afd3 72 (prompt-string prompt))
0d20f9a0 73 (while t
ba5bf5f0 74 (if (functionp prompt)
f135afd3
RS
75 (setq prompt-string (funcall prompt)))
76 (if (not (stringp prompt-string))
ba5bf5f0 77 (setq prompt-string (unless (eq prompt-string 'noprompt) "->")))
f135afd3 78 (setq cmd (read-key-sequence prompt-string))
8989a920 79 (setq last-command-event (aref cmd (1- (length cmd)))
f867d8d3 80 this-command (key-binding cmd t)
0d20f9a0 81 cmd this-command)
f867d8d3
RS
82 ;; This makes universal-argument-other-key work.
83 (setq universal-argument-num-events 0)
0d20f9a0 84 (if (or (prog1 quit-flag (setq quit-flag nil))
1e4bd40d 85 (eq last-input-event ?\C-g))
dbc4e1c1 86 (progn (setq unread-command-events nil
0d20f9a0 87 prefix-arg nil)
c80e3b4a 88 ;; If it wasn't canceling a prefix character, then quit.
0d20f9a0
JB
89 (if (or (= (length (this-command-keys)) 1)
90 (not inhibit-quit)) ; safety
91 (progn (ding)
92 (message "Quit")
93 (throw return-tag nil))
94 (setq cmd nil))))
95 (setq current-prefix-arg prefix-arg)
96 (if cmd
97 (condition-case conditions
98 (progn (command-execute cmd)
17c17ec9 99 (setq last-command this-command)
0d20f9a0 100 (if (or (prog1 quit-flag (setq quit-flag nil))
1e4bd40d 101 (eq last-input-event ?\C-g))
dbc4e1c1 102 (progn (setq unread-command-events nil)
0d20f9a0
JB
103 (if (not inhibit-quit)
104 (progn (ding)
105 (message "Quit")
106 (throw return-tag nil))
107 (ding)))))
108 (buffer-read-only (if loop-function
109 (setq err conditions)
110 (ding)
111 (message "Buffer is read-only")
112 (sit-for 2)))
113 (beginning-of-buffer (if loop-function
114 (setq err conditions)
115 (ding)
116 (message "Beginning of Buffer")
117 (sit-for 2)))
118 (end-of-buffer (if loop-function
119 (setq err conditions)
120 (ding)
121 (message "End of Buffer")
122 (sit-for 2)))
123 (error (if loop-function
124 (setq err conditions)
125 (ding)
126 (message "Error: %s"
127 (if (eq (car conditions) 'error)
128 (car (cdr conditions))
129 (prin1-to-string conditions)))
130 (sit-for 2))))
131 (ding))
132 (if loop-function (funcall loop-function loop-state err))))
133 (ding)
134 (throw return-tag nil))
135
71296446 136;; This function is like pop-to-buffer, sort of.
0d20f9a0
JB
137;; The algorithm is
138;; If there is a window displaying buffer
139;; Select it
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.
144;; Else
145;; Switch to buffer in the current window.
146;;
147;; Then if max-height is nil, and not all of the lines in the buffer
f98955ea 148;; are displayed, grab the whole frame.
0d20f9a0
JB
149;;
150;; Returns selected window on buffer positioned at point-min.
151
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))
156 (pop-up-windows t)
c45c149c 157 (pop-up-frames nil))
0d20f9a0
JB
158 (if (not buf)
159 (error "Buffer %s does not exist" buffer)
0d20f9a0
JB
160 (cond ((and (eq (window-buffer win) buf))
161 (select-window win))
162 (one-window
0d20f9a0 163 (pop-to-buffer buffer)
c45c149c 164 (setq win (selected-window)))
0d20f9a0
JB
165 (t
166 (switch-to-buffer buf)))
48238d1d 167 ;; Don't shrink the window, but expand it if necessary.
0d20f9a0 168 (goto-char (point-min))
0e87e61e 169 (unless (= (point-max) (window-end win t))
48238d1d 170 (fit-window-to-buffer win max-height))
0d20f9a0 171 win)))
49116ac0 172
3b843809
SM
173;;; Electric keys.
174
175(defgroup electricity ()
176 "Electric behavior for self inserting keys."
177 :group 'editing)
178
7100ff98
SM
179(defun electric--after-char-pos ()
180 "Return the position after the char we just inserted.
181Returns nil when we can't find this char."
182 (let ((pos (point)))
183 (when (or (eq (char-before) last-command-event) ;; Sanity check.
184 (save-excursion
185 (or (progn (skip-chars-backward " \t")
186 (setq pos (point))
187 (eq (char-before) last-command-event))
188 (progn (skip-chars-backward " \n\t")
189 (setq pos (point))
190 (eq (char-before) last-command-event)))))
191 pos)))
192
3b843809
SM
193;; Electric indentation.
194
2122161f
SM
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.
198;;;###autoload
3b843809 199(defvar electric-indent-chars '(?\n)
6f5e57e7
SM
200 "Characters that should cause automatic reindentation.")
201
202(defvar electric-indent-functions nil
203 "Special hook run to decide whether to auto-indent.
204Each function is called with one argument (the inserted char), with
205point right after that char, and it should return t to cause indentation,
206`no-indent' to prevent indentation or nil to let other functions decide.")
3b843809
SM
207
208(defun electric-indent-post-self-insert-function ()
209 ;; FIXME: This reindents the current line, but what we really want instead is
210 ;; to reindent the whole affected text. That's the current line for simple
211 ;; cases, but not all cases. We do take care of the newline case in an
212 ;; ad-hoc fashion, but there are still missing cases such as the case of
213 ;; electric-pair-mode wrapping a region with a pair of parens.
214 ;; There might be a way to get it working by analyzing buffer-undo-list, but
215 ;; it looks challenging.
7100ff98 216 (let (pos)
6f5e57e7
SM
217 (when (and
218 ;; Don't reindent while inserting spaces at beginning of line.
219 (or (not (memq last-command-event '(?\s ?\t)))
220 (save-excursion (skip-chars-backward " \t") (not (bolp))))
221 (setq pos (electric--after-char-pos))
222 (save-excursion
223 (goto-char pos)
224 (let ((act (or (run-hook-with-args-until-success
225 'electric-indent-functions
226 last-command-event)
227 (memq last-command-event electric-indent-chars))))
228 (not
229 (or (memq act '(nil no-indent))
230 ;; In a string or comment.
231 (unless (eq act 'do-indent) (nth 8 (syntax-ppss))))))))
7100ff98
SM
232 ;; For newline, we want to reindent both lines and basically behave like
233 ;; reindent-then-newline-and-indent (whose code we hence copied).
a733fc37 234 (when (< (1- pos) (line-beginning-position))
7100ff98
SM
235 (let ((before (copy-marker (1- pos) t)))
236 (save-excursion
a733fc37 237 (unless (memq indent-line-function
74a10be5 238 '(indent-relative indent-to-left-margin
6f5e57e7 239 indent-relative-maybe))
a733fc37
SM
240 ;; Don't reindent the previous line if the indentation function
241 ;; is not a real one.
242 (goto-char before)
243 (indent-according-to-mode))
7100ff98
SM
244 ;; We are at EOL before the call to indent-according-to-mode, and
245 ;; after it we usually are as well, but not always. We tried to
246 ;; address it with `save-excursion' but that uses a normal marker
247 ;; whereas we need `move after insertion', so we do the
248 ;; save/restore by hand.
249 (goto-char before)
250 ;; Remove the trailing whitespace after indentation because
251 ;; indentation may (re)introduce the whitespace.
252 (delete-horizontal-space t))))
74a10be5
SM
253 (unless (memq indent-line-function '(indent-to-left-margin))
254 (indent-according-to-mode)))))
3b843809
SM
255
256;;;###autoload
257(define-minor-mode electric-indent-mode
06e21633
CY
258 "Toggle on-the-fly reindentation (Electric Indent mode).
259With a prefix argument ARG, enable Electric Indent mode if ARG is
260positive, and disable it otherwise. If called from Lisp, enable
261the mode if ARG is omitted or nil.
262
a075a2c5
GM
263This is a global minor mode. When enabled, it reindents whenever
264the hook `electric-indent-functions' returns non-nil, or you
265insert a character from `electric-indent-chars'."
3b843809
SM
266 :global t
267 :group 'electricity
24f3d7b9
SM
268 (if (not electric-indent-mode)
269 (remove-hook 'post-self-insert-hook
270 #'electric-indent-post-self-insert-function)
271 ;; post-self-insert-hooks interact in non-trivial ways.
272 ;; It turns out that electric-indent-mode generally works better if run
273 ;; late, but still before blink-paren.
274 (add-hook 'post-self-insert-hook
275 #'electric-indent-post-self-insert-function
276 'append)
277 ;; FIXME: Ugly!
278 (let ((bp (memq #'blink-paren-post-self-insert-function
279 (default-value 'post-self-insert-hook))))
280 (when (memq #'electric-indent-post-self-insert-function bp)
281 (setcar bp #'electric-indent-post-self-insert-function)
282 (setcdr bp (cons #'blink-paren-post-self-insert-function
283 (delq #'electric-indent-post-self-insert-function
284 (cdr bp))))))))
3b843809
SM
285
286;; Electric pairing.
287
c51bb5d2
SM
288(defcustom electric-pair-pairs
289 '((?\" . ?\"))
290 "Alist of pairs that should be used regardless of major mode."
a075a2c5
GM
291 :group 'electricity
292 :version "24.1"
c51bb5d2
SM
293 :type '(repeat (cons character character)))
294
3b843809
SM
295(defcustom electric-pair-skip-self t
296 "If non-nil, skip char instead of inserting a second closing paren.
297When inserting a closing paren character right before the same character,
298just skip that character instead, so that hitting ( followed by ) results
299in \"()\" rather than \"())\".
300This can be convenient for people who find it easier to hit ) than C-f."
a075a2c5
GM
301 :group 'electricity
302 :version "24.1"
3b843809
SM
303 :type 'boolean)
304
305(defun electric-pair-post-self-insert-function ()
306 (let* ((syntax (and (eq (char-before) last-command-event) ; Sanity check.
0c325082 307 electric-pair-mode
c51bb5d2
SM
308 (let ((x (assq last-command-event electric-pair-pairs)))
309 (cond
310 (x (if (eq (car x) (cdr x)) ?\" ?\())
311 ((rassq last-command-event electric-pair-pairs) ?\))
312 (t (char-syntax last-command-event))))))
3b843809
SM
313 ;; FIXME: when inserting the closer, we should maybe use
314 ;; self-insert-command, although it may prove tricky running
315 ;; post-self-insert-hook recursively, and we wouldn't want to trigger
316 ;; blink-matching-open.
317 (closer (if (eq syntax ?\()
c51bb5d2
SM
318 (cdr (or (assq last-command-event electric-pair-pairs)
319 (aref (syntax-table) last-command-event)))
3b843809
SM
320 last-command-event)))
321 (cond
322 ;; Wrap a pair around the active region.
323 ((and (memq syntax '(?\( ?\" ?\$)) (use-region-p))
324 (if (> (mark) (point))
325 (goto-char (mark))
326 ;; We already inserted the open-paren but at the end of the region,
327 ;; so we have to remove it and start over.
328 (delete-char -1)
329 (save-excursion
330 (goto-char (mark))
331 (insert last-command-event)))
332 (insert closer))
333 ;; Backslash-escaped: no pairing, no skipping.
334 ((save-excursion
335 (goto-char (1- (point)))
336 (not (zerop (% (skip-syntax-backward "\\") 2))))
337 nil)
338 ;; Skip self.
339 ((and (memq syntax '(?\) ?\" ?\$))
340 electric-pair-skip-self
341 (eq (char-after) last-command-event))
342 ;; This is too late: rather than insert&delete we'd want to only skip (or
343 ;; insert in overwrite mode). The difference is in what goes in the
344 ;; undo-log and in the intermediate state which might be visible to other
345 ;; post-self-insert-hook. We'll just have to live with it for now.
346 (delete-char 1))
347 ;; Insert matching pair.
348 ((not (or (not (memq syntax `(?\( ?\" ?\$)))
349 overwrite-mode
350 ;; I find it more often preferable not to pair when the
351 ;; same char is next.
352 (eq last-command-event (char-after))
353 (eq last-command-event (char-before (1- (point))))
354 ;; I also find it often preferable not to pair next to a word.
355 (eq (char-syntax (following-char)) ?w)))
356 (save-excursion (insert closer))))))
357
358;;;###autoload
359(define-minor-mode electric-pair-mode
06e21633
CY
360 "Toggle automatic parens pairing (Electric Pair mode).
361With a prefix argument ARG, enable Electric Pair mode if ARG is
362positive, and disable it otherwise. If called from Lisp, enable
363the mode if ARG is omitted or nil.
364
365Electric Pair mode is a global minor mode. When enabled, typing
366an open parenthesis automatically inserts the corresponding
a075a2c5
GM
367closing parenthesis. \(Likewise for brackets, etc.)
368
369See options `electric-pair-pairs' and `electric-pair-skip-self'."
3b843809
SM
370 :global t
371 :group 'electricity
372 (if electric-pair-mode
373 (add-hook 'post-self-insert-hook
374 #'electric-pair-post-self-insert-function)
375 (remove-hook 'post-self-insert-hook
376 #'electric-pair-post-self-insert-function)))
7100ff98
SM
377
378;; Automatically add newlines after/before/around some chars.
379
380(defvar electric-layout-rules '()
381 "List of rules saying where to automatically insert newlines.
382Each rule has the form (CHAR . WHERE) where CHAR is the char
383that was just inserted and WHERE specifies where to insert newlines
a075a2c5
GM
384and can be: nil, `before', `after', `around', or a function of no
385arguments that returns one of those symbols.")
7100ff98
SM
386
387(defun electric-layout-post-self-insert-function ()
388 (let* ((rule (cdr (assq last-command-event electric-layout-rules)))
389 pos)
390 (when (and rule
391 (setq pos (electric--after-char-pos))
392 ;; Not in a string or comment.
393 (not (nth 8 (save-excursion (syntax-ppss pos)))))
394 (let ((end (copy-marker (point) t)))
395 (goto-char pos)
396 (case (if (functionp rule) (funcall rule) rule)
397 ;; FIXME: we used `newline' down here which called
398 ;; self-insert-command and ran post-self-insert-hook recursively.
399 ;; It happened to make electric-indent-mode work automatically with
400 ;; electric-layout-mode (at the cost of re-indenting lines
401 ;; multiple times), but I'm not sure it's what we want.
c51bb5d2
SM
402 (before (goto-char (1- pos)) (skip-chars-backward " \t")
403 (unless (bolp) (insert "\n")))
404 (after (insert "\n")) ; FIXME: check eolp before inserting \n?
405 (around (save-excursion
406 (goto-char (1- pos)) (skip-chars-backward " \t")
407 (unless (bolp) (insert "\n")))
408 (insert "\n"))) ; FIXME: check eolp before inserting \n?
7100ff98
SM
409 (goto-char end)))))
410
411;;;###autoload
412(define-minor-mode electric-layout-mode
e1ac4066
GM
413 "Automatically insert newlines around some chars.
414With a prefix argument ARG, enable Electric Layout mode if ARG is
415positive, and disable it otherwise. If called from Lisp, enable
a075a2c5
GM
416the mode if ARG is omitted or nil.
417The variable `electric-layout-rules' says when and how to insert newlines."
7100ff98
SM
418 :global t
419 :group 'electricity
420 (if electric-layout-mode
421 (add-hook 'post-self-insert-hook
422 #'electric-layout-post-self-insert-function)
423 (remove-hook 'post-self-insert-hook
424 #'electric-layout-post-self-insert-function)))
425
c0274f38
ER
426(provide 'electric)
427
c8472948 428;;; electric.el ends here