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

How do I remove trailing whitespace without clobbering @/ or showing no-match errors?

Answer

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

Explanation

Trailing whitespace cleanup is a common housekeeping step, but a plain substitution can leave side effects: it can overwrite your last search pattern (@/) and throw a noisy error when no lines match. :silent keeppatterns %s/\s\+$//e solves both problems in one command, so you can clean a buffer quickly without disturbing your editing flow. This is especially useful before commits or formatting passes.

How it works

  • :silent suppresses command-line noise
  • keeppatterns prevents the substitution from replacing your active search register
  • %s/.../.../ runs substitution over the whole buffer
  • \s\+$ matches trailing whitespace at end-of-line
  • // replaces it with nothing
  • e suppresses "pattern not found" errors for clean files

Example

Before:

const a = 1···
const b = 2
return a + b··

After running the command:

const a = 1
const b = 2
return a + b

Tips

  • Keep this as an explicit command for pre-commit cleanup when you do not want autoformatters to run.
  • If you want to clean only part of a file, replace % with a range like :'<,'>.
  • You can map it to a leader key, but keeping the full Ex form visible helps when debugging side effects in complex workflows.

Next

How do I preview a fuzzy tag match in the preview window without immediately switching buffers?