2

I'm writing some vimscript and would like to preserve the cursor position after a yank occurs in visual mode.

Ths issue is that I can't find any way to get the cursor position while in visual mode. It's always at the beginning or the end of the selection but it's not clear which one.

There are the > and < marks to get the beginning/end of the selection. There is also v which appears to work nearly identical to <. And of course there is . for cursor position but when in visual mode this returns the beginning of the selection instead.

3
  • Where you've said register, did you mean mark?
    – tommcdo
    Mar 26, 2015 at 0:08
  • Yep, that's what I meant. I updated the question. Mar 26, 2015 at 1:05
  • 1
    Your function will work outside of visual mode anyway so you can probably use getpos(). Could you show us what you already have?
    – romainl
    Mar 26, 2015 at 8:13

1 Answer 1

3

Not 100% sure if this is what you're trying to do, but following command will restore the cursor to the position it was in during the last visual mode:

execute "normal! gv\<Esc>"

This may or may not be what you want, depending on what actions you're applying to the text selected in visual mode. (It works well if you're just yanking the text.)

If you need to know the cursor position before doing anything with the selection, you could try using :execute "normal! \<esc>", grabbing the cursor position, and then using :normal! gv to reset the visual selection.

1
  • That's exactly what I was looking for, thanks. Mar 26, 2015 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.