From http://vim.wikia.com/wiki/Remove_unwanted_spaces

function TrimWhiteSpace()

autocmd FileWritePre * call TrimWhiteSpace()
autocmd FileAppendPre * call TrimWhiteSpace()
autocmd FilterWritePre * call TrimWhiteSpace()
autocmd BufWritePre * call TrimWhiteSpace()

On :write the cursor moves to the first non-blank character of the last trimmed line. How can I make it stay in place?

1 Answer 1


Save the position and restore it again, as in:

function TrimWhiteSpace()
  let save_cursor = getcurpos()
  call setpos('.', save_cursor)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.