Can bash completion be invoked programmatically?
Asked Answered
M

1

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.

Metagalaxy answered 15/7, 2011 at 21:34 Comment(5)
maybe you can hook into compgen somehow? e.g. compgen -c diff prints one completed command name per line for "diff"...Reputable
start with these links 1st 2ndCarpology
i don't think so. you can't do that without changing code in bash.Vaudeville
@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.Layamon
@Metagalaxy you can -- ive had to do this a few times.Inwards
I
14

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

Inwards answered 19/7, 2011 at 2:56 Comment(2)
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.Metagalaxy
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 nothingLance

© 2022 - 2024 — McMap. All rights reserved.