Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ahmedelgabri/d6f7c70554c0939f640a672b6b5899c5 to your computer and use it in GitHub Desktop.
Save ahmedelgabri/d6f7c70554c0939f640a672b6b5899c5 to your computer and use it in GitHub Desktop.
Vim script for Python Developers

Vim Script for Python Developers

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

For a similar guide for JavaScript developers, refer to Vim Script for the JavaScripter

This guide only describes the programming constructs that are present in both Python and Vim. The constructs that are unique to Vim (e.g. autocommands, key-mapping, abbreviations, user-commands, plugins, etc.) are not described in this guide.

Some of the features described in this guide are available are only in recent versions of Vim (8.1).


Variables

Creating a Variable

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

Deleting a Variable

Python:

del str

VimScript:

unlet str

Help: :unlet

Here Document

Assigning multi-line values to a variable.

Python:

i = """
    one
    two
    three
"""
i = i.strip().split()

VimScript:

let i =<< trim END
    one
    two
    three
END

Help: :let-heredoc

Print an expression

Python:

print("Hello World\n")
s = "vim"
print("Editor = %s" % (s))

VimScript:

echo "Hello World"
let s = "vim"
echo "Editor = " .. s

Help: :echo


Arithmetic Operators

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


Comparison Operators

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


Logical Operators

Python:

x and y
x or y
not x

VimScript:

x && y
x || y
!x

Help: expr2


Bitwise Operators

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()


String

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.

Raw string

Python:

s1 = r"one\ntwo\n"
s2 = "one\ntwo\n"

VimScript:

let s1 = 'one\ntwo\n'
let s2 = "one\ntwo\n"

Help: literal-string, string

Finding string length

Python:

n = len("Hello World")

VimScript:

let n = len("Hello World")
let n = strlen("Hello World")

Help: len(), strlen(), strwidth(), strdisplaywidth()

String Concatenation

Python:

str1 = "blue"
str2 = "sky"
s = str1 + str2

VimScript:

let str1 = "blue"
let str2 = "sky"
let s = str1 .. str2

Help: expr-..

Getting a substring

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]

VimScript:

let str = "HelloWorld"
let sub = str[2:4]
let sub = strpart(str, 2, 3)

Help: expr-[:], strpart()

Counting the occurrences of a substring

Python:

str = "Hello World"
c = str.count("l")

VimScript:

let str = "Hello World"
let c = str->count("l")

Help: count()

Checking whether a substring is present

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

Help: stridx(), strridx()

Checking whether a string starts with or ends with a substring

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-=~#

Merging strings in a List with a separator

Python:

s = ":".join(['a', 'b', 'c'])

VimScript:

let s = join(['a', 'b', 'c'], ':')

Help: join()

Changing the case of letters in a string

Python:

s = "Hello World"
l = s.lower()
l = s.upper()

VimScript:

let s = "Hello World"
let l = s->tolower()
let l = s->toupper()

Help: tolower(), toupper()

Replace a substring

Python:

s = "Hello World"
s2 = s.replace("Hello", "New")

VimScript:

let s = "Hello World"
let s2 = s->substitute("Hello", "New", 'g')

Help: substitute()

Split a string

Python:

s = "a:b:c"
s2 = s.split(":")

VimScript:

let s = "a:b:c"
let s2 = s->split(":")

Help: split(), join(),

Stripping leading and trailing whitespace from a string

Python:

s = "  vim  "
s2 = s.strip()

VimScript:

let s = "  vim  "
let s2 = s->trim()

Help: trim()

Checking whether a string contains specific type of characters

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

Data type conversion to string

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()


List

Creating a List

Python:

l = [1, 2, 3, 4]

VimScript:

let l = [1, 2, 3, 4]

Help: List

Accessing a List element

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

Changing the value of a List element

Python:

l = [1, 2, 3, 4]
l[3] = 5

VimScript:

let l = [1, 2, 3, 4]
let l[3] = 5

Help: list-modification

Adding an item to a List

Python:

l = []
l.append(5)
l += [6, 7]

VimScript:

let l = []
call add(l, 5)
let l += [5, 6]

Help: add()

Extending a List using a List

Python:

l = []
l.extend([2, 3])
l += [6, 7]

VimScript:

let l = []
call extend(l, [2, 3])
let l += [6, 7]

Help: extend()

Inserting an item in a List

Python:

l = [1, 3]
l.insert(1, 2)

VimScript:

let l = [1, 3]
call insert(l, 2, 1)

Help: insert()

Removing an item from a List

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]

Help: remove(), :unlet

Removing the last element from a List

