Alex Rivera | Logout

How to return to the previous point in Vim

Asked 2011-12-30T08:24:23.330
15

In Vim there is a command ``.` to return exactly to where last edited text.

But my question is: How to make it automatic? What I mean is, every time I exit and reopen the same file again, it brings me to the point where I left.

I saw my friend's Vim has that behavior but he doesn't know how to do it.

vim
Edit
Report

4 Answers

11

I use these commands a lot:

CTRL-O Go to [count] Older cursor position in jump list (not a motion command).

CTRL-I Go to [count] newer cursor position in jump list (not a motion command).

ma Set mark a at cursor position (does not move the cursor, this is not a motion command).

'a Jump to the mark a in the current buffer.

gi Insert text in the same position as where Insert mode was stopped last time in the current buffer.

answered 2011-12-30T08:49:26.833
10

You'll want to read this vim tip.

answered 2011-12-30T08:29:24.130
4

Read this: :help last-position-jump

answered 2011-12-30T08:30:56.150
2

Put this lines on your ~/.vimrc file

 " When editing a file, always jump to the last cursor position
 autocmd BufReadPost *
 \ if line("'\"") > 0 && line("'\"") <= line("$") |
 \   exe "normal g`\"" |
 \ endif

This only will help you next time you open vim to restore your cursor position.

Another idea is placing this on your ~/.bashrc

lvim='vim -c "normal '\''0"'

It will allow you to open the last edited file.

Update!

alias lvim="vim -c':e#<1'"

The above alias will open vim in command mode -c to edit an alternative file # in this case the first one <1 which is the last one.

For neovim I have this:

In your init.lua

  require('autocmds')

In your lua directory create a file called autocmds.lua:

local augroups = {}

augroups.restore_position {

restore_cursor_position = {
    event = "BufRead",
    pattern = "*",
    command = [[call setpos(".", getpos("'\""))]],
},

}

for group, commands in pairs(augroups) do
local augroup = vim.api.nvim_create_augroup("AU_"..group, {clear = true})

for _, opts in pairs(commands) do
    local event = opts.event
    opts.event = nil
    opts.group = augroup
    vim.api.nvim_create_autocmd(event, opts)
end
end
answered 2012-05-11T23:01:45.697

Your Answer