Search code examples
fish

autocomplete files on fish shell custom function


I'm migrating from ZSH to Fish, and the only thing I haven't been able to figure out yet is my c function:

functions/c:

#!/bin/sh
cd "$PROJECTS/$1"

functions/_c:

#compdef c
_files -W $PROJECTS -/

That works nicely on ZSH, I can type c <tab> and it completes as if I was doing cd $PROJECTS directly.

On fish, I created a c.fish like this:

function c
    cd $PROJECTS/$argv
end

complete --command c --no-files --arguments='(find $PROJECTS -mindepth 1 -maxdepth 2)'

But as you can imagine, it doesn't work as the ZSH version, as completions don't know about $argv, and won't complete past the first folder.

Is there a way to do the same thing in Fish?

I considered creating an abbr, but I really like the way I have it on ZSH today.


Solution

  • If c should act like cd with $PWD set to $PROJECTS, here's one approach:

    function c_complete
        # get the argument to 'c'
        set arg (commandline -ct)
    
        # save our PWD
        set saved_pwd $PWD
    
        # cd to $PROJECTS (and then back after)
        # while in $PROJECTS, complete as if we are 'cd'
        builtin cd $PROJECTS
        and complete -C"cd $arg"
        builtin cd $saved_pwd
    end
    
    complete --command c --arguments '(c_complete)'