vimtricks.wiki Concise Vim tricks, one at a time.

How do I run a macro across all open buffers at once?

Answer

:bufdo normal @a

Explanation

The :bufdo command executes an Ex command in every open buffer, and when combined with :normal @a, it replays macro a across all of them. This is the fastest way to apply a repetitive edit to every file you have open without manually switching buffers.

How it works

  • :bufdo {cmd} iterates through every buffer in the buffer list and runs {cmd} in each one
  • normal @a executes the keystrokes stored in register a as if you pressed them in normal mode
  • Together, :bufdo normal @a replays your macro in every buffer
  • Add | update at the end to save each modified buffer automatically

Example

Suppose you have 10 Python files open and you need to add a copyright header to each. First, record the macro in one buffer:

qaggO# Copyright 2025 Acme Inc.<Esc>q

This records into register a: go to line 1 (gg), open a new line above (O), type the header, and exit insert mode.

Now apply it to every open buffer:

:bufdo normal @a | update

Every buffer gets the copyright header added at the top, and each file is saved.

Tips

  • Use :bufdo with any Ex command, not just macros: :bufdo %s/old/new/ge | update runs a substitution across all buffers
  • The e flag in %s/old/new/ge suppresses errors when a buffer has no matches, preventing the command from aborting
  • Use :argdo normal @a to run the macro only on files in the argument list instead of all buffers
  • Use :cfdo normal @a to run it only on files in the quickfix list — useful after a :vimgrep search
  • :windo normal @a runs the macro in every visible window instead of every buffer
  • :tabdo windo normal @a covers every window in every tab
  • Always test your macro on a single buffer first before unleashing it with :bufdo
  • If something goes wrong, :bufdo undo reverts the change in every buffer

Next

How do I edit multiple lines at once using multiple cursors in Vim?