One-key vim macro / search-and-run-macro interactively

1k Views Asked by At

I know that I can record macros with q<char> and run them with @<char>. I also know that I can run the last-used macro with @@.

But @@ is two whole keystrokes! That's one too many! Especially if I'm running that macro a lot of times. I know about <num>@<char> but what if I don't know <num> in advance?

What I'm looking for, really, is something like an interactive search-and-replace (see Interactive search/replace regex in Vim?) that runs macros. Can this be done?

2

There are 2 best solutions below

0
On BEST ANSWER

Apply macro a in normal mode with one keystroke:

:nnoremap , @a

You can then use "," when you want to apply the macro, or "n" when you want to skip to the next search occurrence

To interactively apply macro to search matches:

  1. define macro with "qa"
  2. search with "/"
  3. apply macro to match with ","
  4. skip match with "n"
0
On

I have this in my ~/.vimrc:

" <A-@>         Repeat last macro with a single key combination.
nnoremap <A-2> @@

So, first I replay as usual with the register name, e.g. @a. Then I repeat with @@. Then I realize I need several more repeats (but cannot use a [count]), so I switch to Alt + @ (@ is above 2 on the US-English keyboard layout).