Wikia

Vim Tips Wiki

Set options or named registers with let

Talk0
1,612pages on
this wiki
Revision as of 05:24, July 4, 2009 by JohnBot (Talk | contribs)

Tip 1520 Printable Monobook Previous Next

created October 8, 2007 · complexity basic · author Fritzophrenic · version 7.0


Setting registers

It isn't immediately obvious, but let can be used for far more than setting variables. It can also be used, for example, to set a register.

For example, to set register "r" to hold a really long variable name:

let @r = "reallyReallySuperLongVariableNameWithSpamAndEggs"

Use "@@" to set the unnamed register, for example:

let @@ = "example contents of the unnamed register"

Using this technique, you can duplicate the setreg function for use in older versions of Vim, as follows:

if v:version < 602
  " Vim 6.2 introduced the setreg function. Make our own otherwise
  function Setreg(regname, regval)
    exe "let @".a:regname." = '".a:regval."'"
  endfunction
  " set up registers with 'call Setreg', for example
  call Setreg('a', 'yawP`[j')
else
  " set up registers with 'call setreg', for example
  call setreg('a', 'yawP`[j')
endif

Sourcing the above script sets register a. In normal mode, put the cursor in a word and press @a to execute the commands: yaw (yank a word), P (paste), `[ (jump to start of last yank), j (down).

That duplicates the initial word, and is an example of how a macro can be placed in a register.

Setting options

let can also be used to set options, which can be useful in a script.

For example, to save the current value of the 'readonly' option, and restore it later:

let oldro=&readonly
...
...
let &readonly=oldro

References

Comments

Around Wikia's network

Random Wiki