Search code examples
emacselispemacs23

Create an Emacs semi-interactive macro


I would like to create a quick Emacs macro (with C-x () which takes some user input from the minibuffer each time it's executed.

The usage scenario is this:

You have a complex text to change where the regexp query substitution just doesn't cut it, and you want to create a macro which:

  1. does some complex changes in the current line of text
  2. position the cursor at a specific point
  3. asks the user for some text in the minibuffer
  4. possibly executes some other action, then exits

I have tried using

M-x eval-expression

and

(insert-text (read-from-minibuffer ">"))

but after creation, the macro obviously (in retrospect... :) ) repeats the same keystrokes and therefore doesn't give me a chance to insert some new text.

Can this be done?

Thank you for the help!


Solution

  • Use kbd-macro-query, normally bound to C-x q. Specifically, you should use C-u C-x q, which enters a recursive edit mode when you're defining the query and lets you enter whatever text you like to a minibuffer prompt, but note that the text you enter here will not be part of the keyboard macro. While you're defining the macro, you'll need to hit <enter> once to end the recursive edit and then hit it again to send the text to the minibuffer prompt so you can continue defining the macro. Once you finishing defining the macro, you can then execute it and it will stop at the point you called kbd-macro-query, prompt for the text, and then hitting <enter> will work as expected.