Is it possible for vim labels to remember the relative position of the line in the current window?

I am using the (modified version) solution suggested at http://www.thegeekstuff.com/2008/12/vi-and-vim-autocommand-3-steps-to-add-custom-header-to-your-file/ to automatically generate and update headers for my sources.

As explained on the above page, when you invoke a command write

in vim

, the following sequence of commands is executed:

  • The icon is set at the current file position.
  • Updated "Last Modified". This moves the cursor to the beginning of the file (where find and replace is done).
  • The cursor returns to the previously marked position.

This is fine, but there is a slightly annoying problem: suppose we are editing the line closer to the bottom of the window. If at this moment we save the file, due to the movement of the cursor (to update the title), the line that we edited jumps so that it is located in the middle of the window.

In my understanding, it 'a

moves the cursor to the place marked with the label a

and adjusts the contents of the window so that the current line is displayed in the middle of the window. I was wondering if there is a way to make the "marks" remember also the exact relative position of the selected line in the window and keep that position when returning to the mark again?

+3


source to share


2 answers


In docs: Restore cursor position .

   :map <F2> msHmtโ€ฆ'tzt`s

      

(I missed the irrelevant parts with ellipses).



ms  store cursor position in the 's' mark
H   go to the first line in the window
mt  store this position in the 't' mark

      

Position restoration violation:

't  go to the line previously at the top of the window
zt  scroll to move this line to the top of the window
`s  jump to the original position of the cursor

      

+2


source


The label itself only stores the position; the view (what is shown in the current window) is not part of it.

What you are looking for is a couple of functions winsaveview()

and winrestview()

. They preserve the cursor position (like labels, but don't automatically adapt to changes in the buffer, which you probably won't need to update the titles), as well as details of what is currently displayed in the window. It is recommended to use them according to the methods; in custom mappings or commands, it also has the advantage of not knocking off the label.




If you are using :substitute

to update the title, you can also change the current search pattern (if not using :function

) and search history. It is difficult to undo all this; I know because I wrote such a plugin myself ( AutoAdapt plugin ). You might want to take a look at its implementation for further advice (or start using it in general). (The plugin page also contains links to various alternative plugins.)

+1


source







All Articles