Avoid jumping cursor after undo

48 views
Skip to first unread message

Lifepillar

unread,
Mar 14, 2022, 2:11:02 PM3/14/22
to vim...@googlegroups.com
I have defined this function:

fun! Lint()
let l:view = winsaveview()
keepjumps normal gggqG
call winrestview(l:view)
endf

When the function is executed, the cursor does not move, as expected.
Unfortunately, pressing u after that makes the cursor jump to the top of
the buffer. I had hoped that keepjumps would prevent that, but that does
not seem the case. How can I avoid moving the cursor upon undoing
(without touching registers)?

Thanks,
Life.

Salman Halim

unread,
Mar 14, 2022, 2:50:31 PM3/14/22
to Vim Users
I don't know of a built-in way, but maybe you could write a function as above that saves and restores the view, though it would be tricky if the undo adds or removes lines above the cursor location. Then, map u to it.

It's easy to figure out whether the undo added or removed lines (and how many). Then, you could look at where the cursor has ended up. If it's before your original location, then you need to adjust the values you pass to winrestview to move the return location up or down by the number of rows added. 

It'll probably still be less than perfect if the change is right around the cursor location, but those don't move the cursor much. 

Salman

Lifepillar

unread,
Mar 16, 2022, 2:58:53 PM3/16/22
to vim...@googlegroups.com
I have found a rational for this behaviour (Vim restores the position to
where the undone change has happened), and a way to keep the cursor
where it is:

https://vim.fandom.com/wiki/Restore_the_cursor_position_after_undoing_text_change_made_by_a_script

Perhaps, there is a less hackish way that does not modify the buffer.

Life.


Reply all
Reply to author
Forward
0 new messages