Comment by eieio
6 days ago
oh wow, TIL, I'm pretty surprised I didn't know this trick!
back when I was vim golfing the normal solution was to make the macro recursive. So you'd record your macro, and you'd end it with '+@q' (move to next line and run the macro again). Then you run the macro once and it runs over every line.
This ends up being really efficient in terms of keystrokes but in practice I think it's hard to think about and not very ergonomic, so I don't end up using it much. But it's a fun trick for golfing.
There's also the no-macro solution where you just use ":%norm [series of keystrokes]" to run the given keystrokes on each line, but that comes with the added difficulty of not giving any visual feedback of what the keystrokes will do before you submit the entire line.
One thing to keep in mind is that ":%norm" will place the cursor at the start of each line, before any indentation, whereas the trick of ending the macro with "+" will place the cursor at the start of each line after the indentation. But this can be worked around with ":%norm ^@q", using ^ to skip indentation before running macro q on each line.
Related to that, macros are just recorded into normal registers. You can get it out with:
Edit it, and put it back into the register with
Heads up - you should use "qD instead of "qdd to avoid an extra newline at the end of the register contents. (In fact the current Vim 9.1.954 behavior seems a bit odd in that it moves the cursor down, but not to the start of the line, as if j is pressed... Seems like a bug to me.)
1 reply →
Most often when I run a macro it's to change lines matching searches, so I just start the macro with the search (or `n` if the macro doesn't do additional searches) then I end the macro with `@q` (or whatever register), then execute the macro. I don't think I've ever had occasion to run a macro on every line, though I've had occasion to run macros over line ranges (but still, all matching a specific pattern).
To run a macro on the start of each line matching your search, you can use:
Here, g// repeats the most recent search, and norm @q runs the q macro on each matched line. This is not quite the same as starting the macro with a search, since the cursor is at the start of the line and not at the start of the match, but it's often good enough.
You can also restrict it to just the matches inside a range of lines: First select the lines in visual mode, then type :g//norm @q, which will cause Vim to insert a range before g, as in: :'<,'>g//norm @q, which means "between line '< and '>, find lines containing a match of the most recent search, and run @q on each such line".
Thanks!