2

When writing shell scripts, it is frequently necessary to call external commands in $PATH. Some of these have long names (e.g. system-config-printer-applet or xfwm4-workspace-settings), and it would be useful to be able to complete them while in insert mode. Shells like bash and zsh have this capability built in.

However, this isn't built into any of Vim's ins-completion defaults.

http://vimdoc.sourceforge.net/htmldoc/insert.html#ins-completion

The feature was requested in 2004, but does not seem to have been implemented since then.

http://comments.gmane.org/gmane.editors.vim/26022

Is there a setting or plugin to enable this?

4

This recipe enables dictionary completion for shell scripts via regular keyword completion and omni completion:

  1. Add the following lines to ~/.vimrc to enable dictionary completion in shell scripts:

    augroup shellscripts
        " prevent duplicates if .vimrc is sourced twice.
        autocmd!
    
        " tell Vim where the dictionary is
        autocmd FileType sh setlocal complete+=k~/shellcmds.txt dictionary=~/shellcmds.txt
    
        " completions for hyphenated commands
        autocmd FileType sh setlocal iskeyword+=-
    
        " generate the dictionary
        autocmd FileType sh call system("compgen -c > ~/shellcmds.txt")
    augroup END
    
  2. Open a shell script in a new Vim instance.

  3. Press <C-n> (keyword completion) or <C-x><C-k> (omni completion) in insert mode to perform completion.


If you want to keep your vimrc lean and clean, you can move the important bits of the snippet above in a proper ftplugin.

The file:

~/.vim/after/ftplugin/sh.vim

Its content:

setlocal complete+=k~/shellcmds.txt
setlocal dictionary=~/shellcmds.txt
setlocal iskeyword+=-
silent call system("compgen -c > ~/shellcmds.txt")

Dictionary completion is a cheap and easy way to get completion for unsupported languages and frameworks.

  • Could you modify your answer to run compgen when the .vimrc is read? – Nathaniel M. Beaver Sep 22 '15 at 19:20
  • Yeah, answer edited. – romainl Sep 22 '15 at 20:21
  • 1
    It works; the only thing I would add is set iskeyword+=- to complete hyphenated commands cleanly. – Nathaniel M. Beaver Sep 23 '15 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.