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

How do I set up filetype-specific documentation lookup for the K key in Vim?

Answer

:autocmd FileType python setlocal keywordprg=pydoc3

Explanation

The K command looks up the word under the cursor using the program defined by keywordprg (default: man). By using setlocal keywordprg inside a FileType autocommand, you can make K invoke language-appropriate documentation for each file type — pydoc3 for Python, ri for Ruby, or any custom command.

How it works

  • keywordprg defines the program called when you press K
  • setlocal applies the setting only to the current buffer (not globally)
  • autocmd FileType {ft} fires when Vim sets the filetype for a buffer
  • Commands starting with : are run as ex commands; others are run as shell programs with the word appended as an argument

Example

Add to your vimrc:

autocmd FileType python  setlocal keywordprg=pydoc3
autocmd FileType ruby    setlocal keywordprg=ri
autocmd FileType vim     setlocal keywordprg=:help

Now pressing K on a Python symbol opens pydoc3 <word>. For Vim files, it opens the built-in :help directly.

Tips

  • Group your autocommands in an augroup to prevent duplicates when re-sourcing your config:
augroup FiletypeKeywordPrg
  autocmd!
  autocmd FileType python setlocal keywordprg=pydoc3
  autocmd FileType vim    setlocal keywordprg=:help
augroup END
  • Point keywordprg at cht.sh, tldr, devdocs, or a custom wrapper script for any language
  • To include spaces in the command, escape them: keywordprg=rustup\ doc means rustup doc

Next

How do I refresh the diff highlighting in Vim when it becomes stale after editing?