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

How do I strip trailing whitespace without clobbering my last search pattern?

Answer

:keeppatterns %s/\s\+$//e

Explanation

Bulk cleanup commands often damage your navigation flow by overwriting the last search pattern (@/). :keeppatterns prevents that side effect, so you can remove trailing whitespace and keep your current /... search context intact. This is especially useful in long review sessions where you alternate between cleanup and targeted search jumps.

How it works

  • :keeppatterns runs the following command without changing the search register.
  • %s/.../.../ applies substitution to the entire buffer.
  • \s\+$ matches one or more whitespace characters at end of line.
  • // replaces the match with nothing (deletes it).
  • e suppresses errors on lines with no match, so the command is quiet and repeatable.

Example

Before:

alpha··
beta
gamma····

(Here · represents trailing spaces.)

Run:

:keeppatterns %s/\s\+$//e

After:

alpha
beta
gamma

Tips

  • If you want to save only when edits were made, run :update afterward.
  • Combine with :nohlsearch only if you intentionally want to clear highlights; :keeppatterns alone keeps your search pattern available for n/N.

Next

How do I save only real file buffers when running bufdo across many open buffers?