How do I define Vimscript functions that load automatically on demand without slowing down startup?
Answer
function! {name}#{funcname}() in autoload/{name}.vim
Explanation
Vim's autoload mechanism lets you place functions in autoload/*.vim files using a filename#funcname naming convention. The file is loaded only when a function from it is first called, keeping startup fast no matter how much helper code you have.
How it works
Create a file at ~/.vim/autoload/myutils.vim (or ~/.config/nvim/autoload/myutils.vim for Neovim):
function! myutils#TrimWhitespace() abort
let l:saved = @/
%s/\s\+$//e
let @/ = l:saved
endfunction
The prefix before # must exactly match the filename (without .vim). Call it from anywhere:
:call myutils#TrimWhitespace()
Vim automatically finds and sources autoload/myutils.vim on the first call.
Example
Instead of defining a large helper function at the top of your vimrc (loaded every time), move it to autoload/:
~/.vim/
autoload/
myutils.vim ← loaded only when myutils#* is first called
vimrc ← just has mappings and settings
Tips
- Function names must follow the pattern
{filename}#FuncNameexactly — mismatches cause E117 - Nested paths work:
autoload/my/lib.vimuses prefixmy#lib#FuncName - This is how almost all Vim plugins expose their public API
- Combine with
noremap <leader>t :call myutils#TrimWhitespace()<CR>to call autoloaded functions from mappings without loading them at startup