Python:

l = [1, 2, 3]
v = l.pop()

VimScript:

let l = [1, 2, 3]
let v = l->remove(-1)

Help: remove()

Find the index of an item in a List

Python:

l = [1, 2, 3]
x = l.index(2)

VimScript:

let l = [1, 2, 3]
let x = l->index(2)

Help: index()

List slices

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.

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

List Concatenation

Python:

l = [1, 2] + [3 ,4]

VimScript:

let l = [1, 2] + [3 ,4]

Help: list-index

Adding multiple items to a List using repetition

Python:

l = ['vim'] * 4

VimScript:

let l = ['vim']->repeat(4)

Help: repeat()

Count the number of occurrences of an item in a List

Python:

l = [2, 4, 4, 5]
x = l.count(4)

VimScript:

let l = [2, 4, 4, 5]
let x = l->count(2)

Help: count()

Finding the List length

Python:

l = ['a', 'b', 'c']
n = len(l)

VimScript:

let l = ['a', 'b', 'c']
let n = l->len()

Help: len()

Sort a List

Python:

l = [3, 2, 1]
l.sort()

VimScript:

let l = [3, 2, 1]
call sort(l)

Help: sort()

Reverse a List

Python:

l = [1, 2, 3]
l.reverse()

VimScript:

let l = [1, 2, 3]
call reverse(l)

Help: reverse()

Copy a List

Python:

l = [3, 2, 1]
l2 = l.copy()

VimScript:

let l = [3, 2, 1]
let l2 = l->copy()

Help: copy()

Empty a List

Python:

l = [3, 2, 1]
l.clear()

VimScript:

let l = [3, 2, 1]
unlet l[:]

Help: :unlet

Comparing two Lists

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

Filter selected elements from a List

Python:

odd = filter(lambda x: x %2, range(10))

VimScript:

let odd = filter(range(10), {idx, v -> v % 2})

Help: filter()

Map List elements

Python:

num_str = map(lambda x: str(x), range(10))

VimScript:

let num_str = map(range(10), {idx, v -> string(v)})

Help: map()

Finding the max/min value in a List

Python:

n = max([3, 10, 8])
n = min([3, 10, 8])

VimScript:

let n = max([3, 10, 8])
let n = min([3, 10, 8])

Help: max(), min()

Converting a List to a string

Python:

s = str([3, 5, 7])

VimScript:

let s = string([3, 5, 7])

Help: string()


Dictionary

Creating a Dict

Python:

d = {'red' : 10, 'blue' : 20}
x = {}

VimScript:

let d = {'red' : 10, 'blue' : 20}
let x = {}

Help: Dict

Retrieving the value of a Dict item

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

Changing the value of a Dict item

Python:

d = {'red' : 10, 'blue' : 20}
d['red'] = 15

VimScript:

let d = {'red' : 10, 'blue' : 20}
let d.red = 15

Help: dict-modification

Accessing a Dict item

Python:

d = {'red' : 10, 'blue' : 20}
v = d.get('red')

VimScript:

let d = {'red' : 10, 'blue' : 20}
let v = get(d, 'red')

Help: get()

Adding a new Dict item

Python:

d = {'red' : 10, 'blue' : 20}
d['green'] = 30

VimScript:

let d = {'red' : 10, 'blue' : 20}
let d.green = 30

Help: dict-modification

Removing a Dict item

Python:

d = {'red' : 10, 'blue' : 20}
d.pop('red')

VimScript:

let d = {'red' : 10, 'blue' : 20}
call remove(d, 'red')

Help: remove(),

Clearing all the items from a Dict

Python:

d = {'red' : 10, 'blue' : 20}
d.clear()

VimScript:

let d = {'red' : 10, 'blue' : 20}
call filter(d, "0")

Help: dict-modification

Getting the size of a Dict

Python:

d = {'red' : 10, 'blue' : 20}
n = len(d)

VimScript:

let d = {'red' : 10, 'blue' : 20}
let n = d->len()

Help: len()

Checking Dict membership

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()

Iterating through all the keys in a Dict

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()

Iterating through all the values in a Dict

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()

Iterating through all the key, value pairs in a Dict

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()

Copying a Dict

Python:

d = {'red' : 10, 'blue' : 20}
new_d = d.copy()

VimScript:

let d = {'red' : 10, 'blue' : 20}
let new_d = d->copy()

Help: copy()

Converting a Dict to a string

Python:

d = str({'a' : 1, 'b' : 2})

VimScript:

let d = string({'a' : 1, 'b' : 2})

Help: string()

Comparing two Dicts

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


If statement

