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

How do I trim trailing whitespace in a file without polluting jumplist or search history?

Answer

:keepjumps keeppatterns %s/\s\+$//e<CR>

Explanation

Bulk whitespace cleanup is common, but a plain substitution can leave side effects: your last search pattern changes and jump navigation gets noisy. :keepjumps keeppatterns %s/\s\+$//e<CR> performs the cleanup while preserving editing context.

This is a strong default for advanced users who rely on /, n, and jump-list navigation during refactors. You get clean lines without damaging the state you were using to move through code.

How it works

  • keepjumps prevents jump-list updates from the command
  • keeppatterns keeps the current search register (@/) unchanged
  • %s/\s\+$//e removes trailing whitespace on every line
  • % means full buffer
  • \s\+$ matches one or more whitespace characters at end of line
  • e suppresses errors on lines with no match

The result is a quiet, idempotent cleanup command you can run repeatedly.

Example

Before:

const a = 1··
const b = 2····
const c = 3

Run:

:keepjumps keeppatterns %s/\s\+$//e<CR>

After:

const a = 1
const b = 2
const c = 3

Tips

  • Add lockmarks if you also want to preserve marks during large scripted edits
  • Use the same pattern with :argdo for multi-file cleanup once you trust it

Next

How do I run one substitution in nomagic mode so most regex characters are literal?