[TMP] enable load_prefer_newer
[bpt/emacs.git] / lisp / electric.el
CommitLineData
55535639 1;;; electric.el --- window maker and Command loop for `electric' modes
c0274f38 2
ba318903 3;; Copyright (C) 1985-1986, 1995, 2001-2014 Free Software Foundation,
ab422c4d 4;; Inc.
9750e079 5
e5167999 6;; Author: K. Shane Hartman
34dc21db 7;; Maintainer: emacs-devel@gnu.org
fd7fa35a 8;; Keywords: extensions
e5167999 9
0d20f9a0
JB
10;; This file is part of GNU Emacs.
11
eb3fa2cf 12;; GNU Emacs is free software: you can redistribute it and/or modify
0d20f9a0 13;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
0d20f9a0
JB
16
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.
21
22;; You should have received a copy of the GNU General Public License
eb3fa2cf 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
0d20f9a0 24
c8472948 25;;; Commentary:
0d20f9a0 26
3b843809
SM
27;; "Electric" has been used in Emacs to refer to different things.
28;; Among them:
29;;
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
32;; is done with it.
33;;
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.
0d20f9a0 39
c8472948
ER
40;;; Code:
41
0d20f9a0 42;; This loop is the guts for non-standard modes which retain control
f135afd3
RS
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
0d20f9a0
JB
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
f135afd3
RS
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
0d20f9a0
JB
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.
63
64(defun Electric-command-loop (return-tag
06b60517 65 &optional prompt inhibit-quitting
0d20f9a0 66 loop-function loop-state)
f135afd3 67
71296446
JB
68 (let (cmd
69 (err nil)
06b60517 70 (inhibit-quit inhibit-quitting)
f135afd3 71 (prompt-string prompt))
0d20f9a0 72 (while t
ba5bf5f0 73 (if (functionp prompt)
f135afd3
RS
74 (setq prompt-string (funcall prompt)))
75 (if (not (stringp prompt-string))
ba5bf5f0 76 (setq prompt-string (unless (eq prompt-string 'noprompt) "->")))
f135afd3 77 (setq cmd (read-key-sequence prompt-string))
8989a920 78 (setq last-command-event (aref cmd (1- (length cmd)))
f867d8d3 79 this-command (key-binding cmd t)
0d20f9a0
JB
80 cmd this-command)
81 (if (or (prog1 quit-flag (setq quit-flag nil))
1e4bd40d 82 (eq last-input-event ?\C-g))
dbc4e1c1 83 (progn (setq unread-command-events nil
0d20f9a0 84 prefix-arg nil)
c80e3b4a 85 ;; If it wasn't canceling a prefix character, then quit.
0d20f9a0
JB
86 (if (or (= (length (this-command-keys)) 1)
87 (not inhibit-quit)) ; safety
88 (progn (ding)
89 (message "Quit")
90 (throw return-tag nil))
91 (setq cmd nil))))
92 (setq current-prefix-arg prefix-arg)
93 (if cmd
94 (condition-case conditions
95 (progn (command-execute cmd)
17c17ec9 96 (setq last-command this-command)
0d20f9a0 97 (if (or (prog1 quit-flag (setq quit-flag nil))
1e4bd40d 98 (eq last-input-event ?\C-g))
dbc4e1c1 99 (progn (setq unread-command-events nil)
0d20f9a0
JB
100 (if (not inhibit-quit)
101 (progn (ding)
102 (message "Quit")
103 (throw return-tag nil))
104 (ding)))))
105 (buffer-read-only (if loop-function
106 (setq err conditions)
107 (ding)
108 (message "Buffer is read-only")
109 (sit-for 2)))
110 (beginning-of-buffer (if loop-function
111 (setq err conditions)
112 (ding)
113 (message "Beginning of Buffer")
114 (sit-for 2)))
115 (end-of-buffer (if loop-function
116 (setq err conditions)
117 (ding)
118 (message "End of Buffer")
119 (sit-for 2)))
120 (error (if loop-function
121 (setq err conditions)
122 (ding)
123 (message "Error: %s"
124 (if (eq (car conditions) 'error)
125 (car (cdr conditions))
126 (prin1-to-string conditions)))
127 (sit-for 2))))
128 (ding))
129 (if loop-function (funcall loop-function loop-state err))))
130 (ding)
131 (throw return-tag nil))
132
71296446 133;; This function is like pop-to-buffer, sort of.
0d20f9a0
JB
134;; The algorithm is
135;; If there is a window displaying buffer
136;; Select it
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.
141;; Else
142;; Switch to buffer in the current window.
143;;
144;; Then if max-height is nil, and not all of the lines in the buffer
f98955ea 145;; are displayed, grab the whole frame.
0d20f9a0
JB
146;;
147;; Returns selected window on buffer positioned at point-min.
148
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))
153 (pop-up-windows t)
c45c149c 154 (pop-up-frames nil))
0d20f9a0
JB
155 (if (not buf)
156 (error "Buffer %s does not exist" buffer)
0d20f9a0
JB
157 (cond ((and (eq (window-buffer win) buf))
158 (select-window win))
159 (one-window
0d20f9a0 160 (pop-to-buffer buffer)
c45c149c 161 (setq win (selected-window)))
0d20f9a0
JB
162 (t
163 (switch-to-buffer buf)))
48238d1d 164 ;; Don't shrink the window, but expand it if necessary.
0d20f9a0 165 (goto-char (point-min))
0e87e61e 166 (unless (= (point-max) (window-end win t))
48238d1d 167 (fit-window-to-buffer win max-height))
0d20f9a0 168 win)))
49116ac0 169
3b843809
SM
170;;; Electric keys.
171
172(defgroup electricity ()
173 "Electric behavior for self inserting keys."
174 :group 'editing)
175
7100ff98
SM
176(defun electric--after-char-pos ()
177 "Return the position after the char we just inserted.
178Returns nil when we can't find this char."
179 (let ((pos (point)))
180 (when (or (eq (char-before) last-command-event) ;; Sanity check.
181 (save-excursion
182 (or (progn (skip-chars-backward " \t")
183 (setq pos (point))
184 (eq (char-before) last-command-event))
185 (progn (skip-chars-backward " \n\t")
186 (setq pos (point))
187 (eq (char-before) last-command-event)))))
188 pos)))
189
3b8d5131
JT
190(defun electric--sort-post-self-insertion-hook ()
191 "Ensure order of electric functions in `post-self-insertion-hook'.
192
193Hooks in this variable interact in non-trivial ways, so a
194relative order must be maintained within it."
195 (setq-default post-self-insert-hook
196 (sort (default-value 'post-self-insert-hook)
197 #'(lambda (fn1 fn2)
198 (< (or (get fn1 'priority) 0)
199 (or (get fn2 'priority) 0))))))
200
2abb4e65 201;;; Electric indentation.
3b843809 202
2122161f
SM
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.
206;;;###autoload
3b843809 207(defvar electric-indent-chars '(?\n)
6f5e57e7
SM
208 "Characters that should cause automatic reindentation.")
209
210(defvar electric-indent-functions nil
211 "Special hook run to decide whether to auto-indent.
212Each function is called with one argument (the inserted char), with
213point 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.")
3b843809 215
2abb4e65
SM
216(defvar-local electric-indent-inhibit nil
217 "If non-nil, reindentation is not appropriate for this buffer.
218This should be set by major modes such as `python-mode' since
219Python does not lend itself to fully automatic indentation.")
220
a35287ea
SM
221(defvar electric-indent-functions-without-reindent
222 '(indent-relative indent-to-left-margin indent-relative-maybe
c8481b1b 223 py-indent-line coffee-indent-line org-indent-line yaml-indent-line
e6025d72
SM
224 haskell-indentation-indent-line haskell-indent-cycle haskell-simple-indent
225 yaml-indent-line)
a35287ea
SM
226 "List of indent functions that can't reindent.
227If `line-indent-function' is one of those, then `electric-indent-mode' will
228not try to reindent lines. It is normally better to make the major
229mode set `electric-indent-inhibit', but this can be used as a workaround.")
230
3b843809 231(defun electric-indent-post-self-insert-function ()
78540c42
GM
232 "Function that `electric-indent-mode' adds to `post-self-insert-hook'.
233This indents if the hook `electric-indent-functions' returns non-nil,
234or if a member of `electric-indent-chars' was typed; but not in a string
235or comment."
3b843809
SM
236 ;; FIXME: This reindents the current line, but what we really want instead is
237 ;; to reindent the whole affected text. That's the current line for simple
238 ;; cases, but not all cases. We do take care of the newline case in an
239 ;; ad-hoc fashion, but there are still missing cases such as the case of
240 ;; electric-pair-mode wrapping a region with a pair of parens.
241 ;; There might be a way to get it working by analyzing buffer-undo-list, but
242 ;; it looks challenging.
7100ff98 243 (let (pos)
6f5e57e7 244 (when (and
cfc7d5da 245 electric-indent-mode
6f5e57e7
SM
246 ;; Don't reindent while inserting spaces at beginning of line.
247 (or (not (memq last-command-event '(?\s ?\t)))
248 (save-excursion (skip-chars-backward " \t") (not (bolp))))
249 (setq pos (electric--after-char-pos))
250 (save-excursion
251 (goto-char pos)
252 (let ((act (or (run-hook-with-args-until-success
253 'electric-indent-functions
254 last-command-event)
255 (memq last-command-event electric-indent-chars))))
256 (not
257 (or (memq act '(nil no-indent))
258 ;; In a string or comment.
259 (unless (eq act 'do-indent) (nth 8 (syntax-ppss))))))))
7100ff98
SM
260 ;; For newline, we want to reindent both lines and basically behave like
261 ;; reindent-then-newline-and-indent (whose code we hence copied).
3ebdceaf
PR
262 (let ((at-newline (<= pos (line-beginning-position))))
263 (when at-newline
264 (let ((before (copy-marker (1- pos) t)))
265 (save-excursion
266 (unless (or (memq indent-line-function
267 electric-indent-functions-without-reindent)
268 electric-indent-inhibit)
269 ;; Don't reindent the previous line if the indentation function
270 ;; is not a real one.
271 (goto-char before)
272 (indent-according-to-mode))
273 ;; We are at EOL before the call to indent-according-to-mode, and
274 ;; after it we usually are as well, but not always. We tried to
275 ;; address it with `save-excursion' but that uses a normal marker
276 ;; whereas we need `move after insertion', so we do the
277 ;; save/restore by hand.
a733fc37 278 (goto-char before)
3ebdceaf
PR
279 (when (eolp)
280 ;; Remove the trailing whitespace after indentation because
281 ;; indentation may (re)introduce the whitespace.
282 (delete-horizontal-space t)))))
283 (unless (and electric-indent-inhibit
284 (not at-newline))
285 (indent-according-to-mode))))))
3b843809 286
3b8d5131
JT
287(put 'electric-indent-post-self-insert-function 'priority 60)
288
feca4e2d
SM
289(defun electric-indent-just-newline (arg)
290 "Insert just a newline, without any auto-indentation."
291 (interactive "*P")
292 (let ((electric-indent-mode nil))
293 (newline arg 'interactive)))
294
b88eed60
SM
295;;;###autoload
296(define-key global-map "\C-j" 'electric-newline-and-maybe-indent)
494ec1e7
SM
297;;;###autoload
298(defun electric-newline-and-maybe-indent ()
299 "Insert a newline.
300If `electric-indent-mode' is enabled, that's that, but if it
301is *disabled* then additionally indent according to major mode.
302Indentation is done using the value of `indent-line-function'.
303In programming language modes, this is the same as TAB.
304In some text modes, where TAB inserts a tab, this command indents to the
305column specified by the function `current-left-margin'."
306 (interactive "*")
307 (if electric-indent-mode
308 (electric-indent-just-newline nil)
309 (newline-and-indent)))
8d4901dc 310
3b843809
SM
311;;;###autoload
312(define-minor-mode electric-indent-mode
06e21633
CY
313 "Toggle on-the-fly reindentation (Electric Indent mode).
314With a prefix argument ARG, enable Electric Indent mode if ARG is
315positive, and disable it otherwise. If called from Lisp, enable
316the mode if ARG is omitted or nil.
317
8a51e8e4
GM
318When enabled, this reindents whenever the hook `electric-indent-functions'
319returns non-nil, or if you insert a character from `electric-indent-chars'.
320
321This is a global minor mode. To toggle the mode in a single buffer,
322use `electric-indent-local-mode'."
feca4e2d 323 :global t :group 'electricity
da048127
SM
324 :initialize 'custom-initialize-delay
325 :init-value t
24f3d7b9 326 (if (not electric-indent-mode)
494ec1e7
SM
327 (unless (catch 'found
328 (dolist (buf (buffer-list))
329 (with-current-buffer buf
330 (if electric-indent-mode (throw 'found t)))))
25158c76
SM
331 (remove-hook 'post-self-insert-hook
332 #'electric-indent-post-self-insert-function))
24f3d7b9 333 (add-hook 'post-self-insert-hook
3b8d5131
JT
334 #'electric-indent-post-self-insert-function)
335 (electric--sort-post-self-insertion-hook)))
3b843809 336
a35287ea
SM
337;;;###autoload
338(define-minor-mode electric-indent-local-mode
339 "Toggle `electric-indent-mode' only in this buffer."
340 :variable (buffer-local-value 'electric-indent-mode (current-buffer))
341 (cond
342 ((eq electric-indent-mode (default-value 'electric-indent-mode))
343 (kill-local-variable 'electric-indent-mode))
344 ((not (default-value 'electric-indent-mode))
345 ;; Locally enabled, but globally disabled.
346 (electric-indent-mode 1) ; Setup the hooks.
347 (setq-default electric-indent-mode nil) ; But keep it globally disabled.
348 )))
349
2abb4e65 350;;; Electric newlines after/before/around some chars.
7100ff98 351
3b8d5131 352(defvar electric-layout-rules nil
7100ff98 353 "List of rules saying where to automatically insert newlines.
3b8d5131
JT
354
355Each rule has the form (CHAR . WHERE) where CHAR is the char that
356was just inserted and WHERE specifies where to insert newlines
357and can be: nil, `before', `after', `around', `after-stay', or a
358function of no arguments that returns one of those symbols.
359
360The symbols specify where in relation to CHAR the newline
361character(s) should be inserted. `after-stay' means insert a
362newline after CHAR but stay in the same place.")
7100ff98
SM
363
364(defun electric-layout-post-self-insert-function ()
365 (let* ((rule (cdr (assq last-command-event electric-layout-rules)))
366 pos)
367 (when (and rule
368 (setq pos (electric--after-char-pos))
369 ;; Not in a string or comment.
370 (not (nth 8 (save-excursion (syntax-ppss pos)))))
9c3883b4 371 (let ((end (point-marker))
3b8d5131
JT
372 (sym (if (functionp rule) (funcall rule) rule)))
373 (set-marker-insertion-type end (not (eq sym 'after-stay)))
7100ff98 374 (goto-char pos)
3b8d5131 375 (pcase sym
7100ff98
SM
376 ;; FIXME: we used `newline' down here which called
377 ;; self-insert-command and ran post-self-insert-hook recursively.
378 ;; It happened to make electric-indent-mode work automatically with
379 ;; electric-layout-mode (at the cost of re-indenting lines
380 ;; multiple times), but I'm not sure it's what we want.
3b8d5131
JT
381 ;;
382 ;; FIXME: check eolp before inserting \n?
f58e0fd5 383 (`before (goto-char (1- pos)) (skip-chars-backward " \t")
3b8d5131
JT
384 (unless (bolp) (insert "\n")))
385 (`after (insert "\n"))
386 (`after-stay (save-excursion
387 (let ((electric-layout-rules nil))
388 (newline 1 t))))
f58e0fd5 389 (`around (save-excursion
3b8d5131
JT
390 (goto-char (1- pos)) (skip-chars-backward " \t")
391 (unless (bolp) (insert "\n")))
392 (insert "\n"))) ; FIXME: check eolp before inserting \n?
7100ff98
SM
393 (goto-char end)))))
394
3b8d5131
JT
395(put 'electric-layout-post-self-insert-function 'priority 40)
396
7100ff98
SM
397;;;###autoload
398(define-minor-mode electric-layout-mode
e1ac4066
GM
399 "Automatically insert newlines around some chars.
400With a prefix argument ARG, enable Electric Layout mode if ARG is
401positive, and disable it otherwise. If called from Lisp, enable
a075a2c5
GM
402the mode if ARG is omitted or nil.
403The variable `electric-layout-rules' says when and how to insert newlines."
feca4e2d 404 :global t :group 'electricity
3b8d5131
JT
405 (cond (electric-layout-mode
406 (add-hook 'post-self-insert-hook
407 #'electric-layout-post-self-insert-function)
408 (electric--sort-post-self-insertion-hook))
409 (t
410 (remove-hook 'post-self-insert-hook
411 #'electric-layout-post-self-insert-function))))
7100ff98 412
c0274f38
ER
413(provide 'electric)
414
c8472948 415;;; electric.el ends here