vimscript:如何保存和恢复寄存器?

Tom*_*ale 2 vim

如何保存寄存器的当前状态,然后在以后恢复它?

我想确保我的函数没有意外的副作用。

Tom*_*ale 7

要安全地执行此操作,您不仅需要恢复寄存器的内容,还需要恢复其类型:

let old_reg = getreg("a")               " Save the current content of register 'a'
let old_reg_type = getregtype("a")      " Save the type of the register as well

" <Use the register 'a' as a temporary scratch pad here>

call setreg("a", old_reg, old_reg_type) " Restore register 'a'
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记从函数中的 `:finally` 区域调用 `setr​​eg`,以防你调用可能失败的操作——这种情况经常发生。 (3认同)