0

I'm trying to write a shell function to rapidly cd into any directory in my home folder, using the fd and fzf programs.

This is what I have so far

function fdcd() {
  cd "$(fd --type d --ignore-file ~/.config/fd/ignore --hidden | fzf)"
}

which has two problems:

1) it only lists the directories contained in my current working directory, instead of every directory in my home folder;

2) idk if this is my shell's fault, but after I use this command my shell prompt doesn't immediately update to the new directory, instead I have to issue a command (even a blank one) first for it to update, which is annoying.

Any help is appreciated.

noibe
  • 387
  • 3
  • 15

1 Answers1

3
fdcd() {
  local dir
  dir=$(
    cd &&
      fd -0 --type d --ignore-file ~/.config/fd/ignore --hidden |
      fzf --read0
  ) && cd ~/$dir
}

As to why your prompt is not updated automatically, note that the prompt is only re-computed and re-drawn once you enter the line editor or when a zle widget explicitly asks for it to be redrawn (reset-prompt / clear-screen widgets) or returns after having invalidated the display (zle -I) or when the shell handles some asynchronous events.

So, if that fdcd functions is meant to be called as or as part of a custom zle widget, you'll need to ask the prompt to be recomputed if you want the change of directory to be reflected in the prompt:

fdcd() {
  local dir
  dir=$(
    cd &&
      fd ${NUMERIC:+-d$NUMERIC} -0 --type d \
        --ignore-file ~/.config/fd/ignore --hidden |
      fzf --read0
  ) && cd ~/$dir || return
  if zle; then
    # allow fdcd to run inside and outside zle
    zle reset-prompt
  fi
}
zle -N fdcd
bindkey '\es' fdcd

Here also making use of the $NUMERIC argument to limit the depth of the search, so you type Alt+2 Alt+S for instance to limit the search to depth 2.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • Thanks a lot. To make the prompt update automatically I needed the command `zle reset-prompt`. – noibe Feb 07 '20 at 11:33
  • @noibe, OK. I take it that `fdcd` is invoked as part of or as a zle widget? – Stéphane Chazelas Feb 07 '20 at 11:45
  • Yes, it is. I probably should have included that info. – noibe Feb 07 '20 at 12:28
  • @noibe, yes, it's the root of the issue here. See edit for some suggestion of improvement – Stéphane Chazelas Feb 07 '20 at 13:01
  • Sorry to bother you again, but I recently started using the `vcs_info` framework to display `git` related infos in the prompt, and if I use `fdcd` as a zle widget the prompt doesn't get updated even though I'm including a `zle reset-prompt`. [This](https://pastebin.com/RJXZpE6p) is my `vcs_info` setup. – noibe Mar 20 '20 at 16:17