Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim: mapping normal/visual mode movements

Tags:

vim

I have functions that move my cursor around in normal mode, for example:

function! s:Skip(distance, direction)
    execute "normal! ".string(a:distance).a:direction
endfunction

where a:distance is an integer and a:direction is something like 'h' or 'l'. This works fine as a normal mode mapping, however, I would like to extend these motions into visual mode.

The problem is that an execute "normal! etc..." command run while in visual mode doesn't work (i.e. does not perform the cursor movement as if in normal mode selecting the text between the original and final cursor positions). One work around could be to: exit visual mode, drop a mark, execute skip() then visually select from the new cursor position to the mark. I don't care for this solution not only because it requires a mark, but it also doesn't "feel" like the correct way to convert normal mode movements into visual mode movements.

Any suggestions? I should point out that I have many functions like skip() which perform an execute "normal! movement..." so it would be nice to have a general rule, rather than a one time, piece-meal solution (like the marks, if that is the case). Changing the way I perform the normal mode movements from execute "normal! etc..." to something else is perfectly fine.

Thanks!

like image 663
jayflo Avatar asked Jul 10 '26 22:07

jayflo


1 Answers

Pass the current mode into the function (e.g. via an isVisual flag); your mappings know the mode, or you can query mode() for that. Then, for visual mode, one usually re-selects the current selection with gv (as the selection got lost when you triggered your function from the mapping).

function! s:Skip(distance, direction, isVisual)
    execute "normal! ".(a:isVisual ? 'gv': '').a:distance.a:direction
endfunction

This will leave the (extended) selection after your visual mode mapping. Note that gv also restores the cursor to one selection boundary (usually the end); you may need to account for that / switch to the other side (with o).

like image 82
Ingo Karkat Avatar answered Jul 14 '26 15:07

Ingo Karkat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!