简体   繁体   中英

Can bash completion be invoked programmatically?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM