cmcginty's answer uses Vim's :Man
filetype plugin, but that's only appropriate when the K command would run man
(which is keyed on the keywordprg
setting). Here is a solution that only offers that functionality when K would invoke man
:
function! ManVim(...)
if (&keywordprg == "man")
runtime ftplugin/man.vim
setlocal keywordprg=:Man
endif
normal! K
endfunction
noremap K :call ManVim()<CR>
You can optionally surround this with if has("gui_running")
and endif
but I find this works great on the console too.
Note that this checks whether Vim would run man
from within the function call in order to prevent intercepting keywordprg
when it would run a different command, say after loading a python script. The next time you hit K, keywordprg
will not match.
Caveat: Like the original K command, this solution gets stuck on hyphens and dots, such as for man pages like ssh-add
and resolv.conf
. This is because the sh
filetype doesn't consider hyphens or dots to be keyword characters.
Here is a solution that temporarily redefines keyword characters to include hyphen and dot:
function! ManVim(...)
if (&keywordprg != "man") " not invoking man, operate as per normal
normal! K
else
if ! exists(":Man") " load man.vim if it's not already present
runtime ftplugin/man.vim
endif
" man pages allow dashes and dots, so we temporarily add those kwd chars
let old_iskeyword = &iskeyword
setlocal iskeyword+=\.,-
if ! exists(":Man") " fallback in case man.vim failed to load
normal! K
endif
let l:man_page = expand("<cword>")
let &l:iskeyword = old_iskeyword
if exists(":Man") " for whatever reason, the exe has to be last
exe "Man" v:count l:man_page
endif
endif
endfunction
noremap K :call ManVim()<CR>
This is a bit more complicated than I'd like because :Man
changes the current buffer and therefore needs to be run last, but the fallback for when man.vim is missing must be earlier since it has to be run while iskeyword
has the extra characters.