I often find useful/nifty kmacros on the web, like (kmacro-exec-ring-item (quote ([return 3 16 14 5 return 21 3 46 return 24 98 return] 0 "%d")) arg). Being a curious guy I am, I usually want to know how they do what they do.

Given the (kbd) function, which can convert a string like "C-x C-c" to the internally used key codes (that, AFAIK, are used by kmacros), is there a reverse function for this? Can I get a human readable representation of a keyboard macro?


If you purely want the human-readable key sequence, the key-description function is all you need:

(key-description [return 3 16 14 5 return 21 3 46 return 24 98 return])
"<return> C-c C-p C-n C-e <return> C-u C-c . <return> C-x b <return>"

If you want to know the names of the commands which will be executed by that key sequence, you can get those too -- although the commands that a macro will run will, of course, depend on the keymaps that are active in the current buffer, so you can only get the commands which would run for that particular context.

The keyboard macro editor (command edit-kbd-macro) will show you the commands. Invoke it with: C-xC-ke and then select the macro you want. For a named macro, you would use M-x at that prompt.

For your example:

(fset 'foo [return 3 16 14 5 return 21 3 46 return 24 98 return])

Then, in my current text-mode buffer:

C-xC-keM-x foo RET

;; Keyboard Macro Editor.  Press C-c C-c to finish; press C-x k RET to cancel.
;; Original keys: RET C-c C-p C-n C-e RET C-u C-c . RET C-x b RET

Command: foo
Key: none


RET         ;; newline
C-c C-p
C-n         ;; next-line
C-e         ;; move-end-of-line
RET         ;; newline
C-u C-c .
RET         ;; newline
C-x b           ;; switch-to-buffer
RET         ;; newline

Note that edmacro-format-keys isn't necessarily producing the exact same output as key-description. Here we see <return> in the latter, but RET in the former.

  • Of course the commands will differ :) What I’m interested in are the keystrokes to produce the same effect, which your solution does perfectly. Thanks! – GergelyPolonkai Jun 24 '18 at 20:37
  • 1
    In fact I mis-read the question. I've now added a mention of the key-description function, which is really what you wanted (although the macro editor's more detailed output may be preferable in many cases). – phils Jun 24 '18 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.