93

When I quit VIM and open the same file again, I am positioned at the start of the file. How can I preserve the last cursor position?

2

11 Answers 11

81

Taken from http://amix.dk/vim/vimrc.html

" Return to last edit position when opening files (You want this!)
autocmd BufReadPost *
     \ if line("'\"") > 0 && line("'\"") <= line("$") |
     \   exe "normal! g`\"" |
     \ endif
5
  • 2
    Can you explain what the if statement is doing here? I'm reading it as "Only restore the cursor if the cursor is after the first line or before the last line", and it's not clear to me what difference that makes. I currently added autocmd BufReadPost * normal! g`"zv to my vimrc and it seems to work, but I guess I don't understand the potential pitfalls of unconditional mark restoring.
    – robru
    Commented Jun 8, 2014 at 15:36
  • 14
    Ah, if the file is truncated outside of vim, and vim's mark is on a line that no longer exists, vim throws an error. Fixed that with autocmd BufReadPost * silent! normal! g`"zv
    – robru
    Commented Jun 8, 2014 at 15:42
  • 6
    I didn't know why the zv part... Turns out it "unfolds" current line. Wow, there's always something more to learn even if you know how to quit Vim. Commented Oct 5, 2020 at 10:16
  • 1
    This actually worked for me, where the source $VIMRUNTIME/vimrc_example.vim and silent! source $VIMRUNTIME/defaults.vim didn't. Commented May 19, 2022 at 0:37
  • 1
    @TomaszGandor Is no one going to acknowledge the joke Tomasz made here? I chuckled, haha. Commented Feb 18, 2023 at 14:24
50

The "out of the box" .vimrc enables this with the statement:

source $VIMRUNTIME/vimrc_example.vim

You may just need to restore this statement in your .vimrc. In any case, see vimrc_example.vim and also see the line() function in the Vim manual for a discussion of how it works.

3
39

The last edit position is automatically preserved by Vim, and is available as "special" jump mark .. Other special marks include " (position you saved from) and ' (position you jumped from).

You can jump to a mark by typing '<mark>, so '. will take you to the place of the last edit, '' will take you back to where you were, and '" takes you to the position you saved the file at.

That and more about Vim marks at Vim.Wikia.

2
  • It doesn't restore the column pos. Commented Jan 4, 2022 at 10:33
  • 2
    @Rainning: That would then be <backtick>-<mark>, as per the linked Wikia page.
    – DevSolar
    Commented Jan 4, 2022 at 11:41
21

There is a plugin (I am the author) called vim-lastplace that will intelligently return you to the last edit that you made.

It also has a configuration option to ignore certain file types. By default it will ignore commit messages for git, svn, and mercurial. For these file types it will start your cursor at the first line. The code snippets above will jump into the middle of your commit message file (where you left off in your previous commit) even though that's probably not what you want. vim-lastplace fixes this problem.

18

For Neovim users who are looking for a pure Lua version:

-- Restore cursor position
vim.api.nvim_create_autocmd({ "BufReadPost" }, {
    pattern = { "*" },
    callback = function()
        vim.api.nvim_exec('silent! normal! g`"zv', false)
    end,
})
1
  • 1
    nvim_exec is deprecated, new API function: vim.api.nvim_exec2('silent! normal! g`"zv', { output = false })
    – Andrey M.
    Commented Nov 24 at 11:34
17

A more up-to-date version of the currently accepted answer:

silent! source $VIMRUNTIME/defaults.vim
3
  • 4
    This should be the accepted answer Commented Nov 3, 2021 at 11:58
  • 1
    E484: Can't open file /usr/share/vim/vim81/defaults.vim
    – rogerdpack
    Commented Dec 26, 2021 at 5:40
  • Then why not runtime! defaults.vim?
    – Fuseteam
    Commented Apr 21 at 14:05
9

Make sure ~/.viminfo is readable and writable by the user running vim. Somehow I had ended up with a copy readable only by root in my standard user home directory, which meant that the last cursor position could not be stored.

1
  • 1
    Great. This helped me.
    – Sinai
    Commented May 4, 2021 at 8:13
6

I'm adding more complete example to @Mariano answer https://stackoverflow.com/a/14449484/108654 with some additional checks

" Only do this part when compiled with support for autocommands
if has("autocmd")
  augroup redhat
  autocmd!
  " When editing a file, always jump to the last cursor position
  autocmd BufReadPost *
  \ if line("'\"") > 0 && line ("'\"") <= line("$") |
  \   exe "normal! g'\"" |
  \ endif
  augroup END
endif
0
0

You could try the :mks command (make session). It stores a script file which, when run through vim, restores your current editing session, including all open files and the cursor position.

1
  • It creates a Session.vim file in the local directory. This is not what I wanted. I now vim can automatically save the editing position and restore it when the same file is opened. I just don't know how. Commented Oct 25, 2011 at 19:04
0

Neovim lua solution from Neovim repo issue

  • covers edge cases like last cursors pos being outside buffer and ignored file types.
vim.api.nvim_create_autocmd('BufRead', {
  callback = function(opts)
    vim.api.nvim_create_autocmd('BufWinEnter', {
      once = true,
      buffer = opts.buf,
      callback = function()
        local ft = vim.bo[opts.buf].filetype
        local last_known_line = vim.api.nvim_buf_get_mark(opts.buf, '"')[1]
        if
          not (ft:match('commit') and ft:match('rebase'))
          and last_known_line > 1
          and last_known_line <= vim.api.nvim_buf_line_count(opts.buf)
        then
          vim.api.nvim_feedkeys([[g`"]], 'nx', false)
        end
      end,
    })
  end,
})

Basically this is what it does:

  • uses nested auto commands.

  • outer autocmd activates on "BufRead" (= after reading the file into the buffer) and creates create:

    • inner autocmd opon "BufWinEnter" (= After a buffer is displayed in a window.)
      • do file types and number of lines in lastpos vs lines in file checks
      • based on result restore position or do nothing
  • sources:

-1

In support of other posts, a version that works in a neovim init.lua is:

vim.api.nvim_create_autocmd('BufReadPost', { command = "silent! normal! g`"zv" })

The command is just one line, no line break in the middle. This is a bit more direct, and seems to align more with the nvim documentation on autocmd.

1
  • That isn't valid Lua. Commented Apr 6 at 0:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.