A guide to Vim Script development for Python developers. Sample code for the various expressions, statements, functions and programming constructs is shown in both Python and Vim Script. This is not intended to be a tutorial for developing Vim scripts. It is assumed that the reader is familiar with programming in Python.
For an introduction to Vim Script development, refer to usr_41.txt, eval.txt and Learn Vimscript the Hard Way
Python:
i = 10
pi = 3.1415
str = "Hello"
a, b, s = 10, 20, "sky"
VimScript:
let i = 10
let pi = 3.1415
let str = "Hello"
let [a, b, s] = [10, 20, "sky"]
Help: variables
Python:
del str
VimScript:
unlet str
Help: :unlet
Python:
print("Hello World\n")
s = "vim"
print("Editor = %s" % (s))
VimScript:
echo "Hello World"
let s = "vim"
echo "Editor = " .. s
Help: :echo
Python:
a = 10 + 20
a = 30 - 10
a = 3 * 5
a = 22 / 7
a += 1
a -= 2
a *= 4
a /= 2
a = 10 % 3
a = 2 ** 3
a = 10 // 3
VimScript:
let a = 10 + 20
let a = 30 - 10
let a = 3 * 5
let a = 22 / 7
let a += 1
let a -= 2
let a *= 4
let a /= 2
let a = 10 % 3
let a = float2nr(pow(2, 3))
let a = floor(10 / 3.0)
Help: expr5
Python:
a > b
a < b
a == b
a != b
a >= b
a <= b
VimScript:
a > b
a < b
a == b
a != b
a >= b
a <= b
Help: expr4
Python:
x and y
x or y
not x
VimScript:
x && y
x || y
!x
Help: expr2
Python:
c = a & b
c = a | b
c = ~a
c = x ^ y
VimScript:
let c = and(a, b)
let c = or(a, b)
let c = invert(a)
let c = xor(a, b)
Help: and(), or(), invert(), xor()
Python:
n = len("Hello World")
VimScript:
let n = len("Hello World")
let n = strlen("Hello World")
Help: len(), strlen(), strwidth(), strdisplaywidth()
Python:
str1 = "blue"
str2 = "sky"
s = str1 + str2
VimScript:
let str1 = "blue"
let str2 = "sky"
let s = str1 .. str2
Help: expr-..
Python:
str = "Hello World"
sub = str[2:5]
VimScript:
let str = "Hello World"
let sub = str[2:5]
let sub = strpart(str, 2, 4)
Python:
str = "Hello World"
c = str.count("l")
VimScript:
let str = "Hello World"
let c = str->count("l")
Help: count()
Python:
str = "running"
idx = str.find("nn")
idx = str.rfind("ing")
VimScript:
let str = "running"
let idx = str->stridx("nn")
let idx = str->strridx("ing")
endif
Python:
str = "running"
if str.startswith("run"):
print("starts with run")
if str.endswith("ing"):
print("ends with ing")
VimScript:
let str = "running"
if str =~# "^ing"
echo "starts with ing"
if str =~# "ing$"
echo "ends with ing"
endif
Help: expr-=~#
Python:
s = ":".join(['a', 'b', 'c'])
VimScript:
let s = join(['a', 'b', 'c'], ':')
Help: join()
Python:
s = "Hello World"
l = s.lower()
l = s.upper()
VimScript:
let s = "Hello World"
let l = s->tolower()
let l = s->toupper()
Python:
s = "Hello World"
s2 = s.replace("Hello", "New")
VimScript:
let s = "Hello World"
let s2 = s->substitute("Hello", "New", 'g')
Help: substitute()
Python:
s = "a:b:c"
s2 = s.split(":")
VimScript:
let s = "a:b:c"
let s2 = s->split(":")
Help: split()
Python:
s = " vim "
s2 = s.strip()
VimScript:
let s = " vim "
let s2 = s->trim()
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")
VimScript:
let 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})
VimScript:
let s = string(268)
let s = string(22.7)
let s = string([1, 2, 3])
let s = string({'a' : 1, 'b' : 2})
Help: string()
Python:
l = [1, 2, 3, 4]
VimScript:
let l = [1, 2, 3, 4]
Help: List
Python:
l = [1, 2, 3, 4]
v1 = l[2]
v2 = l[-2]
VimScript:
let l = [1, 2, 3, 4]
let v1 = l[2]
let v2 = l[-2]
Help: list-index
Python:
l = [1, 2, 3, 4]
l[3] = 5
VimScript:
let l = [1, 2, 3, 4]
let l[3] = 5
Help: list-modification
Python:
l = []
l.append(5)
l += [6, 7]
VimScript:
let l = []
call add(l, 5)
let l += [5, 6]
Help: add()
Python:
l = []
l.extend([2, 3])
l += [6, 7]
VimScript:
let l = []
call extend(l, [2, 3])
let l += [6, 7]
Help: extend()
Python:
l = [1, 3]
l.insert(1, 2)
VimScript:
let l = [1, 3]
call insert(l, 2, 1)
Help: insert()
Python:
l = [4, 5, 6]
l.remove(5)
del l[0]
VimScript:
let l = [4, 5, 6]
call remove(l, index(l, 5))
unlet l[0]
Python:
l = [1, 2, 3]
v = l.pop()
VimScript:
let l = [1, 2, 3]
let v = l->remove(-1)
Help: remove()
Python:
l = [1, 2, 3]
x = l.index(2)
VimScript:
let l = [1, 2, 3]
let x = l->index(2)
Help: index()
Python:
l = [1, 2, 3, 4]
m = l[1:3]
m = l[2:]
VimScript:
let l = [1, 2, 3, 4]
let m = l[1:3]
let m = l[2:]
Help: sublist
Python:
l = [1, 2] + [3 ,4]
VimScript:
let l = [1, 2] + [3 ,4]
Help: list-index
Python:
l = ['vim'] * 4
VimScript:
let l = ['vim']->repeat(4)
Help: repeat()
Python:
l = [2, 4, 4, 5]
x = l.count(4)
VimScript:
let l = [2, 4, 4, 5]
let x = l->count(2)
Help: count()
Python:
l = ['a', 'b', 'c']
n = len(l)
VimScript:
let l = ['a', 'b', 'c']
let n = l->len()
Help: len()
Python:
l = [3, 2, 1]
l.sort()
VimScript:
let l = [3, 2, 1]
call sort(l)
Help: sort()
Python:
l = [1, 2, 3]
l.reverse()
VimScript:
let l = [1, 2, 3]
call reverse(l)
Help: reverse()
Python:
l = [3, 2, 1]
l2 = l.copy()
VimScript:
let l = [3, 2, 1]
let l2 = l->copy()
Help: copy()
Python:
l = [3, 2, 1]
l.clear()
VimScript:
let l = [3, 2, 1]
unlet l[:]
Help: :unlet
Python:
l1 = [1, 2]
l2 = [1, 2]
if l1 == l2:
print("Lists are equal")
VimScript:
let l1 = [1, 2]
let l2 = [1, 2]
if l1 == l2
echo "Lists are equal"
endif
Help: list-identity
Python:
odd = filter(lambda x: x %2, range(10))
VimScript:
let odd = filter(range(10), {idx, v -> v % 2})
Help: filter()
Python:
num_str = map(lambda x: str(x), range(10))
VimScript:
let num_str = map(range(10), {idx, v -> string(v)})
Help: map()
Python:
n = max([3, 10, 8])
n = min([3, 10, 8])
VimScript:
let n = max([3, 10, 8])
let n = min([3, 10, 8])
Python:
s = str([3, 5, 7])
VimScript:
let s = string([3, 5, 7])
Help: string()
Python:
d = {'red' : 10, 'blue' : 20}
x = {}
VimScript:
let d = {'red' : 10, 'blue' : 20}
let x = {}
Help: Dict
Python:
d = {'red' : 10, 'blue' : 20}
x = d['red']
VimScript:
let d = {'red' : 10, 'blue' : 20}
let x = d['red']
let x = d.red
Help: dict
Python:
d = {'red' : 10, 'blue' : 20}
d['red'] = 15
VimScript:
let d = {'red' : 10, 'blue' : 20}
let d.red = 15
Help: dict-modification
Python:
d = {'red' : 10, 'blue' : 20}
v = d.get('red')
VimScript:
let d = {'red' : 10, 'blue' : 20}
let v = get(d, 'red')
Help: get()
Python:
d = {'red' : 10, 'blue' : 20}
d['green'] = 30
VimScript:
let d = {'red' : 10, 'blue' : 20}
let d.green = 30
Help: dict-modification
Python:
d = {'red' : 10, 'blue' : 20}
d.pop('red')
VimScript:
let d = {'red' : 10, 'blue' : 20}
call remove(d, 'red')
Help: remove(),
Python:
d = {'red' : 10, 'blue' : 20}
d.clear()
VimScript:
let d = {'red' : 10, 'blue' : 20}
let d = {}
Help: dict-modification
Python:
d = {'red' : 10, 'blue' : 20}
n = len(d)
VimScript:
let d = {'red' : 10, 'blue' : 20}
let n = d->len()
Help: len()
Python:
d = {'red' : 10, 'blue' : 20}
if 'red' in d:
print("found red key")
VimScript:
let 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])
VimScript:
let d = {'red' : 10, 'blue' : 20}
for k in keys(d)
echo k
endfor
for k in d->keys()
echo d[k]
endfor
Help: keys()
Python:
d = {'red' : 10, 'blue' : 20}
for v in d.values():
print(v)
VimScript:
let 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)
VimScript:
let 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()
VimScript:
let d = {'red' : 10, 'blue' : 20}
let new_d = d->copy()
Help: copy()
Python:
d = str({'a' : 1, 'b' : 2})
VimScript:
let d = string({'a' : 1, 'b' : 2})
Help: string()
Python:
d1 = {'a' : 10, 'b' : 20}
d2 = {'a' : 10, 'b' : 20}
if d1 == d2:
print("Dicts are equal")
VimScript:
let d1 = {'a' : 10, 'b' : 20}
let d2 = {'a' : 10, 'b' : 20}
if d1 == d2
echo "Dicts are equal"
endif
Help: dict-identity
Python:
if a > b:
print("a is greater than b")
VimScript:
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")
VimScript:
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")
VimScript:
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"
VimScript:
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")
VimScript:
if status == v:true
if a >= 1
echo "Nested if"
endif
endif
Help: :if
Python:
for i in range(5) :
print(i)
VimScript:
for i in range(5)
echo i
endfor
Help: :for
Python:
for i in ['a', 'b', 'c']:
if i == 'b':
break
print(i)
VimScript:
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)
VimScript:
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))
VimScript:
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
VimScript:
let i = 1
while i <= 5
echo i
let i += 1
endwhile
Help: :while
Python:
# This is a python comment
i = 0 # First iteration
VimScript:
" This is a Vimscript comment
let i = 0 " First iteration
Help: :comment
Python:
def Min(x, y):
return x if < y else y
print(Min(6, 3)
VimScript:
function Min(x, y)
return a:x < a:y ? a:x : a:y
endfunction
echo Min(6, 3)
Help: user-functions
Python:
def EchoValue(v):
print(v)
EchoValue(100)
VimScript:
function EchoValue(v)
echo a:v
endfunction
call EchoValue(100)
Help: :call
Python:
def Sum(a, b):
return a + b
s = Sum(10, 20)
VimScript:
function Sum(a, b)
return a:a + a:b
endfunction
let s = Sum(10, 20)
Help: :return
Python:
def AddValues(l):
l.extend([1, 2, 3, 4])
VimScript:
function AddValues(l)
call extend(a:l, [1, 2, 3, 4])
endfunction
Help: function-argument
Python:
def Sum(v1, *args):
sum = v1
for i in *args:
sum += i
return sum
VimScript:
function Sum(v1, ...)
let sum = a:v1
for i in a:000
let sum +=i
endfor
return sum
endfunction
let s1 = Sum(10, 20, 30, 40)
let s1 = Sum(10)
Help: a:000
Python:
def Powerof(base, exp = 2):
return base ** exp
VimScript:
function PowerOf(base, exp = 2)
return float2nr(pow(a:base, a:exp))
endfunction
let val = PowerOf(4)
let val = PowerOf(4, 3)
Help: optional-function-argument
Python:
counter = 1
def Incr():
global counter
counter += 1
VimScript:
let counter = 1
function Incr()
let g:counter += 1
endfunction
cal Incr()
Help: global-variable
Python:
def Foo():
print("Foo")
Bar = Foo
Bar()
VimScript:
function Foo()
echo "Foo"
endfunction
let Bar = function("Foo")
call Bar()
Help: Funcref
Python:
F = lambda x , y: x - y
print(F(5,2))
VimScript:
let 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")
VimScript:
function Mylog(subsys, msg)
echo printf("%s: %s", a:subsys, a:msg)
endfunction
let ErrLog = function('Mylog', ['ERR'])
call 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))
VimScript:
function Foo(arg)
let i = 3
return {x -> x + i - a:arg}
endfunction
let 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))
VimScript:
function Foo(base)
function Bar(val) closure
return a:base + a:val
endfunction
return funcref('Bar')
endfunction
let F = Foo(10)
echo F(2)
let 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("Pt = (" + str(self.x) + ", " + str(self.y) + ")")
pt = Point(10, 20)
pt.setX(40)
pt.setY(50)
pt.Print()
VimScript:
let Point = {}
function Point.New(x, y)
let newpt = copy(self)
let newpt.x = a:x
let newpt.y = a:y
return newpt
endfunction
function Point.getX()
return self.x
endfunction
function Point.getY()
return self.y
endfunction
function Point.setX(x)
let self.x = a:x
endfunction
function Point.setY(y)
let self.y = a:y
endfunction
function Point.Print()
echo "Pt = (" .. self.x .. ", " .. self.y .. ")"
endfunction
let p = Point.New(10, 20)
call p.setX(40)
call p.setY(50)
call p.Print()
Help: Dictionary-function, numbered-function, :func-dict
Python:
try:
f = open('buf.java', 'r')
lines = f.readlines()
f.close()
except IOError:
print("Failed to open file")
VimScript:
try
let 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))
VimScript:
try
let 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")
VimScript:
try
let 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")
VimScript:
try
throw 'MyException'
catch /MyException/
echo "Caught MyException"
finally
echo "Finally block"
endtry
Help: throw-catch
Python:
name = "John"
id = 1001
print("Name: %s, ID: %d" % (name, id))
VimScript:
let name = "John"
let id = 1001
echo printf("Name: %s, ID: %d", name, id)
Help: printf()
Python:
a = 1 + 2 + 3 + \
4 + 5 + 6
VimScript:
let a = 1 + 2 + 3 +
\ 4 + 5 + 6
Help: line-continuation
Python:
with open('myfile.txt', 'r') as f:
lines = f.readlines()
VimScript:
let lines = readfile("myfile.txt")
Help: readfile()
Python:
lines = ['line1', 'line2']
with open('myfile.txt', 'w') as fh:
fh.writelines("\n".join(lines))
VimScript:
call writefile(['line1', 'line2'], 'myfile.txt')
Help: writefile()
Python:
import os.path
if os.path.isfile('myfile.txt'):
print("File exists")
VimScript:
if filereadable('myfile.txt')
echo "File is readable"
endif
Help: filereadable()
Python:
import os
os.remove('myfile.txt')
VimScript:
call delete('myfile.txt')
Help: remove()
Python:
import os
os.rename('myfile.txt', 'somefile.txt)
VimScript:
call rename('myfile.txt', 'somefile.txt')
Help: rename()
Python:
import os
sz = os.path.getsize('move.py')
VimScript:
let sz = getfsize('move.py')
Help: getfsize()
Python:
os.mkdir('somedir')
VimScript:
call mkdir('somedir')
Help: mkdir()
Python:
os.chdir('someotherdir')
VimScript:
call chdir('someotherdir')
Help: chdir()
Python:
dir = os.getcwd()
VimScript:
let dir = getcwd()
Help: getcwd()
Python:
os.rmdir('somedir')
VimScript:
call delete('somedir', 'd')
Help: delete()
Python:
import random
r = random.randint(0, 2147483647)
VimScript:
let r = rand()
Help: rand()
Python:
import random
random.seed()
r = random.randint(0, 2147483647)
print(r)
VimScript:
let seed = srand()
let r = rand(seed)
Help: srand()
Python:
import math
f = math.ceil(1.2)
f = math.fabs(-10)
f = math.floor(1.4)
f = math.fmod(4, 3)
f = math.trunc(1.3)
f = math.exp(2)
f = math.log(12)
f = math.log10(100)
f = math.pow(2, 3)
f = math.sqrt(9)
f = math.cos(4)
f = math.sin(4)
f = math.tan(4)
f = math.cosh(4)
f = math.sinh(4)
f = math.tanh(4)
f = math.acos(0.8)
f = math.asin(0.8)
f = math.atan(0.8)
f = math.atan2(0.4, 0.8)
VimScript:
let f = ceil(1.2)
let f = abs(-10)
let f = floor(1.4)
let f = fmod(4, 3)
let f = trunc(1.3)
let f = exp(2)
let f = log(12)
let f = log10(100)
let f = pow(2, 3)
let f = sqrt(9)
let f = cos(4)
let f = sin(4)
let f = tan(4)
let f = cosh(4)
let f = sinh(4)
let f = tanh(4)
let f = acos(0.8)
let f = asin(0.8)
let f = atan(0.8)
let f = atan2(0.4, 0.8)
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 date
d = date.today()
print d.strftime("%c")
VimScript:
echo strftime("%c")
Help: strftime()
Python:
from datetime import datetime
print(datetime.strptime("1997 Apr 27 11:49:23", "%Y %b %d %X"))
VimScript:
echo strptime("%Y %b %d %X", "1997 Apr 27 11:49:23")
Help: strptime()
Python:
import time
print int(time.time())
VimScript:
echo localtime()
Help: localtime()
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))
VimScript:
let 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.split("\n"))))
VimScript:
let 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))
VimScript:
let lines = system('wc', "one\ntwo\n")
echo lines
echo "Error = " .. v:shell_error
Help: system()
Python:
import os
h = os.environ.get('HOME', '')
if h == '':
print("HOME is not set")
else:
print("HOME = " + h)
VimScript:
let 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"
VimScript:
call setenv('FOO', 'BAR')
let $FOO = 'BAR'
Help: setenv(), :let-environment
Python:
import os
del os.environ['FOO']
VimScript:
call setenv('FOO', v:null)
unlet $FOO
Help: setenv(), :unlet-environment
Python:
import os
print(os.environ)
VimScript:
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)
VimScript:
echo "Number of arguments = " .. len(v:argv)
echo "Arguments = " .. string(v:argv)
for arg in v:argv
echo arg
endfor
Help: v:argv