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
- Populate the argument list:
:args **/*.py(or open multiple files from the shell:nvim *.py) - Record a macro that makes changes and ends with
:wn<CR>:qa{edits}:wn<CR>q - Run it repeatedly:
@athen@@to repeat, or99@ato run up to 99 times - When Vim reaches the last file,
:wnreturns 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 :argswith 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 | updateis faster —:wnshines when you need to review each file before committing