Search code examples
fish

How to implement dynamic tab completion of options in Fish shell?


I want to implement dynamic tab completion of options to a Fish command. This is easy for the -a switch, but I can't figure out how to do it for the -l switch.

Consider the following lines:

$ complete -c foo -a '(echo bar\nbaz\nbiz)' -f
$ complete -c foo -l '(echo bar\nbaz\nbiz)' -f

The behavior of my shell is then as follows:

$ foo b<tab>
  bar  baz  biz

$ foo --<tab>
  foo --\(echo\ bar\\nbaz\\nbiz\) 

Instead I'd like it to suggest three options --bar, --baz and --biz. Is this possible?


Solution

  • edit: Now I understand better. You can do this by just making your "arguments" start with dashes. Here's an example that uses a function for clarity:

    function get_foo_completions
      echo --bar
      echo --baz
      echo --biz
    
      set prev_arg (commandline -pco)[-1]
      test "$prev_arg" = print
      and echo --conditional
    end
    
    complete -c foo -a '(get_foo_completions)' -f
    

    The --conditional argument will only be printed if the previous argument is print which illustrates that these can be dynamic.

    To my knowledge this isn't yet possible. Options are declarative, and only arguments to those options may be dynamic.

    If you give more details about your use case I might be able to suggest other approaches.