2

I have a custom auto-completed command (call it commandA)

in commandB I want to steal the autocomplete options for the first argument to commandA

So, for example the options for argument1 for commandA are:

abcdef abcabc abc123

I would like something along the lines of compgen -? "commandA" or compgen -? "commandA abc" to generate the list above.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Chris
  • 377
  • 2
  • 11

1 Answers1

4

You can use complete -p commandA to find out which function would be invoked to do custom completion for that command. (You need to look for the argument to the -F option. If there are other options, it becomes more complicated.)

You would then need to set up the standard completion environment variables (whose names start COMP_) and call that function with appropiate arguments. It will fill in the COMPREPLY variable; if necessary, you could then add other possibilities. See the bash manual for details.

rici
  • 234,347
  • 28
  • 237
  • 341
  • Thanks for the reply. You got me thinking about calling the auto-complete function directly if it's trying to complete the first parameter, but this doesn't seem to work. What I want is to use the auto-complete for commandA to auto-complete commandB for the first parameter only. I could copy/paste the portion that does the first parameter, but that's not very DRY. (Extracting the block in a function is also difficult because I dont want to change the existing one.) – Chris Jun 01 '15 at 20:21
  • @chris: yeah, its hard to be DRY when you can't refactor. It's possible that commandB's completion function checks to see if it's really commandB; also make sure you pass through the command-line arguments (`"${@}"` is a good way to do that.) I can't think of any other obvious reasons why calling commandB's completion function wouldn't work, but for me it is pure speculation. Good luck. – rici Jun 01 '15 at 22:01
  • Got it working now. Since the auto-complete function (AFAIK) doesn't take parameters directly (uses COMP_WORD[]) I wasn't able to pass parameters. But it seems calling the function directly DOES work, I was just calling exit instead of return. – Chris Jun 02 '15 at 00:04
  • 1
    @chris: bash calls the completion function with three arguments. Many completiom functions don't use the arguments, preferring the environment variables, but they could use the arguments. You'd need to check the function to know for sure. But if you got it working, that's cool! (And functions should practically never do an exit since that exits the (sub)shell.) – rici Jun 02 '15 at 00:35
  • 1
    @Chris can you post your full solution? I would be curious to see. – Xu Wang Apr 13 '16 at 04:36