`recent_keys' now holds last 300 keystrokes, not 100.
[bpt/emacs.git] / lisp / edmacro.el
CommitLineData
e5167999
ER
1;;; edmacro.el --- keyboard macro editor
2
e91081eb 3;; Copyright (C) 1993, 1994, 2001, 2002, 2003, 2004,
409cc4a3 4;; 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
9750e079 5
629d4dcd
RS
6;; Author: Dave Gillespie <daveg@synaptics.com>
7;; Maintainer: Dave Gillespie <daveg@synaptics.com>
8;; Version: 2.01
e9571d2a 9;; Keywords: abbrev
66b3ecce
DL
10
11;; This file is part of GNU Emacs.
12
eb3fa2cf 13;; GNU Emacs is free software: you can redistribute it and/or modify
66b3ecce 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.
66b3ecce
DL
17
18;; GNU Emacs is distributed in the hope that it will be useful,
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/>.
66b3ecce 25
e5167999 26;;; Commentary:
66b3ecce 27
629d4dcd
RS
28;;; Usage:
29;;
b680abcb 30;; The `C-x C-k e' (`edit-kbd-macro') command edits a keyboard macro
629d4dcd
RS
31;; in a special buffer. It prompts you to type a key sequence,
32;; which should be one of:
33;;
71296446 34;; * RET or `C-x e' (call-last-kbd-macro), to edit the most
629d4dcd
RS
35;; recently defined keyboard macro.
36;;
37;; * `M-x' followed by a command name, to edit a named command
38;; whose definition is a keyboard macro.
39;;
40;; * `C-h l' (view-lossage), to edit the 100 most recent keystrokes
41;; and install them as the "current" macro.
42;;
43;; * any key sequence whose definition is a keyboard macro.
44;;
45;; This file includes a version of `insert-kbd-macro' that uses the
46;; more readable format defined by these routines.
47;;
48;; Also, the `read-kbd-macro' command parses the region as
49;; a keyboard macro, and installs it as the "current" macro.
50;; This and `format-kbd-macro' can also be called directly as
51;; Lisp functions.
52
53;; Type `C-h m', or see the documentation for `edmacro-mode' below,
54;; for information about the format of written keyboard macros.
55
56;; `edit-kbd-macro' formats the macro with one command per line,
57;; including the command names as comments on the right. If the
58;; formatter gets confused about which keymap was used for the
59;; characters, the command-name comments will be wrong but that
60;; won't hurt anything.
61
62;; With a prefix argument, `edit-kbd-macro' will format the
63;; macro in a more concise way that omits the comments.
64
65;; This package requires GNU Emacs 19 or later, and daveg's CL
66;; package 2.02 or later. (CL 2.02 comes standard starting with
67;; Emacs 19.18.) This package does not work with Emacs 18 or
68;; Lucid Emacs.
e5167999
ER
69
70;;; Code:
66b3ecce 71\f
c31afdbd
RS
72(eval-when-compile
73 (require 'cl))
629d4dcd 74
70e2ea11
KS
75(require 'kmacro)
76
66b3ecce
DL
77;;; The user-level commands for editing macros.
78
629d4dcd
RS
79;;;###autoload
80(defvar edmacro-eight-bits nil
81 "*Non-nil if edit-kbd-macro should leave 8-bit characters intact.
82Default nil means to write characters above \\177 in octal notation.")
83
84(defvar edmacro-mode-map nil)
85(unless edmacro-mode-map
86 (setq edmacro-mode-map (make-sparse-keymap))
87 (define-key edmacro-mode-map "\C-c\C-c" 'edmacro-finish-edit)
88 (define-key edmacro-mode-map "\C-c\C-q" 'edmacro-insert-key))
89
88c4981a
RS
90(defvar edmacro-store-hook)
91(defvar edmacro-finish-hook)
92(defvar edmacro-original-buffer)
93
f9f9507e 94;;;###autoload
629d4dcd
RS
95(defun edit-kbd-macro (keys &optional prefix finish-hook store-hook)
96 "Edit a keyboard macro.
97At the prompt, type any key sequence which is bound to a keyboard macro.
98Or, type `C-x e' or RET to edit the last keyboard macro, `C-h l' to edit
99the last 100 keystrokes as a keyboard macro, or `M-x' to edit a macro by
100its command name.
101With a prefix argument, format the macro in a more concise way."
102 (interactive "kKeyboard macro to edit (C-x e, M-x, C-h l, or keys): \nP")
103 (when keys
104 (let ((cmd (if (arrayp keys) (key-binding keys) keys))
70e2ea11
KS
105 (mac nil) (mac-counter nil) (mac-format nil)
106 kmacro)
629d4dcd
RS
107 (cond (store-hook
108 (setq mac keys)
109 (setq cmd nil))
71296446 110 ((or (memq cmd '(call-last-kbd-macro kmacro-call-macro
059aa0a7 111 kmacro-end-or-call-macro kmacro-end-and-call-macro))
629d4dcd
RS
112 (member keys '("\r" [return])))
113 (or last-kbd-macro
114 (y-or-n-p "No keyboard macro defined. Create one? ")
115 (keyboard-quit))
116 (setq mac (or last-kbd-macro ""))
70e2ea11 117 (setq keys nil)
629d4dcd
RS
118 (setq cmd 'last-kbd-macro))
119 ((eq cmd 'execute-extended-command)
120 (setq cmd (read-command "Name of keyboard macro to edit: "))
ef8e50b1
RS
121 (if (string-equal cmd "")
122 (error "No command name given"))
70e2ea11 123 (setq keys nil)
629d4dcd 124 (setq mac (symbol-function cmd)))
fcd66424 125 ((memq cmd '(view-lossage electric-view-lossage))
629d4dcd 126 (setq mac (recent-keys))
70e2ea11 127 (setq keys nil)
629d4dcd 128 (setq cmd 'last-kbd-macro))
a8e1fefa
KH
129 ((null cmd)
130 (error "Key sequence %s is not defined" (key-description keys)))
629d4dcd
RS
131 ((symbolp cmd)
132 (setq mac (symbol-function cmd)))
133 (t
134 (setq mac cmd)
135 (setq cmd nil)))
70e2ea11
KS
136 (when (setq kmacro (kmacro-extract-lambda mac))
137 (setq mac (car kmacro)
138 mac-counter (nth 1 kmacro)
139 mac-format (nth 2 kmacro)))
629d4dcd 140 (unless (arrayp mac)
a8e1fefa
KH
141 (error "Key sequence %s is not a keyboard macro"
142 (key-description keys)))
629d4dcd
RS
143 (message "Formatting keyboard macro...")
144 (let* ((oldbuf (current-buffer))
145 (mmac (edmacro-fix-menu-commands mac))
146 (fmt (edmacro-format-keys mmac 1))
147 (fmtv (edmacro-format-keys mmac (not prefix)))
148 (buf (get-buffer-create "*Edit Macro*")))
149 (message "Formatting keyboard macro...done")
150 (switch-to-buffer buf)
151 (kill-all-local-variables)
152 (use-local-map edmacro-mode-map)
153 (setq buffer-read-only nil)
154 (setq major-mode 'edmacro-mode)
155 (setq mode-name "Edit Macro")
156 (set (make-local-variable 'edmacro-original-buffer) oldbuf)
157 (set (make-local-variable 'edmacro-finish-hook) finish-hook)
158 (set (make-local-variable 'edmacro-store-hook) store-hook)
159 (erase-buffer)
160 (insert ";; Keyboard Macro Editor. Press C-c C-c to finish; "
161 "press C-x k RET to cancel.\n")
162 (insert ";; Original keys: " fmt "\n")
163 (unless store-hook
164 (insert "\nCommand: " (if cmd (symbol-name cmd) "none") "\n")
70e2ea11
KS
165 (let ((gkeys (where-is-internal (or cmd mac) '(keymap))))
166 (if (and keys (not (member keys gkeys)))
167 (setq gkeys (cons keys gkeys)))
168 (if gkeys
169 (while gkeys
170 (insert "Key: " (edmacro-format-keys (pop gkeys) 1) "\n"))
171 (insert "Key: none\n")))
172 (when (and mac-counter mac-format)
173 (insert (format "Counter: %d\nFormat: \"%s\"\n" mac-counter mac-format))))
629d4dcd
RS
174 (insert "\nMacro:\n\n")
175 (save-excursion
176 (insert fmtv "\n"))
177 (recenter '(4))
178 (when (eq mac mmac)
179 (set-buffer-modified-p nil))
180 (run-hooks 'edmacro-format-hook)))))
181
182;;; The next two commands are provided for convenience and backward
183;;; compatibility.
184
185;;;###autoload
186(defun edit-last-kbd-macro (&optional prefix)
66b3ecce
DL
187 "Edit the most recently defined keyboard macro."
188 (interactive "P")
629d4dcd 189 (edit-kbd-macro 'call-last-kbd-macro prefix))
66b3ecce 190
f9f9507e 191;;;###autoload
629d4dcd
RS
192(defun edit-named-kbd-macro (&optional prefix)
193 "Edit a keyboard macro which has been given a name by `name-last-kbd-macro'."
194 (interactive "P")
195 (edit-kbd-macro 'execute-extended-command prefix))
66b3ecce 196
f9f9507e 197;;;###autoload
629d4dcd 198(defun read-kbd-macro (start &optional end)
66b3ecce 199 "Read the region as a keyboard macro definition.
052bdd09 200The region is interpreted as spelled-out keystrokes, e.g., \"M-x abc RET\".
629d4dcd
RS
201See documentation for `edmacro-mode' for details.
202Leading/trailing \"C-x (\" and \"C-x )\" in the text are allowed and ignored.
66b3ecce
DL
203The resulting macro is installed as the \"current\" keyboard macro.
204
629d4dcd
RS
205In Lisp, may also be called with a single STRING argument in which case
206the result is returned rather than being installed as the current macro.
207The result will be a string if possible, otherwise an event vector.
208Second argument NEED-VECTOR means to return an event vector always."
66b3ecce 209 (interactive "r")
629d4dcd
RS
210 (if (stringp start)
211 (edmacro-parse-keys start end)
212 (setq last-kbd-macro (edmacro-parse-keys (buffer-substring start end)))))
66b3ecce 213
629d4dcd
RS
214;;;###autoload
215(defun format-kbd-macro (&optional macro verbose)
216 "Return the keyboard macro MACRO as a human-readable string.
217This string is suitable for passing to `read-kbd-macro'.
218Second argument VERBOSE means to put one command per line with comments.
219If VERBOSE is `1', put everything on one line. If VERBOSE is omitted
220or nil, use a compact 80-column format."
221 (and macro (symbolp macro) (setq macro (symbol-function macro)))
222 (edmacro-format-keys (or macro last-kbd-macro) verbose))
66b3ecce 223\f
629d4dcd 224;;; Commands for *Edit Macro* buffer.
66b3ecce
DL
225
226(defun edmacro-finish-edit ()
227 (interactive)
629d4dcd
RS
228 (unless (eq major-mode 'edmacro-mode)
229 (error
230 "This command is valid only in buffers created by `edit-kbd-macro'"))
231 (run-hooks 'edmacro-finish-hook)
232 (let ((cmd nil) (keys nil) (no-keys nil)
70e2ea11 233 (mac-counter nil) (mac-format nil) (kmacro nil)
629d4dcd
RS
234 (top (point-min)))
235 (goto-char top)
236 (let ((case-fold-search nil))
237 (while (cond ((looking-at "[ \t]*\\($\\|;;\\|REM[ \t\n]\\)")
238 t)
239 ((looking-at "Command:[ \t]*\\([^ \t\n]*\\)[ \t]*$")
240 (when edmacro-store-hook
241 (error "\"Command\" line not allowed in this context"))
242 (let ((str (buffer-substring (match-beginning 1)
243 (match-end 1))))
244 (unless (equal str "")
c31afdbd 245 (setq cmd (and (not (equal str "none"))
629d4dcd
RS
246 (intern str)))
247 (and (fboundp cmd) (not (arrayp (symbol-function cmd)))
70e2ea11 248 (not (setq kmacro (get cmd 'kmacro)))
629d4dcd
RS
249 (not (y-or-n-p
250 (format "Command %s is already defined; %s"
251 cmd "proceed? ")))
252 (keyboard-quit))))
253 t)
254 ((looking-at "Key:\\(.*\\)$")
255 (when edmacro-store-hook
256 (error "\"Key\" line not allowed in this context"))
257 (let ((key (edmacro-parse-keys
258 (buffer-substring (match-beginning 1)
259 (match-end 1)))))
260 (unless (equal key "")
c31afdbd 261 (if (equal key "none")
629d4dcd
RS
262 (setq no-keys t)
263 (push key keys)
264 (let ((b (key-binding key)))
265 (and b (commandp b) (not (arrayp b))
70e2ea11 266 (not (kmacro-extract-lambda b))
629d4dcd 267 (or (not (fboundp b))
b680abcb
LT
268 (not (or (arrayp (symbol-function b))
269 (get b 'kmacro))))
629d4dcd
RS
270 (not (y-or-n-p
271 (format "Key %s is already defined; %s"
272 (edmacro-format-keys key 1)
273 "proceed? ")))
274 (keyboard-quit))))))
275 t)
70e2ea11
KS
276 ((looking-at "Counter:[ \t]*\\([^ \t\n]*\\)[ \t]*$")
277 (when edmacro-store-hook
278 (error "\"Counter\" line not allowed in this context"))
279 (let ((str (buffer-substring (match-beginning 1)
280 (match-end 1))))
281 (unless (equal str "")
027a4b6b 282 (setq mac-counter (string-to-number str))))
70e2ea11
KS
283 t)
284 ((looking-at "Format:[ \t]*\"\\([^\n]*\\)\"[ \t]*$")
285 (when edmacro-store-hook
286 (error "\"Format\" line not allowed in this context"))
287 (let ((str (buffer-substring (match-beginning 1)
288 (match-end 1))))
289 (unless (equal str "")
290 (setq mac-format str)))
291 t)
629d4dcd
RS
292 ((looking-at "Macro:[ \t\n]*")
293 (goto-char (match-end 0))
294 nil)
295 ((eobp) nil)
296 (t (error "Expected a `Macro:' line")))
297 (forward-line 1))
298 (setq top (point)))
299 (let* ((buf (current-buffer))
300 (str (buffer-substring top (point-max)))
301 (modp (buffer-modified-p))
302 (obuf edmacro-original-buffer)
303 (store-hook edmacro-store-hook)
304 (finish-hook edmacro-finish-hook))
305 (unless (or cmd keys store-hook (equal str ""))
306 (error "No command name or keys specified"))
307 (when modp
308 (when (buffer-name obuf)
309 (set-buffer obuf))
310 (message "Compiling keyboard macro...")
311 (let ((mac (edmacro-parse-keys str)))
312 (message "Compiling keyboard macro...done")
313 (if store-hook
314 (funcall store-hook mac)
315 (when (eq cmd 'last-kbd-macro)
316 (setq last-kbd-macro (and (> (length mac) 0) mac))
317 (setq cmd nil))
318 (when cmd
319 (if (= (length mac) 0)
320 (fmakunbound cmd)
70e2ea11
KS
321 (fset cmd
322 (if (and mac-counter mac-format)
323 (kmacro-lambda-form mac mac-counter mac-format)
324 mac))))
629d4dcd
RS
325 (if no-keys
326 (when cmd
3f5e6d79 327 (loop for key in (where-is-internal cmd '(keymap)) do
629d4dcd
RS
328 (global-unset-key key)))
329 (when keys
330 (if (= (length mac) 0)
331 (loop for key in keys do (global-unset-key key))
332 (loop for key in keys do
70e2ea11
KS
333 (global-set-key key
334 (or cmd
335 (if (and mac-counter mac-format)
336 (kmacro-lambda-form mac mac-counter mac-format)
337 mac))))))))))
629d4dcd
RS
338 (kill-buffer buf)
339 (when (buffer-name obuf)
340 (switch-to-buffer obuf))
341 (when finish-hook
342 (funcall finish-hook)))))
343
344(defun edmacro-insert-key (key)
345 "Insert the written name of a key in the buffer."
346 (interactive "kKey to insert: ")
347 (if (bolp)
348 (insert (edmacro-format-keys key t) "\n")
349 (insert (edmacro-format-keys key) " ")))
66b3ecce
DL
350
351(defun edmacro-mode ()
629d4dcd
RS
352 "\\<edmacro-mode-map>Keyboard Macro Editing mode. Press
353\\[edmacro-finish-edit] to save and exit.
052bdd09 354To abort the edit, just kill this buffer with \\[kill-buffer] RET.
66b3ecce 355
629d4dcd
RS
356Press \\[edmacro-insert-key] to insert the name of any key by typing the key.
357
358The editing buffer contains a \"Command:\" line and any number of
359\"Key:\" lines at the top. These are followed by a \"Macro:\" line
360and the macro itself as spelled-out keystrokes: `C-x C-f foo RET'.
361
362The \"Command:\" line specifies the command name to which the macro
363is bound, or \"none\" for no command name. Write \"last-kbd-macro\"
364to refer to the current keyboard macro (as used by \\[call-last-kbd-macro]).
365
366The \"Key:\" lines specify key sequences to which the macro is bound,
367or \"none\" for no key bindings.
368
369You can edit these lines to change the places where the new macro
370is stored.
371
372
373Format of keyboard macros during editing:
374
375Text is divided into \"words\" separated by whitespace. Except for
376the words described below, the characters of each word go directly
377as characters of the macro. The whitespace that separates words
378is ignored. Whitespace in the macro must be written explicitly,
379as in \"foo SPC bar RET\".
380
381 * The special words RET, SPC, TAB, DEL, LFD, ESC, and NUL represent
382 special control characters. The words must be written in uppercase.
383
384 * A word in angle brackets, e.g., <return>, <down>, or <f1>, represents
385 a function key. (Note that in the standard configuration, the
386 function key <return> and the control key RET are synonymous.)
387 You can use angle brackets on the words RET, SPC, etc., but they
388 are not required there.
389
390 * Keys can be written by their ASCII code, using a backslash followed
391 by up to six octal digits. This is the only way to represent keys
392 with codes above \\377.
393
394 * One or more prefixes M- (meta), C- (control), S- (shift), A- (alt),
395 H- (hyper), and s- (super) may precede a character or key notation.
396 For function keys, the prefixes may go inside or outside of the
397 brackets: C-<down> = <C-down>. The prefixes may be written in
398 any order: M-C-x = C-M-x.
399
400 Prefixes are not allowed on multi-key words, e.g., C-abc, except
401 that the Meta prefix is allowed on a sequence of digits and optional
402 minus sign: M--123 = M-- M-1 M-2 M-3.
403
404 * The `^' notation for control characters also works: ^M = C-m.
405
406 * Double angle brackets enclose command names: <<next-line>> is
407 shorthand for M-x next-line RET.
408
409 * Finally, REM or ;; causes the rest of the line to be ignored as a
410 comment.
411
412Any word may be prefixed by a multiplier in the form of a decimal
413number and `*': 3*<right> = <right> <right> <right>, and
41410*foo = foofoofoofoofoofoofoofoofoofoo.
415
416Multiple text keys can normally be strung together to form a word,
417but you may need to add whitespace if the word would look like one
418of the above notations: `; ; ;' is a keyboard macro with three
419semicolons, but `;;;' is a comment. Likewise, `\\ 1 2 3' is four
420keys but `\\123' is a single key written in octal, and `< right >'
421is seven keys but `<right>' is a single function key. When in
422doubt, use whitespace."
66b3ecce 423 (interactive)
629d4dcd 424 (error "This mode can be enabled only by `edit-kbd-macro'"))
66b3ecce 425(put 'edmacro-mode 'mode-class 'special)
629d4dcd
RS
426\f
427;;; Formatting a keyboard macro as human-readable text.
66b3ecce 428
629d4dcd
RS
429(defun edmacro-format-keys (macro &optional verbose)
430 (setq macro (edmacro-fix-menu-commands macro))
6db93fd9 431 (let* ((maps (current-active-maps))
629d4dcd
RS
432 (pkeys '(end-macro ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?- ?\C-u
433 ?\M-- ?\M-0 ?\M-1 ?\M-2 ?\M-3 ?\M-4 ?\M-5 ?\M-6
434 ?\M-7 ?\M-8 ?\M-9))
435 (mdigs (nthcdr 13 pkeys))
436 (maxkey (if edmacro-eight-bits 255 127))
437 (case-fold-search nil)
438 (res-words '("NUL" "TAB" "LFD" "RET" "ESC" "SPC" "DEL" "REM"))
439 (rest-mac (vconcat macro [end-macro]))
440 (res "")
441 (len 0)
442 (one-line (eq verbose 1)))
443 (if one-line (setq verbose nil))
444 (when (stringp macro)
445 (loop for i below (length macro) do
446 (when (>= (aref rest-mac i) 128)
a9b8cb16 447 (incf (aref rest-mac i) (- ?\M-\^@ 128)))))
629d4dcd
RS
448 (while (not (eq (aref rest-mac 0) 'end-macro))
449 (let* ((prefix
450 (or (and (integerp (aref rest-mac 0))
451 (memq (aref rest-mac 0) mdigs)
c31afdbd 452 (memq (key-binding (edmacro-subseq rest-mac 0 1))
629d4dcd
RS
453 '(digit-argument negative-argument))
454 (let ((i 1))
455 (while (memq (aref rest-mac i) (cdr mdigs))
456 (incf i))
457 (and (not (memq (aref rest-mac i) pkeys))
6b61353c 458 (prog1 (vconcat "M-" (edmacro-subseq rest-mac 0 i) " ")
c31afdbd 459 (callf edmacro-subseq rest-mac i)))))
629d4dcd
RS
460 (and (eq (aref rest-mac 0) ?\C-u)
461 (eq (key-binding [?\C-u]) 'universal-argument)
462 (let ((i 1))
463 (while (eq (aref rest-mac i) ?\C-u)
464 (incf i))
465 (and (not (memq (aref rest-mac i) pkeys))
466 (prog1 (loop repeat i concat "C-u ")
c31afdbd 467 (callf edmacro-subseq rest-mac i)))))
629d4dcd
RS
468 (and (eq (aref rest-mac 0) ?\C-u)
469 (eq (key-binding [?\C-u]) 'universal-argument)
470 (let ((i 1))
471 (when (eq (aref rest-mac i) ?-)
472 (incf i))
473 (while (memq (aref rest-mac i)
474 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9))
475 (incf i))
476 (and (not (memq (aref rest-mac i) pkeys))
6b61353c 477 (prog1 (vconcat "C-u " (edmacro-subseq rest-mac 1 i) " ")
c31afdbd 478 (callf edmacro-subseq rest-mac i)))))))
629d4dcd
RS
479 (bind-len (apply 'max 1
480 (loop for map in maps
481 for b = (lookup-key map rest-mac)
482 when b collect b)))
c31afdbd 483 (key (edmacro-subseq rest-mac 0 bind-len))
629d4dcd
RS
484 (fkey nil) tlen tkey
485 (bind (or (loop for map in maps for b = (lookup-key map key)
486 thereis (and (not (integerp b)) b))
c40bb1ba 487 (and (setq fkey (lookup-key local-function-key-map rest-mac))
c31afdbd 488 (setq tlen fkey tkey (edmacro-subseq rest-mac 0 tlen)
c40bb1ba 489 fkey (lookup-key local-function-key-map tkey))
629d4dcd
RS
490 (loop for map in maps
491 for b = (lookup-key map fkey)
492 when (and (not (integerp b)) b)
493 do (setq bind-len tlen key tkey)
494 and return b
495 finally do (setq fkey nil)))))
496 (first (aref key 0))
497 (text (loop for i from bind-len below (length rest-mac)
498 for ch = (aref rest-mac i)
499 while (and (integerp ch)
500 (> ch 32) (< ch maxkey) (/= ch 92)
501 (eq (key-binding (char-to-string ch))
502 'self-insert-command)
503 (or (> i (- (length rest-mac) 2))
504 (not (eq ch (aref rest-mac (+ i 1))))
505 (not (eq ch (aref rest-mac (+ i 2))))))
506 finally return i))
507 desc)
508 (if (stringp bind) (setq bind nil))
509 (cond ((and (eq bind 'self-insert-command) (not prefix)
510 (> text 1) (integerp first)
511 (> first 32) (<= first maxkey) (/= first 92)
512 (progn
513 (if (> text 30) (setq text 30))
c31afdbd 514 (setq desc (concat (edmacro-subseq rest-mac 0 text)))
629d4dcd
RS
515 (when (string-match "^[ACHMsS]-." desc)
516 (setq text 2)
517 (callf substring desc 0 2))
518 (not (string-match
519 "^;;\\|^<.*>$\\|^\\\\[0-9]+$\\|^[0-9]+\\*."
520 desc))))
521 (when (or (string-match "^\\^.$" desc)
522 (member desc res-words))
523 (setq desc (mapconcat 'char-to-string desc " ")))
524 (when verbose
525 (setq bind (format "%s * %d" bind text)))
526 (setq bind-len text))
527 ((and (eq bind 'execute-extended-command)
528 (> text bind-len)
529 (memq (aref rest-mac text) '(return 13))
530 (progn
c31afdbd 531 (setq desc (concat (edmacro-subseq rest-mac bind-len text)))
629d4dcd
RS
532 (commandp (intern-soft desc))))
533 (if (commandp (intern-soft desc)) (setq bind desc))
534 (setq desc (format "<<%s>>" desc))
535 (setq bind-len (1+ text)))
536 (t
537 (setq desc (mapconcat
538 (function
539 (lambda (ch)
540 (cond
541 ((integerp ch)
542 (concat
543 (loop for pf across "ACHMsS"
a9b8cb16
KH
544 for bit in '(?\A-\^@ ?\C-\^@ ?\H-\^@
545 ?\M-\^@ ?\s-\^@ ?\S-\^@)
546 when (/= (logand ch bit) 0)
629d4dcd
RS
547 concat (format "%c-" pf))
548 (let ((ch2 (logand ch (1- (lsh 1 18)))))
549 (cond ((<= ch2 32)
550 (case ch2
551 (0 "NUL") (9 "TAB") (10 "LFD")
552 (13 "RET") (27 "ESC") (32 "SPC")
553 (t
554 (format "C-%c"
555 (+ (if (<= ch2 26) 96 64)
556 ch2)))))
557 ((= ch2 127) "DEL")
558 ((<= ch2 maxkey) (char-to-string ch2))
559 (t (format "\\%o" ch2))))))
560 ((symbolp ch)
561 (format "<%s>" ch))
562 (t
563 (error "Unrecognized item in macro: %s" ch)))))
564 (or fkey key) " "))))
6b61353c
KH
565 (if prefix
566 (setq desc (concat (edmacro-sanitize-for-string prefix) desc)))
629d4dcd
RS
567 (unless (string-match " " desc)
568 (let ((times 1) (pos bind-len))
c31afdbd
RS
569 (while (not (edmacro-mismatch rest-mac rest-mac
570 0 bind-len pos (+ bind-len pos)))
629d4dcd
RS
571 (incf times)
572 (incf pos bind-len))
573 (when (> times 1)
574 (setq desc (format "%d*%s" times desc))
575 (setq bind-len (* bind-len times)))))
c31afdbd 576 (setq rest-mac (edmacro-subseq rest-mac bind-len))
629d4dcd
RS
577 (if verbose
578 (progn
579 (unless (equal res "") (callf concat res "\n"))
580 (callf concat res desc)
581 (when (and bind (or (stringp bind) (symbolp bind)))
582 (callf concat res
583 (make-string (max (- 3 (/ (length desc) 8)) 1) 9)
584 ";; " (if (stringp bind) bind (symbol-name bind))))
585 (setq len 0))
586 (if (and (> (+ len (length desc) 2) 72) (not one-line))
587 (progn
588 (callf concat res "\n ")
589 (setq len 1))
590 (unless (equal res "")
591 (callf concat res " ")
592 (incf len)))
593 (callf concat res desc)
594 (incf len (length desc)))))
595 res))
596
c31afdbd
RS
597(defun edmacro-mismatch (cl-seq1 cl-seq2 cl-start1 cl-end1 cl-start2 cl-end2)
598 "Compare SEQ1 with SEQ2, return index of first mismatching element.
599Return nil if the sequences match. If one sequence is a prefix of the
600other, the return value indicates the end of the shorted sequence."
601 (let (cl-test cl-test-not cl-key cl-from-end)
602 (or cl-end1 (setq cl-end1 (length cl-seq1)))
603 (or cl-end2 (setq cl-end2 (length cl-seq2)))
604 (if cl-from-end
605 (progn
606 (while (and (< cl-start1 cl-end1) (< cl-start2 cl-end2)
607 (cl-check-match (elt cl-seq1 (1- cl-end1))
608 (elt cl-seq2 (1- cl-end2))))
609 (setq cl-end1 (1- cl-end1) cl-end2 (1- cl-end2)))
610 (and (or (< cl-start1 cl-end1) (< cl-start2 cl-end2))
611 (1- cl-end1)))
612 (let ((cl-p1 (and (listp cl-seq1) (nthcdr cl-start1 cl-seq1)))
613 (cl-p2 (and (listp cl-seq2) (nthcdr cl-start2 cl-seq2))))
614 (while (and (< cl-start1 cl-end1) (< cl-start2 cl-end2)
615 (cl-check-match (if cl-p1 (car cl-p1)
616 (aref cl-seq1 cl-start1))
617 (if cl-p2 (car cl-p2)
618 (aref cl-seq2 cl-start2))))
619 (setq cl-p1 (cdr cl-p1) cl-p2 (cdr cl-p2)
620 cl-start1 (1+ cl-start1) cl-start2 (1+ cl-start2)))
621 (and (or (< cl-start1 cl-end1) (< cl-start2 cl-end2))
622 cl-start1)))))
623
624(defun edmacro-subseq (seq start &optional end)
625 "Return the subsequence of SEQ from START to END.
626If END is omitted, it defaults to the length of the sequence.
627If START or END is negative, it counts from the end."
628 (if (stringp seq) (substring seq start end)
629 (let (len)
630 (and end (< end 0) (setq end (+ end (setq len (length seq)))))
631 (if (< start 0) (setq start (+ start (or len (setq len (length seq))))))
632 (cond ((listp seq)
633 (if (> start 0) (setq seq (nthcdr start seq)))
634 (if end
635 (let ((res nil))
636 (while (>= (setq end (1- end)) start)
39223437 637 (push (pop seq) res))
c31afdbd
RS
638 (nreverse res))
639 (copy-sequence seq)))
640 (t
641 (or end (setq end (or len (length seq))))
642 (let ((res (make-vector (max (- end start) 0) nil))
643 (i 0))
644 (while (< start end)
645 (aset res i (aref seq start))
646 (setq i (1+ i) start (1+ start)))
647 res))))))
648
6b61353c
KH
649(defun edmacro-sanitize-for-string (seq)
650 "Convert a key sequence vector into a string.
651The string represents the same events; Meta is indicated by bit 7.
652This function assumes that the events can be stored in a string."
653 (setq seq (copy-sequence seq))
654 (loop for i below (length seq) do
b680abcb 655 (when (logand (aref seq i) 128)
6b61353c
KH
656 (setf (aref seq i) (logand (aref seq i) 127))))
657 seq)
658
5cfe1cec
RS
659(defun edmacro-fix-menu-commands (macro &optional noerror)
660 (if (vectorp macro)
661 (let (result)
662 ;; Make a list of the elements.
663 (setq macro (append macro nil))
664 (dolist (ev macro)
665 (cond ((atom ev)
666 (push ev result))
667 ((eq (car ev) 'help-echo))
d2f00838 668 ((eq (car ev) 'switch-frame))
5cfe1cec
RS
669 ((equal ev '(menu-bar))
670 (push 'menu-bar result))
671 ((equal (cadadr ev) '(menu-bar))
672 (push (vector 'menu-bar (car ev)) result))
629d4dcd
RS
673 ;; It would be nice to do pop-up menus, too, but not enough
674 ;; info is recorded in macros to make this possible.
5cfe1cec
RS
675 (noerror
676 ;; Just ignore mouse events.
677 nil)
629d4dcd
RS
678 (t
679 (error "Macros with mouse clicks are not %s"
680 "supported by this command"))))
5cfe1cec
RS
681 ;; Reverse them again and make them back into a vector.
682 (vconcat (nreverse result)))
683 macro))
629d4dcd
RS
684\f
685;;; Parsing a human-readable keyboard macro.
686
687(defun edmacro-parse-keys (string &optional need-vector)
688 (let ((case-fold-search nil)
bf2e3fa7 689 (len (length string)) ; We won't alter string in the loop below.
629d4dcd
RS
690 (pos 0)
691 (res []))
bf2e3fa7 692 (while (and (< pos len)
629d4dcd 693 (string-match "[^ \t\n\f]+" string pos))
bf2e3fa7
CY
694 (let* ((word-beg (match-beginning 0))
695 (word-end (match-end 0))
696 (word (substring string word-beg len))
697 (times 1)
698 key)
699 ;; Try to catch events of the form "<as df>".
a6e05096 700 (if (string-match "^<[^ <>\t\n\f][^>\t\n\f]*>" word)
bf2e3fa7
CY
701 (setq word (match-string 0 word)
702 pos (+ word-beg (match-end 0)))
703 (setq word (substring string word-beg word-end)
704 pos word-end))
629d4dcd 705 (when (string-match "\\([0-9]+\\)\\*." word)
027a4b6b 706 (setq times (string-to-number (substring word 0 (match-end 1))))
629d4dcd
RS
707 (setq word (substring word (1+ (match-end 1)))))
708 (cond ((string-match "^<<.+>>$" word)
709 (setq key (vconcat (if (eq (key-binding [?\M-x])
710 'execute-extended-command)
711 [?\M-x]
712 (or (car (where-is-internal
713 'execute-extended-command))
714 [?\M-x]))
715 (substring word 2 -2) "\r")))
716 ((and (string-match "^\\(\\([ACHMsS]-\\)*\\)<\\(.+\\)>$" word)
717 (progn
718 (setq word (concat (substring word (match-beginning 1)
719 (match-end 1))
720 (substring word (match-beginning 3)
721 (match-end 3))))
722 (not (string-match
723 "\\<\\(NUL\\|RET\\|LFD\\|ESC\\|SPC\\|DEL\\)$"
724 word))))
725 (setq key (list (intern word))))
726 ((or (equal word "REM") (string-match "^;;" word))
727 (setq pos (string-match "$" string pos)))
728 (t
729 (let ((orig-word word) (prefix 0) (bits 0))
730 (while (string-match "^[ACHMsS]-." word)
a9b8cb16
KH
731 (incf bits (cdr (assq (aref word 0)
732 '((?A . ?\A-\^@) (?C . ?\C-\^@)
733 (?H . ?\H-\^@) (?M . ?\M-\^@)
734 (?s . ?\s-\^@) (?S . ?\S-\^@)))))
629d4dcd
RS
735 (incf prefix 2)
736 (callf substring word 2))
737 (when (string-match "^\\^.$" word)
a9b8cb16 738 (incf bits ?\C-\^@)
629d4dcd
RS
739 (incf prefix)
740 (callf substring word 1))
741 (let ((found (assoc word '(("NUL" . "\0") ("RET" . "\r")
742 ("LFD" . "\n") ("TAB" . "\t")
743 ("ESC" . "\e") ("SPC" . " ")
744 ("DEL" . "\177")))))
745 (when found (setq word (cdr found))))
746 (when (string-match "^\\\\[0-7]+$" word)
747 (loop for ch across word
748 for n = 0 then (+ (* n 8) ch -48)
749 finally do (setq word (vector n))))
750 (cond ((= bits 0)
751 (setq key word))
a9b8cb16 752 ((and (= bits ?\M-\^@) (stringp word)
629d4dcd
RS
753 (string-match "^-?[0-9]+$" word))
754 (setq key (loop for x across word collect (+ x bits))))
755 ((/= (length word) 1)
756 (error "%s must prefix a single character, not %s"
757 (substring orig-word 0 prefix) word))
a9b8cb16 758 ((and (/= (logand bits ?\C-\^@) 0) (stringp word)
1e3b420b
RS
759 ;; We used to accept . and ? here,
760 ;; but . is simply wrong,
761 ;; and C-? is not used (we use DEL instead).
762 (string-match "[@-_a-z]" word))
a9b8cb16 763 (setq key (list (+ bits (- ?\C-\^@)
094e8ee4 764 (logand (aref word 0) 31)))))
629d4dcd
RS
765 (t
766 (setq key (list (+ bits (aref word 0)))))))))
767 (when key
768 (loop repeat times do (callf vconcat res key)))))
769 (when (and (>= (length res) 4)
770 (eq (aref res 0) ?\C-x)
771 (eq (aref res 1) ?\()
772 (eq (aref res (- (length res) 2)) ?\C-x)
773 (eq (aref res (- (length res) 1)) ?\)))
c31afdbd 774 (setq res (edmacro-subseq res 2 -2)))
629d4dcd
RS
775 (if (and (not need-vector)
776 (loop for ch across res
97443772 777 always (and (characterp ch)
a9b8cb16 778 (let ((ch2 (logand ch (lognot ?\M-\^@))))
629d4dcd
RS
779 (and (>= ch2 0) (<= ch2 127))))))
780 (concat (loop for ch across res
a9b8cb16 781 collect (if (= (logand ch ?\M-\^@) 0)
629d4dcd
RS
782 ch (+ ch 128))))
783 res)))
629d4dcd
RS
784
785(provide 'edmacro)
c0274f38 786
cbee283d 787;; arch-tag: 726807b4-3ae6-49de-b0ae-b9590973e0d7
c0274f38 788;;; edmacro.el ends here