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

How to write a macro that saves the current file and advances to the next file in the argument list in Vim?

Answer

:wn

Explanation

:wn (short for :wnext) writes the current buffer to disk and immediately advances to the next file in the argument list. Used inside a macro, this enables an interactive multi-file processing workflow where you make changes to each file, review them, and move on — all without leaving Vim or writing a separate script.

How it works

  1. Populate the argument list: :args **/*.py (or open multiple files from the shell: nvim *.py)
  2. Record a macro that makes changes and ends with :wn<CR>:
    qa{edits}:wn<CR>q
    
  3. Run it repeatedly: @a then @@ to repeat, or 99@a to run up to 99 times
  4. When Vim reaches the last file, :wn returns an error — this stops the macro chain automatically

Example

Strip trailing whitespace from every Python file in a project:

:args **/*.py        " load all .py files into the arglist
qa                   " start recording macro 'a'
:%s/\s\+$//e         " strip trailing whitespace (e flag = no error if none found)
:wn<CR>              " save and move to next file
q                    " stop recording
99@a                 " process up to 99 files

The e flag on :s prevents the macro from stopping early when a file has no trailing whitespace.

Tips

  • :wN (:wprevious) — write and move to the previous file in the arglist
  • :wfirst / :wlast — write and jump to the first or last argument
  • To process files without saving (read-only inspection), use :n (next) alone
  • :args with no arguments shows the current arglist and highlights the active file
  • For fully automated changes across all files at once, :argdo %s/old/new/ge | update is faster — :wn shines when you need to review each file before committing

Next

How do I enable matchit so % jumps between if/else/end style pairs?