This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Vimscript Functions Cheatsheet

A quick reference guide for Vimscript built-in functions: list and dictionary manipulation, buffer inspection, cursor motion, string operations, and syntax introspection.

· Published

A reference guide for Vim's built-in script functions and data structures.

Data Structures

Dictionaries

let colors = {
  \ "apple": "red",
  \ "banana": "yellow"
}

echo colors["apple"]
echo get(colors, "apple")   " suppresses error if missing

call remove(colors, "apple")

" Inspection and checks
if has_key(dict, 'foo')
if empty(dict)
keys(dict)
len(dict)

max(dict)
min(dict)
count(dict, 'x')
string(dict)

map(dict, 'v:val . "!"')
extend(s:fruits, { "cherry": "red" })
for key in keys(mydict)
  echo key . ': ' . mydict[key]
endfor

Lists

let mylist = [1, "two", 3, "four"]

let first = mylist[0]
let last  = mylist[-1]

" Safe retrieval with default fallback
let second = get(mylist, 1)
let fallback = get(mylist, 10, "NONE")

Buffer & Cursor

Buffer Inspection

line('.')             " Current line number
col('.')              " Current column number
col('$')              " Last column number in current line

getline('.')          " Current line string content
getline(1)            " Line 1 string content
getline(1, 5)         " Lines 1 to 5 as list of strings
search('^$')          " Next blank line number
search('^$', 'n')     " Find next blank line without moving cursor

getcurpos()           " [bufnum, lnum, col, off, curswant]
getpos('.')           " [bufnum, lnum, col, off]

nextnonblank(1)       " Next non-blank line number after line 1
prevnonblank(10)

Marks

getpos("'a")          " Position of mark 'a'
setpos("'a", [0, 10, 5, 0])

getpos("'<")          " Position of visual selection start
getpos("'>")          " Position of visual selection end

Cursor Positioning

call cursor(line, col)
call cursor(line, col, off, curswant)

Filename Expansion

expand('<cword>')      " Word under cursor
expand('<cfile>')      " Filepath under cursor
expand('%')            " Current file name

" Modifiers:
" :p    Full path (/Users/name/project/file.txt)
" :h    Head / directory (/Users/name/project)
" :t    Tail / basename (file.txt)
" :r    Root without extension (file)
" :e    Extension (txt)
" Example: expand('%:p:h')

Files & Paths

fnameescape('string')
fnamemodify('main.c', ':p:h')
fnamemodify(fname, ':e')
filereadable(fname)
getfsize('file.txt')
getcwd()

globpath(&rtp, "plugin/commentary.vim")

Mathematics & Types

Math

fmod(9, 2)            " Modulo: 1.0
abs(-0.5)             " Absolute value
sqrt(9)               " Square root

trunc(1.84)           " 1.0
floor(1.84)           " 1.0
ceil(1.84)            " 2.0
float2nr(3.14)        " Convert float to integer: 3

Type Conversions

str2float('0.2')
str2nr('240')
str2nr('ff', 16)      " Base-16 hexadecimal parse

string(0.3)           " Convert to string

Type Checking

type(var) == type(0)            " Number
type(var) == type("")           " String
type(var) == type(function("tr")) " Funcref
type(var) == type([])           " List
type(var) == type({})           " Dictionary
type(var) == type(0.0)          " Float

Strings & Regular Expressions

String Manipulation

if a =~ '\s*'
let clean = substitute(str, '\s\+', ' ', 'g')

strpart("abcdef", 3, 2)         " == "de" (substring: offset, length)
strpart("abcdef", 3)            " == "def"
stridx("abcdef", "e")           " == 4 (index of char)
strridx("abcdef", "d")          " Reverse index search

matchstr('testing', 'test')     " == 'test' (matching text)
match('testing', 'test')        " == 0 (match start index)
matchend('testing', 'test')     " == 4 (match end index)
match('testing', '\ctest')      " Ignore case (\c)

split(str, '\zs')               " Split string into character array

strlen(str)                     " Byte length
strchars(str)                   " Character count (multibyte aware)
strdisplaywidth(str)            " Screen display columns

toupper(str)
tolower(str)
tr('foo', '_-', '  ')           " Character translation

Comparisons

if name ==# 'John'     " Case-sensitive equality
if name ==? 'John'     " Case-insensitive equality
if name == 'John'      " Dependent on 'ignorecase' option

if "hello" =~ '.*'     " Matches pattern
if "hello" !~ '.*'     " Does not match pattern

Commands & Execution

Running Commands

normal! ddahello
execute 'normal! ' . a:keys
wincmd J               " Window movement command

Shell Commands

let output = system('ls ' . shellescape(expand('%:h')))

Registers

getreg('*')            " Get clipboard contents
getregtype('*')        " Register type: 'v' (char), 'V' (line), '<ctrl-v>' (block)
setreg('*', 'new text')

Related topics