shellfish

FISH Shell - Cannot `cd -` when extending builtin cd


I have a custom cd function that looks like:

function cd -d "cd with auto conda activation"
    # set -gx OLDPWD (pwd) <-- uncommenting this does not resolve issue
    builtin cd $param $argv
    if test -f (pwd)/.condaconfig
        set -gx CONDACONFIGDIR (pwd)
        conda activate (cat .condaconfig)
    else if [ -n "$CONDACONFIGDIR" ]
        if [ -n (string match -q -- "*$CONDACONFIGDIR*" (pwd)) ]
            set -gx CONDACONFIGDIR ""
            conda deactivate
        end
    end
end

but with this active, I cannot use cd - to change to the previous directory. Have I implemented builtin wrong? I feel like I'm missing something here.

I have an equivalent custom function in bash which works fine and continues setting/using OLDPWD - fish seems to use something else to keep track of previous directory, but it's not an environment variable (ie. doesn't show up in the output of env)


Solution

  • That is a bit tricky. Took me a moment to spot the problem ... From cd --help:

    Fish also ships a wrapper function around the builtin cd that understands cd - as changing to the previous directory.

    In other words,the cd - functionality isn't handled by the cd builtin itself. If you type cd, you'll see the actual function that is getting called.

    So when you create a new function cd, you are overriding the Fish shell cd function, which is why you lose the ability to cd -.

    I'd recommend copying the Fish cd to a new function with:

    functions --copy cd cd_wrapper
    

    Then defining your cd which will call that function (rather than the builtin). Replace:

    builtin cd $param $argv
    

    With:

    cd_wrapper $argv
    

    I'm not sure where the $param is coming from in your original version above, so adjust as needed.


    Side-note: I would probably be trying to use an event-handler on this rather than overriding cd itself. E.g.:

    function conda_activate --on-variable PWD
    

    That will activate on every directory change, and you should be able to incorporate most of your existing function into that.