Vim scripting: Preserve cursor position and screen view in function call

前端 未结 5 945
庸人自扰
庸人自扰 2021-02-02 11:11

I have some Vim functions that make changes to the document format. When I call this function, I currently use something like the following to save and restore my cursor positio

5条回答
  •  灰色年华
    2021-02-02 11:30

    you can use getline() to save the current buffer line and winline() to save the current window line.

    So it would go something like this:

    • save window line with winline()
    • move the cursor to the top of the window with :normal! H
    • save buffer line with getline()
    • ...
    • restore the buffer line with :exec 'normal! '.myline.'G'
    • scroll to the top with :normal zt
    • then restore the original window line with :exec 'normal! '.mywinline.'H'

    There might be a few special cases you will have to take care of such as if the position is near the end or beginning of the file or if the file is smaller then the window size.

提交回复
热议问题