Setting variables

You've already discovered some basics of Vimscript syntax. To set internal Vim options, you use the set keyword:

set background=dark

To assign a value to a non-internal variable, use the let keyword:

let animal_name = 'Miss Cattington'

Vimscript doesn't have explicit booleans, so 1 is treated as true and 0 as false:

let is_cat = 1

Since we're assigning variables, let's talk about scopes. Vim handles variable and function scopes with prefixes, like so:

let g:animal_name = 'Miss Cattington'
let w:is_cat=1

Each letter has a unique meaning, in particular the following:

  • g: global scope (default if scope is not specified)
  • v: global defined by Vim
  • l: local scope (default within a function if scope is not specified)
  • b: current buffer
  • w: current window
  • t: current tab
  • s: local to a :source'd Vim script
  • a: function argument

In this example, g:animal_name is a global variable (it could also be written as let animal_name='Miss Cattington', but explicit scope declarations are always better), and w:is_cat is a window scope variable.

As you might remember, you can also set registers with let. For example, if you wanted to set register a to hold cats are weird, you could do this:

let @a = 'cats are weird'

You can also access Vim options (the ones you can change with set) by prefixing the variable with &, for example:

let &ignorecase = 0

You can use the usual mathematical operations on integers (+, -, *, /). String concatenation is performed using the . operator:

let g:cat_statement = g:animal_name . ' is a cat'

If you wanted to use a single quote within a single-quoted string, you can do so by typing it twice ('').

Oh, and like in many languages, single quotes identify literal strings, while double quotes identify non-literal strings. This becomes slightly confusing because comments also start with a double quote. Due to this behavior, certain commands in Vimscript can't be followed by a comment.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.221.163