2

I want to create a function like this:

function Foo()
    copy something from buffer into a register
    do something
    restore register
endfunction

Foo must have no side effect, every register should remain the same after you call it, how should i do it?

Attempt

unnamed register

function Foo()
    let [regText, regType] = [getreg('"'), getregtype('"')]
    norm! y{motion}
    do something
    call setreg('"', regText, regType)
endfunction

side effect:

  • register 0 was changed
  • if 'clipboard' includes unnamed or unnamedplus, regster * or + was also changed.
  • if " point to other register before calling Foo, it stopped pointing to it after the calling.

named register

function Foo()
    let [regText, regType] = [getreg('a'), getregtype('a')]
    norm! "ay{motion}
    do something
    call setreg('a', regText, regType)
endfunction

side effect:

  • " now point to a.

explicit unnamed register

function Foo()
    let [regText, regType] = [getreg('"'), getregtype('"')]
    norm! ""y{motion}
    do something
    call setreg('"', regText, regType)
endfunction

side effect:

  • if " point to other register before calling Foo, it stopped pointing to it after the calling.
  • Why do you want to both copy a value in a register and restore the register to the original value in the same function? Would copying the in a variable work instead? – padawin May 17 at 14:29
  • It's convenient to copy something from buffer into a register first. – dedowsdi May 17 at 14:36
  • ok, and the issue here is that "ay{motion} sets in the " (unnamed register) as well as a? – padawin May 17 at 14:38
  • No, it set " point to a, check :h quotequote. – dedowsdi May 17 at 23:19

Your Answer

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

Browse other questions tagged or ask your own question.