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?

1 Answer 1

5

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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