Wikia

Vim Tips Wiki

Changes: Set options or named registers with let

Edit

Back to page

(minor formatting)
(Change <tt> to <code>, perhaps also minor tweak.)
 
Line 3: Line 3:
 
|previous=1519
 
|previous=1519
 
|next=1521
 
|next=1521
|created=October 8, 2007
+
|created=2007
 
|complexity=basic
 
|complexity=basic
 
|author=Fritzophrenic
 
|author=Fritzophrenic
Line 36: Line 36:
 
</pre>
 
</pre>
   
Sourcing the above script sets register <tt>a</tt>. In normal mode, put the cursor in a word and press <tt>@a</tt> to execute the commands: <tt>yaw</tt> (yank a word), <tt>P</tt> (paste), <tt>`[</tt> (jump to start of last yank), <tt>j</tt> (down).
+
Sourcing the above script sets register <code>a</code>. In normal mode, put the cursor in a word and press <code>@a</code> to execute the commands: <code>yaw</code> (yank a word), <code>P</code> (paste), <code>`[</code> (jump to start of last yank), <code>j</code> (down).
   
 
That duplicates the initial word, and is an example of how a macro can be placed in a register.
 
That duplicates the initial word, and is an example of how a macro can be placed in a register.

Latest revision as of 06:29, July 13, 2012

Tip 1520 Printable Monobook Previous Next

created 2007 · complexity basic · author Fritzophrenic · version 7.0


Setting registersEdit

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 optionsEdit

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

ReferencesEdit

CommentsEdit

Around Wikia's network

Random Wiki