vimtricks.wiki Concise Vim tricks, one at a time.

How do I define a reusable function in Vimscript?

Answer

function! Name() ... endfunction

Explanation

:function defines a reusable Vimscript function that you can call from mappings, autocommands, commands, and other functions. The ! (bang) after function allows redefining the function when your vimrc is re-sourced without getting an error.

Syntax

function! {Name}({args})
  " function body
  return {value}
endfunction

Rules:

  • Function names must start with an uppercase letter (or use a namespace like myplugin#Name)
  • Use ! to allow overwriting an existing definition
  • return is optional; without it the function returns 0

Examples

A simple function to trim trailing whitespace:

function! TrimWhitespace()
  let l:save = winsaveview()
  %s/\s\+$//e
  call winrestview(l:save)
endfunction

" Call it with:
call TrimWhitespace()
" Or map it:
nnoremap <leader>tw :call TrimWhitespace()<CR>

A function with arguments and return value:

function! Greet(name)
  return 'Hello, ' . a:name . '!'
endfunction

echo Greet('Vim')    " Prints: Hello, Vim!

Variable scopes

Prefix Scope
l: Local to the function
a: Function argument
g: Global
s: Script-local (private to the file)

Tips

  • Use l: prefix for local variables to avoid polluting global scope
  • s: scope is ideal for plugin-private helpers: function! s:MyHelper()
  • :function Name (no parens) displays a function's definition
  • :delfunction Name removes a function
  • In modern Vimscript (Vim 9), use the cleaner def/enddef syntax instead

Next

How do I run a search and replace only within a visually selected region?