Reduce use of (require 'cl).
[emacs.git] / lisp / edmacro.el
blobb1a24bc88a61c9eab4280d045823310b0ec65e5c
1 ;;; edmacro.el --- keyboard macro editor
3 ;; Copyright (C) 1993-1994, 2001-2012 Free Software Foundation, Inc.
5 ;; Author: Dave Gillespie <daveg@synaptics.com>
6 ;; Maintainer: Dave Gillespie <daveg@synaptics.com>
7 ;; Version: 2.01
8 ;; Keywords: abbrev
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
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.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;;; Usage:
29 ;; The `C-x C-k e' (`edit-kbd-macro') command edits a keyboard macro
30 ;; in a special buffer. It prompts you to type a key sequence,
31 ;; which should be one of:
33 ;; * RET or `C-x e' (call-last-kbd-macro), to edit the most
34 ;; recently defined keyboard macro.
36 ;; * `M-x' followed by a command name, to edit a named command
37 ;; whose definition is a keyboard macro.
39 ;; * `C-h l' (view-lossage), to edit the 300 most recent keystrokes
40 ;; and install them as the "current" macro.
42 ;; * any key sequence whose definition is a keyboard macro.
44 ;; This file includes a version of `insert-kbd-macro' that uses the
45 ;; more readable format defined by these routines.
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.
52 ;; Type `C-h m', or see the documentation for `edmacro-mode' below,
53 ;; for information about the format of written keyboard macros.
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.
61 ;; With a prefix argument, `edit-kbd-macro' will format the
62 ;; macro in a more concise way that omits the comments.
64 ;;; Code:
66 (eval-when-compile (require 'cl-lib))
68 (require 'kmacro)
70 ;;; The user-level commands for editing macros.
72 (defcustom edmacro-eight-bits nil
73 "Non-nil if `edit-kbd-macro' should leave 8-bit characters intact.
74 Default nil means to write characters above \\177 in octal notation."
75 :type 'boolean
76 :group 'kmacro)
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))
84 (defvar edmacro-store-hook)
85 (defvar edmacro-finish-hook)
86 (defvar edmacro-original-buffer)
88 ;;;###autoload
89 (defun edit-kbd-macro (keys &optional prefix finish-hook store-hook)
90 "Edit a keyboard macro.
91 At the prompt, type any key sequence which is bound to a keyboard macro.
92 Or, type `C-x e' or RET to edit the last keyboard macro, `C-h l' to edit
93 the last 300 keystrokes as a keyboard macro, or `M-x' to edit a macro by
94 its command name.
95 With 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))
99 (mac nil) (mac-counter nil) (mac-format nil)
100 kmacro)
101 (cond (store-hook
102 (setq mac keys)
103 (setq cmd nil))
104 ((or (memq cmd '(call-last-kbd-macro kmacro-call-macro
105 kmacro-end-or-call-macro kmacro-end-and-call-macro))
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 ""))
111 (setq keys nil)
112 (setq cmd 'last-kbd-macro))
113 ((eq cmd 'execute-extended-command)
114 (setq cmd (read-command "Name of keyboard macro to edit: "))
115 (if (string-equal cmd "")
116 (error "No command name given"))
117 (setq keys nil)
118 (setq mac (symbol-function cmd)))
119 ((memq cmd '(view-lossage electric-view-lossage))
120 (setq mac (recent-keys))
121 (setq keys nil)
122 (setq cmd 'last-kbd-macro))
123 ((null cmd)
124 (error "Key sequence %s is not defined" (key-description keys)))
125 ((symbolp cmd)
126 (setq mac (symbol-function cmd)))
128 (setq mac cmd)
129 (setq cmd nil)))
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)))
134 (unless (arrayp mac)
135 (error "Key sequence %s is not a keyboard macro"
136 (key-description keys)))
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")
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))))
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)))))
176 ;;; The next two commands are provided for convenience and backward
177 ;;; compatibility.
179 ;;;###autoload
180 (defun edit-last-kbd-macro (&optional prefix)
181 "Edit the most recently defined keyboard macro."
182 (interactive "P")
183 (edit-kbd-macro 'call-last-kbd-macro prefix))
185 ;;;###autoload
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))
191 ;;;###autoload
192 (defun read-kbd-macro (start &optional end)
193 "Read the region as a keyboard macro definition.
194 The region is interpreted as spelled-out keystrokes, e.g., \"M-x abc RET\".
195 See documentation for `edmacro-mode' for details.
196 Leading/trailing \"C-x (\" and \"C-x )\" in the text are allowed and ignored.
197 The resulting macro is installed as the \"current\" keyboard macro.
199 In Lisp, may also be called with a single STRING argument in which case
200 the result is returned rather than being installed as the current macro.
201 The result will be a string if possible, otherwise an event vector.
202 Second argument NEED-VECTOR means to return an event vector always."
203 (interactive "r")
204 (if (stringp start)
205 (edmacro-parse-keys start end)
206 (setq last-kbd-macro (edmacro-parse-keys (buffer-substring start end)))))
208 ;;;###autoload
209 (defun format-kbd-macro (&optional macro verbose)
210 "Return the keyboard macro MACRO as a human-readable string.
211 This string is suitable for passing to `read-kbd-macro'.
212 Second argument VERBOSE means to put one command per line with comments.
213 If VERBOSE is `1', put everything on one line. If VERBOSE is omitted
214 or 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))
218 ;;; Commands for *Edit Macro* buffer.
220 (defun edmacro-finish-edit ()
221 (interactive)
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)
227 (mac-counter nil) (mac-format nil)
228 (top (point-min)))
229 (goto-char top)
230 (let ((case-fold-search nil))
231 (while (cond ((looking-at "[ \t]*\\($\\|;;\\|REM[ \t\n]\\)")
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 "")
239 (setq cmd (and (not (equal str "none"))
240 (intern str)))
241 (and (fboundp cmd) (not (arrayp (symbol-function cmd)))
242 (not (get cmd 'kmacro))
243 (not (y-or-n-p
244 (format "Command %s is already defined; %s"
245 cmd "proceed? ")))
246 (keyboard-quit))))
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 "")
255 (if (equal key "none")
256 (setq no-keys t)
257 (push key keys)
258 (let ((b (key-binding key)))
259 (and b (commandp b) (not (arrayp b))
260 (not (kmacro-extract-lambda b))
261 (or (not (fboundp b))
262 (not (or (arrayp (symbol-function b))
263 (get b 'kmacro))))
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))))))
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 "")
276 (setq mac-counter (string-to-number str))))
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)))
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)
315 (fset cmd
316 (if (and mac-counter mac-format)
317 (kmacro-lambda-form mac mac-counter mac-format)
318 mac))))
319 (if no-keys
320 (when cmd
321 (cl-loop for key in (where-is-internal cmd '(keymap)) do
322 (global-unset-key key)))
323 (when keys
324 (if (= (length mac) 0)
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))))))))))
333 (kill-buffer buf)
334 (when (buffer-name obuf)
335 (switch-to-buffer obuf))
336 (when finish-hook
337 (funcall finish-hook)))))
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) " ")))
346 (defun edmacro-mode ()
347 "\\<edmacro-mode-map>Keyboard Macro Editing mode. Press \
348 \\[edmacro-finish-edit] to save and exit.
349 To abort the edit, just kill this buffer with \\[kill-buffer] RET.
351 Press \\[edmacro-insert-key] to insert the name of any key by typing the key.
353 The editing buffer contains a \"Command:\" line and any number of
354 \"Key:\" lines at the top. These are followed by a \"Macro:\" line
355 and the macro itself as spelled-out keystrokes: `C-x C-f foo RET'.
357 The \"Command:\" line specifies the command name to which the macro
358 is bound, or \"none\" for no command name. Write \"last-kbd-macro\"
359 to refer to the current keyboard macro (as used by \\[call-last-kbd-macro]).
361 The \"Key:\" lines specify key sequences to which the macro is bound,
362 or \"none\" for no key bindings.
364 You can edit these lines to change the places where the new macro
365 is stored.
368 Format of keyboard macros during editing:
370 Text is divided into \"words\" separated by whitespace. Except for
371 the words described below, the characters of each word go directly
372 as characters of the macro. The whitespace that separates words
373 is ignored. Whitespace in the macro must be written explicitly,
374 as in \"foo SPC bar RET\".
376 * The special words RET, SPC, TAB, DEL, LFD, ESC, and NUL represent
377 special control characters. The words must be written in uppercase.
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.
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.
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.
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.
399 * The `^' notation for control characters also works: ^M = C-m.
401 * Double angle brackets enclose command names: <<next-line>> is
402 shorthand for M-x next-line RET.
404 * Finally, REM or ;; causes the rest of the line to be ignored as a
405 comment.
407 Any word may be prefixed by a multiplier in the form of a decimal
408 number and `*': 3*<right> = <right> <right> <right>, and
409 10*foo = foofoofoofoofoofoofoofoofoofoo.
411 Multiple text keys can normally be strung together to form a word,
412 but you may need to add whitespace if the word would look like one
413 of the above notations: `; ; ;' is a keyboard macro with three
414 semicolons, but `;;;' is a comment. Likewise, `\\ 1 2 3' is four
415 keys but `\\123' is a single key written in octal, and `< right >'
416 is seven keys but `<right>' is a single function key. When in
417 doubt, use whitespace."
418 (interactive)
419 (error "This mode can be enabled only by `edit-kbd-macro'"))
420 (put 'edmacro-mode 'mode-class 'special)
422 ;;; Formatting a keyboard macro as human-readable text.
424 (defun edmacro-format-keys (macro &optional verbose)
425 (setq macro (edmacro-fix-menu-commands macro))
426 (let* ((maps (current-active-maps))
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)
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)))))
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)
447 (memq (key-binding (edmacro-subseq rest-mac 0 1))
448 '(digit-argument negative-argument))
449 (let ((i 1))
450 (while (memq (aref rest-mac i) (cdr mdigs))
451 (cl-incf i))
452 (and (not (memq (aref rest-mac i) pkeys))
453 (prog1 (vconcat "M-" (edmacro-subseq rest-mac 0 i) " ")
454 (cl-callf edmacro-subseq rest-mac i)))))
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)
459 (cl-incf i))
460 (and (not (memq (aref rest-mac i) pkeys))
461 (prog1 (cl-loop repeat i concat "C-u ")
462 (cl-callf edmacro-subseq rest-mac i)))))
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) ?-)
467 (cl-incf i))
468 (while (memq (aref rest-mac i)
469 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9))
470 (cl-incf i))
471 (and (not (memq (aref rest-mac i) pkeys))
472 (prog1 (vconcat "C-u " (edmacro-subseq rest-mac 1 i) " ")
473 (cl-callf edmacro-subseq rest-mac i)))))))
474 (bind-len (apply 'max 1
475 (cl-loop for map in maps
476 for b = (lookup-key map rest-mac)
477 when b collect b)))
478 (key (edmacro-subseq rest-mac 0 bind-len))
479 (fkey nil) tlen tkey
480 (bind (or (cl-loop for map in maps for b = (lookup-key map key)
481 thereis (and (not (integerp b)) b))
482 (and (setq fkey (lookup-key local-function-key-map rest-mac))
483 (setq tlen fkey tkey (edmacro-subseq rest-mac 0 tlen)
484 fkey (lookup-key local-function-key-map tkey))
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)))))
491 (first (aref key 0))
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))
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))
510 (setq desc (concat (edmacro-subseq rest-mac 0 text)))
511 (when (string-match "^[ACHMsS]-." desc)
512 (setq text 2)
513 (cl-callf substring desc 0 2))
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
527 (setq desc (concat (edmacro-subseq rest-mac bind-len text)))
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)))
533 (setq desc (mapconcat
534 (function
535 (lambda (ch)
536 (cond
537 ((integerp ch)
538 (concat
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))
544 (let ((ch2 (logand ch (1- (lsh 1 18)))))
545 (cond ((<= ch2 32)
546 (pcase ch2
547 (0 "NUL") (9 "TAB") (10 "LFD")
548 (13 "RET") (27 "ESC") (32 "SPC")
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))
559 (error "Unrecognized item in macro: %s" ch)))))
560 (or fkey key) " "))))
561 (if prefix
562 (setq desc (concat (edmacro-sanitize-for-string prefix) desc)))
563 (unless (string-match " " desc)
564 (let ((times 1) (pos bind-len))
565 (while (not (edmacro-mismatch rest-mac rest-mac
566 0 bind-len pos (+ bind-len pos)))
567 (cl-incf times)
568 (cl-incf pos bind-len))
569 (when (> times 1)
570 (setq desc (format "%d*%s" times desc))
571 (setq bind-len (* bind-len times)))))
572 (setq rest-mac (edmacro-subseq rest-mac bind-len))
573 (if verbose
574 (progn
575 (unless (equal res "") (cl-callf concat res "\n"))
576 (cl-callf concat res desc)
577 (when (and bind (or (stringp bind) (symbolp bind)))
578 (cl-callf concat res
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
584 (cl-callf concat res "\n ")
585 (setq len 1))
586 (unless (equal res "")
587 (cl-callf concat res " ")
588 (cl-incf len)))
589 (cl-callf concat res desc)
590 (cl-incf len (length desc)))))
591 res))
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.
595 Return nil if the sequences match. If one sequence is a prefix of the
596 other, the return value indicates the end of the shorted sequence.
597 \n(fn SEQ1 SEQ2 START1 END1 START2 END2)"
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)))
612 (defun edmacro-subseq (seq start &optional end)
613 "Return the subsequence of SEQ from START to END.
614 If END is omitted, it defaults to the length of the sequence.
615 If 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)
625 (push (pop seq) res))
626 (nreverse res))
627 (copy-sequence seq)))
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))))))
637 (defun edmacro-sanitize-for-string (seq)
638 "Convert a key sequence vector SEQ into a string.
639 The string represents the same events; Meta is indicated by bit 7.
640 This function assumes that the events can be stored in a string."
641 (setq seq (copy-sequence seq))
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))))
645 seq)
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))
656 ((eq (car ev) 'switch-frame))
657 ((equal ev '(menu-bar))
658 (push 'menu-bar result))
659 ((equal (cl-cadadr ev) '(menu-bar))
660 (push (vector 'menu-bar (car ev)) result))
661 ;; It would be nice to do pop-up menus, too, but not enough
662 ;; info is recorded in macros to make this possible.
663 (noerror
664 ;; Just ignore mouse events.
665 nil)
667 (error "Macros with mouse clicks are not %s"
668 "supported by this command"))))
669 ;; Reverse them again and make them back into a vector.
670 (vconcat (nreverse result)))
671 macro))
673 ;;; Parsing a human-readable keyboard macro.
675 (defun edmacro-parse-keys (string &optional need-vector)
676 (let ((case-fold-search nil)
677 (len (length string)) ; We won't alter string in the loop below.
678 (pos 0)
679 (res []))
680 (while (and (< pos len)
681 (string-match "[^ \t\n\f]+" string pos))
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>".
688 (if (string-match "\\`<[^ <>\t\n\f][^>\t\n\f]*>" word)
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))
693 (when (string-match "\\([0-9]+\\)\\*." word)
694 (setq times (string-to-number (substring word 0 (match-end 1))))
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)))
717 (let ((orig-word word) (prefix 0) (bits 0))
718 (while (string-match "^[ACHMsS]-." word)
719 (cl-incf bits (cdr (assq (aref word 0)
720 '((?A . ?\A-\^@) (?C . ?\C-\^@)
721 (?H . ?\H-\^@) (?M . ?\M-\^@)
722 (?s . ?\s-\^@) (?S . ?\S-\^@)))))
723 (cl-incf prefix 2)
724 (cl-callf substring word 2))
725 (when (string-match "^\\^.$" word)
726 (cl-incf bits ?\C-\^@)
727 (cl-incf prefix)
728 (cl-callf substring word 1))
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)
735 (cl-loop for ch across word
736 for n = 0 then (+ (* n 8) ch -48)
737 finally do (setq word (vector n))))
738 (cond ((= bits 0)
739 (setq key word))
740 ((and (= bits ?\M-\^@) (stringp word)
741 (string-match "^-?[0-9]+$" word))
742 (setq key (cl-loop for x across word
743 collect (+ x bits))))
744 ((/= (length word) 1)
745 (error "%s must prefix a single character, not %s"
746 (substring orig-word 0 prefix) word))
747 ((and (/= (logand bits ?\C-\^@) 0) (stringp word)
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))
752 (setq key (list (+ bits (- ?\C-\^@)
753 (logand (aref word 0) 31)))))
755 (setq key (list (+ bits (aref word 0)))))))))
756 (when key
757 (cl-loop repeat times do (cl-callf vconcat res key)))))
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)) ?\)))
763 (setq res (edmacro-subseq res 2 -2)))
764 (if (and (not need-vector)
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))))
772 res)))
774 (provide 'edmacro)
776 ;;; edmacro.el ends here