1" ##############
2" Introduction
3" ##############
4"
5" Vim script (also called VimL) is the subset of Vim's ex-commands which
6" supplies a number of features one would expect from a scripting language,
7" such as values, variables, functions or loops. Always keep in the back of
8" your mind that a Vim script file is just a sequence of ex-commands. It is
9" very common for a script to mix programming-language features and raw
10" ex-commands.
11"
12" You can run Vim script directly by entering the commands in command-line mode
13" (press `:` to enter command-line mode), or you can write them to a file
14" (without the leading `:`) and source it in a running Vim instance (`:source
15" path/to/file`). Some files are sourced automatically as part of your
16" configuration (see |startup|). This guide assumes that you are familiar
17" with ex-commands and will only cover the scripting. Help topics to the
18" relevant manual sections are included.
19"
20" See |usr_41.txt| for the official introduction to Vim script. A comment is
21" anything following an unmatched `"` until the end of the line, and `|`
22" separates instructions (what `;` does in most other languages). References to
23" the manual as surrounded with `|`, such as |help.txt|.
24
25" This is a comment
26
27" The vertical line '|' (pipe) separates commands
28echo 'Hello' | echo 'world!'
29
30" Putting a comment after a command usually works
31pwd " Displays the current working directory
32
33" Except for some commands it does not; use the command delimiter before the
34" comment (echo assumes that the quotation mark begins a string)
35echo 'Hello world!' | " Displays a message
36
37" Line breaks can be escaped by placing a backslash as the first non-whitespace
38" character on the *following* line. Only works in script files, not on the
39" command line
40echo " Hello
41 \ world "
42
43echo [1,
44 \ 2]
45
46echo {
47 \ 'a': 1,
48 \ 'b': 2
49\}
50
51
52" #######
53" Types
54" #######
55"
56" For an overview of types see |E712|. For an overview of operators see
57" |expression-syntax|
58
59" Numbers (|expr-number|)
60" #######
61
62echo 123 | " Decimal
63echo 0b1111011 | " Binary
64echo 0173 | " Octal
65echo 0x7B | " Hexadecimal
66echo 123.0 | " Floating-point
67echo 1.23e2 | " Floating-point (scientific notation)
68
69" Note that an *integer* number with a leading `0` is in octal notation. The
70" usual arithmetic operations are supported.
71
72echo 1 + 2 | " Addition
73echo 1 - 2 | " Subtraction
74echo - 1 | " Negation (unary minus)
75echo + 1 | " Unary plus (does nothing really, but still legal)
76echo 1 * 2 | " Multiplication
77echo 1 / 2 | " Division
78echo 1 % 2 | " Modulo (remainder)
79
80" Booleans (|Boolean|)
81" ########
82"
83" The number 0 is false, every other number is true. Strings are implicitly
84" converted to numbers (see below). There are two pre-defined semantic
85" constants.
86
87echo v:true | " Evaluates to 1 or the string 'v:true'
88echo v:false | " Evaluates to 0 or the string 'v:false'
89
90" Boolean values can result from comparison of two objects.
91
92echo x == y | " Equality by value
93echo x != y | " Inequality
94echo x > y | " Greater than
95echo x >= y | " Greater than or equal
96echo x < y | " Smaller than
97echo x <= y | " Smaller than or equal
98echo x is y | " Instance identity (lists and dictionaries)
99echo x isnot y | " Instance non-identity (lists and dictionaries)
100
101" Strings are compared based on their alphanumerical ordering
102" echo 'a' < 'b'. Case sensitivity depends on the setting of 'ignorecase'
103"
104" Explicit case-sensitivity is specified by appending '#' (match case) or '?'
105" (ignore case) to the operator. Prefer explicitly case sensitivity when writing
106" portable scripts.
107
108echo 'a' < 'B' | " True or false depending on 'ignorecase'
109echo 'a' <? 'B' | " True
110echo 'a' <# 'B' | " False
111
112" Regular expression matching
113echo "hi" =~ "hello" | " Regular expression match, uses 'ignorecase'
114echo "hi" =~# "hello" | " Regular expression match, case sensitive
115echo "hi" =~? "hello" | " Regular expression match, case insensitive
116echo "hi" !~ "hello" | " Regular expression unmatch, use 'ignorecase'
117echo "hi" !~# "hello" | " Regular expression unmatch, case sensitive
118echo "hi" !~? "hello" | " Regular expression unmatch, case insensitive
119
120" Boolean operations are possible.
121
122echo v:true && v:false | " Logical AND
123echo v:true || v:false | " Logical OR
124echo ! v:true | " Logical NOT
125echo v:true ? 'yes' : 'no' | " Ternary operator
126
127
128" Strings (|String|)
129" #######
130"
131" An ordered zero-indexed sequence of bytes. The encoding of text into bytes
132" depends on the option |'encoding'|.
133
134" Literal constructors
135echo "Hello world\n" | " The last two characters stand for newline
136echo 'Hello world\n' | " The last two characters are literal
137echo 'Let''s go!' | " Two single quotes become one quote character
138
139" Single-quote strings take all characters are literal, except two single
140" quotes, which are taken to be a single quote in the string itself. See
141" |expr-quote| for all possible escape sequences.
142
143" String concatenation
144" The .. operator is preferred, but only supported in since Vim 8.1.1114
145echo 'Hello ' . 'world' | " String concatenation
146echo 'Hello ' .. 'world' | " String concatenation (new variant)
147
148" String indexing
149echo 'Hello'[0] | " First byte
150echo 'Hello'[1] | " Second byte
151echo 'Hellö'[4] | " Returns a byte, not the character 'ö'
152
153" Substrings (second index is inclusive)
154echo 'Hello'[:] | " Copy of entire string
155echo 'Hello'[1:3] | " Substring, second to fourth byte
156echo 'Hello'[1:-2] | " Substring until second to last byte
157echo 'Hello'[1:] | " Substring with starting index
158echo 'Hello'[:2] | " Substring with ending index
159echo 'Hello'[-2:] | " Substring relative to end of string
160
161" A negative index is relative to the end of the string. See
162" |string-functions| for all string-related functions.
163
164" Lists (|List|)
165" #####
166"
167" An ordered zero-indexed heterogeneous sequence of arbitrary Vim script
168" objects.
169
170" Literal constructor
171echo [] | " Empty list
172echo [1, 2, 'Hello'] | " List with elements
173echo [1, 2, 'Hello', ] | " Trailing comma permitted
174echo [[1, 2], 'Hello'] | " Lists can be nested arbitrarily
175
176" List concatenation
177echo [1, 2] + [3, 4] | " Creates a new list
178
179" List indexing, negative is relative to end of list (|list-index|)
180echo [1, 2, 3, 4][2] | " Third element
181echo [1, 2, 3, 4][-1] | " Last element
182
183" List slicing (|sublist|)
184echo [1, 2, 3, 4][:] | " Shallow copy of entire list
185echo [1, 2, 3, 4][:2] | " Sublist until third item (inclusive)
186echo [1, 2, 3, 4][2:] | " Sublist from third item (inclusive)
187echo [1, 2, 3, 4][:-2] | " Sublist until second-to-last item (inclusive)
188
189" All slicing operations create new lists. To modify a list in-place use list
190" functions (|list-functions|) or assign directly to an item (see below about
191" variables).
192
193
194" Dictionaries (|Dictionary|)
195" ############
196"
197" An unordered sequence of key-value pairs, keys are always strings (numbers
198" are implicitly converted to strings).
199
200" Dictionary literal
201echo {} | " Empty dictionary
202echo {'a': 1, 'b': 2} | " Dictionary literal
203echo {'a': 1, 'b': 2, } | " Trailing comma permitted
204echo {'x': {'a': 1, 'b': 2}} | " Nested dictionary
205
206" Indexing a dictionary
207echo {'a': 1, 'b': 2}['a'] | " Literal index
208echo {'a': 1, 'b': 2}.a | " Syntactic sugar for simple keys
209
210" See |dict-functions| for dictionary manipulation functions.
211
212
213" Funcref (|Funcref|)
214" #######
215"
216" Reference to a function, uses the function name as a string for construction.
217" When stored in a variable the name of the variable has the same restrictions
218" as a function name (see below).
219
220echo function('type') | " Reference to function type()
221" Note that `funcref('type')` will throw an error because the argument must be
222" a user-defined function; see further below for defining your own functions.
223echo funcref('type') | " Reference by identity, not name
224" A lambda (|lambda|) is an anonymous function; it can only contain one
225" expression in its body, which is also its implicit return value.
226echo {x -> x * x} | " Anonymous function
227echo function('substitute', ['hello']) | " Partial function
228
229
230" Regular expression (|regular-expression|)
231" ##################
232"
233" A regular expression pattern is generally a string, but in some cases you can
234" also use a regular expression between a pair of delimiters (usually `/`, but
235" you can choose anything).
236
237" Substitute 'hello' for 'Hello'
238substitute/hello/Hello/
239
240
241" ###########################
242" Implicit type conversions
243" ###########################
244"
245" Strings are converted to numbers, and numbers to strings when necessary. A
246" number becomes its decimal notation as a string. A string becomes its
247" numerical value if it can be parsed to a number, otherwise it becomes zero.
248
249echo "1" + 1 | " Number
250echo "1" .. 1 | " String
251echo "0xA" + 1 | " Number
252
253" Strings are treated like numbers when used as booleans
254echo "true" ? 1 : 0 | " This string is parsed to 0, which is false
255
256" ###########
257" Variables
258" ###########
259"
260" Variables are bound within a scope; if no scope is provided a default is
261" chosen by Vim. Use `:let` and `:const` to bind a value and `:unlet` to unbind
262" it.
263
264let b:my_var = 1 | " Local to current buffer
265let w:my_var = 1 | " Local to current window
266let t:my_var = 1 | " Local to current tab page
267let g:my_var = 1 | " Global variable
268let l:my_var = 1 | " Local to current function (see functions below)
269let s:my_var = 1 | " Local to current script file
270let a:my_arg = 1 | " Function argument (see functions below)
271
272" The Vim scope is read-only
273echo v:true | " Special built-in Vim variables (|v:var|)
274
275" Access special Vim memory like variables
276let @a = 'Hello' | " Register
277let $PATH='' | " Environment variable
278let &textwidth = 79 | " Option
279let &l:textwidth = 79 | " Local option
280let &g:textwidth = 79 | " Global option
281
282" Access scopes as dictionaries (can be modified like all dictionaries)
283" See the |dict-functions|, especially |get()|, for access and manipulation
284echo b: | " All buffer variables
285echo w: | " All window variables
286echo t: | " All tab page variables
287echo g: | " All global variables
288echo l: | " All local variables
289echo s: | " All script variables
290echo a: | " All function arguments
291echo v: | " All Vim variables
292
293" Constant variables
294const x = 10 | " See |:const|, |:lockvar|
295
296" Function reference variables have the same restrictions as function names
297let IsString = {x -> type(x) == type('')} | " Global: capital letter
298let s:isNumber = {x -> type(x) == type(0)} | " Local: any name allowed
299
300" When omitted the scope `g:` is implied, except in functions, there `l:` is
301" implied.
302
303
304" Multiple value binding (list unpacking)
305" #######################################
306"
307" Assign values of list to multiple variables (number of items must match)
308let [x, y] = [1, 2]
309
310" Assign the remainder to a rest variable (note the semicolon)
311let [mother, father; children] = ['Alice', 'Bob', 'Carol', 'Dennis', 'Emily']
312
313
314" ##############
315" Flow control
316" ##############
317
318" Conditional (|:if|, |:elseif|, |:else|, |:endif|)
319" ###########
320"
321" Conditions are set between `if` and `endif`. They can be nested.
322
323let condition = v:true
324
325if condition
326 echo 'First condition'
327elseif another_condition
328 echo 'Second condition'
329else
330 echo 'Fail'
331endif
332
333" Loops (|:for|, |:endfor|, |:while|, |:endwhile|, |:break|, |:continue|)
334" #####
335"
336" Two types of loops: `:for` and `:while`. Use `:continue` to skip to the next
337" iteration, `:break` to break out of the loop.
338
339" For-loop (|:for|, |:endfor|)
340" ========
341"
342" For-loops iterate over lists and nothing else. If you want to iterate over
343" another sequence you need to use a function which will create a list.
344
345" Iterate over a list
346for person in ['Alice', 'Bob', 'Carol', 'Dennis', 'Emily']
347 echo 'Hello ' .. person
348endfor
349
350" Iterate over a nested list by unpacking it
351for [x, y] in [[1, 0], [0, 1], [-1, 0], [0, -1]]
352 echo 'Position: x =' .. x .. ', y = ' .. y
353endfor
354
355" Iterate over a range of numbers
356for i in range(10, 0, -1) " Count down from 10
357 echo 'T minus' .. i
358endfor
359
360" Iterate over the keys of a dictionary
361for symbol in keys({'π': 3.14, 'e': 2.71})
362 echo 'The constant ' .. symbol .. ' is a transcendent number'
363endfor
364
365" Iterate over the values of a dictionary
366for value in values({'π': 3.14, 'e': 2.71})
367 echo 'The value ' .. value .. ' approximates a transcendent number'
368endfor
369
370" Iterate over the keys and values of a dictionary
371for [symbol, value] in items({'π': 3.14, 'e': 2.71})
372 echo 'The number ' .. symbol .. ' is approximately ' .. value
373endfor
374
375" While-loops (|:while|, |:endwhile|)
376
377let there_yet = v:true
378while !there_yet
379 echo 'Are we there yet?'
380endwhile
381
382
383" Exception handling (|exception-handling|)
384" ##################
385"
386" Throw new exceptions as strings, catch them by pattern-matching a regular
387" expression against the string
388
389" Throw new exception
390throw "Wrong arguments"
391
392" Guard against an exception (the second catch matches any exception)
393try
394 source path/to/file
395catch /Cannot open/
396 echo 'Looks like that file does not exist'
397catch /.*/
398 echo 'Something went wrong, but I do not know what'
399finally
400 echo 'I am done trying'
401endtry
402
403
404" ##########
405" Functions
406" ##########
407
408" Defining functions (|:function|, |:endfunction|)
409" ##################
410
411" Unscoped function names have to start with a capital letter
412function! AddNumbersLoudly(x, y)
413 " Use a: scope to access arguments
414 echo 'Adding' .. a:x .. 'and' .. a:y | " A side effect
415 return a:x + a:y | " A return value
416endfunction
417
418" Scoped function names may start with a lower-case letter
419function! s:addNumbersLoudly(x, y)
420 echo 'Adding' .. a:x .. 'and' .. a:y
421 return a:x + a:y
422endfunction
423
424" Without the exclamation mark it would be an error to re-define a function,
425" with the exclamation mark the new definition can replace the old one. Since
426" Vim script files can be reloaded several times over the course of a session
427" it is best to use the exclamation mark unless you really know what you are
428" doing.
429
430" Function definitions can have special qualifiers following the argument list.
431
432" Range functions define two implicit arguments, which will be set to the range
433" of the ex-command
434function! FirstAndLastLine() range
435 echo [a:firstline, a:lastline]
436endfunction
437
438" Prints the first and last line that match a pattern (|cmdline-ranges|)
439/^#!/,/!#$/call FirstAndLastLine()
440
441" Aborting functions, abort once error occurs (|:func-abort|)
442function! SourceMyFile() abort
443 source my-file.vim | " Try sourcing non-existing file
444 echo 'This will never be printed'
445endfunction
446
447" Closures, functions carrying values from outer scope (|:func-closure|)
448function! MakeAdder(x)
449 function! Adder(n) closure
450 return a:n + a:x
451 endfunction
452 return funcref('Adder')
453endfunction
454let AddFive = MakeAdder(5)
455echo AddFive(3) | " Prints 8
456
457" Dictionary functions, poor man's OOP methods (|Dictionary-function|)
458function! Mylen() dict
459 return len(self.data) | " Implicit variable self
460endfunction
461let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
462echo mydict.len()
463
464" Alternatively, more concise
465let mydict = {'data': [0, 1, 2, 3]}
466function! mydict.len()
467 return len(self.data)
468endfunction
469
470" Calling functions (|:call|)
471" #################
472
473" Call a function for its return value, and possibly for its side effects
474let animals = keys({'cow': 'moo', 'dog': 'woof', 'cat': 'meow'})
475
476" Call a function for its side effects only, ignore potential return value
477call sign_undefine()
478
479" The call() function calls a function reference and passes parameters as a
480" list, and returns the function's result.
481echo call(function('get'), [{'a': 1, 'b': 2}, 'c', 3]) | " Prints 3
482
483" Recall that Vim script is embedded within the ex-commands, that is why we
484" cannot just call a function directly, we have to use the `:call` ex-command.
485
486" Function namespaces (|write-library-script|, |autoload|)
487" ###################
488
489" Must be defined in autoload/foo/bar.vim
490" Namspaced function names do not have to start with a capital letter
491function! foo#bar#log(value)
492 echomsg value
493endfunction
494
495call foo#bar#log('Hello')
496
497
498" #############################
499" Frequently used ex-commands
500" #############################
501
502
503" Sourcing runtime files (|'runtimepath'|)
504" ######################
505
506" Source first match among runtime paths
507runtime plugin/my-plugin.vim
508
509
510" Defining new ex-commands (|40.2|, |:command|)
511" ########################
512
513" First argument here is the name of the command, rest is the command body
514command! SwapAdjacentLines normal! ddp
515
516" The exclamation mark works the same as with `:function`. User-defined
517" commands must start with a capital letter. The `:command` command can take a
518" number of attributes (some of which have their own parameters with `=`), such
519" as `-nargs`, all of them start with a dash to set them apart from the command
520" name.
521
522command! -nargs=1 Error echoerr <args>
523
524
525" Defining auto-commands (|40.3|, |autocmd|, |autocommand-events|)
526" ######################
527
528" The arguments are "events", "patterns", rest is "commands"
529autocmd BufWritePost $MYVIMRC source $MYVIMRC
530
531" Events and patterns are separated by commas with no space between. See
532" |autocmd-events| for standard events, |User| for custom events. Everything
533" else are the ex-commands which will be executed.
534
535" Auto groups
536" ===========
537"
538" When a file is sourced multiple times the auto-commands are defined anew,
539" without deleting the old ones, causing auto-commands to pile up over time.
540" Use auto-groups and the following ritual to guard against this.
541
542augroup auto-source | " The name of the group is arbitrary
543 autocmd! | " Deletes all auto-commands in the current group
544 autocmd BufWritePost $MYVIMRC source $MYVIMRC
545augroup END | " Switch back to default auto-group
546
547" It is also possible to assign a group directly. This is useful if the
548" definition of the group is in one script and the definition of the
549" auto-command is in another script.
550
551" In one file
552augroup auto-source
553 autocmd!
554augroup END
555
556" In another file
557autocmd auto-source BufWritePost $MYVIMRC source $MYVIMRC
558
559" Executing (run-time macros of sorts)
560" ####################################
561
562" Sometimes we need to construct an ex-command where part of the command is not
563" known until runtime.
564
565let line = 3 | " Line number determined at runtime
566execute line .. 'delete' | " Delete a line
567
568" Executing normal-mode commands
569" ##############################
570"
571" Use `:normal` to play back a sequence of normal mode commands from the
572" command-line. Add an exclamation mark to ignore user mappings.
573
574normal! ggddGp | " Transplant first line to end of buffer
575
576" Window commands can be used with :normal, or with :wincmd if :normal would
577" not work
578wincmd L | " Move current window all the way to the right
579
580
581" ###########################
582" Frequently used functions
583" ###########################
584
585" Feature check
586echo has('nvim') | " Running Neovim
587echo has('python3') | " Support for Python 3 plugins
588echo has('unix') | " Running on a Unix system
589echo has('win32') | " Running on a Windows system
590
591
592" Test if something exists
593echo exists('&mouse') | " Option (exists only)
594echo exists('+mouse') | " Option (exists and works)
595echo exists('$HOSTNAME') | " Environment variable
596echo exists('*strftime') | " Built-in function
597echo exists('**s:MyFunc') | " User-defined function
598echo exists('bufcount') | " Variable (scope optional)
599echo exists('my_dict["foo"]') | " Variable (dictionary entry)
600echo exists('my_dict["foo"]') | " Variable (dictionary entry)
601echo exists(':Make') | " Command
602echo exists("#CursorHold") | " Auto-command defined for event
603echo exists("#BufReadPre#*.gz") | " Event and pattern
604echo exists("#filetypeindent") | " Auto-command group
605echo exists("##ColorScheme") | " Auto-command supported for event
606
607" Various dynamic values (see |expand()|)
608echo expand('%') | " Current file name
609echo expand('<cword>') | " Current word under cursor
610echo expand('%:p') | " Modifier are possible
611
612" Type tests
613" There are unique constants defined for the following types. Older versions
614" of Vim lack the type variables, see the reference " documentation for a
615" workaround
616echo type(my_var) == v:t_number | " Number
617echo type(my_var) == v:t_string | " String
618echo type(my_var) == v:t_func | " Funcref
619echo type(my_var) == v:t_list | " List
620echo type(my_var) == v:t_dict | " Dictionary
621echo type(my_var) == v:t_float | " Float
622echo type(my_var) == v:t_bool | " Explicit Boolean
623" For the null object should compare it against itself
624echo my_var is v:null
625
626" Format strings
627echo printf('%d in hexadecimal is %X', 123, 123)
628
629
630" #####################
631" Tricks of the trade
632" #####################
633
634" Source guard
635" ############
636
637" Prevent a file from being sourced multiple times; users can set the variable
638" in their configuration to prevent the plugin from loading at all.
639if exists('g:loaded_my_plugin')
640 finish
641endif
642let g:loaded_my_plugin = v:true
643
644" Default values
645" ##############
646
647" Get a default value: if the user defines a variable use it, otherwise use a
648" hard-coded default. Uses the fact that a scope is also a dictionary.
649let s:greeting = get(g:, 'my_plugin_greeting', 'Hello')