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