Extending Bash Auto-Completion

One of the ways of making command line more usable is by providing auto-completion. It is a non-intrusive way of freeing the user from the burden of remembering options. Bash provides something called programmable completion which can be extended for your own applications.

An example using vim

Bash provides you a way of specifying your keywords, and using them to auto complete command line arguments for your application. I use vim as a wiki, task managemer and contacts. The vim helptags system lets me index the content instead of searching through it, and the speed shows it. One feature I wanted to add to this was to access these tags from outside vim.

This can be done in a straight forward way:

$ vim -t tagname

This takes me directly to specific content marked using this tag. However, this will be more productive if I can provide auto-completion for the tags.

I first defined a Bash function for the vim commandline. I added the following code to my .bashrc file:

function get {
    vim -t $1

Now I can use get tagname command to get to the content.

Bash programmable completion is done by sourcing the /etc/bash-completion script. The script lets us add our auto-completion script /etc/bash-completion.d/ directory and executes it whenever it is called. So I added a script file called get with the following code in that directory.

    local cur
    #Variable to hold the current word

    #Build a list of our keywords for auto-completion using 
    #the tags file
    local tags=$(for t in `cat /home/anadgouda/wiki/tags | \
                      awk '{print $1}'`; do echo ${t}; done)

    #Generate possible matches and store them in the 
    #array variable COMPREPLY
    COMPREPLY=($(compgen -W "${tags}" $cur))

#Assign the auto-completion function _get for our command get.
complete -F _get get

Once the /etc/bash-completion is sourced, you will get auto-completion for the tags when you use the get command.

Along with my wiki I use it for all the documentation work and at times the code too. I also use the tags file created from my code. The indexing system lets me remember the context instead of the filenames and directories.

You can tweak this system for any of the tools you use. All you need to do is get a list of the keywords for your command and give it to the Bash programmable completion system.

Say your thought!

If you want to use HTML you can use these tags: <a>, <em>, <strong>, <abbr>, <code>, <blockquote>. Closing the tags will be appreciated as this site uses valid XHTML.



Abhijit Nadgouda
iface Consulting
+91 9819820312
My bookmarks


This is the weblog of Abhijit Nadgouda where he writes down his thoughts on software development and related topics. You are invited to subscribe to the feed to stay updated or check out more subscription options. Or you can choose to browse by one of the topics.