Reputation: 8073
I'm trying to write a Vim function that will execute a series of actions then returned to the line where the function was first triggered. Is it possible to somehow write a Vim function that can perform this behavior?
For example, if I'm somewhere in a vim buffer—say line 55 and type gg
to go to the first line, I can return to line 55 with <C-o>?
How can I write this behavior in a Vim function? Thanks in advance for the help.
Upvotes: 3
Views: 492
Reputation: 172550
First of all, you can do everything in a function that you'd normally type. To use <C-o>
, you just need the right escaping:
:execute "normal! \<C-o>"
Apart from that, you can also use dedicated Vimscript functions. Simplest is cursor()
, which does not modify the jump list (use line('.')
to save the original position in a variable; I'm hard-coding it here):
:call cursor(55, 0)
If you want your actions to be completely invisible, just restoring the cursor position isn't enough, though. The moves may also have affected the viewport; i.e. which buffer lines are displayed in the window. To keep that intact, use:
:let save_view = winsaveview()
" Your actions here
:call winrestview(save_view)
" Now the window looks exactly as before.
Upvotes: 7