44

I know about the :bufdo command, and was trying to combine it with a macro I had recorded (@a) to add a #include in the proper spot of each of the header files I'd loaded. However, I couldn't find an easy way to run the macro on each buffer. Is there a way to execute a macro through ex mode, which is what :bufdo requires? Or is there another command I'm missing?

Caleb Huitt - cjhuitt
  • 14,785
  • 3
  • 42
  • 49
  • take a look at http://stackoverflow.com/questions/1291962/replay-a-vim-macro-until-end-of-buffer EDIT: never mind this – gruntled Jun 11 '10 at 16:07
  • @gruntled: Thanks for the link. I skipped over that because the question didn't seem to apply, but the techniques should work. I voted to close this one. – Caleb Huitt - cjhuitt Jun 11 '10 at 16:09

3 Answers3

53

You can do it like this:

:bufdo execute "normal @a" | write

The normal command will run the macro, but it has to be run using :execute, otherwise the pipe character will be interpreted as a normal-mode character.

Dave Kirby
  • 25,806
  • 5
  • 67
  • 84
15

You have to use normal to execute normal mode commands, such a macro execution (@a) in command mode:

:bufdo normal @a
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 1
    This will only work if 'autowrite' is enabled, other wise it will stop with an error when it tries to change to the second buffer, since it will be abandoning a modified buffer. – Dave Kirby Jun 12 '10 at 09:07
  • 3
    I would do `:se hidden` before running this so that I can change to another buffer without saving; and then save all buffers together with `:wa` – Gautam Jun 29 '17 at 12:31
0

The only alternative I could come up with was to add the :w and :bn commands to the macro, so that it would automatically save and move to the next buffer. I could then run the command on the other 52 buffers by typing 52@a. This worked, but to me is a much different conceptual model than :bufdo, and I'm hoping someone else will point me in the direction of something more similar to :bufdo.

Caleb Huitt - cjhuitt
  • 14,785
  • 3
  • 42
  • 49