Variables

View Vimscript not a single command but as a programming language.

:let foo = "bar"
:echo foo

foo output: bar

:let foo = 42
:echo foo

foo output: 42

Options as Variables

Using an & in front of a variable tells Vim that you're referring to the option, not a variable that happens to have the same name.

Normal variable

:set textwidth=80
:echo &textwidth

textwidth output: 80

Boolean variable (true:1,false:0)

:set nowrap
:echo &wrap

wrap output: 0

:set wrap
:echo &wrap

wrap output: 1

:let &textwidth = 100
:set textwidth?

textwidth output: 100

:let &textwidth = &textwidth + 10
:set textwidth?

textwidth output: 110

Local Options

If you want to set the local value of an option as a variable, instead of the global value, you need to prefix the variable name.

Open two files in separate splits. Run the following command:

:let &l:number = 1

Now switch to the other file and run this command:

:let &l:number = 0

Registers as Variables

You can also read and set registers as variables.

:let @a = "hello!"

Now put your cursor somewhere in your text and type

"ap

This command tells Vim to "paste the contents of register a here". We just set the contents of that register, so Vim pastes hello! into your text.

Registers can also be read. Run the following command:

:echo @a

Vim will echo hello!.

Select a word in your file and yank it with y, then run this command:

:echo @"

Vim will echo the word you just yanked. The " register is the "unnamed" register, which is where text you yank without specifying a destination will go.

Perform a search in your file with /$your_word

/$your_word
:echo @/

Vim will echo the search pattern you just used. This lets you programmatically read and modify the current search pattern, which can be very useful at times.

Exercises (not finish)

Go through your ~/.vimrc file and change some of the set and setlocal commands to their let forms. Remember that boolean options still need to be set to something.

Try setting a boolean option like wrap to something other than zero or one. What happens when you set it to a different number? What happens if you set it to a string?

Go back through your ~/.vimrc file and undo the changes. You should never use let if set will suffice -- it's harder to read.

Read :help registers and look over the list of registers you can read and write.

Variable Scoping

When we used b: in the variable name we told Vim that the variable hello should be local to the current buffer b.

Vim has many different scopes for variables, but we need to learn a little more about Vimscript before we can take advantage of the rest. For now, just remember that when you see a variable that start with a character and a colon that it's describing a scoped variable.

Last updated

Was this helpful?