Search code examples
fishtab-completion

fish shell completions keep-order


How do I use --keep-order ?

My function looks like this:

function filterfile -a file -a word
    grep -i $word $file
    grep -iv $word $file | sponge $file
end

and my completions look like this:

complete -k -c filterfile --require-parameter --no-files -a "(cat (commandline -opc)[2])"
complete -k -c filterfile --require-parameter

Following the documentation "Multiple complete calls with -k result in arguments of the later ones displayed first", but when I press tab for a file path nothing happens


Solution

  • If I understand correctly, you have a function filterfile which takes two arguments, a filename and a word to search for in the file. You would like the first argument to tab-complete as file names, and the second argument to tab-complete as words given in the file from the first argument.

    You can do this by using the --condition option (short -n) to complete, documented here. Here we use the helper function __fish_is_first_arg to control when our completions run:

    # Complete first argument as files.
    complete -c filterfile --condition __fish_is_first_arg --force-files
    
    # Complete remaining arguments as words in the file from the first argument.
    complete --keep-order -c filterfile --condition 'not __fish_is_first_arg' --no-files -a '(cat (__fish_first_token))'
    

    Now the first argument should tab-complete as files, and the second+ arguments should tab-complete as words found in the file named by the first argument.

    (Note that __fish_is_first_arg is an ordinary fish function that ships with fish.)

    To answer your original question, the --keep-order option offers completions in the order they are printed, instead of sorting. With --keep-order:

    > cat words.txt
    sweater
    handy
    scarecrow
    card
    geese
    
    > filterfile words.txt <tab>
    sweater  handy  scarecrow  card  geese
    

    The completions appear in their original order. Without:

    > filterfile words.txt <tab>
    card  geese  handy  scarecrow  sweater
    

    the completions are sorted alphabetically.