Bash autocompletion for your own scripts

Sometimes nice features hide in plain sight – e.g. tabbing in vim – and you just do not come around to using them because you are just too happy with the tools you already have. This time I am talking about autocompletion for bash scripts – I always wondered how sometimes bash just miraculously knows which switches can be used for some command, but I was just happy when that happened and never thought about, how I could make it happen. Talk about complacency!

Well, it ain't that hard and is well documented. You have to write a function using some Bash internals and then register it with the complete command to the keyword after which you want autocompletion.

For example, I have the following small function in my .bashrc (actually in my .bash_common shared between desktop and laptop, which is sourced in .bashrc):

function math () {
        cd ${HOME}/uni/$1/
        atril $1.pdf 2>/dev/null &
        vim $1.tex

It does not do much but; it just fires up a PDF reader and opens the corresponding .tex file in vim. It saves me quite some keystrokes, in particular on the university's computer which is so agonizing slow that manually the whole procedure takes almost half a minute. Just another example where a small fix (here changing a bit in the computer setup) could improve the work flow for a lot of people. But management is usually concerned with looking good or being lazy instead of solving problems. Anyway, I digress.

So I want to be able to invoke this command for a few projects of mine and actually thought about duplicating this function as mathcv, mathmcf, mathpme and whatnot. But then I did the right thing and thought about researching a bit more and found out that bash autocompletion is actually quite easy.

So the following bit is added to my .bashrc:

function _mathautocompletion() {
        local cur
        COMPREPLY=( $(compgen -W "mcf pme krylovsafonov cv prep" -- ${cur}) )

  return 0

complete -o nospace -F _mathautocompletion math

The function _mathautocompletion is what tells the autocompletion how to autocomplete, e.g. I want to autocomplete the words mcf, pme, krylovsafonov, cv and prep. The complete command issues bash to use _mathautocompletion when I have typed math as a command. Note that there is nothing special with the name _mathautocompletion, although it might look like that. The underscore in front just makes sure that I do not accidentally autocomplete it when typing math and the rest of the name is just so I know exactly what it is for. The nospace options tells bash not to add a space in the end of the autocompletion. This is a bit redundant, but sometimes might be useful. Useful other options might be dirnames and filenames, which would tell bash to autocomplete with directory- or filenames in the case the function does not match anything.