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
:keeppatternsruns 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).esuppresses 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
:updateafterward. - Combine with
:nohlsearchonly if you intentionally want to clear highlights;:keeppatternsalone keeps your search pattern available forn/N.