vim - how do I yank to register inside a function?

725 Views Asked by At

I am perplexed how to use the registers from inside a function. For example, if I want to yank the current word to register "k", from inside vim, I would use the command/keystrokes

"kyw

But this does not work from inside a function: " starts a comment:

function MyFunction()
  "kyw
  "^^^ does not work because it is a comment...
  let @k="I can set register k directly to text..."
  " but that's not the same
  yank k "I can yank an entire line, but still not the same
endfunction

Is there a way to do this without changing the comment option (would that even work?) Thanks; I have been hitting my head against this for an entire day.

1

There are 1 best solutions below

2
Luc Hermitte On BEST ANSWER

Use either

  • :normal! "kyw (recurring question),
  • or :let @k = expand('<cword>') if you're at the start of the word. Note that in that case, it's better to avoid storing the value of the current word in a register: it's better to use variables and to leave registers alone (or at least unchanged) when we can.