💾 Archived View for gmi.noulin.net › vim › usr › usr_41.gmi captured on 2022-06-12 at 07:49:00. Gemini links have been rewritten to link to archived content
View Raw
More Information
➡️ Next capture (2022-07-17)
-=-=-=-=-=-=-
- usr_41.txt* For Vim version 8.2. Last change: 2022 May 21
VIM USER MANUAL - by Bram Moolenaar
Write a Vim script
The Vim script language is used for the startup vimrc file, syntax files, and
many other things. This chapter explains the items that can be used in a Vim
script. There are a lot of them, thus this is a long chapter.
|41.1| Introduction
|41.2| Variables
|41.3| Expressions
|41.4| Conditionals
|41.5| Executing an expression
|41.6| Using functions
|41.7| Defining a function
|41.8| Lists and Dictionaries
|41.9| Exceptions
|41.10| Various remarks
Next chapter: |usr_42.txt| Add new menus
Previous chapter: |usr_40.txt| Make new commands
Table of contents: |usr_toc.txt|
==============================================================================
- 41.1* Introduction *vim-script-intro* *script*
Your first experience with Vim scripts is the vimrc file. Vim reads it when
it starts up and executes the commands. You can set options to values you
prefer. And you can use any colon command in it (commands that start with a
":"; these are sometimes referred to as Ex commands or command-line commands).
Syntax files are also Vim scripts. As are files that set options for a
specific file type. A complicated macro can be defined by a separate Vim
script file. You can think of other uses yourself.
Vim script comes in two flavors: legacy and |Vim9|. Since this help file is
for new users, we'll teach you the newer and more convenient |Vim9| syntax.
While legacy script is particular for Vim, |Vim9| script looks more like other
languages, such as JavaScript and TypeScript.
To try out Vim script the best way is to edit a script file and source it.
Basically: >
:edit test.vim
[insert the script lines you want]
:w
:source %
Let's start with a simple example: >
vim9script
var i = 1
while i < 5
echo "count is" i
i += 1
endwhile
<
The output of the example code is:
count is 1 ~
count is 2 ~
count is 3 ~
count is 4 ~
In the first line the `vim9script` command makes clear this is a new, |Vim9|
script file. That matters for how the rest of the file is used.
The `var i = 1` command declares the "i" variable and initializes it. The
generic form is: >
var {name} = {expression}
In this case the variable name is "i" and the expression is a simple value,
the number one.
The `while` command starts a loop. The generic form is: >
while {condition}
{statements}
endwhile
The statements until the matching `endwhile` are executed for as long as the
condition is true. The condition used here is the expression "i < 5". This
is true when the variable i is smaller than five.
Note:
If you happen to write a while loop that keeps on running, you can
interrupt it by pressing CTRL-C (CTRL-Break on MS-Windows).
The `echo` command prints its arguments. In this case the string "count is"
and the value of the variable i. Since i is one, this will print:
count is 1 ~
Then there is the `i += 1` command. This does the same thing as "i = i + 1",
it adds one to the variable i and assigns the new value to the same variable.
The example was given to explain the commands, but would you really want to
make such a loop, it can be written much more compact: >
for i in range(1, 4)
echo "count is" i
endfor
We won't explain how `for` and `range()` work until later. Follow the links
if you are impatient.
FOUR KINDS OF NUMBERS
Numbers can be decimal, hexadecimal, octal or binary.
A hexadecimal number starts with "0x" or "0X". For example "0x1f" is decimal
31.
An octal number starts with "0o", "0O". "0o17" is decimal 15.
A binary number starts with "0b" or "0B". For example "0b101" is decimal 5.
A decimal number is just digits. Careful: In legacy script don't put a zero
before a decimal number, it will be interpreted as an octal number!
The `echo` command evaluates its argument and always prints decimal numbers.
Example: >
echo 0x7f 0o36
< 127 30 ~
A number is made negative with a minus sign. This also works for hexadecimal,
octal and binary numbers: >
echo -0x7f
< -127 ~
A minus sign is also used for subtraction. This can sometimes lead to
confusion. If we put a minus sign before both numbers we get an error: >
echo -0x7f -0o36
< E1004: White space required before and after '-' at "-0o36" ~
Note: if you are not using a |Vim9| script to try out these commands but type
them directly, they will be executed as legacy script. Then the echo command
sees the second minus sign as subtraction. To get the error, prefix the
command with `vim9cmd`: >
vim9cmd echo -0x7f -0o36
< E1004: White space required before and after '-' at "-0o36" ~
White space in an expression is often required to make sure it is easy to read
and avoid errors. Such as thinking that the "-0o36" above makes the number
negative, while it is actually seen as a subtraction.
To actually have the minus sign be used for negation, you can put the second
expression in parentheses: >
echo -0x7f (-0o36)
==============================================================================
A variable name consists of ASCII letters, digits and the underscore. It
cannot start with a digit. Valid variable names are:
counter
_aap3
very_long_variable_name_with_underscores
FuncLength
LENGTH
Invalid names are "foo+bar" and "6var".
Some variables are global. To see a list of currently defined global
variables type this command: >
:let
You can use global variables everywhere. However, it is easy to use the same
name in two unrelated scripts. Therefore variables declared in a script are
local to that script. For example, if you have this in "script1.vim": >
vim9script
var counter = 5
echo counter
< 5 ~
And you try to use the variable in "script2.vim": >
vim9script
echo counter
< E121: Undefined variable: counter ~
Using a script-local variable means you can be sure that it is only changed in
that script and not elsewhere.
If you do want to share variables between scripts, use the "g:" prefix and
assign the value directly, do not use `var`. Thus in "script1.vim": >
vim9script
g:counter = 5
echo g:counter
< 5 ~
And then in "script2.vim": >
vim9script
echo g:counter
< 5 ~
More about script-local variables here: |script-variable|.
There are more kinds of variables, see |internal-variables|. The most often
used ones are:
b:name variable local to a buffer
w:name variable local to a window
g:name global variable (also in a function)
v:name variable predefined by Vim
DELETING VARIABLES
Variables take up memory and show up in the output of the `let` command. To
delete a global variable use the `unlet` command. Example: >
unlet g:counter
This deletes the global variable "g:counter" to free up the memory it uses.
If you are not sure if the variable exists, and don't want an error message
when it doesn't, append !: >
unlet! g:counter
You cannot `unlet` script-local variables in |Vim9| script. You can in legacy
script.
When a script finishes, the local variables declared there will not be
deleted. Functions defined in the script can use them. Example:
>
vim9script
var counter = 0
def g:GetCount(): number
s:counter += 1
return s:counter
enddef
Every time you call the function it will return the next count: >
:echo g:GetCount()
< 1 ~
>
:echo g:GetCount()
< 2 ~
If you are worried a script-local variable is consuming too much
memory, set it to an empty value after you no longer need it.
Note: below we'll leave out the `vim9script` line, so we can concentrate on
the relevant commands, but you'll still need to put it at the top of your
script file.
STRING VARIABLES AND CONSTANTS
So far only numbers were used for the variable value. Strings can be used as
well. Numbers and strings are the basic types of variables that Vim supports.
Example: >
var name = "Peter"
echo name
< Peter ~
Every variable has a type. Very often, as in this example, the type is
defined by assigning a value. This is called type inference. If you do not
want to give the variable a value yet, you need to specify the type: >
var name: string
var age: number
...
name = "Peter"
age = 42
If you make a mistake and try to assign the wrong type of value you'll get an
error: >
age = "Peter"
< E1012: Type mismatch; expected number but got string ~
More about types in |41.8|.
To assign a string value to a variable, you need to use a string constant.
There are two types of these. First the string in double quotes, as we used
already. If you want to include a double quote inside the string, put a
backslash in front of it: >
var name = "he is \"Peter\""
echo name
< he is "Peter" ~
To avoid the need for a backslash, you can use a string in single quotes: >
var name = 'he is "Peter"'
echo name
< he is "Peter" ~
Inside a single-quote string all the characters are as they are. Only the
single quote itself is special: you need to use two to get one. A backslash
is taken literally, thus you can't use it to change the meaning of the
character after it: >
var name = 'P\e''ter'''
echo name
< P\e'ter' ~
In double-quote strings it is possible to use special characters. Here are a
few useful ones:
\t <Tab>
\n <NL>, line break
\r <CR>, <Enter>
\e <Esc>
\b <BS>, backspace
\" "
\\ \, backslash
\<Esc> <Esc>
\<C-W> CTRL-W
The last two are just examples. The "\<name>" form can be used to include
the special key "name".
See |expr-quote| for the full list of special items in a string.
==============================================================================
Vim has a fairly standard way to handle expressions. You can read the
definition here: |expression-syntax|. Here we will show the most common
items.
The numbers, strings and variables mentioned above are expressions by
themselves. Thus everywhere an expression is expected, you can use a number,
string or variable. Other basic items in an expression are:
$NAME environment variable
&name option
@r register
Examples: >
echo "The value of 'tabstop' is" &ts
echo "Your home directory is" $HOME
if @a == 'text'
The &name form can also be used to set an option value, do something and
restore the old value. Example: >
var save_ic = &ic
set noic
s/The Start/The Beginning/
&ic = save_ic
This makes sure the "The Start" pattern is used with the 'ignorecase' option
off. Still, it keeps the value that the user had set. (Another way to do
this would be to add "\C" to the pattern, see |/\C|.)
MATHEMATICS
It becomes more interesting if we combine these basic items. Let's start with
mathematics on numbers:
a + b add
a - b subtract
a * b multiply
a / b divide
a % b modulo
The usual precedence is used. Example: >
echo 10 + 5 * 2
< 20 ~
Grouping is done with parentheses. No surprises here. Example: >
echo (10 + 5) * 2
< 30 ~
Strings can be concatenated with ".." (see |expr6|). Example: >
echo "foo" .. "bar"
< foobar ~
When the "echo" command gets multiple arguments, it separates them with a
space. In the example the argument is a single expression, thus no space is
inserted.
Borrowed from the C language is the conditional expression: >
a ? b : c
If "a" evaluates to true "b" is used, otherwise "c" is used. Example: >
var nr = 4
echo nr > 5 ? "nr is big" : "nr is small"
< nr is small ~
The three parts of the constructs are always evaluated first, thus you could
see it works as: >
(a) ? (b) : (c)
==============================================================================
The `if` commands executes the following statements, until the matching
`endif`, only when a condition is met. The generic form is:
if {condition}
{statements}
endif
Only when the expression {condition} evaluates to true or one will the
{statements} be executed. If they are not executed they must still be valid
commands. If they contain garbage, Vim won't be able to find the matching
`endif`.
You can also use `else`. The generic form for this is:
if {condition}
{statements}
else
{statements}
endif
The second {statements} block is only executed if the first one isn't.
Finally, there is `elseif`
if {condition}
{statements}
elseif {condition}
{statements}
endif
This works just like using `else` and then `if`, but without the need for an
extra `endif`.
A useful example for your vimrc file is checking the 'term' option and doing
something depending upon its value: >
if &term == "xterm"
# Do stuff for xterm
elseif &term == "vt100"
# Do stuff for a vt100 terminal
else
# Do something for other terminals
endif
This uses "#" to start a comment, more about that later.
LOGIC OPERATIONS
We already used some of them in the examples. These are the most often used
ones:
a == b equal to
a != b not equal to
a > b greater than
a >= b greater than or equal to
a < b less than
a <= b less than or equal to
The result is true if the condition is met and false otherwise. An example: >
if v:version >= 700
echo "congratulations"
else
echo "you are using an old version, upgrade!"
endif
Here "v:version" is a variable defined by Vim, which has the value of the Vim
version. 600 is for version 6.0, version 6.1 has the value 601. This is
very useful to write a script that works with multiple versions of Vim.
|v:version|
The logic operators work both for numbers and strings. When comparing two
strings, the mathematical difference is used. This compares byte values,
which may not be right for some languages.
If you try to compare a string with a number you will get an error.
For strings there are two more useful items:
str =~ pat matches with
str !~ pat does not match with
The left item "str" is used as a string. The right item "pat" is used as a
pattern, like what's used for searching. Example: >
if str =~ " "
echo "str contains a space"
endif
if str !~ '\.