I'm trying to implement a custom operator following :h :map-operator. The operator works just fine but has the side effect of moving the cursor position!
For example the code defining the <F4>
operator which counts spaced used in :h :map-operator
(also copied below).
If the cursor is in the middle of a paragraph, typing <F4>ip
correctly prints out the number of spaces in the paragraph, but moves the cursor to the top of the paragraph too! This is also the case for charter wise i.e. <F4>iw
or visuals selection and pressing <F4>
.
This behaviour seems also to be the case in existing operators such as for yank y
. Within a paragraph, typing yip
changes the cursor position to the top of the paragraph as well.
My question: Can this behaviour be changed globally for all operators? I feel this is a rather annoying behaviour and can't quite believe that this would have to be worked around for each operator as in the yank thread above.
Failing that, how could the code for the <F4>
operator below adapter to keep the cursor position? I've already played with let save_pos = getpos(".")
and call setpos('.', save_pos)
without success.
nmap <silent> <F4> :set opfunc=CountSpaces<CR>g@
vmap <silent> <F4> :<C-U>call CountSpaces(visualmode(), 1)<CR>
function! CountSpaces(type, ...)
let sel_save = &selection
let &selection = "inclusive"
let reg_save = @@
if a:0 " Invoked from Visual mode, use gv command.
silent exe "normal! gvy"
elseif a:type == 'line'
silent exe "normal! '[V']y"
else
silent exe "normal! `[v`]y"
endif
echomsg strlen(substitute(@@, '[^ ]', '', 'g'))
let &selection = sel_save
let @@ = reg_save
endfunction