Writing your own autocompletion
When creating a command line tool for use by a small group it’s probably sufficient to print a helpful message when running with the
--help flag. But once you start thinking about redistributing your tool you’ll want to make adoption as easy as possible. An autocompletion script is a good step in that direction. If your tool has a reasonable number of well–named parameters, autocompletion acts as a quicker substitute for referring to a
man page or
--help, and even users completely unfamiliar with the tool can get a good idea of what it’s capable of and how easy it will be to use.
The simplest autocompletion is no autocompletion. As mentioned above, file path completion is the default, and that covers a number of simple commands. But all commands benefit from a
--help flag, and many commands can benefit from common flags such as
--quiet to show more or less output,
--color=[auto|always|never] to set whether the output should be colored, or
--config=FILE to point to a configuration file. Let’s try implementing completion for a fictional “do what I mean” command,
dwim. We start by setting up a completion for a
dwim command which only takes one argument, the static string
complete command specifies how arguments are to be autocompleted. Running the command above means that the command called
dwim will be autocompleted with the single argument (“word”;
--help unconditionally. To test it, simply run the above
complete command, type
dwim -- and press Tab: the command line will now read
dwim --help. It doesn’t matter that no
dwim command exists – the completion is completely independent of the command.
The completion does not include completion of the
dwimcommand itself – if you type
dwiand press Tab it will not complete to
dwim(unless, of course, you have installed a program called “dwim”). Completion of the first word is handled by a different mechanism.
Let’s make this more interesting by adding support for