How do I write a simple Vim plugin?
Answer
Create plugin/myplugin.vim
Explanation
A basic Vim plugin is just a .vim file in the plugin/ directory. It can define commands, mappings, and functions that are loaded automatically.
How it works
- Create
~/.vim/plugin/myplugin.vim - Add Vimscript: commands, functions, mappings
- The file is automatically sourced when Vim starts
Example
" ~/.vim/plugin/myplugin.vim
if exists('g:loaded_myplugin')
finish
endif
let g:loaded_myplugin = 1
function! s:StripTrailingWhitespace()
let save_cursor = getpos('.')
%s/\s\+$//e
call setpos('.', save_cursor)
endfunction
command! StripWhitespace call s:StripTrailingWhitespace()
Tips
- The guard (
g:loaded_myplugin) prevents double-loading s:prefix makes functions script-local- Put autoload functions in
~/.vim/autoload/for lazy loading ftplugin/holds filetype-specific plugins- Distribute via GitHub for easy installation with plugin managers