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

How do I automatically remove trailing whitespace every time I save a file?

Answer

autocmd BufWritePre * :%s/\s\+$//e

Explanation

By adding an autocmd for the BufWritePre event, you can make Vim automatically strip trailing whitespace from every line each time you save. This keeps your files clean without you ever having to think about it — no more noisy whitespace-only diffs in version control.

How it works

  • autocmd defines an automatic command that fires on a specific event
  • BufWritePre is the event that triggers just before a buffer is written to disk
  • * is the file pattern — the wildcard means it applies to all file types
  • :%s/\s\+$//e is the substitute command that removes trailing whitespace:
    • % applies to every line in the file
    • \s\+$ matches one or more whitespace characters at the end of a line
    • The replacement is empty (delete the match)
    • e suppresses the error when no match is found, so the save proceeds silently

Example

Add this line to your vimrc:

autocmd BufWritePre * :%s/\s\+$//e

Now given a file with trailing spaces (shown as ·):

function greet() {··
    console.log("hi");···

Every time you run :w, the file is saved as:

function greet() {
    console.log("hi");
}

Tips

  • Wrap it in an augroup to prevent duplicate autocmds when re-sourcing your vimrc:
augroup TrimWhitespace
    autocmd!
    autocmd BufWritePre * :%s/\s\+$//e
augroup END
  • The autocmd! inside the group clears previous autocmds in that group before redefining them
  • Limit to specific file types if needed: autocmd BufWritePre *.py,*.js,*.go :%s/\s\+$//e
  • This command moves the cursor to the last substitution location — to preserve cursor position, use a function:
function! TrimWhitespace()
    let l:save = winsaveview()
    keeppatterns %s/\s\+$//e
    call winrestview(l:save)
endfunction
autocmd BufWritePre * call TrimWhitespace()
  • keeppatterns prevents the substitution from overwriting your last search pattern
  • Be careful with Markdown files where trailing double-spaces indicate a line break — consider excluding them: autocmd BufWritePre * if &filetype != 'markdown' | :%s/\s\+$//e | endif

Next

How do I edit multiple lines at once using multiple cursors in Vim?