Wikia

Vim Tips Wiki

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

Edit

Back to page

(Assign tip id + convert to TipNew template + minor clean)
(Change <tt> to <code>, perhaps also minor tweak.)
 
Line 3: Line 3:
 
|previous=1594
 
|previous=1594
 
|next=1596
 
|next=1596
|created=July 25, 2008
+
|created=2008
 
|complexity=basic
 
|complexity=basic
 
|author=Lpb612
 
|author=Lpb612
Line 20: Line 20:
 
The cursor will be on line 6, not line 3.
 
The cursor will be on line 6, not line 3.
   
Say you have a function <tt>func()</tt> that changes the text. Cursor is somewhere before the calling. You can insert
+
Say you have a function <code>func()</code> that changes the text. Cursor is somewhere before the calling. You can insert
 
<pre>
 
<pre>
 
normal ix
 
normal ix
Line 26: Line 26:
 
</pre>
 
</pre>
   
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 <tt>func()</tt> is called. With the above two lines before any other changes to be made by the function, the following effect is achieved:
+
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 <code>func()</code> is called. With the above two lines before any other changes to be made by the function, the following effect is achieved:
 
<pre>
 
<pre>
 
" cursor is now at linenr, colnr
 
" cursor is now at linenr, colnr

Latest revision as of 06:37, July 13, 2012

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:

:3
:6,7d
u

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()
u
" 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.

CommentsEdit

Around Wikia's network

Random Wiki