Vim Tips Wiki
Register
Advertisement

With Easy Vim (:help 'insertmode'), the code to perform a last position jump :help last-position-jump can't restore a cursor position beyond EOL, because it will be executed in Normal mode.

The good news is that Vim seems to store a correct value in the viminfo :help viminfo file.

Solution: restore the last position while in Insert mode.

map          <Plug>LastPos <Nop>
cmap         <Plug>LastPos <Nop>
ino <silent> <Plug>LastPos <C-R>=''[setpos('.',getpos("'\""))]<CR>

augroup LastPos
    au! BufReadPost * call s:LastPos(&insertmode)
augroup END

func! s:LastPos(mode)
    if a:mode == 2
        au! LastPos InsertEnter
        call feedkeys("\<Plug>LastPos")
    elseif line("'\"") >= 1 && line("'\"") <= line("$")
        if a:mode == 1
            au LastPos InsertEnter * call s:LastPos(2)
        else
            normal! g`"
        endif
    endif
endfunc

Installation

Add the above code to your vimrc and it should just work.

If you are using the example vimrc :help vimrc_example.vim, you will probably have

  autocmd BufReadPost *
    \ if line("'\"") > 1 && line("'\"") <= line("$") |
    \   exe "normal! g`\"" |
    \ endif

in your vimrc -- make sure to remove this old code.

Advertisement