💾 Archived View for gmi.noulin.net › vim › usr › usr_41.gmi captured on 2024-08-19 at 03:52:05. Gemini links have been rewritten to link to archived content
View Raw
More Information
⬅️ Previous capture (2023-07-10)
🚧 View Differences
-=-=-=-=-=-=-
- usr_41.txt* For Vim version 9.1. Last change: 2024 Jun 09
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, therefore 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| White space
|41.10| Line continuation
|41.11| Comments
|41.12| Fileformat
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*
Let's start with some nomenclature. A Vim script is any file that Vim can
interpret and execute. This includes files written in Vim's scripting language
like for example .vim files or configuration files like .vimrc and .gvimrc.
These scripts may define functions, commands and settings that Vim uses to
customize and extend its behavior.
With a slight abuse of nomenclature, we will use "Vim script" to refer to the
Vim scripting language throughout this documentation. This shorthand helps to
streamline explanations and discussions about scripting with Vim.
A Vim plugin is a collection of one or more Vim scripts, along with additional
files like help documentation, configuration files, and other resources,
designed to add specific features or functionalities to Vim. A plugin can
provide new commands, enhance existing capabilities, and integrate external
tools or services into the Vim environment.
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 the values you
prefer, define mappings, select plugins and much more. 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 particularly 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. It is
recommended to put it in the very first line, before any comments.
*vim9-declarations*
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`, `range()`and `$"string"` work until later. Follow
the links if you are impatient.
TRYING OUT EXAMPLES
You can easily try out most examples in these help files without saving the
commands to a file. For example, to try out the "for" loop above do this:
1. position the cursor on the "for"
2. start Visual mode with "v"
3. move down to the "endfor"
4. press colon, then "so" and Enter
After pressing colon you will see ":'<,'>", which is the range of the Visually
selected text.
For some commands it matters they are executed as in |Vim9| script. But typed
commands normally use legacy script syntax, such as the example below that
causes the E1004 error. For that use this fourth step:
4. press colon, then "vim9 so" and Enter
"vim9" is short for `vim9cmd`, which is a command modifier to execute the
following command in |Vim9| syntax.
Note that this won't work for examples that require a script context.
FOUR KINDS OF NUMBERS
Numbers can be decimal, hexadecimal, octal and binary.
A hexadecimal number starts with "0x" or "0X". For example "0x1f" is decimal
31 and "0x1234" is decimal 4660.
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! That's
one reason to use |Vim9| script.
The `echo` command evaluates its argument and when it is a number always
prints the decimal form. 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)
< -127 -30 ~
==============================================================================
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
CamelCaseName
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 too 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`. And use a specific name to avoid
mistakes. Thus in "script1.vim": >
vim9script
g:mash_counter = 5
echo g:mash_counter
< 5 ~
And then in "script2.vim": >
vim9script
echo g:mash_counter
< 5 ~
Global variables can also be accessed on the command line, E.g. typing this: >
echo g:mash_counter
That will not work for a script-local variable.
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, only in legacy
script.
When a script has been processed to the end, 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
counter += 1
return 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 or null value after you no longer need it. Example: >
var lines = readfile(...)
...
lines = []
Note: below we'll leave out the `vim9script` line from examples, 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
if male
name = "Peter"
age = 42
else
name = "Elisa"
age = 45
endif
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 can 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 backslashes, 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 value
@r register contents
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 ~
OTHERS
Strings can be concatenated with ".." (see |expr6|). Example: >
echo "Name: " .. name
Name: Peter
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.
If you don't like the concatenation you can use the $"string" form, which
accepts an expression in curly braces: >
echo $"Name: {name}"
See |interpolated-string| for more information.
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)
There is also the falsy operator: >
echo name ?? "No name given"
See |??|.
==============================================================================
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 >= 800
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. 800 is for version 8.0, version 8.1 has the value 801. This is
useful to write a script that works with multiple versions of Vim.
See |v:version|. You can also check for a specific feature with `has()` or a
specific patch, see |has-patch|.
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 !~ '\.