For the cursor position, the answer can be found in $VIMRUNTIME/defaults.vim
:
" When editing a file, always jump to the last known cursor position.
autocmd BufReadPost *
\ if line("'\"") >= 1 && line("'\"") <= line("$") && &ft !~# 'commit'
\ | exe "normal! g`\""
\ | endif
This uses the special mark "
(see :h `quote
) which indicates the position of the cursor when the buffer was last exited. The auto command runs upon opening any buffer and verifies that the marked position falls within the buffer's existing lines. If so it'll jump to that position using the command g`{mark}
(see :h g'
) which jumps to a mark without changing the jumplist.
To restore the vertical position of the cursor line, though, I think you'll need to save your session each time you exit Vim. :mksession
(alias :mks
) is the command to do this. A variety of settings will be saved in the file you specify. You can control what exactly those are by changing the value of 'sessionoptions'
(alias 'ssop'
). In your case I believe you only need to have "winpos" included.
The basic workflow would be something like this...
vim /some/dir/foo.txt
...do work...
:mks! foosess.vim
:wq
..later, when you want to edit the file again....
vim -S /some/dir/foosess.vim
Yeah, that's not what one would call convenient if you want to do this for all your files. You might want to take a look at Tim Pope's plugin obsession.vim. It reduces some of the friction involved. Here's an excerpt from the front page...
- Instead of making me remember to capture the session immediately before exiting
Vim, allow me to do it at any time, and automatically re-invoke :mksession
immediately before exit.
- Also invoke :mksession whenever the layout changes (in particular, on BufEnter), so that even if Vim exits abnormally, I'm good to go.
- If I load an existing session, automatically keep it updated as above.
- If I try to create a new session on top of an existing session, don't refuse to
overwrite it. Just do what I mean.
- If I pass in a directory rather than a file name, just create a Session.vim inside of it.
- Don't capture options and maps. Options are sometimes mutilated and maps just
interfere with updating plugins.
Even then it's sort of a lot for just restoring vertical positioning. At least the cursor's location can be restored... :)
vim /some/dir/foo.txt
...do stuff...:mks sess.vim
,:wq
.... later...vim -S /some/dir/sess.vim
'sessionoptions'
value you need to restore the line positioning.