I'd like to delete all spaces on empty lines before saving files. I've figured out how to do that.

autocmd BufWritePre * silent! %s/\v^\s+$//e

But this moves my cursor to the line where the spaces have been removed. I know that not in autocmd I can just press '' and that would do what I want, but I can't figure out how to achieve this in autocmd.

2 Answers 2


You could achieve '' on an autocmd using the following:

:call setpos('.', getpos("''"))

Check :help function-list for built-in functionality on VimL.


okay, how to combine it with search and replace? Another autocmd after the search and replace one?

Vim documentation is very comprehensive and well-written, you should definitively try reading it.

If you are going to write autocmds then :help cmd-lines is a must read:

autocmd BufWritePre * %s/\v^\s+$//e | call setpos('.', getpos("''"))

You should also consider using autocmd groups, as explained in :help autocmd-groups.

  • 1
    okay, how to combine it with search and replace? Another autocmd after the search and replace one? Apr 11, 2016 at 13:10
  • thanks!. You might want to fix typo then :help cmd-lines Apr 11, 2016 at 13:36
  • Okay, this isn't actually working. Somehow when I save file the cursor goes to the start of the file (even when I'm pressing '' manually). However when I'm pressing manually backtick twice the cursor moves to the correct position (where it was before saving file). But! Somehow if I would change double single quote to double backtick in call setpos('.', getpos("``")) when I save file cursor still goes to the start of the file. Apr 12, 2016 at 7:39
  • 1
    IMHO It works just fine. Apr 12, 2016 at 18:20

Inspired from this answer on another post, a possible solution would be

autocmd! BufWritePre * call KeepEx('silent! %s/\v^\s+$//e')

function! KeepEx(arg)
  let l:winview = winsaveview()
  execute a:arg
  call winrestview(l:winview)

using the function KeepEx which can execute arbitrary functions and afterwards restore the old view.

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.