Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing custom motion in a vim map?

Tags:

vim

I have the following mapping that allows to paste over a word from the yank buffer. (cpw = change paste word): nmap <silent> cpw "_cw<C-R>"<Esc>

What I would like to do is allow commands such as the following:

  • cpiw (change paste in word -> like the 'iw' motion)

  • cpaw (change paste a word -> like the 'aw' motion)

for any motion {m} cp{m}

Is this possible to allow in a mapping, so I don't have to write the nmap for each motion that I want to work with it?

Thanks in advance.

EDIT: typo fixes. My solution below

After diligently looking into the map-operator I was successful in making a function that did exactly as I wanted. For any who are interested it is as follows:

"This allows for change paste motion cp{motion}
nmap <silent> cp :set opfunc=ChangePaste<CR>g@
function! ChangePaste(type, ...)
    silent exe "normal! `[v`]\"_c"
    silent exe "normal! p"
endfunction

EDIT - new version that might be better.

"This allows for change paste motion cp{motion}
nmap <silent> cp :set opfunc=ChangePaste<CR>g@
function! ChangePaste(type, ...)
if a:0  " Invoked from Visual mode, use '< and '> marks.
    silent exe "normal! `<" . a:type . "`>\"_c" . @"
elseif a:type == 'line'
    silent exe "normal! '[V']\"_c" . @"
elseif a:type == 'block'
    silent exe "normal! `[\<C-V>`]\"_c" . @"
else
    silent exe "normal! `[v`]\"_c" . @"
endif
endfunction
like image 585
ostler.c Avatar asked Mar 18 '11 20:03

ostler.c


1 Answers

There is a way to define a custom operator, see :help :map-operator for details.

like image 88
Raimondi Avatar answered Nov 16 '22 01:11

Raimondi