]> code.delx.au - gnu-emacs/blob - lisp/edmacro.el
(mail): Use pop-to-buffer.
[gnu-emacs] / lisp / edmacro.el
1 ;;; edmacro.el --- keyboard macro editor
2
3 ;; Copyright (C) 1993, 1994 Free Software Foundation, Inc.
4
5 ;; Author: Dave Gillespie <daveg@synaptics.com>
6 ;; Maintainer: Dave Gillespie <daveg@synaptics.com>
7 ;; Version: 2.01
8 ;; Keywords: abbrev
9
10 ;; This file is part of GNU Emacs.
11
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 2, or (at your option)
15 ;; any later version.
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
23 ;; along with GNU Emacs; see the file COPYING. If not, write to
24 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25
26 ;;; Commentary:
27
28 ;;; Usage:
29 ;;
30 ;; The `C-x C-k' (`edit-kbd-macro') command edits a keyboard macro
31 ;; in a special buffer. It prompts you to type a key sequence,
32 ;; which should be one of:
33 ;;
34 ;; * RET or `C-x e' (call-last-kbd-macro), to edit the most
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.
69
70 ;;; Code:
71 \f
72 (require 'cl)
73
74 ;;; The user-level commands for editing macros.
75
76 ;;;###autoload (define-key ctl-x-map "\C-k" 'edit-kbd-macro)
77
78 ;;;###autoload
79 (defvar edmacro-eight-bits nil
80 "*Non-nil if edit-kbd-macro should leave 8-bit characters intact.
81 Default nil means to write characters above \\177 in octal notation.")
82
83 (defvar edmacro-mode-map nil)
84 (unless edmacro-mode-map
85 (setq edmacro-mode-map (make-sparse-keymap))
86 (define-key edmacro-mode-map "\C-c\C-c" 'edmacro-finish-edit)
87 (define-key edmacro-mode-map "\C-c\C-q" 'edmacro-insert-key))
88
89 ;;;###autoload
90 (defun edit-kbd-macro (keys &optional prefix finish-hook store-hook)
91 "Edit a keyboard macro.
92 At the prompt, type any key sequence which is bound to a keyboard macro.
93 Or, type `C-x e' or RET to edit the last keyboard macro, `C-h l' to edit
94 the last 100 keystrokes as a keyboard macro, or `M-x' to edit a macro by
95 its command name.
96 With a prefix argument, format the macro in a more concise way."
97 (interactive "kKeyboard macro to edit (C-x e, M-x, C-h l, or keys): \nP")
98 (when keys
99 (let ((cmd (if (arrayp keys) (key-binding keys) keys))
100 (mac nil))
101 (cond (store-hook
102 (setq mac keys)
103 (setq cmd nil))
104 ((or (eq cmd 'call-last-kbd-macro)
105 (member keys '("\r" [return])))
106 (or last-kbd-macro
107 (y-or-n-p "No keyboard macro defined. Create one? ")
108 (keyboard-quit))
109 (setq mac (or last-kbd-macro ""))
110 (setq cmd 'last-kbd-macro))
111 ((eq cmd 'execute-extended-command)
112 (setq cmd (read-command "Name of keyboard macro to edit: "))
113 (setq mac (symbol-function cmd)))
114 ((eq cmd 'view-lossage)
115 (setq mac (recent-keys))
116 (setq cmd 'last-kbd-macro))
117 ((symbolp cmd)
118 (setq mac (symbol-function cmd)))
119 (t
120 (setq mac cmd)
121 (setq cmd nil)))
122 (unless (arrayp mac)
123 (error "Not a keyboard macro: %s" cmd))
124 (message "Formatting keyboard macro...")
125 (let* ((oldbuf (current-buffer))
126 (mmac (edmacro-fix-menu-commands mac))
127 (fmt (edmacro-format-keys mmac 1))
128 (fmtv (edmacro-format-keys mmac (not prefix)))
129 (buf (get-buffer-create "*Edit Macro*")))
130 (message "Formatting keyboard macro...done")
131 (switch-to-buffer buf)
132 (kill-all-local-variables)
133 (use-local-map edmacro-mode-map)
134 (setq buffer-read-only nil)
135 (setq major-mode 'edmacro-mode)
136 (setq mode-name "Edit Macro")
137 (set (make-local-variable 'edmacro-original-buffer) oldbuf)
138 (set (make-local-variable 'edmacro-finish-hook) finish-hook)
139 (set (make-local-variable 'edmacro-store-hook) store-hook)
140 (erase-buffer)
141 (insert ";; Keyboard Macro Editor. Press C-c C-c to finish; "
142 "press C-x k RET to cancel.\n")
143 (insert ";; Original keys: " fmt "\n")
144 (unless store-hook
145 (insert "\nCommand: " (if cmd (symbol-name cmd) "none") "\n")
146 (let ((keys (where-is-internal (or cmd mac) '(keymap))))
147 (if keys
148 (while keys
149 (insert "Key: " (edmacro-format-keys (pop keys) 1) "\n"))
150 (insert "Key: none\n"))))
151 (insert "\nMacro:\n\n")
152 (save-excursion
153 (insert fmtv "\n"))
154 (recenter '(4))
155 (when (eq mac mmac)
156 (set-buffer-modified-p nil))
157 (run-hooks 'edmacro-format-hook)))))
158
159 ;;; The next two commands are provided for convenience and backward
160 ;;; compatibility.
161
162 ;;;###autoload
163 (defun edit-last-kbd-macro (&optional prefix)
164 "Edit the most recently defined keyboard macro."
165 (interactive "P")
166 (edit-kbd-macro 'call-last-kbd-macro prefix))
167
168 ;;;###autoload
169 (defun edit-named-kbd-macro (&optional prefix)
170 "Edit a keyboard macro which has been given a name by `name-last-kbd-macro'."
171 (interactive "P")
172 (edit-kbd-macro 'execute-extended-command prefix))
173
174 ;;;###autoload
175 (defun read-kbd-macro (start &optional end)
176 "Read the region as a keyboard macro definition.
177 The region is interpreted as spelled-out keystrokes, e.g., \"M-x abc RET\".
178 See documentation for `edmacro-mode' for details.
179 Leading/trailing \"C-x (\" and \"C-x )\" in the text are allowed and ignored.
180 The resulting macro is installed as the \"current\" keyboard macro.
181
182 In Lisp, may also be called with a single STRING argument in which case
183 the result is returned rather than being installed as the current macro.
184 The result will be a string if possible, otherwise an event vector.
185 Second argument NEED-VECTOR means to return an event vector always."
186 (interactive "r")
187 (if (stringp start)
188 (edmacro-parse-keys start end)
189 (setq last-kbd-macro (edmacro-parse-keys (buffer-substring start end)))))
190
191 ;;;###autoload
192 (defun format-kbd-macro (&optional macro verbose)
193 "Return the keyboard macro MACRO as a human-readable string.
194 This string is suitable for passing to `read-kbd-macro'.
195 Second argument VERBOSE means to put one command per line with comments.
196 If VERBOSE is `1', put everything on one line. If VERBOSE is omitted
197 or nil, use a compact 80-column format."
198 (and macro (symbolp macro) (setq macro (symbol-function macro)))
199 (edmacro-format-keys (or macro last-kbd-macro) verbose))
200 \f
201 ;;; Commands for *Edit Macro* buffer.
202
203 (defun edmacro-finish-edit ()
204 (interactive)
205 (unless (eq major-mode 'edmacro-mode)
206 (error
207 "This command is valid only in buffers created by `edit-kbd-macro'"))
208 (run-hooks 'edmacro-finish-hook)
209 (let ((cmd nil) (keys nil) (no-keys nil)
210 (top (point-min)))
211 (goto-char top)
212 (let ((case-fold-search nil))
213 (while (cond ((looking-at "[ \t]*\\($\\|;;\\|REM[ \t\n]\\)")
214 t)
215 ((looking-at "Command:[ \t]*\\([^ \t\n]*\\)[ \t]*$")
216 (when edmacro-store-hook
217 (error "\"Command\" line not allowed in this context"))
218 (let ((str (buffer-substring (match-beginning 1)
219 (match-end 1))))
220 (unless (equal str "")
221 (setq cmd (and (not (equalp str "none"))
222 (intern str)))
223 (and (fboundp cmd) (not (arrayp (symbol-function cmd)))
224 (not (y-or-n-p
225 (format "Command %s is already defined; %s"
226 cmd "proceed? ")))
227 (keyboard-quit))))
228 t)
229 ((looking-at "Key:\\(.*\\)$")
230 (when edmacro-store-hook
231 (error "\"Key\" line not allowed in this context"))
232 (let ((key (edmacro-parse-keys
233 (buffer-substring (match-beginning 1)
234 (match-end 1)))))
235 (unless (equal key "")
236 (if (equalp key "none")
237 (setq no-keys t)
238 (push key keys)
239 (let ((b (key-binding key)))
240 (and b (commandp b) (not (arrayp b))
241 (or (not (fboundp b))
242 (not (arrayp (symbol-function b))))
243 (not (y-or-n-p
244 (format "Key %s is already defined; %s"
245 (edmacro-format-keys key 1)
246 "proceed? ")))
247 (keyboard-quit))))))
248 t)
249 ((looking-at "Macro:[ \t\n]*")
250 (goto-char (match-end 0))
251 nil)
252 ((eobp) nil)
253 (t (error "Expected a `Macro:' line")))
254 (forward-line 1))
255 (setq top (point)))
256 (let* ((buf (current-buffer))
257 (str (buffer-substring top (point-max)))
258 (modp (buffer-modified-p))
259 (obuf edmacro-original-buffer)
260 (store-hook edmacro-store-hook)
261 (finish-hook edmacro-finish-hook))
262 (unless (or cmd keys store-hook (equal str ""))
263 (error "No command name or keys specified"))
264 (when modp
265 (when (buffer-name obuf)
266 (set-buffer obuf))
267 (message "Compiling keyboard macro...")
268 (let ((mac (edmacro-parse-keys str)))
269 (message "Compiling keyboard macro...done")
270 (if store-hook
271 (funcall store-hook mac)
272 (when (eq cmd 'last-kbd-macro)
273 (setq last-kbd-macro (and (> (length mac) 0) mac))
274 (setq cmd nil))
275 (when cmd
276 (if (= (length mac) 0)
277 (fmakunbound cmd)
278 (fset cmd mac)))
279 (if no-keys
280 (when cmd
281 (loop for key in (where-is-internal cmd '(keymap)) do
282 (global-unset-key key)))
283 (when keys
284 (if (= (length mac) 0)
285 (loop for key in keys do (global-unset-key key))
286 (loop for key in keys do
287 (global-set-key key (or cmd mac)))))))))
288 (kill-buffer buf)
289 (when (buffer-name obuf)
290 (switch-to-buffer obuf))
291 (when finish-hook
292 (funcall finish-hook)))))
293
294 (defun edmacro-insert-key (key)
295 "Insert the written name of a key in the buffer."
296 (interactive "kKey to insert: ")
297 (if (bolp)
298 (insert (edmacro-format-keys key t) "\n")
299 (insert (edmacro-format-keys key) " ")))
300
301 (defun edmacro-mode ()
302 "\\<edmacro-mode-map>Keyboard Macro Editing mode. Press
303 \\[edmacro-finish-edit] to save and exit.
304 To abort the edit, just kill this buffer with \\[kill-buffer] RET.
305
306 Press \\[edmacro-insert-key] to insert the name of any key by typing the key.
307
308 The editing buffer contains a \"Command:\" line and any number of
309 \"Key:\" lines at the top. These are followed by a \"Macro:\" line
310 and the macro itself as spelled-out keystrokes: `C-x C-f foo RET'.
311
312 The \"Command:\" line specifies the command name to which the macro
313 is bound, or \"none\" for no command name. Write \"last-kbd-macro\"
314 to refer to the current keyboard macro (as used by \\[call-last-kbd-macro]).
315
316 The \"Key:\" lines specify key sequences to which the macro is bound,
317 or \"none\" for no key bindings.
318
319 You can edit these lines to change the places where the new macro
320 is stored.
321
322
323 Format of keyboard macros during editing:
324
325 Text is divided into \"words\" separated by whitespace. Except for
326 the words described below, the characters of each word go directly
327 as characters of the macro. The whitespace that separates words
328 is ignored. Whitespace in the macro must be written explicitly,
329 as in \"foo SPC bar RET\".
330
331 * The special words RET, SPC, TAB, DEL, LFD, ESC, and NUL represent
332 special control characters. The words must be written in uppercase.
333
334 * A word in angle brackets, e.g., <return>, <down>, or <f1>, represents
335 a function key. (Note that in the standard configuration, the
336 function key <return> and the control key RET are synonymous.)
337 You can use angle brackets on the words RET, SPC, etc., but they
338 are not required there.
339
340 * Keys can be written by their ASCII code, using a backslash followed
341 by up to six octal digits. This is the only way to represent keys
342 with codes above \\377.
343
344 * One or more prefixes M- (meta), C- (control), S- (shift), A- (alt),
345 H- (hyper), and s- (super) may precede a character or key notation.
346 For function keys, the prefixes may go inside or outside of the
347 brackets: C-<down> = <C-down>. The prefixes may be written in
348 any order: M-C-x = C-M-x.
349
350 Prefixes are not allowed on multi-key words, e.g., C-abc, except
351 that the Meta prefix is allowed on a sequence of digits and optional
352 minus sign: M--123 = M-- M-1 M-2 M-3.
353
354 * The `^' notation for control characters also works: ^M = C-m.
355
356 * Double angle brackets enclose command names: <<next-line>> is
357 shorthand for M-x next-line RET.
358
359 * Finally, REM or ;; causes the rest of the line to be ignored as a
360 comment.
361
362 Any word may be prefixed by a multiplier in the form of a decimal
363 number and `*': 3*<right> = <right> <right> <right>, and
364 10*foo = foofoofoofoofoofoofoofoofoofoo.
365
366 Multiple text keys can normally be strung together to form a word,
367 but you may need to add whitespace if the word would look like one
368 of the above notations: `; ; ;' is a keyboard macro with three
369 semicolons, but `;;;' is a comment. Likewise, `\\ 1 2 3' is four
370 keys but `\\123' is a single key written in octal, and `< right >'
371 is seven keys but `<right>' is a single function key. When in
372 doubt, use whitespace."
373 (interactive)
374 (error "This mode can be enabled only by `edit-kbd-macro'"))
375 (put 'edmacro-mode 'mode-class 'special)
376 \f
377 ;;; Formatting a keyboard macro as human-readable text.
378
379 (defun edmacro-format-keys (macro &optional verbose)
380 (setq macro (edmacro-fix-menu-commands macro))
381 (let* ((maps (append (current-minor-mode-maps)
382 (if (current-local-map)
383 (list (current-local-map)))
384 (list (current-global-map))))
385 (pkeys '(end-macro ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?- ?\C-u
386 ?\M-- ?\M-0 ?\M-1 ?\M-2 ?\M-3 ?\M-4 ?\M-5 ?\M-6
387 ?\M-7 ?\M-8 ?\M-9))
388 (mdigs (nthcdr 13 pkeys))
389 (maxkey (if edmacro-eight-bits 255 127))
390 (case-fold-search nil)
391 (res-words '("NUL" "TAB" "LFD" "RET" "ESC" "SPC" "DEL" "REM"))
392 (rest-mac (vconcat macro [end-macro]))
393 (res "")
394 (len 0)
395 (one-line (eq verbose 1)))
396 (if one-line (setq verbose nil))
397 (when (stringp macro)
398 (loop for i below (length macro) do
399 (when (>= (aref rest-mac i) 128)
400 (incf (aref rest-mac i) (- ?\M-\^@ 128)))))
401 (while (not (eq (aref rest-mac 0) 'end-macro))
402 (let* ((prefix
403 (or (and (integerp (aref rest-mac 0))
404 (memq (aref rest-mac 0) mdigs)
405 (memq (key-binding (subseq rest-mac 0 1))
406 '(digit-argument negative-argument))
407 (let ((i 1))
408 (while (memq (aref rest-mac i) (cdr mdigs))
409 (incf i))
410 (and (not (memq (aref rest-mac i) pkeys))
411 (prog1 (concat "M-" (subseq rest-mac 0 i) " ")
412 (callf subseq rest-mac i)))))
413 (and (eq (aref rest-mac 0) ?\C-u)
414 (eq (key-binding [?\C-u]) 'universal-argument)
415 (let ((i 1))
416 (while (eq (aref rest-mac i) ?\C-u)
417 (incf i))
418 (and (not (memq (aref rest-mac i) pkeys))
419 (prog1 (loop repeat i concat "C-u ")
420 (callf subseq rest-mac i)))))
421 (and (eq (aref rest-mac 0) ?\C-u)
422 (eq (key-binding [?\C-u]) 'universal-argument)
423 (let ((i 1))
424 (when (eq (aref rest-mac i) ?-)
425 (incf i))
426 (while (memq (aref rest-mac i)
427 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9))
428 (incf i))
429 (and (not (memq (aref rest-mac i) pkeys))
430 (prog1 (concat "C-u " (subseq rest-mac 1 i) " ")
431 (callf subseq rest-mac i)))))))
432 (bind-len (apply 'max 1
433 (loop for map in maps
434 for b = (lookup-key map rest-mac)
435 when b collect b)))
436 (key (subseq rest-mac 0 bind-len))
437 (fkey nil) tlen tkey
438 (bind (or (loop for map in maps for b = (lookup-key map key)
439 thereis (and (not (integerp b)) b))
440 (and (setq fkey (lookup-key function-key-map rest-mac))
441 (setq tlen fkey tkey (subseq rest-mac 0 tlen)
442 fkey (lookup-key function-key-map tkey))
443 (loop for map in maps
444 for b = (lookup-key map fkey)
445 when (and (not (integerp b)) b)
446 do (setq bind-len tlen key tkey)
447 and return b
448 finally do (setq fkey nil)))))
449 (first (aref key 0))
450 (text (loop for i from bind-len below (length rest-mac)
451 for ch = (aref rest-mac i)
452 while (and (integerp ch)
453 (> ch 32) (< ch maxkey) (/= ch 92)
454 (eq (key-binding (char-to-string ch))
455 'self-insert-command)
456 (or (> i (- (length rest-mac) 2))
457 (not (eq ch (aref rest-mac (+ i 1))))
458 (not (eq ch (aref rest-mac (+ i 2))))))
459 finally return i))
460 desc)
461 (if (stringp bind) (setq bind nil))
462 (cond ((and (eq bind 'self-insert-command) (not prefix)
463 (> text 1) (integerp first)
464 (> first 32) (<= first maxkey) (/= first 92)
465 (progn
466 (if (> text 30) (setq text 30))
467 (setq desc (concat (subseq rest-mac 0 text)))
468 (when (string-match "^[ACHMsS]-." desc)
469 (setq text 2)
470 (callf substring desc 0 2))
471 (not (string-match
472 "^;;\\|^<.*>$\\|^\\\\[0-9]+$\\|^[0-9]+\\*."
473 desc))))
474 (when (or (string-match "^\\^.$" desc)
475 (member desc res-words))
476 (setq desc (mapconcat 'char-to-string desc " ")))
477 (when verbose
478 (setq bind (format "%s * %d" bind text)))
479 (setq bind-len text))
480 ((and (eq bind 'execute-extended-command)
481 (> text bind-len)
482 (memq (aref rest-mac text) '(return 13))
483 (progn
484 (setq desc (concat (subseq rest-mac bind-len text)))
485 (commandp (intern-soft desc))))
486 (if (commandp (intern-soft desc)) (setq bind desc))
487 (setq desc (format "<<%s>>" desc))
488 (setq bind-len (1+ text)))
489 (t
490 (setq desc (mapconcat
491 (function
492 (lambda (ch)
493 (cond
494 ((integerp ch)
495 (concat
496 (loop for pf across "ACHMsS"
497 for bit in '(?\A-\^@ ?\C-\^@ ?\H-\^@
498 ?\M-\^@ ?\s-\^@ ?\S-\^@)
499 when (/= (logand ch bit) 0)
500 concat (format "%c-" pf))
501 (let ((ch2 (logand ch (1- (lsh 1 18)))))
502 (cond ((<= ch2 32)
503 (case ch2
504 (0 "NUL") (9 "TAB") (10 "LFD")
505 (13 "RET") (27 "ESC") (32 "SPC")
506 (t
507 (format "C-%c"
508 (+ (if (<= ch2 26) 96 64)
509 ch2)))))
510 ((= ch2 127) "DEL")
511 ((<= ch2 maxkey) (char-to-string ch2))
512 (t (format "\\%o" ch2))))))
513 ((symbolp ch)
514 (format "<%s>" ch))
515 (t
516 (error "Unrecognized item in macro: %s" ch)))))
517 (or fkey key) " "))))
518 (if prefix (setq desc (concat prefix desc)))
519 (unless (string-match " " desc)
520 (let ((times 1) (pos bind-len))
521 (while (not (mismatch rest-mac rest-mac
522 :end1 bind-len :start2 pos
523 :end2 (+ bind-len pos)))
524 (incf times)
525 (incf pos bind-len))
526 (when (> times 1)
527 (setq desc (format "%d*%s" times desc))
528 (setq bind-len (* bind-len times)))))
529 (setq rest-mac (subseq rest-mac bind-len))
530 (if verbose
531 (progn
532 (unless (equal res "") (callf concat res "\n"))
533 (callf concat res desc)
534 (when (and bind (or (stringp bind) (symbolp bind)))
535 (callf concat res
536 (make-string (max (- 3 (/ (length desc) 8)) 1) 9)
537 ";; " (if (stringp bind) bind (symbol-name bind))))
538 (setq len 0))
539 (if (and (> (+ len (length desc) 2) 72) (not one-line))
540 (progn
541 (callf concat res "\n ")
542 (setq len 1))
543 (unless (equal res "")
544 (callf concat res " ")
545 (incf len)))
546 (callf concat res desc)
547 (incf len (length desc)))))
548 res))
549
550 (defun edmacro-fix-menu-commands (macro)
551 (when (vectorp macro)
552 (let ((i 0) ev)
553 (while (< i (length macro))
554 (when (consp (setq ev (aref macro i)))
555 (cond ((equal (cadadr ev) '(menu-bar))
556 (setq macro (vconcat (subseq macro 0 i)
557 (vector 'menu-bar (car ev))
558 (subseq macro (1+ i))))
559 (incf i))
560 ;; It would be nice to do pop-up menus, too, but not enough
561 ;; info is recorded in macros to make this possible.
562 (t
563 (error "Macros with mouse clicks are not %s"
564 "supported by this command"))))
565 (incf i))))
566 macro)
567 \f
568 ;;; Parsing a human-readable keyboard macro.
569
570 (defun edmacro-parse-keys (string &optional need-vector)
571 (let ((case-fold-search nil)
572 (pos 0)
573 (res []))
574 (while (and (< pos (length string))
575 (string-match "[^ \t\n\f]+" string pos))
576 (let ((word (substring string (match-beginning 0) (match-end 0)))
577 (key nil)
578 (times 1))
579 (setq pos (match-end 0))
580 (when (string-match "\\([0-9]+\\)\\*." word)
581 (setq times (string-to-int (substring word 0 (match-end 1))))
582 (setq word (substring word (1+ (match-end 1)))))
583 (cond ((string-match "^<<.+>>$" word)
584 (setq key (vconcat (if (eq (key-binding [?\M-x])
585 'execute-extended-command)
586 [?\M-x]
587 (or (car (where-is-internal
588 'execute-extended-command))
589 [?\M-x]))
590 (substring word 2 -2) "\r")))
591 ((and (string-match "^\\(\\([ACHMsS]-\\)*\\)<\\(.+\\)>$" word)
592 (progn
593 (setq word (concat (substring word (match-beginning 1)
594 (match-end 1))
595 (substring word (match-beginning 3)
596 (match-end 3))))
597 (not (string-match
598 "\\<\\(NUL\\|RET\\|LFD\\|ESC\\|SPC\\|DEL\\)$"
599 word))))
600 (setq key (list (intern word))))
601 ((or (equal word "REM") (string-match "^;;" word))
602 (setq pos (string-match "$" string pos)))
603 (t
604 (let ((orig-word word) (prefix 0) (bits 0))
605 (while (string-match "^[ACHMsS]-." word)
606 (incf bits (cdr (assq (aref word 0)
607 '((?A . ?\A-\^@) (?C . ?\C-\^@)
608 (?H . ?\H-\^@) (?M . ?\M-\^@)
609 (?s . ?\s-\^@) (?S . ?\S-\^@)))))
610 (incf prefix 2)
611 (callf substring word 2))
612 (when (string-match "^\\^.$" word)
613 (incf bits ?\C-\^@)
614 (incf prefix)
615 (callf substring word 1))
616 (let ((found (assoc word '(("NUL" . "\0") ("RET" . "\r")
617 ("LFD" . "\n") ("TAB" . "\t")
618 ("ESC" . "\e") ("SPC" . " ")
619 ("DEL" . "\177")))))
620 (when found (setq word (cdr found))))
621 (when (string-match "^\\\\[0-7]+$" word)
622 (loop for ch across word
623 for n = 0 then (+ (* n 8) ch -48)
624 finally do (setq word (vector n))))
625 (cond ((= bits 0)
626 (setq key word))
627 ((and (= bits ?\M-\^@) (stringp word)
628 (string-match "^-?[0-9]+$" word))
629 (setq key (loop for x across word collect (+ x bits))))
630 ((/= (length word) 1)
631 (error "%s must prefix a single character, not %s"
632 (substring orig-word 0 prefix) word))
633 ((and (/= (logand bits ?\C-\^@) 0) (stringp word)
634 (string-match "[@-_.a-z?]" word))
635 (setq key (list (+ bits (- ?\C-\^@)
636 (if (equal word "?") 127
637 (logand (aref word 0) 31))))))
638 (t
639 (setq key (list (+ bits (aref word 0)))))))))
640 (when key
641 (loop repeat times do (callf vconcat res key)))))
642 (when (and (>= (length res) 4)
643 (eq (aref res 0) ?\C-x)
644 (eq (aref res 1) ?\()
645 (eq (aref res (- (length res) 2)) ?\C-x)
646 (eq (aref res (- (length res) 1)) ?\)))
647 (setq res (subseq res 2 -2)))
648 (if (and (not need-vector)
649 (loop for ch across res
650 always (and (integerp ch)
651 (let ((ch2 (logand ch (lognot ?\M-\^@))))
652 (and (>= ch2 0) (<= ch2 127))))))
653 (concat (loop for ch across res
654 collect (if (= (logand ch ?\M-\^@) 0)
655 ch (+ ch 128))))
656 res)))
657 \f
658 ;;; The following probably ought to go in macros.el:
659
660 ;;;###autoload
661 (defun insert-kbd-macro (macroname &optional keys)
662 "Insert in buffer the definition of kbd macro NAME, as Lisp code.
663 Optional second arg KEYS means also record the keys it is on
664 \(this is the prefix argument, when calling interactively).
665
666 This Lisp code will, when executed, define the kbd macro with the same
667 definition it has now. If you say to record the keys, the Lisp code
668 will also rebind those keys to the macro. Only global key bindings
669 are recorded since executing this Lisp code always makes global
670 bindings.
671
672 To save a kbd macro, visit a file of Lisp code such as your `~/.emacs',
673 use this command, and then save the file."
674 (interactive "CInsert kbd macro (name): \nP")
675 (let (definition)
676 (if (string= (symbol-name macroname) "")
677 (progn
678 (setq definition (format-kbd-macro))
679 (insert "(setq last-kbd-macro"))
680 (setq definition (format-kbd-macro macroname))
681 (insert (format "(defalias '%s" macroname)))
682 (if (> (length definition) 50)
683 (insert " (read-kbd-macro\n")
684 (insert "\n (read-kbd-macro "))
685 (prin1 definition (current-buffer))
686 (insert "))\n")
687 (if keys
688 (let ((keys (where-is-internal macroname '(keymap))))
689 (while keys
690 (insert (format "(global-set-key %S '%s)\n" (car keys) macroname))
691 (setq keys (cdr keys)))))))
692
693 (provide 'edmacro)
694
695 ;;; edmacro.el ends here
696