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

How do I remove trailing whitespace across all open buffers and save only changed files?

Answer

:bufdo keeppatterns %s/\s\+$//e | update

Explanation

If you keep many files open during a refactor, cleaning trailing whitespace one buffer at a time is slow and error-prone. :bufdo lets you run one Ex pipeline across every listed buffer, while update writes only buffers that actually changed. This keeps the operation fast and avoids noisy writes.

How it works

  • :bufdo iterates through listed buffers and executes the following command in each
  • keeppatterns prevents %s from overwriting your last search pattern (@/)
  • %s/\s\+$//e removes trailing whitespace on each line; e suppresses pattern-not-found errors in clean buffers
  • | update writes only if the buffer was modified

Example

Use this after a broad multi-file edit where trailing spaces may have been introduced:

:bufdo keeppatterns %s/\s\+$//e | update

This applies cleanup to all open buffers and persists only actual diffs.

Tips

  • Pair with :args + :argdo when you want explicit file scope instead of all open buffers
  • Run :ls first if you want to confirm which buffers are listed before batch editing
  • If you want to skip special buffers, filter your working set first (for example by opening only target files before running :bufdo)

Next

How do I open a vertical diff between index and working tree for the current file in vim-fugitive?