repeat.el 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. ;;; repeat.el --- convenient way to repeat the previous command
  2. ;; Copyright (C) 1998, 2001-2012 Free Software Foundation, Inc.
  3. ;; Author: Will Mengarini <seldon@eskimo.com>
  4. ;; Created: Mo 02 Mar 98
  5. ;; Version: 0.51
  6. ;; Keywords: convenience, vi, repeat
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; Sometimes the fastest way to get something done is just to lean on a key;
  20. ;; moving forward through a series of words by leaning on M-f is an example.
  21. ;; But 'forward-page is orthodoxly bound to C-x ], so moving forward through
  22. ;; several pages requires
  23. ;; Loop until desired page is reached:
  24. ;; Hold down control key with left pinkie.
  25. ;; Tap <x>.
  26. ;; Lift left pinkie off control key.
  27. ;; Tap <]>.
  28. ;; This is a pain in the ass.
  29. ;; This package defines a command that repeats the preceding command,
  30. ;; whatever that was, including its arguments, whatever they were.
  31. ;; This command is connected to the key C-x z.
  32. ;; To repeat the previous command once, type C-x z.
  33. ;; To repeat it a second time immediately after, type just z.
  34. ;; By typing z again and again, you can repeat the command over and over.
  35. ;; This works correctly inside a keyboard macro as far as recording and
  36. ;; playback go, but `edit-kbd-macro' gets it wrong. That shouldn't really
  37. ;; matter; if you need to edit something like
  38. ;; C-x ] ;; forward-page
  39. ;; C-x z ;; repeat
  40. ;; zz ;; self-insert-command * 2
  41. ;; C-x ;; Control-X-prefix
  42. ;; you can just kill the bogus final 2 lines, then duplicate the repeat line
  43. ;; as many times as it's really needed. Also, `edit-kbd-macro' works
  44. ;; correctly if `repeat' is invoked through a rebinding to a single keystroke
  45. ;; and the global variable repeat-on-final-keystroke is set to a value
  46. ;; that doesn't include that keystroke. For example, the lines
  47. ;; (global-set-key "\C-z" 'repeat)
  48. ;; (setq repeat-on-final-keystroke "z")
  49. ;; in your .emacs would allow `edit-kbd-macro' to work correctly when C-z was
  50. ;; used in a keyboard macro to invoke `repeat', but would still allow C-x z
  51. ;; to be used for `repeat' elsewhere. The real reason for documenting this
  52. ;; isn't that anybody would need it for the `edit-kbd-macro' problem, but
  53. ;; that there might be other unexpected ramifications of re-executing on
  54. ;; repetitions of the final keystroke, and this shows how to do workarounds.
  55. ;; If the preceding command had a prefix argument, that argument is applied
  56. ;; to the repeat command, unless the repeat command is given a new prefix
  57. ;; argument, in which case it applies that new prefix argument to the
  58. ;; preceding command. This means a key sequence like C-u - C-x C-t can be
  59. ;; repeated. (It shoves the preceding line upward in the buffer.)
  60. ;; Here are some other key sequences with which repeat might be useful:
  61. ;; C-u - C-t [shove preceding character backward in line]
  62. ;; C-u - M-t [shove preceding word backward in sentence]
  63. ;; C-x ^ enlarge-window [one line] (assuming frame has > 1 window)
  64. ;; C-u - C-x ^ [shrink window one line]
  65. ;; C-x ` next-error
  66. ;; C-u - C-x ` [previous error]
  67. ;; C-x DEL backward-kill-sentence
  68. ;; C-x e call-last-kbd-macro
  69. ;; C-x r i insert-register
  70. ;; C-x r t string-rectangle
  71. ;; C-x TAB indent-rigidly [one character]
  72. ;; C-u - C-x TAB [outdent rigidly one character]
  73. ;; C-x { shrink-window-horizontally
  74. ;; C-x } enlarge-window-horizontally
  75. ;; This command was first called `vi-dot', because
  76. ;; it was inspired by the `.' command in the vi editor,
  77. ;; but it was renamed to make its name more meaningful.
  78. ;;; Code:
  79. ;;;;; ************************* USER OPTIONS ************************** ;;;;;
  80. (defcustom repeat-too-dangerous '(kill-this-buffer)
  81. "Commands too dangerous to repeat with \\[repeat]."
  82. :group 'convenience
  83. :type '(repeat function))
  84. ;; If the last command was self-insert-command, the char to be inserted was
  85. ;; obtained by that command from last-command-event, which has now been
  86. ;; clobbered by the command sequence that invoked `repeat'. We could get it
  87. ;; from (recent-keys) & set last-command-event to that, "unclobbering" it, but
  88. ;; this has the disadvantage that if the user types a sequence of different
  89. ;; chars then invokes repeat, only the final char will be inserted. In vi,
  90. ;; the dot command can reinsert the entire most-recently-inserted sequence.
  91. (defvar repeat-message-function nil
  92. "If non-nil, function used by `repeat' command to say what it's doing.
  93. Message is something like \"Repeating command glorp\".
  94. To disable such messages, set this variable to `ignore'. To customize
  95. display, assign a function that takes one string as an arg and displays
  96. it however you want.")
  97. (defcustom repeat-on-final-keystroke t
  98. "Allow `repeat' to re-execute for repeating lastchar of a key sequence.
  99. If this variable is t, `repeat' determines what key sequence
  100. it was invoked by, extracts the final character of that sequence, and
  101. re-executes as many times as that final character is hit; so for example
  102. if `repeat' is bound to C-x z, typing C-x z z z repeats the previous command
  103. 3 times. If this variable is a sequence of characters, then re-execution
  104. only occurs if the final character by which `repeat' was invoked is a
  105. member of that sequence. If this variable is nil, no re-execution occurs."
  106. :group 'convenience
  107. :type '(choice (const :tag "Repeat for all keys" t)
  108. (const :tag "Don't repeat" nil)
  109. (sexp :tag "Repeat for specific keys")))
  110. ;;;;; ****************** HACKS TO THE REST OF EMACS ******************* ;;;;;
  111. ;; The basic strategy is to use last-command, a variable built in to Emacs.
  112. ;; There are 2 issues that complicate this strategy. The first is that
  113. ;; last-command is given a bogus value when any kill command is executed;
  114. ;; this is done to make it easy for `yank-pop' to know that it's being invoked
  115. ;; after a kill command. The second is that the meaning of the command is
  116. ;; often altered by the prefix arg, but although Emacs (19.34) has a
  117. ;; builtin prefix-arg specifying the arg for the next command, as well as a
  118. ;; builtin current-prefix-arg, it has no builtin last-prefix-arg.
  119. ;; There's a builtin (this-command-keys), the return value of which could be
  120. ;; executed with (command-execute), but there's no (last-command-keys).
  121. ;; Using (last-command-keys) if it existed wouldn't be optimal, however,
  122. ;; since it would complicate checking membership in repeat-too-dangerous.
  123. ;; It would of course be trivial to implement last-prefix-arg &
  124. ;; true-last-command by putting something in post-command-hook, but that
  125. ;; entails a performance hit; the approach taken below avoids that.
  126. ;; Coping with strings of self-insert commands gets hairy when they interact
  127. ;; with auto-filling. Most problems are eliminated by remembering what we're
  128. ;; self-inserting, so we only need to get it from the undo information once.
  129. ;; With Emacs 22.2 the variable `last-repeatable-command' stores the
  130. ;; most recently executed command that was not bound to an input event.
  131. ;; `repeat' now repeats that command instead of `real-last-command' to
  132. ;; avoid a "... must be bound to an event with parameters" error.
  133. (defvar repeat-last-self-insert nil
  134. "If last repeated command was `self-insert-command', it inserted this.")
  135. ;; That'll require another keystroke count so we know we're in a string of
  136. ;; repetitions of self-insert commands:
  137. (defvar repeat-num-input-keys-at-self-insert -1
  138. "# key sequences read in Emacs session when `self-insert-command' repeated.")
  139. ;;;;; *************** ANALOGOUS HACKS TO `repeat' ITSELF **************** ;;;;;
  140. ;; That mechanism of checking num-input-keys to figure out what's really
  141. ;; going on can be useful to other commands that need to fine-tune their
  142. ;; interaction with repeat. Instead of requiring them to advise repeat, we
  143. ;; can just defvar the value they need here, & setq it in the repeat command:
  144. (defvar repeat-num-input-keys-at-repeat -1
  145. "# key sequences read in Emacs session when `repeat' last invoked.")
  146. ;; Also, we can assign a name to the test for which that variable is
  147. ;; intended, which thereby documents here how to use it, & makes code that
  148. ;; uses it self-documenting:
  149. (defsubst repeat-is-really-this-command ()
  150. "Return t if this command is happening because user invoked `repeat'.
  151. Usually, when a command is executing, the Emacs builtin variable
  152. `this-command' identifies the command the user invoked. Some commands modify
  153. that variable on the theory they're doing more good than harm; `repeat' does
  154. that, and usually does do more good than harm. However, like all do-gooders,
  155. sometimes `repeat' gets surprising results from its altruism. The value of
  156. this function is always whether the value of `this-command' would've been
  157. 'repeat if `repeat' hadn't modified it."
  158. (= repeat-num-input-keys-at-repeat num-input-keys))
  159. ;; An example of the use of (repeat-is-really-this-command) may still be
  160. ;; available in <http://www.eskimo.com/~seldon/dotemacs.el>; search for
  161. ;; "defun wm-switch-buffer".
  162. ;;;;; ******************* THE REPEAT COMMAND ITSELF ******************* ;;;;;
  163. (defvar repeat-previous-repeated-command nil
  164. "The previous repeated command.")
  165. ;; The following variable counts repeated self-insertions. The idea is
  166. ;; that repeating a self-insertion command and subsequently undoing it
  167. ;; should have almost the same effect as if the characters were inserted
  168. ;; manually. The basic difference is that we leave in one undo-boundary
  169. ;; between the original insertion and its first repetition.
  170. (defvar repeat-undo-count nil
  171. "Number of self-insertions since last `undo-boundary'.")
  172. ;;;###autoload
  173. (defun repeat (repeat-arg)
  174. "Repeat most recently executed command.
  175. With prefix arg, apply new prefix arg to that command; otherwise,
  176. use the prefix arg that was used before (if any).
  177. This command is like the `.' command in the vi editor.
  178. If this command is invoked by a multi-character key sequence, it
  179. can then be repeated by repeating the final character of that
  180. sequence. This behavior can be modified by the global variable
  181. `repeat-on-final-keystroke'.
  182. `repeat' ignores commands bound to input events. Hence the term
  183. \"most recently executed command\" shall be read as \"most
  184. recently executed command not bound to an input event\"."
  185. ;; The most recently executed command could be anything, so surprises could
  186. ;; result if it were re-executed in a context where new dynamically
  187. ;; localized variables were shadowing global variables in a `let' clause in
  188. ;; here. (Remember that GNU Emacs 19 is dynamically localized.)
  189. ;; To avoid that, I tried the `lexical-let' of the Common Lisp extensions,
  190. ;; but that entails a very noticeable performance hit, so instead I use the
  191. ;; "repeat-" prefix, reserved by this package, for *local* variables that
  192. ;; might be visible to re-executed commands, including this function's arg.
  193. (interactive "P")
  194. (when (eq last-repeatable-command 'repeat)
  195. (setq last-repeatable-command repeat-previous-repeated-command))
  196. (cond
  197. ((null last-repeatable-command)
  198. (error "There is nothing to repeat"))
  199. ((eq last-repeatable-command 'mode-exit)
  200. (error "last-repeatable-command is mode-exit & can't be repeated"))
  201. ((memq last-repeatable-command repeat-too-dangerous)
  202. (error "Command %S too dangerous to repeat automatically"
  203. last-repeatable-command)))
  204. (setq this-command last-repeatable-command
  205. repeat-previous-repeated-command last-repeatable-command
  206. repeat-num-input-keys-at-repeat num-input-keys)
  207. (when (null repeat-arg)
  208. (setq repeat-arg last-prefix-arg))
  209. ;; Now determine whether to loop on repeated taps of the final character
  210. ;; of the key sequence that invoked repeat. The Emacs global
  211. ;; last-command-event contains the final character now, but may not still
  212. ;; contain it after the previous command is repeated, so the character
  213. ;; needs to be saved.
  214. (let ((repeat-repeat-char
  215. (if (eq repeat-on-final-keystroke t)
  216. last-command-event
  217. ;; allow only specified final keystrokes
  218. (car (memq last-command-event
  219. (listify-key-sequence
  220. repeat-on-final-keystroke))))))
  221. (if (memq last-repeatable-command '(exit-minibuffer
  222. minibuffer-complete-and-exit
  223. self-insert-and-exit))
  224. (let ((repeat-command (car command-history)))
  225. (repeat-message "Repeating %S" repeat-command)
  226. (eval repeat-command))
  227. (if (null repeat-arg)
  228. (repeat-message "Repeating command %S" last-repeatable-command)
  229. (setq current-prefix-arg repeat-arg)
  230. (repeat-message
  231. "Repeating command %S %S" repeat-arg last-repeatable-command))
  232. (if (eq last-repeatable-command 'self-insert-command)
  233. (let ((insertion
  234. (if (<= (- num-input-keys
  235. repeat-num-input-keys-at-self-insert)
  236. 1)
  237. repeat-last-self-insert
  238. (let ((range (nth 1 buffer-undo-list)))
  239. (condition-case nil
  240. (setq repeat-last-self-insert
  241. (buffer-substring (car range)
  242. (cdr range)))
  243. (error (error "%s %s %s" ;Danger, Will Robinson!
  244. "repeat can't intuit what you"
  245. "inserted before auto-fill"
  246. "clobbered it, sorry")))))))
  247. (setq repeat-num-input-keys-at-self-insert num-input-keys)
  248. ;; If the self-insert had a repeat count, INSERTION
  249. ;; includes that many copies of the same character.
  250. ;; So use just the first character
  251. ;; and repeat it the right number of times.
  252. (setq insertion (substring insertion -1))
  253. (let ((count (prefix-numeric-value repeat-arg))
  254. (i 0))
  255. ;; Run pre- and post-command hooks for self-insertion too.
  256. (run-hooks 'pre-command-hook)
  257. (cond
  258. ((not repeat-undo-count))
  259. ((< repeat-undo-count 20)
  260. ;; Don't make an undo-boundary here.
  261. (setq repeat-undo-count (1+ repeat-undo-count)))
  262. (t
  263. ;; Make an undo-boundary after 20 repetitions only.
  264. (undo-boundary)
  265. (setq repeat-undo-count 1)))
  266. (while (< i count)
  267. (repeat-self-insert insertion)
  268. (setq i (1+ i)))
  269. (run-hooks 'post-command-hook)))
  270. (let ((indirect (indirect-function last-repeatable-command)))
  271. ;; Make each repetition undo separately.
  272. (undo-boundary)
  273. (if (or (stringp indirect)
  274. (vectorp indirect))
  275. ;; Bind real-last-command so that executing the macro does
  276. ;; not alter it. Do the same for last-repeatable-command.
  277. (let ((real-last-command real-last-command)
  278. (last-repeatable-command last-repeatable-command))
  279. (execute-kbd-macro last-repeatable-command))
  280. (run-hooks 'pre-command-hook)
  281. (call-interactively last-repeatable-command)
  282. (run-hooks 'post-command-hook)))))
  283. (when repeat-repeat-char
  284. ;; A simple recursion here gets into trouble with max-lisp-eval-depth
  285. ;; on long sequences of repetitions of a command like `forward-word'
  286. ;; (only 32 repetitions are possible given the default value of 200 for
  287. ;; max-lisp-eval-depth), but if I now locally disable the repeat char I
  288. ;; can iterate indefinitely here around a single level of recursion.
  289. (let (repeat-on-final-keystroke
  290. ;; Bind `undo-inhibit-record-point' to t in order to avoid
  291. ;; recording point in `buffer-undo-list' here. We have to
  292. ;; do this since the command loop does not set the last
  293. ;; position of point thus confusing the point recording
  294. ;; mechanism when inserting or deleting text.
  295. (undo-inhibit-record-point t))
  296. (setq real-last-command 'repeat)
  297. (setq repeat-undo-count 1)
  298. (unwind-protect
  299. (while (let ((evt (read-key)))
  300. ;; For clicks, we need to strip the meta-data to
  301. ;; check the underlying event name.
  302. (eq (or (car-safe evt) evt)
  303. (or (car-safe repeat-repeat-char)
  304. repeat-repeat-char)))
  305. (repeat repeat-arg))
  306. ;; Make sure `repeat-undo-count' is reset.
  307. (setq repeat-undo-count nil))
  308. (setq unread-command-events (list last-input-event))))))
  309. (defun repeat-self-insert (string)
  310. (let ((i 0))
  311. (while (< i (length string))
  312. (let ((last-command-event (aref string i)))
  313. (self-insert-command 1))
  314. (setq i (1+ i)))))
  315. (defun repeat-message (format &rest args)
  316. "Like `message' but displays with `repeat-message-function' if non-nil."
  317. (let ((message (apply 'format format args)))
  318. (if repeat-message-function
  319. (funcall repeat-message-function message)
  320. (message "%s" message))))
  321. ;; OK, there's one situation left where that doesn't work correctly: when the
  322. ;; most recent self-insertion provoked an auto-fill. The problem is that
  323. ;; unraveling the undo information after an auto-fill is too hard, since all
  324. ;; kinds of stuff can get in there as a result of comment prefixes etc. It'd
  325. ;; be possible to advise do-auto-fill to record the most recent
  326. ;; self-insertion before it does its thing, but that's a performance hit on
  327. ;; auto-fill, which already has performance problems; so it's better to just
  328. ;; leave it like this. If text didn't provoke an auto-fill when the user
  329. ;; typed it, this'll correctly repeat its self-insertion, even if the
  330. ;; repetition does cause auto-fill.
  331. ;; If you wanted perfection, probably it'd be necessary to hack do-auto-fill
  332. ;; into 2 functions, maybe-do-auto-fill & really-do-auto-fill, because only
  333. ;; really-do-auto-fill should be advised. As things are, either the undo
  334. ;; information would need to be scanned on every do-auto-fill invocation, or
  335. ;; the code at the top of do-auto-fill deciding whether filling is necessary
  336. ;; would need to be duplicated in the advice, wasting execution time when
  337. ;; filling does turn out to be necessary.
  338. ;; I thought maybe this story had a moral, something about functional
  339. ;; decomposition; but now I'm not even sure of that, since a function
  340. ;; call per se is a performance hit, & even the code that would
  341. ;; correspond to really-do-auto-fill has performance problems that
  342. ;; can make it necessary to stop typing while Emacs catches up.
  343. ;; Maybe the real moral is that perfection is a chimera.
  344. ;; Ah, hell, it's all going to fall into a black hole someday anyway.
  345. ;;;;; ************************* EMACS CONTROL ************************* ;;;;;
  346. (provide 'repeat)
  347. ;;; repeat.el ends here