Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cursor jump in Vim after save

I started to experience a strange behavior in Vim - when saving a file (:w) the cursor jumps to a specific location in a file. The location is constant and is different for different files, that is, it can be a beginning of a function etc, but if I move the line up or down, the location after save remains.

My .vimrc is quite long, and for now I tried only :noautocmd command.

How can I fix or debug this?

like image 334
valk Avatar asked Nov 30 '22 09:11

valk


1 Answers

I have had the same issue, not due to syntastic_auto_jump setting, but due to a command I had placed for trailing whitespace:

autocmd FileType * autocmd BufWritePre <buffer> :%s/\s\+$//e

This was moving the cursor to the last line that whitespace was being replaced. Essentially, any sort of command making changes to the document and changing the cursor without restoring it might cause similar behavior.

P.S.: The trailing whitespace can be fixed either by using a function that restores the cursor, like the following (taken from here)

function! <SID>StripTrailingWhitespaces()
    let l = line(".")
    let c = col(".")
    %s/\s\+$//e
    call cursor(l, c)
endfun

autocmd BufWritePre * :call <SID>StripTrailingWhitespaces()

or using a plugin that replaces trailing whitespaces and restores the cursor for you

like image 151
nettrino Avatar answered Dec 04 '22 22:12

nettrino