13

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
8
  • How do you solve the special cases when cw behaves like ce? Mar 5, 2013 at 3:50
  • I do not solve this. The motion is still handled by vim. The motion of cpw / cpe is the same as cw / ce. You can correct me if I am wrong.
    – ostler.c
    Mar 5, 2013 at 23:10
  • It seems that cpw works differently from cw as it consumes the space behind the word: first second -> newsecond and first = second -> new= second. Additionally, if the word is at the beginning of a line, cpw with new in the clipboard does this: first second -> snewecond. Mar 7, 2013 at 3:57
  • @Michael: See my edit. Try the new version and see if it fixes what you are seeing.
    – ostler.c
    Mar 8, 2013 at 0:49
  • Thanks for the new version. It solves the issue with replacing a word at the beginning of a line. However it does not make cpw behave like cw. Mar 14, 2013 at 0:57

1 Answer 1

12

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

0

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.