2

I'm attemping to call a function when pressing y + motion like this in my vimrc:

function! s:MyFunction(reg)
  echo a:reg
endfunction

nnoremap y :<C-U> call <SID>MyFunction(v:register)<CR>y

When I type "ayw, MyFunction echoes 'a' like expected, but the yanked word is never written to register "a, instead it is written to the yank register "0.

Why and how to fix this so my mapping honors the specified named register?

  • 2
    Well, your function needs to do something with the given register. From your example, it is not clear, why you think anything should appear in register a – Christian Brabandt Aug 1 '16 at 12:06
  • My thinking is that Vim replaces the 'y' in "ayw with my mapping. So as I specfied "a in front, VIm should complete the command as so. I do realize it doesn't seem to work this way... – Jörgen Aug 1 '16 at 12:12
  • I think, what is happening is, that by the time the command y is executed, the value of v:register is actually lost. That's why you see the value echo'ed, but after that command is finished, Vim resets v:register, so the y does not see the specified register anymore – Christian Brabandt Aug 1 '16 at 12:53
  • Makes sence. If I make a second call to MyFunction like: nnoremap y :<C-U> call <SID>MyFunction(v:register)<CR>:<C-U> call <SID>MyFunction(v:register)<CR>y. I only get an echo of the default register.. – Jörgen Aug 1 '16 at 13:03
3

It seem that the v:register is lost after calling MyFunction. After a bit of reading I found map-expression that can be used to solve the issue like this.

function! s:MyFunction(reg)
  echo a:reg
  return '"'.a:reg.'y'
endfunction

nnoremap <expr> y <SID>MyFunction(v:register)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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