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 returnis optional; without it the function returns0
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 Nameremoves a function- In modern Vimscript (Vim 9), use the cleaner
def/enddefsyntax instead