:help last-position-jump
in Vim
The help for Vim actually includes documentation for how to do this. Open Vim, and run :help last-position-jump
or :help restore-cursor
. Here is what it says:
*restore-cursor* *last-position-jump* >
autocmd BufReadPost *
\ if line("'\"") >= 1 && line("'\"") <= line("$") && &ft !~# 'commit'
\ | exe "normal! g`\""
\ | endif
Another autocommand. This time it is used after reading any file. The
complicated stuff after it checks if the '" mark is defined, and jumps to it
if so. The backslash at the start of a line is used to continue the command
from the previous line. That avoids a line getting very long.
See |line-continuation|. This only works in a Vim script file, not when
typing commands at the command-line.
If you want to make use of this code, copy and paste these documented lines into your ~.vimrc
:
autocmd BufReadPost *
\ if line("'\"") >= 1 && line("'\"") <= line("$") && &ft !~# 'commit'
\ | exe "normal! g`\""
\ | endif
:help last-position-jump
in Neovim
Interestingly, the code in Neovim's help files don't match Vim's in this regard. Here is the result of :help last-position-jump
or :help restore-cursor
in Neovim:
*restore-cursor* *last-position-jump*
autocmd BufRead * autocmd FileType <buffer> ++once
\ if &ft !~# 'commit\|rebase' && line("'\"") > 1 && line("'\"") <= line("$") | exe 'normal! g`"' | endif
Another autocommand. This time it is used after reading any file. The
complicated stuff after it checks if the '" mark is defined, and jumps to it
if so. The backslash at the start of a line is used to continue the command
from the previous line. That avoids a line getting very long.
See |line-continuation|. This only works in a Vim script file, not when
typing commands at the command-line.
To make use of this in NeoVim, add the following code to your init.lua
file:
vim.cmd([[
autocmd BufRead * autocmd FileType <buffer> ++once
\ if &ft !~# 'commit\|rebase' && line("'\"") > 1 && line("'\"") <= line("$") | exe 'normal! g`"' | endif
]])