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