Gio
Gio

Reputation: 3340

Vim unwanted jump to end of file after write

When I write to a file with :w, vim sometimes (NOT ALWAYS) jumps to the end of the file after the write operation is complete. I don't understand why this happens. I've been going through my .vimrc to see if I have some kind of bug. My .vimrc is quite large so I don't include the full source here, I think the only parts of my .vimrc which are perhaps relevant to this question are the following parts:

nore ; :
inoremap jj <Esc>

" Automatically remove all trailing whitespace.
" Every time the user issues a :w command, Vim will automatically remove all
" trailing whitespace before saving
autocmd BufWritePre * :%s/\s\+$//e

" Restore cursor position
au BufReadPost *
            \ if line("'\"") > 0|
            \ if line("'\"") <= line("$")|
            \ exe("norm '\"")|
            \else|
            \exe "norm $"|
            \endif|
            \endif                           

However I don't see how these parts of my .vimrc can cause the jump behavior after writing, a full source of my .vimrc is available here. I hope somebody has an idea about what is causing the unwanted jump.

Upvotes: 0

Views: 328

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172510

Even with @romainl's addition of the mark, this still isn't fully transparent:

  • the view (of displayed lines) may still change (winsaveview() instead of a mark would fix that)
  • the :s command clobbers the last search pattern

A plugin (like my DeleteTrailingWhitespace plugin) would provide a more robust solution. (The plugin page has links to alternative plugins.)

Upvotes: 0

romainl
romainl

Reputation: 196476

Here is a command from my ~/.vimrc:

command! -range=% TR mark `|execute <line1> . ',' . <line2> . 's/\s\+$//'|normal! ``

The trick is to create mark ` before the trimming and jump back to it afterward.

You can change your autocmd to:

autocmd BufWritePre * :mark `|%s/\s\+$//e|normal! ``

Upvotes: 4

Related Questions