Search code examples
fish

How to port `ranger-cd` function to fish shell


I have been trying to port the ranger-cd function for the ranger file manager to the fish shell. As of 2013, ranger’s ranger-cd function looks like this:

function ranger-cd {
    tempfile='/tmp/chosendir'
    /usr/bin/ranger --choosedir="$tempfile" "${@:-$(pwd)}"
    test -f "$tempfile" &&
    if [ "$(cat -- "$tempfile")" != "$(echo -n `pwd`)" ]; then
        cd -- "$(cat "$tempfile")"
    fi
    rm -f -- "$tempfile"
}

# This binds Ctrl-O to ranger-cd:
bind '"\C-o":"ranger-cd\C-m"'

(This function gives a temporary file to ranger file manager to store the last accessed directory so that we can change to that directory after ranger quits.)

Here’s what I have done so far to port the function to fish:

function ranger-cd
    set tempfile '/tmp/chosendir'
    /usr/bin/ranger --choosedir=$tempfile (pwd)
    test -f $tempfile and
    if cat $tempfile != echo -n (pwd)
        cd (cat $tempfile)
    end
    rm -f $tempfile
end

function fish_user_key_bindings
        bind \co ranger-cd
end

When I use this function I get:

test: unexpected argument at index 2: 'and'
     1  /home/gokcecat: !=: No such file or directory
cat: echo: No such file or directory
cat: /home/gokce: Is a directory

I’m guessing there are still multiple errors in the above code. Does anyone have a working solution for this?


Solution

  • My answer is based off of gzfrancisco's. However, I fix the "'-a' at index 2" issue, and I also ensure that a new prompt is printed after exiting ranger.

    I put the following in ~/.config/fish/config.fish:

    function ranger-cd                                                               
    
      set tempfile '/tmp/chosendir'                                                  
      ranger --choosedir=$tempfile (pwd)                                    
    
      if test -f $tempfile                                                           
          if [ (cat $tempfile) != (pwd) ]                                            
            cd (cat $tempfile)                                                       
          end                                                                        
      end                                                                            
    
      rm -f $tempfile                                                                
    
    end                                                                              
    
    function fish_user_key_bindings                                                  
        bind \co 'ranger-cd ; commandline -f repaint'                                           
    end