19

What I want is a function I can call from a program so it completes the way bash would given a commandline and a location where TAB was pressed.

. /etc/bash_completion
generate_completions "command arg1 arg2" 17

would return the same thing as

command arg1 arg2[TAB]

I haven't seen any way to do this.

tshepang
  • 12,111
  • 21
  • 91
  • 136
jpkotta
  • 9,237
  • 3
  • 29
  • 34
  • 1
    maybe you can hook into compgen somehow? e.g. compgen -c diff prints one completed command name per line for "diff"... – fearlesstost Jul 15 '11 at 21:51
  • 1
    start with these links [1st](http://tldp.org/LDP/abs/html/tabexpansion.html) [2nd](http://www.linuxquestions.org/questions/programming-9/bash-script-using-tab-complete-473112/) – Fredrik Pihl Jul 15 '11 at 21:53
  • 1
    i don't think so. you can't do that without changing code in bash. – ahmet alp balkan Jul 15 '11 at 21:53
  • 1
    @Fredrik: This does not really help here, if I understand the question right. We don't want to customize the completion, but we want to execute the completion without the user calling `tab`. – Paŭlo Ebermann Jul 15 '11 at 22:15
  • @jpkotta you can -- ive had to do this a few times. – Foo Bah Jul 19 '11 at 18:58

1 Answers1

13

I actually had to do this to figure out how apt-get autocomplete works on ubuntu (built my own pseudo-repository tool :)

This is a multistep process:

First, complete -p will give you a listing of all completions in the form of a set of commands you can run to replicate the configuration. For example, lets say you want to hunt down the autocomplete for apt-get. Then:

$ complete -p | grep apt-get
complete -F _apt_get apt-get

This tells you that the shell function _apt_get is called by the completion mechanism.

You need to recreate the special variables used by the function,, namely COMP_LINE (the full line), COMP_WORDS (bash array of all of the arguments -- basically split COMP_LINE), COMP_CWORD (index, should point to last value), COMP_POINT (where within the word you are doing the autocomplete), and COMP_TYPE (this is how you tell it that you want to complete as if you hit tab).

Note: read the manpage for more info -- this is how i figured it out in the first place. man bash

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
  • This shows how to handle the completions that call a function, but there are dozens of other possibilities (e.g. the -o and -A options to `complete`). This does take care of most cases other than filenames, which are easy enough. – jpkotta Jul 20 '11 at 21:11
  • As of November 2015, this doesn’t show completions that use `complete -F`. The definition for `xrdb`, for example looks like `complete -F _xrdb xrdb` , but `complete -p | grep xrdb` returns nothing – tijagi Nov 04 '15 at 07:53