Vim Tips Wiki

Restore the cursor position after undoing text change made by a script

1,610pages on
this wiki
Revision as of 06:37, July 13, 2012 by JohnBot (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Tip 1595 Printable Monobook Previous Next

created 2008 · complexity basic · author Lpb612 · version 7.0

If you modify the text using some script, and then undo it, the cursor may not return to the place where it was before the script was run (called). This comes from the fact that when Vim performs an undo, it restores the position to where the change happened, and not where the cursor was before the change. For example:


The cursor will be on line 6, not line 3.

Say you have a function func() that changes the text. Cursor is somewhere before the calling. You can insert

normal ix
normal x

in the beginning of the function/script (before other changes). Then when the script returns, an undo will restore the cursor position to the place right before func() is called. With the above two lines before any other changes to be made by the function, the following effect is achieved:

" cursor is now at linenr, colnr
:call func()
" cursor is now restored at linenr, colnr

Without the "fake" change, undo will go to a position closest to where the first change is made by the function/script, not where the cursor was when the function is called.


Advertisement | Your ad here

Around Wikia's network

Random Wiki