Basic If statement

Python:

if a > b:
    print("a is greater than b")

VimScript:

if a > b
    echo "a is greater than b"
endif

Help: :if

If-else statement

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

If-elseif statement

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

Checking multiple conditions

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

Nested If statements

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


For Loop

Python:

for i in range(5) :
    print(i)

VimScript:

for i in range(5)
    echo i
endfor

Help: :for

Breaking out of a For loop

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

Continuing a For loop

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

Nested For Loops

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


While Loop

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


Comments

Python:

# This is a python comment
i = 0    # First iteration

VimScript:

" This is a Vimscript comment
let i = 0    " First iteration

Help: :comment


Functions

The names of global functions in Vim must start with an uppercase letter. The examples in this document use the "function" and "endfunction" keywords for defining a function. But these can be abbreviated as "func" and "endfunc".

When a function encounters an error, it will continue to execute the rest of the function unless the "abort" argument is specified when defining the function. So it is recommended to specify the "abort" keyword at the end of the "function" line. To simplify the example code, this keyword is not used in this guide.

Defining a Function

Python:

def Min(x, y):
    return x if < y else y

print(Min(6, 3)

VimScript:

function Min(x, y) abort
    return a:x < a:y ? a:x : a:y
endfunction

echo Min(6, 3)

Help: user-functions

Calling a Function

Python:

def EchoValue(v):
    print(v)

EchoValue(100)

VimScript:

function EchoValue(v)
    echo a:v
endfunction

call EchoValue(100)

Help: :call

Function return value

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

Pass by reference

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

Variable number of arguments

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

Default value for arguments

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

Accessing global variables

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

Function reference

Python:

def Foo():
    print("Foo")
Bar = Foo
Bar()

VimScript:

function Foo()
    echo "Foo"
endfunction
let Bar = function("Foo")
call Bar()

Help: Funcref


Lambda Function

Python:

F = lambda x , y: x - y
print(F(5,2))

VimScript:

let F = {x, y -> x - y}
echo F(5,2)

Help: lambda


Partial Function

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


Closures

Closure with a lambda function

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

Closure with a function reference

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


Classes

Defining a class

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:

function s:new(x, y) dict
  let newpt = copy(self)
  let newpt.x = a:x
  let newpt.y = a:y
  return newpt
endfunction

function s:getX() dict
  return self.x
endfunction

function s:getY() dict
  return self.y
endfunction

function s:setX(x) dict
  let self.x = a:x
endfunction

function s:setY(y) dict
  let self.y = a:y
endfunction

function s:Print() dict
  echo "Pt = (" .. self.x .. ", " .. self.y .. ")"
endfunction

let Point = {}
let Point.new = function("s:new")
let Point.getX = function("s:getX")
let Point.getY = function("s:getY")
let Point.setX = function("s:setX")
let Point.setY = function("s:setY")
let Point.Print = function("s:Print")

let p = Point.new(10, 20)
call p.setX(40)
call p.setY(50)
call p.Print()

Help: Dictionary-function, numbered-function, :func-dict


Exception Handling

Basic exception handling

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

Catching all exceptions

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

Executing code after a try block (finally)

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

Raising a custom exception

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


Formatted Output

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()


Line Continuation

Python:

a = 1 + 2 + 3 + \
      4 + 5 + 6

VimScript:

let a = 1 + 2 + 3 +
      \ 4 + 5 + 6

Help: line-continuation


File Operations

Reading all the lines in a file

Python:

with open('myfile.txt', 'r') as f:
    lines = f.readlines()

VimScript:

let lines = readfile("myfile.txt")

Help: readfile()

Writing lines to a file

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()

Checking whether a file exists

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()

Deleting a file

Python:

import os
os.remove('myfile.txt')

VimScript:

call delete('myfile.txt')

Help: remove()

Renaming a file

Python:

import os
os.rename('myfile.txt', 'somefile.txt)

VimScript:

call rename('myfile.txt', 'somefile.txt')

Help: rename()

Getting the size of a file

Python:

import os
sz = os.path.getsize('move.py')

VimScript:

let sz = getfsize('move.py')

Help: getfsize()


Directory Operations

Creating a directory

Python:

os.mkdir('somedir')

VimScript:

call mkdir('somedir')

Help: mkdir()

Changing to a directory

Python:

os.chdir('someotherdir')

VimScript:

call chdir('someotherdir')

Help: chdir()

Getting the current directory

Python:

dir = os.getcwd()

VimScript:

let dir = getcwd()

Help: getcwd()

Deleting a directory

Python:

os.rmdir('somedir')

VimScript:

call delete('somedir', 'd')

Help: delete()


Random numbers

Generating a random number

Python:

import random
r = random.randint(0, 2147483647)

VimScript:

let r = rand()

Help: rand()

Generating a random number from a seed

Python:

import random
random.seed()
r = random.randint(0, 2147483647)
print(r)

VimScript:

let seed = srand()
let r = rand(seed)

Help: srand()


Mathematical functions

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()


Date/Time functions

Get current date and time

Python:

from datetime import date
d = date.today()
print d.strftime("%c")

VimScript:

echo strftime("%c")

Help: strftime()

Parse a date/time string

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()

Getting the time in seconds since epoch

Python:

import time
print int(time.time())

VimScript:

echo localtime()

Help: localtime()


External commands

Getting the output of an external command as a string

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

Splitting the output of an external command into lines

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()

Sending input to an external command and getting the output

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()


Environment Variables

Getting the value of an environment variable

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()

Setting an environment variable

Python:

import os
os.environ['FOO'] = "BAR"

VimScript:

call setenv('FOO', 'BAR')

let $FOO = 'BAR'

Help: setenv(), :let-environment

Removing an environment variable

Python:

import os
del os.environ['FOO']

VimScript:

call setenv('FOO', v:null)

unlet $FOO

Help: setenv(), :unlet-environment

Getting all the environment variables

Python:

import os
print(os.environ)

VimScript:

echo environ()

Help: environ()


Command-line Arguments

Displaying the command-line arguments

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


Regular Expressions

Finding whether a pattern matches a string

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) == None:
    print("Test passed")

VimScript:

let s = 'Test failed with error E123:'
if s =~# 'E\d\+:'
    echo "Error code found"
endif

let s = 'Test successful'
if s !~# 'E\d\+:'
    echo "Test passed"
endif

Help: expr-=~, expr-!~

Finding the beginning or ending index of a pattern in a string

Python:

import re
m = re.search(r'\d+', "Abc 123 Def")
if m != None:
    idx = m.start()
    end_idx = m.end()

VimScript:

let idx = match("Abc 123 Def", '\d\+')
let end_idx = matchend("Abc 123 Def", '\d\+')

let l = matchstrpos("Abc 123 Def", '\d\+')
echo "start:" l[1] "end:" l[2]

Help: match(), matchend(), matchstrpos()

Getting matching substring using a pattern

Python:

import re
m = re.search(r'\d+', "Abc 123 Def")
if m != None:
    s = m.group(0)
    print s

VimScript:

let s = matchstr("Abc 123 Def", '\d\+')

Help: matchstr()

Getting multiple matches using a pattern

Python:

import re
m = re.match(r'(\w+) (\w+) (\w+)', "foo bar baz")
if m != None:
    print("Full match: " + m.group(0))
    print("1: " + m.group(1) + " 2: " + m.group(2) + " 3: " + m.group(3))

VimScript:

let 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()

Substituting text using a pattern

Python:

import re
s = re.sub(r'bar', r'baz', "foo bar")
print(s)

VimScript:

let s = substitute("foo bar", 'bar', 'baz', '')
echo s

Help: substitute()

Using a function to get the replacement string

Python:

import re
def Dashrepl(m):
  if m.group(0) == '-':
    return ' '
  else:
    return '-'
s = re.sub('-{1,2}', Dashrepl, 'pro----gram-files')
print(s)

VimScript:

function Dashrepl(m)
  if a:m[0] == '-'
    return ' '
  else
    return '-'
  endif
endfunction
let s = substitute("pro----gram-files", '-\{1,2}', function('Dashrepl'), 'g')
echo s

Help: substitute()

Regular expression comparison

Note that the below table shows 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

Binary Data

Storing binary data in a variable

Python:

data = bytearray(b'\x12\xF6\xAB\xFF\x49\xC0\x88\x3A\xE2\xC1\x42\xAA')
print(data)
print(data[0:4])

VimScript:

let data = 0z12F6ABFF.49C0883A.E2C142AA
echo data
echo data[0:3]

Help: blob

Manipulating binary data stored in a variable

Python:

data = bytearray(b'')
data.append(0xC2)
data += b'\xB3\xF7\xA5'
del data[2]
print(data)

VimScript:

let data = 0z
let data[0] = 0xC2
let data += 0zB3F7A5
call remove(data, 2)
echo data

Help: blob-index, blob-modification

Reading and writing binary data from a file

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)

VimScript:

let data = readfile('datafile.bin', 'B')
call writefile(data, 'data2.bin')

Help: readfile(), writefile()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment