How do I write a Vim plugin using the autoload directory structure?
Answer
autoload/myplugin.vim
Explanation
The autoload mechanism in Vim lets you write plugins whose functions are only loaded into memory when they are first called. This keeps Vim startup fast, even with many plugins installed.
How it works
Vim plugins using autoload follow a naming convention. A function defined in autoload/myplugin.vim must be named myplugin#functionname(). The # character maps to directory separators, so myplugin#utils#helper() would live in autoload/myplugin/utils.vim. When Vim encounters a call to an autoload function, it automatically sources the corresponding file.
A proper plugin typically has this structure: plugin/ contains the command definitions and mappings that are loaded at startup (kept minimal), while autoload/ contains the actual implementation. This separation means the heavy logic only loads when the user first invokes a command.
The plugin/ file uses command! to define ex-commands and nnoremap for key mappings, all pointing to autoload functions.
Example
Create a plugin called wordcount with this structure:
~/.vim/pack/plugins/start/wordcount/
plugin/wordcount.vim
autoload/wordcount.vim
plugin/wordcount.vim (loaded at startup):
if exists('g:loaded_wordcount')
finish
endif
let g:loaded_wordcount = 1
command! WordCount call wordcount#count()
nnoremap <leader>wc :call wordcount#count()<CR>
autoload/wordcount.vim (loaded on demand):
function! wordcount#count() abort
let l:count = wordcount().words
echo 'Word count: ' . l:count
endfunction
The abort keyword ensures the function stops on the first error. The g:loaded_wordcount guard prevents double-loading. With this pattern, you can create maintainable, fast-loading plugins that follow Vim conventions.