electric.el 18 KB

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