Runtimepath, packages and autocommands

Vim · Expert · 15 min

Knowing the load order lets you add plugins and filetype settings without mystery or slow startup.

Vim finds scripts through the runtimepath option, a list of directories (~/.vim, $VIMRUNTIME, plugin dirs...). In each, sub-directories have fixed roles:

  • plugin/ scripts load at every startup.
  • ftplugin/<filetype>.vim loads when a buffer gets that filetype; indent/ and syntax/ similarly.
  • autoload/ functions are loaded lazily the first time they are called (foo#bar() loads autoload/foo.vim).
  • after/ directories run last, to override defaults.

Packages are the built-in plugin manager: put a plugin in ~/.vim/pack/<any>/start/<name>/ to load it at startup, or in opt/ and load it on demand with :packadd name. External managers (vim-plug, minpac) only automate this.

Autocommands run commands on events: autocmd BufWritePre *.py %s/\s\+$//e strips trailing whitespace before saving. Always put them in an augroup that starts with autocmd!, otherwise sourcing your vimrc twice registers them twice:

For per-language settings prefer ~/.vim/after/ftplugin/python.vim with setlocal over autocmd FileType; it keeps the vimrc small. To find what is slow, start with vim --startuptime log.txt. :scriptnames lists every script loaded so far, in order.

Example

" ~/.vimrc
augroup my_au
  autocmd!                                  " clear on re-source
  autocmd BufWritePre *.py,*.js %s/\s\+$//e  " strip trailing spaces
  autocmd FileType gitcommit setlocal spell textwidth=72
augroup END
packadd! matchit           " load an optional bundled package

" ~/.vim/after/ftplugin/python.vim
setlocal expandtab shiftwidth=4 colorcolumn=89

" plugin layout:  ~/.vim/pack/plugins/start/vim-surround/
" shell:          vim --startuptime /tmp/startup.log

Remember

  • runtimepath dirs: plugin/, ftplugin/, autoload/, after/
  • pack//start loads always, pack//opt with :packadd
  • Wrap autocmds in augroup + autocmd! to avoid duplicates

Watch out for

  • Using set instead of setlocal in ftplugin files, leaking settings into other buffers.

Check yourself

  1. Why start an augroup with `autocmd!`?
  2. A plugin placed in `~/.vim/pack/x/opt/foo/` is loaded when?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vimhelp.org/repeat.txt.html#packages