KarlsD
KarlsD

Reputation: 667

Save exact cursor position in the line

I am looking way to make Vim save my exact cursor position when I exit it or switch between buffers.

I have the following configuration in my config:

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

It only returns the cursor to the beginning of the line where my cursor was, but not the position of the cursor in it; i.e. my cursor returns to the beginning of the line, not where it was in it.

Is there any way to bring back the exact position of the cursor?

Upvotes: 0

Views: 1084

Answers (1)

romainl
romainl

Reputation: 196826

Your snippet seems to be a variant of the one found under :help restore-cursor, which works the way you want:

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

The difference is your use of g' ("g then single quote") versus their use of g` ("g then backtick"):

  • the former jumps to the beginning of the line marked with marker ", just like 'a would jump to the beginning of the line marked with marker a,
  • the latter jumps to the exact location of marker ", just like `a would jump to the exact location of marker a.

See :help mark-motions and, more specifically, :help g'.

Upvotes: 1

Related Questions