Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my program utilize tab completion?

I've noticed that some programs (e.g. hg) allow the user to tab-complete specific parts of the command. For example, if, in an hg repository working directory, I type:

hg qpush --move b8<TAB>

It will try to complete the command with any mercurial patches in my patch queue that start with "b8".

What I'd like to do is imitate this behavior in my program. That is, I have a series of commands that depend on files within a certain directory, and I'd like to be able to provide tab completion in the shell. Is there an API for providing this on Ubuntu Linux (preferably using python, as that's what my script is written in)?

like image 277
jwir3 Avatar asked Feb 14 '13 15:02

jwir3


2 Answers

To do this, you need to write tab-completion modules for your shell. The default shell in most Linux distributions is bash, so you should write a completion script (typically a shell script). Once you've written your script, add it to /etc/bash_completion.d/. This should be distributed with your program (for Linux distributions, included in the package).

Debian Administration has a guide for writing your completion scripts. For using completion on a Mac, see https://trac.macports.org/wiki/howto/bash-completion.

For examples of completion files, take a look at the bash-completion project from Debian (also on Github). See also https://unix.stackexchange.com/questions/4738/an-easy-bash-completion-tutorial.

If you use zsh, hack.augusto linked to the documentation for writing completions.

like image 50
Mechanical snail Avatar answered Nov 15 '22 21:11

Mechanical snail


This is what the readline module is for.

Actually, readline is a common C library so it has bindings in many languages. And I can say, I've had tons of fun with it.

Enjoy B)

like image 35
jpic Avatar answered Nov 15 '22 19:11

jpic