A short #Emacs story from yesterday:
I've been using the macro facility in Emacs for at least a few years. The interface is very simple: you press F3, then do your thing, and when you're done, you press F4 to save the macro, and all the subsequent presses of F4 will replay that macro (understood as a sequence of key presses).
But yesterday I wanted to have quick access to two different macros. I think that Vim has a good support for this sort of macros out of the box. I read in the manual, that there is a command "insert-kbd-macro", which pastes to the current buffer the following snippet of code:
(setq last-kbd-macro "sequence of keystrokes ...")
So here's what I did:
I first invoked the "describe-key" function on the F4 key, which eventually lead me to the definition of procedure "kmacro-call-macro". After some experiments, I was able to write something like this to my .emacs file:
(defun my-first-macro (arg)
(interactive "P")
(kmacro-call-macro arg t nil
"pasted sequence of keystrokes ..."))
(global-set-key (kbd "<f5>") 'my-first-macro)
While it may not be the most ergonomic approach to this problem, I feel that - in its peculiar way - it is the most powerful approach.
@PaniczGodek Interesting approach! But I saw this and immediately thought of how vim lets you run macros stored in arbitrary registers (right?). We could do the same with emacs. Emacs already has `kmacro-to-register`, but no command for calling a macro *from* a register (weird right?).
1/2
(defun kmacro-call-from-register (register &optional arg)
(interactive `(,(register-read-with-preview "Call macro from register: ")
current-prefix-arg))
(when-let* ((kmacro (kmacro--keys (get-register register)))
(_ (or (vectorp kmacro)
(stringp kmacro)
(user-error "Value of register %c is not a macro"
register))))
(kmacro-call-macro arg t nil kmacro)))
(without docstring, so it fits in a toot)
@PaniczGodek I'm slightly disbelieving that there isn't something like this already in Emacs. But if there isn't, maybe I'll upstream it...
@HugoHeagren a quick search reveals this:
https://www.gnu.org/software/emacs/manual/html_node/emacs/Keyboard-Macro-Registers.html
(but I haven't ever used registers, and frankly, both memorizing and using things like C-x C-k x r is my least favorite part of Emacs, to say it mildly)
@PaniczGodek ahh, I missed that because its called `jump-to-register'. I might submit a patch to alias it with something meaningful for kmacros as well.
@HugoHeagren I think that the part on keyboard macros in the manual could also have a reference to the section about keyboard macro registers
@HugoHeagren @PaniczGodek Quoting the manual, "(emacs) Keyboard Macro Registers":
"To execute the keyboard macro in register R, type ‘C-x r j R’. (This
is the same command used to jump to a position or restore a frameset.)"