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
keywordprgdefines the program called when you pressKsetlocalapplies 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
augroupto 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
keywordprgatcht.sh,tldr,devdocs, or a custom wrapper script for any language - To include spaces in the command, escape them:
keywordprg=rustup\ docmeansrustup doc