Subject: bug#77317: 31.0.50; insert-kbd-macro RET produces elisp that does not work

From: Stefan Monnier <[email-masked]>
Date: Fri, 28 Mar 2025 16:59:56 -0400

> For my use-case generating
>
>     (setq last-kbd-macro (kmacro--keys
>        (kmacro "A B B A")))
>
> instead of:
>
>     (setq last-kbd-macro
>        (kmacro "A B B A"))

The patch below makes it emit

    (setq last-kbd-macro
          (key-parse "A B B A"))

> How does that actually work for a named macro? If I name the macro
> "hep" and insert it, I get:
>
>     (defalias 'hep
>        (kmacro "A B B A"))

Yes.

> Maybe that's because I didn't use any counters?

If you use the counter or the format, they'll appear as additional
arguments to the `kmacro` constructor.

> From time to time I edit a list of (spam)domains to reject, and I
> often create a macro that inserts an email-address and changes the .
> to [.] and deletes everything in front of the @.
>
> Instead of recreating that macro when I edit that list, I thought
> "Hey, I can probably save that macro in the file and reconstitute it
> when I need it".
>
> So I found M-x insert-kbd-macro and didn't give a name when prompted
> (as the macro didn't have one), and it promisingly inserted some code,
> which I tried evaluating and executing.

Thanks, that gives a good reason to support that functionality.

> With C-x e I can repeat the macro by pressing e more times.  Is that
> functionality present when I do M-x hep (ie run a named macro)?

No, the named macros are meant to use the "generic" repetition support,
e.g. by binding them to convenient keys or by using `C-x z`.

        Stefan

diff --git a/lisp/macros.el b/lisp/macros.el
index 64b78d1cdf4..25ea303d439 100644
--- a/lisp/macros.el
+++ b/lisp/macros.el
@@ -78,8 +78,6 @@ insert-kbd-macro
       (insert "(defalias '"))
     (prin1 macroname (current-buffer))
     (insert "\n   ")
-    (when (or (stringp definition) (vectorp definition))
-      (setq definition (kmacro (kmacro--to-vector definition))))
     (if (kmacro-p definition)
         (let ((vecdef  (kmacro--keys     definition))
               (counter (kmacro--counter definition))
@@ -93,8 +91,7 @@ insert-kbd-macro
             (insert " ")
             (prin1 format (current-buffer)))
           (insert ")"))
-      ;; FIXME: Shouldn't this signal an error?
-      (prin1 definition (current-buffer)))
+        (prin1 `(key-parse ,(key-description definition)) (current-buffer)))
     (insert ")\n")
     (if keys
         (let ((keys (or (and (symbol-function macroname)