A guide to Vim9script development for Python developers. This guide presents sample code for various expressions, statements, functions, and programming constructs, shown in both Python and Vim9script. It is not intended as a tutorial on Vim script development, and assumes the reader is already familiar with Python programming.
For an introduction to Vim9 Script development, refer to vim9.txt, vim9class.txt, usr_41.txt and eval.txt.
This guide focuses only on programming constructs that are common to both Python and Vim9. Constructs unique to Vim - such as autocommands, key-mapping, abbreviations, user-commands and plugins - are not covered in this guide.
The Vim9 script features are only available starting from Vim 9.0.
The Github repository for this gist is available at: https://github.com/yegappan/Vim9ScriptForPythonDevelopers.
Note: The first command in a Vim9script file should be the :vim9script command. However, for simplicity, this guide omits it from the examples.
- Literals
- Variables
- Operators
- String
- List
- Tuple
- Dictionary
- If Statement
- For Loop
- While Loop
- Comment
- Function
- Lambda Function
- Partial Function
- Closure
- Class
- Exception Handling
- Line Continuation
- File Operations
- Directory Operations
- Random Numbers
- Mathematical Functions
- Date/Time Functions
- External Commands
- User Input/Output
- Environment Variables
- Command Line Arguments
- Regular Expressions
- Binary Data
- Timers
- JSON encoder and decoder
- Network Sockets
- Background Processes
- Unit Tests
Type | Python | Vim9Script |
---|---|---|
integer | -1, 0, 5 |
-1, 0, 5 |
binary | 0b1011 |
0b1011 |
octal | 0o477 |
0477 |
hexadecimal | 0x1AE |
0x1AE |
float | 3.14, -1.5e2 |
3.14, -1.5e2 |
string | "hello", 'world' |
"hello", 'world' |
boolean | True, False |
true, false |
list | [], [5, 9], ['a', 'b'] |
[], [5, 9], ['a', 'b'] |
tuple | (), (1,), (5, 9), ('a', 'b') |
(), (1,), (5, 9), ('a', 'b') |
dict | {}, {'idx' : 2, 'name' : 'abc'} |
{}, {idx: 2, name: 'abc'} |
special | None |
none, null |
Help: expr-number, string, Boolean, list, tuple, dict, v:none, v:null
Python:
i = 10
pi = 3.1415
str = "Hello"
a, b, s = 10, 20, "sky"
Vim9Script:
var i = 10
var pi = 3.1415
var str = "Hello"
var [a, b, s] = [10, 20, "sky"]
You can also create the variables with a specific type declaration:
var i: number = 10
var pi: float = 3.1415
var str: string = "Hello"
var [a: number, b: number, s: string] = [10, 20, "sky"]
In Vim9script, strict type checking is recommended, so specifying the type of each variable is advised. However, for simplicity, this guide omits explicit type declarations and relies on inferred types instead.
Help: variables
Python:
del str
Vim9Script:
Variables are garbage collected in Vim9 and cannot be deleted.
Help: :unlet
Assigning multi-line values to a variable.
Python:
import textwrap
i = textwrap.dedent("""
one
two three
four
five
""".lstrip('\n')).splitlines()
# i == ['one', 'two three', ' four', 'five']
Vim9Script:
vim9script
var i =<< trim END
one
two three
four
five
END
# i == ['one', 'two three', ' four', 'five']
Help: :let-heredoc
Type | Python | Vim9Script |
---|---|---|
Number | num = 10 |
var num: number = 10 |
Float | f = 3.4 |
var f: float = 3.4 |
Booelan | done = True |
var done: bool = true |
String | str = "green" |
var str: string = "green" |
List | l = [1, 2, 3] |
var l: list<number> = [1, 2, 3] |
Tuple | t = (1, 2, 3) |
var t: tuple<number> = (1, 2, 3) |
Dictionary | d = {'a' : 5, 'b' : 6} |
var d: dict<number> = {a: 5, b: 6} |
Help: variables
Conversion | Python | Vim9Script |
---|---|---|
Number to Float | float(n) |
floor(n) |
Float to Number | int(f) |
float2nr(f) |
Number to String | str(n) |
string(n) |
String to Number | int(str) |
str2nr(str) |
Float to String | str(f) |
string(f) |
String to Float | float(str) |
str2float(str) |
List to String | str(l) |
string(l) |
String to List | eval(str) |
eval(str) |
List to Tuple | tuple(l) |
list2tuple(l) |
Tuple to List | list(t) |
tuple2list(t) |
Tuple to String | str(t) |
string(t) |
String to Tuple | eval(str) |
eval(str) |
Dict to String | str(d) |
string(d) |
String to Dict | eval(str) |
eval(str) |
Help: string(), str2nr(), str2float(), float2nr(), floor(), eval(), list2tuple(), tuple2list()
Type | Python | Vim9Script |
---|---|---|
Number | isintance(x, int) |
type(x) is v:t_number |
String | isinstance(x, str) |
type(x) is v:t_string |
List | isintance(x, list) |
type(x) is v:t_list |
Tuple | isintance(x, tuple) |
type(x) is v:t_tuple |
Dictionary | isintance(x, dict) |
type(x) is v:t_dict |
Float | isintance(x, float) |
type(x) is v:t_float |
Boolean | isinstance(x, bool) |
type(x) is v:t_bool |
Help: type()
All the variables in a Vim9Script have a scope. The default scope for variables and functions is script-local. The scope is specified by prefixing the variable name with one of the prefix strings shown in the table below. If a variable name is used without a scope prefix, then inside a function the function local scope is used. Otherwise the script-local scope is used.
Scope Prefix | Description |
---|---|
g: | global |
v: | internal |
b: | buffer local |
w: | window local |
t: | tab local |
Help: global-variable, vim-variable, buffer-variable, window-variable, tabpage-variable
What | Python | Vim9Script |
---|---|---|
addition | a = 10 + 20 |
a = 10 + 20 |
subtraction | a = 30 - 10 |
a = 30 - 10 |
multiplication | a = 3 * 5 |
a = 3 * 5 |
division | a = 22 / 7 |
a = 22 / 7 |
modulus | a = 10 % 3 |
a = 10 % 3 |
exponentiation | a = 2 ** 3 |
a = float2nr(pow(2, 3)) |
floor division | a = 10 // 3 |
a = floor(10 / 3.0) |
Help: expr5
What | Python | Vim9Script |
---|---|---|
addition | a += 1 |
a += 1 |
subtraction | a -= 2 |
a -= 2 |
multiplication | a *= 4 |
a *= 4 |
division | a /= 2 |
a /= 2 |
modulus | a %= 2 |
a %= 2 |
Help: :let+=
What | Python | Vim9Script |
---|---|---|
equal to | a == b |
a == b |
not equal to | a != b |
a != b |
greater than | a > b |
a > b |
less than | a < b |
a < b |
greater than or equal to | a >= b |
a >= b |
less than or equal to | a <= b |
a <= b |
Help: expr4
What | Python | Vim9Script |
---|---|---|
logical and | x and y |
x && y |
logical or | x or y |
x || y |
logical not | not x |
!x |
Help: expr2
What | Python | Vim9Script |
---|---|---|
bitwise AND | c = a & b |
c = and(a, b) |
bitwise OR | c = a | b |
c = or(a, b) |
bitwise NOT | c = ~a |
c = invert(a) |
bitwise XOR | c = a ^ b |
c = xor(a, b) |
left shift | c = a << b |
c = a << b |
right shift | c = a >> b |
c = a >> b |
Help: and(), or(), invert(), xor()
What | Python | Vim9Script |
---|---|---|
is | x is y |
x is y |
is not | x is not y |
x isnot y |
Help: expr-is, expr-isnot
Vim has functions for dealing with both multibyte and non-multibyte strings. Some functions deal with bytes and some functions deal with characters. Refer to the reference guide for the various functions to get the detailed information.
Python:
s1 = r"one\ntwo\n"
s2 = "one\ntwo\n"
Vim9Script:
var s1 = 'one\ntwo\n'
var s2 = "one\ntwo\n"
Help: literal-string, string
Python:
n = len("Hello World")
Vim9Script:
# count the number of bytes in a string
var n = len("Hello World")
# count the number of bytes in a string
n = strlen("Hello World")
# count the number of characters in a string
n = strcharlen("Hello World")
# count the number of characters in a string
n = strwidth("Hello World")
Help: len(), strlen(), strcharlen(), strwidth(), strdisplaywidth()
Python:
str1 = "blue"
str2 = "sky"
s = str1 + str2
Vim9Script:
var str1 = "blue"
var str2 = "sky"
var s = str1 .. str2
Python:
# compare strings matching case
str1 = "blue"
str2 = "blue"
str3 = "sky"
if str1 == str2:
print("str1 and str2 are same")
if str1 is str2:
print("str1 and str2 are same")
if str1 != str3:
print("str1 and str3 are not same")
if str1 is not str3:
print("str1 and str3 are not same")
# compare strings ignoring case
str1 = "Blue"
str2 = "BLUE"
str3 = "sky"
if str1.lower() == str2.lower():
print("str1 and str2 are same")
if str1.lower() != str3.lower():
print("str1 and str3 are not same")
Vim9Script:
# compare strings matching case
var str1 = "blue"
var str2 = "blue"
var str3 = "sky"
if str1 == str2
echo "str1 and str2 are same"
endif
if str1 != str3
echo "str1 and str3 are not same"
endif
# compare strings ignoring case
str1 = "Blue"
str2 = "BLUE"
str3 = "sky"
if str1 ==? str2
echo "str1 and str2 are same"
endif
if str1 !=? str3
echo "str1 and str3 are not same"
endif
Help: expr4
In Python, when using an index range to specify a sequence of characters in a string, the character at the end index is not included. In Vim, the character at the end index is included.
Python:
str = "HelloWorld"
sub = str[2 : 5]
sub = str[-3 : ]
sub = str[2 : -3]
Vim9Script:
var str = "HelloWorld"
# use character index range
var sub = str[2 : 4]
# use a negative character range
sub = str[-3 : ]
sub = str[2 : -3]
# use byte index and length
echo strpart(str, 2, 3)
# use character index and length
echo strcharpart(str, 2, 3)
# use the start and end character indexes
echo slice(str, 2, 3)
# exclude the last character
echo slice(str, 6, -1)
Help: expr-[:], strpart(), strcharpart(), slice()
Python:
str = "Hello World"
c = str.count("l")
Vim9Script:
var str = "Hello World"
var c = str->count("l")
Help: count()
Python:
str = "running"
idx = str.find("nn") # leftmost
idx = str.rfind("ing") # rightmost
# idx == -1 if the substring is not present
Vim9Script:
var str = "running"
var idx = str->stridx("nn") # leftmost
idx = str->strridx("ing") # rightmost
# idx == -1 if the substring is not present
Python:
str = "running"
if str.startswith("run"):
print("starts with run")
if str.endswith("ing"):
print("ends with ing")
Vim9Script:
var str = "running"
if str =~# '^run'
echo "starts with run"
endif
if str[ : len('run') - 1] == 'run'
echo "starts with run"
endif
if str =~ 'ing$'
echo "ends with ing"
endif
Help: expr-=~#
Python:
s = ":".join(['ab', 'cd', 'ef'])
Vim9Script:
var s = join(['ab', 'cd', 'ef'], ':')
Help: join()
Python:
s = "Hello World"
l = s.lower()
l = s.upper()
Vim9Script:
var s = "Hello World"
var l = s->tolower()
l = s->toupper()
Python:
s = "Hello World"
s2 = s.replace("Hello", "New")
Vim9Script:
var s = "Hello World"
var s2 = s->substitute("Hello", "New", 'g')
Help: substitute()
Python:
s = "a:b:c"
s2 = s.split(":")
Vim9Script:
var s = "a:b:c"
var s2 = s->split(":")
Python:
s = " python "
# strip leading and trailing whitespace
s2 = s.strip()
print(f"<{s2}>")
# strip leading space characters
s2 = s.lstrip(' ')
print(f"<{s2}>")
# strip trailing space characters
s2 = s.rstrip(' ')
print(f"<{s2}>")
Vim9Script:
var s: string
s = " vim "
# strip leading and trailing whitespace
s2 = s->trim()
echo $"<{s2}>"
# strip leading space characters
s2 = s->trim(' ', 1)
echo $"<{s2}>"
# strip trailing space characters
s2 = s->trim(' ', 2)
echo $"<{s2}>"
Help: trim()
Python:
s = "text"
if s.isalnum():
print("Contains only alphanumeric characters")
if s.isalpha():
print("Contains only alphabetic characters")
if s.isdigit():
print("Contains only digits")
if s.isspace():
print("Contains only whitespace characters")
if s.isupper():
print("Contains only uppercase characters")
if s.islower():
print("Contains only lowercase characters")
Vim9Script:
var s = "text"
if s =~ '^[:alnum:]\+'
echo "Contains only alphanumeric characters"
endif
if s =~ '^\a\+$'
echo "Contains only alphabetic characters"
endif
if s =~ '^\d\+$'
echo "Contains only digits"
endif
if s =~ '^\s\+$'
echo "Contains only whitespace characters"
endif
if s =~ '^\u\+$'
echo "Contains only uppercase characters"
endif
if s =~ '^\l\+$'
echo "Contains only lowercase characters"
endif
Help: /collection
Python:
s = str(268)
s = str(22.7)
s = str([1, 2, 3])
s = str({'a' : 1, 'b' : 2})
Vim9Script:
var s = string(268)
s = string(22.7)
s = string([1, 2, 3])
s = string({a: 1, b: 2})
Help: string()
Python:
x = 10
y = eval("x * 2")
print(y)
n = eval("min([4, 3, 5])")
Vim9Script:
var x = 10
var y = eval("x * 2")
echo y
var n = eval("min([4, 3, 5])")
Help: eval()
Python:
exec("for i in range(5):\n print(i)\n")
Vim9Script:
execute "for i in range(5)\necho i\nendfor"
Help: :execute
Python:
aVar = 10
str = f"Value of 'a' is {aVar}"
print(str)
bList = [1, 2, 3]
str = f"bList is {bList}"
print(str)
Vim9Script:
var aVar = 10
var str = $"Value of 'a' is {aVar}"
echo str
var bList = [1, 2, 3]
str = $"bList is {string(bList)}"
echo str
Help: interp-string
Python:
print("Ordinal value of 'a' is " + str(ord("a")))
print("Character with value 65 is " + chr(65))
Vim9Script:
echo "Ordinal value of 'a' is " .. char2nr('a')
echo "Character with value 65 is " .. nr2char(65)
Python:
l = [ord(i) for i in 'Hello']
s = ''.join(chr(i) for i in l)
print(s)
print(l)
Vim9Script:
var l = str2list('Hello')
var s = list2str(l)
echo s
echo l
Help: str2list(), list2str()
Python:
from fuzzywuzzy import process
from fuzzywuzzy import fuzz
str_list = ['crow', 'clay', 'cobb']
m = process.extractOne('cay', str_list, scorer=fuzz.partial_ratio)
print(m)
Vim9Script:
var str_list = ['crow', 'clay', 'cobb']
var m = matchfuzzy(str_list, 'cay')
echo m
Help: matchfuzzy(), matchfuzzypos()
Method | Python | Vim9Script |
---|---|---|
capitalize() | 'one two'.capitalize() |
'one two'->substitute('.', '\u&', '') |
center() | 'abc'.center(10) |
Not available |
count() | "abbc".count('b') |
"abbc"->count('b') |
decode() | str.decode() |
Not available |
encode() | str.encode() |
Not available |
endswith() | 'running'.endswith('ing') |
'running' =~# 'ing$' |
expandtabs() | "a\tb".expandtabs() |
"a\tb"->substitute("\t", repeat(' ', 8), 'g') |
find() | "running".find('nn') |
"running"->stridx('nn') |
index() | 'hello'.index('e') |
'hello'->stridx('e') |
isalnum() | str.isalnum() |
str =~ '^[[:alnum:]]\+' |
isalpha() | str.isalpha() |
str =~ '^\a\+$' |
isdigit() | str.isdigit() |
str =~ '^\d\+$' |
islower() | str.islower() |
str =~ '^\l\+$' |
isspace() | str.isspace() |
str =~ '^\s\+$' |
istitle() | str.istitle() |
str =~ '\(\<\u\l\+\>\)\s\?' |
isupper() | str.isupper() |
str =~ '^\u\+$' |
join() | ':'.join(['a', 'b', 'c']) |
join(['a', 'b', 'c'], ':') |
ljust() | 'abc'.ljust(10) |
Not available |
lower() | 'Hello'.lower() |
'Hello'->tolower() |
lstrip() | ' vim '.lstrip() |
' vim '->trim(' ', 1) |
partition() | 'ab-cd-ef'.partition('-') |
'ab-cd-ef'->matchlist('\(.\{-}\)\(-\)\(.*\)')[1:3] |
replace() | 'abc'.replace('abc', 'xyz') |
'abc'->substitute('abc', 'xyz', 'g') |
rfind() | 'running'.rfind('ing') |
'running'->strridx('ing') |
rindex() | 'running'.rindex('ing') |
'running'->strridx('ing') |
rjust() | 'abc'.rjust(10) |
Not available |
rpartition() | 'ab-cd-ef'.rpartition('-') |
'ab-cd-ef'->matchlist('\(.*\)\(-\)\(.*\)')[1:3] |
rsplit() | 'a-b-c-d'.rsplit('-', 2) |
Not available |
rstrip() | ' vim '.rstrip() |
' vim '->trim(' ', 2) |
split() | 'a-b-c'.split('-') |
'a-b-c'->split('-') |
splitlines() | "one\ntwo".splitlines() |
"one\ntwo"->split("\n") |
startswith() | 'running'.startswith('run') |
'running' =~# '^run' |
strip() | ' vim '.strip() |
' vim '->trim() |
swapcase() | 'Abc'.swapcase() |
Not available |
title() | 'onE twO'.title() |
'onE twO'->substitute('\<\(.\)\(\S\+\)\>', '\u\1\L\2', 'g') |
translate() | 'abcd'.translate(string.maketrans('bd', '12')) |
'abcd'->tr('bd', '12') |
upper() | 'Hello'.upper() |
'Hello'->toupper() |
zfill() | str.zfill(10) |
printf("%010s", "Hello") |
Help: string-functions
Python:
l = [1, 2, 3, 4]
Vim9script:
var l = [1, 2, 3, 4]
Help: List
Python:
l = [1, 2, 3, 4]
v1 = l[2]
v2 = l[-2]
Vim9Script:
var l = [1, 2, 3, 4]
var v1 = l[2]
var v2 = l[-2]
Help: list-index
Python:
l = [1, 2, 3, 4]
l[3] = 5
Vim9Script:
var l = [1, 2, 3, 4]
var l[3] = 5
Help: list-modification
Python:
l = []
l.append(5)
l += [6, 7]
Vim9Script:
var l = []
add(l, 5)
var l += [5, 6]
Help: add()
Python:
l = []
l.extend([2, 3])
l += [6, 7]
Vim9Script:
var l = []
l->extend([2, 3])
l += [6, 7]
Help: extend()
Python:
l = [1, 3]
l.insert(1, 2)
Vim9Script:
var l = [1, 3]
# insert before index 1
eval l->insert(2, 1)
# insert at the begining
eval l->insert(5)
Help: insert()
Python:
l = [4, 5, 6]
l.remove(5)
del l[0]
Vim9Script:
var l = [4, 5, 6]
var idx = index(l, 5)
if idx != -1
remove(l, idx)
endif
unlet l[0]
echo l
Python:
l = [1, 2, 3]
v = l.pop()
Vim9Script:
var l = [1, 2, 3]
var v = l->remove(-1)
Help: remove()
Python:
l = [1, 2, 3]
x = l.index(2)
Vim9Script:
var l = [1, 2, 3]
var x = l->index(2)
Help: index()
Python:
colors = [{'color': 'red'}, {'color': 'blue'}, {'color': 'green'}]
idx = next((i for i, v in enumerate(colors) if v['color'] == 'blue'), -1)
print(idx)
Vim9Script:
var colors = [{color: 'red'}, {color: 'blue'}, {color: 'green'}]
var idx = indexof(colors, (i, v) => v.color == 'blue')
echo idx
Help: indexof()
In Python, when using an index range to specify a series of items in a List, the item at the end index is not included. In Vim, the item at the end index is included. The slice() function excludes the item at the end index.
Python:
l = [1, 2, 3, 4]
print(l[1:3])
print(l[2:])
Vim9Script:
var l = [1, 2, 3, 4]
echo l[1 : 3]
echo l[2 : ]
echo l[-2 : ]
# slice() function excludes the item at the end index.
echo slice(l, 2, 3)
echo slice(l, 2)
Python:
l = [1, 2] + [3 ,4]
Vim9Script:
var l = [1, 2] + [3, 4]
Help: list-index
Python:
l = ['vim'] * 4
Vim9Script:
var l = ['vim']->repeat(4)
Help: repeat()
Python:
l = [2, 4, 4, 5]
x = l.count(4)
Vim9Script:
var l = [2, 4, 4, 5]
var x = l->count(2)
Help: count()
Python:
l = ['a', 'b', 'c']
n = len(l)
Vim9Script:
var l = ['a', 'b', 'c']
var n = l->len()
Help: len()
Python:
l = [10, 20, 30]
for v in l:
print(v)
# Print both the list index and the value
for i, v in enumerate(l):
print(i, v)
# Use a for loop for list iteration
for i in range(len(l)):
print(i, l[i])
Vim9Script:
var l = [10, 20, 30]
for v in l
echo v
endfor
# Print both the list index and the value
for [i, v2] in items(l)
echo i v2
endfor
# Use a for loop for list iteration
for i2 in range(len(l))
echo i l[i2]
endfor
Help: :for
Python:
l = [3, 2, 1]
l.sort()
print(l)
Vim9Script:
var l = [3, 2, 1]
echo l->sort()
Help: sort()
Python:
l = ['a', 'b', 'b', 'c', 'c', 'd']
# order of the elements is not retained
tset = set(l)
print(list(tset))
Vim9Script:
# needs a sorted list
var l = ['a', 'b', 'b', 'c', 'c', 'd']
echo copy(l)->uniq()
Help: uniq()
Python:
l = [1, 2, 3]
l.reverse()
print(l)
Vim9Script:
var l = [1, 2, 3]
echo reverse(l)
Help: reverse()
Python:
l = [3, 2, 1]
l2 = l.copy()
Vim9Script:
var l = [3, 2, 1]
var l2 = l->copy()
Help: copy()
Python:
import copy
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a)
Vim9Script:
var a = [[1, 2], [3, 4]]
var b = a->deepcopy()
Help: deepcopy()
Python:
l = [3, 2, 1]
l.clear()
Vim9Script:
var l = [3, 2, 1]
unlet l[:]
Help: :unlet
Python:
l1 = [1, 2]
l2 = l1
l3 = [1, 2]
if l1 is l2:
print("Lists l1 and l2 refer to the same list")
if l1 is not l3:
print("Lists l1 and l3 do not refer to the same list")
if l1 == l3:
print("Lists l1 and l3 contain the same elements")
if l1 != l3:
print("Lists l1 and l3 are different")
Vim9Script:
var l1 = [1, 2]
var l2 = l1
var l3 = [1, 2]
if l1 is l2
echo "Lists l1 and l2 refer to the same list"
endif
if l1 isnot l3
echo "Lists l1 and l3 do not refer to the same list"
endif
if l1 == l3
echo "Lists l1 and l3 contain the same elements"
endif
if l1 != l3
echo "Lists l1 and l3 are different"
endif
Help: list-identity
Note that Vim does not support List comprehension.
Python:
odd = list(filter(lambda x: x % 2, range(10)))
odd = [x for x in range(10) if x % 2]
Vim9Script:
var odd = filter(range(10), (idx, v) => v % 2)
echo odd
Help: filter()
Note that Vim does not support List comprehension.
Python:
num_str = list(map(lambda x: str(x), range(10)))
num_str = [str(x) for x in range(10)]
Vim9Script:
var num_str = map(range(10), (idx, v) => string(v))
echo num_str
Help: map()
Python:
# using a lambda function
from functools import reduce
sum = reduce((lambda x, y: x + y), [1, 2, 3, 4])
# using a function
def SumNum(a, b):
return a + b
sum = reduce(SumNum, [1, 2, 3, 4])
Vim9Script:
# using a lambda function
var sum = reduce([1, 2, 3, 4], (x, y) => x + y)
# using a function
def SumNum(x: number, y: number): number
return x + y
enddef
var sum2 = reduce([1, 2, 3, 4], function('SumNum'))
echo sum2
Help: reduce()
Python:
l = [[5, 9], [1, 3], [10, 20]]
flattenlist = [i for subl in l for i in subl]
print(flattenlist)
Vim9Script:
var l = [[5, 9], [1, 3], [10, 20]]
var flattenlist = flattennew(l)
echo flattenlist
Help: flatten(), flattennew()
Python:
l = [3, 10, 8]
v1 = min(l)
v2 = max(l)
print(v1, v2)
Vim9Script:
var l = [3, 10, 8]
var v1 = l->min()
var v2 = l->max()
echo v1 v2
Python:
s = str([3, 5, 7])
Vim9Script:
var s = string([3, 5, 7])
echo s
Help: string()
Method | Python | Vim9Script |
---|---|---|
append() | m.append(6) |
m->add(6) |
clear() | m.clear() |
unlet m[:] |
copy() | m.copy() |
m->copy() |
count() | m.count(6) |
m->count(6) |
extend() | m.extend([5, 6]) |
m->extend([5, 6]) |
index() | m.index(6) |
m-index(6) |
insert() | m.insert(2, 9) |
m->insert(9, 2) |
pop() | m.pop() |
m->remove(-1) |
remove() | m.remove(6) |
m->remove(m->index(6)) |
reverse() | m.reverse() |
m->reverse() |
sort() | m.sort() |
m->sort() |
Help: list-functions
Python:
t = (1, 2, 3, 4)
Vim9Script:
var t = (1, 2, 3, 4)
Help: Tuple
Python:
t = (1, 2, 3, 4)
v1 = t[2]
v2 = t[-2]
Vim9Script:
var t = (1, 2, 3, 4)
var v1 = t[2]
var v2 = t[-2]
Help: tuple-index
Python:
t = (1, [2, 3], {'a': 4})
t[1][0] = 5
t[2]['a'] = 10
Vim9Script:
var t = (1, [2, 3], {'a': 6})
t[1][0] = 5
t[2]['a'] = 10
Help: tuple-modification
Python:
t = (1, 2, 3)
x = t.index(2)
Vim9Script:
var t = (1, 2, 3)
var x = t->index(2)
echo x
Help: index()
Python:
colors = ({'color': 'red'}, {'color': 'blue'}, {'color': 'green'})
idx = next((i for i, v in enumerate(colors) if v['color'] == 'blue'), -1)
print(idx)
Vim9Script:
var colors = ({color: 'red'}, {color: 'blue'}, {color: 'green'})
var idx = indexof(colors, (i, v) => v.color == 'blue')
echo idx
Help: indexof()
In Python, when using an index range to specify a series of items in a Tuple, the item at the end index is not included. In Vim, the item at the end index is included. The slice() function excludes the item at the end index.
Python:
t = (1, 2, 3, 4)
print(t[1:3])
print(t[2:])
Vim9Script:
var t = (1, 2, 3, 4)
echo t[1 : 3]
echo t[2 :]
echo t[-2 :]
# slice() function excludes the item at the end index.
echo slice(t, 2, 3)
echo slice(t, 2)
Python:
t = (1, 2) + (3 ,4)
Vim9Script:
var t = (1, 2) + (3, 4)
echo t
Help: tuple-concatenation
Python:
t = ('vim',) * 4
Vim9Script:
var t = ('vim')->repeat(4)
echo t
Help: repeat()
Python:
t = (2, 4, 4, 5)
x = t.count(4)
Vim9Script:
var t = (2, 4, 4, 5)
var x = t->count(2)
Help: count()
Python:
t = ('a', 'b', 'c')
n = len(t)
Vim9Script:
var t = ('a', 'b', 'c')
var n = t->len()
Help: len()
Python:
t = (10, 20, 30)
for v in t:
print(v)
# Print both the tuple index and the value
for i, v in enumerate(t):
print(i, v)
# Use a for loop for tuple iteration
for i in range(len(t)):
print(i, t[i])
Vim9Script:
var t = (10, 20, 30)
for v in t
echo v
endfor
# Print both the tuple index and the value
for [i, v2] in items(t)
echo i v2
endfor
# Use a for loop for tuple iteration
for i2 in range(len(t))
echo i2 t[i2]
endfor
Help: :for
Python:
t = (1, 2, 3)
t.reverse()
print(t)
Vim9Script:
var t = (1, 2, 3)
echo reverse(t)
Help: reverse()
Python:
t = (3, 2, 1)
t2 = t.copy()
Vim9Script:
var t = (3, 2, 1)
var t2 = t->copy()
Help: copy()
Python:
import copy
a = ([1, 2], [3, 4])
b = copy.deepcopy(a)
Vim9Script:
var a = ([1, 2], [3, 4])
var b = a->deepcopy()
Help: deepcopy()
Python:
t1 = (1, 2)
t2 = l1
t3 = (1, 2)
if t1 is t2:
print("Tuples t1 and t2 refer to the same tuple")
if t1 is not t3:
print("Tuples t1 and t3 do not refer to the same tuple")
if t1 == t3:
print("Tuples t1 and t3 contain the same elements")
if t1 != t3:
print("Tuples t1 and t3 are different")
Vim9Script:
var t1 = (1, 2)
var t2 = t1
var t3 = (1, 2)
if t1 is t2
echo "Tuples t1 and t2 refer to the same tuple"
endif
if t1 isnot t3
echo "Tuples t1 and t3 do not refer to the same tuple"
endif
if t1 == t3
echo "Tuples t1 and t3 contain the same elements"
endif
if t1 != t3
echo "Tuples t1 and t3 are different"
endif
Help: tuple-identity
Python:
# using a lambda function
from functools import reduce
sum = reduce((lambda x, y: x + y), (1, 2, 3, 4))
# using a function
def SumNum(a, b):
return a + b
sum = reduce(SumNum, (1, 2, 3, 4))
Vim9Script:
# using a lambda function
var sum = reduce((1, 2, 3, 4), (x, y) => x + y)
# using a function
def SumNum(x: number, y: number): number
return x + y
enddef
var sum2 = reduce((1, 2, 3, 4), function('SumNum'))
Help: reduce()
Python:
t = (3, 10, 8)
v1 = min(t)
v2 = max(t)
print(v1, v2)
Vim9Script:
var t = (3, 10, 8)
var v1 = t->min()
var v2 = t->max()
echo v1 v2
Python:
s = str((3, 5, 7))
Vim9Script:
var s = string((3, 5, 7))
Help: string()
Method | Python | Vim9Script |
---|---|---|
copy() | m.copy() |
m->copy() |
count() | m.count(6) |
m->count(6) |
index() | m.index(6) |
m-index(6) |
reverse() | m.reverse() |
m->reverse() |
Help: tuple-functions
Python:
d = {'red' : 10, 'blue' : 20}
x = {}
Vim9Script:
var d = {red: 10, blue: 20}
var x = {}
Help: Dict
Python:
d = {'red' : 10, 'blue' : 20}
x = d['red']
Vim9Script:
var d = {red: 10, blue: 20}
var x = d['red']
x = d.red
Help: dict
Python:
d = {'red' : 10, 'blue' : 20}
d['red'] = 15
Vim9Script:
var d = {red: 10, blue: 20}
d.red = 15
Help: dict-modification
Python:
d = {'red' : 10, 'blue' : 20}
v = d.get('red')
Vim9Script:
var d = {red: 10, blue: 20}
var v = d->get('red')
Help: get()
Python:
d = {'red' : 10, 'blue' : 20}
d['green'] = 30
Vim9Script:
var d = {red: 10, blue: 20}
d.green = 30
Help: dict-modification
Python:
d = {}
d.update({'color' : 'grey'})
Vim9Script:
var d = {}
eval d->extend({color: 'grey'})
Help: extend()
Python:
d = {'red' : 10, 'blue' : 20}
d.pop('red')
Vim9Script:
var d = {red: 10, blue: 20}
d->remove('red')
Help: remove(),
Python:
d = {'red' : 10, 'blue' : 20}
d.clear()
Vim9Script:
var d = {red: 10, blue: 20}
d->filter("0")
Help: dict-modification
Python:
d = {'red' : 10, 'blue' : 20}
n = len(d)
Vim9Script:
var d = {red: 10, blue: 20}
var n = d->len()
Help: len()
Python:
d = {'red' : 10, 'blue' : 10}
x = sum(n == 10 for n in d.values())
print(x)
Vim9Script:
var d = {red: 10, blue: 10}
var x = d->count(10)
echo x
Help: count()
Python:
d = {'red' : 10, 'blue' : 20}
if 'red' in d:
print("found red key")
Vim9Script:
var d = {red: 10, blue: 20}
if d->has_key('red')
echo "found red key"
endif
Help: has_key()
Python:
d = {'red' : 10, 'blue' : 20}
for k in d:
print(k)
for k in d:
print(d[k])
Vim9Script:
var d = {red: 10, blue: 20}
for k in d->keys()
echo k
endfor
for k2 in d->keys()
echo d[k2]
endfor
Help: keys()
Python:
d = {'red' : 10, 'blue' : 20}
for v in d.values():
print(v)
Vim9Script:
var d = {red: 10, blue: 20}
for v in d->values()
echo v
endfor
Help: values()
Python:
d = {'red' : 10, 'blue' : 20}
for k, v in d.items():
print(k, v)
Vim9Script:
var d = {red: 10, blue: 20}
for [k, v] in d->items()
echo k v
endfor
Help: items()
Python:
d = {'red' : 10, 'blue' : 20}
new_d = d.copy()
Vim9Script:
var d = {red: 10, blue: 20}
var new_d = d->copy()
Help: copy()
Python:
import copy
a = {'x' : [1, 2], 'y' : [3, 4]}
b = copy.deepcopy(a)
Vim9Script:
var a = {x: [1, 2], y: [3, 4]}
var b = a->deepcopy()
Help: deepcopy()
Python:
d1 = {'a' : 10, 'b' : 20}
d2 = {'a' : 10, 'b' : 20}
if d1 == d2:
print("Dicts d1 and d2 have the same content")
d3 = d1
if d1 is d3:
print("Dicts d1 and d3 refer to the same dict")
if d2 is not d3:
print("Dicts d2 and d3 do not refer to the same dict")
Vim9Script:
var d1 = {a: 10, b: 20}
var d2 = {a: 10, b: 20}
if d1 == d2
echo "Dicts d1 and d2 have the same content"
endif
var d3 = d1
if d1 is d3
echo "Dicts d1 and d3 refer to the same dict"
endif
if d2 isnot d3
echo "Dicts d2 and d3 do not refer to the same dict"
endif
Help: dict-identity
Note that Vim does not support Dict comprehension.
Python:
d1 = {'red' : 10, 'green' : 20, 'blue' : 10}
# filter dict items with value 10
d2 = dict(filter(lambda e : e[1] == 10, d1.items()))
print(d1, d2)
# use dict comprehension
d3 = {k: v for [k, v] in d1.items() if v == 10}
print(d1, d3)
Vim9Script:
var d1 = {red: 10, green: 20, blue: 10}
# filter dict items with value 10
var d2 = copy(d1)->filter((k, v) => v == 10)
echo d1 d2
Help: filter()
Note that Vim does not support Dict comprehension.
Python:
d1 = {'red' : 10, 'green' : 20, 'blue' : 30}
# increment the values by 5
d2 = dict(map(lambda e : (e[0], e[1] + 5), d1.items()))
print(d1, d2)
# use dict comprehension
d3 = {k: v + 5 for k, v in d1.items()}
print(d1, d3)
Vim9Script:
var d1 = {red: 10, green: 20, blue: 30}
# increment the values by 5
var d2 = copy(d1)->map((k, v) => v + 5)
echo d1 d2
Help: map()
Python:
d = {'red' : 10, 'green' : 20}
v1 = min(d.values())
v2 = max(d.values())
print(v1, v2)
Vim9Script:
var d = {red: 10, green: 20}
var v1 = d->min()
var v2 = d->max()
echo v1 v2
Python:
d = str({'a' : 1, 'b' : 2})
Vim9Script:
var d = string({a: 1, b: 2})
Help: string()
Method | Python | Vim9Script |
---|---|---|
clear() | d.clear() |
call filter(d, '0') |
copy() | newDict = d.copy() |
var newDict = d->copy() |
fromkeys() | d = dict.fromkeys(x) |
Not available |
get() | v = d.get('red') |
var v = d->get('red') |
in or has_key() | 'red' in d |
d->has_key('red') |
items() | d.items() |
d->items() |
keys() | d.keys() |
d->keys() |
pop() | d.pop('red') |
call d->remove('red') |
popitem() | d.popitem() |
Not available |
setdefault() | d.setdefault('red', 10) |
Not available |
update() | d.update({'a' : 10, 'b' : 20} |
d->extend({'a' : 10, 'b' : 20}) |
values() | d.values() |
d->values() |
Help: dict-functions
Python:
if a > b:
print("a is greater than b")
Vim9Script:
if a > b
echo "a is greater than b"
endif
Help: :if
Python:
if a > b:
print("a is greater than b")
else:
print("a is less than or equal to b")
Vim9Script:
if a > b
echo "a is greater than b"
else
echo "a is less than or equal to b"
endif
Help: :else
Python:
if a > b:
print("a is greater than b")
elif a < b:
print("a is less than b")
else:
print("a is equal to b")
Vim9Script:
if a > b
echo "a is greater than b"
elseif a < b
echo "a is less than b"
else
echo "a is equal to b"
endif
Help: :elseif
Python:
if a > b and (a > c or a > d):
print "a is greater than b and greater than c or d"
Vim9Script:
if a > b && (a > c || a > d)
echo "a is greater than b and greater than c or d"
endif
Help: expr2
Python:
if status == True:
if a >= 1:
print("Nested if")
Vim9Script:
if status == true
if a >= 1
echo "Nested if"
endif
endif
Help: :if
Python:
for i in range(5):
print(i)
Vim9Script:
for i in range(5)
echo i
endfor
Help: :for
Python:
for i in ['a', 'b', 'c']:
if i == 'b':
break
print(i)
Vim9Script:
for i in ['a', 'b', 'c']
if i == 'b'
break
endif
echo i
endfor
Help: :break
Python:
for i in ['a', 'b', 'c']:
if i == 'b':
continue
print(i)
Vim9Script:
for i in ['a', 'b', 'c']
if i == 'b'
continue
endif
echo i
endfor
Help: :continue
Python:
for i in range(10):
for j in range(10):
print(str(i) + 'x' + str(j) + '=' + str(i * j))
Vim9Script:
for i in range(4)
for j in range(4)
echo $"{i} x {j} = {i * j}"
endfor
endfor
Help: :for
Python:
i = 1
while i <= 5 :
print(i)
i += 1
Vim9Script:
var i = 1
while i <= 5
echo i
i += 1
endwhile
Help: :while
Python:
# This is a python comment
i = 0 # First iteration
Vim9Script:
# This is a Vim9script comment
var i = 0 # First iteration
Help: :comment
Functions in a Vim9script are automatically compiled. A Vim9 function name must start with an uppercase letter.
Python:
def Min(x, y):
return x if < y else y
print(Min(6, 3)
Vim9Script:
def Min(x: number, y: number): number
return x < y ? x : y
enddef
echo Min(6, 3)
Help: user-functions
Python:
def EchoValue(v):
print(v)
EchoValue(100)
Vim9Script:
def EchoValue(v: number)
echo v
enddef
call EchoValue(100)
Help: :call
Python:
def Sum(a, b):
return a + b
s = Sum(10, 20)
Vim9Script:
def Sum(a: number, b: number): number
return a + b
enddef
var s = Sum(10, 20)
Help: :return
Python:
def AddValues(l):
l.extend([1, 2, 3, 4])
Vim9Script:
def AddValues(l: list<number>)
l->extend([1, 2, 3, 4])
enddef
Help: function-argument
Python:
def Sum(v1, *args):
sum = v1
for i in *args:
sum += i
return sum
Vim9Script:
def Sum(v1: number, ...rest: list<number>): number
var sum = v1
for i in rest
sum += i
endfor
return sum
enddef
var s1 = Sum(10, 20, 30, 40)
s1 = Sum(10)
Help: a:000
Python:
def Powerof(base, exp = 2):
return base ** exp
Vim9Script:
def PowerOf(base: number, exp: number = 2): number
return float2nr(pow(base, exp))
enddef
var val = PowerOf(4)
echo val
val = PowerOf(4, 3)
echo val
Help: optional-function-argument
Python:
counter = 1
def Incr():
global counter
counter += 1
Vim9Script:
g:counter = 1
def Incr()
g:counter += 1
enddef
Incr()
echo g:counter
Help: global-variable
Python:
def Foo():
print("Foo")
Bar = Foo
Bar()
Vim9Script:
def Foo()
echo "Foo"
enddef
var Bar = function("Foo")
Bar()
Help: Funcref
Python:
F = lambda x , y: x - y
print(F(5,2))
Vim9Script:
var F = (x, y) => x - y
echo F(5, 2)
Help: lambda
Python:
import functools
def Mylog(subsys, msg):
print("%s: %s" % (subsys, msg))
ErrLog = functools.partial(Mylog, 'ERR')
ErrLog("Failed to open file")
Vim9Script:
def Mylog(subsys: string, msg: string)
echo printf("%s: %s", subsys, msg)
enddef
var ErrLog = function('Mylog', ['ERR'])
ErrLog("Failed to open file")
Help: Partial
Python:
def foo(arg):
i = 3
return lambda x: x + i - arg
bar = foo(4)
print(bar(6))
Vim9Script:
def Foo(arg: number): func
var i = 3
return (x) => x + i - arg
enddef
var Bar = Foo(4)
echo Bar(6)
Help: closure
Python:
def Foo(base):
def Bar(val):
return base + val
return Bar
F = Foo(10)
print(F(2))
F = Foo(20)
print(F(2))
Vim9Script:
def Foo(base: number): func
def g:Bar(val: number): number
return base + val
enddef
return funcref('g:Bar')
enddef
var F = Foo(10)
echo F(2)
F = Foo(20)
echo F(2)
Help: func-closure
Python:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
def setX(self, x):
self.x = x
def setY(self, y):
self.y = y
def Print(self):
print(f"Pt = ({self.x}, {self.y})")
pt = Point(10, 20)
pt.setX(40)
pt.setY(50)
pt.Print()
print(f"x = {pt.getX()}, y = {pt.getY()}")
Vim9Script:
vim9script
class Point
var x: number
var y: number
def new(x: number, y: number)
this.x = x
this.y = y
enddef
def GetX(): number
return this.x
enddef
def GetY(): number
return this.y
enddef
def SetX(x: number)
this.x = x
enddef
def SetY(y: number)
this.y = y
enddef
def Print()
echo $"Pt = ({this.x}, {this.y})"
enddef
endclass
var pt = Point.new(10, 20)
pt.SetX(40)
pt.SetY(50)
pt.Print()
echo $"x = {pt.GetX()}, y = {pt.GetY()}"
Help: vim9-class
Python:
try:
f = open('buf.java', 'r')
lines = f.readlines()
f.close()
except IOError:
print("Failed to open file")
Vim9Script:
try
var l = readfile('buf.java')
catch /E484:/
echo "Failed to read file"
endtry
Help: exception-handling
Python:
try:
f = open('buf.java', 'r')
lines = f.readlines()
f.close()
except Exception as e:
print("Caught " + str(e))
Vim9Script:
try
var l = readfile('buf.java')
catch
echo $"Caught {v:exception}"
endtry
Help: catch-errors
Python:
try:
f = open('buf.java', 'r')
lines = f.readlines()
f.close()
finally:
print("executing code in finally block")
Vim9Script:
try
var l = readfile('buf.java')
finally
echo "executing code in finally block"
endtry
Help: try-finally
Python:
try:
raise Exception('MyException')
except Exception as e:
if str(e) == 'MyException':
print("Caught MyException")
finally:
print("Finally block")
Vim9Script:
try
throw 'MyException'
catch /MyException/
echo "Caught MyException"
finally
echo "Finally block"
endtry
Help: throw-catch
Python:
a = 1 + 2 + 3 + \
4 + 5 + 6
print(a)
Vim9Script:
var a = 1 + 2 + 3 +
4 + 5 + 6
echo a
Help: line-continuation
Vim has a function to read the entire file but doesn't have a function to read a file one line at a time.
Python:
with open('myfile.txt', 'r') as f:
lines = f.readlines()
# lines == ['line1\n', 'line2\n']
Vim9Script:
var lines = readfile("myfile.txt")
# lines == ['line1', 'line2']
Help: readfile()
Python:
lines = ['line1\n', 'line2\n']
with open('myfile.txt', 'w') as fh:
fh.writelines(lines)
lines = ['line1', 'line2']
with open('myfile.txt', 'w') as fh:
print(*lines, sep='\n', file=fh)
Vim9Script:
writefile(['line1', 'line2'], 'myfile.txt')
Help: writefile()
Python:
lines = ["line3\n", "line4\n"]
with open('myfile.txt', 'a') as fh:
fh.writelines(lines)
Vim9Script:
writefile(['line3', 'line4'], 'myfile.txt', 'a')
Help: writefile()
Python:
import os.path
if os.path.isfile('myfile.txt'):
print("File exists")
Vim9Script:
if filereadable('myfile.txt')
echo "File is readable"
endif
Help: filereadable()
Python:
import os
os.remove('myfile.txt')
Vim9Script:
delete('myfile.txt')
Help: remove()
Python:
import os
os.rename('myfile.txt', 'somefile.txt)
Vim9Script:
rename('myfile.txt', 'somefile.txt')
Help: rename()
Python:
import os
sz = os.path.getsize('move.py')
Vim9Script:
var sz = getfsize('move.py')
Help: getfsize()
Python:
os.mkdir('somedir')
Vim9Script:
mkdir('somedir')
Help: mkdir()
Python:
os.chdir('someotherdir')
Vim9Script:
chdir('someotherdir')
Help: chdir()
Python:
dir = os.getcwd()
Vim9Script:
var dir = getcwd()
Help: getcwd()
Python:
os.rmdir('somedir')
Vim9Script:
delete('somedir', 'd')
Help: delete()
Python:
import os
dir = os.scandir('.')
for f in dir:
print(f.name)
# get extended file information
dir = os.scandir('.')
for f in dir:
print(f.stat())
Vim9Script:
var dir = readdir('.')
for f in dir
echo f
endfor
# get extended file information
var dir2 = readdirex('.')
for f2 in dir2
echo f2
endfor
Help: readdir(), readdirex(), glob()
Python:
import random
r = random.randint(0, 2147483647)
Vim9Script:
var r = rand()
Help: rand()
Python:
import random
random.seed()
r = random.randint(0, 2147483647)
print(r)
Vim9Script:
var seed = srand()
var r = rand(seed)
Help: srand()
Function | Python | Vim9Script |
---|---|---|
abs | f = math.fabs(-10) |
var f = abs(-10) |
acos | f = math.acos(0.8) |
var f = acos(0.8) |
asin | f = math.asin(0.8) |
var f = asin(0.8) |
atan | f = math.atan(0.8) |
var f = atan(0.8) |
atan2 | f = math.atan2(0.4, 0.8) |
var f = atan2(0.4, 0.8) |
ceil | f = math.ceil(1.2) |
var f = ceil(1.2) |
cos | f = math.cos(4) |
var f = cos(4) |
cosh | f = math.cosh(4) |
var f = cosh(4) |
exp | f = math.exp(2) |
var f = exp(2) |
floor | f = math.floor(1.4) |
var f = floor(1.4) |
log | f = math.log(12) |
var f = log(12) |
log10 | f = math.log10(100) |
var f = log10(100) |
mod | f = math.fmod(4, 3) |
var f = fmod(4, 3) |
pow | f = math.pow(2, 3) |
var f = pow(2, 3) |
sin | f = math.sin(4) |
var f = sin(4) |
sinh | f = math.sinh(4) |
var f = sinh(4) |
sqrt | f = math.sqrt(9) |
var f = sqrt(9) |
tan | f = math.tan(4) |
var f = tan(4) |
tanh | f = math.tanh(4) |
var f = tanh(4) |
trunc | f = math.trunc(1.3) |
var f = trunc(1.3) |
Help: ceil(), abs(), floor(), fmod(), trunc(), exp(), log(), log10(), pow(), sqrt(), cos(), sin(), tan(), cosh(), sinh(), tanh(), acos(), asin(), atan(), atan2()
Python:
from datetime import datetime
d = datetime.now()
print(d.strftime("%c"))
Vim9Script:
echo strftime("%c")
Help: strftime()
Python:
from datetime import datetime
print(datetime.strptime("1997 Apr 27 11:49:23", "%Y %b %d %X"))
Vim9Script:
echo strptime("%Y %b %d %X", "1997 Apr 27 11:49:23")
Help: strptime()
Python:
import time
print int(time.time())
Vim9Script:
echo localtime()
Help: localtime()
Python:
import time
start_time = time.perf_counter()
sum = 1
for i in range(1000):
sum += i
end_time = time.perf_counter()
print("Elapsed time " + str(end_time - start_time))
Vim9Script:
var start = reltime()
var sum = 0
for i in range(1000)
sum += i
endfor
var elapsed_time = reltime(start)
echo "Elasped time" reltimefloat(elapsed_time)
Help: reltime(), reltimestr(), reltimefloat()
Python:
import subprocess
procObj = subprocess.Popen('grep class *.java',
stdout=subprocess.PIPE,
shell=True)
lines, err = procObj.communicate()
print(lines)
print("Error = " + str(procObj.returncode))
Vim9Script:
var lines = system('grep class *.java')
echo lines
echo $"Error = {v:shell_error}"
Help: system(), v:shell_error
Python:
import subprocess
procObj = subprocess.Popen('grep class *.java',
stdout=subprocess.PIPE,
shell=True)
lines, err = procObj.communicate()
print("Number of matches = " + str(len(lines.splitlines())))
Vim9Script:
var lines = systemlist('grep class *.java')
echo $"Number of matches = {len(lines)}"
Help: systemlist()
Python:
import subprocess
procObj = subprocess.Popen('wc',
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True)
lines, err = procObj.communicate("one\ntwo\n")
print(lines)
print("Error = " + str(procObj.returncode))
Vim9Script:
var lines = system('wc', "one\ntwo\n")
echo lines
echo $"Error = {v:shell_error}"
Help: system()
Python:
choice = input("coffee or tea? ")
print("You selected " + choice)
Vim9Script:
var ans = input("coffee or tea? ", "tea")
echo $"You selected {ans}"
Help: input(), inputlist(), inputdialog()
Python:
import getpass
passwd = getpass.getpass("Password: ")
print("You entered " + passwd)
Vim9Script:
var passwd = inputsecret("Password: ")
echo $"You entered {passwd}"
Help: inputsecret()
Python:
print("Hello World\n")
s = "vim"
print("Editor = %s" % (s))
Vim9Script:
echo "Hello World"
var s = "vim"
echo $"Editor = {s}"
Help: :echo, :echon, echoraw(), :echohl, :echoerr, :echomsg
Python:
name = "John"
id = 1001
print(f"Name: {name}, ID: {id}")
print("Name: {}, ID: {}".format(name, id))
print("Name: %s, ID: %d" % (name, id))
Vim9Script:
var name = "John"
var id = 1001
echo printf("Name: %s, ID: %d", name, id)
Help: printf()
Python:
import os
h = os.environ.get('HOME', '')
if h == '':
print("HOME is not set")
else:
print("HOME = " + h)
Vim9Script:
var h = getenv('HOME')
if h == v:null
echo 'HOME is not set'
else
echo $'HOME = {h}'
endif
if !exists('$HOME')
echo 'HOME is not set'
else
echo $'HOME = {$HOME}'
endif
Help: getenv(), expr-env, exists()
Python:
import os
os.environ['FOO'] = "BAR"
Vim9Script:
setenv('FOO', 'BAR')
$FOO = 'BAR'
Help: setenv(), :let-environment
Python:
import os
del os.environ['FOO']
Vim9Script:
setenv('FOO', null)
# Another method to unset an environment variable
unlet $FOO
Help: setenv(), :unlet-environment
Python:
import os
print(os.environ)
Vim9Script:
echo environ()
Help: environ()
Python:
import sys
print("Number of arguments = " + str(len(sys.argv)))
print("Arguments = " + str(sys.argv))
for arg in sys.argv:
print(arg)
Vim9Script:
echo $"Number of arguments = {len(v:argv)}"
echo $"Arguments = {string(v:argv)}"
for arg in v:argv
echo arg
endfor
Help: v:argv
Python:
import re
s = 'Test failed with error E123:'
if re.search(r'E\d+:', s):
print('Error code found')
s = 'Test successful'
if re.search(r'E\d+:', s) is None:
print("Test passed")
Vim9Script:
var s = 'Test failed with error E123:'
if s =~# 'E\d\+:'
echo "Error code found"
endif
s = 'Test successful'
if s !~# 'E\d\+:'
echo "Test passed"
endif
Python:
import re
m = re.search(r'\d+', "Abc 123 Def")
if m is not None:
idx = m.start()
end_idx = m.end()
Vim9Script:
var idx = match("Abc 123 Def", '\d\+')
var end_idx = matchend("Abc 123 Def", '\d\+')
var l = matchstrpos("Abc 123 Def", '\d\+')
echo $"start = {l[1]}, end = {l[2]}"
Help: match(), matchend(), matchstrpos()
Python:
import re
m = re.search(r'\d+', "Abc 123 Def")
if m is not None:
s = m.group(0)
print s
Vim9Script:
var s = matchstr("Abc 123 Def", '\d\+')
Help: matchstr()
Python:
import re
m = re.match(r'(\w+) (\w+) (\w+)', "foo bar baz")
if m is not None:
print("Full match: " + m.group(0))
print("1: " + m.group(1) + " 2: " + m.group(2) + " 3: " + m.group(3))
Vim9Script:
var list = matchlist("foo bar baz", '\(\w\+\) \(\w\+\) \(\w\+\)')
echo "Full match:" list[0]
echo "1:" list[1] "2:" list[2] "3:" list[3]
Help: matchlist()
Python:
import re
s = re.sub(r'bar', r'baz', "foo bar")
print(s)
Vim9Script:
var s = substitute("foo bar", 'bar', 'baz', '')
echo s
Help: substitute()
Python:
import re
def Dashrepl(m):
if m.group(0) == '-':
return ' '
else:
return '-'
s = re.sub('-{1,2}', Dashrepl, 'pro----gram-files')
print(s)
Vim9Script:
def Dashrepl(m: list<string>): string
if m[0] == '-'
return ' '
else
return '-'
endif
enddef
var s = substitute("pro----gram-files", '-\{1,2}', function('Dashrepl'), 'g')
echo s
Help: substitute()
Note that the below table contains only the regular expressions that are present in both Python and Vim.
What | Python | Vim |
---|---|---|
single character | . |
. |
start of string | ^ |
^ |
end of string | $ |
$ |
0 or more matches | * |
* |
1 or more matches | + |
\+ |
0 or 1 match | ? |
\? |
non-greedy match | *? |
\{-} |
fixed matches | {n} |
\{n} |
m to n matches | {m,n} |
\{m,n} |
m to n non-greedy matches | {m,n}? |
\{-m,n} |
character class | [...] |
[...] |
negated character class | [^...] |
[^...] |
range | [a-z] |
[a-z] |
either-or branch | | |
\| |
capturing group | (...) |
\(...\) |
non-capturing match | (?:...) |
\%(...\) |
positive look-ahead | (?=...) |
\(...\)\@= |
negative look-ahead | (?!...) |
\(...\)\@! |
positive look-behind | (?<=...) |
\(...\)\@<= |
negative look-behind | (?<!...) |
\(...\)\@<! |
start of word | \b |
\< |
end of word | \b |
\> |
digit | \d |
\d |
non-digit | \D |
\D |
whitespace | \s |
\s |
non-whitespace | \S |
\S |
word character | \w |
\w |
non-word character | \W |
\W |
ignore case | (?i) |
\c |
Help: pattern
Python:
data = bytearray(b'\x12\xF6\xAB\xFF\x49\xC0\x88\x3A\xE2\xC1\x42\xAA')
print(data)
print(data[0:4])
Vim9Script:
var data = 0z12F6ABFF.49C0883A.E2C142AA
echo data
echo data[0 : 3]
Help: blob
Python:
data = bytearray(b'')
data.append(0xC2)
data += b'\xB3\xF7\xA5'
del data[2]
print(data)
Vim9Script:
var data = 0z
data[0] = 0xC2
data += 0zB3F7A5
remove(data, 2)
echo data
Help: blob-index, blob-modification
Python:
l = [11, 12, 14]
data = bytearray(l)
print(data)
data = bytearray(b'\xDE\xAD\xBE\xEF')
l = list(data)
print(l)
Vim9Script:
var l = [11, 12, 14]
var data = list2blob(l)
echo data
data = 0zDEADBEEF
l = blob2list(data)
echo l
Help: list2blob(), blob2list()
Python:
with open("datafile.bin", "rb") as bin_fh:
data = bytearray(bin_fh.read())
with open("data2.bin", "wb") as bin_fh:
bin_fh.write(data)
Vim9Script:
var data = readblob('datafile.bin')
writefile(data, 'data2.bin')
Help: readblob(), writefile()
Python:
import threading
def TimerCallback(ctx):
print("Timer callback, context = " + ctx)
timer = threading.Timer(5, TimerCallback, args=["green"])
timer.start()
Vim9Script:
def TimerCallback(ctx: string, tid: number)
echo $"Timer callback, context = {ctx}, id = {tid}"
enddef
# Run a function after 5 seconds
var timer_id = timer_start(5 * 1000, function('TimerCallback', ["green"]))
Help: timer_start()
Python:
import threading
def TimerCallback():
print("Timer callback")
threading.Timer(5, TimerCallback).start()
# run a function every 5 seconds (approximately)
timer = threading.Timer(5, TimerCallback)
timer.start()
Vim9Script:
def TimerCallback(tid: number)
echo "Timer callback"
enddef
# run a function every 5 seconds periodically
var timer_id = timer_start(5 * 1000, function('TimerCallback'), {'repeat': -1})
Help: timer
Python:
import threading
def TimerCallback():
print("Timer callback")
timer = threading.Timer(1, TimerCallback)
timer.start()
timer.cancel()
Vim9Script:
def TimerCallback(tid: number)
echo "Timer callback"
enddef
# start a timer and then stop it
var timer_id = timer_start(1000, 'TimerCallback')
timer_stop(timer_id)
# to stop all the timers
timer_stopall()
Help: timer_start()
Python:
import time
time.sleep(5)
time.sleep(0.2)
Vim9Script:
# sleep for 5 seconds
sleep 5
# sleep for 200 milliseconds
sleep 200m
Help: :sleep
Python:
import json
v = ['foo', {'a' : 3}, True]
# encode data to JSON
str = json.dumps(v)
# decode data from JSON
x = json.loads(str)
Vim9Script:
var v = ['foo', {'a': 3}, true]
# encode data to JSON
var str = v->json_encode()
echo str
# decode data from JSON
var x = str->json_decode()
echo x
Help: json_encode(), json_decode(), js_encode(), js_decode()
Python:
import requests
# Get a web page from http://httpbin.org
def Display_Page():
r = requests.get('http://httpbin.org/')
if r.status_code == requests.codes.ok:
# display the received header and contents
print(r.headers)
print(r.text)
else:
print("Error: Failed to open URL")
Display_Page()
Vim9Script:
g:rcvd_data = []
# channel data callback function. Called for every received line.
def Chan_data_cb(ch: channel, msg: string)
add(g:rcvd_data, msg)
enddef
# channel close callback function.
def Chan_close_cb(ch: channel)
echo g:rcvd_data
enddef
def Display_Page()
var addr = "httpbin.org:80"
var ch_opt = {}
# data received is processed one line at a time
ch_opt.mode = 'nl'
ch_opt.waittime = -1
ch_opt.drop = "never"
ch_opt.callback = function('Chan_data_cb')
ch_opt.close_cb = function('Chan_close_cb')
# open the channel
var ch = ch_open(addr, ch_opt)
if ch_status(ch) != "open"
echomsg $"Failed to open channel, status = {ch_status(ch)}"
return
endif
# send a http request
ch_sendraw(ch, "GET / HTTP/1.0\nHost: httpbin.org\n\n")
enddef
Display_Page()
Help: job-channel-overview, ch_open(), ch_status(), ch_sendraw(), ch_close()
The 'bc' calculator utility is used in the below example for illustrative purposes only.
Python:
import subprocess
procObj = subprocess.Popen('bc',
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
shell=True)
lines, err = procObj.communicate("12 * 6\n")
print("Result = " + lines)
print("Exitcode = " + str(procObj.returncode))
Vim9Script:
var job = job_start('bc')
if job_status(job) != "run"
echo "Failed to start bc"
else
var output = ch_evalraw(job, "6 * 12\n")
echo $"Result = {output}"
job_stop(job, "kill")
var info = job_info(job)
echo $"Exitcode = {info.exitval}"
endif
Help: job, job_start(), job_status(), job_stop(), job_info()
Python:
import unittest
class TestDemoMethods(unittest.TestCase):
def test_abc(self):
self.assertEqual('FOO'.lower(), 'foo')
self.assertNotEqual(1, 2)
self.assertTrue('foo' == 'foo')
self.assertFalse('FOO' == 'foo')
self.assertIsNot('foo', 1)
self.assertRegex('ab123xy', '\d+')
self.assertNotRegex('abcd', '\d+')
with self.assertRaises(TypeError):
'a:b'.split(2)
unittest.main()
Vim9Script:
v:errors = []
assert_equal(tolower('FOO'), 'foo')
assert_notequal(1, 2)
assert_true('foo' == 'foo')
assert_false('FOO' == 'foo')
assert_fails('echo split("a:b", [])', 'E730:')
assert_match('\d\+', 'ab123xy')
assert_notmatch('\d\+', 'abcd')
if len(v:errors) == 0
echo "Test passed"
else
echo $"Test failed: {v:errors}"
endif