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

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

  1. Create ~/.vim/plugin/myplugin.vim
  2. Add Vimscript: commands, functions, mappings
  3. 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

Next

How do you yank a single word into a named register?